SitemapGenerator.php 8.03 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
   * @param $from
   * @return $this
Pawel G's avatar
Pawel G committed
65
   */
Pawel G's avatar
Pawel G committed
66 67
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
68
    return $this;
69 70
  }

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

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

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

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

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

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

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

193 194 195 196 197
  public function getCustomBaseUrl() {
    $customBaseUrl = $this->generator->getSetting('base_url', '');
    return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  }

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

Pawel G's avatar
Pawel G committed
219
    foreach ($links as $link) {
220

221
      // Add each translation variant URL as location to the sitemap.
222 223 224
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

225 226 227 228
      // 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
229
        foreach ($link['alternate_urls'] as $language_id => $alternate_url) {
230 231 232 233 234 235
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $alternate_url);
          $writer->endElement();
        }
236
      }
237

238 239
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
240 241
        $writer->writeElement('lastmod', $link['lastmod']);
      }
242 243 244 245 246 247 248 249

      //todo: Implement changefreq here.

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

250 251
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
252
    $writer->endElement();
253 254
    $writer->endDocument();
    return $writer->outputMemory();
255
  }
Pawel G's avatar
Pawel G committed
256

257
}