SitemapGenerator.php 6.23 KB
Newer Older
1 2 3
<?php
/**
 * @file
Pawel G's avatar
Pawel G committed
4
 * Contains \Drupal\simple_sitemap\SitemapGenerator.
5 6 7 8
 *
 * Generates a sitemap for entities and custom links.
 */

Pawel G's avatar
Pawel G committed
9
namespace Drupal\simple_sitemap;
10

11
use \XMLWriter;
12 13 14 15 16 17 18 19

/**
 * SitemapGenerator class.
 */
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

Pawel G's avatar
Pawel G committed
23
  private $generator;
24
  private $links;
Pawel G's avatar
Pawel G committed
25
  private $generateFrom;
26

Pawel G's avatar
Pawel G committed
27 28
  function __construct($generator) {
    $this->generator = $generator;
Pawel G's avatar
Pawel G committed
29 30
    $this->links = [];
    $this->generateFrom = 'form';
31 32
  }

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

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

  /**
56 57 58
   * Returns the custom path generating operation.
   *
   * @return array $operation.
Pawel G's avatar
Pawel G committed
59
   */
60
  private function batchAddCustomPaths() {
Pawel G's avatar
Pawel G committed
61
    $link_generator = new CustomLinkGenerator();
Pawel G's avatar
Pawel G committed
62
    return $link_generator->getCustomPaths($this->generator->getConfig('custom'));
Pawel G's avatar
Pawel G committed
63
  }
64

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

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

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

147 148 149
  /**
   * Generates and returns a sitemap chunk.
   *
Pawel G's avatar
Pawel G committed
150
   * @param array $links
151
   *  All links with their multilingual versions and settings.
152 153 154
   *
   * @return string sitemap chunk
   */
Pawel G's avatar
Pawel G committed
155
  private static function generateSitemapChunk($links) {
156
    $default_language_id = Simplesitemap::getDefaultLangId();
157 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.
Pawel G's avatar
Pawel G committed
170
      $writer->writeElement('loc', $link['urls'][$default_language_id]);
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