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

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

gbyte.co's avatar
gbyte.co committed
5
use Drupal\Core\Database\Connection;
6
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
gbyte.co's avatar
gbyte.co committed
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\simple_sitemap\Queue\QueueWorker;
gbyte.co's avatar
gbyte.co committed
9
use Drupal\Core\Path\PathValidator;
gbyte.co's avatar
gbyte.co committed
10 11
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Datetime\DateFormatter;
12
use Drupal\Component\Datetime\Time;
13
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase;
14

15
/**
gbyte.co's avatar
gbyte.co committed
16
 * Class Simplesitemap
gbyte.co's avatar
gbyte.co committed
17
 * @package Drupal\simple_sitemap
18 19
 */
class Simplesitemap {
gbyte.co's avatar
gbyte.co committed
20 21 22
  /**
   * @var \Drupal\simple_sitemap\EntityHelper
   */
23
  protected $entityHelper;
gbyte.co's avatar
gbyte.co committed
24

25 26 27 28 29 30 31 32 33 34
  /**
   * @var \Drupal\simple_sitemap\SimplesitemapSettings
   */
  protected $settings;

  /**
   * @var \Drupal\simple_sitemap\SimplesitemapManager
   */
  protected $manager;

gbyte.co's avatar
gbyte.co committed
35 36 37
  /**
   * @var \Drupal\Core\Config\ConfigFactory
   */
38
  protected $configFactory;
gbyte.co's avatar
gbyte.co committed
39 40 41 42

  /**
   * @var \Drupal\Core\Database\Connection
   */
43
  protected $db;
gbyte.co's avatar
gbyte.co committed
44 45 46 47

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
48
  protected $entityTypeManager;
gbyte.co's avatar
gbyte.co committed
49

50 51 52 53 54
  /**
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

gbyte.co's avatar
gbyte.co committed
55 56 57
  /**
   * @var \Drupal\Core\Path\PathValidator
   */
58
  protected $pathValidator;
gbyte.co's avatar
gbyte.co committed
59

60 61 62 63 64
  /**
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

65 66 67 68 69
  /**
   * @var \Drupal\Component\Datetime\Time
   */
  protected $time;

70
  /**
71
   * @var \Drupal\simple_sitemap\Queue\QueueWorker
72
   */
73
  protected $queueWorker;
74

75 76 77 78 79
  /**
   * @var array
   */
  protected $variants;

gbyte.co's avatar
gbyte.co committed
80 81 82
  /**
   * @var array
   */
gbyte.co's avatar
gbyte.co committed
83
  protected static $allowedLinkSettings = [
84
    'entity' => ['index', 'priority', 'changefreq', 'include_images'],
85 86 87
    'custom' => ['priority', 'changefreq'],
  ];

gbyte.co's avatar
gbyte.co committed
88 89 90 91
  /**
   * @var array
   */
  protected static $linkSettingDefaults = [
92
    'index' => FALSE,
93
    'priority' => '0.5',
94
    'changefreq' => '',
95
    'include_images' => FALSE,
96
  ];
97

98 99
  /**
   * Simplesitemap constructor.
100
   * @param \Drupal\simple_sitemap\EntityHelper $entity_helper
101 102
   * @param \Drupal\simple_sitemap\SimplesitemapSettings $settings
   * @param \Drupal\simple_sitemap\SimplesitemapManager $manager
103
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
104
   * @param \Drupal\Core\Database\Connection $database
105
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
106
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
107 108
   * @param \Drupal\Core\Path\PathValidator $path_validator
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
109
   * @param \Drupal\Component\Datetime\Time $time
110
   * @param \Drupal\simple_sitemap\Queue\QueueWorker $queue_worker
111
   */
112
  public function __construct(
113
    EntityHelper $entity_helper,
114 115
    SimplesitemapSettings $settings,
    SimplesitemapManager $manager,
116
    ConfigFactory $config_factory,
gbyte.co's avatar
gbyte.co committed
117
    Connection $database,
118
    EntityTypeManagerInterface $entity_type_manager,
119
    EntityTypeBundleInfoInterface $entity_type_bundle_info,
120 121
    PathValidator $path_validator,
    DateFormatter $date_formatter,
122
    Time $time,
123
    QueueWorker $queue_worker
124
  ) {
125
    $this->entityHelper = $entity_helper;
126 127
    $this->settings = $settings;
    $this->manager = $manager;
128
    $this->configFactory = $config_factory;
129
    $this->db = $database;
130
    $this->entityTypeManager = $entity_type_manager;
131
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
132 133
    $this->pathValidator = $path_validator;
    $this->dateFormatter = $date_formatter;
134
    $this->time = $time;
135
    $this->queueWorker = $queue_worker;
136 137
  }

138
  /**
139 140
   * Returns a specific sitemap setting or a default value if setting does not
   * exist.
gbyte.co's avatar
gbyte.co committed
141
   *
142
   * @param string $name
gbyte.co's avatar
gbyte.co committed
143
   *  Name of the setting, like 'max_links'.
144 145
   *
   * @param mixed $default
gbyte.co's avatar
gbyte.co committed
146
   *  Value to be returned if the setting does not exist in the configuration.
147 148
   *
   * @return mixed
gbyte.co's avatar
gbyte.co committed
149
   *  The current setting from configuration or a default value.
gbyte.co's avatar
gbyte.co committed
150
   */
151
  public function getSetting($name, $default = FALSE) {
152
    return $this->settings->getSetting($name, $default);
153 154 155 156 157 158
  }

  /**
   * Stores a specific sitemap setting in configuration.
   *
   * @param string $name
gbyte.co's avatar
gbyte.co committed
159
   *  Setting name, like 'max_links'.
160
   *
161
   * @param mixed $setting
gbyte.co's avatar
gbyte.co committed
162
   *  The setting to be saved.
163 164 165 166
   *
   * @return $this
   */
  public function saveSetting($name, $setting) {
167
    $this->settings->saveSetting($name, $setting);
168 169 170
    return $this;
  }

gbyte.co's avatar
gbyte.co committed
171
  /**
172
   * @return \Drupal\simple_sitemap\Queue\QueueWorker
gbyte.co's avatar
gbyte.co committed
173
   */
174 175
  public function getQueueWorker() {
    return $this->queueWorker;
gbyte.co's avatar
gbyte.co committed
176 177 178
  }

  /**
179
   * @return \Drupal\simple_sitemap\SimplesitemapManager
gbyte.co's avatar
gbyte.co committed
180
   */
181 182
  public function getSitemapManager() {
    return $this->manager;
183 184
  }

185 186 187
  /**
   * @param array|string|true|null $variants
   *  array: Array of variants to be set.
188
   *  string: A particular variant to be set.
189 190 191 192 193 194 195
   *  null: Default variant will be set.
   *  true: All existing variants will be set.
   *
   * @return $this
   */
  public function setVariants($variants = NULL) {
    if (NULL === $variants) {
196
      $this->variants = FALSE !== ($default_variant = $this->getSetting('default_variant')) ? [$default_variant] : [];
197 198 199 200 201 202
    }
    elseif ($variants === TRUE) {
      $this->variants = array_keys(
        $this->manager->getSitemapVariants(NULL, FALSE));
    }
    else {
gbyte.co's avatar
gbyte.co committed
203
      $this->variants = (array) $variants;
204 205 206 207 208 209
    }

    return $this;
  }

  /**
210 211
   * Gets the currently set variants, the default variant, or all variants.
   *
212
   * @param bool $default_get_all
213 214 215
   *  If true and no variants are set, all variants are returned. If false and
   *  no variants are set, only the default variant is returned.
   *
216 217
   * @return array
   */
218
  protected function getVariants($default_get_all = TRUE) {
219
    if (NULL === $this->variants) {
220
      $this->setVariants($default_get_all ? TRUE : NULL);
221 222 223 224 225
    }

    return $this->variants;
  }

226
  /**
gbyte.co's avatar
gbyte.co committed
227
   * Returns a sitemap variant, its index, or its requested chunk.
228
   *
gbyte.co's avatar
gbyte.co committed
229
   * @param int|null $delta
230
   *  Optional delta of the chunk.
231 232
   *
   * @return string|false
gbyte.co's avatar
gbyte.co committed
233 234 235 236
   *  If no chunk delta is provided, either the sitemap variant is returned,
   *  or its index in case of a chunked sitemap.
   *  If a chunk delta is provided, the relevant chunk is returned.
   *  Returns false if the sitemap variant is not retrievable from the database.
237
   */
238 239
  public function getSitemap($delta = NULL) {
    $chunk_info = $this->fetchSitemapVariantInfo();
240

241
    if (empty($delta) || !isset($chunk_info[$delta])) {
242

243
      if (isset($chunk_info[SitemapGeneratorBase::INDEX_DELTA])) {
gbyte.co's avatar
gbyte.co committed
244
        // Return sitemap index if one exists.
245 246
        return $this->fetchSitemapChunk($chunk_info[SitemapGeneratorBase::INDEX_DELTA]->id)
          ->sitemap_string;
247 248
      }
      else {
gbyte.co's avatar
gbyte.co committed
249
        // Return sitemap chunk if there is only one chunk.
250 251
        return isset($chunk_info[SitemapGeneratorBase::FIRST_CHUNK_DELTA])
          ? $this->fetchSitemapChunk($chunk_info[SitemapGeneratorBase::FIRST_CHUNK_DELTA]->id)
252 253 254 255 256 257
            ->sitemap_string
          : FALSE;
      }
    }
    else {
      // Return specific sitemap chunk.
258
      return $this->fetchSitemapChunk($chunk_info[$delta]->id)->sitemap_string;
259 260 261 262
    }
  }

  /**
263
   * Fetches info about all published sitemap variants and their chunks.
264 265
   *
   * @return array
266
   *  An array containing all published sitemap chunk IDs, deltas and creation
267 268
   *  timestamps keyed by the currently set variants, or in case of only one
   *  variant set the above keyed by sitemap delta.
269
   */
270 271
  protected function fetchSitemapVariantInfo() {
    $result = $this->db->select('simple_sitemap', 's')
272
      ->fields('s', ['id', 'delta', 'sitemap_created', 'type'])
273 274 275
      ->condition('s.status', 1)
      ->condition('s.type', $this->getVariants(), 'IN')
      ->execute();
276

277 278 279
    return count($this->getVariants()) > 1
      ? $result->fetchAllAssoc('type')
      : $result->fetchAllAssoc('delta');
280 281
  }

282 283 284 285 286 287 288 289 290
  /**
   * Fetches a single sitemap chunk by ID.
   *
   * @param int $id
   *   The chunk ID.
   *
   * @return object
   *   A sitemap chunk object.
   */
291
  protected function fetchSitemapChunk($id) {
292 293 294 295
    return $this->db->query('SELECT * FROM {simple_sitemap} WHERE id = :id',
      [':id' => $id])->fetchObject();
  }

296
  /**
297 298
   * Removes sitemap instances for the currently set variants.
   *
299
   * @return $this
300
   * @throws \Drupal\Component\Plugin\Exception\PluginException
301
   */
302
  public function removeSitemap() {
303
    $this->manager->removeSitemap($this->getVariants(FALSE));
304

305 306 307
    return $this;
  }

308
  /**
309 310
   * Generates all sitemaps.
   *
311
   * @param string $from
312 313
   *  Can be 'form', 'drush', 'cron' and 'backend'.
   *
gbyte.co's avatar
gbyte.co committed
314
   * @return $this
315
   *
gbyte.co's avatar
gbyte.co committed
316
   * @throws \Drupal\Component\Plugin\Exception\PluginException
317
   *
318 319
   * @todo Respect $this->variants and generate for specific variants.
   * @todo Implement lock functionality.
320
   */
321
  public function generateSitemap($from = 'form') {
322 323 324
    switch($from) {
      case 'form':
      case 'drush':
gbyte.co's avatar
gbyte.co committed
325
        $this->queueWorker->batchGenerateSitemap($from);
326 327 328 329
        break;

      case 'cron':
      case 'backend':
gbyte.co's avatar
gbyte.co committed
330
        $this->queueWorker->generateSitemap($from);
331
        break;
332
    }
gbyte.co's avatar
gbyte.co committed
333 334

    return $this;
335
  }
336

337 338 339 340 341 342
  /**
   * Rebuilds the queue for the currently set variants.
   *
   * @return $this
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
343 344
  public function rebuildQueue() {
    $this->queueWorker->rebuildQueue($this->getVariants());
gbyte.co's avatar
gbyte.co committed
345 346

    return $this;
347 348 349 350 351
  }

  /**
   * Returns a 'time ago' string of last timestamp generation.
   *
352
   * @param string|null $variant
353 354
   *
   * @return string|array|false
gbyte.co's avatar
gbyte.co committed
355
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
356
   */
357
/*  public function getGeneratedAgo() {
358 359 360 361 362 363
    $chunks = $this->fetchSitemapVariantInfo();
    return isset($chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]->sitemap_created)
      ? $this->dateFormatter
        ->formatInterval($this->time->getRequestTime() - $chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]
            ->sitemap_created)
      : FALSE;
364
  }*/
365

366 367
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
368 369
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
370 371 372
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
gbyte.co's avatar
gbyte.co committed
373
   *  Entity type id like 'node'.
374
   *
gbyte.co's avatar
gbyte.co committed
375
   * @return $this
376 377
   */
  public function enableEntityType($entity_type_id) {
378 379 380 381
    $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);
382
    }
gbyte.co's avatar
gbyte.co committed
383
    return $this;
384 385 386 387 388 389 390 391 392
  }

  /**
   * 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
   *
gbyte.co's avatar
gbyte.co committed
393
   * @return $this
394 395
   */
  public function disableEntityType($entity_type_id) {
396 397 398

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
399
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
400
      unset ($enabled_entity_types[$key]);
401
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
402 403 404
    }

    // Deleting inclusion settings.
405
    $config_names = $this->configFactory->listAll('simple_sitemap.bundle_settings.');
gbyte.co's avatar
gbyte.co committed
406
    foreach ($config_names as $config_name) {
407 408 409 410
      $config_name_parts = explode('.', $config_name);
      if ($config_name_parts[3] === $entity_type_id) {
        $this->configFactory->getEditable($config_name)->delete();
      }
411
    }
412 413

    // Deleting entity overrides.
414 415
    $this->setVariants(TRUE)->removeEntityInstanceSettings($entity_type_id);

gbyte.co's avatar
gbyte.co committed
416
    return $this;
417 418 419
  }

  /**
420 421
   * Sets settings for bundle or non-bundle entity types. This is done for the
   * currently set variant.
422
   *
423 424
   * @param $entity_type_id
   * @param null $bundle_name
425
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
426 427
   *
   * @return $this
428
   *
429 430 431
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   *
432
   * @todo: enableEntityType automatically
433
   * @todo multiple variants
434
   */
435
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings = ['index' => TRUE]) {
436 437 438 439
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

440
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
441

gbyte.co's avatar
gbyte.co committed
442 443 444
    if (!empty($old_settings = $this->getBundleSettings($entity_type_id, $bundle_name))) {
      $settings = array_merge($old_settings, $settings);
    }
445
    self::supplementDefaultSettings('entity', $settings);
446

447
    if ($settings != $old_settings) {
448

449 450
      // Save new bundle settings to configuration.
      $bundle_settings = $this->configFactory
451
        ->getEditable("simple_sitemap.bundle_settings.$variants[0].$entity_type_id.$bundle_name");
452 453 454 455
      foreach ($settings as $setting_key => $setting) {
        $bundle_settings->set($setting_key, $setting);
      }
      $bundle_settings->save();
456

457
      // Delete entity overrides which are identical to new bundle settings.
458
      $entity_ids = $this->entityHelper->getEntityInstanceIds($entity_type_id, $bundle_name);
459 460 461 462 463 464 465
      $query = $this->db->select('simple_sitemap_entity_overrides', 'o')
        ->fields('o', ['id', 'inclusion_settings'])
        ->condition('o.entity_type', $entity_type_id)
        ->condition('o.type', $variants[0]);
      if (!empty($entity_ids)) {
        $query->condition('o.entity_id', $entity_ids, 'IN');
      }
466

467 468 469 470 471 472 473 474
      $delete_instances = [];
      foreach ($query->execute()->fetchAll() as $result) {
        $delete = TRUE;
        $instance_settings = unserialize($result->inclusion_settings);
        foreach ($instance_settings as $setting_key => $instance_setting) {
          if ($instance_setting != $settings[$setting_key]) {
            $delete = FALSE;
            break;
475 476
          }
        }
477 478
        if ($delete) {
          $delete_instances[] = $result->id;
479
        }
480
      }
481 482 483 484
      if (!empty($delete_instances)) {
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('id', $delete_instances, 'IN')
          ->execute();
485
      }
486
    }
487

gbyte.co's avatar
gbyte.co committed
488
    return $this;
489 490
  }

491
  /**
492 493
   * Gets settings for bundle or non-bundle entity types. This is done for the
   * currently set variants.
494
   *
495
   * @param string|null $entity_type_id
496 497
   *  Limit the result set to a specific entity type.
   *
498
   * @param string|null $bundle_name
499
   *  Limit the result set to a specific bundle name.
500
   *
gbyte.co's avatar
gbyte.co committed
501 502 503 504 505 506 507
   * @param bool $supplement_defaults
   *  Supplements the result set with default custom link settings.
   *
   * @param bool $multiple_variants
   *  If true, returns an array of results keyed by variant name, otherwise it
   *  returns the result set for the first variant only.
   *
508
   * @return array|false
509 510
   *  Array of settings or array of settings keyed by variant name. False if
   *  entity type does not exist.
511
   */
512
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL, $supplement_defaults = TRUE, $multiple_variants = FALSE) {
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    $all_bundle_settings = [];

    foreach ($variants = $this->getVariants(FALSE) as $variant) {
      if (NULL !== $entity_type_id) {
        $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;

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

        // If not found and entity type is enabled, return default bundle settings.
        if (empty($bundle_settings) && $supplement_defaults) {
          if ($this->entityTypeIsEnabled($entity_type_id)
            && isset($this->entityTypeBundleInfo->getBundleInfo($entity_type_id)[$bundle_name])) {
            self::supplementDefaultSettings('entity', $bundle_settings);
          }
          else {
            $bundle_settings = NULL;
          }
533
        }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
      }
      else {
        $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$variant.");
        $bundle_settings = [];
        foreach ($config_names as $config_name) {
          $config_name_parts = explode('.', $config_name);
          $bundle_settings[$config_name_parts[3]][$config_name_parts[4]] = $this->configFactory->get($config_name)->get();
        }

        // Supplement default bundle settings for all bundles not found in simple_sitemap.bundle_settings.*.* configuration.
        if ($supplement_defaults) {
          foreach ($this->entityHelper->getSupportedEntityTypes() as $type_id => $type_definition) {
            if ($this->entityTypeIsEnabled($type_id)) {
              foreach($this->entityTypeBundleInfo->getBundleInfo($type_id) as $bundle => $bundle_definition) {
                if (!isset($bundle_settings[$type_id][$bundle])) {
                  self::supplementDefaultSettings('entity', $bundle_settings[$type_id][$bundle]);
                }
              }
            }
          }
        }
      }
556
      if ($multiple_variants) {
557 558
        if (!empty($bundle_settings)) {
          $all_bundle_settings[$variant] = $bundle_settings;
559 560
        }
      }
561 562 563
      else {
        return $bundle_settings;
      }
564
    }
565 566 567 568 569

    return $all_bundle_settings;
  }

  /**
570 571 572
   * Removes settings for bundle or a non-bundle entity types. This is done for
   * the currently set variants.
   *
573
   * @param string|null $entity_type_id
574 575
   *  Limit the removal to a specific entity type.
   *
576
   * @param string|null $bundle_name
577 578
   *  Limit the removal to a specific bundle name.
   *
579
   * @return $this
580 581 582
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
583 584 585 586 587 588 589 590 591 592 593 594
   */
  public function removeBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

    if (NULL !== $entity_type_id) {
      $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;

      foreach ($variants as $variant) {
        $this->configFactory
          ->getEditable("simple_sitemap.bundle_settings.$variant.$entity_type_id.$bundle_name")->delete();
595 596
      }

597 598 599 600 601
      $this->removeEntityInstanceSettings($entity_type_id, (
        empty($ids)
          ? NULL
          : $this->entityHelper->getEntityInstanceIds($entity_type_id, $bundle_name)
      ));
602 603 604 605 606 607
    }
    else {
      foreach ($variants as $variant) {
        $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$variant.");
        foreach ($config_names as $config_name) {
          $this->configFactory->getEditable($config_name)->delete();
608
        }
609
        $this->removeEntityInstanceSettings();
610 611
      }
    }
612 613

    return $this;
614 615 616
  }

  /**
617 618
   * Supplements all missing link setting with default values.
   *
619
   * @param string $type
620 621
   *  Can be 'entity' or 'custom'.
   *
gbyte.co's avatar
gbyte.co committed
622 623
   * @param array &$settings
   * @param array $overrides
624
   */
gbyte.co's avatar
gbyte.co committed
625
  public static function supplementDefaultSettings($type, &$settings, $overrides = []) {
626
    foreach (self::$allowedLinkSettings[$type] as $allowed_link_setting) {
627
      if (!isset($settings[$allowed_link_setting])
gbyte.co's avatar
gbyte.co committed
628
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
629 630 631
        $settings[$allowed_link_setting] = isset($overrides[$allowed_link_setting])
          ? $overrides[$allowed_link_setting]
          : self::$linkSettingDefaults[$allowed_link_setting];
632 633
      }
    }
634 635
  }

636
  /**
637 638
   * Overrides sitemap settings for a single entity for the currently set
   * variants.
639
   *
gbyte.co's avatar
gbyte.co committed
640
   * @param string $entity_type_id
641
   * @param string $id
gbyte.co's avatar
gbyte.co committed
642
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
643
   *
644
   * @return $this
645 646 647
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
648
   */
649
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
650 651 652 653
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

654
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
655 656 657

    $all_bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity), TRUE, TRUE
658
    );
659 660 661 662 663 664 665 666 667 668 669

    foreach ($all_bundle_settings as $variant => $bundle_settings) {
      if (!empty($bundle_settings)) {

        // Check if overrides are different from bundle setting before saving.
        $override = FALSE;
        foreach ($settings as $key => $setting) {
          if (!isset($bundle_settings[$key]) || $setting != $bundle_settings[$key]) {
            $override = TRUE;
            break;
          }
670
        }
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
        // Save overrides for this entity if something is different.
        if ($override) {
          $this->db->merge('simple_sitemap_entity_overrides')
            ->keys([
              'type' => $variant,
              'entity_type' => $entity_type_id,
              'entity_id' => $id])
            ->fields([
              'type' => $variant,
              'entity_type' => $entity_type_id,
              'entity_id' => $id,
              'inclusion_settings' => serialize(array_merge($bundle_settings, $settings))])
            ->execute();
        }
        // Else unset override.
        else {
          $this->removeEntityInstanceSettings($entity_type_id, $id);
        }
690
      }
691
    }
692

gbyte.co's avatar
gbyte.co committed
693
    return $this;
694 695
  }

696
  /**
697 698 699
   * Gets sitemap settings for an entity instance which overrides bundle
   * settings, or gets bundle settings, if they are not overridden. This is
   * done for the currently set variant.
700
   *
gbyte.co's avatar
gbyte.co committed
701
   * @param string $entity_type_id
702
   * @param string $id
gbyte.co's avatar
gbyte.co committed
703
   *
704
   * @return array|false
705
   *  Array of entity instance settings or the settings of its bundle. False if
gbyte.co's avatar
gbyte.co committed
706
   *  entity type or variant does not exist.
707 708 709
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
710
   *
711
   * @todo multiple variants
712
   */
713
  public function getEntityInstanceSettings($entity_type_id, $id) {
714 715 716 717
    if (empty($variants = $this->getVariants(FALSE))) {
      return FALSE;
    }

718 719
    $results = $this->db->select('simple_sitemap_entity_overrides', 'o')
      ->fields('o', ['inclusion_settings'])
720
      ->condition('o.type', $variants[0])
721 722 723 724 725 726
      ->condition('o.entity_type', $entity_type_id)
      ->condition('o.entity_id', $id)
      ->execute()
      ->fetchField();

    if (!empty($results)) {
727
      return unserialize($results);
728 729
    }
    else {
730 731 732 733 734 735
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
736 737 738
    }
  }

739
  /**
740 741 742 743 744
   * Removes sitemap settings for entities that override bundle settings. This
   * is done for the currently set variants.
   *
   * @param string|null $entity_type_id
   *  Limits the removal to a certain entity type.
745 746
   *
   * @param string|null $entity_ids
747
   *  Limits the removal to entities with certain IDs.
748 749 750
   *
   * @return $this
   */
751
  public function removeEntityInstanceSettings($entity_type_id = NULL, $entity_ids = NULL) {
752
    if (empty($variants = $this->getVariants(FALSE))) {
753 754 755
      return $this;
    }

756
    $query = $this->db->delete('simple_sitemap_entity_overrides')
757 758 759 760 761 762 763 764
      ->condition('type', $variants, 'IN');

    if (NULL !== $entity_type_id) {
      $query->condition('entity_type', $entity_type_id);

      if (NULL !== $entity_ids) {
        $query->condition('entity_id', (array) $entity_ids, 'IN');
      }
765
    }
766

767
    $query->execute();
768

769 770 771
    return $this;
  }

772 773
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
774
   * indexed for the currently set variant.
775
   *
776 777
   * @param string $entity_type_id
   * @param string|null $bundle_name
gbyte.co's avatar
gbyte.co committed
778
   *
779
   * @return bool
780 781
   *
   * @todo multiple variants?
782
   */
783
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
784 785 786 787
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

788 789 790
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
791
   * @param string $entity_type_id
gbyte.co's avatar
gbyte.co committed
792
   *
793 794
   * @return bool
   */
795
  public function entityTypeIsEnabled($entity_type_id) {
796
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
797 798
  }

799
  /**
800 801
   * Stores a custom path along with its settings to configuration for the
   * currently set variants.
802
   *
gbyte.co's avatar
gbyte.co committed
803
   * @param string $path
804
   *
gbyte.co's avatar
gbyte.co committed
805
   * @param array $settings
806
   *  Settings that are not provided are supplemented by defaults.
gbyte.co's avatar
gbyte.co committed
807
   *
gbyte.co's avatar
gbyte.co committed
808
   * @return $this
809 810
   *
   * @todo Validate $settings and throw exceptions
811
   */
812
  public function addCustomLink($path, $settings = []) {
813 814 815 816
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

817
    if (!(bool) $this->pathValidator->getUrlIfValidWithoutAccessCheck($path)) {
gbyte.co's avatar
gbyte.co committed
818 819 820
      // todo: log error.
      return $this;
    }
gbyte.co's avatar
gbyte.co committed
821
    if ($path[0] !== '/') {
gbyte.co's avatar
gbyte.co committed
822 823 824
      // todo: log error.
      return $this;
    }
gbyte.co's avatar
gbyte.co committed
825

826 827 828 829 830 831 832 833 834 835 836 837 838
    $variant_links = $this->getCustomLinks(NULL, FALSE, TRUE);
    foreach ($variants as $variant) {
      $links = [];
      $link_key = 0;
      if (isset($variant_links[$variant])) {
        $links = $variant_links[$variant];
        $link_key = count($links);
        foreach ($links as $key => $link) {
          if ($link['path'] === $path) {
            $link_key = $key;
            break;
          }
        }
839
      }
840 841 842 843

      $links[$link_key] = ['path' => $path] + $settings;
      $this->configFactory->getEditable("simple_sitemap.custom_links.$variant")
        ->set('links', $links)->save();
844
    }
845

gbyte.co's avatar
gbyte.co committed
846
    return $this;
847 848
  }

849
  /**
850 851 852 853
   * Gets custom link settings for the currently set variants.
   *
   * @param string|null $path
   *  Limits the result set by an internal path.
854
   *
855
   * @param bool $supplement_defaults
856 857 858 859 860 861 862
   *  Supplements the result set with default custom link settings.
   *
   * @param bool $multiple_variants
   *  If true, returns an array of results keyed by variant name, otherwise it
   *  returns the result set for the first variant only.
   *
   * @return array|mixed|null
863
   */
864 865 866 867 868 869
  public function getCustomLinks($path = NULL, $supplement_defaults = TRUE, $multiple_variants = FALSE) {
    $all_custom_links = [];
    foreach ($variants = $this->getVariants(FALSE) as $variant) {
      $custom_links = $this->configFactory
        ->get("simple_sitemap.custom_links.$variant")
        ->get('links');
870

871 872 873 874 875 876 877 878
      $custom_links = !empty($custom_links) ? $custom_links : [];

      if (!empty($custom_links) && $path !== NULL) {
        foreach ($custom_links as $key => $link) {
          if ($link['path'] !== $path) {
            unset($custom_links[$key]);
          }
        }
879 880
      }

881 882 883 884 885 886
      if (!empty($custom_links) && $supplement_defaults) {
        foreach ($custom_links as $i => $link_settings) {
          self::supplementDefaultSettings('custom', $link_settings);
          $custom_links[$i] = $link_settings;
        }
      }
887

888 889 890 891 892 893 894 895 896 897 898 899
      $custom_links = $path !== NULL && !empty($custom_links)
        ? array_values($custom_links)[0]
        : array_values($custom_links);


      if (!empty($custom_links)) {
        if ($multiple_variants) {
          $all_custom_links[$variant] = $custom_links;
        }
        else {
          return $custom_links;
        }
900 901
      }
    }
902 903

    return $all_custom_links;
904 905
  }

906
  /**
907 908 909 910
   * Removes custom links from currently set variants.
   *
   * @param array|null $paths
   *  Limits the removal to certain paths.
gbyte.co's avatar
gbyte.co committed
911
   *
912 913
   * @return $this
   */
914
  public function removeCustomLinks($paths = NULL) {
915 916 917 918
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

919
    if (NULL === $paths) {
920 921 922 923
      foreach ($variants as $variant) {
        $this->configFactory
          ->getEditable("simple_sitemap.custom_links.$variant")->delete();
      }
924 925
    }
    else {
926 927 928 929 930 931 932 933 934 935 936
      $variant_links = $this->getCustomLinks(NULL, FALSE, TRUE);
      foreach ($variant_links as $variant => $links) {
        $custom_links = $links;
        $save = FALSE;
        foreach ((array) $paths  as $path) {
          foreach ($custom_links as $key => $link) {
            if ($link['path'] === $path) {
              unset($custom_links[$key]);
              $save = TRUE;
              break 2;
            }
937 938
          }
        }
939 940 941 942
        if ($save) {
          $this->configFactory->getEditable("simple_sitemap.custom_links.$variant")
            ->set('links', array_values($custom_links))->save();
        }
943 944 945
      }
    }

gbyte.co's avatar
gbyte.co committed
946
    return $this;
947
  }
948
}