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

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

5
use \XMLWriter;
6 7

/**
Pawel G's avatar
Pawel G committed
8 9
 * Class SitemapGenerator.
 *
Pawel G's avatar
Pawel G committed
10
 * @package Drupal\simple_sitemap
11 12 13 14 15
 */
class SitemapGenerator {

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

20
  private $batch;
21 22 23 24
  private $db;
  private $moduleHandler;
  private $defaultLanguageId;
  private $generateFrom = 'form';
25
  private $isHreflangSitemap;
26
  private $generator;
27

28 29
  /**
   * SitemapGenerator constructor.
Pawel G's avatar
Pawel G committed
30
   *
31 32 33 34 35 36 37
   * @param $batch
   * @param $database
   * @param $module_handler
   * @param $language_manager
   */
  public function __construct($batch, $database, $module_handler, $language_manager) {
    $this->batch = $batch;
38
    $this->db = $database;
39
    $this->moduleHandler = $module_handler;
40
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
41
    $this->isHreflangSitemap = count($language_manager->getLanguages()) > 1;
42 43 44 45 46 47 48 49 50
  }

  /**
   * @param $generator
   * @return $this
   */
  public function setGenerator($generator) {
    $this->generator = $generator;
    return $this;
51 52
  }

Pawel G's avatar
Pawel G committed
53 54 55
  /**
   *
   */
Pawel G's avatar
Pawel G committed
56 57
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
58
    return $this;
59 60
  }

61
  /**
62
   * Adds all operations to the batch and starts it.
63
   */
64
  public function startGeneration() {
65
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
66
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
67
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
68
      ? $this->generator->getSetting('batch_process_limit') : NULL,
69 70 71
      'max_links' => $this->generator->getSetting('max_links', 2000),
      'skip_untranslated' => $this->generator->getSetting('skip_untranslated', FALSE),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates', TRUE),
Pawel G's avatar
Pawel G committed
72
      'entity_types' => $this->generator->getConfig('entity_types'),
73
    ]);
Pawel G's avatar
Pawel G committed
74
    // Add custom link generating operation.
75
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
76 77

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
78
    foreach ($this->getEntityTypeData() as $data) {
79
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
80
    }
81
    $this->batch->start();
Pawel G's avatar
Pawel G committed
82 83 84
  }

  /**
Pawel G's avatar
Pawel G committed
85
   * Returns a batch-ready data array for custom link generation.
86
   *
Pawel G's avatar
Pawel G committed
87
   * @return array
Pawel G's avatar
Pawel G committed
88
   *   Data to be processed.
Pawel G's avatar
Pawel G committed
89
   */
Pawel G's avatar
Pawel G committed
90
  private function getCustomUrlsData() {
91
    $paths = [];
Pawel G's avatar
Pawel G committed
92
    foreach ($this->generator->getConfig('custom') as $i => $custom_path) {
93 94
      $paths[$i]['path'] = $custom_path['path'];
      $paths[$i]['priority'] = isset($custom_path['priority']) ? $custom_path['priority'] : NULL;
Pawel G's avatar
Pawel G committed
95 96
      // todo: implement lastmod.
      $paths[$i]['lastmod'] = NULL;
97 98
    }
    return $paths;
Pawel G's avatar
Pawel G committed
99
  }
100

Pawel G's avatar
Pawel G committed
101
  /**
102
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
103
   * and returns an array of batch-ready data sets for entity link generation.
104
   *
Pawel G's avatar
Pawel G committed
105
   * @return array
Pawel G's avatar
Pawel G committed
106
   */
Pawel G's avatar
Pawel G committed
107 108
  private function getEntityTypeData() {
    $data_sets = [];
109
    $sitemap_entity_types = $this->generator->getSitemapEntityTypes();
Pawel G's avatar
Pawel G committed
110
    $entity_types = $this->generator->getConfig('entity_types');
Pawel G's avatar
Pawel G committed
111
    foreach ($entity_types as $entity_type_name => $bundles) {
112 113
      if (isset($sitemap_entity_types[$entity_type_name])) {
        $keys = $sitemap_entity_types[$entity_type_name]->getKeys();
Pawel G's avatar
Pawel G committed
114 115 116
        // Menu fix.
        $keys['bundle'] = $entity_type_name == 'menu_link_content' ? 'menu_name' : $keys['bundle'];
        foreach ($bundles as $bundle_name => $bundle_settings) {
117
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
118 119 120 121 122
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
123 124
            ];
          }
Pawel G's avatar
Pawel G committed
125
        }
126 127
      }
    }
Pawel G's avatar
Pawel G committed
128
    return $data_sets;
Pawel G's avatar
Pawel G committed
129 130 131
  }

  /**
132 133
   * 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
134
   *
135
   * @param array $links
Pawel G's avatar
Pawel G committed
136
   *   All links with their multilingual versions and settings.
137
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
138
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
139
   */
140
  public function generateSitemap($links, $remove_sitemap = FALSE) {
141
    // Invoke alter hook.
142
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
143
    $values = [
144 145
      'id' => $remove_sitemap ? 1 : $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
      'sitemap_string' => $this->generateSitemapChunk($links),
Pawel G's avatar
Pawel G committed
146
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
147
    ];
148
    if ($remove_sitemap) {
149
      $this->db->truncate('simple_sitemap')->execute();
150
    }
151
    $this->db->insert('simple_sitemap')->fields($values)->execute();
152 153
  }

154
  /**
155
   * Generates and returns the sitemap index for all sitemap chunks.
156
   *
Pawel G's avatar
Pawel G committed
157
   * @param array $chunks
Pawel G's avatar
Pawel G committed
158
   *   All sitemap chunks keyed by the chunk ID.
159 160 161
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
162
  public function generateSitemapIndex($chunks) {
163 164 165 166
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
167
    $writer->writeComment(self::GENERATED_BY);
168 169 170
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

Pawel G's avatar
Pawel G committed
171
    foreach ($chunks as $chunk_id => $chunk_data) {
172
      $writer->startElement('sitemap');
173 174
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
175
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
176 177 178 179 180 181 182
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

183 184 185
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
186
   * @param array $links
Pawel G's avatar
Pawel G committed
187
   *   All links with their multilingual versions and settings.
188
   *
Pawel G's avatar
Pawel G committed
189
   * @return string
Pawel G's avatar
Pawel G committed
190
   *   Sitemap chunk
191
   */
192
  private function generateSitemapChunk($links) {
193 194 195 196
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
197
    $writer->writeComment(self::GENERATED_BY);
198 199
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', self::XMLNS);
200 201 202
    if ($this->isHreflangSitemap) {
      $writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
    }
203

Pawel G's avatar
Pawel G committed
204
    foreach ($links as $link) {
205

206
      // Add each translation variant URL as location to the sitemap.
207 208 209
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

210 211 212 213
      // 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
214
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
215 216 217 218 219 220
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
221
      }
222 223
      // Add priority if any.
      if (isset($link['priority'])) {
224 225
        $writer->writeElement('priority', $link['priority']);
      }
226 227
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
228 229 230 231
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
232
    $writer->endElement();
233 234
    $writer->endDocument();
    return $writer->outputMemory();
235
  }
Pawel G's avatar
Pawel G committed
236

237
}