SitemapGeneratorBase.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. <?php
  2. namespace Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator;
  3. use Drupal\simple_sitemap\Plugin\simple_sitemap\SimplesitemapPluginBase;
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Drupal\Core\Database\Connection;
  6. use Drupal\Core\Extension\ModuleHandler;
  7. use Drupal\Core\Language\LanguageManagerInterface;
  8. use Drupal\Component\Datetime\Time;
  9. /**
  10. * Class SitemapGeneratorBase
  11. * @package Drupal\simple_sitemap\Plugin\simple_sitemap\UrlGenerator
  12. */
  13. abstract class SitemapGeneratorBase extends SimplesitemapPluginBase implements SitemapGeneratorInterface {
  14. const FIRST_CHUNK_DELTA = 1;
  15. const INDEX_DELTA = 0;
  16. const GENERATED_BY = 'Generated by the Simple XML sitemap Drupal module: https://drupal.org/project/simple_sitemap.';
  17. const XML_VERSION = '1.0';
  18. const ENCODING = 'UTF-8';
  19. const XMLNS = 'http://www.sitemaps.org/schemas/sitemap/0.9';
  20. /**
  21. * @var \Drupal\Core\Database\Connection
  22. */
  23. protected $db;
  24. /**
  25. * @var \Drupal\Core\Language\LanguageManagerInterface
  26. */
  27. protected $languageManager;
  28. /**
  29. * @var \Drupal\Core\Extension\ModuleHandler
  30. */
  31. protected $moduleHandler;
  32. /**
  33. * @var \Drupal\Component\Datetime\Time
  34. */
  35. protected $time;
  36. /**
  37. * @var array
  38. */
  39. protected $settings;
  40. /**
  41. * @var \Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapWriter
  42. */
  43. protected $writer;
  44. /**
  45. * @var string
  46. */
  47. protected $sitemapVariant;
  48. /**
  49. * @var array
  50. */
  51. protected static $indexAttributes = [
  52. 'xmlns' => self::XMLNS,
  53. ];
  54. /**
  55. * SitemapGeneratorBase constructor.
  56. * @param array $configuration
  57. * @param string $plugin_id
  58. * @param mixed $plugin_definition
  59. * @param \Drupal\Core\Database\Connection $database
  60. * @param \Drupal\Core\Extension\ModuleHandler $module_handler
  61. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  62. * @param \Drupal\Component\Datetime\Time $time
  63. * @param \Drupal\simple_sitemap\Plugin\simple_sitemap\SitemapGenerator\SitemapWriter $sitemap_writer
  64. */
  65. public function __construct(
  66. array $configuration,
  67. $plugin_id,
  68. $plugin_definition,
  69. Connection $database,
  70. ModuleHandler $module_handler,
  71. LanguageManagerInterface $language_manager,
  72. Time $time,
  73. SitemapWriter $sitemap_writer
  74. ) {
  75. parent::__construct($configuration, $plugin_id, $plugin_definition);
  76. $this->db = $database;
  77. $this->moduleHandler = $module_handler;
  78. $this->languageManager = $language_manager;
  79. $this->time = $time;
  80. $this->writer = $sitemap_writer;
  81. $this->sitemapVariant = $this->settings['default_variant'];
  82. }
  83. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  84. return new static(
  85. $configuration,
  86. $plugin_id,
  87. $plugin_definition,
  88. $container->get('database'),
  89. $container->get('module_handler'),
  90. $container->get('language_manager'),
  91. $container->get('datetime.time'),
  92. $container->get('simple_sitemap.sitemap_writer')
  93. );
  94. }
  95. /**
  96. * @param string $sitemap_variant
  97. * @return $this
  98. */
  99. public function setSitemapVariant($sitemap_variant) {
  100. $this->sitemapVariant = $sitemap_variant;
  101. return $this;
  102. }
  103. /**
  104. * @return bool
  105. */
  106. protected function isDefaultVariant() {
  107. return $this->sitemapVariant === $this->settings['default_variant'];
  108. }
  109. /**
  110. * @param array $links
  111. * @return string
  112. */
  113. abstract protected function getXml(array $links);
  114. protected function getChunkInfo() {
  115. return $this->db->select('simple_sitemap', 's')
  116. ->fields('s', ['delta', 'sitemap_created', 'type'])
  117. ->condition('s.type', $this->sitemapVariant)
  118. ->condition('s.delta', self::INDEX_DELTA, '<>')
  119. ->condition('s.status', 0)
  120. ->execute()
  121. ->fetchAllAssoc('delta');
  122. }
  123. /**
  124. * @param array $chunk_info
  125. * @return string
  126. */
  127. protected function getIndexXml(array $chunk_info) {
  128. $this->writer->openMemory();
  129. $this->writer->setIndent(TRUE);
  130. $this->writer->startDocument(self::XML_VERSION, self::ENCODING);
  131. $this->writer->writeComment(self::GENERATED_BY);
  132. $this->writer->startElement('sitemapindex');
  133. // Add attributes to document.
  134. $attributes = self::$indexAttributes;
  135. $sitemap_variant = $this->sitemapVariant;
  136. $this->moduleHandler->alter('simple_sitemap_index_attributes', $attributes, $sitemap_variant);
  137. foreach ($attributes as $name => $value) {
  138. $this->writer->writeAttribute($name, $value);
  139. }
  140. // Add sitemap chunk locations to document.
  141. foreach ($chunk_info as $chunk_data) {
  142. $this->writer->startElement('sitemap');
  143. $this->writer->writeElement('loc', $this->getCustomBaseUrl()
  144. . '/' . (!$this->isDefaultVariant() ? ($chunk_data->type . '/') : '') . 'sitemap.xml?page=' . $chunk_data->delta);
  145. $this->writer->writeElement('lastmod', date_iso8601($chunk_data->sitemap_created));
  146. $this->writer->endElement();
  147. }
  148. $this->writer->endElement();
  149. $this->writer->endDocument();
  150. return $this->writer->outputMemory();
  151. }
  152. /**
  153. * @param string $mode
  154. * @return $this
  155. */
  156. public function remove($mode = 'all') {
  157. self::purgeSitemapVariants($this->sitemapVariant, $mode);
  158. return $this;
  159. }
  160. public static function purgeSitemapVariants($variants = NULL, $mode = 'all') {
  161. if (NULL === $variants || !empty((array) $variants)) {
  162. $delete_query = \Drupal::database()->delete('simple_sitemap');
  163. switch($mode) {
  164. case 'published':
  165. $delete_query->condition('status', 1);
  166. break;
  167. case 'unpublished':
  168. $delete_query->condition('status', 0);
  169. break;
  170. case 'all':
  171. break;
  172. default:
  173. //todo: throw error
  174. }
  175. if (NULL !== $variants) {
  176. $delete_query->condition('type', (array) $variants, 'IN');
  177. }
  178. $delete_query->execute();
  179. }
  180. }
  181. /**
  182. * @param array $links
  183. * @return $this
  184. * @throws \Exception
  185. */
  186. public function generate(array $links) {
  187. $highest_id = $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField();
  188. $highest_delta = $this->db->query('SELECT MAX(delta) FROM {simple_sitemap} WHERE type = :type AND status = :status', [':type' => $this->sitemapVariant, ':status' => 0])
  189. ->fetchField();
  190. $this->db->insert('simple_sitemap')->fields([
  191. 'id' => NULL === $highest_id ? 0 : $highest_id + 1,
  192. 'delta' => NULL === $highest_delta ? self::FIRST_CHUNK_DELTA : $highest_delta + 1,
  193. 'type' => $this->sitemapVariant,
  194. 'sitemap_string' => $this->getXml($links),
  195. 'sitemap_created' => $this->time->getRequestTime(),
  196. 'status' => 0,
  197. ])->execute();
  198. return $this;
  199. }
  200. /**
  201. * @return $this
  202. * @throws \Exception
  203. */
  204. public function generateIndex() {
  205. if (!empty($chunk_info = $this->getChunkInfo()) && count($chunk_info) > 1) {
  206. $index_xml = $this->getIndexXml($chunk_info);
  207. $highest_id = $this->db->query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField();
  208. $this->db->merge('simple_sitemap')
  209. ->keys([
  210. 'delta' => self::INDEX_DELTA,
  211. 'type' => $this->sitemapVariant,
  212. 'status' => 0
  213. ])
  214. ->insertFields([
  215. 'id' => NULL === $highest_id ? 0 : $highest_id + 1,
  216. 'delta' => self::INDEX_DELTA,
  217. 'type' => $this->sitemapVariant,
  218. 'sitemap_string' => $index_xml,
  219. 'sitemap_created' => $this->time->getRequestTime(),
  220. 'status' => 0,
  221. ])
  222. ->updateFields([
  223. 'sitemap_string' => $index_xml,
  224. 'sitemap_created' => $this->time->getRequestTime(),
  225. ])
  226. ->execute();
  227. }
  228. return $this;
  229. }
  230. /**
  231. * @return $this
  232. */
  233. public function publish() {
  234. $unpublished_chunk = $this->db->query('SELECT MAX(id) FROM {simple_sitemap} WHERE type = :type AND status = :status', [':type' => $this->sitemapVariant, ':status' => 0])
  235. ->fetchField();
  236. // Only allow publishing a sitemap variant if there is an unpublished
  237. // sitemap variant, as publishing involves deleting the currently published
  238. // variant.
  239. if (FALSE !== $unpublished_chunk) {
  240. $this->remove('published');
  241. $this->db->query('UPDATE {simple_sitemap} SET status = :status WHERE type = :type', [':type' => $this->sitemapVariant, ':status' => 1]);
  242. }
  243. return $this;
  244. }
  245. /**
  246. * @param array $settings
  247. * @return $this
  248. */
  249. public function setSettings(array $settings) {
  250. $this->settings = $settings;
  251. return $this;
  252. }
  253. /**
  254. * @return string
  255. */
  256. protected function getCustomBaseUrl() {
  257. $customBaseUrl = $this->settings['base_url'];
  258. return !empty($customBaseUrl) ? $customBaseUrl : $GLOBALS['base_url'];
  259. }
  260. }