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

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

5
use \XMLWriter;
6 7 8 9 10 11 12 13

/**
 * SitemapGenerator class.
 */
class SitemapGenerator {

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

Pawel G's avatar
Pawel G committed
18
  private $generator;
19 20 21 22
  private $db;
  private $moduleHandler;
  private $defaultLanguageId;
  private $generateFrom = 'form';
23
  private $isHreflangSitemap;
24

25
  public function __construct($generator, $database, $language_manager, $module_handler) {
Pawel G's avatar
Pawel G committed
26
    $this->generator = $generator;
27 28
    $this->db = $database;
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
29
    $this->isHreflangSitemap = count($language_manager->getLanguages()) > 1;
30
    $this->moduleHandler = $module_handler;
31 32
  }

Pawel G's avatar
Pawel G committed
33 34
  public function setGenerateFrom($from) {
    $this->generateFrom = $from;
Pawel G's avatar
Pawel G committed
35
    return $this;
36 37
  }

38
  /**
39
   * Adds all operations to the batch and starts it.
40
   */
41 42 43
  public function startGeneration() {
    $batch = new Batch();
    $batch->setBatchInfo([
Pawel G's avatar
Pawel G committed
44
      'from' => $this->generateFrom,
Pawel G's avatar
Pawel G committed
45 46
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
        ? $this->generator->getSetting('batch_process_limit') : NULL,
47 48 49
      '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
50
      'entity_types' => $this->generator->getConfig('entity_types'),
51
    ]);
Pawel G's avatar
Pawel G committed
52 53 54 55 56 57 58
    // Add custom link generating operation.
    $batch->addOperation('generateCustomUrls', $this->getCustomUrlsData());

    // Add entity link generating operations.
    foreach($this->getEntityTypeData() as $data) {
      $batch->addOperation('generateBundleUrls', $data);
    }
Pawel G's avatar
Pawel G committed
59 60 61 62
    $batch->start();
  }

  /**
Pawel G's avatar
Pawel G committed
63
   * Returns a batch-ready data array for custom link generation.
64
   *
Pawel G's avatar
Pawel G committed
65
   * @return array
Pawel G's avatar
Pawel G committed
66
   *  Data to be processed.
Pawel G's avatar
Pawel G committed
67
   */
Pawel G's avatar
Pawel G committed
68
  private function getCustomUrlsData() {
69 70 71 72 73 74 75
    $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
76
  }
77

Pawel G's avatar
Pawel G committed
78
  /**
79
   * Collects entity metadata for entities that are set to be indexed
Pawel G's avatar
Pawel G committed
80
   * and returns an array of batch-ready data sets for entity link generation.
81
   *
Pawel G's avatar
Pawel G committed
82
   * @return array
Pawel G's avatar
Pawel G committed
83
   */
Pawel G's avatar
Pawel G committed
84 85
  private function getEntityTypeData() {
    $data_sets = [];
86
    $sitemap_entity_types = $this->generator->getSitemapEntityTypes();
Pawel G's avatar
Pawel G committed
87
    $entity_types = $this->generator->getConfig('entity_types');
88
    foreach($entity_types as $entity_type_name => $bundles) {
89 90 91 92
      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) {
93
          if ($bundle_settings['index']) {
Pawel G's avatar
Pawel G committed
94 95 96 97 98
            $data_sets[] = [
              'bundle_settings' => $bundle_settings,
              'bundle_name' => $bundle_name,
              'entity_type_name' => $entity_type_name,
              'keys' => $keys,
99 100
            ];
          }
Pawel G's avatar
Pawel G committed
101
        }
102 103
      }
    }
Pawel G's avatar
Pawel G committed
104
    return $data_sets;
Pawel G's avatar
Pawel G committed
105 106 107
  }

  /**
108 109
   * 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
110
   *
111 112
   * @param array $links
   *  All links with their multilingual versions and settings.
113 114
   * @param bool $remove_sitemap
   *  Remove old sitemap from database before inserting the new one.
Pawel G's avatar
Pawel G committed
115
   */
116
  public function generateSitemap($links, $remove_sitemap = FALSE) {
117
    // Invoke alter hook.
118
    $this->moduleHandler->alter('simple_sitemap_links', $links);
Pawel G's avatar
Pawel G committed
119
    $values = [
120 121
      '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
122
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
123
    ];
124
    if ($remove_sitemap) {
125
      $this->db->truncate('simple_sitemap')->execute();
126
    }
127
    $this->db->insert('simple_sitemap')->fields($values)->execute();
128 129
  }

130
  /**
131
   * Generates and returns the sitemap index for all sitemap chunks.
132
   *
Pawel G's avatar
Pawel G committed
133
   * @param array $chunks
134 135 136 137
   *  All sitemap chunks keyed by the chunk ID.
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
138
  public function generateSitemapIndex($chunks) {
139 140 141 142
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
143
    $writer->writeComment(self::GENERATED_BY);
144 145 146
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

Pawel G's avatar
Pawel G committed
147
    foreach ($chunks as $chunk_id => $chunk_data) {
148
      $writer->startElement('sitemap');
149 150
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
151
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
152 153 154 155 156 157 158
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

159 160 161
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
162
   * @param array $links
163
   *  All links with their multilingual versions and settings.
164
   *
Pawel G's avatar
Pawel G committed
165 166
   * @return string
   *  Sitemap chunk
167
   */
168
  private function generateSitemapChunk($links) {
169 170 171 172
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
173
    $writer->writeComment(self::GENERATED_BY);
174 175
    $writer->startElement('urlset');
    $writer->writeAttribute('xmlns', self::XMLNS);
176 177 178
    if ($this->isHreflangSitemap) {
      $writer->writeAttribute('xmlns:xhtml', self::XMLNS_XHTML);
    }
179

Pawel G's avatar
Pawel G committed
180
    foreach ($links as $link) {
181

182
      // Add each translation variant URL as location to the sitemap.
183 184 185
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

186 187 188 189 190 191 192 193 194 195 196
      // 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();
        }
197
      }
198 199
      // Add priority if any.
      if (isset($link['priority'])) {
200 201
        $writer->writeElement('priority', $link['priority']);
      }
202 203
      // Add lastmod if any.
      if (isset($link['lastmod'])) {
204 205 206 207
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
208
    $writer->endElement();
209 210
    $writer->endDocument();
    return $writer->outputMemory();
211 212
  }
}