SitemapGenerator.php 8.41 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 13
 * Class SitemapGenerator.
 *
Pawel G's avatar
Pawel G committed
14
 * @package Drupal\simple_sitemap
15 16 17 18 19
 */
class SitemapGenerator {

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

24
  private $batch;
25
  private $entityHelper;
26 27 28 29
  private $db;
  private $moduleHandler;
  private $defaultLanguageId;
  private $generateFrom = 'form';
30
  private $isHreflangSitemap;
31
  private $generator;
32

33 34
  /**
   * SitemapGenerator constructor.
Pawel G's avatar
Pawel G committed
35
   * @param \Drupal\simple_sitemap\Batch\Batch $batch
36
   * @param \Drupal\simple_sitemap\EntityHelper $entityHelper
Pawel G's avatar
Pawel G committed
37 38 39
   * @param \Drupal\Core\Database\Connection $database
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
40
   */
Pawel G's avatar
Pawel G committed
41 42
  public function __construct(
    Batch $batch,
43
    EntityHelper $entityHelper,
Pawel G's avatar
Pawel G committed
44 45
    Connection $database,
    ModuleHandler $module_handler,
46
    LanguageManagerInterface $language_manager
Pawel G's avatar
Pawel G committed
47
  ) {
48
    $this->batch = $batch;
49
    $this->entityHelper = $entityHelper;
50
    $this->db = $database;
51
    $this->moduleHandler = $module_handler;
52
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
53
    $this->isHreflangSitemap = count($language_manager->getLanguages()) > 1;
54 55 56
  }

  /**
Pawel G's avatar
Pawel G committed
57
   * @param \Drupal\simple_sitemap\Simplesitemap $generator
58 59
   * @return $this
   */
Pawel G's avatar
Pawel G committed
60
  public function setGenerator(Simplesitemap $generator) {
61 62
    $this->generator = $generator;
    return $this;
63 64
  }

Pawel G's avatar
Pawel G committed
65
  /**
Pawel G's avatar
Pawel G committed
66
   * @param string $from
67
   * @return $this
Pawel G's avatar
Pawel G committed
68
   */
Pawel G's avatar
Pawel G committed
69 70
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
71
    return $this;
72 73
  }

74
  /**
75
   * Adds all operations to the batch and starts it.
76
   */
77
  public function startGeneration() {
78
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
79
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
80
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
81
      ? $this->generator->getSetting('batch_process_limit') : NULL,
82 83 84
      'max_links' => $this->generator->getSetting('max_links', 2000),
      'skip_untranslated' => $this->generator->getSetting('skip_untranslated', FALSE),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates', TRUE),
85
      'entity_types' => $this->generator->getBundleSettings(),
86
      'base_url' => $this->generator->getSetting('base_url', ''),
87
    ]);
Pawel G's avatar
Pawel G committed
88
    // Add custom link generating operation.
89
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
90 91

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
92
    foreach ($this->getEntityTypeData() as $data) {
93
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
94
    }
95
    $this->batch->start();
Pawel G's avatar
Pawel G committed
96 97 98
  }

  /**
Pawel G's avatar
Pawel G committed
99
   * Returns a batch-ready data array for custom link generation.
100
   *
Pawel G's avatar
Pawel G committed
101
   * @return array
Pawel G's avatar
Pawel G committed
102
   *   Data to be processed.
Pawel G's avatar
Pawel G committed
103
   */
Pawel G's avatar
Pawel G committed
104
  private function getCustomUrlsData() {
105
    $paths = [];
106
    foreach ($this->generator->getCustomLinks() as $i => $custom_path) {
107 108
      $paths[$i]['path'] = $custom_path['path'];
      $paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
Pawel G's avatar
Pawel G committed
109 110
      // todo: implement lastmod.
      $paths[$i]['lastmod'] = NULL;
111 112
    }
    return $paths;
Pawel G's avatar
Pawel G committed
113
  }
114

Pawel G's avatar
Pawel G committed
115
  /**
116
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
117
   * and returns an array of batch-ready data sets for entity link generation.
118
   *
Pawel G's avatar
Pawel G committed
119
   * @return array
Pawel G's avatar
Pawel G committed
120
   */
Pawel G's avatar
Pawel G committed
121 122
  private function getEntityTypeData() {
    $data_sets = [];
123
    $sitemap_entity_types = $this->entityHelper->getSitemapEntityTypes();
124
    $entity_types = $this->generator->getBundleSettings();
Pawel G's avatar
Pawel G committed
125
    foreach ($entity_types as $entity_type_name => $bundles) {
126 127
      if (isset($sitemap_entity_types[$entity_type_name])) {
        $keys = $sitemap_entity_types[$entity_type_name]->getKeys();
Pawel G's avatar
Pawel G committed
128

Pawel G's avatar
Pawel G committed
129 130
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
Pawel G's avatar
Pawel G committed
131

Pawel G's avatar
Pawel G committed
132
        foreach ($bundles as $bundle_name => $bundle_settings) {
133
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
134 135 136 137 138
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
139 140
            ];
          }
Pawel G's avatar
Pawel G committed
141
        }
142 143
      }
    }
Pawel G's avatar
Pawel G committed
144
    return $data_sets;
Pawel G's avatar
Pawel G committed
145 146 147
  }

  /**
148 149
   * 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
150
   *
151
   * @param array $links
Pawel G's avatar
Pawel G committed
152
   *   All links with their multilingual versions and settings.
153
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
154
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
155
   */
Pawel G's avatar
Pawel G committed
156
  public function generateSitemap(array $links, $remove_sitemap = FALSE) {
157
    // Invoke alter hook.
158
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
159

Pawel G's avatar
Pawel G committed
160
    $values = [
161 162
      'id' => $remove_sitemap ? 1 : $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
      'sitemap_string' => $this->generateSitemapChunk($links),
163
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
164
    ];
165
    if ($remove_sitemap) {
166
      $this->db->truncate('simple_sitemap')->execute();
167
    }
168
    $this->db->insert('simple_sitemap')->fields($values)->execute();
169 170
  }

171
  /**
172
   * Generates and returns the sitemap index for all sitemap chunks.
173
   *
Pawel G's avatar
Pawel G committed
174
   * @param array $chunks
Pawel G's avatar
Pawel G committed
175
   *   All sitemap chunks keyed by the chunk ID.
176 177 178
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
179
  public function generateSitemapIndex(array $chunks) {
180 181 182 183
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
184
    $writer->writeComment(self::GENERATED_BY);
185 186 187
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

Pawel G's avatar
Pawel G committed
188
    foreach ($chunks as $chunk_id => $chunk_data) {
189
      $writer->startElement('sitemap');
190
      $writer->writeElement('loc', $this->getCustomBaseUrl() . '/sitemaps/' . $chunk_id . '/' . 'sitemap.xml');
191
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
192 193 194 195 196 197 198
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

199 200 201 202 203
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

204 205 206
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
207
   * @param array $links
Pawel G's avatar
Pawel G committed
208
   *   All links with their multilingual versions and settings.
209
   *
Pawel G's avatar
Pawel G committed
210
   * @return string
Pawel G's avatar
Pawel G committed
211
   *   Sitemap chunk
212
   */
Pawel G's avatar
Pawel G committed
213
  private function generateSitemapChunk(array $links) {
214 215 216 217
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
218
    $writer->writeComment(self::GENERATED_BY);
219 220
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', self::XMLNS);
221 222 223
    if ($this->isHreflangSitemap) {
      $writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
    }
224

Pawel G's avatar
Pawel G committed
225
    foreach ($links as $link) {
226

227
      // Add each translation variant URL as location to the sitemap.
228 229 230
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

231 232 233 234
      // 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
235
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
236 237 238 239 240 241
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
242
      }
243

244 245
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
246 247
        $writer->writeElement('lastmod', $link['lastmod']);
      }
248 249 250 251 252 253 254 255

      //todo: Implement changefreq here.

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

256 257
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
258
    $writer->endElement();
259 260
    $writer->endDocument();
    return $writer->outputMemory();
261
  }
Pawel G's avatar
Pawel G committed
262

263
}