xmlsitemap.module 81 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_sitemap_insert',
    'xmlsitemap_sitemap_update',
98 99 100 101
    'xmlsitemap_sitemap_operations',
    'xmlsitemap_sitemap_delete',
    'xmlsitemap_sitemap_link_url_options_alter',
    'query_xmlsitemap_generate_alter',
102
    'query_xmlsitemap_link_bundle_access_alter',
103
    'form_xmlsitemap_sitemap_edit_form_alter',
104
  ];
105 106 107

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

111 112 113
  return $hooks;
}

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

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

128
    case 'xmlsitemap.admin_search':
129
      break;
130

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

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

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

  return $output;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

337
  return $sitemaps;
338 339
}

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

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

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

  return $sitemap;
372 373 374
}

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

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

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

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

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

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

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

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

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

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

  $sitemaps = xmlsitemap_sitemap_load_multiple(FALSE);
503
  foreach ($sitemaps as $sitemap) {
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    $directory = xmlsitemap_get_directory($sitemap);
    $directories[$directory] = $directory;
  }

  foreach ($directories as $directory) {
    $result = file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
    if ($result) {
      $directories[$directory] = TRUE;
    }
    else {
      $directories[$directory] = FALSE;
    }
  }

  return $directories;
}

521 522 523 524 525 526 527 528 529 530 531
/**
 * Clears sitemap directory.
 *
 * @param \Drupal\xmlsitemap\XmlSitemapInterface $sitemap
 *   Sitemap entity.
 * @param bool $delete
 *   If TRUE, delete the path directory afterwards.
 *
 * @return bool
 *   Returns TRUE is operation was successful, FALSE otherwise.
 */
532
function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete = FALSE) {
533 534 535 536
  $directory = xmlsitemap_get_directory($sitemap);
  return _xmlsitemap_delete_recursive($directory, $delete);
}

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

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

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

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

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

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

  return $link_info;
Darren Oh's avatar
Darren Oh committed
689 690
}

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

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

727 728
  $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();
729

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

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

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

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

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

Dave Reid's avatar