SitemapGenerator.php 6.33 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 44 45 46
      'batch_process_limit' => !empty($this->generator->getSetting('batch_process_limit'))
        ? $this->generator->getSetting('batch_process_limit') : NULL,
      'max_links' => $this->generator->getSetting('max_links'),
      'remove_duplicates' => $this->generator->getSetting('remove_duplicates'),
      'entity_types' => $this->generator->getConfig('entity_types'),
47
    ]);
Pawel G's avatar
Pawel G committed
48 49 50 51 52 53 54
    // 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
55 56 57 58
    $batch->start();
  }

  /**
Pawel G's avatar
Pawel G committed
59
   * Returns a batch-ready data array for custom link generation.
60
   *
Pawel G's avatar
Pawel G committed
61 62
   * @return array $data
   *  Data to be processed.
Pawel G's avatar
Pawel G committed
63
   */
Pawel G's avatar
Pawel G committed
64
  private function getCustomUrlsData() {
Pawel G's avatar
Pawel G committed
65
    $link_generator = new CustomLinkGenerator();
Pawel G's avatar
Pawel G committed
66
    return $link_generator->getCustomPaths($this->generator->getConfig('custom'));
Pawel G's avatar
Pawel G committed
67
  }
68

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

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

121
  /**
122
   * Generates and returns the sitemap index for all sitemap chunks.
123
   *
Pawel G's avatar
Pawel G committed
124
   * @param array $chunks
125 126 127 128
   *  All sitemap chunks keyed by the chunk ID.
   *
   * @return string sitemap index
   */
Pawel G's avatar
Pawel G committed
129
  public function generateSitemapIndex($chunks) {
130 131 132 133 134 135 136
    $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
137
    foreach ($chunks as $chunk_id => $chunk_data) {
138
      $writer->startElement('sitemap');
139 140
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
141
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
142 143 144 145 146 147 148
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

149 150 151
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
152
   * @param array $links
153
   *  All links with their multilingual versions and settings.
154 155 156
   *
   * @return string sitemap chunk
   */
157
  private function generateSitemapChunk($links) {
158 159 160 161 162 163 164 165
    $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
166
    foreach ($links as $link) {
167 168 169
      $writer->startElement('url');

      // Adding url to standard language.
170
      $writer->writeElement('loc', $link['urls'][$this->defaultLanguageId]);
171

172
      // Adding alternate urls (other languages) if any.
Pawel G's avatar
Pawel G committed
173 174
      if (count($link['urls']) > 1) {
        foreach($link['urls'] as $language_id => $localised_url) {
175 176 177 178 179
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $localised_url);
          $writer->endElement();
180 181
        }
      }
182
      if (isset($link['priority'])) { // Add priority if any.
183 184
        $writer->writeElement('priority', $link['priority']);
      }
185
      if (isset($link['lastmod'])) { // Add lastmod if any.
186 187 188 189
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
190
    $writer->endElement();
191 192
    $writer->endDocument();
    return $writer->outputMemory();
193 194
  }
}
195