xmlsitemap.module 79.5 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 29
use Drupal\xmlsitemap\Entity\XmlSitemap;
use Drupal\xmlsitemap\XmlSitemapInterface;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
32

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

38 39 40
/**
 * The maximum filesize of a sitemap chunk file.
 */
41
const XMLSITEMAP_MAX_SITEMAP_FILESIZE = 10485760;
42

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

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

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

/**
 * Long lastmod timestamp format.
 */
71
const XMLSITEMAP_LASTMOD_LONG = 'c';
72

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

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

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

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

114 115 116
  return $hooks;
}

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

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

131
    case 'xmlsitemap.admin_search':
132
      break;
133

134
    case 'xmlsitemap.admin_search_list':
135
      break;
136

137
    case 'xmlsitemap.admin_rebuild':
138 139 140
      $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>';
  }

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

  return $output;
}

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

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

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

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

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

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

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

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

226
/**
227
 * Internal default variables config for xmlsitemap_var().
228 229 230
 *
 * @return array
 *   Array with config variables of xmlsitemap.settings config object.
231
 */
232
function xmlsitemap_config_variables() {
233
  return [
234
    'minimum_lifetime' => 0,
235 236 237 238 239 240 241 242 243
    '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,
244
    'disable_cron_regeneration' => FALSE,
245
  ];
246 247
}

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

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

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

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

Darren Oh's avatar
Darren Oh committed
287
/**
288
 * @defgroup xmlsitemap_api XML sitemap API.
289
 * @{
290 291
 * 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
292
 */
293 294 295 296

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

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

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

334
  return $sitemaps;
335 336
}

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

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

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

  return $sitemap;
369 370 371
}

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

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

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

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

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

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

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

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

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

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

  $sitemaps = xmlsitemap_sitemap_load_multiple(FALSE);
503
  foreach ($sitemaps as $sitemap) {
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    $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;
}

521 522 523 524 525 526 527 528 529 530 531
/**
 * 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.
 */
532
function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete = FALSE) {
533 534 535 536 537 538
  if ($directory = xmlsitemap_get_directory($sitemap)) {
    return _xmlsitemap_delete_recursive($directory, $delete);
  }
  else {
    return FALSE;
  }
539 540
}

541 542 543
/**
 * Move a directory to a new location.
 *
544
 * @param string $old_dir
545
 *   A string specifying the filepath or URI of the original directory.
546
 * @param string $new_dir
547
 *   A string specifying the filepath or URI of the new directory.
548 549
 * @param int $replace
 *   Behavior when the destination file already exists.
550 551
 *   Replace behavior when the destination file already exists.
 *
552
 * @return bool
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
 *   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.
571
  $success &= \Drupal::service('file_system')->rmdir($old_dir);
572 573 574
  return $success;
}

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

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

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

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

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

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

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

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

731 732
  $status['indexed'] = db_query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", [':entity' => $entity_type_id, ':bundle' => $bundle])->fetchField();
  $status['visible'] = db_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();
733

734
  try {
735 736 737 738 739 740 741 742 743 744 745 746 747
    $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();
748 749
    return $status;
  }
750
  catch (\Exception $e) {
751 752
    $status['total'] = 0;
  }
753 754
  return $status;
}
755

756 757 758 759 760 761 762 763 764 765 766 767
/**
 * 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.
 */
768 769
function xmlsitemap_link_bundle_settings_save($entity, $bundle, array $settings, $update_links = TRUE) {
  if ($update_links) {
770
    $old_settings = xmlsitemap_link_bundle_load($entity, $bundle);
771
    if ($settings['status'] != $old_settings['status']) {
772 773 774 775 776
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(['status' => $settings['status']], [
        'type' => $entity,
        'subtype' => $bundle,
        'status_override' => 0,
      ]);
777 778
    }
    if ($settings['priority'] != $old_settings['priority']) {
779 780 781 782 783
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(['priority' => $settings['priority']], [
        'type' => $entity,
        'subtype' => $bundle,
        'priority_override' => 0,
      ]);
784 785 786
    }
  }

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

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

797 798 799 800 801 802 803 804 805 806
/**
 * Renames a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle_old
 *   Old bundle name.
 * @param string $bundle_new
 *   New bundle name.
 */
807 808
function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  if ($bundle_old != $bundle_new) {
809 810
    if (!\Drupal::config("xmlsitemap.settings.{$entity}.{$bundle_old}")->isNew()) {
      $settings = xmlsitemap_link_bundle_load($entity, $bundle_old);
811
      \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle_old}")->delete();
812
      xmlsitemap_link_bundle_settings_save($entity, $bundle_new, $settings, FALSE);
813
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(['subtype' => $bundle_new], ['type' => $entity, 'subtype' => $bundle_old]);
814
    }
815 816