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

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

341
  return $sitemaps;
342 343
}

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

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

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

  return $sitemap;
376 377 378
}

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

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

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

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

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

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

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

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

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

503 504 505
/**
 * Check all directories.
 */
506
function xmlsitemap_check_all_directories() {
507
  $directories = [];
508 509

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

528 529 530 531 532 533 534 535 536 537 538
/**
 * 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.
 */
539
function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete = FALSE) {
540 541 542 543 544 545
  if ($directory = xmlsitemap_get_directory($sitemap)) {
    return _xmlsitemap_delete_recursive($directory, $delete);
  }
  else {
    return FALSE;
  }
546 547
}

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

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

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

635 636
  if ($reset) {
    $link_info = NULL;
637 638 639
    foreach (\Drupal::languageManager()->getLanguages() as $lang) {
      \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
    }
640 641
  }

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

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

  return $link_info;
Darren Oh's avatar
Darren Oh committed
700 701
}

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

723 724 725
/**
 * Returns statistics about specific entity links.
 *
726
 * @param string $entity_type_id
727 728
 *   Entity type id.
 * @param string $bundle
729
 *   Bundle id.
730 731 732 733
 *
 * @return array
 *   Array with statistics.
 */
734 735 736
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);
737

738 739
  $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();
740

741
  try {
742 743 744 745 746 747 748 749 750 751 752 753 754
    $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();
755 756
    return $status;
  }
757
  catch (\Exception $e) {
758 759
    $status['total'] = 0;
  }
760 761
  return $status;
}
762

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

794
  foreach ($settings as $key => $value) {
795
    \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle}")->set($key, $value)->save();
796 797
  }

798
  foreach (\Drupal::languageManager()->getLanguages() as $lang) {
799
    \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
800 801
  }
  xmlsitemap_get_link_info(NULL, TRUE);
802 803
}

804 805 806 807 808 809 810 811 812 813
/**
 * Renames a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle_old
 *   Old bundle name.
 * @param string $bundle_new
 *   New bundle name.
 */
814 815
function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  if ($bundle_old != $bundle_new) {
816 817
    if (!\Drupal::config("xmlsitemap.settings.{$entity}.{$bundle_old}")->isNew()) {
      $settings = xmlsitemap_link_bundle_load($entity, $bundle_old);
818
      \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle_old}")->delete();
819
      xmlsitemap_link_bundle_settings_save($entity, $bundle_new, $settings, FALSE);
RenatoG's avatar