Simplesitemap.php 7.25 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @file
 * Contains \Drupal\simplesitemap\Simplesitemap.
 */

namespace Drupal\simplesitemap;

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

16
  private $config;
17 18 19
  private $sitemap;

  function __construct() {
20
    $this->initialize();
21 22
  }

23 24 25 26 27
  private function initialize() {
    $this->get_config_from_db();
    $this->get_sitemap_from_db();
  }

28
  /**
29 30
   * 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.
31 32
   *
   * @param object $form_state
33
   * @param string $form_id
34
   *
35 36
   * @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.
37
   */
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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
  public static function get_sitemap_form_entity_data($form_state, $form_id) {

    // Get all simplesitemap plugins.
    $manager = \Drupal::service('plugin.manager.simplesitemap');
    $plugins = $manager->getDefinitions();

    // Go through simplesitemap plugins and check if one of them declares usage
    // of this particular form. If that's the case, get entity type id of the
    // 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'],
        );
      }
    }

    // Else get entity type id and bundle name from the form if available and only
    // if a simplesitemap plugin of the same entity type exists.
    $form_entity = self::get_form_entity($form_state);
    if ($form_entity !== FALSE) {
      $form_entity_type_id = $form_entity->getEntityTypeId();
      if (isset($plugins[$form_entity_type_id])) {
        if (!isset($plugins[$form_entity_type_id]['form_id'])
          || $plugins[$form_entity_type_id]['form_id'] === $form_id) {
          return array(
            'entity_type_id' => $form_entity_type_id,
            'bundle_name' => $form_entity->Id(),
          );
        }
      }
    }

    // If both methods of getting simplesitemap entity data for this form
    // 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'.
   */
  private static function get_form_entity($form_state) {
    $form_object = $form_state->getFormObject();
    if (!is_null($form_object)
      && method_exists($form_state->getFormObject(), 'getEntity')
      && $form_object->getOperation() !== 'delete') {
91 92 93 94 95 96
      $entity = $form_state->getFormObject()->getEntity();
      return $entity;
    }
    return FALSE;
  }

97 98 99
  /**
   * Gets sitemap from db.
   */
100
  private function get_sitemap_from_db() {
101
    $this->sitemap = db_query("SELECT * FROM {simplesitemap}")->fetchAllAssoc('id');
102
  }
103

104
  /**
105
   * Gets sitemap settings from the configuration storage.
106
   */
107
  private function get_config_from_db() {
108 109 110
    $this->config = \Drupal::config('simplesitemap.settings');
  }

111
  /**
112
   * Gets a specific sitemap configuration from the configuration storage.
113 114 115
   *
   * @return mixed
   *  The requested configuration.
116
   */
117 118
  public function get_config($key) {
    return $this->config->get($key);
119 120
  }

121
  /**
122
   * Saves a specific sitemap configuration to db.
123
   *
124 125 126 127
   * @param string $key
   *  Configuration key, like 'entity_links'.
   * @param mixed $value
   *  The configuration to be saved.
128
   */
129
  public function save_config($key, $value) {
130 131
    \Drupal::service('config.factory')->getEditable('simplesitemap.settings')
      ->set($key, $value)->save();
132
    $this->initialize();
133 134
  }

135 136 137 138 139 140 141 142 143 144 145
  /**
   * 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.
   */
146
  public function get_sitemap($sitemap_id = NULL) {
147 148 149
    if (empty($this->sitemap)) {
      $this->generate_sitemap();
    }
150 151 152 153 154 155 156 157 158 159

    if (is_null($sitemap_id) || !isset($this->sitemap[$sitemap_id])) {

      // Return sitemap index, if there are multiple sitemap chunks.
      if (count($this->sitemap) > 1) {
        return $this->get_sitemap_index();
      }

      // Return sitemap if there is only one chunk.
      else {
160
        return $this->sitemap[0]->sitemap_string;
161 162 163 164 165
      }
    }

    // Return specific sitemap chunk.
    else {
166
      return $this->sitemap[$sitemap_id]->sitemap_string;
167
    }
168 169
  }

170 171 172
  /**
   * Generates the sitemap for all languages and saves it to the db.
   */
173
  public function generate_sitemap() {
174
    $generator = new SitemapGenerator();
175 176 177
    $generator->set_custom_links($this->get_config('custom'));
    $generator->set_entity_types($this->get_config('entity_types'));
    $this->sitemap = $generator->generate_sitemap($this->get_setting('max_links'));
178
    $this->save_sitemap();
179 180
    drupal_set_message(t("The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.",
      array('@url' => $GLOBALS['base_url'] . '/sitemap.xml')));
181 182
  }

183 184 185
  /**
   * Saves the sitemap to the db.
   */
186
  private function save_sitemap() {
187 188
    db_truncate('simplesitemap')->execute();
    $values = array();
189
    foreach($this->sitemap as $chunk_id => $chunk_data) {
190
      $values[] = array(
191 192
        'id' => $chunk_id,
        'sitemap_string' => $chunk_data->sitemap_string,
193
        'sitemap_created' =>  $chunk_data->sitemap_created,
194 195 196
      );
    }

197
    $query = db_insert('simplesitemap')
198
      ->fields(array('id', 'sitemap_string', 'sitemap_created'));
199 200 201 202 203 204
    foreach ($values as $record) {
      $query->values($record);
    }
    $query->execute();
  }

205
  /**
206 207 208 209
   * Generates and returns the sitemap index as string.
   *
   * @return string
   *  The sitemap index.
210
   */
211 212 213
  private function get_sitemap_index() {
    $generator = new SitemapGenerator();
    return $generator->generate_sitemap_index($this->sitemap);
gbyte.co's avatar
gbyte.co committed
214 215
  }

216
  /**
217 218 219 220 221 222 223
   * 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.
224
   */
225 226 227
  public function get_setting($name) {
    $settings = $this->get_config('settings');
    return isset($settings[$name]) ? $settings[$name] : FALSE;
228
  }
229

230
  /**
231 232 233 234 235 236
   * Saves a specific sitemap setting to db.
   *
   * @param $name
   *  Setting name, like 'max_links'.
   * @param $setting
   *  The setting to be saved.
237
   */
238 239 240 241
  public function save_setting($name, $setting) {
    $settings = $this->get_config('settings');
    $settings[$name] = $setting;
    $this->save_config('settings', $settings);
242
  }
243

gbyte.co's avatar
gbyte.co committed
244 245
  /**
   * Returns a 'time ago' string of last timestamp generation.
246
   *
gbyte.co's avatar
gbyte.co committed
247 248 249
   * @return mixed
   *  Formatted timestamp of last sitemap generation, otherwise FALSE.
   */
250 251 252 253 254 255 256
  public function get_generated_ago() {
    if (isset($this->sitemap[0]->sitemap_created)) {
      return \Drupal::service('date.formatter')
        ->formatInterval(REQUEST_TIME - $this->sitemap[0]->sitemap_created);
    }
    return FALSE;
  }
257
}