Simplesitemap.php 18.5 KB
Newer Older
1 2
<?php

gbyte.co's avatar
gbyte.co committed
3
namespace Drupal\simple_sitemap;
4

5
use Drupal\simple_sitemap\Form\FormHelper;
gbyte.co's avatar
gbyte.co committed
6 7 8
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\PathValidator;
gbyte.co's avatar
gbyte.co committed
9 10
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Datetime\DateFormatter;
11

12
/**
gbyte.co's avatar
gbyte.co committed
13
 * Class Simplesitemap
gbyte.co's avatar
gbyte.co committed
14
 * @package Drupal\simple_sitemap
15 16 17
 */
class Simplesitemap {

gbyte.co's avatar
gbyte.co committed
18 19 20
  /**
   * @var \Drupal\simple_sitemap\SitemapGenerator
   */
21
  protected $sitemapGenerator;
gbyte.co's avatar
gbyte.co committed
22 23 24 25

  /**
   * @var \Drupal\simple_sitemap\EntityHelper
   */
26
  protected $entityHelper;
gbyte.co's avatar
gbyte.co committed
27 28 29 30

  /**
   * @var \Drupal\Core\Config\ConfigFactory
   */
31
  protected $configFactory;
gbyte.co's avatar
gbyte.co committed
32 33 34 35

  /**
   * @var \Drupal\Core\Database\Connection
   */
36
  protected $db;
gbyte.co's avatar
gbyte.co committed
37 38 39 40

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
41
  protected $entityTypeManager;
gbyte.co's avatar
gbyte.co committed
42 43 44 45

  /**
   * @var \Drupal\Core\Path\PathValidator
   */
46
  protected $pathValidator;
gbyte.co's avatar
gbyte.co committed
47 48 49 50

  /**
   * @var array
   */
51
  protected static $allowed_link_settings = [
52 53 54 55 56 57 58
    'entity' => ['index', 'priority', 'changefreq'],
    'custom' => ['priority', 'changefreq'],
  ];

  protected static $link_setting_defaults = [
    'index' => 0,
    'priority' => 0.5,
59
  ];
60

61 62
  /**
   * Simplesitemap constructor.
63
   * @param \Drupal\simple_sitemap\SitemapGenerator $sitemapGenerator
64
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
65 66 67 68 69
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   * @param \Drupal\Core\Database\Connection $database
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   * @param \Drupal\Core\Path\PathValidator $pathValidator
   * @param \Drupal\Core\Datetime\DateFormatter $dateFormatter
70
   */
71
  public function __construct(
gbyte.co's avatar
gbyte.co committed
72
    SitemapGenerator $sitemapGenerator,
73
    EntityHelper $entityHelper,
gbyte.co's avatar
gbyte.co committed
74
    ConfigFactory $configFactory,
gbyte.co's avatar
gbyte.co committed
75 76 77
    Connection $database,
    EntityTypeManagerInterface $entityTypeManager,
    PathValidator $pathValidator,
78
    DateFormatter $dateFormatter
79 80
  ) {
    $this->sitemapGenerator = $sitemapGenerator;
81
    $this->entityHelper = $entityHelper;
gbyte.co's avatar
gbyte.co committed
82
    $this->configFactory = $configFactory;
83 84
    $this->db = $database;
    $this->entityTypeManager = $entityTypeManager;
85
    $this->pathValidator = $pathValidator;
86
    $this->dateFormatter = $dateFormatter;
87 88
  }

89
  /**
90 91
   * Returns a specific sitemap setting or a default value if setting does not
   * exist.
gbyte.co's avatar
gbyte.co committed
92
   *
93 94 95 96 97 98 99 100
   * @param string $name
   *   Name of the setting, like 'max_links'.
   *
   * @param mixed $default
   *   Value to be returned if the setting does not exist in the configuration.
   *
   * @return mixed
   *   The current setting from configuration or a default value.
gbyte.co's avatar
gbyte.co committed
101
   */
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  public function getSetting($name, $default = FALSE) {
    $setting = $this->configFactory
      ->get('simple_sitemap.settings')
      ->get($name);
    return NULL !== $setting ? $setting : $default;
  }

  /**
   * Stores a specific sitemap setting in configuration.
   *
   * @param string $name
   *   Setting name, like 'max_links'.
   * @param mixed $setting
   *   The setting to be saved.
   *
   * @return $this
   */
  public function saveSetting($name, $setting) {
    $this->configFactory->getEditable("simple_sitemap.settings")
      ->set($name, $setting)->save();
    return $this;
  }

  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
   * @param int $chunk_id
   *
   * @return string|false
   *   If no sitemap id provided, either a sitemap index is returned, or the
   *   whole sitemap, if the amount of links does not exceed the max links
   *   setting. If a sitemap id is provided, a sitemap chunk is returned. False
   *   if sitemap is not retrievable from the database.
   */
  public function getSitemap($chunk_id = NULL) {
    $chunk_info = $this->fetchSitemapChunkInfo();

    if (NULL === $chunk_id || !isset($chunk_info[$chunk_id])) {

      if (count($chunk_info) > 1) {
        // Return sitemap index, if there are multiple sitemap chunks.
        return $this->getSitemapIndex($chunk_info);
      }
      else {
        // Return sitemap if there is only one chunk.
        return count($chunk_info) === 1
        && isset($chunk_info[SitemapGenerator::FIRST_CHUNK_INDEX])
          ? $this->fetchSitemapChunk(SitemapGenerator::FIRST_CHUNK_INDEX)
            ->sitemap_string
          : FALSE;
      }
    }
    else {
      // Return specific sitemap chunk.
      return $this->fetchSitemapChunk($chunk_id)->sitemap_string;
    }
  }

  /**
   * Fetches all sitemap chunk timestamps keyed by chunk ID.
   *
   * @return array
   *   An array containing chunk creation timestamps keyed by chunk ID.
   */
  protected function fetchSitemapChunkInfo() {
168
    return $this->db
169
      ->query("SELECT id, sitemap_created FROM {simple_sitemap}")
170 171 172
      ->fetchAllAssoc('id');
  }

173 174 175 176 177 178 179 180 181
  /**
   * Fetches a single sitemap chunk by ID.
   *
   * @param int $id
   *   The chunk ID.
   *
   * @return object
   *   A sitemap chunk object.
   */
182
  protected function fetchSitemapChunk($id) {
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
    return $this->db->query('SELECT * FROM {simple_sitemap} WHERE id = :id',
      [':id' => $id])->fetchObject();
  }

  /**
   * Generates the sitemap for all languages and saves it to the db.
   *
   * @param string $from
   *   Can be 'form', 'cron', 'drush' or 'nobatch'.
   *   This decides how the batch process is to be run.
   */
  public function generateSitemap($from = 'form') {
    $this->sitemapGenerator
      ->setGenerator($this)
      ->setGenerateFrom($from)
      ->startGeneration();
  }

  /**
   * Generates and returns the sitemap index as string.
   *
gbyte.co's avatar
gbyte.co committed
204 205
   * @param array $chunk_info
   *   Array containing chunk creation timestamps keyed by chunk ID.
206 207 208 209
   *
   * @return string
   *   The sitemap index.
   */
gbyte.co's avatar
gbyte.co committed
210
  protected function getSitemapIndex($chunk_info) {
211 212
    return $this->sitemapGenerator
      ->setGenerator($this)
gbyte.co's avatar
gbyte.co committed
213
      ->generateSitemapIndex($chunk_info);
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  }

  /**
   * Returns a 'time ago' string of last timestamp generation.
   *
   * @return string|false
   *   Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
  public function getGeneratedAgo() {
    $chunks = $this->fetchSitemapChunkInfo();
    if (isset($chunks[SitemapGenerator::FIRST_CHUNK_INDEX]->sitemap_created)) {
      return $this->dateFormatter
        ->formatInterval(REQUEST_TIME - $chunks[SitemapGenerator::FIRST_CHUNK_INDEX]
            ->sitemap_created);
    }
    return FALSE;
  }

232 233
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
234 235
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
236 237 238
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
gbyte.co's avatar
gbyte.co committed
239
   *   Entity type id like 'node'.
240
   *
gbyte.co's avatar
gbyte.co committed
241
   * @return $this
242 243
   */
  public function enableEntityType($entity_type_id) {
244 245 246 247
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
    if (!in_array($entity_type_id, $enabled_entity_types)) {
      $enabled_entity_types[] = $entity_type_id;
      $this->saveSetting('enabled_entity_types', $enabled_entity_types);
248
    }
gbyte.co's avatar
gbyte.co committed
249
    return $this;
250 251 252 253 254 255 256 257
  }

  /**
   * Disables sitemap support for an entity type. Disabling support for an
   * entity type deletes its sitemap settings permanently and removes sitemap
   * settings from entity forms.
   *
   * @param string $entity_type_id
258
   *  Entity type id like 'node'.
259
   *
gbyte.co's avatar
gbyte.co committed
260
   * @return $this
261 262
   */
  public function disableEntityType($entity_type_id) {
263 264 265

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
266
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
267
      unset ($enabled_entity_types[$key]);
268
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
269 270 271
    }

    // Deleting inclusion settings.
272
    $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$entity_type_id.");
273 274
    foreach($config_names as $config_name) {
      $this->configFactory->getEditable($config_name)->delete();
275
    }
276 277 278

    // Deleting entity overrides.
    $this->removeEntityInstanceSettings($entity_type_id);
gbyte.co's avatar
gbyte.co committed
279
    return $this;
280 281 282
  }

  /**
283
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
284 285 286
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
gbyte.co's avatar
gbyte.co committed
287
   *   Entity type id like 'node' the bundle belongs to.
288
   * @param string $bundle_name
gbyte.co's avatar
gbyte.co committed
289
   *   Name of the bundle. NULL if entity type has no bundles.
290
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
291
   *   An array of sitemap settings for this bundle/entity type.
292
   *   Example: ['index' => TRUE, 'priority' => 0.5, 'changefreq' => 'never'].
gbyte.co's avatar
gbyte.co committed
293 294
   *
   * @return $this
295 296
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
297

298
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
299

300 301 302 303 304 305 306 307 308 309
    foreach($settings as $setting_key => $setting) {
      if ($setting_key == 'index') {
        $setting = intval($setting);
      }
      $this->configFactory
        ->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->set($setting_key, $setting)
        ->save();
    }
    //todo: Use addLinkSettings()?
310 311

    // Delete entity overrides which are identical to new bundle setting.
gbyte.co's avatar
gbyte.co committed
312
    $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
313 314 315
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $entity_type = $sitemap_entity_types[$entity_type_id];
      $keys = $entity_type->getKeys();
316 317

      // Menu fix.
318 319
      $keys['bundle'] = $entity_type_id == 'menu_link_content' ? 'menu_name' : $keys['bundle'];

320
      $query = $this->entityTypeManager->getStorage($entity_type_id)->getQuery();
321
      if (!$this->entityHelper->entityTypeIsAtomic($entity_type_id)) {
322
        $query->condition($keys['bundle'], $bundle_name);
323
      }
324 325 326 327 328 329 330 331 332 333 334 335
      $entity_ids = $query->execute();

      $bundle_settings = $this->configFactory
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name");

      $query = $this->db->select('simple_sitemap_entity_overrides', 'o')
        ->fields('o', ['id', 'inclusion_settings'])
        ->condition('o.entity_type', $entity_type_id);
      if (!empty($entity_ids)) {
        $query->condition('o.entity_id', $entity_ids, 'IN');
      }

336
      foreach($query->execute()->fetchAll() as $result) {
337 338 339 340 341 342 343 344 345 346 347 348 349
        $delete = TRUE;
        $instance_settings = unserialize($result->inclusion_settings);
        foreach ($instance_settings as $setting_key => $instance_setting) {
          if ($instance_setting != $bundle_settings->get($setting_key)) {
            $delete = FALSE;
            break;
          }
        }
        if ($delete) {
          $this->db->delete('simple_sitemap_entity_overrides')
            ->condition('id', $result->id)
            ->execute();
        }
350 351
      }
    }
352 353 354
    else {
      //todo: log error
    }
gbyte.co's avatar
gbyte.co committed
355
    return $this;
356 357
  }

358
  /**
359 360
   * Gets sitemap settings for an entity bundle, a non-bundle entity type or for
   * all entity types and their bundles.
361
   *
362 363 364
   * @param string|null $entity_type_id
   *  If set to null, sitemap settings for all entity types and their bundles
   *  are fetched.
365 366 367
   * @param string|null $bundle_name
   *
   * @return array|false
gbyte.co's avatar
gbyte.co committed
368 369
   *  Array of sitemap settings for an entity bundle, a non-bundle entity type
   *  or for all entity types and their bundles.
370
   *  False if entity type does not exist.
371
   */
372
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
373
    if (NULL !== $entity_type_id) {
374
      $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
375
      $bundle_settings = $this->configFactory
376 377
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->get();
378 379 380
      return !empty($bundle_settings)
        ? $this->supplementDefaultSettings('entity', $bundle_settings)
        : FALSE;
381
    }
382
    else {
383
      $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.");
384
      $all_settings = [];
385 386
      foreach($config_names as $config_name) {
        $config_name_parts = explode('.', $config_name);
387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
        $all_settings[$config_name_parts[2]][$config_name_parts[3]] = $this->supplementDefaultSettings(
          'entity',
          $this->configFactory->get($config_name)->get()
        );
      }
      return $all_settings;
    }
  }

  /**
   * @param string $type
   * @param array $settings
   * @return array
   */
  protected function supplementDefaultSettings($type, $settings) {
    foreach(self::$allowed_link_settings[$type] as $allowed_link_setting) {
      if (!isset($settings[$allowed_link_setting])
        && isset($link_setting_defaults[$allowed_link_setting])) {
        $settings[$allowed_link_setting] = self::$link_setting_defaults[$allowed_link_setting];
406 407
      }
    }
408
    return $settings;
409 410
  }

411 412 413
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
gbyte.co's avatar
gbyte.co committed
414 415 416
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
417
   *
418 419
   * @return $this
   */
420
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
421

422
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
423
    $bundle_name = $this->entityHelper->getEntityInstanceBundleName($entity);
424 425 426 427 428
    $bundle_settings = $this->configFactory
      ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
      ->get();

    if (!empty($bundle_settings)) {
429 430 431 432

      // Check if overrides are different from bundle setting before saving.
      $override = FALSE;
      foreach ($settings as $key => $setting) {
433
        if ($setting != $bundle_settings[$key]) {
434 435 436 437
          $override = TRUE;
          break;
        }
      }
gbyte.co's avatar
gbyte.co committed
438 439
      // Save overrides for this entity if something is different.
      if ($override) {
440 441 442 443 444 445 446 447 448 449
        $this->db->merge('simple_sitemap_entity_overrides')
          ->key([
            'entity_type' => $entity_type_id,
            'entity_id' => $id])
          ->fields([
            'entity_type' => $entity_type_id,
            'entity_id' => $id,
            'inclusion_settings' => serialize($settings),
          ])
          ->execute();
450
      }
gbyte.co's avatar
gbyte.co committed
451 452
      // Else unset override.
      else {
453
        $this->removeEntityInstanceSettings($entity_type_id, $id);
454
      }
455 456 457
    }
    else {
      //todo: log error
458
    }
gbyte.co's avatar
gbyte.co committed
459
    return $this;
460 461
  }

462
  /**
463
   * Gets sitemap settings for an entity instance which overrides the sitemap
464
   * settings of its bundle, or bundle settings, if they are not overridden.
465
   *
gbyte.co's avatar
gbyte.co committed
466
   * @param string $entity_type_id
467
   * @param int $id
gbyte.co's avatar
gbyte.co committed
468
   *
469
   * @return array|false
470
   */
471 472 473 474 475 476 477 478 479
  public function getEntityInstanceSettings($entity_type_id, $id) {
    $results = $this->db->select('simple_sitemap_entity_overrides', 'o')
      ->fields('o', ['inclusion_settings'])
      ->condition('o.entity_type', $entity_type_id)
      ->condition('o.entity_id', $id)
      ->execute()
      ->fetchField();

    if (!empty($results)) {
480
      return $this->supplementDefaultSettings('entity', unserialize($results));
481 482
    }
    else {
483 484 485 486 487 488
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
489 490 491
    }
  }

492 493 494 495 496 497 498 499 500 501 502 503
  /**
   * Removes sitemap settings for an entity that overrides the sitemap settings
   * of its bundle.
   *
   * @param string $entity_type_id
   * @param string|null $entity_ids
   *
   * @return $this
   */
  public function removeEntityInstanceSettings($entity_type_id, $entity_ids = NULL) {
    $query = $this->db->delete('simple_sitemap_entity_overrides')
      ->condition('entity_type', $entity_type_id);
504
    if (NULL !== $entity_ids) {
505 506 507 508 509 510 511
      $entity_ids = !is_array($entity_ids) ? [$entity_ids] : $entity_ids;
      $query->condition('entity_id', $entity_ids, 'IN');
    }
    $query->execute();
    return $this;
  }

512 513 514 515
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
516 517
   * @param string $entity_type_id
   * @param string|null $bundle_name
gbyte.co's avatar
gbyte.co committed
518
   *
519 520
   * @return bool
   */
521
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
522 523 524 525
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

526 527 528
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
529
   * @param string $entity_type_id
gbyte.co's avatar
gbyte.co committed
530
   *
531 532
   * @return bool
   */
533
  public function entityTypeIsEnabled($entity_type_id) {
534
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
535 536
  }

537
  /**
538
   * Stores a custom path along with its sitemap settings to configuration.
539
   *
gbyte.co's avatar
gbyte.co committed
540 541
   * @param string $path
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
542
   *
gbyte.co's avatar
gbyte.co committed
543
   * @return $this
544 545
   *
   * @todo Validate $settings and throw exceptions
546
   */
547
  public function addCustomLink($path, $settings) {
gbyte.co's avatar
gbyte.co committed
548 549 550 551 552 553 554 555
    if (!$this->pathValidator->isValid($path)) {
      // todo: log error.
      return $this;
    }
    if ($path[0] != '/') {
      // todo: log error.
      return $this;
    }
gbyte.co's avatar
gbyte.co committed
556

557
    $custom_links = $this->getCustomLinks();
gbyte.co's avatar
gbyte.co committed
558
    foreach ($custom_links as $key => $link) {
559 560 561 562 563 564
      if ($link['path'] == $path) {
        $link_key = $key;
        break;
      }
    }
    $link_key = isset($link_key) ? $link_key : count($custom_links);
565
    $custom_links[$link_key] = ['path' => $path] + $settings;
566
    $this->configFactory->getEditable("simple_sitemap.custom")
567
      ->set('links', $custom_links)->save();
gbyte.co's avatar
gbyte.co committed
568
    return $this;
569 570
  }

571 572 573 574 575 576 577 578
  /**
   * Returns an array of custom paths and their sitemap settings.
   *
   * @return array
   */
  public function getCustomLinks() {
    $custom_links = $this->configFactory
      ->get('simple_sitemap.custom')
579
      ->get('links');
580
    return $custom_links !== NULL ? $custom_links : [];
581 582
  }

583 584 585
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
gbyte.co's avatar
gbyte.co committed
586
   * @param string $path
gbyte.co's avatar
gbyte.co committed
587
   *
gbyte.co's avatar
gbyte.co committed
588
   * @return array|false
589
   */
590
  public function getCustomLink($path) {
591
    foreach ($this->getCustomLinks() as $key => $link) {
592 593
      if ($link['path'] === $path) {
        return $this->supplementDefaultSettings('custom', $link);
594 595 596 597 598
      }
    }
    return FALSE;
  }

599 600 601
  /**
   * Removes a custom path from the sitemap settings.
   *
gbyte.co's avatar
gbyte.co committed
602
   * @param string $path
gbyte.co's avatar
gbyte.co committed
603
   *
604 605
   * @return $this
   */
606
  public function removeCustomLink($path) {
607
    $custom_links = $this->getCustomLinks();
gbyte.co's avatar
gbyte.co committed
608
    foreach ($custom_links as $key => $link) {
609
      if ($link['path'] === $path) {
610 611
        unset($custom_links[$key]);
        $custom_links = array_values($custom_links);
612
        $this->configFactory->getEditable("simple_sitemap.custom")
613
          ->set('links', $custom_links)->save();
614
        break;
615 616
      }
    }
gbyte.co's avatar
gbyte.co committed
617
    return $this;
618 619
  }

620 621
  /**
   * Removes all custom paths from the sitemap settings.
gbyte.co's avatar
gbyte.co committed
622 623
   *
   * @return $this
624
   */
625
  public function removeCustomLinks() {
626
    $this->configFactory->getEditable("simple_sitemap.custom")
627
      ->set('links', [])->save();
gbyte.co's avatar
gbyte.co committed
628
    return $this;
629
  }
630
}