Simplesitemap.php 30.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 26 27
  const DEFAULT_SITEMAP_TYPE = 'default_hreflang';
  const DEFAULT_SITEMAP_VARIANT = 'default';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    $result = $query->execute();

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

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

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  /**
   * @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
Pawel G's avatar
Pawel G committed
276
   * @return $this
277 278 279 280 281 282 283 284 285 286 287 288 289 290
   *
   * @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();
Pawel G's avatar
Pawel G committed
291 292

    return $this;
293 294 295
  }

  /**
296
   * @param $type_name
Pawel G's avatar
Pawel G committed
297
   * @return $this
298 299 300
   *
   * @todo document
   */
301 302
  public function removeSitemapTypeDefinition($type_name) {
    if ($type_name !== self::DEFAULT_SITEMAP_TYPE) {
303 304 305 306

      // Remove variants tied to this definition.
      $variants = $this->getSitemapVariants();
      foreach ($variants as $variant_name => $variant_definition) {
307 308
        if ($variant_definition['type'] === $type_name) {
          $remove_variants[] = $variant_name;
309 310
        }
      }
311 312 313
      if (!empty($remove_variants)) {
        $this->removeSitemapVariants($remove_variants);
      }
314 315

      // Remove type definition from configuration.
316
      $this->configFactory->getEditable("simple_sitemap.types.$type_name")->delete();
317 318 319 320
    }
    else {
      //todo: exception
    }
Pawel G's avatar
Pawel G committed
321 322

    return $this;
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  }

  /**
   * @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
   */
343
  public function addSitemapVariant($name, $definition = []) {
344
    if (empty($definition['label'])) {
Pawel G's avatar
Pawel G committed
345
      $definition['label'] = $name;
346 347 348
    }

    if (empty($definition['type'])) {
Pawel G's avatar
Pawel G committed
349
      $definition['type'] = self::DEFAULT_SITEMAP_TYPE;
350
    }
351 352 353 354 355 356 357
    else {
      $types = $this->getSitemapTypeDefinitions();
      if (!isset($types[$definition['type']])) {
        // todo: exception
        return $this;
      }
    }
358 359 360

    $variants = array_merge($this->getSitemapVariants(), [$name => ['label' => $definition['label'], 'type' => $definition['type']]]);
    $this->configFactory->getEditable('simple_sitemap.variants')
361 362
      ->set('variants', $variants)
      ->save();
363 364 365 366 367 368 369 370 371 372

    return $this;
  }

  /**
   * @param $name
   * @return $this
   *
   * @todo document
   */
373 374 375 376 377 378 379 380
  public function removeSitemapVariants($variant_names = NULL) {
    if (NULL === $variant_names) {
      $this->removeSitemap();
      $variants = [];
      $save = TRUE;
    }
    else {
      $this->removeSitemap($variant_names);
381

382 383 384 385 386 387 388 389 390 391
      $variants = $this->getSitemapVariants();
      foreach ((array) $variant_names as $variant_name) {
        foreach ($variants as $variant => $variant_definition) {
          if (isset($variants[$variant_name])) {
            unset($variants[$variant_name]);
            $save = TRUE;
          }
        }
      }
    }
392

393
    if (!empty($save)) {
Pawel G's avatar
Pawel G committed
394 395 396
      $this->configFactory->getEditable('simple_sitemap.variants')
        ->set('variants', $variants)->save();
    }
397 398 399 400

    return $this;
  }

401 402 403
  /**
   * @param null $variants
   * @return $this
404
   * @throws \Drupal\Component\Plugin\Exception\PluginException
405
   *
406
   * @todo document
407 408 409
   */
  public function removeSitemap($variants = NULL) {
    $variant_definitions = $this->getSitemapVariants();
410
    // $this->moduleHandler->alter('simple_sitemap_variants', $variant_definitions); //todo Is this necessary?
411 412 413 414 415 416 417 418 419 420 421 422 423
    $remove_variants = [];
    if (NULL === $variants) {
      $remove_variants = $variant_definitions;
    }
    else {
      foreach ((array) $variants as $variant) {
        if (isset($variant_definitions[$variant])) {
          $remove_variants[$variant] = $variant_definitions[$variant];
        }
      }
    }
    if (!empty($remove_variants)) {
      $type_definitions = $this->getSitemapTypeDefinitions();
424 425 426 427

      /** @var SitemapGeneratorBase[] $sitemap_generators */
      $sitemap_generators = [];

428
      foreach ($remove_variants as $variant_name => $variant_definition) {
429 430 431 432 433 434
        $sitemap_generator_id = $type_definitions[$variant_definition['type']]['sitemap_generator'];
        if (!isset($sitemap_generators[$sitemap_generator_id])) {
          $sitemap_generators[$sitemap_generator_id] = $this->sitemapGeneratorManager
            ->createInstance($sitemap_generator_id);
        }
        $sitemap_generators[$sitemap_generator_id]
435
          ->setSitemapVariant($variant_name)
436 437
          ->remove()
          ->invalidateCache();
438
      }
439

440 441 442 443
    }
    return $this;
  }

444
  /**
Pawel G's avatar
Pawel G committed
445
   * Generates the XML sitemap and saves it to the database.
446 447
   *
   * @param string $from
Pawel G's avatar
Pawel G committed
448 449
   *  Can be 'form', 'backend', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
Pawel G's avatar
Pawel G committed
450
   *
451
   * @param array|string|null $variants
452
   *
Pawel G's avatar
Pawel G committed
453
   * @return bool|\Drupal\simple_sitemap\Simplesitemap
454
   */
455 456
  public function generateSitemap($from = 'form', $variants = NULL) {
    $variants = NULL === $variants ? NULL : (array) $variants;
457

458
    $settings = [
459
      'base_url' => $this->getSetting('base_url', ''),
460
      'batch_process_limit' => $this->getSetting('batch_process_limit', 1500),
461 462 463 464
      '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', []),
465
    ];
466

467 468
    $this->batch->setBatchMeta(['from' => $from]);

469
    $operations = [];
Pawel G's avatar
Pawel G committed
470

471 472
    $type_definitions = $this->getSitemapTypeDefinitions();
    $this->moduleHandler->alter('simple_sitemap_types', $type_definitions);
Pawel G's avatar
Pawel G committed
473

474 475
    $sitemap_variants = $this->getSitemapVariants();
    $this->moduleHandler->alter('simple_sitemap_variants', $sitemap_variants);
476

477 478 479
    /** @var UrlGeneratorBase[] $url_generators */
    $url_generators = [];

480 481 482 483 484 485
    foreach ($sitemap_variants as $variant_name => $variant_definition) {

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

487 488 489 490 491 492 493 494 495 496 497 498 499
      $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) {
500 501 502 503 504 505 506

        if (!isset($url_generators[$url_generator_id])) {
          $url_generators[$url_generator_id] = $this->urlGeneratorManager
            ->createInstance($url_generator_id);
        }

        foreach ($url_generators[$url_generator_id]
507 508 509 510 511
                   ->setSitemapVariant($variant_name)
                   ->getDataSets() as $data_set) {
          if (!empty($data_set)) {
            $operations[] = [
              'operation' => 'generateSitemap',
512
              'arguments' => [
513 514 515 516 517 518
                'url_generator' => $url_generator_id,
                'data_set' => $data_set,
                'variant' => $variant_name,
                'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
                'settings' => $settings,
              ],
519 520
            ];
          }
521
        }
522
      }
523

524 525
      // Adding generate_index operations for all sitemap variants.
      $operations[] = [
526 527
        'operation' => 'generateIndex',
        'arguments' => [
528 529
          'sitemap_generator' => $type_definitions[$type]['sitemap_generator'],
          'variant' => $variant_name,
530 531 532 533 534
          'settings' => $settings,
        ],
      ];
    }

535 536 537 538
    // Adding operations to and starting batch.
    if (!empty($operations)) {
      foreach ($operations as $operation_data) {
        $this->batch->addOperation($operation_data['operation'], $operation_data['arguments']);
539 540 541 542 543
      }
      $success = $this->batch->start();
    }

    return $from === 'nobatch' ? $this : (isset($success) ? $success : FALSE);
544 545 546 547 548
  }

  /**
   * Returns a 'time ago' string of last timestamp generation.
   *
549
   * @param string|null $variant
550 551
   *
   * @return string|array|false
Pawel G's avatar
Pawel G committed
552
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
553
   */
554
  public function getGeneratedAgo($variant = NULL) {
Pawel G's avatar
Pawel G committed
555
    $chunks = $this->fetchSitemapVariantInfo($variant);
556
    if ($variant !== NULL) {
557
      return isset($chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]->sitemap_created)
558
        ? $this->dateFormatter
559
          ->formatInterval($this->time->getRequestTime() - $chunks[DefaultSitemapGenerator::FIRST_CHUNK_DELTA]
560 561 562 563 564 565 566 567 568 569 570 571
              ->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;
572 573 574
    }
  }

575 576
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
577 578
   * sitemap settings on their bundle setting forms. If an enabled entity type
   * features bundles (e.g. 'node'), it needs to be set up with
579 580 581
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
582
   *  Entity type id like 'node'.
583
   *
Pawel G's avatar
Pawel G committed
584
   * @return $this
585 586
   */
  public function enableEntityType($entity_type_id) {
587 588 589 590
    $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);
591
    }
Pawel G's avatar
Pawel G committed
592
    return $this;
593 594 595 596 597 598 599 600
  }

  /**
   * 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
601
   *  Entity type id like 'node'.
602
   *
Pawel G's avatar
Pawel G committed
603
   * @return $this
604 605
   */
  public function disableEntityType($entity_type_id) {
606 607 608

    // Updating settings.
    $enabled_entity_types = $this->getSetting('enabled_entity_types');
609
    if (FALSE !== ($key = array_search($entity_type_id, $enabled_entity_types))) {
610
      unset ($enabled_entity_types[$key]);
611
      $this->saveSetting('enabled_entity_types', array_values($enabled_entity_types));
612 613 614
    }

    // Deleting inclusion settings.
615
    $config_names = $this->configFactory->listAll("simple_sitemap.bundle_settings.$entity_type_id.");
Pawel G's avatar
Pawel G committed
616
    foreach ($config_names as $config_name) {
617
      $this->configFactory->getEditable($config_name)->delete();
618
    }
619 620 621

    // Deleting entity overrides.
    $this->removeEntityInstanceSettings($entity_type_id);
Pawel G's avatar
Pawel G committed
622
    return $this;
623 624 625
  }

  /**
Pawel G's avatar
Pawel G committed
626
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
627 628 629
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
630
   *  Entity type id like 'node' the bundle belongs to.
631
   * @param string $bundle_name
Pawel G's avatar
Pawel G committed
632
   *  Name of the bundle. NULL if entity type has no bundles.
633
   * @param array $settings
Pawel G's avatar
Pawel G committed
634 635
   *  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
636 637
   *
   * @return $this
638 639
   *
   * @todo: enableEntityType automatically
640
   */
641
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings = ['index' => TRUE]) {
642
    $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
643

Pawel G's avatar
Pawel G committed
644 645 646
    if (!empty($old_settings = $this->getBundleSettings($entity_type_id, $bundle_name))) {
      $settings = array_merge($old_settings, $settings);
    }
647
    self::supplementDefaultSettings('entity', $settings);
648

649
    if ($settings != $old_settings) {
650

651 652 653 654 655 656 657
      // 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();
658

659 660 661 662 663
      // 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();
664

665 666
        // Menu fix.
        $keys['bundle'] = $entity_type_id === 'menu_link_content' ? 'menu_name' : $keys['bundle'];
667

668 669 670 671 672 673 674 675 676 677 678 679
        $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');
        }
680

681 682 683 684 685 686 687 688 689 690 691 692
        $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;
693 694
          }
        }
695 696 697 698
        if (!empty($delete_instances)) {
          $this->db->delete('simple_sitemap_entity_overrides')
            ->condition('id', $delete_instances, 'IN')
            ->execute();
699
        }
700
      }
701 702
      else {
        //todo: log error
703
      }
704
    }
705

Pawel G's avatar
Pawel G committed
706
    return $this;
707 708
  }

709
  /**
710 711
   * Gets sitemap settings for an entity bundle, a non-bundle entity type or for
   * all entity types and their bundles.
712
   *
713 714 715
   * @param string|null $entity_type_id
   *  If set to null, sitemap settings for all entity types and their bundles
   *  are fetched.
716 717 718
   * @param string|null $bundle_name
   *
   * @return array|false
Pawel G's avatar
Pawel G committed
719 720
   *  Array of sitemap settings for an entity bundle, a non-bundle entity type
   *  or for all entity types and their bundles.
721
   *  False if entity type does not exist.
722
   */
723
  public function getBundleSettings($entity_type_id = NULL, $bundle_name = NULL) {
724
    if (NULL !== $entity_type_id) {
725 726

      // Get bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
727
      $bundle_name = NULL !== $bundle_name ? $bundle_name : $entity_type_id;
728
      $bundle_settings = $this->configFactory
729 730
        ->get("simple_sitemap.bundle_settings.$entity_type_id.$bundle_name")
        ->get();
731 732 733 734 735

      // 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])) {
736
          self::supplementDefaultSettings('entity', $bundle_settings);
737 738 739 740 741
        }
        else {
          $bundle_settings = FALSE;
        }
      }
742
    }
743
    else {
744
      // Get all bundle settings saved in simple_sitemap.bundle_settings.*.* configuration.
Pawel G's avatar
Pawel G committed
745
      $config_names = $this->configFactory->listAll('simple_sitemap.bundle_settings.');
746
      $bundle_settings = [];
Pawel G's avatar
Pawel G committed
747
      foreach ($config_names as $config_name) {
748
        $config_name_parts = explode('.', $config_name);
749 750 751 752 753 754 755 756
        $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])) {
757
              self::supplementDefaultSettings('entity', $bundle_settings[$type_id][$bundle]);
758 759 760
            }
          }
        }
761 762
      }
    }
763
    return $bundle_settings;
764 765 766
  }

  /**
767 768
   * Supplements all missing link setting with default values.
   *
769
   * @param string $type
Pawel G's avatar
Pawel G committed
770 771 772
   *  'entity'|'custom'
   * @param array &$settings
   * @param array $overrides
773
   */
Pawel G's avatar
Pawel G committed
774
  public static function supplementDefaultSettings($type, &$settings, $overrides = []) {
775
    foreach (self::$allowedLinkSettings[$type] as $allowed_link_setting) {
776
      if (!isset($settings[$allowed_link_setting])
Pawel G's avatar
Pawel G committed
777
        && isset(self::$linkSettingDefaults[$allowed_link_setting])) {
778 779 780
        $settings[$allowed_link_setting] = isset($overrides[$allowed_link_setting])
          ? $overrides[$allowed_link_setting]
          : self::$linkSettingDefaults[$allowed_link_setting];
781 782
      }
    }
783 784
  }

Pawel G's avatar
Pawel G committed
785 786 787
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
788 789 790
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
791
   *
Pawel G's avatar
Pawel G committed
792 793
   * @return $this
   */
794
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
795
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
796 797 798
    $bundle_settings = $this->getBundleSettings(
      $entity_type_id, $this->entityHelper->getEntityInstanceBundleName($entity)
    );
799
    if (!empty($bundle_settings)) {
800 801 802 803

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

Pawel G's avatar
Pawel G committed
810 811
      // Save overrides for this entity if something is different.
      if ($override) {
812 813 814 815 816 817 818
        $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,
819
            'inclusion_settings' => serialize(array_merge($bundle_settings, $settings)),])
820
          ->execute();
821
      }
Pawel G's avatar
Pawel G committed
822 823
      // Else unset override.
      else {
824
        $this->removeEntityInstanceSettings($entity_type_id, $id);
825
      }
826 827 828
    }
    else {
      //todo: log error
829
    }
Pawel G's avatar
Pawel G committed
830
    return $this;
831 832
  }

Pawel G's avatar
Pawel G committed
833
  /**
834
   * Gets sitemap settings for an entity instance which overrides the sitemap
835
   * settings of its bundle, or bundle settings, if they are not overridden.
Pawel G's avatar
Pawel G committed
836
   *
Pawel G's avatar
Pawel G committed
837
   * @param string $entity_type_id
838
   * @param int $id
Pawel G's avatar
Pawel G committed
839
   *
840
   * @return array|false
Pawel G's avatar
Pawel G committed
841
   */
842 843 844 845 846 847 848 849 850
  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)) {
851
      return unserialize($results);
852 853
    }
    else {
854 855 856 857 858 859
      $entity = $this->entityTypeManager->getStorage($entity_type_id)
        ->load($id);
      return $this->getBundleSettings(
        $entity_type_id,
        $this->entityHelper->getEntityInstanceBundleName($entity)
      );
860 861 862
    }
  }

863 864 865 866 867 868 869 870 871 872 873 874
  /**
   * 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);
875
    if (NULL !== $entity_ids) {
876 877 878 879 880 881 882
      $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
883 884 885 886
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
887 888
   * @param string $entity_type_id
   * @param string|null $bundle_name
Pawel G's avatar
Pawel G committed
889
   *
Pawel G's avatar
Pawel G committed
890 891
   * @return bool
   */
892
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
893 894 895 896
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
897 898 899
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
900
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
901
   *
Pawel G's avatar
Pawel G committed
902 903
   * @return bool
   */
904
  public function entityTypeIsEnabled($entity_type_id) {
905
    return in_array($entity_type_id, $this->getSetting('enabled_entity_types', []));
906 907
  }

Pawel G's avatar
Pawel G committed
908
  /**
909
   * Stores a custom path along with its sitemap settings to configuration.
Pawel G's avatar
Pawel G committed
910
   *
Pawel G's avatar
Pawel G committed
911 912
   * @param string $path
   * @param array $settings
Pawel G's avatar
Pawel G committed
913
   *
Pawel G's avatar
Pawel G committed
914
   * @return $this
915 916
   *
   * @todo Validate $settings and throw exceptions
Pawel G's avatar
Pawel G committed
917
   */
918
  public function addCustomLink($path, $settings = []) {
919
    if (!(bool) $this->pathValidator->getUrlIfValidWithoutAccessCheck($path)) {
Pawel G's avatar
Pawel G committed
920 921 922
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
923
    if ($path[0] !== '/') {
Pawel G's avatar
Pawel G committed
924 925 926
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
927

928
    $custom_links = $this->getCustomLinks(FALSE);
Pawel G's avatar
Pawel G committed
929
    foreach ($custom_links as $key => $link) {
930
      if ($link['path'] === $path) {
931 932 933 934 935
        $link_key = $key;
        break;
      }
    }
    $link_key = isset($link_key) ? $link_key : count($custom_links);
936
    $custom_links[$link_key] = ['path' => $path] + $settings;
Pawel G's avatar
Pawel G committed
937
    $this->configFactory->getEditable('simple_sitemap.custom')
938
      ->set('links', $custom_links)->save();
939

Pawel G's avatar
Pawel G committed
940
    return $this;
941 942
  }

943 944 945
  /**
   * Returns an array of custom paths and their sitemap settings.
   *
946
   * @param bool $supplement_default_settings
947 948
   * @return array
   */
949
  public function getCustomLinks($supplement_default_settings = TRUE) {
950 951
    $custom_links = $this->configFactory
      ->get('simple_sitemap.custom')
952
      ->get('links');
953 954 955

    if ($supplement_default_settings) {
      foreach ($custom_links as $i => $link_settings) {
Pawel G's avatar
Pawel G committed
956 957
        self::supplementDefaultSettings('custom', $link_settings);
        $custom_links[$i] = $link_settings;
958 959 960
      }
    }

961
    return !empty($custom_links) ? $custom_links : [];
962 963
  }

Pawel G's avatar
Pawel G committed
964 965 966
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
967
   * @param string $path
Pawel G's avatar
Pawel G committed
968
   *
Pawel G's avatar
Pawel G committed
969
   * @return array|false
Pawel G's avatar
Pawel G committed
970
   */
971
  public function getCustomLink($path) {
972
    foreach ($this->getCustomLinks() as $key => $link) {
973
      if ($link['path'] === $path) {
974
        return $link;
975 976 977 978 979
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
980
  /**
981
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
982
   *
Pawel G's avatar
Pawel G committed
983 984
   * @return $this
   */
985 986 987 988 989 990 991 992 993 994 995 996 997 998
  public function removeCustomLinks($paths = NULL) {
    if (NULL === $paths) {
      $custom_links = [];
      $save = TRUE;
    }
    else {
      $custom_links = $this->getCustomLinks(FALSE);
      foreach ((array) $paths as $path) {
        foreach ($custom_links as $key => $link) {
          if ($link['path'] === $path) {
            unset($custom_links[$key]);
            $save = TRUE;
          }
        }
999 1000
      }
    }
1001 1002 1003 1004
    if (!empty($save)) {
      $this->configFactory->getEditable('simple_sitemap.custom')
        ->set('links', array_values($custom_links))->save();
    }
1005

Pawel G's avatar
Pawel G committed
1006
    return $this;
1007
  }
1008
}