Simplesitemap.php 27.7 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 6
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
7
use Drupal\simple_sitemap\Queue\QueueWorker;
gbyte.co's avatar
gbyte.co committed
8
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
use Drupal\Component\Datetime\Time;
12
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase;
13

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

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

  /**
   * @var \Drupal\Core\Path\PathValidator
   */
53
  protected $pathValidator;
gbyte.co's avatar
gbyte.co committed
54

55 56 57 58 59
  /**
   * @var \Drupal\Core\Datetime\DateFormatter
   */
  protected $dateFormatter;

60 61 62 63 64
  /**
   * @var \Drupal\Component\Datetime\Time
   */
  protected $time;

65
  /**
66
   * @var \Drupal\simple_sitemap\Queue\QueueWorker
67
   */
68
  protected $queueWorker;
69

70 71 72 73 74
  /**
   * @var array
   */
  protected $variants;

gbyte.co's avatar
gbyte.co committed
75 76 77
  /**
   * @var array
   */
gbyte.co's avatar
gbyte.co committed
78
  protected static $allowedLinkSettings = [
79
    'entity' => ['index', 'priority', 'changefreq', 'include_images'],
80 81 82
    'custom' => ['priority', 'changefreq'],
  ];

gbyte.co's avatar
gbyte.co committed
83 84 85 86
  /**
   * @var array
   */
  protected static $linkSettingDefaults = [
87
    'index' => FALSE,
88
    'priority' => '0.5',
89
    'changefreq' => '',
90
    'include_images' => FALSE,
91
  ];
92

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

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

  /**
   * Stores a specific sitemap setting in configuration.
   *
   * @param string $name
gbyte.co's avatar
gbyte.co committed
151
   *  Setting name, like 'max_links'.
152
   *
153
   * @param mixed $setting
gbyte.co's avatar
gbyte.co committed
154
   *  The setting to be saved.
155 156 157 158
   *
   * @return $this
   */
  public function saveSetting($name, $setting) {
159
    $this->settings->saveSetting($name, $setting);
160

161 162 163
    return $this;
  }

gbyte.co's avatar
gbyte.co committed
164
  /**
165
   * @return \Drupal\simple_sitemap\Queue\QueueWorker
gbyte.co's avatar
gbyte.co committed
166
   */
167 168
  public function getQueueWorker() {
    return $this->queueWorker;
gbyte.co's avatar
gbyte.co committed
169 170 171
  }

  /**
172
   * @return \Drupal\simple_sitemap\SimplesitemapManager
gbyte.co's avatar
gbyte.co committed
173
   */
174 175
  public function getSitemapManager() {
    return $this->manager;
176 177
  }

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

    return $this;
  }

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

    return $this->variants;
  }

221
  /**
gbyte.co's avatar
gbyte.co committed
222
   * Returns a sitemap variant, its index, or its requested chunk.
223
   *
gbyte.co's avatar
gbyte.co committed
224
   * @param int|null $delta
225
   *  Optional delta of the chunk.
226 227
   *
   * @return string|false
gbyte.co's avatar
gbyte.co committed
228 229 230 231
   *  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.
232
   */
233 234
  public function getSitemap($delta = NULL) {
    $chunk_info = $this->fetchSitemapVariantInfo();
235

236
    if (empty($delta) || !isset($chunk_info[$delta])) {
237

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

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

      return count($this->getVariants()) > 1
        ? $result->fetchAllAssoc('type')
        : $result->fetchAllAssoc('delta');
    }
    else {
      return [];
    }
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
    }
383

gbyte.co's avatar
gbyte.co committed
384
    return $this;
385 386 387 388 389 390 391 392 393
  }

  /**
   * 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
394
   * @return $this
395 396
   */
  public function disableEntityType($entity_type_id) {
397 398 399

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

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

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

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

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

442
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
443

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

449
    if ($settings != $old_settings) {
450

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

459
      // Delete entity overrides which are identical to new bundle settings.
460
      $entity_ids = $this->entityHelper->getEntityInstanceIds($entity_type_id, $bundle_name);
461 462 463 464 465 466 467
      $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');
      }
468

469 470 471 472 473 474 475 476
      $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;
477 478
          }
        }
479 480
        if ($delete) {
          $delete_instances[] = $result->id;
481
        }
482
      }
483 484 485 486
      if (!empty($delete_instances)) {
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('id', $delete_instances, 'IN')
          ->execute();
487
      }
488
    }
489

gbyte.co's avatar
gbyte.co committed
490
    return $this;
491 492
  }

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

516
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
517 518 519 520 521 522 523 524 525
    $all_bundle_settings = [];

    foreach ($variants = $this->getVariants(FALSE) as $variant) {
      if (NULL !== $entity_type_id) {
        $bundle_settings = $this->configFactory
          ->get("simple_sitemap.bundle_settings.$variant.$entity_type_id.$bundle_name")
          ->get();

        if (empty($bundle_settings) && $supplement_defaults) {
526
          self::supplementDefaultSettings('entity', $bundle_settings);
527
        }
528 529 530 531 532 533 534 535 536 537 538 539
      }
      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) {
540
            foreach($this->entityHelper->getBundleInfo($type_id) as $bundle => $bundle_definition) {
541 542
              if (!isset($bundle_settings[$type_id][$bundle])) {
                self::supplementDefaultSettings('entity', $bundle_settings[$type_id][$bundle]);
543 544 545 546 547
              }
            }
          }
        }
      }
548

549
      if ($multiple_variants) {
550
        $all_bundle_settings[$variant] = $bundle_settings;
551
      }
552 553 554
      else {
        return $bundle_settings;
      }
555
    }
556 557 558 559 560

    return $all_bundle_settings;
  }

  /**
561 562 563
   * Removes settings for bundle or a non-bundle entity types. This is done for
   * the currently set variants.
   *
564
   * @param string|null $entity_type_id
565 566
   *  Limit the removal to a specific entity type.
   *
567
   * @param string|null $bundle_name
568 569
   *  Limit the removal to a specific bundle name.
   *
570
   * @return $this
571 572 573
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
574 575 576 577 578 579 580 581 582 583 584 585
   */
  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();
586 587
      }

588 589 590 591 592
      $this->removeEntityInstanceSettings($entity_type_id, (
        empty($ids)
          ? NULL
          : $this->entityHelper->getEntityInstanceIds($entity_type_id, $bundle_name)
      ));
593 594 595 596 597 598
    }
    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();
599
        }
600
        $this->removeEntityInstanceSettings();
601 602
      }
    }
603 604

    return $this;
605 606 607
  }

  /**
608 609
   * Supplements all missing link setting with default values.
   *
610
   * @param string $type
611 612
   *  Can be 'entity' or 'custom'.
   *
gbyte.co's avatar
gbyte.co committed
613 614
   * @param array &$settings
   * @param array $overrides
615
   */
gbyte.co's avatar
gbyte.co committed
616
  public static function supplementDefaultSettings($type, &$settings, $overrides = []) {
617
    foreach (self::$allowedLinkSettings[$type] as $allowed_link_setting) {
618
      if (!isset($settings[$allowed_link_setting])
gbyte.co's avatar
gbyte.co committed
619
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
620 621 622
        $settings[$allowed_link_setting] = isset($overrides[$allowed_link_setting])
          ? $overrides[$allowed_link_setting]
          : self::$linkSettingDefaults[$allowed_link_setting];
623 624
      }
    }
625 626
  }

627
  /**
628 629
   * Overrides sitemap settings for a single entity for the currently set
   * variants.
630
   *
gbyte.co's avatar
gbyte.co committed
631
   * @param string $entity_type_id
632
   * @param string $id
gbyte.co's avatar
gbyte.co committed
633
   * @param array $settings
gbyte.co's avatar
gbyte.co committed
634
   *
635
   * @return $this
636 637 638
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
639
   */
640
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
641 642 643 644
    if (empty($variants = $this->getVariants(FALSE))) {
      return $this;
    }

645
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
646 647 648

    $all_bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity), TRUE, TRUE
649
    );
650 651 652 653 654 655 656 657 658 659 660

    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;
          }
661
        }
662

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
        // 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);
        }
681
      }
682
    }
683

gbyte.co's avatar
gbyte.co committed
684
    return $this;
685 686
  }

687
  /**
688 689 690
   * 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.
691 692
   * Please note, this method takes only the first set
   * variant into account. See todo.
693
   *
gbyte.co's avatar
gbyte.co committed
694
   * @param string $entity_type_id
695
   * @param string $id
gbyte.co's avatar
gbyte.co committed
696
   *
697
   * @return array|false
698
   *  Array of entity instance settings or the settings of its bundle. False if
gbyte.co's avatar
gbyte.co committed
699
   *  entity type or variant does not exist.
700 701 702
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
703
   *
704
   * @todo multiple variants
705
   * @todo: May want to use Simplesitemap::supplementDefaultSettings('entity', $settings) inside here instead of calling it everywhere this method is called.
706
   */
707
  public function getEntityInstanceSettings($entity_type_id, $id) {
708 709 710 711
    if (empty($variants = $this->getVariants(FALSE))) {
      return FALSE;
    }

712 713
    $results = $this->db->select('simple_sitemap_entity_overrides', 'o')
      ->fields('o', ['inclusion_settings'])
714
      ->condition('o.type', $variants[0])
715 716 717 718 719 720
      ->condition('o.entity_type', $entity_type_id)
      ->condition('o.entity_id', $id)
      ->execute()
      ->fetchField();

    if (!empty($results)) {
721
      return unserialize($results);
722 723
    }
    else {
724 725
      return $this->getBundleSettings(
        $entity_type_id,
726 727 728
        $this->entityHelper->getEntityInstanceBundleName(
          $this->entityTypeManager->getStorage($entity_type_id)->load($id)
        )
729
      );
730 731 732
    }
  }

733
  /**
734 735 736 737 738
   * 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.
739 740
   *
   * @param string|null $entity_ids
741
   *  Limits the removal to entities with certain IDs.
742 743 744
   *
   * @return $this
   */
745
  public function removeEntityInstanceSettings($entity_type_id = NULL, $entity_ids = NULL) {
746
    if (empty($variants = $this->getVariants(FALSE))) {
747 748 749
      return $this;
    }

750
    $query = $this->db->delete('simple_sitemap_entity_overrides')
751 752 753 754 755 756 757 758
      ->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');
      }
759
    }
760

761
    $query->execute();
762

763 764 765
    return $this;
  }

766 767
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
768
   * indexed for any of the currently set variants.
769
   *
770 771
   * @param string $entity_type_id
   * @param string|null $bundle_name
gbyte.co's avatar
gbyte.co committed
772
   *
773 774
   * @return bool
   */
775
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
776 777 778 779 780
    foreach ($this->getBundleSettings($entity_type_id, $bundle_name, FALSE, TRUE) as $settings) {
      if (!empty($settings['index'])) {
        return TRUE;
      }
    }
781

782
    return FALSE;
783 784
  }

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

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

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

823 824 825 826 827 828 829 830 831 832 833 834 835
    $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;
          }
        }
836
      }
837 838 839 840

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

gbyte.co's avatar
gbyte.co committed
843
    return $this;
844 845
  }

846
  /**
847 848 849 850
   * Gets custom link settings for the currently set variants.
   *
   * @param string|null $path
   *  Limits the result set by an internal path.
851
   *
852
   * @param bool $supplement_defaults
853 854 855 856 857 858 859
   *  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
860
   */
861 862 863 864 865 866
  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');
867

868 869 870 871 872 873 874 875
      $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]);
          }
        }
876 877
      }

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

885 886 887 888 889 890 891 892 893 894 895 896
      $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;
        }
897 898
      }
    }
899 900

    return $all_custom_links;
901 902
  }

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

916
    if (NULL === $paths) {
917 918 919 920
      foreach ($variants as $variant) {
        $this->configFactory
          ->getEditable("simple_sitemap.custom_links.$variant")->delete();
      }
921 922
    }
    else {
923 924 925 926 927 928 929 930 931 932 933
      $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;
            }
934 935
          }
        }
936 937 938 939
        if ($save) {
          $this->configFactory->getEditable("simple_sitemap.custom_links.$variant")
            ->set('links', array_values($custom_links))->save();
        }
940 941 942
      }
    }

gbyte.co's avatar
gbyte.co committed
943
    return $this;
944
  }
945
}