BatchUrlGenerator.php 14 KB
Newer Older
1 2 3 4 5 6 7 8
<?php

namespace Drupal\simple_sitemap\Batch;

use Drupal\Core\Url;
use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
use Drupal\Core\StringTranslation\StringTranslationTrait;
Pawel G's avatar
Pawel G committed
9 10 11 12 13 14
use Drupal\simple_sitemap\Logger;
use Drupal\simple_sitemap\SitemapGenerator;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Path\PathValidator;
use Drupal\Core\Entity\Query\QueryFactory;
15 16

/**
Pawel G's avatar
Pawel G committed
17 18
 * Class BatchUrlGenerator.
 *
19 20 21 22 23 24 25
 * @package Drupal\simple_sitemap\Batch
 */
class BatchUrlGenerator {

  use StringTranslationTrait;

  const ANONYMOUS_USER_ID = 0;
26 27
  const PATH_DOES_NOT_EXIST_OR_NO_ACCESS_MESSAGE = "The path @path has been omitted from the XML sitemap as it either does not exist, or it is not accessible to anonymous users.";
  const PROCESSING_PATH_MESSAGE = 'Processing path #@current out of @max: @path';
Pawel G's avatar
Pawel G committed
28
  const REGENERATION_FINISHED_MESSAGE = "The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.";
Pawel G's avatar
Pawel G committed
29
  const REGENERATION_FINISHED_ERROR_MESSAGE = 'The sitemap generation finished with an error.';
30 31

  protected $sitemapGenerator;
32
  protected $languageManager;
33
  protected $languages;
34
  protected $defaultLanguageId;
35 36 37
  protected $entityTypeManager;
  protected $pathValidator;
  protected $entityQuery;
Pawel G's avatar
Pawel G committed
38
  protected $logger;
39 40
  protected $anonUser;

41 42 43
  protected $context;
  protected $batchInfo;

44 45
  /**
   * BatchUrlGenerator constructor.
Pawel G's avatar
Pawel G committed
46
   *
47 48 49 50 51
   * @param $sitemap_generator
   * @param $language_manager
   * @param $entity_type_manager
   * @param $path_validator
   * @param $entity_query
Pawel G's avatar
Pawel G committed
52
   * @param $logger
53
   */
54
  public function __construct(
Pawel G's avatar
Pawel G committed
55 56 57 58 59 60
    SitemapGenerator $sitemap_generator,
    LanguageManagerInterface $language_manager,
    EntityTypeManagerInterface $entity_type_manager,
    PathValidator $path_validator,
    QueryFactory $entity_query,
    Logger $logger
61
  ) {
Pawel G's avatar
Pawel G committed
62 63
    // Todo using only one method, maybe make method static instead?
    $this->sitemapGenerator = $sitemap_generator;
64
    $this->languageManager = $language_manager;
65
    $this->languages = $language_manager->getLanguages();
66
    $this->defaultLanguageId = $language_manager->getDefaultLanguage()->getId();
67 68 69
    $this->entityTypeManager = $entity_type_manager;
    $this->pathValidator = $path_validator;
    $this->entityQuery = $entity_query;
Pawel G's avatar
Pawel G committed
70
    $this->logger = $logger;
71 72 73
    $this->anonUser = $this->entityTypeManager->getStorage('user')->load(self::ANONYMOUS_USER_ID);
  }

74 75 76 77 78 79 80 81 82
  /**
   * @param $context
   * @return $this
   */
  public function setContext(&$context) {
    $this->context = &$context;
    return $this;
  }

83 84
  /**
   * @param $batch_info
85
   * @return $this
86
   */
87 88 89
  public function setBatchInfo($batch_info) {
    $this->batchInfo = $batch_info;
    return $this;
90 91 92 93 94 95 96
  }

  /**
   * Batch callback function which generates urls to entity paths.
   *
   * @param array $entity_info
   */
97
  public function generateBundleUrls($entity_info) {
98

99
    foreach ($this->getBatchIterationEntities($entity_info) as $entity_id => $entity) {
100

101 102
      $this->setCurrentId($entity_id);
      $priority = NULL;
103

104 105
      // Overriding entity settings if it has been overridden on entity edit page...
      if (isset($this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index'])) {
106

107 108 109 110 111 112 113
        // Skipping entity if it has been excluded on entity edit page.
        if (!$this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['index']) {
          continue;
        }
        // Otherwise overriding priority settings for this entity.
        $priority = $this->batchInfo['entity_types'][$entity_info['entity_type_name']][$entity_info['bundle_name']]['entities'][$entity_id]['priority'];
      }
114

115 116 117 118
      switch ($entity_info['entity_type_name']) {
        // Loading url object for menu links.
        case 'menu_link_content':
          if (!$entity->isEnabled()) {
119
            continue 2;
120
          }
121 122
          $url_object = $entity->getUrlObject();
          break;
123

124 125 126 127 128
        // Loading url object for other entities.
        default:
          // todo: file entity type does not have a canonical url and breaks generation, hopefully fixed in https://www.drupal.org/node/2402533
          $url_object = $entity->toUrl();
      }
129

130 131 132 133
      // Do not include external paths.
      if (!$url_object->isRouted()) {
        continue;
      }
134

135 136 137 138
      // Do not include paths inaccessible to anonymous users.
      if (!$url_object->access($this->anonUser)) {
        continue;
      }
139

140
      $path = $url_object->getInternalPath();
Pawel G's avatar
Pawel G committed
141 142

      // Do not include paths that have been already indexed.
143 144 145
      if ($this->batchInfo['remove_duplicates'] && $this->pathProcessed($path)) {
        continue;
      }
146

147
      $url_object->setOption('absolute', TRUE);
148

149 150 151 152 153 154 155
      $path_data = [
        'path' => $path,
        'entity_info' => ['entity_type' => $entity_info['entity_type_name'], 'id' => $entity_id],
        'lastmod' => method_exists($entity, 'getChangedTime') ? date_iso8601($entity->getChangedTime()) : NULL,
        'priority' => isset($priority) ? $priority : (isset($entity_info['bundle_settings']['priority']) ? $entity_info['bundle_settings']['priority'] : NULL),
      ];
      $this->addUrlVariants($url_object, $path_data, $entity);
156
    }
157
    $this->processSegment();
158 159 160 161 162 163 164
  }

  /**
   * Batch function which generates urls to custom paths.
   *
   * @param array $custom_paths
   */
165
  public function generateCustomUrls($custom_paths) {
166

167 168 169 170 171
    $custom_paths = $this->getBatchIterationCustomPaths($custom_paths);

    if ($this->needsInitialization()) {
      $this->initializeBatch(count($custom_paths));
    }
172

Pawel G's avatar
Pawel G committed
173
    foreach ($custom_paths as $i => $custom_path) {
174
      $this->setCurrentId($i);
175

Pawel G's avatar
Pawel G committed
176 177
      // todo: Change to different function, as this also checks if current user has access. The user however varies depending if process was started from the web interface or via cron/drush. Use getUrlIfValidWithoutAccessCheck()?
      if (!$this->pathValidator->isValid($custom_path['path'])) {
Pawel G's avatar
Pawel G committed
178 179 180
        $this->logger->m(self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS_MESSAGE, ['@path' => $custom_path['path']])
          ->display('warning', 'administer sitemap settings')
          ->log('warning');
181 182 183 184
        continue;
      }
      $url_object = Url::fromUserInput($custom_path['path'], ['absolute' => TRUE]);

Pawel G's avatar
Pawel G committed
185
      if (!$url_object->access($this->anonUser)) {
186
        continue;
Pawel G's avatar
Pawel G committed
187
      }
188 189

      $path = $url_object->getInternalPath();
Pawel G's avatar
Pawel G committed
190
      if ($this->batchInfo['remove_duplicates'] && $this->pathProcessed($path)) {
191
        continue;
Pawel G's avatar
Pawel G committed
192
      }
193

194
      $entity = $this->getEntityFromUrlObject($url_object);
195 196 197 198 199 200 201 202 203

      $path_data = [
        'path' => $path,
        'lastmod' => method_exists($entity, 'getChangedTime') ? date_iso8601($entity->getChangedTime()) : NULL,
        'priority' => isset($custom_path['priority']) ? $custom_path['priority'] : NULL,
      ];
      if (!is_null($entity)) {
        $path_data['entity_info'] = ['entity_type' => $entity->getEntityTypeId(), 'id' => $entity->id()];
      }
204 205 206 207 208
      $this->addUrlVariants($url_object, $path_data, $entity);
    }
    $this->processSegment();
  }

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  /**
   * @return bool
   */
  protected function isBatch() {
    return $this->batchInfo['from'] != 'nobatch';
  }

  /**
   * @param $path
   * @return bool
   */
  protected function pathProcessed($path) {
    $path_pool = isset($this->context['results']['processed_paths']) ? $this->context['results']['processed_paths'] : [];
    if (in_array($path, $path_pool)) {
      return TRUE;
    }
    $this->context['results']['processed_paths'][] = $path;
    return FALSE;
  }

  /**
   * @param $entity_info
   * @return mixed
   */
  private function getBatchIterationEntities($entity_info) {
    $query = $this->entityQuery->get($entity_info['entity_type_name']);

    if (!empty($entity_info['keys']['id'])) {
      $query->sort($entity_info['keys']['id'], 'ASC');
    }
    if (!empty($entity_info['keys']['bundle'])) {
      $query->condition($entity_info['keys']['bundle'], $entity_info['bundle_name']);
    }
    if (!empty($entity_info['keys']['status'])) {
      $query->condition($entity_info['keys']['status'], 1);
    }

    if ($this->needsInitialization()) {
      $count_query = clone $query;
      $this->initializeBatch($count_query->count()->execute());
    }

    if ($this->isBatch()) {
      $query->range($this->context['sandbox']['progress'], $this->batchInfo['batch_process_limit']);
    }

    return $this->entityTypeManager
      ->getStorage($entity_info['entity_type_name'])
      ->loadMultiple($query->execute());
  }

  /**
   * @param $custom_paths
   * @return mixed
   */
  private function getBatchIterationCustomPaths($custom_paths) {

    if ($this->needsInitialization()) {
      $this->initializeBatch(count($custom_paths));
    }

    if ($this->isBatch()) {
      $custom_paths = array_slice($custom_paths, $this->context['sandbox']['progress'], $this->batchInfo['batch_process_limit']);
    }

    return $custom_paths;
  }

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
  /**
   * @param $url_object
   * @param $path_data
   * @param $entity
   */
  private function addUrlVariants($url_object, $path_data, $entity) {
    $alternate_urls = [];

    $translation_languages = !is_null($entity) && $this->batchInfo['skip_untranslated']
      ? $entity->getTranslationLanguages() : $this->languages;

    if (!is_null($entity) && isset($translation_languages['und'])) {
      $alternate_urls[$this->defaultLanguageId] = $url_object
        ->setOption('language', $this->languages[$this->defaultLanguageId])
        ->toString();
    }
    else {
Pawel G's avatar
Pawel G committed
294
      foreach ($translation_languages as $language) {
295 296 297 298 299
        if (!is_null($entity) && $this->batchInfo['skip_untranslated']) {
          $translation = $entity->getTranslation($language->getId());
          if (!$translation->access('view')) {
            continue;
          }
300
        }
301 302 303
        $alternate_urls[$language->getId()] = $url_object
          ->setOption('language', $language)
          ->toString();
304 305
      }
    }
306

Pawel G's avatar
Pawel G committed
307
    foreach ($alternate_urls as $langcode => $url) {
308 309
      $this->context['results']['generate'][] = $path_data + ['langcode' => $langcode, 'url' => $url, 'alternate_urls' => $alternate_urls];
    }
310 311
  }

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  /**
   * @return bool
   */
  protected function needsInitialization() {
    return empty($this->context['sandbox']);
  }

  /**
   * @param $max
   */
  protected function initializeBatch($max) {
    $this->context['results']['generate'] = !empty($this->context['results']['generate']) ? $this->context['results']['generate'] : [];
    if ($this->isBatch()) {
      $this->context['sandbox']['progress'] = 0;
      $this->context['sandbox']['current_id'] = 0;
      $this->context['sandbox']['max'] = $max;
      $this->context['results']['processed_paths'] = !empty($this->context['results']['processed_paths'])
        ? $this->context['results']['processed_paths'] : [];
    }
  }

  /**
   * @param $id
   */
  protected function setCurrentId($id) {
    if ($this->isBatch()) {
      $this->context['sandbox']['progress']++;
      $this->context['sandbox']['current_id'] = $id;
    }
  }

  /**
   *
   */
  protected function processSegment() {
    if ($this->isBatch()) {
      $this->setProgressInfo();
    }
    if (!empty($this->batchInfo['max_links']) && count($this->context['results']['generate']) >= $this->batchInfo['max_links']) {
      $chunks = array_chunk($this->context['results']['generate'], $this->batchInfo['max_links']);
      foreach ($chunks as $i => $chunk_links) {
        if (count($chunk_links) == $this->batchInfo['max_links']) {
          $remove_sitemap = empty($this->context['results']['chunk_count']);
          $this->sitemapGenerator->generateSitemap($chunk_links, $remove_sitemap);
          $this->context['results']['chunk_count'] = !isset($this->context['results']['chunk_count'])
            ? 1 : $this->context['results']['chunk_count'] + 1;
          $this->context['results']['generate'] = array_slice($this->context['results']['generate'], count($chunk_links));
        }
      }
    }
  }

  /**
   *
   */
  protected function setProgressInfo() {
    if ($this->context['sandbox']['progress'] != $this->context['sandbox']['max']) {
      // Providing progress info to the batch API.
      $this->context['finished'] = $this->context['sandbox']['progress'] / $this->context['sandbox']['max'];
      // Adding processing message after finishing every batch segment.
      end($this->context['results']['generate']);
      $last_key = key($this->context['results']['generate']);
      if (!empty($this->context['results']['generate'][$last_key]['path'])) {
        $this->context['message'] = $this->t(self::PROCESSING_PATH_MESSAGE, [
          '@current' => $this->context['sandbox']['progress'],
          '@max' => $this->context['sandbox']['max'],
          '@path' => HTML::escape($this->context['results']['generate'][$last_key]['path']),
        ]);
      }
    }
  }

  /**
   * @param $url_object
   * @return object|null
   */
  private function getEntityFromUrlObject($url_object) {
    $route_parameters = $url_object->getRouteParameters();
    return !empty($route_parameters) && $this->entityTypeManager
      ->getDefinition($entity_type_id = key($route_parameters), FALSE)
      ? $this->entityTypeManager->getStorage($entity_type_id)
        ->load($route_parameters[$entity_type_id])
      : NULL;
  }

397 398 399 400 401 402 403 404 405 406 407 408
  /**
   * Callback function called by the batch API when all operations are finished.
   *
   * @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
   */
  public function finishGeneration($success, $results, $operations) {
    if ($success) {
      $remove_sitemap = empty($results['chunk_count']);
      if (!empty($results['generate']) || $remove_sitemap) {
        $this->sitemapGenerator->generateSitemap($results['generate'], $remove_sitemap);
      }
      Cache::invalidateTags(['simple_sitemap']);
Pawel G's avatar
Pawel G committed
409 410 411 412
      $this->logger->m(self::REGENERATION_FINISHED_MESSAGE,
        ['@url' => $GLOBALS['base_url'] . '/sitemap.xml'])
        ->display('status')
        ->log('info');
413 414
    }
    else {
Pawel G's avatar
Pawel G committed
415
      $this->logger->m(self::REGENERATION_FINISHED_ERROR_MESSAGE)
Pawel G's avatar
Pawel G committed
416 417
        ->display('error', 'administer sitemap settings')
        ->log('error');
418 419
    }
  }
Pawel G's avatar
Pawel G committed
420

421
}