SitemapGenerator.php 7.44 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
 * @package Drupal\simple_sitemap
10 11 12 13 14
 */
class SitemapGenerator {

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

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

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

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

Pawel G's avatar
Pawel G committed
51 52
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
53
    return $this;
54 55
  }

56
  /**
57
   * Adds all operations to the batch and starts it.
58
   */
59
  public function startGeneration() {
60
    $this->batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
61
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
62 63
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
        ? $this->generator->getSetting('batch_process_limit') : NULL,
64 65 66
      '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
67
      'entity_types' => $this->generator->getConfig('entity_types'),
68
    ]);
Pawel G's avatar
Pawel G committed
69
    // Add custom link generating operation.
70
    $this->batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());
Pawel G's avatar
Pawel G committed
71 72 73

    // Add entity link generating operations.
    foreach($this->getEntityTypeData() as $data) {
74
      $this->batch->addOperation('generateBundleUrls', $data);
Pawel G's avatar
Pawel G committed
75
    }
76
    $this->batch->start();
Pawel G's avatar
Pawel G committed
77 78 79
  }

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

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

  /**
125 126
   * 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
127
   *
128 129
   * @param array $links
   *  All links with their multilingual versions and settings.
130 131
   * @param bool $remove_sitemap
   *  Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
132
   */
133
  public function generateSitemap($links, $remove_sitemap = FALSE) {
134
    // Invoke alter hook.
135
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
136
    $values = [
137 138
      '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
139
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
140
    ];
141
    if ($remove_sitemap) {
142
      $this->db->truncate('simple_sitemap')->execute();
143
    }
144
    $this->db->insert('simple_sitemap')->fields($values)->execute();
145 146
  }

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

Pawel G's avatar
Pawel G committed
164
    foreach ($chunks as $chunk_id => $chunk_data) {
165
      $writer->startElement('sitemap');
166 167
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
168
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
169 170 171 172 173 174 175
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

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

Pawel G's avatar
Pawel G committed
197
    foreach ($links as $link) {
198

199
      // Add each translation variant URL as location to the sitemap.
200 201 202
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

203 204 205 206 207 208 209 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) {
        foreach($link['alternate_urls'] as $language_id => $alternate_url) {
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
214
      }
215 216
      // Add priority if any.
      if (isset($link['priority'])) {
217 218
        $writer->writeElement('priority', $link['priority']);
      }
219 220
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
221 222 223 224
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
225
    $writer->endElement();
226 227
    $writer->endDocument();
    return $writer->outputMemory();
228 229
  }
}