xmlsitemap.module 79.8 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\HttpFoundation\Request;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33

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

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

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

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

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

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

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

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

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

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

115 116 117
  return $hooks;
}

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

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

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

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

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

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

  return $output;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

335
  return $sitemaps;
336 337
}

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

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

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

  return $sitemap;
370 371 372
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

636
  if (!isset($link_info)) {
637
    $cid = 'xmlsitemap:link_info:' . $language->getId();
638
    if ($cache = \Drupal::cache()->get($cid)) {
639
      $link_info = $cache->data;
640
    }
641
    else {
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]);
andrei.dincu's avatar