xmlsitemap.module 80.1 KB
Newer Older
Darren Oh's avatar
Darren Oh committed
1 2 3
<?php

/**
4
 * @file
5
 * @defgroup xmlsitemap XML sitemap
Darren Oh's avatar
Darren Oh committed
6 7 8
 */

/**
9 10 11
 * @file
 * Main file for the xmlsitemap module.
 */
12

13
use Drupal\Component\Utility\Crypt;
14
use Drupal\Component\Utility\Unicode;
15
use Drupal\Component\Utility\UrlHelper;
16 17 18
use Drupal\Core\Cache\Cache;
use Drupal\Core\Database\Query\AlterableInterface;
use Drupal\Core\Entity\ContentEntityInterface;
19
use Drupal\Core\Entity\ContentEntityTypeInterface;
20
use Drupal\Core\Entity\EntityForm;
21
use Drupal\Core\Entity\EntityInterface;
22
use Drupal\Core\Entity\Query\QueryInterface;
23
use Drupal\Core\Form\FormStateInterface;
24
use Drupal\Core\Language\LanguageInterface;
25 26
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
27
use Drupal\Core\Url;
28
use Drupal\Core\Site\Settings;
29 30
use Drupal\xmlsitemap\Entity\XmlSitemap;
use Drupal\xmlsitemap\XmlSitemapInterface;
31
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
34

35 36 37
/**
 * The maximum number of links in one sitemap chunk file.
 */
38
const XMLSITEMAP_MAX_SITEMAP_LINKS = 50000;
39

40 41 42
/**
 * The maximum filesize of a sitemap chunk file.
 */
43
const XMLSITEMAP_MAX_SITEMAP_FILESIZE = 52528800;
44

45
/**
46
 * Xmlsitemap Frequencies.
47
 */
48
const XMLSITEMAP_FREQUENCY_YEARLY = 31449600;
49
// 60 * 60 * 24 * 7 * 52.
50
const XMLSITEMAP_FREQUENCY_MONTHLY = 2419200;
51
// 60 * 60 * 24 * 7 * 4.
52
const XMLSITEMAP_FREQUENCY_WEEKLY = 604800;
53
// 60 * 60 * 24 * 7.
54
const XMLSITEMAP_FREQUENCY_DAILY = 86400;
55
// 60 * 60 * 24.
56
const XMLSITEMAP_FREQUENCY_HOURLY = 3600;
57
// 60 * 60.
58
const XMLSITEMAP_FREQUENCY_ALWAYS = 60;
59

60 61 62
/**
 * Short lastmod timestamp format.
 */
63
const XMLSITEMAP_LASTMOD_SHORT = 'Y-m-d';
64 65 66 67

/**
 * Medium lastmod timestamp format.
 */
68
const XMLSITEMAP_LASTMOD_MEDIUM = 'Y-m-d\TH:i\Z';
69 70 71 72

/**
 * Long lastmod timestamp format.
 */
73
const XMLSITEMAP_LASTMOD_LONG = 'c';
74

75 76 77
/**
 * The default inclusion status for link types in the sitemaps.
 */
78
const XMLSITEMAP_STATUS_DEFAULT = 0;
79 80 81 82

/**
 * The default priority for link types in the sitemaps.
 */
83
const XMLSITEMAP_PRIORITY_DEFAULT = 0.5;
84

85 86 87 88
/**
 * Implements hook_hook_info().
 */
function xmlsitemap_hook_info() {
89
  $hooks = [
90 91 92 93 94 95
    'xmlsitemap_link_info',
    'xmlsitemap_link_info_alter',
    'xmlsitemap_link_alter',
    'xmlsitemap_index_links',
    'xmlsitemap_context_info',
    'xmlsitemap_context_info_alter',
96
    'xmlsitemap_context_url_options',
97
    'xmlsitemap_context',
98 99
    'xmlsitemap_element_alter',
    'xmlsitemap_root_attributes_alter',
100 101
    'xmlsitemap_sitemap_insert',
    'xmlsitemap_sitemap_update',
102 103 104 105
    'xmlsitemap_sitemap_operations',
    'xmlsitemap_sitemap_delete',
    'xmlsitemap_sitemap_link_url_options_alter',
    'query_xmlsitemap_generate_alter',
106
    'query_xmlsitemap_link_bundle_access_alter',
107
    'form_xmlsitemap_sitemap_edit_form_alter',
108
    'xmlsitemap_rebuild_clear',
109
  ];
110 111 112

  $hooks = array_combine($hooks, $hooks);
  foreach ($hooks as $hook => $info) {
113
    $hooks[$hook] = ['group' => 'xmlsitemap'];
114
  }
115

116 117 118
  return $hooks;
}

119 120
/**
 * Implements hook_help().
Darren Oh's avatar
Darren Oh committed
121
 */
122
function xmlsitemap_help($route_name, RouteMatchInterface $route_match) {
123 124
  $output = '';

125
  switch ($route_name) {
126
    case 'help.page.xmlsitemap':
127 128
    case 'xmlsitemap.admin_settings':
    case 'xmlsitemap.entities_settings':
129 130
    case 'entity.xmlsitemap.edit_form':
    case 'entity.xmlsitemap.delete_form':
131
      return;
132

133
    case 'xmlsitemap.admin_search':
134
      break;
135

136
    case 'xmlsitemap.admin_search_list':
137
      break;
138

139
    case 'xmlsitemap.admin_rebuild':
140 141 142
      $output .= '<p>' . t("This action rebuilds your site's XML sitemap and regenerates the cached files, and may be a lengthy process. If you just installed XML sitemap, this can be helpful to import all your site's content into the sitemap. Otherwise, this should only be used in emergencies.") . '</p>';
  }

143
  $currentUser = \Drupal::currentUser();
144
  if (strpos($route_name, 'xmlsitemap') !== FALSE && $currentUser->hasPermission('administer xmlsitemap')) {
145
    // Alert the user to any potential problems detected by hook_requirements.
146
    $output .= _xmlsitemap_get_blurb();
Darren Oh's avatar
Darren Oh committed
147
  }
148 149 150 151

  return $output;
}

152 153 154 155
/**
 * Implements hook_theme().
 */
function xmlsitemap_theme() {
156 157
  return [
    'xmlsitemap_content_settings_table' => [
158 159
      'render element' => 'element',
      'file' => 'xmlsitemap.module',
160 161
    ],
  ];
162 163
}

164 165
/**
 * Menu access callback; determines if the user can use the rebuild links page.
166 167 168
 *
 * @return bool
 *   Returns TRUE if current user can access rebuild form. FALSE otherwise.
169 170 171
 */
function _xmlsitemap_rebuild_form_access() {
  $rebuild_types = xmlsitemap_get_rebuildable_link_types();
172
  return !empty($rebuild_types) && \Drupal::currentUser()->hasPermission('administer xmlsitemap');
173 174
}

Darren Oh's avatar
Darren Oh committed
175
/**
176
 * Implements hook_cron().
177 178 179
 *
 * @todo Use new Queue system. Need to add {sitemap}.queued.
 * @todo Regenerate one at a time?
Darren Oh's avatar
Darren Oh committed
180
 */
181
function xmlsitemap_cron() {
182 183 184 185 186
  // If cron sitemap file regeneration is disabled, stop.
  if (\Drupal::config('xmlsitemap.settings')->get('disable_cron_regeneration')) {
    return;
  }

187
  // If there were no new or changed links, skip.
188
  if (!\Drupal::state()->get('xmlsitemap_regenerate_needed')) {
189 190 191
    return;
  }

192
  // If the minimum sitemap lifetime hasn't been passed, skip.
193
  $lifetime = REQUEST_TIME - \Drupal::state()->get('xmlsitemap_generated_last');
194
  if ($lifetime < \Drupal::config('xmlsitemap.settings')->get('minimum_lifetime')) {
195 196
    return;
  }
197
  xmlsitemap_xmlsitemap_index_links(\Drupal::config('xmlsitemap.settings')->get('batch_limit'));
198
  // Regenerate the sitemap XML files.
199
  xmlsitemap_run_unprogressive_batch('xmlsitemap_regenerate_batch');
Darren Oh's avatar
Darren Oh committed
200 201
}

202
/**
203
 * Implements hook_modules_installed().
204
 */
205
function xmlsitemap_modules_installed(array $modules) {
206
  Cache::invalidateTags(['xmlsitemap']);
207 208 209
}

/**
210
 * Implements hook_modules_uninstalled().
211
 */
212
function xmlsitemap_modules_uninstalled(array $modules) {
213
  Cache::invalidateTags(['xmlsitemap']);
214 215
}

Darren Oh's avatar
Darren Oh committed
216
/**
217
 * Implements hook_robotstxt().
Darren Oh's avatar
Darren Oh committed
218
 */
219
function xmlsitemap_robotstxt() {
220
  if ($sitemap = XmlSitemap::loadByContext()) {
221
    $uri = xmlsitemap_sitemap_uri($sitemap);
222 223
    $path = UrlHelper::isExternal($uri['path']) ? $uri['path'] : 'base://' . $uri['path'];
    $robotstxt[] = 'Sitemap: ' . Url::fromUri($path, $uri['options'])->toString();
224
    return $robotstxt;
225
  }
Darren Oh's avatar
Darren Oh committed
226 227
}

228
/**
229
 * Internal default variables config for xmlsitemap_var().
230 231 232
 *
 * @return array
 *   Array with config variables of xmlsitemap.settings config object.
233
 */
234
function xmlsitemap_config_variables() {
235
  return [
236
    'minimum_lifetime' => 0,
237 238 239 240 241 242 243 244 245
    'xsl' => 1,
    'prefetch_aliases' => 1,
    'chunk_size' => 'auto',
    'batch_limit' => 100,
    'path' => 'xmlsitemap',
    'frontpage_priority' => 1.0,
    'frontpage_changefreq' => XMLSITEMAP_FREQUENCY_DAILY,
    'lastmod_format' => XMLSITEMAP_LASTMOD_MEDIUM,
    'gz' => FALSE,
246
    'disable_cron_regeneration' => FALSE,
247
  ];
248 249
}

250 251
/**
 * Internal default variables state for xmlsitemap_var().
252 253 254
 *
 * @return array
 *   Array with state variables defined by xmlsitemap module.
255 256
 */
function xmlsitemap_state_variables() {
257
  return [
258 259 260 261
    'xmlsitemap_rebuild_needed' => FALSE,
    'xmlsitemap_regenerate_needed' => TRUE,
    'xmlsitemap_base_url' => '',
    'xmlsitemap_generated_last' => 0,
262 263
    'xmlsitemap_developer_mode' => 0,
    'max_chunks' => NULL,
264
    'max_filesize' => NULL,
265
  ];
266 267
}

268 269 270 271 272 273
/**
 * Internal implementation of variable_get().
 */
function xmlsitemap_var($name, $default = NULL) {
  $defaults = &drupal_static(__FUNCTION__);
  if (!isset($defaults)) {
274 275
    $defaults = xmlsitemap_config_variables();
    $defaults += xmlsitemap_state_variables();
276 277
  }

278 279
  // @todo Remove when stable.
  if (!isset($defaults[$name])) {
280
    trigger_error(strtr('Default variable for %variable not found.', ['%variable' => drupal_placeholder($name)]));
281 282
  }

283 284 285 286
  if (\Drupal::state()->get($name, NULL) === NULL) {
    return \Drupal::config('xmlsitemap.settings')->get($name);
  }
  return \Drupal::state()->get($name);
287 288
}

Darren Oh's avatar
Darren Oh committed
289
/**
290
 * @defgroup xmlsitemap_api XML sitemap API.
291
 * @{
292 293
 * This is the XML sitemap API to be used by modules wishing to work with
 * XML sitemap and/or link data.
Darren Oh's avatar
Darren Oh committed
294
 */
295 296 297 298

/**
 * Load an XML sitemap array from the database.
 *
299
 * @param mixed $smid
300
 *   An XML sitemap ID.
301
 *
302
 * @return \Drupal\xmlsitemap\XmlSitemapInterface
303
 *   The XML sitemap object.
304 305
 */
function xmlsitemap_sitemap_load($smid) {
306
  $sitemap = xmlsitemap_sitemap_load_multiple([$smid]);
307
  return $sitemap ? reset($sitemap) : FALSE;
Darren Oh's avatar
Darren Oh committed
308 309 310
}

/**
311 312
 * Load multiple XML sitemaps from the database.
 *
313
 * @param array|bool $smids
314
 *   An array of XML sitemap IDs, or FALSE to load all XML sitemaps.
315
 * @param array $conditions
316
 *   An array of conditions in the form 'field' => $value.
317
 *
318
 * @return \Drupal\xmlsitemap\XmlSitemapInterface[]
319
 *   An array of XML sitemap objects.
Darren Oh's avatar
Darren Oh committed
320
 */
321
function xmlsitemap_sitemap_load_multiple($smids = [], array $conditions = []) {
322 323 324
  if ($smids !== FALSE) {
    $conditions['smid'] = $smids;
  }
325
  else {
326
    $conditions['smid'] = NULL;
327
  }
328
  $storage = Drupal::entityTypeManager()->getStorage('xmlsitemap');
329

330
  /** @var \Drupal\xmlsitemap\XmlSitemapInterface[] $sitemaps */
331
  $sitemaps = $storage->loadMultiple($conditions['smid']);
332
  if (count($sitemaps) <= 0) {
333
    return [];
334
  }
335

336
  return $sitemaps;
337 338
}

Darren Oh's avatar
Darren Oh committed
339
/**
340
 * Save changes to an XML sitemap or add a new XML sitemap.
341
 *
342
 * @param Drupal\xmlsitemap\XmlSitemapInterface $sitemap
343
 *   The XML sitemap array to be saved. If $sitemap->smid is omitted, a new
344 345 346
 *   XML sitemap will be added.
 *
 * @todo Save the sitemap's URL as a column?
Darren Oh's avatar
Darren Oh committed
347
 */
348
function xmlsitemap_sitemap_save(XmlSitemapInterface $sitemap) {
349
  $context = $sitemap->context;
350
  if (!isset($context) || !$context) {
351
    $sitemap->context = [];
352 353
  }

354
  // Make sure context is sorted before saving the hash.
355
  $sitemap->setOriginalId($sitemap->isNew() ? NULL : $sitemap->getId());
356
  $sitemap->setId(xmlsitemap_sitemap_get_context_hash($context));
357
  // If the context was changed, we need to perform additional actions.
358
  if (!$sitemap->isNew() && $sitemap->getId() != $sitemap->getOriginalId()) {
359
    // Rename the files directory so the sitemap does not break.
360
    $old_sitemap = xmlsitemap_sitemap_load($sitemap->getOriginalId());
361
    $old_dir = xmlsitemap_get_directory($old_sitemap);
362 363 364 365
    $new_dir = xmlsitemap_get_directory($sitemap);
    xmlsitemap_directory_move($old_dir, $new_dir);

    // Mark the sitemaps as needing regeneration.
366
    \Drupal::state()->set('xmlsitemap_regenerate_needed', TRUE);
367
  }
368
  $sitemap->save();
369 370

  return $sitemap;
371 372 373
}

/**
374
 * Delete an XML sitemap.
375
 *
376
 * @param string $smid
377
 *   An XML sitemap ID.
378
 */
379
function xmlsitemap_sitemap_delete($smid) {
380
  xmlsitemap_sitemap_delete_multiple([$smid]);
381 382
}

Darren Oh's avatar
Darren Oh committed
383
/**
384
 * Delete multiple XML sitemaps.
385
 *
386
 * @param array $smids
387
 *   An array of XML sitemap IDs.
Darren Oh's avatar
Darren Oh committed
388
 */
389 390 391 392
function xmlsitemap_sitemap_delete_multiple(array $smids) {
  if (!empty($smids)) {
    $sitemaps = xmlsitemap_sitemap_load_multiple($smids);
    foreach ($sitemaps as $sitemap) {
393
      //xmlsitemap_clear_directory($sitemap, TRUE);
394
      $sitemap->delete();
395
      \Drupal::moduleHandler()->invokeAll('xmlsitemap_sitemap_delete', [$sitemap]);
396
    }
397
  }
398
}
399

400 401 402
/**
 * Return the expected file path for a specific sitemap chunk.
 *
403
 * @param Drupal\xmlsitemap\XmlSitemapInterface $sitemap
404
 *   An XmlSitemapInterface sitemap object.
405
 * @param string $chunk
406
 *   An optional specific chunk in the sitemap. Defaults to the index page.
407 408 409
 *
 * @return string
 *   File path for a specific sitemap chunk.
410
 */
411
function xmlsitemap_sitemap_get_file(XmlSitemapInterface $sitemap, $chunk = 'index') {
412
  return xmlsitemap_get_directory($sitemap) . "/{$chunk}.xml";
Darren Oh's avatar
Darren Oh committed
413 414
}

415 416 417
/**
 * Find the maximum file size of all a sitemap's XML files.
 *
418 419
 * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
 *   The XML sitemap object.
420
 */
421
function xmlsitemap_sitemap_get_max_filesize(XmlSitemapInterface $sitemap) {
422
  $dir = xmlsitemap_get_directory($sitemap);
423
  $sitemap->setMaxFileSize(0);
424
  foreach (file_scan_directory($dir, '/\.xml$/') as $file) {
425
    $sitemap->setMaxFileSize(max($sitemap->getMaxFileSize(), filesize($file->uri)));
426
  }
427
  return $sitemap->getMaxFileSize();
428 429
}

430 431 432 433 434
/**
 * Returns the hash string for a context.
 *
 * @param array $context
 *   Context to be hashed.
435
 *
436 437 438
 * @return string
 *   Hash string for the context.
 */
439
function xmlsitemap_sitemap_get_context_hash(array &$context) {
440
  ksort($context);
441
  return Crypt::hashBase64(serialize($context));
442 443
}

Darren Oh's avatar
Darren Oh committed
444
/**
445
 * Returns the uri elements of an XML sitemap.
446
 *
447 448
 * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
 *   The sitemap represented by and XmlSitemapInterface object.
449 450
 *
 * @return array
451 452
 *   An array containing the 'path' and 'options' keys used to build the uri of
 *   the XML sitemap, and matching the signature of url().
Darren Oh's avatar
Darren Oh committed
453
 */
454
function xmlsitemap_sitemap_uri(XmlSitemapInterface $sitemap) {
455
  $uri['path'] = 'sitemap.xml';
456
  $uri['options'] = \Drupal::moduleHandler()->invokeAll('xmlsitemap_context_url_options', [$sitemap->context]);
457
  $context = $sitemap->context;
458
  \Drupal::moduleHandler()->alter('xmlsitemap_context_url_options', $uri['options'], $context);
459
  $uri['options'] += [
460
    'absolute' => TRUE,
461
    'base_url' => Settings::get('xmlsitemap_base_url', \Drupal::state()->get('xmlsitemap_base_url')),
462
  ];
463 464
  return $uri;
}
465

Darren Oh's avatar
Darren Oh committed
466
/**
467
 * @} End of "defgroup xmlsitemap_api"
468
 */
469
function xmlsitemap_get_directory(XmlSitemapInterface $sitemap = NULL) {
470 471
  $directory = &drupal_static(__FUNCTION__);
  if (!isset($directory)) {
472
    $directory = \Drupal::config('xmlsitemap.settings')->get('path');
Darren Oh's avatar
Darren Oh committed
473
  }
474

475 476 477 478
  if (empty($directory)) {
    return FALSE;
  }
  elseif ($sitemap != NULL && !empty($sitemap->id)) {
479
    return file_build_uri($directory . '/' . $sitemap->id);
480 481 482 483
  }
  else {
    return file_build_uri($directory);
  }
Darren Oh's avatar
Darren Oh committed
484 485 486
}

/**
487
 * Check that the sitemap files directory exists and is writable.
Darren Oh's avatar
Darren Oh committed
488
 */
489
function xmlsitemap_check_directory(XmlSitemapInterface $sitemap = NULL) {
490 491 492
  $directory = xmlsitemap_get_directory($sitemap);
  $result = file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  if (!$result) {
493
    \Drupal::logger('file system')->error('The directory %directory does not exist or is not writable.', ['%directory' => $directory]);
494 495 496 497
  }
  return $result;
}

498 499 500
/**
 * Check all directories.
 */
501
function xmlsitemap_check_all_directories() {
502
  $directories = [];
503 504

  $sitemaps = xmlsitemap_sitemap_load_multiple(FALSE);
505
  foreach ($sitemaps as $sitemap) {
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    $directory = xmlsitemap_get_directory($sitemap);
    $directories[$directory] = $directory;
  }

  foreach ($directories as $directory) {
    $result = file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    if ($result) {
      $directories[$directory] = TRUE;
    }
    else {
      $directories[$directory] = FALSE;
    }
  }

  return $directories;
}

523 524 525 526 527 528 529 530 531 532 533
/**
 * Clears sitemap directory.
 *
 * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
 *   Sitemap entity.
 * @param bool $delete
 *   If TRUE, delete the path directory afterwards.
 *
 * @return bool
 *   Returns TRUE is operation was successful, FALSE otherwise.
 */
534
function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete = FALSE) {
535 536 537 538 539 540
  if ($directory = xmlsitemap_get_directory($sitemap)) {
    return _xmlsitemap_delete_recursive($directory, $delete);
  }
  else {
    return FALSE;
  }
541 542
}

543 544 545
/**
 * Move a directory to a new location.
 *
546
 * @param string $old_dir
547
 *   A string specifying the filepath or URI of the original directory.
548
 * @param string $new_dir
549
 *   A string specifying the filepath or URI of the new directory.
550 551
 * @param int $replace
 *   Behavior when the destination file already exists.
552 553
 *   Replace behavior when the destination file already exists.
 *
554
 * @return bool
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
 *   TRUE if the directory was moved successfully. FALSE otherwise.
 */
function xmlsitemap_directory_move($old_dir, $new_dir, $replace = FILE_EXISTS_REPLACE) {
  $success = file_prepare_directory($new_dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);

  $old_path = drupal_realpath($old_dir);
  $new_path = drupal_realpath($new_dir);
  if (!is_dir($old_path) || !is_dir($new_path) || !$success) {
    return FALSE;
  }

  $files = file_scan_directory($old_dir, '/.*/');
  foreach ($files as $file) {
    $file->uri_new = $new_dir . '/' . basename($file->filename);
    $success &= (bool) file_unmanaged_move($file->uri, $file->uri_new, $replace);
  }

  // The remove the directory.
573
  $success &= \Drupal::service('file_system')->rmdir($old_dir);
574 575 576
  return $success;
}

577 578 579
/**
 * Recursively delete all files and folders in the specified filepath.
 *
580
 * This is a backport of Drupal 8's file_unmanaged_delete_recursive().
581 582 583
 *
 * Note that this only deletes visible files with write permission.
 *
584
 * @param string $path
585
 *   A filepath relative to the Drupal root directory.
586
 * @param bool $delete_root
587
 *   A boolean if TRUE will delete the $path directory afterwards.
588 589 590
 *
 * @return bool
 *   TRUE if operation was successful, FALSE otherwise.
591 592 593 594 595 596 597 598 599 600 601
 */
function _xmlsitemap_delete_recursive($path, $delete_root = FALSE) {
  // Resolve streamwrapper URI to local path.
  $path = drupal_realpath($path);
  if (is_dir($path)) {
    $dir = dir($path);
    while (($entry = $dir->read()) !== FALSE) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $entry_path = $path . '/' . $entry;
602
      file_unmanaged_delete_recursive($entry_path, NULL);
603 604
    }
    $dir->close();
605
    return $delete_root ? \Drupal::service('file_system')->rmdir($path) : TRUE;
606 607
  }
  return file_unmanaged_delete($path);
Darren Oh's avatar
Darren Oh committed
608 609 610
}

/**
611 612
 * Returns information about supported sitemap link types.
 *
613
 * @param mixed $type
614 615
 *   (optional) The link type to return information for. If omitted,
 *   information for all link types is returned.
616
 * @param mixed $reset
617 618 619
 *   (optional) Boolean whether to reset the static cache and do nothing. Only
 *   used for tests.
 *
620 621 622
 * @return array
 *   Info about sitemap link.
 *
623 624
 * @see hook_xmlsitemap_link_info()
 * @see hook_xmlsitemap_link_info_alter()
Darren Oh's avatar
Darren Oh committed
625
 */
626
function xmlsitemap_get_link_info($type = NULL, $reset = FALSE) {
627
  $language = \Drupal::languageManager()->getCurrentLanguage();
628
  $link_info = &drupal_static(__FUNCTION__);
629

630 631
  if ($reset) {
    $link_info = NULL;
632 633 634
    foreach (\Drupal::languageManager()->getLanguages() as $lang) {
      \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
    }
635 636
  }

637
  if (!isset($link_info)) {
638
    $cid = 'xmlsitemap:link_info:' . $language->getId();
639
    if ($cache = \Drupal::cache()->get($cid)) {
640
      $link_info = $cache->data;
641
    }
642
    else {
643
      $link_info = [];
644
      $entity_types = \Drupal::entityTypeManager()->getDefinitions();
645
      foreach ($entity_types as $key => $entity_type) {
646
        $link_info[$key] = [
647 648 649
          'label' => $entity_type->getLabel(),
          'type' => $entity_type->id(),
          'base table' => $entity_type->getBaseTable(),
650
          'bundles' => \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type->id()),
651
        ];
652 653
        $uri_callback = $entity_type->getUriCallback();
        if (empty($uri_callback) || !isset($entity_type->xmlsitemap)) {
654
          // Remove any non URL-able or XML sitemap un-supported entities.
655
        }
656
        foreach (\Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type->id()) as $bundle) {
657 658 659 660
          if (!isset($bundle['xmlsitemap'])) {
            // Remove any un-supported entity bundles.
          }
        }
661
      }
662
      $link_info = array_merge($link_info, \Drupal::moduleHandler()->invokeAll('xmlsitemap_link_info'));
663
      foreach ($link_info as $key => &$info) {
664
        $info += [
665 666
          'type' => $key,
          'base table' => FALSE,
667
          'bundles' => [],
668 669 670
          'xmlsitemap' => [
            'process callback' => 'xmlsitemap_xmlsitemap_process_entity_links',
          ],
671
        ];
672
        if (!isset($info['xmlsitemap']['rebuild callback']) && !empty($info['base table']) && $entity_types[$key]->getKey('id')) {
673 674 675
          $info['xmlsitemap']['rebuild callback'] = 'xmlsitemap_rebuild_batch_fetch';
        }
        foreach ($info['bundles'] as $bundle => &$bundle_info) {
676 677 678
          $bundle_info += [
            'xmlsitemap' => [],
          ];
679 680
          $bundle_info['xmlsitemap'] += xmlsitemap_link_bundle_load($key, $bundle, FALSE);
        }
681
      }
682
      \Drupal::moduleHandler()->alter('xmlsitemap_link_info', $link_info);
683 684
      ksort($link_info);
      // Cache by language since this info contains translated strings.
685
      \Drupal::cache()->set($cid, $link_info, Cache::PERMANENT, ['xmlsitemap']);
686
    }
Darren Oh's avatar
Darren Oh committed
687
  }
688 689 690 691 692 693

  if (isset($type)) {
    return isset($link_info[$type]) ? $link_info[$type] : NULL;
  }

  return $link_info;
Darren Oh's avatar
Darren Oh committed
694 695
}

696 697 698 699 700 701 702 703 704
/**
 * Returns enabled bundles of an entity type.
 *
 * @param string $entity_type
 *   Entity type id.
 *
 * @return array
 *   Array with entity bundles info.
 */
705
function xmlsitemap_get_link_type_enabled_bundles($entity_type) {
706
  $bundles = [];
707 708
  $info = xmlsitemap_get_link_info($entity_type);
  foreach ($info['bundles'] as $bundle => $bundle_info) {
709
    $settings = xmlsitemap_link_bundle_load($entity_type, $bundle);
710
    if (!empty($settings['status'])) {
711 712 713 714 715 716
      $bundles[] = $bundle;
    }
  }
  return $bundles;
}

717 718 719
/**
 * Returns statistics about specific entity links.
 *
720
 * @param string $entity_type_id
721 722
 *   Entity type id.
 * @param string $bundle
723
 *   Bundle id.
724 725 726 727
 *
 * @return array
 *   Array with statistics.
 */
728 729
function xmlsitemap_get_link_type_indexed_status($entity_type_id, $bundle = '') {
  $info = xmlsitemap_get_link_info($entity_type_id);
730
  $database = \Drupal::database();
731
  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
732

733 734
  $status['indexed'] = $database->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", [':entity' => $entity_type_id, ':bundle' => $bundle])->fetchField();
  $status['visible'] = $database->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle AND status = 1 AND access = 1", [':entity' => $entity_type_id, ':bundle' => $bundle])->fetchField();
735

736
  try {
737 738 739 740 741 742 743 744 745 746 747 748 749
    $query = \Drupal::entityQuery($entity_type_id);

    if ($bundle) {
      $query->condition($entity_type->getKey('bundle'), $bundle, '=');
    }

    $query->addTag('xmlsitemap_link_bundle_access');
    $query->addTag('xmlsitemap_link_indexed_status');
    $query->addMetaData('entity_type_id', $entity_type_id);
    $query->addMetaData('bundle', $bundle);
    $query->addMetaData('entity_info', $info);
    $query->count();
    $status['total'] = $query->execute();
750 751
    return $status;
  }
752
  catch (\Exception $e) {
753 754
    $status['total'] = 0;
  }
755 756
  return $status;
}
757

758 759 760 761 762 763 764 765 766 767 768 769
/**
 * Saves xmlsitemap settings for a specific bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle
 *   Bundle id.
 * @param array $settings
 *   Settings to be saved.
 * @param bool $update_links
 *   Update bundle links after settings are saved.
 */
770 771
function xmlsitemap_link_bundle_settings_save($entity, $bundle, array $settings, $update_links = TRUE) {
  if ($update_links) {
772
    $old_settings = xmlsitemap_link_bundle_load($entity, $bundle);
773
    if ($settings['status'] != $old_settings['status']) {
774 775 776 777 778
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(['status' => $settings['status']], [
        'type' => $entity,
        'subtype' => $bundle,
        'status_override' => 0,
      ]);
779 780
    }
    if ($settings['priority'] != $old_settings['priority']) {
781 782 783 784 785
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(['priority' => $settings['priority']], [
        'type' => $entity,
        'subtype' => $bundle,
        'priority_override' => 0,
      ]);
786 787 788
    }
  }

789
  foreach ($settings as $key => $value) {
790
    \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle}")->set($key, $value)->save();
791 792
  }

793
  foreach (\Drupal::languageManager()->getLanguages() as $lang) {
794
    \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
795 796
  }
  xmlsitemap_get_link_info(NULL, TRUE);
797 798
}

799 800 801 802 803 804 805 806 807 808
/**
 * Renames a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle_old
 *   Old bundle name.
 * @param string $bundle_new
 *   New bundle name.
 */
809 810
function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  if ($bundle_old != $bundle_new) {
811 812
    if (!\Drupal::config("xmlsitemap.settings.{$entity}.{$bundle_old}")->isNew()) {
      $settings = xmlsitemap_link_bundle_load($entity, $bundle_old);
813
      \Drupal