xmlsitemap.module 79.6 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
use Drupal\Component\Utility\Crypt;
12
use Drupal\Core\Language\LanguageInterface;
13
use Drupal\xmlsitemap\XmlSitemapInterface;
14
use Drupal\Component\Utility\SafeMarkup;
15
use Drupal\Core\Render\Element;
16
use Drupal\Core\Entity\EntityForm;
17
use Drupal\Core\Entity\EntityInterface;
18
use Drupal\Core\Session\AnonymousUserSession;
19
use Drupal\Core\Routing\RouteMatchInterface;
20
use Drupal\Core\Database\Query\AlterableInterface;
21
use Drupal\Core\Entity\Query\QueryInterface;
22
use Drupal\Core\Entity\Query\QueryException;
23
use Drupal\Core\Cache\Cache;
24
use Drupal\Core\Form\FormStateInterface;
25
use Drupal\Core\Url;
26
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
27
use Symfony\Component\HttpFoundation\Response;
28
use Drupal\Component\Utility\Unicode;
29 30 31 32

/**
 * The maximum number of links in one sitemap chunk file.
 */
33
const XMLSITEMAP_MAX_SITEMAP_LINKS = 50000;
34

35 36 37
/**
 * The maximum filesize of a sitemap chunk file.
 */
38
const XMLSITEMAP_MAX_SITEMAP_FILESIZE = 10485760;
39

40
/**
41
 * Xmlsitemap Frequencies.
42
 */
43 44 45 46 47 48 49 50 51 52
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
53
const XMLSITEMAP_FREQUENCY_ALWAYS = 60;
54

55 56 57
/**
 * Short lastmod timestamp format.
 */
58
const XMLSITEMAP_LASTMOD_SHORT = 'Y-m-d';
59 60 61 62

/**
 * Medium lastmod timestamp format.
 */
63
const XMLSITEMAP_LASTMOD_MEDIUM = 'Y-m-d\TH:i\Z';
64 65 66 67

/**
 * Long lastmod timestamp format.
 */
68
const XMLSITEMAP_LASTMOD_LONG = 'c';
69

70 71 72
/**
 * The default inclusion status for link types in the sitemaps.
 */
73
const XMLSITEMAP_STATUS_DEFAULT = 0;
74 75 76 77

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

80 81 82 83
/**
 * Implements hook_hook_info().
 */
function xmlsitemap_hook_info() {
84 85 86 87 88 89 90
  $hooks = array(
    'xmlsitemap_link_info',
    'xmlsitemap_link_info_alter',
    'xmlsitemap_link_alter',
    'xmlsitemap_index_links',
    'xmlsitemap_context_info',
    'xmlsitemap_context_info_alter',
91
    'xmlsitemap_context_url_options',
92
    'xmlsitemap_context',
93 94
    'xmlsitemap_sitemap_insert',
    'xmlsitemap_sitemap_update',
95 96 97 98
    'xmlsitemap_sitemap_operations',
    'xmlsitemap_sitemap_delete',
    'xmlsitemap_sitemap_link_url_options_alter',
    'query_xmlsitemap_generate_alter',
99
    'query_xmlsitemap_link_bundle_access_alter',
100
    'form_xmlsitemap_sitemap_edit_form_alter',
101
  );
102 103 104 105 106

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

108 109 110
  return $hooks;
}

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

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

125
    case 'xmlsitemap.admin_search':
126
      break;
127

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

131
    case 'xmlsitemap.admin_rebuild':
132 133 134
      $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>';
  }

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

  return $output;
}

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

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

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

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

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

194
/**
195
 * Implements hook_modules_installed().
196
 */
197
function xmlsitemap_modules_installed(array $modules) {
198
  Cache::invalidateTags(array('xmlsitemap'));
199 200 201
}

/**
202
 * Implements hook_modules_uninstalled().
203
 */
204
function xmlsitemap_modules_uninstalled(array $modules) {
205
  Cache::invalidateTags(array('xmlsitemap'));
206 207
}

Darren Oh's avatar
Darren Oh committed
208
/**
209
 * Implements hook_robotstxt().
Darren Oh's avatar
Darren Oh committed
210
 */
211
function xmlsitemap_robotstxt() {
212 213
  $sitemap_storage = \Drupal::entityManager()->getStorage('xmlsitemap');
  if ($sitemap = $sitemap_storage->loadByContext()) {
214
    $uri = xmlsitemap_sitemap_uri($sitemap);
215
    $robotstxt[] = 'Sitemap: ' . Url::fromUri($uri['path'], $uri['options'])->toString();
216
    return $robotstxt;
217
  }
Darren Oh's avatar
Darren Oh committed
218 219
}

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

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

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

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

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

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

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

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

322
  $sitemaps = $storage->loadMultiple($conditions['smid']);
323 324 325 326 327 328
  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
329
  }
330

331
  return $sitemaps;
332 333
}

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

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

    // Mark the sitemaps as needing regeneration.
361
    \Drupal::state()->set('xmlsitemap_regenerate_needed', TRUE);
362
  }
363
  $sitemap->save();
364 365

  return $sitemap;
366 367 368
}

/**
369
 * Delete an XML sitemap.
370
 *
371
 * @param string $smid
372
 *   An XML sitemap ID.
373
 */
374 375
function xmlsitemap_sitemap_delete($smid) {
  xmlsitemap_sitemap_delete_multiple(array($smid));
376 377
}

Darren Oh's avatar
Darren Oh committed
378
/**
379
 * Delete multiple XML sitemaps.
380
 *
381
 * @param array $smids
382
 *   An array of XML sitemap IDs.
Darren Oh's avatar
Darren Oh committed
383
 */
384 385 386 387 388
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);
389
      $sitemap->delete();
390
      \Drupal::moduleHandler()->invokeAll('xmlsitemap_sitemap_delete', array($sitemap));
391
    }
392
  }
393
}
394

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

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

425 426 427 428 429 430 431 432
/**
 * Returns the hash string for a context.
 *
 * @param array $context
 *   Context to be hashed.
 * @return string
 *   Hash string for the context.
 */
433 434
function xmlsitemap_sitemap_get_context_hash(array &$context) {
  asort($context);
435
  return Crypt::hashBase64(serialize($context));
436 437
}

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

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

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

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

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
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;
}

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

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

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

/**
593 594 595 596 597 598 599 600 601
 * 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.
 *
602 603 604
 * @return array
 *   Info about sitemap link.
 *
605 606
 * @see hook_xmlsitemap_link_info()
 * @see hook_xmlsitemap_link_info_alter()
Darren Oh's avatar
Darren Oh committed
607
 */
608
function xmlsitemap_get_link_info($type = NULL, $reset = FALSE) {
609
  $language = \Drupal::languageManager()->getCurrentLanguage();
610
  $link_info = &drupal_static(__FUNCTION__);
611

612 613
  if ($reset) {
    $link_info = NULL;
614 615 616
    foreach (\Drupal::languageManager()->getLanguages() as $lang) {
      \Drupal::cache()->delete('xmlsitemap:link_info:' . $lang->getId());
    }
617 618
  }

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

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

  return $link_info;
Darren Oh's avatar
Darren Oh committed
675 676
}

677 678 679 680 681 682 683 684 685
/**
 * Returns enabled bundles of an entity type.
 *
 * @param string $entity_type
 *   Entity type id.
 *
 * @return array
 *   Array with entity bundles info.
 */
686 687 688 689
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) {
690
    $settings = xmlsitemap_link_bundle_load($entity_type, $bundle);
691
    if (!empty($settings['status'])) {
692 693 694 695 696 697
      $bundles[] = $bundle;
    }
  }
  return $bundles;
}

698 699 700 701 702 703
/**
 * Returns statistics about specific entity links.
 *
 * @param string $entity_type
 *   Entity type id.
 * @param string $bundle
704
 *   Bundle id.
705 706 707 708
 *
 * @return array
 *   Array with statistics.
 */
709 710 711
function xmlsitemap_get_link_type_indexed_status($entity_type, $bundle = '') {
  $info = xmlsitemap_get_link_info($entity_type);

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

715 716 717 718 719 720 721 722 723 724 725 726 727 728
  try {
    $entity_query_object = \Drupal::entityQuery($entity_type);
    $entity_query_object->addTag('xmlsitemap_link_bundle_access');
    $entity_query_object->addTag('xmlsitemap_link_indexed_status');
    $entity_query_object->addMetaData('entity', $entity_type);
    $entity_query_object->addMetaData('type', $bundle);
    $entity_query_object->addMetaData('entity_info', $info);
    $entity_query_object->count();
    $status['total'] = $entity_query_object->execute();
    return $status;
  }
  catch (Exception $e) {
    $status['total'] = 0;
  }
729 730
  return $status;
}
731

732 733 734 735 736 737 738 739 740 741 742 743 744 745
/**
 * Implements hook_entity_query_alter().
 *
 * @todo Remove when http://drupal.org/node/1054168 is fixed.
 */
function xmlsitemap_entity_query_alter($query) {
  $conditions = &$query->entityConditions;

  // Alter user entity queries only.
  if (isset($conditions['entity_type']) && $conditions['entity_type']['value'] == 'user' && isset($conditions['bundle'])) {
    unset($conditions['bundle']);
  }
}

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

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

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

783 784 785 786 787 788 789 790 791 792
/**
 * Renames a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle_old
 *   Old bundle name.
 * @param string $bundle_new
 *   New bundle name.
 */
793 794
function xmlsitemap_link_bundle_rename($entity, $bundle_old, $bundle_new) {
  if ($bundle_old != $bundle_new) {
795 796
    if (!\Drupal::config("xmlsitemap.settings.{$entity}.{$bundle_old}")->isNew()) {
      $settings = xmlsitemap_link_bundle_load($entity, $bundle_old);
797
      \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle_old}")->delete();
798 799 800
      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));
    }
801 802 803
  }
}

804
/**
805 806 807 808
 * Renames a link type.
 *
 * @param string $entity_old
 *   Old entity type id.
809
 * @param string or int or object... $entity_newNew entity type id.
810 811 812
 *   New entity type id.
 * @param array $bundles
 *   Bundles to be updated.
813 814
 */
function xmlsitemap_link_type_rename($entity_old, $entity_new, $bundles = NULL) {
815 816 817 818 819
  $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;
    }
820
    \Drupal::configFactory()->getEditable('xmlsitemap.settings')->clear($key);
821
    if (isset($value)) {
822
      $variable_new = str_replace('xmlsitemap_settings_' . $entity_old, 'xmlsitemap_settings_' . $entity_new, $key);
823
      \Drupal::configFactory()->getEditable('xmlsitemap.settings')->set($variable_new, $value)->save();
824 825 826
    }
  }

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

831 832 833 834 835 836 837 838 839 840 841 842
/**
 * 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.
 */
843 844 845 846 847 848 849
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);
850 851 852
    if (isset($entity_info['bundles'][$bundle])) {
      $info['info'] = $entity_info['bundles'][$bundle];
    }
853
  }
854
  $bundle_settings = \Drupal::config("xmlsitemap.settings.{$entity}.{$bundle}")->get();
855 856 857
  if ($bundle_settings) {
    $info += $bundle_settings;
  }
858 859 860
  $info += array(
    'status' => XMLSITEMAP_STATUS_DEFAULT,
    'priority' => XMLSITEMAP_PRIORITY_DEFAULT,
861
    'changefreq' => 0,
862 863
  );
  return $info;
864 865
}

866 867 868 869 870 871 872 873 874 875
/**
 * 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.
 */
876
function xmlsitemap_link_bundle_delete($entity, $bundle, $delete_links = TRUE) {
877
  \Drupal::configFactory()->getEditable("xmlsitemap.settings.{$entity}.{$bundle}")->delete();
878
  if ($delete_links) {
879
    \Drupal::service('xmlsitemap.link_storage')->deleteMultiple(array('type' => $entity, 'subtype' => $bundle));
880
  }
881
  xmlsitemap_get_link_info(NULL, TRUE);
882 883
}

884 885 886 887 888 889 890 891 892 893
/**
 * 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.
 */
894 895 896 897 898 899 900
function xmlsitemap_link_bundle_access($entity, $bundle = NULL) {
  if (is_array($entity) && !isset($bundle)) {
    $bundle = $entity;
  }
  else {
    $bundle = xmlsitemap_link_bundle_load($entity, $bundle);
  }
901

902 903
  if (isset($bundle['info']['admin'])) {
    $admin = $bundle['info']['admin'];
904 905 906 907 908 909 910 911
    $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']);
912 913 914 915 916
    }
  }

  return FALSE;
}
917

918 919 920 921 922 923 924 925 926 927 928
/**
 * Get path of a bundle.
 *
 * @param string $entity
 *   Entity type id.
 * @param string $bundle
 *   Bundle id.
 *
 * @return
 *   Path of bundle, or FALSE if it does not exist.
 */
929 930 931 932 933 934 935 936 937 938 939 940 941
function xmlsitemap_get_bundle_path($entity, $bundle) {
  $info = xmlsitemap_get_link_info($entity);

  if (!empty($info['bundles'][$bundle]['admin']['real path'])) {
    return $info['bundles'][$bundle]['admin']['real path'];
  }
  elseif (!empty($info['bundles'][$bundle]['admin']['path'])) {
    return $info['bundles'][$bundle]['admin']['path'];
  }
  else {
    return FALSE;
  }
}