xmlsitemap.module 81.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\Environment;
15
use Drupal\Component\Utility\UrlHelper;
16 17
use Drupal\Core\Cache\Cache;
use Drupal\Core\Database\Query\AlterableInterface;
18
use Drupal\Core\Database\Query\Condition;
19
use Drupal\Core\Entity\ContentEntityFormInterface;
20
use Drupal\Core\Entity\ContentEntityInterface;
21
use Drupal\Core\Entity\ContentEntityTypeInterface;
22
use Drupal\Core\Entity\EntityInterface;
23
use Drupal\Core\Entity\Query\QueryInterface;
24
use Drupal\Core\File\FileSystemInterface;
25
use Drupal\Core\Form\FormStateInterface;
26
use Drupal\Core\Language\LanguageInterface;
27 28
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
29
use Drupal\Core\Site\Settings;
30
use Drupal\Core\Url;
31 32
use Drupal\xmlsitemap\Entity\XmlSitemap;
use Drupal\xmlsitemap\XmlSitemapInterface;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
36

37 38 39
/**
 * The maximum number of links in one sitemap chunk file.
 */
40
const XMLSITEMAP_MAX_SITEMAP_LINKS = 50000;
41

42 43 44
/**
 * The maximum filesize of a sitemap chunk file.
 */
45
const XMLSITEMAP_MAX_SITEMAP_FILESIZE = 52528800;
46

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

62 63 64
/**
 * Short lastmod timestamp format.
 */
65
const XMLSITEMAP_LASTMOD_SHORT = 'Y-m-d';
66 67 68 69

/**
 * Medium lastmod timestamp format.
 */
70
const XMLSITEMAP_LASTMOD_MEDIUM = 'Y-m-d\TH:i\Z';
71 72 73 74

/**
 * Long lastmod timestamp format.
 */
75
const XMLSITEMAP_LASTMOD_LONG = 'c';
76

77 78 79
/**
 * The default inclusion status for link types in the sitemaps.
 */
80
const XMLSITEMAP_STATUS_DEFAULT = 0;
81 82 83 84

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

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

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

118 119 120
  return $hooks;
}

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

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

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

138
    case 'xmlsitemap.admin_search_list':
139
      break;
140

141
    case 'xmlsitemap.admin_rebuild':
142 143 144
      $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>';
  }

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

  return $output;
}

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

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

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

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

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

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

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

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

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

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

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

280 281
  // @todo Remove when stable.
  if (!isset($defaults[$name])) {
282
    trigger_error("Default variable for $name not found.");
283 284
  }

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

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

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

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

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

338
  return $sitemaps;
339 340
}

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

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

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

  return $sitemap;
373 374 375
}

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

Darren Oh's avatar
Darren Oh committed
385
/**
386
 * Delete multiple XML sitemaps.
387
 *
388
 * @param array $smids
389
 *   An array of XML sitemap IDs.
Darren Oh's avatar
Darren Oh committed
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) {
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
function xmlsitemap_sitemap_get_context_hash(array &$context) {
441
  ksort($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' => Settings::get('xmlsitemap_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 477 478 479
  if (empty($directory)) {
    return FALSE;
  }
  elseif ($sitemap != NULL && !empty($sitemap->id)) {
480
    return file_build_uri($directory . '/' . $sitemap->id);
481 482 483 484
  }
  else {
    return file_build_uri($directory);
  }
Darren Oh's avatar
Darren Oh committed
485 486 487
}

/**
488
 * Check that the sitemap files directory exists and is writable.
Darren Oh's avatar
Darren Oh committed
489
 */
490
function xmlsitemap_check_directory(XmlSitemapInterface $sitemap = NULL) {
491
  $directory = xmlsitemap_get_directory($sitemap);
492 493 494
  /** @var \Drupal\Core\File\FileSystemInterface $filesystem */
  $filesystem = \Drupal::service('file_system');
  $result = $filesystem->prepareDirectory($directory, $filesystem::CREATE_DIRECTORY | $filesystem::MODIFY_PERMISSIONS);
495
  if (!$result) {
496
    \Drupal::logger('file system')->error('The directory %directory does not exist or is not writable.', ['%directory' => $directory]);
497 498 499 500
  }
  return $result;
}

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

  $sitemaps = xmlsitemap_sitemap_load_multiple(FALSE);
508
  foreach ($sitemaps as $sitemap) {
509 510 511 512
    $directory = xmlsitemap_get_directory($sitemap);
    $directories[$directory] = $directory;
  }

513 514 515
  /** @var \Drupal\Core\File\FileSystemInterface $filesystem */
  $filesystem = \Drupal::service('file_system');

516
  foreach ($directories as $directory) {
517
    $result = $filesystem->prepareDirectory($directory, $filesystem::CREATE_DIRECTORY | $filesystem::MODIFY_PERMISSIONS);
518 519 520 521 522 523 524 525 526 527 528
    if ($result) {
      $directories[$directory] = TRUE;
    }
    else {
      $directories[$directory] = FALSE;
    }
  }

  return $directories;
}

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

549 550 551
/**
 * Move a directory to a new location.
 *
552
 * @param string $old_dir
553
 *   A string specifying the filepath or URI of the original directory.
554
 * @param string $new_dir
555
 *   A string specifying the filepath or URI of the new directory.
556 557
 * @param int $replace
 *   Behavior when the destination file already exists.
558 559
 *   Replace behavior when the destination file already exists.
 *
560
 * @return bool
561 562
 *   TRUE if the directory was moved successfully. FALSE otherwise.
 */
563 564 565 566 567
function xmlsitemap_directory_move($old_dir, $new_dir, $replace = FileSystemInterface::EXISTS_REPLACE) {
  /** @var \Drupal\Core\File\FileSystemInterface $filesystem */
  $filesystem = \Drupal::service('file_system');

  $success = $filesystem->prepareDirectory($new_dir, $filesystem::CREATE_DIRECTORY | $filesystem::MODIFY_PERMISSIONS);
568

569 570
  $old_path = $filesystem->realpath($old_dir);
  $new_path = $filesystem->realpath($new_dir);
571 572 573 574 575 576 577
  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);
578
    $success &= (bool) $filesystem->move($file->uri, $file->uri_new, $replace);
579 580 581
  }

  // The remove the directory.
582
  $success &= $filesystem->rmdir($old_dir);
583 584 585
  return $success;
}

586 587 588
/**
 * Recursively delete all files and folders in the specified filepath.
 *
589
 * This is a backport of Drupal 8's file_unmanaged_delete_recursive().
590 591 592
 *
 * Note that this only deletes visible files with write permission.
 *
593
 * @param string $path
594
 *   A filepath relative to the Drupal root directory.
595
 * @param bool $delete_root
596
 *   A boolean if TRUE will delete the $path directory afterwards.
597 598 599
 *
 * @return bool
 *   TRUE if operation was successful, FALSE otherwise.
600 601
 */
function _xmlsitemap_delete_recursive($path, $delete_root = FALSE) {
602 603 604
  /** @var \Drupal\Core\File\FileSystemInterface $filesystem */
  $filesystem = \Drupal::service('file_system');

605
  // Resolve streamwrapper URI to local path.
606
  $path = $filesystem->realpath($path);
607 608 609 610 611 612 613
  if (is_dir($path)) {
    $dir = dir($path);
    while (($entry = $dir->read()) !== FALSE) {
      if ($entry == '.' || $entry == '..') {
        continue;
      }
      $entry_path = $path . '/' . $entry;
614
      $filesystem->deleteRecursive($entry_path);
615 616
    }
    $dir->close();
617
    return $delete_root ? $filesystem->rmdir($path) : TRUE;
618
  }
619
  return $filesystem->delete($path);
Darren Oh's avatar
Darren Oh committed
620 621 622
}

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

642 643
  if ($reset) {
    $link_info = NULL;
644 645 646
    foreach (\Drupal::languageManager()->getLanguages() as $lang) {
      \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
    }
647 648
  }

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

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

  return $link_info;
Darren Oh's avatar
Darren Oh committed
706 707
}

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

729 730 731
/**
 * Returns statistics about specific entity links.
 *
732
 * @param string $entity_type_id
733 734
 *   Entity type id.
 * @param string $bundle
735
 *   Bundle id.
736 737 738 739
 *
 * @return array
 *   Array with statistics.
 */
740 741
function xmlsitemap_get_link_type_indexed_status($entity_type_id, $bundle = '') {
  $info = xmlsitemap_get_link_info($entity_type_id);
742
  $database = \Drupal::database();
743
  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
744

745 746
  $status['indexed'] = $database->query("SELECT COUNT(id) FROM {xmlsitemap} WHERE type = :entity AND subtype = :bundle", [':entity' => $entity_type_id, ':bundle' => $bundle])->fetchField();
  $status['visible'] = $database->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();
747

748
  try {
749 750 751 752 753 754 755 756 757 758 759 760 761
    $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();
762 763
    return $status;
  }
764
  catch (\Exception $e) {
765 766
    $status['total'] = 0;
  }
767 768
  return $status;
}
769

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