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
  ];
107 108 109

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

113 114 115
  return $hooks;
}

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

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

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

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

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

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

  return $output;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

339
  return $sitemaps;
340 341
}

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

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

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

  return $sitemap;
374 375 376
}

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

Darren Oh's avatar
Darren Oh committed
386
/**
387
 * Delete multiple XML sitemaps.
388
 *
389
 * @param array $smids
390
 *   An array of XML sitemap IDs.
Darren Oh's avatar
Darren Oh committed
391
 */
392 393 394 395 396
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);
397
      $sitemap->delete();
398
      \Drupal::moduleHandler()->invokeAll('xmlsitemap_sitemap_delete', [$sitemap]);
399
    }
400
  }
401
}
402

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

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

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

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

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

478
  if ($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
  $directory = xmlsitemap_get_directory($sitemap);
  return _xmlsitemap_delete_recursive($directory, $delete);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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