Simplesitemap.php 13.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

7 8
/**
 * Simplesitemap class.
9 10
 *
 * Main module class.
11 12 13
 */
class Simplesitemap {

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

22 23 24
  /**
   * Simplesitemap constructor.
   *
25
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface
Pawel G's avatar
Pawel G committed
26 27
   * @param \Drupal\Core\Database\Database $database
   * @param \Drupal\Core\Entity\EntityTypeManager $entityTypeManager
28
   */
29
  public function __construct(
Pawel G's avatar
Pawel G committed
30
    \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface,
31
    $database,
Pawel G's avatar
Pawel G committed
32
    \Drupal\Core\Entity\EntityTypeManager $entityTypeManager) {
33 34 35 36 37

    $this->configFactory = $configFactoryInterface;
    $this->db = $database;
    $this->entityTypeManager = $entityTypeManager;
    $this->config = $this->configFactory->get('simple_sitemap.settings');
38 39
  }

40
  /**
41
   * Gets a specific sitemap configuration from the configuration storage.
42
   *
Pawel G's avatar
Pawel G committed
43
   * @param string $key
44
   *  Configuration key, like 'entity_types'.
45 46
   * @return mixed
   *  The requested configuration.
47
   */
48
  public function getConfig($key) {
49
    return $this->config->get($key);
50 51
  }

Pawel G's avatar
Pawel G committed
52
  private function fetchSitemapChunks() {
53
    return $this->db
54 55 56 57
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

58
  /**
59
   * Saves a specific sitemap configuration to db.
60
   *
61
   * @param string $key
62
   *  Configuration key, like 'entity_types'.
63 64
   * @param mixed $value
   *  The configuration to be saved.
Pawel G's avatar
Pawel G committed
65 66
   *
   * @return $this
67
   */
68
  public function saveConfig($key, $value) {
69
    $this->configFactory->getEditable('simple_sitemap.settings')
70
      ->set($key, $value)->save();
71
    // Refresh config object after making changes.
72
    $this->config = $this->configFactory->get('simple_sitemap.settings');
Pawel G's avatar
Pawel G committed
73
    return $this;
74 75
  }

Pawel G's avatar
Pawel G committed
76

77 78 79 80 81 82 83 84 85
  /**
   * 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
86
   * @return $this
87 88 89 90 91 92 93
   */
  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
94
    return $this;
95 96 97 98 99 100 101 102 103 104
  }

  /**
   * 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
105
   * @return $this
106 107 108 109 110 111 112
   */
  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
113
    return $this;
114 115 116
  }

  /**
Pawel G's avatar
Pawel G committed
117
   * Sets sitemap settings for a non-bundle entity type (e.g. user) or a bundle
118 119 120 121 122 123 124 125 126
   * 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
127 128
   *
   * @return $this
129 130
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
131
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
132
    $entity_types = $this->getConfig('entity_types');
133
    $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]);
134
    $this->saveConfig('entity_types', $entity_types);
Pawel G's avatar
Pawel G committed
135
    return $this;
136 137
  }

Pawel G's avatar
Pawel G committed
138 139 140
  /**
   * Overrides entity bundle/entity type sitemap settings for a single entity.
   *
Pawel G's avatar
Pawel G committed
141 142 143
   * @param string $entity_type_id
   * @param int $id
   * @param array $settings
Pawel G's avatar
Pawel G committed
144 145
   * @return $this
   */
146 147
  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
    $entity_types = $this->getConfig('entity_types');
148 149
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
150 151 152 153 154 155 156 157 158 159 160
    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.
161
        $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
162 163 164 165 166 167
      }
      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
168
    return $this;
169 170
  }

Pawel G's avatar
Pawel G committed
171 172 173
  /**
   * Gets sitemap settings for an entity bundle or a non-bundle entity type.
   *
Pawel G's avatar
Pawel G committed
174 175 176
   * @param string $entity_type_id
   * @param string|null $bundle_name
   * @return array|false
Pawel G's avatar
Pawel G committed
177
   */
178 179
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
180 181 182 183 184 185 186 187 188
    $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
189 190 191 192 193 194 195 196
  /**
   * 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
   */
197
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
198 199 200 201
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
202 203 204 205 206 207
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
   * @param $entity_type_id
   * @return bool
   */
208 209 210 211 212
  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
213 214 215 216
  /**
   * Gets sitemap settings for an entity instance which overrides bundle
   * settings.
   *
Pawel G's avatar
Pawel G committed
217 218 219
   * @param string $entity_type_id
   * @param int $id
   * @return array
Pawel G's avatar
Pawel G committed
220
   */
221 222
  public function getEntityInstanceSettings($entity_type_id, $id) {
    $entity_types = $this->getConfig('entity_types');
223 224
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
225 226 227 228 229 230 231 232
    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
233 234 235
  /**
   * Adds a custom path to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
236 237 238
   * @param string $path
   * @param array $settings
   * @return $this
Pawel G's avatar
Pawel G committed
239
   */
240 241
  public function addCustomLink($path, $settings) {
    if (!\Drupal::service('path.validator')->isValid($path))
Pawel G's avatar
Pawel G committed
242
      return $this; // todo: log error
243
    if ($path[0] != '/')
Pawel G's avatar
Pawel G committed
244 245
      return $this; // todo: log error

246 247 248 249 250 251 252 253 254 255 256
    $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
257
    return $this;
258 259
  }

Pawel G's avatar
Pawel G committed
260 261 262
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
263 264
   * @param string $path
   * @return array|false
Pawel G's avatar
Pawel G committed
265
   */
266 267 268 269 270 271 272 273 274 275
  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
276 277 278
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
279
   * @param string $path
Pawel G's avatar
Pawel G committed
280 281
   * @return $this
   */
282 283 284 285 286 287 288 289 290
  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
291
    return $this;
292 293
  }

Pawel G's avatar
Pawel G committed
294 295
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
296 297
   *
   * @return $this
Pawel G's avatar
Pawel G committed
298
   */
299 300
  public function removeCustomLinks() {
    $this->saveConfig('custom', []);
Pawel G's avatar
Pawel G committed
301
    return $this;
302 303 304 305 306 307 308
  }

  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':
309
            if (Form::isValidPriority($setting)) {
310 311 312 313 314 315 316 317 318 319 320
              // todo: register error
              continue;
            }
            break;
          //todo: add index check
        }
        $target[$setting_key] = $setting;
      }
    }
  }

Pawel G's avatar
Pawel G committed
321 322 323 324 325 326 327 328 329 330
  public function getEntityInstanceBundleName($entity) {
    return $entity->getEntityTypeId() == 'menu_link_content'
      ? $entity->getMenuName() : $entity->bundle(); // Menu fix.
  }

  public function getBundleEntityTypeId($entity) {
    return $entity->getEntityTypeId() == 'menu'
      ? 'menu_link_content' : $entity->getEntityType()->getBundleOf(); // Menu fix.
  }

331 332 333 334
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
335
   * @param int $chunk_id
336
   *
Pawel G's avatar
Pawel G committed
337
   * @return string|false
338 339 340 341
   *  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
342 343 344
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
345 346

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
347 348
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
349
      }
350
      else { // Return sitemap if there is only one chunk.
Pawel G's avatar
Pawel G committed
351 352
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
353 354
        }
        return FALSE;
355 356
      }
    }
357
    else { // Return specific sitemap chunk.
Pawel G's avatar
Pawel G committed
358
      return $chunks[$chunk_id]->sitemap_string;
359
    }
360 361
  }

362 363
  /**
   * Generates the sitemap for all languages and saves it to the db.
364 365
   *
   * @param string $from
366 367
   *  Can be 'form', 'cron', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
368
   */
369
  public function generateSitemap($from = 'form') {
Pawel G's avatar
Pawel G committed
370 371 372
    \Drupal::service('simple_sitemap.sitemap_generator')
    ->setGenerateFrom($from)
    ->startGeneration();
373 374
  }

375
  /**
376 377
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
378
   * @param array $chunks
379 380
   *  Sitemap chunks which to generate the index from.
   *
381 382
   * @return string
   *  The sitemap index.
383
   */
Pawel G's avatar
Pawel G committed
384
  private function getSitemapIndex($chunks) {
Pawel G's avatar
Pawel G committed
385 386
    return \Drupal::service('simple_sitemap.sitemap_generator')
      ->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
387 388
  }

389
  /**
Pawel G's avatar
Pawel G committed
390
   * Returns a specific sitemap setting.
391 392 393 394
   *
   * @param string $name
   *  Name of the setting, like 'max_links'.
   *
395
   * @param mixed $default
Pawel G's avatar
Pawel G committed
396
   *  Value to be returned if the setting does not exist in the configuration.
397
   *
398
   * @return mixed
399
   *  The current setting from db or a default value.
400
   */
401
  public function getSetting($name, $default = FALSE) {
402
    $settings = $this->getConfig('settings');
403
    return isset($settings[$name]) ? $settings[$name] : $default;
404
  }
405

406
  /**
407 408
   * Saves a specific sitemap setting to db.
   *
Pawel G's avatar
Pawel G committed
409
   * @param string $name
410
   *  Setting name, like 'max_links'.
Pawel G's avatar
Pawel G committed
411
   * @param mixed $setting
412
   *  The setting to be saved.
Pawel G's avatar
Pawel G committed
413 414
   *
   * @return $this
415
   */
416 417
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
418
    $settings[$name] = $setting;
419
    $this->saveConfig('settings', $settings);
Pawel G's avatar
Pawel G committed
420
    return $this;
421
  }
422

Pawel G's avatar
Pawel G committed
423 424
  /**
   * Returns a 'time ago' string of last timestamp generation.
425
   *
Pawel G's avatar
Pawel G committed
426
   * @return string|false
Pawel G's avatar
Pawel G committed
427 428
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
429
  public function getGeneratedAgo() {
430
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
431
    if (isset($chunks[1]->sitemap_created)) {
432
      return \Drupal::service('date.formatter')
Pawel G's avatar
Pawel G committed
433
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
434 435 436
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
437

438 439 440 441 442 443
  /**
   * 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.
   */
444 445
  public function getSitemapEntityTypes() {
    $entity_types = $this->entityTypeManager->getDefinitions();
446 447 448 449 450 451 452 453

    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;
  }
454

455
  public function entityTypeIsAtomic($entity_type_id) {
456 457
    if ($entity_type_id == 'menu_link_content') // Menu fix.
      return FALSE;
458
    $sitemap_entity_types = $this->getSitemapEntityTypes();
459 460 461 462 463 464 465 466
    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
  }
467
}