SitemapGenerator.php 10.6 KB
Newer Older
1 2
<?php

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

Pawel G's avatar
Pawel G committed
5
use XMLWriter;
Pawel G's avatar
Pawel G committed
6 7 8 9
use Drupal\simple_sitemap\Batch\Batch;
use Drupal\Core\Database\Connection;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Language\LanguageManagerInterface;
10 11

/**
Pawel G's avatar
Pawel G committed
12
 * Class SitemapGenerator
Pawel G's avatar
Pawel G committed
13
 * @package Drupal\simple_sitemap
14 15 16 17 18
 */
class SitemapGenerator {

  const XML_VERSION = '1.0';
  const ENCODING = 'UTF-8';
19 20
  const XMLNS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
  const XMLNS_XHTML = 'http://www.w3.org/1999/xhtml';
21
  const GENERATED_BY = 'Generated by the Simple XML sitemap Drupal module: https://drupal.org/project/simple_sitemap.';
22
  const FIRST_CHUNK_INDEX = 1;
23
  const XMLNS_IMAGE = 'http://www.google.com/schemas/sitemap-image/1.1';
24

Pawel G's avatar
Pawel G committed
25 26 27
  /**
   * @var \Drupal\simple_sitemap\Batch\Batch
   */
28
  protected $batch;
Pawel G's avatar
Pawel G committed
29 30 31 32

  /**
   * @var \Drupal\simple_sitemap\EntityHelper
   */
33
  protected $entityHelper;
Pawel G's avatar
Pawel G committed
34 35 36 37

  /**
   * @var \Drupal\Core\Database\Connection
   */
38
  protected $db;
Pawel G's avatar
Pawel G committed
39 40

  /**
Pawel G's avatar
Pawel G committed
41
   * @var \Drupal\Core\Language\LanguageManagerInterface
Pawel G's avatar
Pawel G committed
42
   */
Pawel G's avatar
Pawel G committed
43
  protected $languageManager;
Pawel G's avatar
Pawel G committed
44 45

  /**
Pawel G's avatar
Pawel G committed
46
   * @var \Drupal\Core\Extension\ModuleHandler
Pawel G's avatar
Pawel G committed
47
   */
Pawel G's avatar
Pawel G committed
48
  protected $moduleHandler;
Pawel G's avatar
Pawel G committed
49 50 51 52

  /**
   * @var string
   */
53
  protected $generateFrom = 'form';
Pawel G's avatar
Pawel G committed
54 55 56 57

  /**
   * @var bool
   */
58
  protected $isHreflangSitemap;
Pawel G's avatar
Pawel G committed
59 60 61 62

  /**
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
63
  protected $generator;
64

Pawel G's avatar
Pawel G committed
65 66 67
  /**
   * @var array
   */
68 69 70 71 72 73
  protected static $attributes = [
    'xmlns' => self::XMLNS,
    'xmlns:xhtml' => self::XMLNS_XHTML,
    'xmlns:image' => self::XMLNS_IMAGE,
  ];

Pawel G's avatar
Pawel G committed
74 75 76
  /**
   * @var array
   */
77 78 79 80
  protected static $indexAttributes = [
    'xmlns' => self::XMLNS,
  ];

81 82
  /**
   * SitemapGenerator constructor.
Pawel G's avatar
Pawel G committed
83
   * @param \Drupal\simple_sitemap\Batch\Batch $batch
84
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
Pawel G's avatar
Pawel G committed
85 86 87
   * @param \Drupal\Core\Database\Connection $database
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
88
   */
Pawel G's avatar
Pawel G committed
89 90
  public function __construct(
    Batch $batch,
91
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
92 93
    Connection $database,
    ModuleHandler $module_handler,
94
    LanguageManagerInterface $language_manager
Pawel G's avatar
Pawel G committed
95
  ) {
96
    $this->batch = $batch;
97
    $this->entityHelper = $entityHelper;
98
    $this->db = $database;
99
    $this->moduleHandler = $module_handler;
Pawel G's avatar
Pawel G committed
100 101 102 103 104 105 106 107 108 109 110 111 112
    $this->languageManager = $language_manager;
    $this->setIsHreflangSitemap();
  }

  protected function setIsHreflangSitemap() {
    $this->isHreflangSitemap = count($this->languageManager->getLanguages()) > 1;
  }

  /**
   * @return bool
   */
  public function isHreflangSitemap() {
    return $this->isHreflangSitemap;
113 114 115
  }

  /**
Pawel G's avatar
Pawel G committed
116
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
117 118
   * @return $this
   */
Pawel G's avatar
Pawel G committed
119
  public function setGenerator(Simplesitemap $generator) {
120 121
    $this->generator = $generator;
    return $this;
122 123
  }

Pawel G's avatar
Pawel G committed
124
  /**
Pawel G's avatar
Pawel G committed
125
   * @param string $from
126
   * @return $this
Pawel G's avatar
Pawel G committed
127
   */
Pawel G's avatar
Pawel G committed
128 129
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
130
    return $this;
131 132
  }

133
  /**
134
   * Adds all operations to the batch and starts it.
135
   */
136
  public function startGeneration() {
137
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
138
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
139
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
140
        ? $this->generator->getSetting('batch_process_limit') : NULL,
141 142 143
      'max_links' => $this->generator->getSetting('max_links', 2000),
      'skip_untranslated' => $this->generator->getSetting('skip_untranslated', FALSE),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates', TRUE),
144
      'entity_types' => $this->generator->getBundleSettings(),
145
      'base_url' => $this->generator->getSetting('base_url', ''),
146
    ]);
147

Pawel G's avatar
Pawel G committed
148
    // Add custom link generating operation.
149
    $this->batch->addOperation('simple_sitemap.custom_url_generator', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
150 151

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
152
    foreach ($this->getEntityTypeData() as $data) {
153 154 155 156 157 158 159 160
      $this->batch->addOperation('simple_sitemap.entity_url_generator', $data);
    }

    // Add arbitrary links generating operation.
    $arbitrary_links = [];
    $this->moduleHandler->alter('simple_sitemap_arbitrary_links', $arbitrary_links);
    if (!empty($arbitrary_links)) {
      $this->batch->addOperation('simple_sitemap.arbitrary_url_generator', $arbitrary_links);
Pawel G's avatar
Pawel G committed
161
    }
162

163
    $this->batch->start();
Pawel G's avatar
Pawel G committed
164 165 166
  }

  /**
Pawel G's avatar
Pawel G committed
167
   * Returns a batch-ready data array for custom link generation.
168
   *
Pawel G's avatar
Pawel G committed
169
   * @return array
Pawel G's avatar
Pawel G committed
170
   *   Data to be processed.
Pawel G's avatar
Pawel G committed
171
   */
172
  protected function getCustomUrlsData() {
173
    $paths = [];
174
    foreach ($this->generator->getCustomLinks() as $i => $custom_path) {
175 176
      $paths[$i]['path'] = $custom_path['path'];
      $paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
177
      $paths[$i]['changefreq'] = isset($custom_path['changefreq']) ? $custom_path['changefreq'] : NULL;
178 179
    }
    return $paths;
Pawel G's avatar
Pawel G committed
180
  }
181

Pawel G's avatar
Pawel G committed
182
  /**
183
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
184
   * and returns an array of batch-ready data sets for entity link generation.
185
   *
Pawel G's avatar
Pawel G committed
186
   * @return array
Pawel G's avatar
Pawel G committed
187
   */
188
  protected function getEntityTypeData() {
Pawel G's avatar
Pawel G committed
189
    $data_sets = [];
Pawel G's avatar
Pawel G committed
190
    $sitemap_entity_types = $this->entityHelper->getSupportedEntityTypes();
191
    $entity_types = $this->generator->getBundleSettings();
Pawel G's avatar
Pawel G committed
192
    foreach ($entity_types as $entity_type_name => $bundles) {
193 194
      if (isset($sitemap_entity_types[$entity_type_name])) {
        $keys = $sitemap_entity_types[$entity_type_name]->getKeys();
Pawel G's avatar
Pawel G committed
195

Pawel G's avatar
Pawel G committed
196 197
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
Pawel G's avatar
Pawel G committed
198

Pawel G's avatar
Pawel G committed
199
        foreach ($bundles as $bundle_name => $bundle_settings) {
200
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
201 202 203 204 205
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
206 207
            ];
          }
Pawel G's avatar
Pawel G committed
208
        }
209 210
      }
    }
Pawel G's avatar
Pawel G committed
211
    return $data_sets;
Pawel G's avatar
Pawel G committed
212 213 214
  }

  /**
215 216
   * Wrapper method which takes links along with their options and then
   * generates and saves the sitemap.
Pawel G's avatar
Pawel G committed
217
   *
218
   * @param array $links
Pawel G's avatar
Pawel G committed
219
   *   All links with their multilingual versions and settings.
220
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
221
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
222
   */
Pawel G's avatar
Pawel G committed
223
  public function generateSitemap(array $links, $remove_sitemap = FALSE) {
Pawel G's avatar
Pawel G committed
224
    $values = [
225 226 227
      'id' => $remove_sitemap ? self::FIRST_CHUNK_INDEX
        : $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')
          ->fetchField() + 1,
228
      'sitemap_string' => $this->generateSitemapChunk($links),
229
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
230
    ];
231
    if ($remove_sitemap) {
232
      $this->db->truncate('simple_sitemap')->execute();
233
    }
234
    $this->db->insert('simple_sitemap')->fields($values)->execute();
235 236
  }

237
  /**
238
   * Generates and returns the sitemap index for all sitemap chunks.
239
   *
Pawel G's avatar
Pawel G committed
240 241
   * @param array $chunk_info
   *   Array containing chunk creation timestamps keyed by chunk ID.
242 243 244
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
245
  public function generateSitemapIndex(array $chunk_info) {
246 247 248 249
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
250
    $writer->writeComment(self::GENERATED_BY);
251 252
    $writer->startElement('sitemapindex');

253 254 255 256 257 258 259
    // Add attributes to document.
    $this->moduleHandler->alter('simple_sitemap_index_attributes', self::$indexAttributes);
    foreach (self::$indexAttributes as $name => $value) {
      $writer->writeAttribute($name, $value);
    }

    // Add sitemap locations to document.
Pawel G's avatar
Pawel G committed
260
    foreach ($chunk_info as $chunk_id => $chunk_data) {
261
      $writer->startElement('sitemap');
262
      $writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
263
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
264 265
      $writer->endElement();
    }
266

267 268 269 270 271
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

272 273 274
  /**
   * @return string
   */
275 276 277 278 279
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

280 281 282
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
283
   * @param array $links
Pawel G's avatar
Pawel G committed
284
   *   All links with their multilingual versions and settings.
285
   *
Pawel G's avatar
Pawel G committed
286
   * @return string
Pawel G's avatar
Pawel G committed
287
   *   Sitemap chunk
288
   */
289
  protected function generateSitemapChunk(array $links) {
290 291 292 293
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
294
    $writer->writeComment(self::GENERATED_BY);
295
    $writer->startElement('urlset');
Pawel G's avatar
Pawel G committed
296

297 298 299 300 301 302 303
    // Add attributes to document.
    if (!$this->isHreflangSitemap()) {
      unset(self::$attributes['xmlns:xhtml']);
    }
    $this->moduleHandler->alter('simple_sitemap_attributes', self::$attributes);
    foreach (self::$attributes as $name => $value) {
      $writer->writeAttribute($name, $value);
304
    }
305

306 307
    // Add URLs to document.
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
308
    foreach ($links as $link) {
309

310
      // Add each translation variant URL as location to the sitemap.
311 312 313
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

314 315 316
      // If more than one language is enabled, add all translation variant URLs
      // as alternate links to this location turning the sitemap into a hreflang
      // sitemap.
317
      if (isset($link['alternate_urls']) && $this->isHreflangSitemap()) {
Pawel G's avatar
Pawel G committed
318
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
319 320 321 322 323 324
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
325
      }
326

327 328
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
329 330
        $writer->writeElement('lastmod', $link['lastmod']);
      }
331

332 333 334 335
      // Add changefreq if any.
      if (isset($link['changefreq'])) {
        $writer->writeElement('changefreq', $link['changefreq']);
      }
336 337 338 339 340 341

      // Add priority if any.
      if (isset($link['priority'])) {
        $writer->writeElement('priority', $link['priority']);
      }

342 343
      // Add images if any.
      if (!empty($link['images'])) {
Pawel G's avatar
Pawel G committed
344
        foreach ($link['images'] as $image) {
345
          $writer->startElement('image:image');
Pawel G's avatar
Pawel G committed
346
          $writer->writeElement('image:loc', $image['path']);
347 348 349 350
          $writer->endElement();
        }
      }

351 352
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
353
    $writer->endElement();
354 355
    $writer->endDocument();
    return $writer->outputMemory();
356
  }
Pawel G's avatar
Pawel G committed
357

358
}