Simplesitemap.php 12.2 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\Entity\ContentEntityTypeInterface;
7
use Drupal\simple_sitemap\Form;
8

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

16
  private $config_factory;
17
  private $config;
18 19 20
  private static $allowed_link_settings = [
    'entity' => ['index', 'priority'],
    'custom' => ['priority']];
21

22 23 24 25 26 27 28
  /**
   * Simplesitemap constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory from the container.
   */
  function __construct(ConfigFactoryInterface $config_factory) {
29 30
    $this->config_factory = $config_factory;
    $this->config = $this->config_factory->get('simple_sitemap.settings');
31 32
  }

33
  /**
34
   * Gets a specific sitemap configuration from the configuration storage.
35
   *
Pawel G's avatar
Pawel G committed
36
   * @param string $key
37
   *  Configuration key, like 'entity_types'.
38 39
   * @return mixed
   *  The requested configuration.
40
   */
41
  public function getConfig($key) {
42
    return $this->config->get($key);
43 44
  }

Pawel G's avatar
Pawel G committed
45
  private function fetchSitemapChunks() {
46 47 48 49 50
    return \Drupal::service('database')
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

51
  /**
52
   * Saves a specific sitemap configuration to db.
53
   *
54
   * @param string $key
55
   *  Configuration key, like 'entity_types'.
56 57
   * @param mixed $value
   *  The configuration to be saved.
58
   */
59
  public function saveConfig($key, $value) {
60
    $this->config_factory->getEditable('simple_sitemap.settings')
61
      ->set($key, $value)->save();
62 63
    // Refresh config object after making changes.
    $this->config = $this->config_factory->get('simple_sitemap.settings');
64 65
  }

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
  /**
   * 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);
      return TRUE;
    }
    return FALSE;
  }

  /**
   * 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);
      return TRUE;
    }
    return FALSE;
  }

  /**
   * 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]
   */
  public function setBundleSettings($entity_type_id, $bundle_name = NULL, $settings) {
122
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
123
    $entity_types = $this->getConfig('entity_types');
124
    $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]);
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    $this->saveConfig('entity_types', $entity_types);
  }

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

  public static function getBundleEntityTypeId($entity) {
    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');
    $entity = \Drupal::entityTypeManager()->getStorage($entity_type_id)->load($id);
    $bundle_name = self::getEntityInstanceBundleName($entity);
    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.
153
        $this->addLinkSettings('entity', $settings, $entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
154 155 156 157 158 159 160 161 162 163
      }
      else { // Else unset override.
        unset($entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
      }
      $this->saveConfig('entity_types', $entity_types);
      return TRUE;
    }
    return FALSE;
  }

164 165
  public function getBundleSettings($entity_type_id, $bundle_name = NULL) {
    $bundle_name = is_null($bundle_name) ? $entity_type_id : $bundle_name;
166 167 168 169 170 171 172 173 174
    $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;
  }

175
  public function bundleIsIndexed($entity_type_id, $bundle_name = NULL) {
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    $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');
    $entity = \Drupal::entityTypeManager()->getStorage($entity_type_id)->load($id);
    $bundle_name = self::getEntityInstanceBundleName($entity);
    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);
    }
  }

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  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);
    return TRUE;
  }

  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);
        return TRUE;
      }
    }
    return FALSE;
  }

  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':
            if (!Form::isValidPriority($setting)) {
              // todo: register error
              continue;
            }
            break;
          //todo: add index check
        }
        $target[$setting_key] = $setting;
      }

    }
  }

261 262 263 264
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
Pawel G's avatar
Pawel G committed
265
   * @param int $chunk_id
266 267 268 269 270 271
   *
   * @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
272 273 274
  public function getSitemap($chunk_id = NULL) {
    $chunks = $this->fetchSitemapChunks();
    if (is_null($chunk_id) || !isset($chunks[$chunk_id])) {
275 276

      // Return sitemap index, if there are multiple sitemap chunks.
Pawel G's avatar
Pawel G committed
277 278
      if (count($chunks) > 1) {
        return $this->getSitemapIndex($chunks);
279
      }
280
      else { // Return sitemap if there is only one chunk.
Pawel G's avatar
Pawel G committed
281 282
        if (isset($chunks[1])) {
          return $chunks[1]->sitemap_string;
283 284
        }
        return FALSE;
285 286
      }
    }
287
    else { // Return specific sitemap chunk.
Pawel G's avatar
Pawel G committed
288
      return $chunks[$chunk_id]->sitemap_string;
289
    }
290 291
  }

292 293
  /**
   * Generates the sitemap for all languages and saves it to the db.
294 295
   *
   * @param string $from
296 297
   *  Can be 'form', 'cron', 'drush' or 'nobatch'.
   *  This decides how the batch process is to be run.
298
   */
299
  public function generateSitemap($from = 'form') {
300 301 302
    $generator = new SitemapGenerator($this);
    $generator->setGenerateFrom($from);
    $generator->startGeneration();
303 304
  }

305
  /**
306 307
   * Generates and returns the sitemap index as string.
   *
Pawel G's avatar
Pawel G committed
308
   * @param array $chunks
309 310
   *  Sitemap chunks which to generate the index from.
   *
311 312
   * @return string
   *  The sitemap index.
313
   */
Pawel G's avatar
Pawel G committed
314
  private function getSitemapIndex($chunks) {
315
    $generator = new SitemapGenerator($this);
Pawel G's avatar
Pawel G committed
316
    return $generator->generateSitemapIndex($chunks);
Pawel G's avatar
Pawel G committed
317 318
  }

319
  /**
320 321 322 323 324 325 326
   * 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.
327
   */
328 329
  public function getSetting($name) {
    $settings = $this->getConfig('settings');
330
    return isset($settings[$name]) ? $settings[$name] : FALSE;
331
  }
332

333
  /**
334 335 336 337 338 339
   * Saves a specific sitemap setting to db.
   *
   * @param $name
   *  Setting name, like 'max_links'.
   * @param $setting
   *  The setting to be saved.
340
   */
341 342
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
343
    $settings[$name] = $setting;
344
    $this->saveConfig('settings', $settings);
345
  }
346

Pawel G's avatar
Pawel G committed
347 348
  /**
   * Returns a 'time ago' string of last timestamp generation.
349
   *
Pawel G's avatar
Pawel G committed
350 351 352
   * @return mixed
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
353
  public function getGeneratedAgo() {
354
    $chunks = $this->fetchSitemapChunks();
Pawel G's avatar
Pawel G committed
355
    if (isset($chunks[1]->sitemap_created)) {
356
      return \Drupal::service('date.formatter')
Pawel G's avatar
Pawel G committed
357
        ->formatInterval(REQUEST_TIME - $chunks[1]->sitemap_created);
358 359 360
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
361

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  /**
   * 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.
   */
  public static function getSitemapEntityTypes() {
    $entity_types = \Drupal::entityTypeManager()->getDefinitions();

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

379
  public static function entityTypeIsAtomic($entity_type_id) {
380 381 382 383 384 385 386 387 388 389 390
    if ($entity_type_id == 'menu_link_content') // Menu fix.
      return FALSE;
    $sitemap_entity_types = self::getSitemapEntityTypes();
    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
  }
391
}