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

Pawel G's avatar
Pawel G committed
3
namespace Drupal\simple_sitemap;
4

5
use Drupal\Core\Entity\ContentEntityTypeInterface;
6
use Drupal\simple_sitemap\Form\FormHelper;
Pawel G's avatar
Pawel G committed
7 8 9
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\PathValidator;
10

11
/**
Pawel G's avatar
Pawel G committed
12 13
 * Class Simplesitemap.
 *
Pawel G's avatar
Pawel G committed
14
 * @package Drupal\simple_sitemap
15 16 17
 */
class Simplesitemap {

18
  private $sitemapGenerator;
19 20 21
  private $configFactory;
  private $db;
  private $entityTypeManager;
22
  private $pathValidator;
23 24
  private static $allowed_link_settings = [
    'entity' => ['index', 'priority'],
Pawel G's avatar
Pawel G committed
25
    'custom' => ['priority'],
26
  ];
27

28 29
  /**
   * Simplesitemap constructor.
Pawel G's avatar
Pawel G committed
30
   *
31
   * @param $sitemapGenerator
32
   * @param $configFactoryInterface
33
   * @param $database
34
   * @param $entityTypeManager
35 36
   * @param $pathValidator
   * @param $dateFormatter
37
   */
38
  public function __construct(
Pawel G's avatar
Pawel G committed
39
    SitemapGenerator $sitemapGenerator,
40
    $configFactoryInterface,
Pawel G's avatar
Pawel G committed
41 42 43
    Connection $database,
    EntityTypeManagerInterface $entityTypeManager,
    PathValidator $pathValidator,
44
    $dateFormatter
45 46
  ) {
    $this->sitemapGenerator = $sitemapGenerator;
47 48 49
    $this->configFactory = $configFactoryInterface;
    $this->db = $database;
    $this->entityTypeManager = $entityTypeManager;
50
    $this->pathValidator = $pathValidator;
51
    $this->dateFormatter = $dateFormatter;
52 53
  }

54
  /**
55
   * Gets a specific sitemap configuration from the configuration storage.
56
   *
Pawel G's avatar
Pawel G committed
57
   * @param string $key
Pawel G's avatar
Pawel G committed
58 59
   *   Configuration key, like 'entity_types'.
   *
60
   * @return mixed
Pawel G's avatar
Pawel G committed
61
   *   The requested configuration.
62
   */
63
  public function getConfig($key) {
64 65 66
    $config = $this->configFactory->get("simple_sitemap.$key")->get();
    unset($config['_core']);
    return $config;
67 68
  }

Pawel G's avatar
Pawel G committed
69 70 71
  /**
   *
   */
Pawel G's avatar
Pawel G committed
72
  private function fetchSitemapChunks() {
73
    return $this->db
74 75 76 77
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

78
  /**
79
   * Saves a specific sitemap configuration to db.
80
   *
81
   * @param string $key
Pawel G's avatar
Pawel G committed
82
   *   Configuration key, like 'entity_types'.
83
   * @param mixed $value
Pawel G's avatar
Pawel G committed
84
   *   The configuration to be saved.
Pawel G's avatar
Pawel G committed
85 86
   *
   * @return $this
87
   */
88
  public function saveConfig($key, $value) {
89 90
    $this->configFactory->getEditable("simple_sitemap.$key")
      ->setData($value)->save();
Pawel G's avatar
Pawel G committed
91
    return $this;
92 93
  }

94 95 96 97 98 99 100
  /**
   * Enables sitemap support for an entity type. Enabled entity types show
   * sitemap settings on their bundles. If an enabled entity type does not
   * featured bundles (e.g. 'user'), it needs to be set up with
   * setBundleSettings() as well.
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
101
   *   Entity type id like 'node'.
102
   *
Pawel G's avatar
Pawel G committed
103
   * @return $this
104 105 106 107 108 109 110
   */
  public function enableEntityType($entity_type_id) {
    $entity_types = $this->getConfig('entity_types');
    if (empty($entity_types[$entity_type_id])) {
      $entity_types[$entity_type_id] = [];
      $this->saveConfig('entity_types', $entity_types);
    }
Pawel G's avatar
Pawel G committed
111
    return $this;
112 113 114 115 116 117 118 119
  }

  /**
   * 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
Pawel G's avatar
Pawel G committed
120
   *   Entity type id like 'node'.
121
   *
Pawel G's avatar
Pawel G committed
122
   * @return $this
123 124 125 126 127 128
   */
  public function disableEntityType($entity_type_id) {
    $entity_types = $this->getConfig('entity_types');
    if (isset($entity_types[$entity_type_id])) {
      unset($entity_types[$entity_type_id]);
      $this->saveConfig('entity_types', $entity_types);
129 130 131 132
      // todo: test
      $this->db->delete('simple_sitemap_entity_overrides')
        ->condition('entity_type', $entity_type_id)
        ->execute();
133
    }
Pawel G's avatar
Pawel G committed
134
    return $this;
135 136 137
  }

  /**
Pawel G's avatar
Pawel G committed
138
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
139 140 141
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
Pawel G's avatar
Pawel G committed
142
   *   Entity type id like 'node' the bundle belongs to.
143
   * @param string $bundle_name
Pawel G's avatar
Pawel G committed
144
   *   Name of the bundle. NULL if entity type has no bundles.
145
   * @param array $settings
Pawel G's avatar
Pawel G committed
146 147
   *   An array of sitemap settings for this bundle/entity type.
   *   Example: ['index' => TRUE, 'priority' => 0.5].
Pawel G's avatar
Pawel G committed
148 149
   *
   * @return $this
150 151
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
152

153
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
154
    $entity_types = $this->getConfig('entity_types');
155
    $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]);
156
    $this->saveConfig('entity_types', $entity_types);
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

    $results = $this->db->select('simple_sitemap_entity_overrides', 'o')
      ->fields('o', ['id', 'inclusion_settings'])
      ->condition('o.entity_type', $entity_type_id)
      ->execute()
      ->fetchAll();

    // Delete entity overrides which are identical to new bundle setting.
    foreach($results as $result) {
      $delete = TRUE;
      $instance_settings = unserialize($result->inclusion_settings);
      foreach ($instance_settings as $key => $instance_setting) {
        if ($instance_setting != $entity_types[$entity_type_id][$bundle_name][$key]) {
          $delete = FALSE;
          break;
        }
      }
      if ($delete) {
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('id', $result->id)
          ->execute();
      }
    }

Pawel G's avatar
Pawel G committed
181
    return $this;
182 183
  }

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
  /**
   * Gets sitemap settings for an entity bundle or a non-bundle entity type.
   *
   * @param string $entity_type_id
   * @param string|null $bundle_name
   *
   * @return array|false
   */
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
    $entity_types = $this->getConfig('entity_types');
    if (isset($entity_types[$entity_type_id][$bundle_name])) {
      $settings = $entity_types[$entity_type_id][$bundle_name];
      return $settings;
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
202 203 204
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
205 206 207
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
208
   *
Pawel G's avatar
Pawel G committed
209 210
   * @return $this
   */
211 212
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
    $entity_types = $this->getConfig('entity_types');
213 214
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
215 216 217 218 219 220 221 222 223 224
    if (isset($entity_types[$entity_type_id][$bundle_name])) {

      // Check if overrides are different from bundle setting before saving.
      $override = FALSE;
      foreach ($settings as $key => $setting) {
        if ($setting != $entity_types[$entity_type_id][$bundle_name][$key]) {
          $override = TRUE;
          break;
        }
      }
Pawel G's avatar
Pawel G committed
225 226
      // Save overrides for this entity if something is different.
      if ($override) {
227 228 229 230 231 232 233 234 235 236
        $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,
            'inclusion_settings' => serialize($settings),
          ])
          ->execute();
237
      }
Pawel G's avatar
Pawel G committed
238 239
      // Else unset override.
      else {
240 241 242 243
        $this->db->delete('simple_sitemap_entity_overrides')
          ->condition('entity_type', $entity_type_id)
          ->condition('entity_id', $id)
          ->execute();
244
      }
245 246 247
    }
    else {
      //todo: log error
248
    }
Pawel G's avatar
Pawel G committed
249
    return $this;
250 251
  }

Pawel G's avatar
Pawel G committed
252
  /**
253 254
   * Gets sitemap settings for an entity instance which overrides bundle
   * settings.
Pawel G's avatar
Pawel G committed
255
   *
Pawel G's avatar
Pawel G committed
256
   * @param string $entity_type_id
257
   * @param int $id
Pawel G's avatar
Pawel G committed
258
   *
259
   * @return array
Pawel G's avatar
Pawel G committed
260
   */
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
  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)) {
      return unserialize($results);
    }
    else {
      $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
      $bundle_name = $this->getEntityInstanceBundleName($entity);
      return $this->getBundleSettings($entity_type_id, $bundle_name);
276 277 278
    }
  }

Pawel G's avatar
Pawel G committed
279 280 281 282 283 284
  /**
   * Checks if an entity bundle (or a non-bundle entity type) is set to be
   * indexed in the sitemap settings.
   *
   * @param $entity_type_id
   * @param null $bundle_name
Pawel G's avatar
Pawel G committed
285
   *
Pawel G's avatar
Pawel G committed
286 287
   * @return bool
   */
288
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
289 290 291 292
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
293 294 295 296
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
   * @param $entity_type_id
Pawel G's avatar
Pawel G committed
297
   *
Pawel G's avatar
Pawel G committed
298 299
   * @return bool
   */
300 301 302 303 304
  public function entityTypeIsEnabled($entity_type_id) {
    $entity_types = $this->getConfig('entity_types');
    return isset($entity_types[$entity_type_id]);
  }

Pawel G's avatar
Pawel G committed
305 306 307
  /**
   * Adds a custom path to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
308 309
   * @param string $path
   * @param array $settings
Pawel G's avatar
Pawel G committed
310
   *
Pawel G's avatar
Pawel G committed
311
   * @return $this
Pawel G's avatar
Pawel G committed
312
   */
313
  public function addCustomLink($path, $settings) {
Pawel G's avatar
Pawel G committed
314 315 316 317 318 319 320 321
    if (!$this->pathValidator->isValid($path)) {
      // todo: log error.
      return $this;
    }
    if ($path[0] != '/') {
      // todo: log error.
      return $this;
    }
Pawel G's avatar
Pawel G committed
322

323
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
324
    foreach ($custom_links as $key => $link) {
325 326 327 328 329 330 331 332 333
      if ($link['path'] == $path) {
        $link_key = $key;
        break;
      }
    }
    $link_key = isset($link_key) ? $link_key : count($custom_links);
    $custom_links[$link_key]['path'] = $path;
    $this->addLinkSettings('entity', $settings, $custom_links[$link_key]);
    $this->saveConfig('custom', $custom_links);
Pawel G's avatar
Pawel G committed
334
    return $this;
335 336
  }

Pawel G's avatar
Pawel G committed
337 338 339
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
340
   * @param string $path
Pawel G's avatar
Pawel G committed
341
   *
Pawel G's avatar
Pawel G committed
342
   * @return array|false
Pawel G's avatar
Pawel G committed
343
   */
344 345
  public function getCustomLink($path) {
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
346
    foreach ($custom_links as $key => $link) {
347 348 349 350 351 352 353
      if ($link['path'] == $path) {
        return $custom_links[$key];
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
354 355 356
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
357
   * @param string $path
Pawel G's avatar
Pawel G committed
358
   *
Pawel G's avatar
Pawel G committed
359 360
   * @return $this
   */
361 362
  public function removeCustomLink($path) {
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
363
    foreach ($custom_links as $key => $link) {
364 365 366 367 368 369
      if ($link['path'] == $path) {
        unset($custom_links[$key]);
        $custom_links = array_values($custom_links);
        $this->saveConfig('custom', $custom_links);
      }
    }
Pawel G's avatar
Pawel G committed
370
    return $this;
371 372
  }

Pawel G's avatar
Pawel G committed
373 374
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
375 376
   *
   * @return $this
Pawel G's avatar
Pawel G committed
377
   */
378 379
  public function removeCustomLinks() {
    $this->saveConfig('custom', []);
Pawel G's avatar
Pawel G committed
380
    return $this;
381 382
  }

Pawel G's avatar
Pawel G committed
383 384 385
  /**
   *
   */
386
  private function addLinkSettings($type, $settings, &$target) {
Pawel G's avatar
Pawel G committed
387
    foreach ($settings as $setting_key => $setting) {
388
      if (in_array($setting_key, self::$allowed_link_settings[$type])) {
Pawel G's avatar
Pawel G committed
389
        switch ($setting_key) {
390
          case 'priority':
391
            if (!FormHelper::isValidPriority($setting)) {
392
              // todo: log error.
393 394 395
              continue;
            }
            break;
Pawel G's avatar
Pawel G committed
396 397

          // todo: add index check.
398 399 400 401 402 403
        }
        $target[$setting_key] = $setting;
      }
    }
  }

Pawel G's avatar
Pawel G committed
404 405 406 407
  /**
   * @param $entity
   * @return mixed
   */
Pawel G's avatar
Pawel G committed
408 409
  public function getEntityInstanceBundleName($entity) {
    return $entity->getEntityTypeId() == 'menu_link_content'
Pawel G's avatar
Pawel G committed
410 411
    // Menu fix.
      ? $entity->getMenuName() : $entity->bundle();
Pawel G's avatar
Pawel G committed
412 413
  }

Pawel G's avatar
Pawel G committed
414 415 416 417
  /**
   * @param $entity
   * @return string
   */
Pawel G's avatar
Pawel G committed
418 419
  public function getBundleEntityTypeId($entity) {
    return $entity->getEntityTypeId() == 'menu'
Pawel G's avatar
Pawel G committed
420 421
    // Menu fix.
      ? 'menu_link_content' : $entity->getEntityType()->getBundleOf();
Pawel G's avatar
Pawel G committed
422 423
  }

424 425 426 427
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
428
   * @param int $chunk_id
429
   *
Pawel G's avatar
Pawel G committed
430
   * @return string|false
Pawel G's avatar
Pawel G committed
431 432 433 434
   *   If no sitemap id provided, either a sitemap index is returned, or the
   *   whole sitemap, if the amount of links does not exceed the max links
   *   setting. If a sitemap id is provided, a sitemap chunk is returned. False
   *   if sitemap is not retrievable from the database.
435
   */
Pawel G's avatar
Pawel G committed
436 437 438
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
439 440

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
441 442
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
443
      }
Pawel G's avatar
Pawel G committed
444 445
      // Return sitemap if there is only one chunk.
      else {
Pawel G's avatar
Pawel G committed
446 447
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
448 449
        }
        return FALSE;
450 451
      }
    }
Pawel G's avatar
Pawel G committed
452 453
    // Return specific sitemap chunk.
    else {
Pawel G's avatar
Pawel G committed
454
      return $chunks[$chunk_id]->sitemap_string;
455
    }
456 457
  }

458 459
  /**
   * Generates the sitemap for all languages and saves it to the db.
460 461
   *
   * @param string $from
Pawel G's avatar
Pawel G committed
462 463
   *   Can be 'form', 'cron', 'drush' or 'nobatch'.
   *   This decides how the batch process is to be run.
464
   */
465
  public function generateSitemap($from = 'form') {
466 467 468 469
    $this->sitemapGenerator
      ->setGenerator($this)
      ->setGenerateFrom($from)
      ->startGeneration();
470 471
  }

472
  /**
473 474
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
475
   * @param array $chunks
Pawel G's avatar
Pawel G committed
476
   *   Sitemap chunks which to generate the index from.
477
   *
478
   * @return string
Pawel G's avatar
Pawel G committed
479
   *   The sitemap index.
480
   */
Pawel G's avatar
Pawel G committed
481
  private function getSitemapIndex($chunks) {
482 483
    return $this->sitemapGenerator
      ->setGenerator($this)
Pawel G's avatar
Pawel G committed
484
      ->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
485 486
  }

487
  /**
Pawel G's avatar
Pawel G committed
488
   * Returns a specific sitemap setting.
489 490
   *
   * @param string $name
Pawel G's avatar
Pawel G committed
491
   *   Name of the setting, like 'max_links'.
492
   *
493
   * @param mixed $default
Pawel G's avatar
Pawel G committed
494
   *   Value to be returned if the setting does not exist in the configuration.
495
   *
496
   * @return mixed
Pawel G's avatar
Pawel G committed
497
   *   The current setting from db or a default value.
498
   */
499
  public function getSetting($name, $default = FALSE) {
500
    $settings = $this->getConfig('settings');
501
    return isset($settings[$name]) ? $settings[$name] : $default;
502
  }
503

504
  /**
505 506
   * Saves a specific sitemap setting to db.
   *
Pawel G's avatar
Pawel G committed
507
   * @param string $name
Pawel G's avatar
Pawel G committed
508
   *   Setting name, like 'max_links'.
Pawel G's avatar
Pawel G committed
509
   * @param mixed $setting
Pawel G's avatar
Pawel G committed
510
   *   The setting to be saved.
Pawel G's avatar
Pawel G committed
511 512
   *
   * @return $this
513
   */
514 515
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
516
    $settings[$name] = $setting;
517
    $this->saveConfig('settings', $settings);
Pawel G's avatar
Pawel G committed
518
    return $this;
519
  }
520

Pawel G's avatar
Pawel G committed
521 522
  /**
   * Returns a 'time ago' string of last timestamp generation.
523
   *
Pawel G's avatar
Pawel G committed
524
   * @return string|false
Pawel G's avatar
Pawel G committed
525
   *   Formatted timestamp of last sitemap generation, otherwise FALSE.
Pawel G's avatar
Pawel G committed
526
   */
527
  public function getGeneratedAgo() {
528
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
529
    if (isset($chunks[1]->sitemap_created)) {
530
      return $this->dateFormatter
Pawel G's avatar
Pawel G committed
531
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
532 533 534
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
535

536 537 538 539
  /**
   * Returns objects of entity types that can be indexed by the sitemap.
   *
   * @return array
Pawel G's avatar
Pawel G committed
540
   *   Objects of entity types that can be indexed by the sitemap.
541
   */
542 543
  public function getSitemapEntityTypes() {
    $entity_types = $this->entityTypeManager->getDefinitions();
544 545

    foreach ($entity_types as $entity_type_id => $entity_type) {
546 547 548
      if (!$entity_type instanceof ContentEntityTypeInterface
        || !method_exists($entity_type, 'getBundleEntityType')
        || !$entity_type->hasLinkTemplate('canonical')) {
549 550 551 552 553
        unset($entity_types[$entity_type_id]);
      }
    }
    return $entity_types;
  }
554

Pawel G's avatar
Pawel G committed
555 556 557 558
  /**
   * @param $entity_type_id
   * @return bool
   */
559
  public function entityTypeIsAtomic($entity_type_id) {
Pawel G's avatar
Pawel G committed
560 561
    // Menu fix.
    if ($entity_type_id == 'menu_link_content') {
562
      return FALSE;
Pawel G's avatar
Pawel G committed
563
    }
564
    $sitemap_entity_types = $this->getSitemapEntityTypes();
565 566 567 568 569 570
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $entity_type = $sitemap_entity_types[$entity_type_id];
      if (empty($entity_type->getBundleEntityType())) {
        return TRUE;
      }
    }
Pawel G's avatar
Pawel G committed
571 572
    // todo: throw exception.
    return FALSE;
573
  }
Pawel G's avatar
Pawel G committed
574

575
}