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

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

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

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

  /**
   * @var \Drupal\Core\Extension\ModuleHandler
   */
41
  protected $moduleHandler;
Pawel G's avatar
Pawel G committed
42
43
44
45

  /**
   * @var string
   */
46
  protected $defaultLanguageId;
Pawel G's avatar
Pawel G committed
47
48
49
50

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

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

  /**
   * @var \Drupal\simple_sitemap\Simplesitemap
   */
61
  protected $generator;
62

63
64
  /**
   * SitemapGenerator constructor.
Pawel G's avatar
Pawel G committed
65
   * @param \Drupal\simple_sitemap\Batch\Batch $batch
66
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
Pawel G's avatar
Pawel G committed
67
68
69
   * @param \Drupal\Core\Database\Connection $database
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
70
   */
Pawel G's avatar
Pawel G committed
71
72
  public function __construct(
    Batch $batch,
73
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
74
75
    Connection $database,
    ModuleHandler $module_handler,
76
    LanguageManagerInterface $language_manager
Pawel G's avatar
Pawel G committed
77
  ) {
78
    $this->batch = $batch;
79
    $this->entityHelper = $entityHelper;
80
    $this->db = $database;
81
    $this->moduleHandler = $module_handler;
82
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
83
    $this->isHreflangSitemap = count($language_manager->getLanguages()) > 1;
84
85
86
  }

  /**
Pawel G's avatar
Pawel G committed
87
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
88
89
   * @return $this
   */
Pawel G's avatar
Pawel G committed
90
  public function setGenerator(Simplesitemap $generator) {
91
92
    $this->generator = $generator;
    return $this;
93
94
  }

Pawel G's avatar
Pawel G committed
95
  /**
Pawel G's avatar
Pawel G committed
96
   * @param string $from
97
   * @return $this
Pawel G's avatar
Pawel G committed
98
   */
Pawel G's avatar
Pawel G committed
99
100
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
101
    return $this;
102
103
  }

104
  /**
105
   * Adds all operations to the batch and starts it.
106
   */
107
  public function startGeneration() {
108
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
109
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
110
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
111
      ? $this->generator->getSetting('batch_process_limit') : NULL,
112
113
114
      'max_links' => $this->generator->getSetting('max_links', 2000),
      'skip_untranslated' => $this->generator->getSetting('skip_untranslated', FALSE),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates', TRUE),
115
      'entity_types' => $this->generator->getBundleSettings(),
116
      'base_url' => $this->generator->getSetting('base_url', ''),
117
    ]);
Pawel G's avatar
Pawel G committed
118
    // Add custom link generating operation.
119
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
120
121

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
122
    foreach ($this->getEntityTypeData() as $data) {
123
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
124
    }
125
    $this->batch->start();
Pawel G's avatar
Pawel G committed
126
127
128
  }

  /**
Pawel G's avatar
Pawel G committed
129
   * Returns a batch-ready data array for custom link generation.
130
   *
Pawel G's avatar
Pawel G committed
131
   * @return array
Pawel G's avatar
Pawel G committed
132
   *   Data to be processed.
Pawel G's avatar
Pawel G committed
133
   */
134
  protected function getCustomUrlsData() {
135
    $paths = [];
136
    foreach ($this->generator->getCustomLinks() as $i => $custom_path) {
137
138
      $paths[$i]['path'] = $custom_path['path'];
      $paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
Pawel G's avatar
Pawel G committed
139
140
      // todo: implement lastmod.
      $paths[$i]['lastmod'] = NULL;
141
142
    }
    return $paths;
Pawel G's avatar
Pawel G committed
143
  }
144

Pawel G's avatar
Pawel G committed
145
  /**
146
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
147
   * and returns an array of batch-ready data sets for entity link generation.
148
   *
Pawel G's avatar
Pawel G committed
149
   * @return array
Pawel G's avatar
Pawel G committed
150
   */
151
  protected function getEntityTypeData() {
Pawel G's avatar
Pawel G committed
152
    $data_sets = [];
153
    $sitemap_entity_types = $this->entityHelper->getSitemapEntityTypes();
154
    $entity_types = $this->generator->getBundleSettings();
Pawel G's avatar
Pawel G committed
155
    foreach ($entity_types as $entity_type_name => $bundles) {
156
157
      if (isset($sitemap_entity_types[$entity_type_name])) {
        $keys = $sitemap_entity_types[$entity_type_name]->getKeys();
Pawel G's avatar
Pawel G committed
158

Pawel G's avatar
Pawel G committed
159
160
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
Pawel G's avatar
Pawel G committed
161

Pawel G's avatar
Pawel G committed
162
        foreach ($bundles as $bundle_name => $bundle_settings) {
163
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
164
165
166
167
168
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
169
170
            ];
          }
Pawel G's avatar
Pawel G committed
171
        }
172
173
      }
    }
Pawel G's avatar
Pawel G committed
174
    return $data_sets;
Pawel G's avatar
Pawel G committed
175
176
177
  }

  /**
178
179
   * Wrapper method which takes links along with their options, lets other
   * modules alter the links and then generates and saves the sitemap.
Pawel G's avatar
Pawel G committed
180
   *
181
   * @param array $links
Pawel G's avatar
Pawel G committed
182
   *   All links with their multilingual versions and settings.
183
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
184
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
185
   */
Pawel G's avatar
Pawel G committed
186
  public function generateSitemap(array $links, $remove_sitemap = FALSE) {
187
    // Invoke alter hook.
188
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
189

Pawel G's avatar
Pawel G committed
190
    $values = [
191
192
      'id' => $remove_sitemap ? 1 : $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
      'sitemap_string' => $this->generateSitemapChunk($links),
193
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
194
    ];
195
    if ($remove_sitemap) {
196
      $this->db->truncate('simple_sitemap')->execute();
197
    }
198
    $this->db->insert('simple_sitemap')->fields($values)->execute();
199
200
  }

201
  /**
202
   * Generates and returns the sitemap index for all sitemap chunks.
203
   *
Pawel G's avatar
Pawel G committed
204
   * @param array $chunks
Pawel G's avatar
Pawel G committed
205
   *   All sitemap chunks keyed by the chunk ID.
206
207
208
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
209
  public function generateSitemapIndex(array $chunks) {
210
211
212
213
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
214
    $writer->writeComment(self::GENERATED_BY);
215
216
217
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

Pawel G's avatar
Pawel G committed
218
    foreach ($chunks as $chunk_id => $chunk_data) {
219
      $writer->startElement('sitemap');
220
      $writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
221
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
222
223
224
225
226
227
228
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

229
230
231
232
233
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

234
235
236
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
237
   * @param array $links
Pawel G's avatar
Pawel G committed
238
   *   All links with their multilingual versions and settings.
239
   *
Pawel G's avatar
Pawel G committed
240
   * @return string
Pawel G's avatar
Pawel G committed
241
   *   Sitemap chunk
242
   */
243
  protected function generateSitemapChunk(array $links) {
244
245
246
247
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
248
    $writer->writeComment(self::GENERATED_BY);
249
250
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', self::XMLNS);
251
252
253
    if ($this->isHreflangSitemap) {
      $writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
    }
254

Pawel G's avatar
Pawel G committed
255
    foreach ($links as $link) {
256

257
      // Add each translation variant URL as location to the sitemap.
258
259
260
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

261
262
263
264
      // 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.
      if ($this->isHreflangSitemap) {
Pawel G's avatar
Pawel G committed
265
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
266
267
268
269
270
271
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
272
      }
273

274
275
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
276
277
        $writer->writeElement('lastmod', $link['lastmod']);
      }
278
279
280
281
282
283
284
285

      //todo: Implement changefreq here.

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

286
287
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
288
    $writer->endElement();
289
290
    $writer->endDocument();
    return $writer->outputMemory();
291
  }
Pawel G's avatar
Pawel G committed
292

293
}