xmlsitemap.module 81.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
use Drupal\Core\Link;
17
use Drupal\Core\Entity\EntityForm;
18
use Drupal\Core\Entity\ContentEntityTypeInterface;
19
use Drupal\Core\Entity\EntityInterface;
20
use Drupal\Core\Routing\RouteMatchInterface;
21
use Drupal\Core\Database\Query\AlterableInterface;
22
use Drupal\Core\Entity\Query\QueryInterface;
23
use Drupal\Core\Entity\Query\QueryException;
24
use Drupal\Core\Cache\Cache;
25
use Drupal\Core\Form\FormStateInterface;
26
use Drupal\Core\Language\LanguageInterface;
27
use Drupal\Core\Url;
28 29
use Drupal\xmlsitemap\Entity\XmlSitemap;
use Drupal\xmlsitemap\XmlSitemapInterface;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
use Symfony\Component\HttpFoundation\Response;
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 object
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 $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 array
317
 *   An array of XML sitemap objects.
318 319
 *
 * @codingStandardsIgnoreStart
Darren Oh's avatar
Darren Oh committed
320
 */
321 322
function xmlsitemap_sitemap_load_multiple($smids = [], array $conditions = []) {
  // @codingStandardsIgnoreEnd
323 324 325
  if ($smids !== FALSE) {
    $conditions['smid'] = $smids;
  }
326
  else {
327
    $conditions['smid'] = NULL;
328
  }
329
  $storage = Drupal::entityTypeManager()->getStorage('xmlsitemap');
330

331
  $sitemaps = $storage->loadMultiple($conditions['smid']);
332
  if (count($sitemaps) <= 0) {
333
    return [];
334 335 336 337
  }
  foreach ($sitemaps as &$sitemap) {
    $uri = xmlsitemap_sitemap_uri($sitemap);
    $sitemap->uri = $uri;
Darren Oh's avatar
Darren Oh committed
338
  }
339

340
  return $sitemaps;
341 342
}

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

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

    // Mark the sitemaps as needing regeneration.
370
    \Drupal::state()->set('xmlsitemap_regenerate_needed', TRUE);
371
  }
372
  $sitemap->save();
373 374

  return $sitemap;
375 376 377
}

/**
378
 * Delete an XML sitemap.
379
 *
380
 * @param string $smid
381
 *   An XML sitemap ID.
382
 */
383
function xmlsitemap_sitemap_delete($smid) {
384
  xmlsitemap_sitemap_delete_multiple([$smid]);
385 386
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

715 716 717
/**
 * Returns statistics about specific entity links.
 *
718
 * @param string $entity_type_id
719 720
 *   Entity type id.
 * @param string $bundle
721
 *   Bundle id.
722 723 724 725
 *
 * @return array
 *   Array with statistics.
 */
726 727 728
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);
729

730 731
  $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();
732

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

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

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

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

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