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

Pawel G's avatar
Pawel G committed
38

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

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

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

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

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

64 65
  /**
   * SitemapGenerator constructor.
Pawel G's avatar
Pawel G committed
66
   * @param \Drupal\simple_sitemap\Batch\Batch $batch
67
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
Pawel G's avatar
Pawel G committed
68 69 70
   * @param \Drupal\Core\Database\Connection $database
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
71
   */
Pawel G's avatar
Pawel G committed
72 73
  public function __construct(
    Batch $batch,
74
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
75 76
    Connection $database,
    ModuleHandler $module_handler,
77
    LanguageManagerInterface $language_manager
Pawel G's avatar
Pawel G committed
78
  ) {
79
    $this->batch = $batch;
80
    $this->entityHelper = $entityHelper;
81
    $this->db = $database;
82
    $this->moduleHandler = $module_handler;
Pawel G's avatar
Pawel G committed
83 84 85 86 87 88 89 90 91 92 93 94 95
    $this->languageManager = $language_manager;
    $this->setIsHreflangSitemap();
  }

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

  /**
   * @return bool
   */
  public function isHreflangSitemap() {
    return $this->isHreflangSitemap;
96 97 98
  }

  /**
Pawel G's avatar
Pawel G committed
99
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
100 101
   * @return $this
   */
Pawel G's avatar
Pawel G committed
102
  public function setGenerator(Simplesitemap $generator) {
103 104
    $this->generator = $generator;
    return $this;
105 106
  }

Pawel G's avatar
Pawel G committed
107
  /**
Pawel G's avatar
Pawel G committed
108
   * @param string $from
109
   * @return $this
Pawel G's avatar
Pawel G committed
110
   */
Pawel G's avatar
Pawel G committed
111 112
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
113
    return $this;
114 115
  }

116
  /**
117
   * Adds all operations to the batch and starts it.
118
   */
119
  public function startGeneration() {
120
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
121
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
122
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
123
        ? $this->generator->getSetting('batch_process_limit') : NULL,
124 125 126
      'max_links' => $this->generator->getSetting('max_links', 2000),
      'skip_untranslated' => $this->generator->getSetting('skip_untranslated', FALSE),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates', TRUE),
127
      'entity_types' => $this->generator->getBundleSettings(),
128
      'base_url' => $this->generator->getSetting('base_url', ''),
129
    ]);
Pawel G's avatar
Pawel G committed
130
    // Add custom link generating operation.
131
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
132 133

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
134
    foreach ($this->getEntityTypeData() as $data) {
135
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
136
    }
137
    $this->batch->start();
Pawel G's avatar
Pawel G committed
138 139 140
  }

  /**
Pawel G's avatar
Pawel G committed
141
   * Returns a batch-ready data array for custom link generation.
142
   *
Pawel G's avatar
Pawel G committed
143
   * @return array
Pawel G's avatar
Pawel G committed
144
   *   Data to be processed.
Pawel G's avatar
Pawel G committed
145
   */
146
  protected function getCustomUrlsData() {
147
    $paths = [];
148
    foreach ($this->generator->getCustomLinks() as $i => $custom_path) {
149 150
      $paths[$i]['path'] = $custom_path['path'];
      $paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
Pawel G's avatar
Pawel G committed
151 152
      // todo: implement lastmod.
      $paths[$i]['lastmod'] = NULL;
153 154
    }
    return $paths;
Pawel G's avatar
Pawel G committed
155
  }
156

Pawel G's avatar
Pawel G committed
157
  /**
158
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
159
   * and returns an array of batch-ready data sets for entity link generation.
160
   *
Pawel G's avatar
Pawel G committed
161
   * @return array
Pawel G's avatar
Pawel G committed
162
   */
163
  protected function getEntityTypeData() {
Pawel G's avatar
Pawel G committed
164
    $data_sets = [];
165
    $sitemap_entity_types = $this->entityHelper->getSitemapEntityTypes();
166
    $entity_types = $this->generator->getBundleSettings();
Pawel G's avatar
Pawel G committed
167
    foreach ($entity_types as $entity_type_name => $bundles) {
168 169
      if (isset($sitemap_entity_types[$entity_type_name])) {
        $keys = $sitemap_entity_types[$entity_type_name]->getKeys();
Pawel G's avatar
Pawel G committed
170

Pawel G's avatar
Pawel G committed
171 172
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
Pawel G's avatar
Pawel G committed
173

Pawel G's avatar
Pawel G committed
174
        foreach ($bundles as $bundle_name => $bundle_settings) {
175
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
176 177 178 179 180
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
181 182
            ];
          }
Pawel G's avatar
Pawel G committed
183
        }
184 185
      }
    }
Pawel G's avatar
Pawel G committed
186
    return $data_sets;
Pawel G's avatar
Pawel G committed
187 188 189
  }

  /**
190 191
   * 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
192
   *
193
   * @param array $links
Pawel G's avatar
Pawel G committed
194
   *   All links with their multilingual versions and settings.
195
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
196
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
197
   */
Pawel G's avatar
Pawel G committed
198
  public function generateSitemap(array $links, $remove_sitemap = FALSE) {
199
    // Invoke alter hook.
200
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
201

Pawel G's avatar
Pawel G committed
202
    $values = [
203 204
      'id' => $remove_sitemap ? 1 : $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
      'sitemap_string' => $this->generateSitemapChunk($links),
205
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
206
    ];
207
    if ($remove_sitemap) {
208
      $this->db->truncate('simple_sitemap')->execute();
209
    }
210
    $this->db->insert('simple_sitemap')->fields($values)->execute();
211 212
  }

213
  /**
214
   * Generates and returns the sitemap index for all sitemap chunks.
215
   *
Pawel G's avatar
Pawel G committed
216
   * @param array $chunks
Pawel G's avatar
Pawel G committed
217
   *   All sitemap chunks keyed by the chunk ID.
218 219 220
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
221
  public function generateSitemapIndex(array $chunks) {
222 223 224 225
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
226
    $writer->writeComment(self::GENERATED_BY);
227 228 229
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

Pawel G's avatar
Pawel G committed
230
    foreach ($chunks as $chunk_id => $chunk_data) {
231
      $writer->startElement('sitemap');
232
      $writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
233
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
234 235 236 237 238 239 240
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

241 242 243 244 245
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

246 247 248
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
249
   * @param array $links
Pawel G's avatar
Pawel G committed
250
   *   All links with their multilingual versions and settings.
251
   *
Pawel G's avatar
Pawel G committed
252
   * @return string
Pawel G's avatar
Pawel G committed
253
   *   Sitemap chunk
254
   */
255
  protected function generateSitemapChunk(array $links) {
256 257 258 259
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
260
    $writer->writeComment(self::GENERATED_BY);
261 262
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', self::XMLNS);
Pawel G's avatar
Pawel G committed
263 264

    if ($this->isHreflangSitemap()) {
265 266
      $writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
    }
267

Pawel G's avatar
Pawel G committed
268
    foreach ($links as $link) {
269

270
      // Add each translation variant URL as location to the sitemap.
271 272 273
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

274 275 276
      // 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.
Pawel G's avatar
Pawel G committed
277
      if ($this->isHreflangSitemap()) {
Pawel G's avatar
Pawel G committed
278
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
279 280 281 282 283 284
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
285
      }
286

287 288
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
289 290
        $writer->writeElement('lastmod', $link['lastmod']);
      }
291 292 293 294 295 296 297 298

      //todo: Implement changefreq here.

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

299 300
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
301
    $writer->endElement();
302 303
    $writer->endDocument();
    return $writer->outputMemory();
304
  }
Pawel G's avatar
Pawel G committed
305

306
}