xmlsitemap.module 80.7 KB
Newer Older
Darren Oh's avatar
Darren Oh committed
1 2 3
<?php

/**
4
 * @defgroup xmlsitemap XML sitemap
Darren Oh's avatar
Darren Oh committed
5 6 7
 */

/**
8 9 10
 * @file
 * Main file for the xmlsitemap module.
 */
11

12
use Drupal\Component\Utility\Crypt;
13
use Drupal\Component\Utility\Unicode;
14
use Drupal\Component\Utility\UrlHelper;
15
use Drupal\Core\Link;
16
use Drupal\Core\Entity\EntityForm;
17
use Drupal\Core\Entity\ContentEntityTypeInterface;
18
use Drupal\Core\Entity\EntityInterface;
19
use Drupal\Core\Session\AnonymousUserSession;
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 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 48 49 50 51 52 53 54 55 56
const XMLSITEMAP_FREQUENCY_YEARLY = 31449600;
// 60 * 60 * 24 * 7 * 52
const XMLSITEMAP_FREQUENCY_MONTHLY = 2419200;
// 60 * 60 * 24 * 7 * 4
const XMLSITEMAP_FREQUENCY_WEEKLY = 604800;
// 60 * 60 * 24 * 7
const XMLSITEMAP_FREQUENCY_DAILY = 86400;
// 60 * 60 * 24
const XMLSITEMAP_FREQUENCY_HOURLY = 3600;
// 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 89 90 91 92 93 94
  $hooks = array(
    '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_sitemap_insert',
    'xmlsitemap_sitemap_update',
99 100 101 102
    'xmlsitemap_sitemap_operations',
    'xmlsitemap_sitemap_delete',
    'xmlsitemap_sitemap_link_url_options_alter',
    'query_xmlsitemap_generate_alter',
103
    'query_xmlsitemap_link_bundle_access_alter',
104
    'form_xmlsitemap_sitemap_edit_form_alter',
105
  );
106 107 108 109 110

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

112 113 114
  return $hooks;
}

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

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

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

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

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

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

  return $output;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

326
  $sitemaps = $storage->loadMultiple($conditions['smid']);
327 328 329 330 331 332
  if (count($sitemaps) <= 0) {
    return array();
  }
  foreach ($sitemaps as &$sitemap) {
    $uri = xmlsitemap_sitemap_uri($sitemap);
    $sitemap->uri = $uri;
Darren Oh's avatar
Darren Oh committed
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 $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 = array();
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 = (object) array('smid' => $sitemap->old_smid);
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 379
function xmlsitemap_sitemap_delete($smid) {
  xmlsitemap_sitemap_delete_multiple(array($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 392
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);
393
      $sitemap->delete();
394
      \Drupal::moduleHandler()->invokeAll('xmlsitemap_sitemap_delete', array($sitemap));
395
    }
396
  }
397
}
398

399 400 401 402
/**
 * Return the expected file path for a specific sitemap chunk.
 *
 * @param $sitemap
403
 *   An XmlSitemapInterface sitemap object.
404 405
 * @param $chunk
 *   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 434 435 436
/**
 * Returns the hash string for a context.
 *
 * @param array $context
 *   Context to be hashed.
 * @return string
 *   Hash string for the context.
 */
437 438
function xmlsitemap_sitemap_get_context_hash(array &$context) {
  asort($context);
439
  return Crypt::hashBase64(serialize($context));
440 441
}

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

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

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

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

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
function xmlsitemap_check_all_directories() {
  $directories = array();

  $sitemaps = xmlsitemap_sitemap_load_multiple(FALSE);
  foreach ($sitemaps as $smid => $sitemap) {
    $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;
}

514 515 516 517 518 519 520 521 522 523 524
/**
 * 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.
 */
525
function xmlsitemap_clear_directory(XmlSitemapInterface $sitemap = NULL, $delete = FALSE) {
526 527 528 529
  $directory = xmlsitemap_get_directory($sitemap);
  return _xmlsitemap_delete_recursive($directory, $delete);
}

530 531 532
/**
 * Move a directory to a new location.
 *
533
 * @param string $old_dir
534
 *   A string specifying the filepath or URI of the original directory.
535
 * @param string $new_dir
536
 *   A string specifying the filepath or URI of the new directory.
537
 * @param int $replaceReplace behavior when the destination file already exists.
538 539
 *   Replace behavior when the destination file already exists.
 *
540
 * @return bool
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
 *   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.
  $success &= drupal_rmdir($old_dir);
  return $success;
}

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

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

616 617
  if ($reset) {
    $link_info = NULL;
618 619 620
    foreach (\Drupal::languageManager()->getLanguages() as $lang) {
      \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
    }
621 622
  }

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

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

  return $link_info;
Darren Oh's avatar
Darren Oh committed
681 682
}

683 684 685 686 687 688 689 690 691
/**
 * Returns enabled bundles of an entity type.
 *
 * @param string $entity_type
 *   Entity type id.
 *
 * @return array
 *   Array with entity bundles info.
 */
692 693 694 695
function xmlsitemap_get_link_type_enabled_bundles($entity_type) {
  $bundles = array();
  $info = xmlsitemap_get_link_info($entity_type);
  foreach ($info['bundles'] as $bundle => $bundle_info) {
696
    $settings = xmlsitemap_link_bundle_load($entity_type, $bundle);
697
    if (!empty($settings['status'])) {
698 699 700 701 702 703
      $bundles[] = $bundle;
    }
  }
  return $bundles;
}

704 705 706
/**
 * Returns statistics about specific entity links.
 *
707
 * @param string $entity_type_id
708 709
 *   Entity type id.
 * @param string $bundle
710
 *   Bundle id.
711 712 713 714
 *
 * @return array
 *   Array with statistics.
 */
715 716 717
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);
718

719 720
  $status['indexed'] = db_query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", array(':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", array(':entity' => $entity_type_id, ':bundle' => $bundle))->fetchField();
721

722
  try {
723 724 725 726 727 728 729 730 731 732 733 734 735
    $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();
736 737
    return $status;
  }
738
  catch (\Exception $e) {
739 740
    $status['total'] = 0;
  }
741 742
  return $status;
}
743

744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
/**
 * 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.
 *
 * @return array
 *   Info about sitemap link.
 */
759 760
function xmlsitemap_link_bundle_settings_save($entity, $bundle, array $settings, $update_links = TRUE) {
  if ($update_links) {
761
    $old_settings = xmlsitemap_link_bundle_load($entity, $bundle);
762
    if ($settings['status'] != $old_settings['status']) {
763
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('status' => $settings['status']), array('type' => $entity, 'subtype' => $bundle, 'status_override' => 0));
764 765
    }
    if ($settings['priority'] != $old_settings['priority']) {
766
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('priority' => $settings['priority']), array('type' => $entity, 'subtype' => $bundle, 'priority_override' => 0));
767 768 769
    }
  }

770
  foreach ($settings as $key => $value) {
771
    \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle}")->set($key, $value)->save();
772 773
  }

774
  foreach (\Drupal::languageManager()->getLanguages() as $lang) {
775
    \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
776 777
  }
  xmlsitemap_get_link_info(NULL, TRUE);
778 779
}

780 781 782 783 784 785 786 787 788 789
/**
 * Renames a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle_old
 *   Old bundle name.
 * @param string $bundle_new
 *   New bundle name.
 */
790 791
function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  if ($bundle_old != $bundle_new) {
792 793
    if (!\Drupal::config("xmlsitemap.settings.{$entity}.{$bundle_old}")->isNew()) {
      $settings = xmlsitemap_link_bundle_load($entity, $bundle_old);
794
      \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle_old}")->delete();
795 796 797
      xmlsitemap_link_bundle_settings_save($entity, $bundle_new, $settings, FALSE);
      \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('subtype' => $bundle_new), array('type' => $entity, 'subtype' => $bundle_old));
    }
798 799 800
  }
}

801
/**
802 803 804 805
 * Renames a link type.
 *
 * @param string $entity_old
 *   Old entity type id.
806
 * @param string or int or object... $entity_newNew entity type id.
807 808 809
 *   New entity type id.
 * @param array $bundles
 *   Bundles to be updated.
810 811
 */
function xmlsitemap_link_type_rename($entity_old, $entity_new, $bundles = NULL) {
812 813 814 815 816
  $variables = \Drupal::config('xmlsitemap.settings')->get();
  foreach ($variables as $key => $value) {
    if (!strpos($key, "xmlsitemap_settings_{$entity_old}") && !strpos($key, "xmlsitemap_entity_{$entity_old}")) {
      continue;
    }
817
    \Drupal::configFactory()->getEditable('xmlsitemap.settings')->clear($key);
818
    if (isset($value)) {
819
      $variable_new = str_replace('xmlsitemap_settings_' . $entity_old, 'xmlsitemap_settings_' . $entity_new, $key);
820
      \Drupal::configFactory()->getEditable('xmlsitemap.settings')->set($variable_new, $value)->save();
821 822 823
    }
  }

824
  \Drupal::service('xmlsitemap.link_storage')->updateMultiple(array('type' => $entity_new), array('type' => $entity_old), FALSE);
825 826 827
  xmlsitemap_get_link_info(NULL, TRUE);
}

828 829 830 831 832 833 834 835 836 837 838 839
/**
 * Loads link bundle info.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle
 *   Bundle info.
 * @param bool $load_bundle_info
 *   If TRUE, loads bundle info.
 * @return array
 *   Info about a bundle.
 */
840 841 842 843 844 845 846
function xmlsitemap_link_bundle_load($entity, $bundle, $load_bundle_info = TRUE) {
  $info = array(
    'entity' => $entity,
    'bundle' => $bundle,
  );
  if ($load_bundle_info) {
    $entity_info = xmlsitemap_get_link_info($entity);
847 848 849
    if (isset($entity_info['bundles'][$bundle])) {
      $info['info'] = $entity_info['bundles'][$bundle];
    }
850
  }
851
  $bundle_settings = \Drupal::config("xmlsitemap.settings.{$entity}.{$bundle}")->get();
852 853 854
  if ($bundle_settings) {
    $info += $bundle_settings;
  }
855 856 857
  $info += array(
    'status' => XMLSITEMAP_STATUS_DEFAULT,
    'priority' => XMLSITEMAP_PRIORITY_DEFAULT,
858
    'changefreq' => 0,
859 860
  );
  return $info;
861 862
}

863 864 865 866 867 868 869 870 871 872
/**
 * Deletes all links of a specific bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle
 *   Bundle id.
 * @param bool $delete_links
 *   If TRUE, deletes bundle links from {xmlsitemap} table.
 */
873
function xmlsitemap_link_bundle_delete($entity, $bundle, $delete_links = TRUE) {
874
  \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle}")->delete();
875
  if ($delete_links) {
876
    \Drupal::service('xmlsitemap.link_storage')->deleteMultiple(array('type' => $entity, 'subtype' => $bundle));
877
  }
878
  xmlsitemap_get_link_info(NULL, TRUE);
879 880
}

881 882 883 884 885 886 887 888 889 890
/**
 * Checks access for a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle
 *   Bundle id.
 * @return bool
 *   If TRUE, access is allowed, FALSE otherwise.
 */
891 892 893 894 895 896 897
function xmlsitemap_link_bundle_access($entity, $bundle = NULL) {
  if (is_array($entity) && !isset($bundle)) {
    $bundle = $entity;
  }
  else {
    $bundle = xmlsitemap_link_bundle_load($entity, $bundle);
  }
898

899 900
  if (isset($bundle['info']['admin'])) {
    $admin = $bundle['info']['admin'];
901 902 903 904 905 906 907 908
    $admin += array('access arguments' => array());

    if (!isset($admin['access callback']) && count($admin['access arguments']) == 1) {
      $admin['access callback'] = 'user_access';
    }

    if (!empty($admin['access callback'])) {
      return call_user_func_array($admin['access callback'], $admin['access arguments']);
909 910 911 912 913
    }
  }

  return FALSE;
}