SitemapGenerator.php 10.5 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

Pawel G's avatar
Pawel G committed
40

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

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

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

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

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

66 67 68 69 70 71 72 73 74 75
  protected static $attributes = [
    'xmlns' => self::XMLNS,
    'xmlns:xhtml' => self::XMLNS_XHTML,
    'xmlns:image' => self::XMLNS_IMAGE,
  ];

  protected static $indexAttributes = [
    'xmlns' => self::XMLNS,
  ];

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

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

  /**
   * @return bool
   */
  public function isHreflangSitemap() {
    return $this->isHreflangSitemap;
108 109 110
  }

  /**
Pawel G's avatar
Pawel G committed
111
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
112 113
   * @return $this
   */
Pawel G's avatar
Pawel G committed
114
  public function setGenerator(Simplesitemap $generator) {
115 116
    $this->generator = $generator;
    return $this;
117 118
  }

Pawel G's avatar
Pawel G committed
119
  /**
Pawel G's avatar
Pawel G committed
120
   * @param string $from
121
   * @return $this
Pawel G's avatar
Pawel G committed
122
   */
Pawel G's avatar
Pawel G committed
123 124
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
125
    return $this;
126 127
  }

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

Pawel G's avatar
Pawel G committed
143
    // Add custom link generating operation.
144
    $this->batch->addOperation('simple_sitemap.custom_url_generator', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
145 146

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
147
    foreach ($this->getEntityTypeData() as $data) {
148 149 150 151 152 153 154 155
      $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
156
    }
157

158
    $this->batch->start();
Pawel G's avatar
Pawel G committed
159 160 161
  }

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

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

Pawel G's avatar
Pawel G committed
191 192
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
Pawel G's avatar
Pawel G committed
193

Pawel G's avatar
Pawel G committed
194
        foreach ($bundles as $bundle_name => $bundle_settings) {
195
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
196 197 198 199 200
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
201 202
            ];
          }
Pawel G's avatar
Pawel G committed
203
        }
204 205
      }
    }
Pawel G's avatar
Pawel G committed
206
    return $data_sets;
Pawel G's avatar
Pawel G committed
207 208 209
  }

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

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

248 249 250 251 252 253 254
    // 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
255
    foreach ($chunk_info as $chunk_id => $chunk_data) {
256
      $writer->startElement('sitemap');
257
      $writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
258
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
259 260
      $writer->endElement();
    }
261

262 263 264 265 266
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

267 268 269
  /**
   * @return string
   */
270 271 272 273 274
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

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

292 293 294 295 296 297 298
    // 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);
299
    }
300

301 302
    // Add URLs to document.
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
303
    foreach ($links as $link) {
304

305
      // Add each translation variant URL as location to the sitemap.
306 307 308
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

309 310 311
      // 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.
312
      if (isset($link['alternate_urls']) && $this->isHreflangSitemap()) {
Pawel G's avatar
Pawel G committed
313
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
314 315 316 317 318 319
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
320
      }
321

322 323
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
324 325
        $writer->writeElement('lastmod', $link['lastmod']);
      }
326

327 328 329 330
      // Add changefreq if any.
      if (isset($link['changefreq'])) {
        $writer->writeElement('changefreq', $link['changefreq']);
      }
331 332 333 334 335 336

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

337 338 339 340 341 342 343 344 345
      // Add images if any.
      if (!empty($link['images'])) {
        foreach ($link['images'] as $image_url) {
          $writer->startElement('image:image');
          $writer->writeElement('image:loc', $image_url);
          $writer->endElement();
        }
      }

346 347
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
348
    $writer->endElement();
349 350
    $writer->endDocument();
    return $writer->outputMemory();
351
  }
Pawel G's avatar
Pawel G committed
352

353
}