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

Pawel G's avatar
Pawel G committed
3
namespace Drupal\simple_sitemap;
4

Pawel G's avatar
Pawel G committed
5 6 7
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\PathValidator;
Pawel G's avatar
Pawel G committed
8 9
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Datetime\DateFormatter;
10
use Drupal\Component\Datetime\Time;
11

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

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

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

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

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

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

  /**
   * @var \Drupal\Core\Path\PathValidator
   */
46
  protected $pathValidator;
Pawel G's avatar
Pawel G committed
47

48 49 50 51 52
  /**
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

53 54 55 56 57
  /**
   * @var \Drupal\Component\Datetime\Time
   */
  protected $time;

Pawel G's avatar
Pawel G committed
58 59 60
  /**
   * @var array
   */
Pawel G's avatar
Pawel G committed
61
  protected static $allowedLinkSettings = [
62
    'entity' => ['index', 'priority', 'changefreq', 'include_images'],
63 64 65
    'custom' => ['priority', 'changefreq'],
  ];

Pawel G's avatar
Pawel G committed
66 67 68 69
  /**
   * @var array
   */
  protected static $linkSettingDefaults = [
70
    'index' => 1,
71
    'priority' => 0.5,
72
    'changefreq' => '',
73
    'include_images' => 0,
74
  ];
75

76 77
  /**
   * Simplesitemap constructor.
Pawel G's avatar
Pawel G committed
78
   * @param \Drupal\simple_sitemap\SitemapGenerator $sitemapGenerator
79
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
Pawel G's avatar
Pawel G committed
80 81 82 83 84
   * @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
85
   * @param \Drupal\Component\Datetime\Time $time
86
   */
87
  public function __construct(
Pawel G's avatar
Pawel G committed
88
    SitemapGenerator $sitemapGenerator,
89
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
90
    ConfigFactory $configFactory,
Pawel G's avatar
Pawel G committed
91 92 93
    Connection $database,
    EntityTypeManagerInterface $entityTypeManager,
    PathValidator $pathValidator,
94 95
    DateFormatter $dateFormatter,
    Time $time
96 97
  ) {
    $this->sitemapGenerator = $sitemapGenerator;
98
    $this->entityHelper = $entityHelper;
Pawel G's avatar
Pawel G committed
99
    $this->configFactory = $configFactory;
100 101
    $this->db = $database;
    $this->entityTypeManager = $entityTypeManager;
102
    $this->pathValidator = $pathValidator;
103
    $this->dateFormatter = $dateFormatter;
104
    $this->time = $time;
105 106
  }

107
  /**
108 109
   * Returns a specific sitemap setting or a default value if setting does not
   * exist.
Pawel G's avatar
Pawel G committed
110
   *
111 112 113 114 115 116 117 118
   * @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.
Pawel G's avatar
Pawel G committed
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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  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() {
186
    return $this->db
187
      ->query("SELECT id, sitemap_created FROM {simple_sitemap}")
188 189 190
      ->fetchAllAssoc('id');
  }

191 192 193 194 195 196 197 198 199
  /**
   * Fetches a single sitemap chunk by ID.
   *
   * @param int $id
   *   The chunk ID.
   *
   * @return object
   *   A sitemap chunk object.
   */
200
  protected function fetchSitemapChunk($id) {
201 202 203 204 205
    return $this->db->query('SELECT * FROM {simple_sitemap} WHERE id = :id',
      [':id' => $id])->fetchObject();
  }

  /**
Pawel G's avatar
Pawel G committed
206
   * Generates the XML sitemap and saves it to the db.
207 208 209 210 211 212 213
   *
   * @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
Pawel G's avatar
Pawel G committed
214 215 216 217 218 219 220 221 222 223 224
      ->setBundleSettings($this->getBundleSettings())
      ->setCustomLinks($this->getCustomLinks())
      ->setSettings([
        'base_url' => $this->getSetting('base_url', ''),
        'batch_process_limit' => $this->getSetting('batch_process_limit', NULL),
        'max_links' => $this->getSetting('max_links', 2000),
        'skip_untranslated' => $this->getSetting('skip_untranslated', FALSE),
        'remove_duplicates' => $this->getSetting('remove_duplicates', TRUE),
        'excluded_languages' => $this->getSetting('excluded_languages', []),
        'from' => $from,
      ])
225 226 227 228 229 230
      ->startGeneration();
  }

  /**
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
231 232
   * @param array $chunk_info
   *   Array containing chunk creation timestamps keyed by chunk ID.
233 234 235 236
   *
   * @return string
   *   The sitemap index.
   */
Pawel G's avatar
Pawel G committed
237
  protected function getSitemapIndex($chunk_info) {
238
    return $this->sitemapGenerator
Pawel G's avatar
Pawel G committed
239
      ->setSettings(['base_url' => $this->getSetting('base_url', '')])
Pawel G's avatar
Pawel G committed
240
      ->generateSitemapIndex($chunk_info);
241 242 243 244 245 246 247 248 249 250 251 252
  }

  /**
   * 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
253
        ->formatInterval($this->time->getRequestTime() - $chunks[SitemapGenerator::FIRST_CHUNK_INDEX]
254 255 256 257 258
            ->sitemap_created);
    }
    return FALSE;
  }

259 260
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
261 262
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
263 264 265
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
266
   *   Entity type id like 'node'.
267
   *
Pawel G's avatar
Pawel G committed
268
   * @return $this
269 270
   */
  public function enableEntityType($entity_type_id) {
271 272 273 274
    $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);
275
    }
Pawel G's avatar
Pawel G committed
276
    return $this;
277 278 279 280 281 282 283 284
  }

  /**
   * 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
285
   *  Entity type id like 'node'.
286
   *
Pawel G's avatar
Pawel G committed
287
   * @return $this
288 289
   */
  public function disableEntityType($entity_type_id) {
290 291 292

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
293
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
294
      unset ($enabled_entity_types[$key]);
295
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
296 297 298
    }

    // Deleting inclusion settings.
299
    $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$entity_type_id.");
300 301
    foreach($config_names as $config_name) {
      $this->configFactory->getEditable($config_name)->delete();
302
    }
303 304 305

    // Deleting entity overrides.
    $this->removeEntityInstanceSettings($entity_type_id);
Pawel G's avatar
Pawel G committed
306
    return $this;
307 308 309
  }

  /**
Pawel G's avatar
Pawel G committed
310
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
311 312 313
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
314
   *   Entity type id like 'node' the bundle belongs to.
315
   * @param string $bundle_name
Pawel G's avatar
Pawel G committed
316
   *   Name of the bundle. NULL if entity type has no bundles.
317
   * @param array $settings
Pawel G's avatar
Pawel G committed
318
   *   An array of sitemap settings for this bundle/entity type.
319
   *   Example: ['index' => TRUE, 'priority' => 0.5, 'changefreq' => 'never', 'include_images' => FALSE].
Pawel G's avatar
Pawel G committed
320 321
   *
   * @return $this
322 323
   *
   * @todo: enableEntityType automatically
324
   */
325
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings = []) {
326
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
327

328 329 330 331 332
    $old_settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    $settings = !empty($old_settings) ? array_merge($old_settings, $settings) : $this->supplementDefaultSettings('entity', $settings);

    $bundle_settings = $this->configFactory
      ->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name");
333
    foreach($settings as $setting_key => $setting) {
334
      if ($setting_key === 'index') {
335 336
        $setting = intval($setting);
      }
337
      $bundle_settings->set($setting_key, $setting);
338
    }
339
    $bundle_settings->save();
340 341

    // Delete entity overrides which are identical to new bundle setting.
Pawel G's avatar
Pawel G committed
342
    $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
343 344 345
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $entity_type = $sitemap_entity_types[$entity_type_id];
      $keys = $entity_type->getKeys();
346 347

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

350
      $query = $this->entityTypeManager->getStorage($entity_type_id)->getQuery();
351
      if (!$this->entityHelper->entityTypeIsAtomic($entity_type_id)) {
352
        $query->condition($keys['bundle'], $bundle_name);
353
      }
354 355 356 357 358 359 360 361 362
      $entity_ids = $query->execute();

      $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');
      }

363
      $delete_instances = [];
364
      foreach($query->execute()->fetchAll() as $result) {
365 366 367
        $delete = TRUE;
        $instance_settings = unserialize($result->inclusion_settings);
        foreach ($instance_settings as $setting_key => $instance_setting) {
368
          if ($instance_setting != $settings[$setting_key]) {
369 370 371 372 373
            $delete = FALSE;
            break;
          }
        }
        if ($delete) {
374
          $delete_instances[] = $result->id;
375
        }
376
      }
377 378 379 380 381
      if (!empty($delete_instances)) {
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('id', $delete_instances, 'IN')
          ->execute();
      }
382
    }
383 384 385
    else {
      //todo: log error
    }
Pawel G's avatar
Pawel G committed
386
    return $this;
387 388
  }

389
  /**
390 391
   * Gets sitemap settings for an entity bundle, a non-bundle entity type or for
   * all entity types and their bundles.
392
   *
393 394 395
   * @param string|null $entity_type_id
   *  If set to null, sitemap settings for all entity types and their bundles
   *  are fetched.
396 397 398
   * @param string|null $bundle_name
   *
   * @return array|false
Pawel G's avatar
Pawel G committed
399 400
   *  Array of sitemap settings for an entity bundle, a non-bundle entity type
   *  or for all entity types and their bundles.
401
   *  False if entity type does not exist.
402
   */
403
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
404
    if (NULL !== $entity_type_id) {
405
      $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
406
      $bundle_settings = $this->configFactory
407 408
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->get();
409
      return !empty($bundle_settings) ? $bundle_settings : FALSE;
410
    }
411
    else {
412
      $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.");
413
      $all_settings = [];
414 415
      foreach($config_names as $config_name) {
        $config_name_parts = explode('.', $config_name);
416
        $all_settings[$config_name_parts[2]][$config_name_parts[3]] = $this->configFactory->get($config_name)->get();
417 418 419 420 421 422
      }
      return $all_settings;
    }
  }

  /**
423 424
   * Supplements all missing link setting with default values.
   *
425 426 427 428 429
   * @param string $type
   * @param array $settings
   * @return array
   */
  protected function supplementDefaultSettings($type, $settings) {
Pawel G's avatar
Pawel G committed
430
    foreach(self::$allowedLinkSettings[$type] as $allowed_link_setting) {
431
      if (!isset($settings[$allowed_link_setting])
Pawel G's avatar
Pawel G committed
432 433
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
        $settings[$allowed_link_setting] = self::$linkSettingDefaults[$allowed_link_setting];
434 435
      }
    }
436
    return $settings;
437 438
  }

Pawel G's avatar
Pawel G committed
439 440 441
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
442 443 444
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
445
   *
Pawel G's avatar
Pawel G committed
446 447
   * @return $this
   */
448
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
449
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
450 451 452
    $bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity)
    );
453
    if (!empty($bundle_settings)) {
454 455 456 457

      // Check if overrides are different from bundle setting before saving.
      $override = FALSE;
      foreach ($settings as $key => $setting) {
458
        if (!isset($bundle_settings[$key]) || $setting != $bundle_settings[$key]) {
459 460 461 462
          $override = TRUE;
          break;
        }
      }
Pawel G's avatar
Pawel G committed
463 464
      // Save overrides for this entity if something is different.
      if ($override) {
465 466 467 468 469 470 471
        $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,
472
            'inclusion_settings' => serialize(array_merge($bundle_settings, $settings)),])
473
          ->execute();
474
      }
Pawel G's avatar
Pawel G committed
475 476
      // Else unset override.
      else {
477
        $this->removeEntityInstanceSettings($entity_type_id, $id);
478
      }
479 480 481
    }
    else {
      //todo: log error
482
    }
Pawel G's avatar
Pawel G committed
483
    return $this;
484 485
  }

Pawel G's avatar
Pawel G committed
486
  /**
487
   * Gets sitemap settings for an entity instance which overrides the sitemap
488
   * settings of its bundle, or bundle settings, if they are not overridden.
Pawel G's avatar
Pawel G committed
489
   *
Pawel G's avatar
Pawel G committed
490
   * @param string $entity_type_id
491
   * @param int $id
Pawel G's avatar
Pawel G committed
492
   *
493
   * @return array|false
Pawel G's avatar
Pawel G committed
494
   */
495 496 497 498 499 500 501 502 503
  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)) {
504
      return unserialize($results);
505 506
    }
    else {
507 508 509 510 511 512
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
513 514 515
    }
  }

516 517 518 519 520 521 522 523 524 525 526 527
  /**
   * 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);
528
    if (NULL !== $entity_ids) {
529 530 531 532 533 534 535
      $entity_ids = !is_array($entity_ids) ? [$entity_ids] : $entity_ids;
      $query->condition('entity_id', $entity_ids, 'IN');
    }
    $query->execute();
    return $this;
  }

Pawel G's avatar
Pawel G committed
536 537 538 539
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
540 541
   * @param string $entity_type_id
   * @param string|null $bundle_name
Pawel G's avatar
Pawel G committed
542
   *
Pawel G's avatar
Pawel G committed
543 544
   * @return bool
   */
545
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
546 547 548 549
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
550 551 552
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
553
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
554
   *
Pawel G's avatar
Pawel G committed
555 556
   * @return bool
   */
557
  public function entityTypeIsEnabled($entity_type_id) {
558
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
559 560
  }

Pawel G's avatar
Pawel G committed
561
  /**
562
   * Stores a custom path along with its sitemap settings to configuration.
Pawel G's avatar
Pawel G committed
563
   *
Pawel G's avatar
Pawel G committed
564 565
   * @param string $path
   * @param array $settings
Pawel G's avatar
Pawel G committed
566
   *
Pawel G's avatar
Pawel G committed
567
   * @return $this
568 569
   *
   * @todo Validate $settings and throw exceptions
Pawel G's avatar
Pawel G committed
570
   */
571
  public function addCustomLink($path, $settings = []) {
Pawel G's avatar
Pawel G committed
572 573 574 575 576 577 578 579
    if (!$this->pathValidator->isValid($path)) {
      // todo: log error.
      return $this;
    }
    if ($path[0] != '/') {
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
580

581
    $custom_links = $this->getCustomLinks(FALSE);
Pawel G's avatar
Pawel G committed
582
    foreach ($custom_links as $key => $link) {
583
      if ($link['path'] === $path) {
584 585 586 587 588
        $link_key = $key;
        break;
      }
    }
    $link_key = isset($link_key) ? $link_key : count($custom_links);
589
    $custom_links[$link_key] = ['path' => $path] + $settings;
590
    $this->configFactory->getEditable("simple_sitemap.custom")
591
      ->set('links', $custom_links)->save();
Pawel G's avatar
Pawel G committed
592
    return $this;
593 594
  }

595 596 597
  /**
   * Returns an array of custom paths and their sitemap settings.
   *
598
   * @param bool $supplement_default_settings
599 600
   * @return array
   */
601
  public function getCustomLinks($supplement_default_settings = TRUE) {
602 603
    $custom_links = $this->configFactory
      ->get('simple_sitemap.custom')
604
      ->get('links');
605 606 607 608 609 610 611

    if ($supplement_default_settings) {
      foreach ($custom_links as $i => $link_settings) {
        $custom_links[$i] = $this->supplementDefaultSettings('custom', $link_settings);
      }
    }

612
    return $custom_links !== NULL ? $custom_links : [];
613 614
  }

Pawel G's avatar
Pawel G committed
615 616 617
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
618
   * @param string $path
Pawel G's avatar
Pawel G committed
619
   *
Pawel G's avatar
Pawel G committed
620
   * @return array|false
Pawel G's avatar
Pawel G committed
621
   */
622
  public function getCustomLink($path) {
623
    foreach ($this->getCustomLinks() as $key => $link) {
624
      if ($link['path'] === $path) {
625
        return $link;
626 627 628 629 630
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
631 632 633
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
634
   * @param string $path
Pawel G's avatar
Pawel G committed
635
   *
Pawel G's avatar
Pawel G committed
636 637
   * @return $this
   */
638
  public function removeCustomLink($path) {
639
    $custom_links = $this->getCustomLinks(FALSE);
Pawel G's avatar
Pawel G committed
640
    foreach ($custom_links as $key => $link) {
641
      if ($link['path'] === $path) {
642 643
        unset($custom_links[$key]);
        $custom_links = array_values($custom_links);
644
        $this->configFactory->getEditable("simple_sitemap.custom")
645
          ->set('links', $custom_links)->save();
646
        break;
647 648
      }
    }
Pawel G's avatar
Pawel G committed
649
    return $this;
650 651
  }

Pawel G's avatar
Pawel G committed
652 653
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
654 655
   *
   * @return $this
Pawel G's avatar
Pawel G committed
656
   */
657
  public function removeCustomLinks() {
658
    $this->configFactory->getEditable("simple_sitemap.custom")
659
      ->set('links', [])->save();
Pawel G's avatar
Pawel G committed
660
    return $this;
661
  }
662
}