SitemapGenerator.php 6.55 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

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

23
  function __construct($generator, $database, $language_manager, $module_handler) {
Pawel G's avatar
Pawel G committed
24
    $this->generator = $generator;
25 26 27
    $this->db = $database;
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
    $this->moduleHandler = $module_handler;
28 29
  }

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

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

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

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

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

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

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

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

Pawel G's avatar
Pawel G committed
173
    foreach ($links as $link) {
174

175 176 177 178 179 180 181 182 183 184 185
      // Add each translation variant URL to the sitemap.
      $writer->startElement('url');
      $writer->writeElement('loc', $link['url']);

      // Add all alternate URLs to this translation variant.
      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();
186
      }
187
      if (isset($link['priority'])) { // Add priority if any.
188 189
        $writer->writeElement('priority', $link['priority']);
      }
190
      if (isset($link['lastmod'])) { // Add lastmod if any.
191 192 193 194
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
195
    $writer->endElement();
196 197
    $writer->endDocument();
    return $writer->outputMemory();
198 199
  }
}
200