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

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

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 26 27 28
  private $db;
  private $moduleHandler;
  private $defaultLanguageId;
  private $generateFrom = 'form';
29
  private $isHreflangSitemap;
30
  private $generator;
31

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

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

Pawel G's avatar
Pawel G committed
62 63 64
  /**
   *
   */
Pawel G's avatar
Pawel G committed
65 66
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
67
    return $this;
68 69
  }

70
  /**
71
   * Adds all operations to the batch and starts it.
72
   */
73
  public function startGeneration() {
74
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
75
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
76
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
Pawel G's avatar
Pawel G committed
77
      ? $this->generator->getSetting('batch_process_limit') : NULL,
78 79 80
      '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
81
      'entity_types' => $this->generator->getConfig('entity_types'),
82
    ]);
Pawel G's avatar
Pawel G committed
83
    // Add custom link generating operation.
84
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
85 86

    // Add entity link generating operations.
Pawel G's avatar
Pawel G committed
87
    foreach ($this->getEntityTypeData() as $data) {
88
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
89
    }
90
    $this->batch->start();
Pawel G's avatar
Pawel G committed
91 92 93
  }

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

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

  /**
141 142
   * 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
143
   *
144
   * @param array $links
Pawel G's avatar
Pawel G committed
145
   *   All links with their multilingual versions and settings.
146
   * @param bool $remove_sitemap
Pawel G's avatar
Pawel G committed
147
   *   Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
148
   */
149
  public function generateSitemap($links, $remove_sitemap = FALSE) {
150
    // Invoke alter hook.
151
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
152
    $values = [
153 154
      '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
155
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
156
    ];
157
    if ($remove_sitemap) {
158
      $this->db->truncate('simple_sitemap')->execute();
159
    }
160
    $this->db->insert('simple_sitemap')->fields($values)->execute();
161 162
  }

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

Pawel G's avatar
Pawel G committed
180
    foreach ($chunks as $chunk_id => $chunk_data) {
181
      $writer->startElement('sitemap');
182 183
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
184
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
185 186 187 188 189 190 191
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

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

Pawel G's avatar
Pawel G committed
213
    foreach ($links as $link) {
214

215
      // Add each translation variant URL as location to the sitemap.
216 217 218
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

219 220 221 222
      // 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
223
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
224 225 226 227 228 229
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
230
      }
231 232
      // Add priority if any.
      if (isset($link['priority'])) {
233 234
        $writer->writeElement('priority', $link['priority']);
      }
235 236
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
237 238 239 240
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
241
    $writer->endElement();
242 243
    $writer->endDocument();
    return $writer->outputMemory();
244
  }
Pawel G's avatar
Pawel G committed
245

246
}