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

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

5
use Drupal\Core\Config\ConfigFactoryInterface;
6
use Drupal\Core\Database\Database;
7
use Drupal\Core\Entity\ContentEntityTypeInterface;
8
use Drupal\Core\Entity\EntityTypeManager;
9

10 11
/**
 * Simplesitemap class.
12 13
 *
 * Main module class.
14 15 16
 */
class Simplesitemap {

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

25 26 27
  /**
   * Simplesitemap constructor.
   *
28
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactoryInterface
29
   *   The config factory from the container.
30 31 32
   *
   * @param $database
   *   The database from the container.
33
   */
34 35 36 37 38 39 40 41 42
  function __construct(
    ConfigFactoryInterface $configFactoryInterface,
    $database,
    EntityTypeManager $entityTypeManager) {

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

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

Pawel G's avatar
Pawel G committed
57
  private function fetchSitemapChunks() {
58
    return $this->db
59 60 61 62
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

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

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
  /**
   * 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'.
   *
   * @return bool
   *  TRUE if entity type has been enabled, FALSE if it was not.
   */
  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
99
    return $this;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
  }

  /**
   * 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'.
   *
   * @return bool
   *  TRUE if entity type has been disabled, FALSE if it was not.
   */
  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
119
    return $this;
120 121 122 123 124 125 126 127 128 129 130 131 132
  }

  /**
   * Sets sitemap settings for a bundle less entity type (e.g. user) or a bundle
   * 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
133 134
   *
   * @return $this
135 136
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
137
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
138
    $entity_types = $this->getConfig('entity_types');
139
    $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]);
140
    $this->saveConfig('entity_types', $entity_types);
Pawel G's avatar
Pawel G committed
141
    return $this;
142 143
  }

144
  public function getEntityInstanceBundleName($entity) {
145 146 147 148
    return $entity->getEntityTypeId() == 'menu_link_content'
      ? $entity->getMenuName() : $entity->bundle(); // Menu fix.
  }

149
  public function getBundleEntityTypeId($entity) {
150 151 152 153 154 155
    return $entity->getEntityTypeId() == 'menu'
      ? 'menu_link_content' : $entity->getEntityType()->getBundleOf(); // Menu fix.
  }

  public function setEntityInstanceSettings($entity_type_id, $id, $settings) {
    $entity_types = $this->getConfig('entity_types');
156 157
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
158 159 160 161 162 163 164 165 166 167 168
    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.
169
        $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
170 171 172 173 174 175
      }
      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
176
    return $this;
177 178
  }

179 180
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
181 182 183 184 185 186 187 188 189
    $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;
  }

190
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
191 192 193 194 195 196 197 198 199 200 201
    $settings = $this->getBundleSettings($entity_type_id, $bundle_name);
    return !empty($settings['index']);
  }

  public function entityTypeIsEnabled($entity_type_id) {
    $entity_types = $this->getConfig('entity_types');
    return isset($entity_types[$entity_type_id]);
  }

  public function getEntityInstanceSettings($entity_type_id, $id) {
    $entity_types = $this->getConfig('entity_types');
202 203
    $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($id);
    $bundle_name = $this->getEntityInstanceBundleName($entity);
204 205 206 207 208 209 210 211
    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);
    }
  }

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  public function addCustomLink($path, $settings) {
    if (!\Drupal::service('path.validator')->isValid($path))
      return FALSE; // todo: log error
    if ($path[0] != '/')
      return FALSE; // todo: log error
    $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
228
    return $this;
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
  }

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

  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
250
    return $this;
251 252 253 254 255 256 257 258 259 260 261
  }

  public function removeCustomLinks() {
    $this->saveConfig('custom', []);
  }

  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':
262
            if (Form::isValidPriority($setting)) {
263 264 265 266 267 268 269 270 271 272 273
              // todo: register error
              continue;
            }
            break;
          //todo: add index check
        }
        $target[$setting_key] = $setting;
      }
    }
  }

274 275 276 277
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
278
   * @param int $chunk_id
279 280 281 282 283 284
   *
   * @return string $sitemap
   *  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
285 286 287
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
288 289

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
290 291
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
292
      }
293
      else { // Return sitemap if there is only one chunk.
Pawel G's avatar
Pawel G committed
294 295
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
296 297
        }
        return FALSE;
298 299
      }
    }
300
    else { // Return specific sitemap chunk.
Pawel G's avatar
Pawel G committed
301
      return $chunks[$chunk_id]->sitemap_string;
302
    }
303 304
  }

305 306
  /**
   * Generates the sitemap for all languages and saves it to the db.
307 308
   *
   * @param string $from
309 310
   *  Can be 'form', 'cron', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
311
   */
312
  public function generateSitemap($from = 'form') {
Pawel G's avatar
Pawel G committed
313 314 315
    \Drupal::service('simple_sitemap.sitemap_generator')
    ->setGenerateFrom($from)
    ->startGeneration();
316 317
  }

318
  /**
319 320
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
321
   * @param array $chunks
322 323
   *  Sitemap chunks which to generate the index from.
   *
324 325
   * @return string
   *  The sitemap index.
326
   */
Pawel G's avatar
Pawel G committed
327
  private function getSitemapIndex($chunks) {
Pawel G's avatar
Pawel G committed
328 329
    return \Drupal::service('simple_sitemap.sitemap_generator')
      ->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
330 331
  }

332
  /**
333 334 335 336 337 338 339
   * Gets a specific sitemap setting.
   *
   * @param string $name
   *  Name of the setting, like 'max_links'.
   *
   * @return mixed
   *  The current setting from db or FALSE if setting does not exist.
340
   */
341 342
  public function getSetting($name) {
    $settings = $this->getConfig('settings');
343
    return isset($settings[$name]) ? $settings[$name] : FALSE;
344
  }
345

346
  /**
347 348 349 350 351 352
   * Saves a specific sitemap setting to db.
   *
   * @param $name
   *  Setting name, like 'max_links'.
   * @param $setting
   *  The setting to be saved.
Pawel G's avatar
Pawel G committed
353 354
   *
   * @return $this
355
   */
356 357
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
358
    $settings[$name] = $setting;
359
    $this->saveConfig('settings', $settings);
Pawel G's avatar
Pawel G committed
360
    return $this;
361
  }
362

Pawel G's avatar
Pawel G committed
363 364
  /**
   * Returns a 'time ago' string of last timestamp generation.
365
   *
Pawel G's avatar
Pawel G committed
366 367 368
   * @return mixed
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
369
  public function getGeneratedAgo() {
370
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
371
    if (isset($chunks[1]->sitemap_created)) {
372
      return \Drupal::service('date.formatter')
Pawel G's avatar
Pawel G committed
373
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
374 375 376
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
377

378 379 380 381 382 383
  /**
   * 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.
   */
384 385
  public function getSitemapEntityTypes() {
    $entity_types = $this->entityTypeManager->getDefinitions();
386 387 388 389 390 391 392 393

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

395
  public function entityTypeIsAtomic($entity_type_id) {
396 397
    if ($entity_type_id == 'menu_link_content') // Menu fix.
      return FALSE;
398
    $sitemap_entity_types = $this->getSitemapEntityTypes();
399 400 401 402 403 404 405 406
    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
  }
407
}