Simplesitemap.php 14.2 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;
7

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

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

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

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

Pawel G's avatar
Pawel G committed
64 65 66
  /**
   *
   */
Pawel G's avatar
Pawel G committed
67
  private function fetchSitemapChunks() {
68
    return $this->db
69 70 71 72
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

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

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

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

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

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

Pawel G's avatar
Pawel G committed
186 187 188
  /**
   * Gets sitemap settings for an entity bundle or a non-bundle entity type.
   *
Pawel G's avatar
Pawel G committed
189 190
   * @param string $entity_type_id
   * @param string|null $bundle_name
Pawel G's avatar
Pawel G committed
191
   *
Pawel G's avatar
Pawel G committed
192
   * @return array|false
Pawel G's avatar
Pawel G committed
193
   */
194
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
195
    $bundle_name = empty($bundle_name) ? $entity_type_id : $bundle_name;
196 197 198 199 200 201 202 203 204
    $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
205 206 207 208 209 210
  /**
   * 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
211
   *
Pawel G's avatar
Pawel G committed
212 213
   * @return bool
   */
214
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
215 216 217 218
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

Pawel G's avatar
Pawel G committed
219 220 221 222
  /**
   * Checks if an entity type is enabled in the sitemap settings.
   *
   * @param $entity_type_id
Pawel G's avatar
Pawel G committed
223
   *
Pawel G's avatar
Pawel G committed
224 225
   * @return bool
   */
226 227 228 229 230
  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
231 232 233 234
  /**
   * Gets sitemap settings for an entity instance which overrides bundle
   * settings.
   *
Pawel G's avatar
Pawel G committed
235 236
   * @param string $entity_type_id
   * @param int $id
Pawel G's avatar
Pawel G committed
237
   *
Pawel G's avatar
Pawel G committed
238
   * @return array
Pawel G's avatar
Pawel G committed
239
   */
240 241
  public function getEntityInstanceSettings($entity_type_id, $id) {
    $entity_types = $this->getConfig('entity_types');
242 243
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
244 245 246 247 248 249 250 251
    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
252 253 254
  /**
   * Adds a custom path to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
255 256
   * @param string $path
   * @param array $settings
Pawel G's avatar
Pawel G committed
257
   *
Pawel G's avatar
Pawel G committed
258
   * @return $this
Pawel G's avatar
Pawel G committed
259
   */
260
  public function addCustomLink($path, $settings) {
Pawel G's avatar
Pawel G committed
261 262 263 264 265 266 267 268
    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
269

270
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
271
    foreach ($custom_links as $key => $link) {
272 273 274 275 276 277 278 279 280
      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
281
    return $this;
282 283
  }

Pawel G's avatar
Pawel G committed
284 285 286
  /**
   * Returns settings for a custom path added to the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
287
   * @param string $path
Pawel G's avatar
Pawel G committed
288
   *
Pawel G's avatar
Pawel G committed
289
   * @return array|false
Pawel G's avatar
Pawel G committed
290
   */
291 292
  public function getCustomLink($path) {
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
293
    foreach ($custom_links as $key => $link) {
294 295 296 297 298 299 300
      if ($link['path'] == $path) {
        return $custom_links[$key];
      }
    }
    return FALSE;
  }

Pawel G's avatar
Pawel G committed
301 302 303
  /**
   * Removes a custom path from the sitemap settings.
   *
Pawel G's avatar
Pawel G committed
304
   * @param string $path
Pawel G's avatar
Pawel G committed
305
   *
Pawel G's avatar
Pawel G committed
306 307
   * @return $this
   */
308 309
  public function removeCustomLink($path) {
    $custom_links = $this->getConfig('custom');
Pawel G's avatar
Pawel G committed
310
    foreach ($custom_links as $key => $link) {
311 312 313 314 315 316
      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
317
    return $this;
318 319
  }

Pawel G's avatar
Pawel G committed
320 321
  /**
   * Removes all custom paths from the sitemap settings.
Pawel G's avatar
Pawel G committed
322 323
   *
   * @return $this
Pawel G's avatar
Pawel G committed
324
   */
325 326
  public function removeCustomLinks() {
    $this->saveConfig('custom', []);
Pawel G's avatar
Pawel G committed
327
    return $this;
328 329
  }

Pawel G's avatar
Pawel G committed
330 331 332
  /**
   *
   */
333
  private function addLinkSettings($type, $settings, &$target) {
Pawel G's avatar
Pawel G committed
334
    foreach ($settings as $setting_key => $setting) {
335
      if (in_array($setting_key, self::$allowed_link_settings[$type])) {
Pawel G's avatar
Pawel G committed
336
        switch ($setting_key) {
337
          case 'priority':
338
            if (!FormHelper::isValidPriority($setting)) {
Pawel G's avatar
Pawel G committed
339
              // todo: register error.
340 341 342
              continue;
            }
            break;
Pawel G's avatar
Pawel G committed
343 344

          // todo: add index check.
345 346 347 348 349 350
        }
        $target[$setting_key] = $setting;
      }
    }
  }

Pawel G's avatar
Pawel G committed
351 352 353 354
  /**
   * @param $entity
   * @return mixed
   */
Pawel G's avatar
Pawel G committed
355 356
  public function getEntityInstanceBundleName($entity) {
    return $entity->getEntityTypeId() == 'menu_link_content'
Pawel G's avatar
Pawel G committed
357 358
    // Menu fix.
      ? $entity->getMenuName() : $entity->bundle();
Pawel G's avatar
Pawel G committed
359 360
  }

Pawel G's avatar
Pawel G committed
361 362 363 364
  /**
   * @param $entity
   * @return string
   */
Pawel G's avatar
Pawel G committed
365 366
  public function getBundleEntityTypeId($entity) {
    return $entity->getEntityTypeId() == 'menu'
Pawel G's avatar
Pawel G committed
367 368
    // Menu fix.
      ? 'menu_link_content' : $entity->getEntityType()->getBundleOf();
Pawel G's avatar
Pawel G committed
369 370
  }

371 372 373 374
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
375
   * @param int $chunk_id
376
   *
Pawel G's avatar
Pawel G committed
377
   * @return string|false
Pawel G's avatar
Pawel G committed
378 379 380 381
   *   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.
382
   */
Pawel G's avatar
Pawel G committed
383 384 385
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
386 387

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
388 389
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
390
      }
Pawel G's avatar
Pawel G committed
391 392
      // Return sitemap if there is only one chunk.
      else {
Pawel G's avatar
Pawel G committed
393 394
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
395 396
        }
        return FALSE;
397 398
      }
    }
Pawel G's avatar
Pawel G committed
399 400
    // Return specific sitemap chunk.
    else {
Pawel G's avatar
Pawel G committed
401
      return $chunks[$chunk_id]->sitemap_string;
402
    }
403 404
  }

405 406
  /**
   * Generates the sitemap for all languages and saves it to the db.
407 408
   *
   * @param string $from
Pawel G's avatar
Pawel G committed
409 410
   *   Can be 'form', 'cron', 'drush' or 'nobatch'.
   *   This decides how the batch process is to be run.
411
   */
412
  public function generateSitemap($from = 'form') {
413 414 415 416
    $this->sitemapGenerator
      ->setGenerator($this)
      ->setGenerateFrom($from)
      ->startGeneration();
417 418
  }

419
  /**
420 421
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
422
   * @param array $chunks
Pawel G's avatar
Pawel G committed
423
   *   Sitemap chunks which to generate the index from.
424
   *
425
   * @return string
Pawel G's avatar
Pawel G committed
426
   *   The sitemap index.
427
   */
Pawel G's avatar
Pawel G committed
428
  private function getSitemapIndex($chunks) {
429 430
    return $this->sitemapGenerator
      ->setGenerator($this)
Pawel G's avatar
Pawel G committed
431
      ->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
432 433
  }

434
  /**
Pawel G's avatar
Pawel G committed
435
   * Returns a specific sitemap setting.
436 437
   *
   * @param string $name
Pawel G's avatar
Pawel G committed
438
   *   Name of the setting, like 'max_links'.
439
   *
440
   * @param mixed $default
Pawel G's avatar
Pawel G committed
441
   *   Value to be returned if the setting does not exist in the configuration.
442
   *
443
   * @return mixed
Pawel G's avatar
Pawel G committed
444
   *   The current setting from db or a default value.
445
   */
446
  public function getSetting($name, $default = FALSE) {
447
    $settings = $this->getConfig('settings');
448
    return isset($settings[$name]) ? $settings[$name] : $default;
449
  }
450

451
  /**
452 453
   * Saves a specific sitemap setting to db.
   *
Pawel G's avatar
Pawel G committed
454
   * @param string $name
Pawel G's avatar
Pawel G committed
455
   *   Setting name, like 'max_links'.
Pawel G's avatar
Pawel G committed
456
   * @param mixed $setting
Pawel G's avatar
Pawel G committed
457
   *   The setting to be saved.
Pawel G's avatar
Pawel G committed
458 459
   *
   * @return $this
460
   */
461 462
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
463
    $settings[$name] = $setting;
464
    $this->saveConfig('settings', $settings);
Pawel G's avatar
Pawel G committed
465
    return $this;
466
  }
467

Pawel G's avatar
Pawel G committed
468 469
  /**
   * Returns a 'time ago' string of last timestamp generation.
470
   *
Pawel G's avatar
Pawel G committed
471
   * @return string|false
Pawel G's avatar
Pawel G committed
472
   *   Formatted timestamp of last sitemap generation, otherwise FALSE.
Pawel G's avatar
Pawel G committed
473
   */
474
  public function getGeneratedAgo() {
475
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
476
    if (isset($chunks[1]->sitemap_created)) {
477
      return $this->dateFormatter
Pawel G's avatar
Pawel G committed
478
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
479 480 481
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
482

483 484 485 486
  /**
   * Returns objects of entity types that can be indexed by the sitemap.
   *
   * @return array
Pawel G's avatar
Pawel G committed
487
   *   Objects of entity types that can be indexed by the sitemap.
488
   */
489 490
  public function getSitemapEntityTypes() {
    $entity_types = $this->entityTypeManager->getDefinitions();
491 492 493 494 495 496 497 498

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

Pawel G's avatar
Pawel G committed
500 501 502 503
  /**
   * @param $entity_type_id
   * @return bool
   */
504
  public function entityTypeIsAtomic($entity_type_id) {
Pawel G's avatar
Pawel G committed
505 506
    // Menu fix.
    if ($entity_type_id == 'menu_link_content') {
507
      return FALSE;
Pawel G's avatar
Pawel G committed
508
    }
509
    $sitemap_entity_types = $this->getSitemapEntityTypes();
510 511 512 513 514 515
    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
516 517
    // todo: throw exception.
    return FALSE;
518
  }
Pawel G's avatar
Pawel G committed
519

520
}