SitemapGenerator.php 6.42 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @file
 * Contains \Drupal\simplesitemap\SitemapGenerator.
 *
 * Generates a sitemap for entities and custom links.
 */

namespace Drupal\simplesitemap;

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 27 28

  private $entity_types;
  private $custom;
  private $links;
29
  private $default_language_id;
30 31

  function __construct() {
32
    $this->default_language_id = \Drupal::languageManager()->getDefaultLanguage()->getId();
33 34
    $this->links = array();
  }
35

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

  public function set_entity_types($entity_types) {
51
    $this->entity_types = is_array($entity_types) ? $entity_types : array();
52 53 54
  }

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

58 59 60 61 62 63 64 65
  /**
   * Generates and returns the sitemap.
   *
   * @param int $max_links
   *  This number dictates how many sitemap chunks are to be created.
   *
   * @return array $sitemaps.
   */
66
  public function generate_sitemap($max_links = NULL) {
67

68 69
    $this->generate_custom_paths();
    $this->generate_entity_paths();
70

71
    $sitemaps = array();
72 73

    // Create sitemap chunks according to the max_links setting.
74 75
    if (!empty($max_links) && count($this->links) > 0) {
      foreach(array_chunk($this->links, $max_links) as $sitemap_id => $sitemap_links) {
76 77
        $sitemaps[] = (object)[
          'sitemap_string' => $this->generate_sitemap_chunk($sitemap_links),
78
          'sitemap_created' => REQUEST_TIME,
79
        ];
80 81
      }
    }
82
    // If max_link setting is not set, create just one sitemap.
83
    else {
84 85
      $sitemaps[] = (object)[
        'sitemap_string' => $this->generate_sitemap_chunk($this->links),
86
        'sitemap_created' => REQUEST_TIME,
87
      ];
88 89 90 91
    }
    return $sitemaps;
  }

92 93 94 95 96 97 98 99
  /**
   * Generates and returns the sitemap index.
   *
   * @param array $sitemap
   *  All sitemap chunks keyed by the chunk ID.
   *
   * @return string sitemap index
   */
100 101 102 103 104 105 106 107
  public function generate_sitemap_index($sitemap) {
    $writer = new XMLWriter();
    $writer->openMemory();
    $writer->setIndent(TRUE);
    $writer->startDocument(self::XML_VERSION, self::ENCODING);
    $writer->startElement('sitemapindex');
    $writer->writeAttribute('xmlns', self::XMLNS);

108
    foreach ($sitemap as $chunk_id => $chunk_data) {
109
      $writer->startElement('sitemap');
110 111
      $writer->writeElement('loc', $GLOBALS['base_url'] . '/sitemaps/'
        . $chunk_id . '/' . 'sitemap.xml');
112
      $writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
113 114 115 116 117 118 119
      $writer->endElement();
    }
    $writer->endElement();
    $writer->endDocument();
    return $writer->outputMemory();
  }

120 121 122 123 124 125 126 127
  /**
   * Generates and returns a sitemap chunk.
   *
   * @param array $sitemap_links
   *  All links with their translation and settings.
   *
   * @return string sitemap chunk
   */
128
  private function generate_sitemap_chunk($sitemap_links) {
129 130 131 132 133 134 135 136 137

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

138
    foreach ($sitemap_links as $link) {
139 140 141
      $writer->startElement('url');

      // Adding url to standard language.
142
      $writer->writeElement('loc', $link['path_data']['urls'][$this->default_language_id]);
143

144
      // Adding alternate urls (other languages) if any.
145 146
      if (count($link['path_data']['urls']) > 1) {
        foreach($link['path_data']['urls'] as $language_id => $localised_url) {
147 148 149 150 151
          $writer->startElement('xhtml:link');
          $writer->writeAttribute('rel', 'alternate');
          $writer->writeAttribute('hreflang', $language_id);
          $writer->writeAttribute('href', $localised_url);
          $writer->endElement();
152 153 154
        }
      }

155
      // Add priority if any.
156 157 158 159
      if (!is_null($link['priority'])) {
        $writer->writeElement('priority', $link['priority']);
      }

160
      // Add lastmod if any.
161 162 163 164 165 166 167
      if (!is_null($link['lastmod'])) {
        $writer->writeElement('lastmod', $link['lastmod']);
      }
      $writer->endElement();
    }
    $writer->endDocument();
    return $writer->outputMemory();
168 169
  }

170
  /**
171
   * Generates custom internal paths.
172
   */
173
  private function generate_custom_paths() {
174
    $link_generator = new CustomLinkGenerator();
175
    $links = $link_generator->get_paths($this->custom);
176
    $this->add_created_paths($links);
177 178
  }

179
  /**
180
   * Lets all simple sitemap plugins add their paths to the sitemap.
181
   */
182
  private function generate_entity_paths() {
183 184 185 186

    $manager = \Drupal::service('plugin.manager.simplesitemap');
    $plugins = $manager->getDefinitions();

187
    // Let all simplesitemap plugins generate add their links to the sitemap.
188 189 190
    foreach ($plugins as $link_generator_plugin) {
      if (isset($this->entity_types[$link_generator_plugin['id']])) {
        $instance = $manager->createInstance($link_generator_plugin['id']);
191 192 193 194 195 196 197 198 199 200 201 202 203 204
        $links = $instance->get_entity_paths($link_generator_plugin['id'],
          $this->entity_types[$link_generator_plugin['id']]);
        $this->add_created_paths($links);
      }
    }
  }

  /**
   * Adds Drupal internal paths generated by a plugin while removing duplicates.
   *
   * @param array $paths
   *  Drupal internal paths generated by a plugin.
   */
  private function add_created_paths($paths) {
205 206

    // Do not include path if anonymous users have no access to it.
207
    foreach($paths as $i => $path) {
208 209 210 211 212
      if (!$path['path_data']['access']) {
        unset($paths[$i]);
        continue;
      }
      // Do not include path if it is a duplicate.
213
      foreach($this->links as $existing_path) {
214
        if ($path['path_data']['path'] === $existing_path['path_data']['path']) {
215
          unset($paths[$i]);
216
          break;
217
        }
218 219
      }
    }
220
    $this->links = array_merge($this->links, $paths);
221 222
  }
}