SitemapGenerator.php 6.12 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 20 21 22

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

  const PRIORITY_DEFAULT = 0.5;
  const PRIORITY_HIGHEST = 10;
  const PRIORITY_DIVIDER = 10;
  const XML_VERSION = '1.0';
  const ENCODING = 'UTF-8';
23 24
  const XMLNS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
  const XMLNS_XHTML = 'http://www.w3.org/1999/xhtml';
25

26
  private $entityTypes;
27 28
  private $custom;
  private $links;
29
  private $generatingFrom;
30

Pawel G's avatar
Pawel G committed
31
  function __construct($from = 'form') {
32
    $this->links = array();
33
    $this->generatingFrom = $from;
34
  }
35

36 37 38 39 40
  /**
   * Gets the values needed to display the priority dropdown setting.
   *
   * @return array $options
   */
41
  public static function getPrioritySelectValues() {
42 43 44 45 46 47 48 49
    $options = array();
    foreach(range(0, self::PRIORITY_HIGHEST) as $value) {
      $value = $value / self::PRIORITY_DIVIDER;
      $options[(string)$value] = (string)$value;
    }
    return $options;
  }

50 51
  public function setEntityTypes($entityTypes) {
    $this->entityTypes = is_array($entityTypes) ? $entityTypes : array();
52 53
  }

54
  public function setCustomLinks($custom) {
55
    $this->custom = is_array($custom) ? $custom : array();
56 57
  }

58
  /**
59
   * Adds all operations to the batch and starts it.
60
   */
61 62 63 64
  public function startBatch() {
    $batch = new Batch($this->generatingFrom);
    $batch->addOperations('custom_paths', $this->batchAddCustomPaths());
    $batch->addOperations('entity_types', $this->batchAddEntityTypePaths());
Pawel G's avatar
Pawel G committed
65 66 67 68
    $batch->start();
  }

  /**
69 70 71
   * Returns the custom path generating operation.
   *
   * @return array $operation.
Pawel G's avatar
Pawel G committed
72
   */
73
  private function batchAddCustomPaths() {
Pawel G's avatar
Pawel G committed
74
    $link_generator = new CustomLinkGenerator();
75
    return $link_generator->getCustomPaths($this->custom);
Pawel G's avatar
Pawel G committed
76
  }
77

Pawel G's avatar
Pawel G committed
78
  /**
79 80 81 82
   * Collects the entity path generating information from all simeple_sitemap
   * plugins to be added to the batch.
   *
   * @return array $operations.
Pawel G's avatar
Pawel G committed
83
   */
84
  private function batchAddEntityTypePaths() {
85

Pawel G's avatar
Pawel G committed
86 87 88
    $manager = \Drupal::service('plugin.manager.simple_sitemap');
    $plugins = $manager->getDefinitions();
    $operations = array();
89

Pawel G's avatar
Pawel G committed
90 91
    // Let all simple_sitemap plugins add their links to the sitemap.
    foreach ($plugins as $link_generator_plugin) {
92
      if (isset($this->entityTypes[$link_generator_plugin['id']])) {
Pawel G's avatar
Pawel G committed
93
        $instance = $manager->createInstance($link_generator_plugin['id']);
94
        foreach($this->entityTypes[$link_generator_plugin['id']] as $bundle => $bundle_settings) {
Pawel G's avatar
Pawel G committed
95
          if ($bundle_settings['index']) {
96 97
            $operation['info'] = $instance->getInfo();
            $operation['query'] = $instance->getQuery($bundle);
Pawel G's avatar
Pawel G committed
98
            $operation['info']['bundle_settings'] = $bundle_settings;
99 100
            $operation['info']['bundle_settings']['bundle_name'] = $bundle;
            $operation['info']['bundle_settings']['bundle_entity_type'] = $link_generator_plugin['id'];
Pawel G's avatar
Pawel G committed
101 102 103
            $operations[] = $operation;
          }
        }
104 105
      }
    }
Pawel G's avatar
Pawel G committed
106 107 108 109
    return $operations;
  }

  /**
110 111
   * Wrapper method which takes links along with their options and then
   * generates and saves the sitemap.
Pawel G's avatar
Pawel G committed
112
   *
113 114
   * @param array $links
   *  All links with their multilingual versions and settings.
Pawel G's avatar
Pawel G committed
115
   */
116
  public static function generateSitemap($links) {
Pawel G's avatar
Pawel G committed
117 118
    $values = array(
      'id' => db_query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField() + 1,
119
      'sitemap_string' => self::generateSitemapChunk($links),
Pawel G's avatar
Pawel G committed
120
      'sitemap_created' => REQUEST_TIME,
Pawel G's avatar
Pawel G committed
121
    );
Pawel G's avatar
Pawel G committed
122
    db_insert('simple_sitemap')->fields($values)->execute();
123 124
  }

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

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

153 154 155 156
  /**
   * Generates and returns a sitemap chunk.
   *
   * @param array $sitemap_links
157
   *  All links with their multilingual versions and settings.
158 159 160
   *
   * @return string sitemap chunk
   */
161 162
  private static function generateSitemapChunk($sitemap_links) {
    $default_language_id = Simplesitemap::getDefaultLangId();
163 164 165 166 167 168 169 170 171

    $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);

172
    foreach ($sitemap_links as $link) {
173 174 175
      $writer->startElement('url');

      // Adding url to standard language.
Pawel G's avatar
Pawel G committed
176
      $writer->writeElement('loc', $link['urls'][$default_language_id]);
177

178
      // Adding alternate urls (other languages) if any.
Pawel G's avatar
Pawel G committed
179 180
      if (count($link['urls']) > 1) {
        foreach($link['urls'] as $language_id => $localised_url) {
181 182 183 184 185
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $localised_url);
          $writer->endElement();
186 187 188
        }
      }

189
      // Add priority if any.
Pawel G's avatar
Pawel G committed
190
      if (isset($link['priority'])) {
191 192 193
        $writer->writeElement('priority', $link['priority']);
      }

194
      // Add lastmod if any.
Pawel G's avatar
Pawel G committed
195
      if (isset($link['lastmod'])) {
196 197 198 199
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
Pawel G's avatar
Pawel G committed
200
    $writer->endElement();
201 202
    $writer->endDocument();
    return $writer->outputMemory();
203 204
  }
}