Simplesitemap.php 32.9 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
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\DefaultSitemapGenerator;
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase;
15
use Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorBase;
16
use Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorManager;
17
use Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorManager;
18

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

Pawel G's avatar
Pawel G committed
25
  const DEFAULT_SITEMAP_TYPE = 'default_hreflang';
Pawel G's avatar
Pawel G committed
26
  const DEFAULT_SITEMAP_GENERATOR = 'default';
Pawel G's avatar
Pawel G committed
27 28
  const DEFAULT_SITEMAP_VARIANT = 'default';

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

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

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

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

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

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

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

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

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

  /**
75
   * @var \Drupal\simple_sitemap\Batch
76
   */
77
  protected $batch;
78

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

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

Pawel G's avatar
Pawel G committed
89 90 91 92 93 94 95 96 97 98
  /**
   * @var UrlGeneratorBase[] $urlGenerators
   */
  protected $urlGenerators = [];

  /**
   * @var SitemapGeneratorBase[] $sitemapGenerators
   */
  protected $sitemapGenerators = [];

Pawel G's avatar
Pawel G committed
99 100 101
  /**
   * @var array
   */
Pawel G's avatar
Pawel G committed
102
  protected static $allowedLinkSettings = [
103
    'entity' => ['index', 'priority', 'changefreq', 'include_images'],
104 105 106
    'custom' => ['priority', 'changefreq'],
  ];

Pawel G's avatar
Pawel G committed
107 108 109 110
  /**
   * @var array
   */
  protected static $linkSettingDefaults = [
111
    'index' => FALSE,
112
    'priority' => 0.5,
113
    'changefreq' => '',
114
    'include_images' => FALSE,
115
  ];
116

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

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

Pawel G's avatar
Pawel G committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
  /**
   * @param $sitemap_generator_id
   * @return \Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapGeneratorBase
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  protected function getSitemapGenerator($sitemap_generator_id) {
    if (!isset($this->sitemapGenerators[$sitemap_generator_id])) {
      $this->sitemapGenerators[$sitemap_generator_id]
        = $this->sitemapGeneratorManager->createInstance($sitemap_generator_id);
    }

    return $this->sitemapGenerators[$sitemap_generator_id];
  }

  /**
   * @param $url_generator_id
   * @return \Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator\UrlGeneratorBase
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  protected function getUrlGenerator($url_generator_id) {
    if (!isset($this->urlGenerators[$url_generator_id])) {
      $this->urlGenerators[$url_generator_id]
        = $this->urlGeneratorManager->createInstance($url_generator_id);
    }

    return $this->urlGenerators[$url_generator_id];
  }

224 225 226 227
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
228
   * @param string $variant
229 230
   *
   * @param int $delta
231 232
   *
   * @return string|false
Pawel G's avatar
Pawel G committed
233
   *  If no sitemap ID provided, either a sitemap index is returned, or the
234 235
   *  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
236
   *  Returns false if the sitemap is not retrievable from the database.
237
   */
Pawel G's avatar
Pawel G committed
238 239
  public function getSitemap($variant = self::DEFAULT_SITEMAP_VARIANT, $delta = NULL) {
    $chunk_info = $this->fetchSitemapVariantInfo($variant);
240

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

243
      if (isset($chunk_info[SitemapGeneratorBase::INDEX_DELTA])) {
Pawel G's avatar
Pawel G committed
244
        // Return sitemap index if one exists.
245 246
        return $this->fetchSitemapChunk($chunk_info[SitemapGeneratorBase::INDEX_DELTA]->id)
          ->sitemap_string;
247 248
      }
      else {
Pawel G's avatar
Pawel G 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
    }
  }

  /**
Pawel G's avatar
Pawel G committed
263
   * Fetches info about all sitemap variants and their chunks.
264
   *
265
   * @param string|null $variant
266
   *
267
   * @return array
Pawel G's avatar
Pawel G committed
268 269
   *  An array containing all sitemap chunk IDs, deltas and creation timestamps
   * keyed by their variant ID.
270
   */
Pawel G's avatar
Pawel G committed
271
  protected function fetchSitemapVariantInfo($variant = NULL) {
272 273 274
    $query = $this->db->select('simple_sitemap', 's')
      ->fields('s', ['id', 'delta', 'sitemap_created', 'type']);

275 276
    if (NULL !== $variant) {
      $query->condition('s.type', $variant);
277 278 279 280
    }

    $result = $query->execute();

281
    return NULL === $variant ? $result->fetchAllAssoc('type') : $result->fetchAllAssoc('delta');
282 283
  }

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

298 299 300 301 302 303 304 305
  /**
   * @return array
   *
   * @todo document
   */
  public function getSitemapTypeDefinitions() {
    $type_definitions = [];
    foreach ($this->configFactory->listAll('simple_sitemap.types.') as $config_name) {
Pawel G's avatar
Pawel G committed
306 307
      $config_name_parts = explode('.', $config_name);
      $type_definitions[$config_name_parts[2]] = $this->configFactory->get($config_name)->get();
308 309 310 311 312 313 314 315
    }

    return $type_definitions;
  }

  /**
   * @param $name
   * @param $definition
Pawel G's avatar
Pawel G committed
316
   * @return $this
317 318 319 320 321
   *
   * @todo document
   */
  public function setSitemapTypeDefinition($name, $definition) {
    $type = $this->configFactory->getEditable("simple_sitemap.types.$name");
Pawel G's avatar
Pawel G committed
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338

    if (empty($type->get('label')) && empty($definition['label'])) {
      $definition['label'] = $name;
    }

    if (empty($type->get('description')) && empty($definition['description'])) {
      $definition['description'] = '';
    }

    if (empty($type->get('sitemap_generator')) && empty($definition['sitemap_generator'])) {
      $definition['sitemap_generator'] = self::DEFAULT_SITEMAP_GENERATOR;
    }

    if (empty($type->get('url_generators')) && empty($definition['url_generators'])) {
      //todo exception
    }

339 340 341 342 343
    foreach ($definition as $key => $value) {
      if (in_array($key, ['label', 'description', 'sitemap_generator', 'url_generators'])) {
        $type->set($key, $value);
      }
      else {
Pawel G's avatar
Pawel G committed
344
        //todo: exception
345 346 347
      }
    }
    $type->save();
Pawel G's avatar
Pawel G committed
348 349

    return $this;
350 351 352
  }

  /**
353
   * @param $type_name
Pawel G's avatar
Pawel G committed
354
   * @return $this
355 356 357
   *
   * @todo document
   */
358 359
  public function removeSitemapTypeDefinition($type_name) {
    if ($type_name !== self::DEFAULT_SITEMAP_TYPE) {
360

Pawel G's avatar
Pawel G committed
361 362
      // Remove type definition and variants from configuration.
      $this->configFactory->getEditable("simple_sitemap.variants.$type_name")->delete();
363
      $this->configFactory->getEditable("simple_sitemap.types.$type_name")->delete();
364 365 366 367
    }
    else {
      //todo: exception
    }
Pawel G's avatar
Pawel G committed
368 369

    return $this;
370 371 372
  }

  /**
Pawel G's avatar
Pawel G committed
373
   * @param null $sitemap_type
374 375 376 377 378
   * @return array
   *
   * @todo document
   * @todo translate label
   */
Pawel G's avatar
Pawel G committed
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  public function getSitemapVariants($sitemap_type = NULL, $attach_type_info = TRUE) {
    if (NULL === $sitemap_type) {
      $variants = [];
      foreach ($this->configFactory->listAll('simple_sitemap.variants.') as $config_name) {
        $config_name_parts = explode('.', $config_name);
        $saved_variants = $this->configFactory->get($config_name)->get('variants');
        $saved_variants = $attach_type_info ? $this->attachSitemapTypeToVariants($saved_variants, $config_name_parts[2]) : $saved_variants;
        $variants = array_merge($variants, (is_array($saved_variants) ? $saved_variants : []));
      }
      return $variants;
    }
    else {
      $variants = $this->configFactory->get("simple_sitemap.variants.$sitemap_type")->get('variants');
      $variants = is_array($variants) ? $variants : [];
      return $attach_type_info ? $this->attachSitemapTypeToVariants($variants, $sitemap_type) : $variants;
    }
  }

  protected function attachSitemapTypeToVariants(array $variants, $type) {
    return array_map(function($variant) use ($type) { return $variant + ['type' => $type]; }, $variants);
  }

  protected function detachSitemapTypeFromVariants(array $variants) {
    return array_map(function($variant) { unset($variant['type']); return $variant; }, $variants);
403 404 405 406 407 408 409 410 411 412
  }

  /**
   * @param $name
   * @param $definition
   * @return $this
   *
   * @todo document
   * @todo exceptions
   */
413
  public function addSitemapVariant($name, $definition = []) {
414
    if (empty($definition['label'])) {
Pawel G's avatar
Pawel G committed
415
      $definition['label'] = $name;
416 417 418
    }

    if (empty($definition['type'])) {
Pawel G's avatar
Pawel G committed
419
      $definition['type'] = self::DEFAULT_SITEMAP_TYPE;
420
    }
421 422 423 424 425 426
    else {
      $types = $this->getSitemapTypeDefinitions();
      if (!isset($types[$definition['type']])) {
        // todo: exception
      }
    }
Pawel G's avatar
Pawel G committed
427 428 429 430 431 432 433 434 435 436
    $all_variants = $this->getSitemapVariants();
    if (isset($all_variants[$name])) {
      //todo: exception
    }
    else {
      $variants = array_merge($this->getSitemapVariants($definition['type'], FALSE), [$name => ['label' => $definition['label']]]);
      $this->configFactory->getEditable('simple_sitemap.variants.' . $definition['type'])
        ->set('variants', $variants)
        ->save();
    }
437 438 439 440 441 442 443 444 445 446

    return $this;
  }

  /**
   * @param $name
   * @return $this
   *
   * @todo document
   */
Pawel G's avatar
Pawel G committed
447 448 449 450 451 452 453 454 455 456
  public function removeSitemapVariant($variant_name) {
    $this->removeSitemap($variant_name);
    $variants = $this->getSitemapVariants();
    foreach($variants as $saved_variant_name => $variant_definition) {
      if ($variant_name === $saved_variant_name) {
        unset($variants[$variant_name]);
        $this->configFactory->getEditable('simple_sitemap.variants.' . $variant_definition['type'])
          ->set('variants', $this->detachSitemapTypeFromVariants($variants))
          ->save();
        break;
457 458
      }
    }
459

460 461 462
    return $this;
  }

463 464 465
  /**
   * @param null $variants
   * @return $this
466
   * @throws \Drupal\Component\Plugin\Exception\PluginException
467
   *
468
   * @todo document
469 470
   */
  public function removeSitemap($variants = NULL) {
Pawel G's avatar
Pawel G committed
471 472 473 474 475 476
    $saved_variants = $this->getSitemapVariants();
    $this->moduleHandler->alter('simple_sitemap_variants', $saved_variants);
    $remove_variants = NULL !== $variants
      ? array_intersect_key($saved_variants, array_flip((array) $variants))
      : $saved_variants;

477 478
    if (!empty($remove_variants)) {
      $type_definitions = $this->getSitemapTypeDefinitions();
Pawel G's avatar
Pawel G committed
479
      $this->moduleHandler->alter('simple_sitemap_types', $type_definitions);
480
      foreach ($remove_variants as $variant_name => $variant_definition) {
Pawel G's avatar
Pawel G committed
481
        $this->getSitemapGenerator($type_definitions[$variant_definition['type']]['sitemap_generator'])
482
          ->setSitemapVariant($variant_name)
483 484
          ->remove()
          ->invalidateCache();
485 486
      }
    }
Pawel G's avatar
Pawel G committed
487

488 489 490
    return $this;
  }

491
  /**
Pawel G's avatar
Pawel G committed
492
   * Generates the XML sitemap and saves it to the database.
493 494
   *
   * @param string $from
Pawel G's avatar
Pawel G committed
495 496
   *  Can be 'form', 'backend', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
Pawel G's avatar
Pawel G committed
497
   *
498
   * @param array|string|null $variants
499
   *
Pawel G's avatar
Pawel G committed
500
   * @return bool|\Drupal\simple_sitemap\Simplesitemap
501
   */
502 503
  public function generateSitemap($from = 'form', $variants = NULL) {
    $variants = NULL === $variants ? NULL : (array) $variants;
504

505
    $settings = [
506
      'base_url' => $this->getSetting('base_url', ''),
507
      'batch_process_limit' => $this->getSetting('batch_process_limit', 1500),
508 509 510 511
      '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', []),
512
    ];
513

514 515
    $this->batch->setBatchMeta(['from' => $from]);

516
    $operations = [];
Pawel G's avatar
Pawel G committed
517

518 519
    $type_definitions = $this->getSitemapTypeDefinitions();
    $this->moduleHandler->alter('simple_sitemap_types', $type_definitions);
Pawel G's avatar
Pawel G committed
520

521 522
    $sitemap_variants = $this->getSitemapVariants();
    $this->moduleHandler->alter('simple_sitemap_variants', $sitemap_variants);
523

524 525 526 527 528 529
    foreach ($sitemap_variants as $variant_name => $variant_definition) {

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

531 532 533 534 535 536 537 538 539 540 541 542 543
      $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) {
544

Pawel G's avatar
Pawel G committed
545
        foreach ($this->getUrlGenerator($url_generator_id)
546 547 548 549 550
                   ->setSitemapVariant($variant_name)
                   ->getDataSets() as $data_set) {
          if (!empty($data_set)) {
            $operations[] = [
              'operation' => 'generateSitemap',
551
              'arguments' => [
552 553 554 555 556 557
                'url_generator' => $url_generator_id,
                'data_set' => $data_set,
                'variant' => $variant_name,
                'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
                'settings' => $settings,
              ],
558 559
            ];
          }
560
        }
561
      }
562

563 564
      // Adding generate_index operations for all sitemap variants.
      $operations[] = [
565 566
        'operation' => 'generateIndex',
        'arguments' => [
567 568
          'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
          'variant' => $variant_name,
569 570 571 572 573
          'settings' => $settings,
        ],
      ];
    }

574 575 576 577
    // Adding operations to and starting batch.
    if (!empty($operations)) {
      foreach ($operations as $operation_data) {
        $this->batch->addOperation($operation_data['operation'], $operation_data['arguments']);
578 579 580 581 582
      }
      $success = $this->batch->start();
    }

    return $from === 'nobatch' ? $this : (isset($success) ? $success : FALSE);
583 584 585 586 587
  }

  /**
   * Returns a 'time ago' string of last timestamp generation.
   *
588
   * @param string|null $variant
589 590
   *
   * @return string|array|false
Pawel G's avatar
Pawel G committed
591
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
592
   */
593
  public function getGeneratedAgo($variant = NULL) {
Pawel G's avatar
Pawel G committed
594
    $chunks = $this->fetchSitemapVariantInfo($variant);
595
    if ($variant !== NULL) {
596
      return isset($chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]->sitemap_created)
597
        ? $this->dateFormatter
598
          ->formatInterval($this->time->getRequestTime() - $chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]
599 600 601 602 603 604 605 606 607 608 609 610
              ->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;
611 612 613
    }
  }

614 615
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
616 617
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
618 619 620
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
621
   *  Entity type id like 'node'.
622
   *
Pawel G's avatar
Pawel G committed
623
   * @return $this
624 625
   */
  public function enableEntityType($entity_type_id) {
626 627 628 629
    $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);
630
    }
Pawel G's avatar
Pawel G committed
631
    return $this;
632 633 634 635 636 637 638 639
  }

  /**
   * 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
640
   *  Entity type id like 'node'.
641
   *
Pawel G's avatar
Pawel G committed
642
   * @return $this
643 644
   */
  public function disableEntityType($entity_type_id) {
645 646 647

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
648
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
649
      unset ($enabled_entity_types[$key]);
650
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
651 652 653
    }

    // Deleting inclusion settings.
654
    $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$entity_type_id.");
Pawel G's avatar
Pawel G committed
655
    foreach ($config_names as $config_name) {
656
      $this->configFactory->getEditable($config_name)->delete();
657
    }
658 659 660

    // Deleting entity overrides.
    $this->removeEntityInstanceSettings($entity_type_id);
Pawel G's avatar
Pawel G committed
661
    return $this;
662 663 664
  }

  /**
Pawel G's avatar
Pawel G committed
665
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
666 667 668
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
669
   *  Entity type id like 'node' the bundle belongs to.
670
   * @param string $bundle_name
Pawel G's avatar
Pawel G committed
671
   *  Name of the bundle. NULL if entity type has no bundles.
672
   * @param array $settings
Pawel G's avatar
Pawel G committed
673 674
   *  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
675 676
   *
   * @return $this
677 678
   *
   * @todo: enableEntityType automatically
679
   */
680
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings = ['index' => TRUE]) {
681
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
682

Pawel G's avatar
Pawel G committed
683 684 685
    if (!empty($old_settings = $this->getBundleSettings($entity_type_id, $bundle_name))) {
      $settings = array_merge($old_settings, $settings);
    }
686
    self::supplementDefaultSettings('entity', $settings);
687

688
    if ($settings != $old_settings) {
689

690 691 692 693 694 695 696
      // Save new bundle settings to configuration.
      $bundle_settings = $this->configFactory
        ->getEditable("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name");
      foreach ($settings as $setting_key => $setting) {
        $bundle_settings->set($setting_key, $setting);
      }
      $bundle_settings->save();
697

698 699 700 701 702
      // Delete entity overrides which are identical to new bundle settings.
      $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
      if (isset($sitemap_entity_types[$entity_type_id])) {
        $entity_type = $sitemap_entity_types[$entity_type_id];
        $keys = $entity_type->getKeys();
703

704 705
        // Menu fix.
        $keys['bundle'] = $entity_type_id === 'menu_link_content' ? 'menu_name' : $keys['bundle'];
706

707 708 709 710 711 712 713 714 715 716 717 718
        $query = $this->entityTypeManager->getStorage($entity_type_id)->getQuery();
        if (!$this->entityHelper->entityTypeIsAtomic($entity_type_id)) {
          $query->condition($keys['bundle'], $bundle_name);
        }
        $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');
        }
719

720 721 722 723 724 725 726 727 728 729 730 731
        $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;
            }
          }
          if ($delete) {
            $delete_instances[] = $result->id;
732 733
          }
        }
734 735 736 737
        if (!empty($delete_instances)) {
          $this->db->delete('simple_sitemap_entity_overrides')
            ->condition('id', $delete_instances, 'IN')
            ->execute();
738
        }
739
      }
740 741
      else {
        //todo: log error
742
      }
743
    }
744

Pawel G's avatar
Pawel G committed
745
    return $this;
746 747
  }

748
  /**
749 750
   * Gets sitemap settings for an entity bundle, a non-bundle entity type or for
   * all entity types and their bundles.
751
   *
752 753 754
   * @param string|null $entity_type_id
   *  If set to null, sitemap settings for all entity types and their bundles
   *  are fetched.
755 756 757
   * @param string|null $bundle_name
   *
   * @return array|false
Pawel G's avatar
Pawel G committed
758 759
   *  Array of sitemap settings for an entity bundle, a non-bundle entity type
   *  or for all entity types and their bundles.
760
   *  False if entity type does not exist.
761
   */
762
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
763
    if (NULL !== $entity_type_id) {
764 765

      // Get bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
766
      $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
767
      $bundle_settings = $this->configFactory
768 769
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->get();
770 771 772 773 774

      // 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])) {
775
          self::supplementDefaultSettings('entity', $bundle_settings);
776 777 778 779 780
        }
        else {
          $bundle_settings = FALSE;
        }
      }
781
    }
782
    else {
783
      // Get all bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
Pawel G's avatar
Pawel G committed
784
      $config_names = $this->configFactory->listAll('simple_sitemap.bundle_settings.');
785
      $bundle_settings = [];
Pawel G's avatar
Pawel G committed
786
      foreach ($config_names as $config_name) {
787
        $config_name_parts = explode('.', $config_name);
788 789 790 791 792 793 794 795
        $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])) {
796
              self::supplementDefaultSettings('entity', $bundle_settings[$type_id][$bundle]);
797 798 799
            }
          }
        }
800 801
      }
    }
802
    return $bundle_settings;
803 804 805
  }

  /**
806 807
   * Supplements all missing link setting with default values.
   *
808
   * @param string $type
Pawel G's avatar
Pawel G committed
809 810 811
   *  'entity'|'custom'
   * @param array &$settings
   * @param array $overrides
812
   */
Pawel G's avatar
Pawel G committed
813
  public static function supplementDefaultSettings($type, &$settings, $overrides = []) {
814
    foreach (self::$allowedLinkSettings[$type] as $allowed_link_setting) {
815
      if (!isset($settings[$allowed_link_setting])
Pawel G's avatar
Pawel G committed
816
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
817 818 819
        $settings[$allowed_link_setting] = isset($overrides[$allowed_link_setting])
          ? $overrides[$allowed_link_setting]
          : self::$linkSettingDefaults[$allowed_link_setting];
820 821
      }
    }
822 823
  }

Pawel G's avatar
Pawel G committed
824 825 826
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
827 828 829
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
830
   *
Pawel G's avatar
Pawel G committed
831 832
   * @return $this
   */
833
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
834
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
835 836 837
    $bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity)
    );
838
    if (!empty($bundle_settings)) {
839 840 841 842

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

Pawel G's avatar
Pawel G committed
849 850
      // Save overrides for this entity if something is different.
      if ($override) {
851 852 853 854 855 856 857
        $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,
858
            'inclusion_settings' => serialize(array_merge($bundle_settings, $settings)),])
859
          ->execute();
860
      }
Pawel G's avatar
Pawel G committed
861 862
      // Else unset override.
      else {
863
        $this->removeEntityInstanceSettings($entity_type_id, $id);
864
      }
865 866 867
    }
    else {
      //todo: log error
868
    }
Pawel G's avatar
Pawel G committed
869
    return $this;
870 871
  }

Pawel G's avatar
Pawel G committed
872
  /**
873
   * Gets sitemap settings for an entity instance which overrides the sitemap
874
   * settings of its bundle, or bundle settings, if they are not overridden.
Pawel G's avatar
Pawel G committed
875
   *
Pawel G's avatar
Pawel G committed
876
   * @param string $entity_type_id
877
   * @param int $id
Pawel G's avatar
Pawel G committed
878
   *
879
   * @return array|false
Pawel G's avatar
Pawel G committed
880
   */
881 882 883 884 885 886 887 888 889
  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)) {
890
      return unserialize($results);
891 892
    }
    else {
893 894 895 896 897 898
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
899 900 901
    }
  }

902 903 904 905 906 907 908 909 910 911 912 913
  /**
   * 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);
914
    if (NULL !== $entity_ids) {
915 916 917 918 919 920 921
      $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
922 923 924 925
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
926 927
   * @param string $entity_type_id
   * @param string|null $bundle_name
Pawel G's avatar
Pawel G committed
928
   *
Pawel G's avatar
Pawel G committed
929 930
   * @return bool
   */
931
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
932 933 934 935
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
936 937 938
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
939
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
940
   *
Pawel G's avatar
Pawel G committed
941 942
   * @return bool
   */
943
  public function entityTypeIsEnabled($entity_type_id) {
944
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
945 946
  }

Pawel G's avatar
Pawel G committed
947
  /**
948
   * Stores a custom path along with its sitemap settings to configuration.
Pawel G's avatar
Pawel G committed
949
   *