Simplesitemap.php 14.1 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\Form;
7

8
/**
Pawel G's avatar
Pawel G committed
9 10
 * Class Simplesitemap
 * @package Drupal\simple_sitemap
11 12 13
 */
class Simplesitemap {

14
  private $sitemapGenerator;
15 16 17
  private $configFactory;
  private $db;
  private $entityTypeManager;
18
  private $pathValidator;
19 20
  private static $allowed_link_settings = [
    'entity' => ['index', 'priority'],
21 22
    'custom' => ['priority']
  ];
23

24 25
  /**
   * Simplesitemap constructor.
26
   * @param $sitemapGenerator
27
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface
28
   * @param $database
Pawel G's avatar
Pawel G committed
29
   * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
30 31
   * @param $pathValidator
   * @param $dateFormatter
32
   */
33
  public function __construct(
34
    $sitemapGenerator,
Pawel G's avatar
Pawel G committed
35
    \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface,
36
    $database,
37
    \Drupal\Core\Entity\EntityTypeManager $entityTypeManager,
38 39
    $pathValidator,
    $dateFormatter
40 41
  ) {
    $this->sitemapGenerator = $sitemapGenerator;
42 43 44
    $this->configFactory = $configFactoryInterface;
    $this->db = $database;
    $this->entityTypeManager = $entityTypeManager;
45
    $this->pathValidator = $pathValidator;
46
    $this->dateFormatter = $dateFormatter;
47 48
  }

49
  /**
50
   * Gets a specific sitemap configuration from the configuration storage.
51
   *
Pawel G's avatar
Pawel G committed
52
   * @param string $key
53
   *  Configuration key, like 'entity_types'.
54 55
   * @return mixed
   *  The requested configuration.
56
   */
57
  public function getConfig($key) {
58
    return $this->configFactory->get('simple_sitemap.settings')->get($key);
59 60
  }

Pawel G's avatar
Pawel G committed
61
  private function fetchSitemapChunks() {
62
    return $this->db
63 64 65 66
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

67
  /**
68
   * Saves a specific sitemap configuration to db.
69
   *
70
   * @param string $key
71
   *  Configuration key, like 'entity_types'.
72 73
   * @param mixed $value
   *  The configuration to be saved.
Pawel G's avatar
Pawel G committed
74 75
   *
   * @return $this
76
   */
77
  public function saveConfig($key, $value) {
78
    $this->configFactory->getEditable('simple_sitemap.settings')
79
      ->set($key, $value)->save();
Pawel G's avatar
Pawel G committed
80
    return $this;
81 82
  }

Pawel G's avatar
Pawel G committed
83

84 85 86 87 88 89 90 91 92
  /**
   * 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
   *  Entity type id like 'node'.
   *
Pawel G's avatar
Pawel G committed
93
   * @return $this
94 95 96 97 98 99 100
   */
  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
101
    return $this;
102 103 104 105 106 107 108 109 110 111
  }

  /**
   * 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
   *  Entity type id like 'node'.
   *
Pawel G's avatar
Pawel G committed
112
   * @return $this
113 114 115 116 117 118 119
   */
  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);
    }
Pawel G's avatar
Pawel G committed
120
    return $this;
121 122 123
  }

  /**
Pawel G's avatar
Pawel G committed
124
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
125 126 127 128 129 130 131 132 133
   * of an entity type (e.g. page).
   *
   * @param string $entity_type_id
   *  Entity type id like 'node' the bundle belongs to.
   * @param string $bundle_name
   *  Name of the bundle. NULL if entity type has no bundles.
   * @param array $settings
   *  An array of sitemap settings for this bundle/entity type.
   *  Example: ['index' => TRUE, 'priority' => 0.5]
Pawel G's avatar
Pawel G committed
134 135
   *
   * @return $this
136 137
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
138
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
139
    $entity_types = $this->getConfig('entity_types');
140
    $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]);
141
    $this->saveConfig('entity_types', $entity_types);
Pawel G's avatar
Pawel G committed
142
    return $this;
143 144
  }

Pawel G's avatar
Pawel G committed
145 146 147
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
148 149 150
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
151 152
   * @return $this
   */
153 154
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
    $entity_types = $this->getConfig('entity_types');
155 156
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
157 158 159 160 161 162 163 164 165 166 167
    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;
        }
      }
      if ($override) { //Save overrides for this entity if something is different.
168
        $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
169 170 171 172 173 174
      }
      else { // Else unset override.
        unset($entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
      }
      $this->saveConfig('entity_types', $entity_types);
    }
Pawel G's avatar
Pawel G committed
175
    return $this;
176 177
  }

Pawel G's avatar
Pawel G committed
178 179 180
  /**
   * Gets sitemap settings for an entity bundle or a non-bundle entity type.
   *
Pawel G's avatar
Pawel G committed
181 182 183
   * @param string $entity_type_id
   * @param string|null $bundle_name
   * @return array|false
Pawel G's avatar
Pawel G committed
184
   */
185
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
186
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
187 188 189 190 191 192 193 194 195
    $entity_types = $this->getConfig('entity_types');
    if (isset($entity_types[$entity_type_id][$bundle_name])) {
      $settings = $entity_types[$entity_type_id][$bundle_name];
      unset($settings['entities']);
      return $settings;
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
196 197 198 199 200 201 202 203
  /**
   * 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
   * @return bool
   */
204
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
205 206 207 208
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
209 210 211 212 213 214
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
   * @param $entity_type_id
   * @return bool
   */
215 216 217 218 219
  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
220 221 222 223
  /**
   * Gets sitemap settings for an entity instance which overrides bundle
   * settings.
   *
Pawel G's avatar
Pawel G committed
224 225 226
   * @param string $entity_type_id
   * @param int $id
   * @return array
Pawel G's avatar
Pawel G committed
227
   */
228 229
  public function getEntityInstanceSettings($entity_type_id, $id) {
    $entity_types = $this->getConfig('entity_types');
230 231
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
232 233 234 235 236 237 238 239
    if (isset($entity_types[$entity_type_id][$bundle_name]['entities'][$id])) {
      return $entity_types[$entity_type_id][$bundle_name]['entities'][$id];
    }
    else {
      return $this->getBundleSettings($entity_type_id, $bundle_name);
    }
  }

Pawel G's avatar
Pawel G committed
240 241 242
  /**
   * Adds a custom path to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
243 244 245
   * @param string $path
   * @param array $settings
   * @return $this
Pawel G's avatar
Pawel G committed
246
   */
247
  public function addCustomLink($path, $settings) {
248
    if (!$this->pathValidator->isValid($path))
Pawel G's avatar
Pawel G committed
249
      return $this; // todo: log error
250
    if ($path[0] != '/')
Pawel G's avatar
Pawel G committed
251 252
      return $this; // todo: log error

253 254 255 256 257 258 259 260 261 262 263
    $custom_links = $this->getConfig('custom');
    foreach($custom_links as $key => $link) {
      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
264
    return $this;
265 266
  }

Pawel G's avatar
Pawel G committed
267 268 269
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
270 271
   * @param string $path
   * @return array|false
Pawel G's avatar
Pawel G committed
272
   */
273 274 275 276 277 278 279 280 281 282
  public function getCustomLink($path) {
    $custom_links = $this->getConfig('custom');
    foreach($custom_links as $key => $link) {
      if ($link['path'] == $path) {
        return $custom_links[$key];
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
283 284 285
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
286
   * @param string $path
Pawel G's avatar
Pawel G committed
287 288
   * @return $this
   */
289 290 291 292 293 294 295 296 297
  public function removeCustomLink($path) {
    $custom_links = $this->getConfig('custom');
    foreach($custom_links as $key => $link) {
      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
298
    return $this;
299 300
  }

Pawel G's avatar
Pawel G committed
301 302
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
303 304
   *
   * @return $this
Pawel G's avatar
Pawel G committed
305
   */
306 307
  public function removeCustomLinks() {
    $this->saveConfig('custom', []);
Pawel G's avatar
Pawel G committed
308
    return $this;
309 310 311 312 313 314 315
  }

  private function addLinkSettings($type, $settings, &$target) {
    foreach($settings as $setting_key => $setting) {
      if (in_array($setting_key, self::$allowed_link_settings[$type])) {
        switch($setting_key) {
          case 'priority':
316
            if (!Form::isValidPriority($setting)) {
317 318 319 320 321 322 323 324 325 326 327
              // todo: register error
              continue;
            }
            break;
          //todo: add index check
        }
        $target[$setting_key] = $setting;
      }
    }
  }

Pawel G's avatar
Pawel G committed
328 329 330 331
  /**
   * @param $entity
   * @return mixed
   */
Pawel G's avatar
Pawel G committed
332 333 334 335 336
  public function getEntityInstanceBundleName($entity) {
    return $entity->getEntityTypeId() == 'menu_link_content'
      ? $entity->getMenuName() : $entity->bundle(); // Menu fix.
  }

Pawel G's avatar
Pawel G committed
337 338 339 340
  /**
   * @param $entity
   * @return string
   */
Pawel G's avatar
Pawel G committed
341 342 343 344 345
  public function getBundleEntityTypeId($entity) {
    return $entity->getEntityTypeId() == 'menu'
      ? 'menu_link_content' : $entity->getEntityType()->getBundleOf(); // Menu fix.
  }

346 347 348 349
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
350
   * @param int $chunk_id
351
   *
Pawel G's avatar
Pawel G committed
352
   * @return string|false
353 354 355 356
   *  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.
   */
Pawel G's avatar
Pawel G committed
357 358 359
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
360 361

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
362 363
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
364
      }
365
      else { // Return sitemap if there is only one chunk.
Pawel G's avatar
Pawel G committed
366 367
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
368 369
        }
        return FALSE;
370 371
      }
    }
372
    else { // Return specific sitemap chunk.
Pawel G's avatar
Pawel G committed
373
      return $chunks[$chunk_id]->sitemap_string;
374
    }
375 376
  }

377 378
  /**
   * Generates the sitemap for all languages and saves it to the db.
379 380
   *
   * @param string $from
381 382
   *  Can be 'form', 'cron', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
383
   */
384
  public function generateSitemap($from = 'form') {
385 386 387 388
    $this->sitemapGenerator
      ->setGenerator($this)
      ->setGenerateFrom($from)
      ->startGeneration();
389 390
  }

391
  /**
392 393
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
394
   * @param array $chunks
395 396
   *  Sitemap chunks which to generate the index from.
   *
397 398
   * @return string
   *  The sitemap index.
399
   */
Pawel G's avatar
Pawel G committed
400
  private function getSitemapIndex($chunks) {
401 402
    return $this->sitemapGenerator
      ->setGenerator($this)
Pawel G's avatar
Pawel G committed
403
      ->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
404 405
  }

406
  /**
Pawel G's avatar
Pawel G committed
407
   * Returns a specific sitemap setting.
408 409 410 411
   *
   * @param string $name
   *  Name of the setting, like 'max_links'.
   *
412
   * @param mixed $default
Pawel G's avatar
Pawel G committed
413
   *  Value to be returned if the setting does not exist in the configuration.
414
   *
415
   * @return mixed
416
   *  The current setting from db or a default value.
417
   */
418
  public function getSetting($name, $default = FALSE) {
419
    $settings = $this->getConfig('settings');
420
    return isset($settings[$name]) ? $settings[$name] : $default;
421
  }
422

423
  /**
424 425
   * Saves a specific sitemap setting to db.
   *
Pawel G's avatar
Pawel G committed
426
   * @param string $name
427
   *  Setting name, like 'max_links'.
Pawel G's avatar
Pawel G committed
428
   * @param mixed $setting
429
   *  The setting to be saved.
Pawel G's avatar
Pawel G committed
430 431
   *
   * @return $this
432
   */
433 434
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
435
    $settings[$name] = $setting;
436
    $this->saveConfig('settings', $settings);
Pawel G's avatar
Pawel G committed
437
    return $this;
438
  }
439

Pawel G's avatar
Pawel G committed
440 441
  /**
   * Returns a 'time ago' string of last timestamp generation.
442
   *
Pawel G's avatar
Pawel G committed
443
   * @return string|false
Pawel G's avatar
Pawel G committed
444 445
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
446
  public function getGeneratedAgo() {
447
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
448
    if (isset($chunks[1]->sitemap_created)) {
449
      return $this->dateFormatter
Pawel G's avatar
Pawel G committed
450
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
451 452 453
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
454

455 456 457 458 459 460
  /**
   * Returns objects of entity types that can be indexed by the sitemap.
   *
   * @return array
   *  Objects of entity types that can be indexed by the sitemap.
   */
461 462
  public function getSitemapEntityTypes() {
    $entity_types = $this->entityTypeManager->getDefinitions();
463 464 465 466 467 468 469 470

    foreach ($entity_types as $entity_type_id => $entity_type) {
      if (!$entity_type instanceof ContentEntityTypeInterface || !method_exists($entity_type, 'getBundleEntityType')) {
        unset($entity_types[$entity_type_id]);
      }
    }
    return $entity_types;
  }
471

Pawel G's avatar
Pawel G committed
472 473 474 475
  /**
   * @param $entity_type_id
   * @return bool
   */
476
  public function entityTypeIsAtomic($entity_type_id) {
477 478
    if ($entity_type_id == 'menu_link_content') // Menu fix.
      return FALSE;
479
    $sitemap_entity_types = $this->getSitemapEntityTypes();
480 481 482 483 484 485 486 487
    if (isset($sitemap_entity_types[$entity_type_id])) {
      $entity_type = $sitemap_entity_types[$entity_type_id];
      if (empty($entity_type->getBundleEntityType())) {
        return TRUE;
      }
    }
    return FALSE; //todo: throw exception
  }
488
}