Simplesitemap.php 28.2 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
use Drupal\Core\Database\Connection;
6
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
Pawel G's avatar
Pawel G committed
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\Core\Extension\ModuleHandler;
Pawel G's avatar
Pawel G committed
9
use Drupal\Core\Path\PathValidator;
Pawel G's avatar
Pawel G committed
10 11
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Datetime\DateFormatter;
12
use Drupal\Component\Datetime\Time;
13 14 15
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\DefaultSitemapGenerator;
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase;
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorManager;
16
use Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorManager;
17

18
/**
Pawel G's avatar
Pawel G committed
19
 * Class Simplesitemap
Pawel G's avatar
Pawel G committed
20
 * @package Drupal\simple_sitemap
21 22 23
 */
class Simplesitemap {

Pawel G's avatar
Pawel G committed
24 25 26
  const DEFAULT_SITEMAP_TYPE = 'default_hreflang';
  const DEFAULT_SITEMAP_VARIANT = 'default';

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

  /**
   * @var \Drupal\Core\Config\ConfigFactory
   */
35
  protected $configFactory;
Pawel G's avatar
Pawel G committed
36 37 38 39

  /**
   * @var \Drupal\Core\Database\Connection
   */
40
  protected $db;
Pawel G's avatar
Pawel G committed
41 42 43 44

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

47 48 49 50 51
  /**
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

Pawel G's avatar
Pawel G committed
52 53 54
  /**
   * @var \Drupal\Core\Path\PathValidator
   */
55
  protected $pathValidator;
Pawel G's avatar
Pawel G committed
56

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

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

67
  /**
68
   * @var \Drupal\Core\Extension\ModuleHandler
69
   */
70
  protected $moduleHandler;
71 72

  /**
73
   * @var \Drupal\simple_sitemap\Batch
74
   */
75
  protected $batch;
76

77 78 79 80 81
  /**
   * @var \Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorManager
   */
  protected $urlGeneratorManager;

82 83 84 85 86
  /**
   * @var \Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorManager
   */
  protected $sitemapGeneratorManager;

Pawel G's avatar
Pawel G committed
87 88 89
  /**
   * @var array
   */
Pawel G's avatar
Pawel G committed
90
  protected static $allowedLinkSettings = [
91
    'entity' => ['index', 'priority', 'changefreq', 'include_images'],
92 93 94
    'custom' => ['priority', 'changefreq'],
  ];

Pawel G's avatar
Pawel G committed
95 96 97 98
  /**
   * @var array
   */
  protected static $linkSettingDefaults = [
99
    'index' => 1,
100
    'priority' => 0.5,
101
    'changefreq' => '',
102
    'include_images' => 0,
103
  ];
104

105 106
  /**
   * Simplesitemap constructor.
107 108
   * @param \Drupal\simple_sitemap\EntityHelper $entity_helper
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
Pawel G's avatar
Pawel G committed
109
   * @param \Drupal\Core\Database\Connection $database
110
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
111
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
112 113
   * @param \Drupal\Core\Path\PathValidator $path_validator
   * @param \Drupal\Core\Datetime\DateFormatter $date_formatter
114
   * @param \Drupal\Component\Datetime\Time $time
115
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
116
   * @param \Drupal\simple_sitemap\Batch $batch
117 118
   * @param \Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorManager $url_generator_manager
   * @param \Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorManager $sitemap_generator_manager
119
   */
120
  public function __construct(
121 122
    EntityHelper $entity_helper,
    ConfigFactory $config_factory,
Pawel G's avatar
Pawel G committed
123
    Connection $database,
124
    EntityTypeManagerInterface $entity_type_manager,
125
    EntityTypeBundleInfoInterface $entity_type_bundle_info,
126 127
    PathValidator $path_validator,
    DateFormatter $date_formatter,
128
    Time $time,
129
    ModuleHandler $module_handler,
130
    Batch $batch,
131 132
    UrlGeneratorManager $url_generator_manager,
    SitemapGeneratorManager $sitemap_generator_manager
133
  ) {
134 135
    $this->entityHelper = $entity_helper;
    $this->configFactory = $config_factory;
136
    $this->db = $database;
137
    $this->entityTypeManager = $entity_type_manager;
138
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
139 140
    $this->pathValidator = $path_validator;
    $this->dateFormatter = $date_formatter;
141
    $this->time = $time;
142
    $this->moduleHandler = $module_handler;
143
    $this->batch = $batch;
144 145
    $this->urlGeneratorManager = $url_generator_manager;
    $this->sitemapGeneratorManager = $sitemap_generator_manager;
146 147
  }

148
  /**
149 150
   * Returns a specific sitemap setting or a default value if setting does not
   * exist.
Pawel G's avatar
Pawel G committed
151
   *
152
   * @param string $name
Pawel G's avatar
Pawel G committed
153
   *  Name of the setting, like 'max_links'.
154 155
   *
   * @param mixed $default
Pawel G's avatar
Pawel G committed
156
   *  Value to be returned if the setting does not exist in the configuration.
157 158
   *
   * @return mixed
Pawel G's avatar
Pawel G committed
159
   *  The current setting from configuration or a default value.
Pawel G's avatar
Pawel G committed
160
   */
161 162 163 164 165 166 167 168 169 170 171
  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
Pawel G's avatar
Pawel G committed
172
   *  Setting name, like 'max_links'.
173
   * @param mixed $setting
Pawel G's avatar
Pawel G committed
174
   *  The setting to be saved.
175 176 177 178
   *
   * @return $this
   */
  public function saveSetting($name, $setting) {
Pawel G's avatar
Pawel G committed
179
    $this->configFactory->getEditable('simple_sitemap.settings')
180 181 182 183 184 185 186 187
      ->set($name, $setting)->save();
    return $this;
  }

  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
188
   * @param string $variant
189 190
   *
   * @param int $delta
191 192
   *
   * @return string|false
Pawel G's avatar
Pawel G committed
193
   *  If no sitemap ID provided, either a sitemap index is returned, or the
194 195
   *  whole sitemap variant, if the amount of links does not exceed the max
   *  links setting. If a sitemap ID is provided, a sitemap chunk is returned.
Pawel G's avatar
Pawel G committed
196
   *  Returns false if the sitemap is not retrievable from the database.
197
   */
Pawel G's avatar
Pawel G committed
198 199
  public function getSitemap($variant = self::DEFAULT_SITEMAP_VARIANT, $delta = NULL) {
    $chunk_info = $this->fetchSitemapVariantInfo($variant);
200

201
    if (empty($delta) || !isset($chunk_info[$delta])) {
202

203
      if (isset($chunk_info[SitemapGeneratorBase::INDEX_DELTA])) {
Pawel G's avatar
Pawel G committed
204
        // Return sitemap index if one exists.
205 206
        return $this->fetchSitemapChunk($chunk_info[SitemapGeneratorBase::INDEX_DELTA]->id)
          ->sitemap_string;
207 208
      }
      else {
Pawel G's avatar
Pawel G committed
209
        // Return sitemap chunk if there is only one chunk.
210 211
        return isset($chunk_info[SitemapGeneratorBase::FIRST_CHUNK_DELTA])
          ? $this->fetchSitemapChunk($chunk_info[SitemapGeneratorBase::FIRST_CHUNK_DELTA]->id)
212 213 214 215 216 217
            ->sitemap_string
          : FALSE;
      }
    }
    else {
      // Return specific sitemap chunk.
218
      return $this->fetchSitemapChunk($chunk_info[$delta]->id)->sitemap_string;
219 220 221 222
    }
  }

  /**
Pawel G's avatar
Pawel G committed
223
   * Fetches info about all sitemap variants and their chunks.
224
   *
225
   * @param string|null $variant
226
   *
227
   * @return array
Pawel G's avatar
Pawel G committed
228 229
   *  An array containing all sitemap chunk IDs, deltas and creation timestamps
   * keyed by their variant ID.
230
   */
Pawel G's avatar
Pawel G committed
231
  protected function fetchSitemapVariantInfo($variant = NULL) {
232 233 234
    $query = $this->db->select('simple_sitemap', 's')
      ->fields('s', ['id', 'delta', 'sitemap_created', 'type']);

235 236
    if (NULL !== $variant) {
      $query->condition('s.type', $variant);
237 238 239 240
    }

    $result = $query->execute();

241
    return NULL === $variant ? $result->fetchAllAssoc('type') : $result->fetchAllAssoc('delta');
242 243
  }

244 245 246 247 248 249 250 251 252
  /**
   * Fetches a single sitemap chunk by ID.
   *
   * @param int $id
   *   The chunk ID.
   *
   * @return object
   *   A sitemap chunk object.
   */
253
  protected function fetchSitemapChunk($id) {
254 255 256 257
    return $this->db->query('SELECT * FROM {simple_sitemap} WHERE id = :id',
      [':id' => $id])->fetchObject();
  }

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
  /**
   * @return array
   *
   * @todo document
   */
  public function getSitemapTypeDefinitions() {
    $type_definitions = [];
    foreach ($this->configFactory->listAll('simple_sitemap.types.') as $config_name) {
      $type_definitions[explode('.', $config_name)[2]] = $this->configFactory->get($config_name)->get();
    }

    return $type_definitions;
  }

  /**
   * @param $name
   * @param $definition
   *
   * @todo document
   */
  public function setSitemapTypeDefinition($name, $definition) {
    $type = $this->configFactory->getEditable("simple_sitemap.types.$name");
    foreach ($definition as $key => $value) {
      if (in_array($key, ['label', 'description', 'sitemap_generator', 'url_generators'])) {
        $type->set($key, $value);
      }
      else {
        //todo exception
      }
    }
    $type->save();
  }

  /**
   * @param $name
   *
   * @todo document
   */
  public function removeSitemapTypeDefinition($name) {
Pawel G's avatar
Pawel G committed
297
    if ($name !== self::DEFAULT_SITEMAP_TYPE) {
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
      $this->configFactory->getEditable("simple_sitemap.types.$name")->delete();
    }
    else {
      //todo: exception
    }
  }

  /**
   * @return array
   *
   * @todo document
   * @todo translate label
   */
  public function getSitemapVariants() {
    return $this->configFactory->get('simple_sitemap.variants')->get('variants');
  }

  /**
   * @param $name
   * @param $definition
   * @return $this
   *
   * @todo document
   * @todo exceptions
   */
  public function addSitemapVariant($name, $definition) {
    if (empty($definition['label'])) {
Pawel G's avatar
Pawel G committed
325
      $definition['label'] = $name;
326 327 328
    }

    if (empty($definition['type'])) {
Pawel G's avatar
Pawel G committed
329
      $definition['type'] = self::DEFAULT_SITEMAP_TYPE;
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    }

    $variants = array_merge($this->getSitemapVariants(), [$name => ['label' => $definition['label'], 'type' => $definition['type']]]);
    $this->configFactory->getEditable('simple_sitemap.variants')
      ->set('variants', $variants)->save();

    return $this;
  }

  /**
   * @param $name
   * @return $this
   *
   * @todo document
   */
  public function removeSitemapVariant($name) {
    $variants = $this->getSitemapVariants();
Pawel G's avatar
Pawel G committed
347 348 349 350 351
    if (isset($variants[$name])) {
      unset($variants[$name]);
      $this->configFactory->getEditable('simple_sitemap.variants')
        ->set('variants', $variants)->save();
    }
352 353 354 355

    return $this;
  }

356
  /**
Pawel G's avatar
Pawel G committed
357
   * Generates the XML sitemap and saves it to the database.
358 359
   *
   * @param string $from
Pawel G's avatar
Pawel G committed
360 361
   *  Can be 'form', 'backend', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
Pawel G's avatar
Pawel G committed
362
   *
363
   * @param array|string|null $variants
364
   *
Pawel G's avatar
Pawel G committed
365
   * @return bool|\Drupal\simple_sitemap\Simplesitemap
366
   */
367 368
  public function generateSitemap($from = 'form', $variants = NULL) {
    $variants = NULL === $variants ? NULL : (array) $variants;
369

370
    $settings = [
371
      'base_url' => $this->getSetting('base_url', ''),
372
      'batch_process_limit' => $this->getSetting('batch_process_limit', 1500),
373 374 375 376
      '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', []),
377
    ];
378

379 380
    $this->batch->setBatchMeta(['from' => $from]);

381
    $operations = [];
Pawel G's avatar
Pawel G committed
382

383 384
    $type_definitions = $this->getSitemapTypeDefinitions();
    $this->moduleHandler->alter('simple_sitemap_types', $type_definitions);
Pawel G's avatar
Pawel G committed
385

386 387
    $sitemap_variants = $this->getSitemapVariants();
    $this->moduleHandler->alter('simple_sitemap_variants', $sitemap_variants);
388

389 390 391 392 393 394
    foreach ($sitemap_variants as $variant_name => $variant_definition) {

      // Skipping unwanted sitemap variants.
      if (NULL !== $variants && !in_array($variant_name, $variants)) {
        continue;
      }
395

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
      $type = $variant_definition['type'];

      // Adding a remove_sitemap operation for all sitemap variants.
      $operations[] = [
        'operation' => 'removeSitemap',
        'arguments' => [
          'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
          'variant' => $variant_name,
        ]
      ];

      // Adding generate_sitemap operations for all data sets.
      foreach ($type_definitions[$type]['url_generators'] as $url_generator_id) {
        foreach ($this->urlGeneratorManager->createInstance($url_generator_id)
                   ->setSitemapVariant($variant_name)
                   ->getDataSets() as $data_set) {
          if (!empty($data_set)) {
            $operations[] = [
              'operation' => 'generateSitemap',
415
              'arguments' => [
416 417 418 419 420 421
                'url_generator' => $url_generator_id,
                'data_set' => $data_set,
                'variant' => $variant_name,
                'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
                'settings' => $settings,
              ],
422 423
            ];
          }
424
        }
425
      }
426

427 428
      // Adding generate_index operations for all sitemap variants.
      $operations[] = [
429 430
        'operation' => 'generateIndex',
        'arguments' => [
431 432
          'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
          'variant' => $variant_name,
433 434 435 436 437
          'settings' => $settings,
        ],
      ];
    }

438 439 440 441
    // Adding operations to and starting batch.
    if (!empty($operations)) {
      foreach ($operations as $operation_data) {
        $this->batch->addOperation($operation_data['operation'], $operation_data['arguments']);
442 443 444 445 446
      }
      $success = $this->batch->start();
    }

    return $from === 'nobatch' ? $this : (isset($success) ? $success : FALSE);
447 448
  }

449
  /**
450
   * @param null|array $variant
Pawel G's avatar
Pawel G committed
451
   *
452 453
   * @todo Add removeSitemap API method.
   */
454
  public function removeSitemap($variant = NULL) {
Pawel G's avatar
Pawel G committed
455 456

  }
457

458 459 460
  /**
   * Returns a 'time ago' string of last timestamp generation.
   *
461
   * @param string|null $variant
462 463
   *
   * @return string|array|false
Pawel G's avatar
Pawel G committed
464
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
465
   */
466
  public function getGeneratedAgo($variant = NULL) {
Pawel G's avatar
Pawel G committed
467
    $chunks = $this->fetchSitemapVariantInfo($variant);
468
    if ($variant !== NULL) {
469
      return isset($chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]->sitemap_created)
470
        ? $this->dateFormatter
471
          ->formatInterval($this->time->getRequestTime() - $chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]
472 473 474 475 476 477 478 479 480 481 482 483
              ->sitemap_created)
        : FALSE;
    }
    else {
      $time_strings = [];
//      foreach ($chunks as $sitemap_type => $type_chunks) {
//        $time_strings[$sitemap_type] = isset($type_chunks[DefaultSitemapGenerator::FIRST_DELTA_INDEX]->sitemap_created)
//          ? $type_chunks[DefaultSitemapGenerator::FIRST_DELTA_INDEX]->sitemap_created
//          : FALSE;
//    }
      // todo: Implement.
      return $time_strings;
484 485 486
    }
  }

487 488
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
489 490
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
491 492 493
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
494
   *  Entity type id like 'node'.
495
   *
Pawel G's avatar
Pawel G committed
496
   * @return $this
497 498
   */
  public function enableEntityType($entity_type_id) {
499 500 501 502
    $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);
503
    }
Pawel G's avatar
Pawel G committed
504
    return $this;
505 506 507 508 509 510 511 512
  }

  /**
   * 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
513
   *  Entity type id like 'node'.
514
   *
Pawel G's avatar
Pawel G committed
515
   * @return $this
516 517
   */
  public function disableEntityType($entity_type_id) {
518 519 520

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
521
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
522
      unset ($enabled_entity_types[$key]);
523
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
524 525 526
    }

    // Deleting inclusion settings.
527
    $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$entity_type_id.");
Pawel G's avatar
Pawel G committed
528
    foreach ($config_names as $config_name) {
529
      $this->configFactory->getEditable($config_name)->delete();
530
    }
531 532 533

    // Deleting entity overrides.
    $this->removeEntityInstanceSettings($entity_type_id);
Pawel G's avatar
Pawel G committed
534
    return $this;
535 536 537
  }

  /**
Pawel G's avatar
Pawel G committed
538
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
539 540 541
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
542
   *  Entity type id like 'node' the bundle belongs to.
543
   * @param string $bundle_name
Pawel G's avatar
Pawel G committed
544
   *  Name of the bundle. NULL if entity type has no bundles.
545
   * @param array $settings
Pawel G's avatar
Pawel G committed
546 547
   *  An array of sitemap settings for this bundle/entity type.
   *  Example: ['index' => TRUE, 'priority' => 0.5, 'changefreq' => 'never', 'include_images' => FALSE].
Pawel G's avatar
Pawel G committed
548 549
   *
   * @return $this
550 551
   *
   * @todo: enableEntityType automatically
552
   */
553
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings = []) {
554
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
555

Pawel G's avatar
Pawel G committed
556 557 558 559 560 561
    if (!empty($old_settings = $this->getBundleSettings($entity_type_id, $bundle_name))) {
      $settings = array_merge($old_settings, $settings);
    }
    else {
      self::supplementDefaultSettings('entity', $settings);
    }
562 563 564

    $bundle_settings = $this->configFactory
      ->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name");
Pawel G's avatar
Pawel G committed
565
    foreach ($settings as $setting_key => $setting) {
566
      if ($setting_key === 'index') {
Pawel G's avatar
Pawel G committed
567
        $setting = (int) $setting;
568
      }
569
      $bundle_settings->set($setting_key, $setting);
570
    }
571
    $bundle_settings->save();
572 573

    // Delete entity overrides which are identical to new bundle setting.
Pawel G's avatar
Pawel G committed
574
    $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
575 576 577
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $entity_type = $sitemap_entity_types[$entity_type_id];
      $keys = $entity_type->getKeys();
578 579

      // Menu fix.
Pawel G's avatar
Pawel G committed
580
      $keys['bundle'] = $entity_type_id === 'menu_link_content' ? 'menu_name' : $keys['bundle'];
581

582
      $query = $this->entityTypeManager->getStorage($entity_type_id)->getQuery();
583
      if (!$this->entityHelper->entityTypeIsAtomic($entity_type_id)) {
584
        $query->condition($keys['bundle'], $bundle_name);
585
      }
586 587 588 589 590 591 592 593 594
      $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');
      }

595
      $delete_instances = [];
Pawel G's avatar
Pawel G committed
596
      foreach ($query->execute()->fetchAll() as $result) {
597 598 599
        $delete = TRUE;
        $instance_settings = unserialize($result->inclusion_settings);
        foreach ($instance_settings as $setting_key => $instance_setting) {
600
          if ($instance_setting != $settings[$setting_key]) {
601 602 603 604 605
            $delete = FALSE;
            break;
          }
        }
        if ($delete) {
606
          $delete_instances[] = $result->id;
607
        }
608
      }
609 610 611 612 613
      if (!empty($delete_instances)) {
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('id', $delete_instances, 'IN')
          ->execute();
      }
614
    }
615 616 617
    else {
      //todo: log error
    }
Pawel G's avatar
Pawel G committed
618
    return $this;
619 620
  }

621
  /**
622 623
   * Gets sitemap settings for an entity bundle, a non-bundle entity type or for
   * all entity types and their bundles.
624
   *
625 626 627
   * @param string|null $entity_type_id
   *  If set to null, sitemap settings for all entity types and their bundles
   *  are fetched.
628 629 630
   * @param string|null $bundle_name
   *
   * @return array|false
Pawel G's avatar
Pawel G committed
631 632
   *  Array of sitemap settings for an entity bundle, a non-bundle entity type
   *  or for all entity types and their bundles.
633
   *  False if entity type does not exist.
634
   */
635
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
636
    if (NULL !== $entity_type_id) {
637 638

      // Get bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
639
      $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
640
      $bundle_settings = $this->configFactory
641 642
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->get();
643 644 645 646 647 648 649 650 651 652 653

      // If not found and entity type is enabled, return default bundle settings.
      if (empty($bundle_settings)) {
        if ($this->entityTypeIsEnabled($entity_type_id)
          && isset($this->entityTypeBundleInfo->getBundleInfo($entity_type_id)[$bundle_name])) {
          self::supplementDefaultSettings('entity', $bundle_settings, ['index' => 0]);
        }
        else {
          $bundle_settings = FALSE;
        }
      }
654
    }
655
    else {
656
      // Get all bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
Pawel G's avatar
Pawel G committed
657
      $config_names = $this->configFactory->listAll('simple_sitemap.bundle_settings.');
658
      $bundle_settings = [];
Pawel G's avatar
Pawel G committed
659
      foreach ($config_names as $config_name) {
660
        $config_name_parts = explode('.', $config_name);
661 662 663 664 665 666 667 668 669 670 671 672
        $bundle_settings[$config_name_parts[2]][$config_name_parts[3]] = $this->configFactory->get($config_name)->get();
      }

      // Supplement default bundle settings for all bundles not found in simple_sitemap.bundle_settings.*.* configuration.
      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], ['index' => 0]);
            }
          }
        }
673 674
      }
    }
675
    return $bundle_settings;
676 677 678
  }

  /**
679 680
   * Supplements all missing link setting with default values.
   *
681
   * @param string $type
Pawel G's avatar
Pawel G committed
682 683 684
   *  'entity'|'custom'
   * @param array &$settings
   * @param array $overrides
685
   */
Pawel G's avatar
Pawel G committed
686
  public static function supplementDefaultSettings($type, &$settings, $overrides = []) {
687
    foreach (self::$allowedLinkSettings[$type] as $allowed_link_setting) {
688
      if (!isset($settings[$allowed_link_setting])
Pawel G's avatar
Pawel G committed
689
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
690 691 692
        $settings[$allowed_link_setting] = isset($overrides[$allowed_link_setting])
          ? $overrides[$allowed_link_setting]
          : self::$linkSettingDefaults[$allowed_link_setting];
693 694
      }
    }
695 696
  }

Pawel G's avatar
Pawel G committed
697 698 699
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
700 701 702
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
703
   *
Pawel G's avatar
Pawel G committed
704 705
   * @return $this
   */
706
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
707
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
708 709 710
    $bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity)
    );
711
    if (!empty($bundle_settings)) {
712 713 714 715

      // Check if overrides are different from bundle setting before saving.
      $override = FALSE;
      foreach ($settings as $key => $setting) {
716
        if (!isset($bundle_settings[$key]) || $setting != $bundle_settings[$key]) {
717 718 719 720
          $override = TRUE;
          break;
        }
      }
Pawel G's avatar
Pawel G committed
721 722
      // Save overrides for this entity if something is different.
      if ($override) {
723 724 725 726 727 728 729
        $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,
730
            'inclusion_settings' => serialize(array_merge($bundle_settings, $settings)),])
731
          ->execute();
732
      }
Pawel G's avatar
Pawel G committed
733 734
      // Else unset override.
      else {
735
        $this->removeEntityInstanceSettings($entity_type_id, $id);
736
      }
737 738 739
    }
    else {
      //todo: log error
740
    }
Pawel G's avatar
Pawel G committed
741
    return $this;
742 743
  }

Pawel G's avatar
Pawel G committed
744
  /**
745
   * Gets sitemap settings for an entity instance which overrides the sitemap
746
   * settings of its bundle, or bundle settings, if they are not overridden.
Pawel G's avatar
Pawel G committed
747
   *
Pawel G's avatar
Pawel G committed
748
   * @param string $entity_type_id
749
   * @param int $id
Pawel G's avatar
Pawel G committed
750
   *
751
   * @return array|false
Pawel G's avatar
Pawel G committed
752
   */
753 754 755 756 757 758 759 760 761
  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)) {
762
      return unserialize($results);
763 764
    }
    else {
765 766 767 768 769 770
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
771 772 773
    }
  }

774 775 776 777 778 779 780 781 782 783 784 785
  /**
   * 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);
786
    if (NULL !== $entity_ids) {
787 788 789 790 791 792 793
      $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
794 795 796 797
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
798 799
   * @param string $entity_type_id
   * @param string|null $bundle_name
Pawel G's avatar
Pawel G committed
800
   *
Pawel G's avatar
Pawel G committed
801 802
   * @return bool
   */
803
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
804 805 806 807
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
808 809 810
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
811
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
812
   *
Pawel G's avatar
Pawel G committed
813 814
   * @return bool
   */
815
  public function entityTypeIsEnabled($entity_type_id) {
816
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
817 818
  }

Pawel G's avatar
Pawel G committed
819
  /**
820
   * Stores a custom path along with its sitemap settings to configuration.
Pawel G's avatar
Pawel G committed
821
   *
Pawel G's avatar
Pawel G committed
822 823
   * @param string $path
   * @param array $settings
Pawel G's avatar
Pawel G committed
824
   *
Pawel G's avatar
Pawel G committed
825
   * @return $this
826 827
   *
   * @todo Validate $settings and throw exceptions
Pawel G's avatar
Pawel G committed
828
   */
829
  public function addCustomLink($path, $settings = []) {
Pawel G's avatar
Pawel G committed
830 831 832 833
    if (!$this->pathValidator->isValid($path)) {
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
834
    if ($path[0] !== '/') {
Pawel G's avatar
Pawel G committed
835 836 837
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
838

839
    $custom_links = $this->getCustomLinks(FALSE);
Pawel G's avatar
Pawel G committed
840
    foreach ($custom_links as $key => $link) {
841
      if ($link['path'] === $path) {
842 843 844 845 846
        $link_key = $key;
        break;
      }
    }
    $link_key = isset($link_key) ? $link_key : count($custom_links);
847
    $custom_links[$link_key] = ['path' => $path] + $settings;
Pawel G's avatar
Pawel G committed
848
    $this->configFactory->getEditable('simple_sitemap.custom')
849
      ->set('links', $custom_links)->save();
Pawel G's avatar
Pawel G committed
850
    return $this;
851 852
  }

853 854 855
  /**
   * Returns an array of custom paths and their sitemap settings.
   *
856
   * @param bool $supplement_default_settings
857 858
   * @return array
   */
859
  public function getCustomLinks($supplement_default_settings = TRUE) {
860 861
    $custom_links = $this->configFactory
      ->get('simple_sitemap.custom')
862
      ->get('links');
863 864 865

    if ($supplement_default_settings) {
      foreach ($custom_links as $i => $link_settings) {
Pawel G's avatar
Pawel G committed
866 867
        self::supplementDefaultSettings('custom', $link_settings);
        $custom_links[$i] = $link_settings;
868 869 870
      }
    }

871
    return $custom_links !== NULL ? $custom_links : [];
872 873
  }

Pawel G's avatar
Pawel G committed
874 875 876
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
877
   * @param string $path
Pawel G's avatar
Pawel G committed
878
   *
Pawel G's avatar
Pawel G committed
879
   * @return array|false
Pawel G's avatar
Pawel G committed
880
   */
881
  public function getCustomLink($path) {
882
    foreach ($this->getCustomLinks() as $key => $link) {
883
      if ($link['path'] === $path) {
884
        return $link;
885 886 887 888 889
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
890 891 892
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
893
   * @param string $path
Pawel G's avatar
Pawel G committed
894
   *
Pawel G's avatar
Pawel G committed
895 896
   * @return $this
   */
897
  public function removeCustomLink($path) {
898
    $custom_links = $this->getCustomLinks(FALSE);
Pawel G's avatar
Pawel G committed
899
    foreach ($custom_links as $key => $link) {
900
      if ($link['path'] === $path) {
901 902
        unset($custom_links[$key]);
        $custom_links = array_values($custom_links);
Pawel G's avatar
Pawel G committed
903
        $this->configFactory->getEditable('simple_sitemap.custom')
904
          ->set('links', $custom_links)->save();
905
        break;
906 907
      }
    }
Pawel G's avatar
Pawel G committed
908
    return $this;
909 910
  }

Pawel G's avatar
Pawel G committed
911 912
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
913 914
   *
   * @return $this
Pawel G's avatar
Pawel G committed
915
   */
916
  public function removeCustomLinks() {
Pawel G's avatar
Pawel G committed
917
    $this->configFactory->getEditable('simple_sitemap.custom')
918
      ->set('links', [])->save();
Pawel G's avatar
Pawel G committed
919
    return $this;
920
  }
921
}