Simplesitemap.php 10.5 KB
Newer Older
1 2 3
<?php
/**
 * @file
Pawel G's avatar
Pawel G committed
4
 * Contains \Drupal\simple_sitemap\Simplesitemap.
5 6
 */

Pawel G's avatar
Pawel G committed
7
namespace Drupal\simple_sitemap;
8

9
use Drupal\Core\Config\ConfigFactoryInterface;
10
use Drupal\Core\Entity\ContentEntityTypeInterface;
11
use Drupal\simple_sitemap\Form;
12

13 14
/**
 * Simplesitemap class.
15 16
 *
 * Main module class.
17 18 19
 */
class Simplesitemap {

20
  private $config;
21 22
  private $sitemap;

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

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

46 47 48 49 50 51
  private function fetchSitemap() {
    return \Drupal::service('database')
      ->query("SELECT * FROM {simple_sitemap}")
      ->fetchAllAssoc('id');
  }

52
  /**
53
   * Saves a specific sitemap configuration to db.
54
   *
55
   * @param string $key
56
   *  Configuration key, like 'entity_types'.
57 58
   * @param mixed $value
   *  The configuration to be saved.
59
   */
60
  public function saveConfig($key, $value) {
61
    $this->config_factory->getEditable('simple_sitemap.settings')
62
      ->set($key, $value)->save();
63 64
    // Refresh config object after making changes.
    $this->config = $this->config_factory->get('simple_sitemap.settings');
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 122 123 124 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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  /**
   * 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) {
    $bundle_name = !empty($bundle_name) ? $bundle_name : $entity_type_id;
    $entity_types = $this->getConfig('entity_types');
    foreach($settings as $key => $setting) {
      $entity_types[$entity_type_id][$bundle_name][$key] = $setting;
    }
    $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.
        foreach($settings as $key => $setting) {
          $entity_types[$entity_type_id][$bundle_name]['entities'][$id][$key] = $setting;
        }
      }
      else { // Else unset override.
        unset($entity_types[$entity_type_id][$bundle_name]['entities'][$id]);
      }
      $this->saveConfig('entity_types', $entity_types);
      return TRUE;
    }
    return FALSE;
  }

  public function getBundleSettings($entity_type_id, $bundle_name) {
    $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;
  }

  public function bundleIsIndexed($entity_type_id, $bundle_name) {
    $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);
    }
  }

201 202 203 204 205 206 207 208 209 210 211
  /**
   * Returns the whole sitemap, a requested sitemap chunk,
   * or the sitemap index file.
   *
   * @param int $sitemap_id
   *
   * @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.
   */
212
  public function getSitemap($sitemap_id = NULL) {
213 214
    $sitemap = $this->fetchSitemap();
    if (is_null($sitemap_id) || !isset($sitemap[$sitemap_id])) {
215 216

      // Return sitemap index, if there are multiple sitemap chunks.
217 218
      if (count($sitemap) > 1) {
        return $this->getSitemapIndex($sitemap);
219 220
      }

221 222 223
      else { // Return sitemap if there is only one chunk.
        if (isset($sitemap[1])) {
          return $sitemap[1]->sitemap_string;
224 225
        }
        return FALSE;
226 227
      }
    }
228 229
    else { // Return specific sitemap chunk.
      return $sitemap[$sitemap_id]->sitemap_string;
230
    }
231 232
  }

233 234
  /**
   * Generates the sitemap for all languages and saves it to the db.
235 236 237 238
   *
   * @param string $from
   *  Can be 'form', 'cron', or 'drush'. This decides how to the batch process
   *  is to be run.
239
   */
240
  public function generateSitemap($from = 'form') {
Pawel G's avatar
Pawel G committed
241
    $generator = new SitemapGenerator($from);
242 243 244
    $generator->setCustomLinks($this->getConfig('custom'));
    $generator->setEntityTypes($this->getConfig('entity_types'));
    $generator->startBatch();
245 246
  }

247
  /**
248 249
   * Generates and returns the sitemap index as string.
   *
250 251 252
   * @param array $sitemap
   *  Sitemap chunks which to generate the index from.
   *
253 254
   * @return string
   *  The sitemap index.
255
   */
256
  private function getSitemapIndex($sitemap) {
257
    $generator = new SitemapGenerator();
258
    return $generator->generateSitemapIndex($sitemap);
Pawel G's avatar
Pawel G committed
259 260
  }

261
  /**
262 263 264 265 266 267 268
   * 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.
269
   */
270 271
  public function getSetting($name) {
    $settings = $this->getConfig('settings');
272
    return isset($settings[$name]) ? $settings[$name] : FALSE;
273
  }
274

275
  /**
276 277 278 279 280 281
   * Saves a specific sitemap setting to db.
   *
   * @param $name
   *  Setting name, like 'max_links'.
   * @param $setting
   *  The setting to be saved.
282
   */
283 284
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
285
    $settings[$name] = $setting;
286
    $this->saveConfig('settings', $settings);
287
  }
288

Pawel G's avatar
Pawel G committed
289 290
  /**
   * Returns a 'time ago' string of last timestamp generation.
291
   *
Pawel G's avatar
Pawel G committed
292 293 294
   * @return mixed
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
295
  public function getGeneratedAgo() {
296 297
    $sitemap = $this->fetchSitemap();
    if (isset($sitemap[1]->sitemap_created)) {
298
      return \Drupal::service('date.formatter')
299
        ->formatInterval(REQUEST_TIME - $sitemap[1]->sitemap_created);
300 301 302
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
303

304
  public static function getDefaultLangId() {
Pawel G's avatar
Pawel G committed
305 306
    return \Drupal::languageManager()->getDefaultLanguage()->getId();
  }
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

  /**
   * 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]);
        continue;
      }
    }
    return $entity_types;
  }
325

326
  public static function entityTypeIsAtomic($entity_type_id) {
327 328 329 330 331 332 333 334 335 336 337 338
    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;
    }
    return FALSE; //todo: throw exception
  }
339
}