SitemapGenerator.php 6.31 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;
32 33
  }

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

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

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

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

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

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

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

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