Simplesitemap.php 7.42 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
use Drupal\Core\Config\ConfigFactoryInterface;
9

10 11
use Drupal\Core\Cache\Cache;

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

19
  private $config;
20 21
  private $sitemap;

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

33
  /**
34 35
   * Gets the entity_type_id and bundle_name of the form object if available and only
   * if the sitemap supports this entity type through an existing plugin.
36 37
   *
   * @param object $form_state
38
   * @param string $form_id
39
   *
40 41
   * @return array containing the entity_type_id and the bundle_name of the
   *  form object or FALSE if none found or not supported by an existing plugin.
42
   */
43
  public static function getSitemapFormEntityData($form_state, $form_id) {
44

Pawel G's avatar
Pawel G committed
45 46
    // Get all simple_sitemap plugins.
    $manager = \Drupal::service('plugin.manager.simple_sitemap');
47 48
    $plugins = $manager->getDefinitions();

Pawel G's avatar
Pawel G committed
49
    // Go through simple_sitemap plugins and check if one of them declares usage
50
    // of this particular form. If that's the case, get the entity type id of the
51 52 53 54 55 56 57
    // plugin definition and assume the bundle to be of the same name as the
    // entity type id.
    foreach($plugins as $plugin) {
      if (isset($plugin['form_id']) && $plugin['form_id'] === $form_id) {
        return array(
          'entity_type_id' => $plugin['id'],
          'bundle_name' => $plugin['id'],
58
          'entity_id' => NULL,
59 60 61 62
        );
      }
    }

63
    $form_entity = self::getFormEntity($form_state);
64
    if ($form_entity !== FALSE) {
65 66 67 68 69 70 71 72
      $entity_type = $form_entity->getEntityType();

      // If this entity is of a bundle, this will be an entity add/edit page.
      // If a simple_sitemap plugin of this entity_type exists, return the
      // entity type ID, the bundle name and ethe entity ID.
      if (!empty($entity_type->getBundleEntityType())) {
        $bundle_entity_type = $entity_type->getBundleEntityType();
        if (isset($plugins[$bundle_entity_type])) {
73
          return array(
74 75 76
            'entity_type_id' => $bundle_entity_type,
            'bundle_name' => $form_entity->bundle(),
            'entity_id' => $form_entity->Id(),
77 78 79
          );
        }
      }
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

      // Else if this entity has an entity type ID, it means it is a bundle
      // configuration form. If a simple_sitemap plugin of this entity_type
      // exists, return the entity type ID, the bundle name and ethe entity ID.
      else {
        $entity_type_id = $form_entity->getEntityTypeId();
        if (isset($plugins[$entity_type_id])) {
          if (!isset($plugins[$entity_type_id]['form_id'])
            || $plugins[$entity_type_id]['form_id'] === $form_id) {
            return array(
              'entity_type_id' => $entity_type_id,
              'bundle_name' => $form_entity->Id(),
              'entity_id' => NULL,
            );
          }
        }
      }
97 98
    }

99
    // If all methods of getting simple_sitemap entity data for this form
100 101 102 103 104 105 106 107 108 109 110 111
    // failed, return FALSE.
    return FALSE;
  }

  /**
   * Gets the object entity of the form if available.
   *
   * @param object $form_state
   *
   * @return object $entity or FALSE if non-existent or if form operation is
   *  'delete'.
   */
112
  private static function getFormEntity($form_state) {
113 114 115 116
    $form_object = $form_state->getFormObject();
    if (!is_null($form_object)
      && method_exists($form_state->getFormObject(), 'getEntity')
      && $form_object->getOperation() !== 'delete') {
117 118 119 120 121 122
      $entity = $form_state->getFormObject()->getEntity();
      return $entity;
    }
    return FALSE;
  }

123
  /**
124
   * Gets a specific sitemap configuration from the configuration storage.
125
   *
Pawel G's avatar
Pawel G committed
126 127
   * @param string $key
   *  Configuration key, like 'entity_links'.
128 129
   * @return mixed
   *  The requested configuration.
130
   */
131
  public function getConfig($key) {
132
    return $this->config->get($key);
133 134
  }

135
  /**
136
   * Saves a specific sitemap configuration to db.
137
   *
138 139 140 141
   * @param string $key
   *  Configuration key, like 'entity_links'.
   * @param mixed $value
   *  The configuration to be saved.
142
   */
143
  public function saveConfig($key, $value) {
Pawel G's avatar
Pawel G committed
144
    \Drupal::service('config.factory')->getEditable('simple_sitemap.settings')
145
      ->set($key, $value)->save();
146 147
  }

148 149 150 151 152 153 154 155 156 157 158
  /**
   * 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.
   */
159
  public function getSitemap($sitemap_id = NULL) {
160 161 162 163
    if (is_null($sitemap_id) || !isset($this->sitemap[$sitemap_id])) {

      // Return sitemap index, if there are multiple sitemap chunks.
      if (count($this->sitemap) > 1) {
164
        return $this->getSitemapIndex();
165 166 167 168
      }

      // Return sitemap if there is only one chunk.
      else {
169 170 171 172
        if (isset($this->sitemap[1])) {
          return $this->sitemap[1]->sitemap_string;
        }
        return FALSE;
173 174 175 176
      }
    }
    // Return specific sitemap chunk.
    else {
177
      return $this->sitemap[$sitemap_id]->sitemap_string;
178
    }
179 180
  }

181 182 183
  /**
   * Generates the sitemap for all languages and saves it to the db.
   */
184
  public function generateSitemap($from = 'form') {
185
    Cache::invalidateTags(array('simple_sitemap'));
Pawel G's avatar
Pawel G committed
186 187
    db_truncate('simple_sitemap')->execute();
    $generator = new SitemapGenerator($from);
188 189 190
    $generator->setCustomLinks($this->getConfig('custom'));
    $generator->setEntityTypes($this->getConfig('entity_types'));
    $generator->startBatch();
191 192
  }

193
  /**
194 195 196 197
   * Generates and returns the sitemap index as string.
   *
   * @return string
   *  The sitemap index.
198
   */
199
  private function getSitemapIndex() {
200
    $generator = new SitemapGenerator();
201
    return $generator->generateSitemapIndex($this->sitemap);
Pawel G's avatar
Pawel G committed
202 203
  }

204
  /**
205 206 207 208 209 210 211
   * 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.
212
   */
213 214
  public function getSetting($name) {
    $settings = $this->getConfig('settings');
215
    return isset($settings[$name]) ? $settings[$name] : FALSE;
216
  }
217

218
  /**
219 220 221 222 223 224
   * Saves a specific sitemap setting to db.
   *
   * @param $name
   *  Setting name, like 'max_links'.
   * @param $setting
   *  The setting to be saved.
225
   */
226 227
  public function saveSetting($name, $setting) {
    $settings = $this->getConfig('settings');
228
    $settings[$name] = $setting;
229
    $this->saveConfig('settings', $settings);
230
  }
231

Pawel G's avatar
Pawel G committed
232 233
  /**
   * Returns a 'time ago' string of last timestamp generation.
234
   *
Pawel G's avatar
Pawel G committed
235 236 237
   * @return mixed
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
238
  public function getGeneratedAgo() {
239
    if (isset($this->sitemap[1]->sitemap_created)) {
240
      return \Drupal::service('date.formatter')
241
        ->formatInterval(REQUEST_TIME - $this->sitemap[1]->sitemap_created);
242 243 244
    }
    return FALSE;
  }
Pawel G's avatar
Pawel G committed
245

246
  public static function getDefaultLangId() {
Pawel G's avatar
Pawel G committed
247 248
    return \Drupal::languageManager()->getDefaultLanguage()->getId();
  }
249
}