Batch.php 13 KB
Newer Older
Pawel G's avatar
Pawel G committed
1 2 3 4
<?php
/**
 * @file
 * Contains \Drupal\simple_sitemap\Batch.
5 6 7
 *
 * Helper functions for the Drupal batch API.
 * @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
Pawel G's avatar
Pawel G committed
8 9 10 11 12 13 14 15 16 17 18
 */

namespace Drupal\simple_sitemap;

use Drupal\user\Entity\User;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;


class Batch {
  private $batch;
19
  private $batchInfo;
Pawel G's avatar
Pawel G committed
20 21 22 23 24 25

  const PLUGIN_ERROR_MESSAGE = "The simple_sitemap @plugin plugin has been omitted, as it does not return the required numeric array of path data sets. Each data sets must contain the required path element (relative path string or Drupal\\Core\\Url object) and optionally other elements, like lastmod.";
  const PATH_DOES_NOT_EXIST = "The path @faulty_path has been omitted from the XML sitemap, as it does not exist.";
  const PATH_DOES_NOT_EXIST_OR_NO_ACCESS = "The path @faulty_path has been omitted from the XML sitemap as it either does not exist, or it is not accessible to anonymous users.";
  const ANONYMOUS_USER_ID = 0;

26

Pawel G's avatar
Pawel G committed
27 28 29 30 31 32 33
  function __construct($from = 'form') {
    $this->batch = array(
      'title' => t('Generating XML sitemap'),
      'init_message' => t('Initializing batch...'),
      'error_message' => t('An error occurred'),
      'progress_message' => t('Processing @current out of @total link types.'),
      'operations' => array(),
34
      'finished' => __CLASS__ . '::finishBatch',
Pawel G's avatar
Pawel G committed
35 36
    );
    $config = \Drupal::config('simple_sitemap.settings')->get('settings');
37
    $this->batchInfo = array(
Pawel G's avatar
Pawel G committed
38 39 40 41
      'from' => $from,
      'batch_process_limit' => $config['batch_process_limit'],
      'max_links' => $config['max_links'],
      'remove_duplicates' => $config['remove_duplicates'],
42
      'anonymous_user_account' => User::load(self::ANONYMOUS_USER_ID),
Pawel G's avatar
Pawel G committed
43 44 45
    );
  }

46 47 48
  /**
   * Starts the batch process depending on where it was requested from.
   */
Pawel G's avatar
Pawel G committed
49
  public function start() {
Pawel G's avatar
Pawel G committed
50
    batch_set($this->batch);
51
    switch ($this->batchInfo['from']) {
Pawel G's avatar
Pawel G committed
52 53 54
      case 'form':
        break;
      case 'drush':
Pawel G's avatar
Pawel G committed
55
        $this->batch =& batch_get();
Pawel G's avatar
Pawel G committed
56 57 58 59
        $this->batch['progressive'] = FALSE;
        drush_log($this->batch['init_message'], 'status');
        drush_backend_batch_process();
        break;
60
      case 'backend':
Pawel G's avatar
Pawel G committed
61
        $this->batch =& batch_get();
62
        $this->batch['progressive'] = FALSE;
Pawel G's avatar
Pawel G committed
63
        batch_process(); //todo: Does not take advantage of batch API and eventually runs out of memory on very large sites.
64
        break;
Pawel G's avatar
Pawel G committed
65 66 67
    }
  }

68 69 70 71 72 73
  /**
   * Adds operations to the batch of type 'entity_types' or 'custom_paths'.
   *
   * @param string $type
   * @param array $operations
   */
74
  public function addOperations($type, $operations) {
Pawel G's avatar
Pawel G committed
75 76 77 78
    switch ($type) {
      case 'entity_types':
        foreach ($operations as $operation) {
          $this->batch['operations'][] = array(
79 80
            __CLASS__ . '::generateBundleUrls',
            array($operation['query'], $operation['info'], $this->batchInfo)
Pawel G's avatar
Pawel G committed
81 82 83 84 85
          );
        };
        break;
      case 'custom_paths':
        $this->batch['operations'][] = array(
86 87
          __CLASS__ . '::generateCustomUrls',
          array($operations, $this->batchInfo)
Pawel G's avatar
Pawel G committed
88 89 90 91 92
        );
        break;
    }
  }

93 94 95 96 97
  /**
   * 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
   */
98
  public static function finishBatch($success, $results, $operations) {
Pawel G's avatar
Pawel G committed
99 100
    if ($success) {
      if (!empty($results) || is_null(db_query('SELECT MAX(id) FROM {simple_sitemap}')->fetchField())) {
101
        SitemapGenerator::generateSitemap($results['generate']);
Pawel G's avatar
Pawel G committed
102 103 104 105 106 107 108 109 110
      }
      drupal_set_message(t("The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.",
        array('@url' => $GLOBALS['base_url'] . '/sitemap.xml')));
    }
    else {
    }
  }

  /**
111
   * Batch callback function which generates urls to entity paths.
Pawel G's avatar
Pawel G committed
112
   *
113 114 115 116
   * @param object $query
   * @param array $info
   * @param array $batch_info
   * @param array &$context
Pawel G's avatar
Pawel G committed
117
   *
118
   * @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
Pawel G's avatar
Pawel G committed
119
   */
120
  public static function generateBundleUrls($query, $info, $batch_info, &$context) {
Pawel G's avatar
Pawel G committed
121
    $languages = \Drupal::languageManager()->getLanguages();
122
    $default_language_id = Simplesitemap::getDefaultLangId();
Pawel G's avatar
Pawel G committed
123

124 125
    // Initializing batch.
    if (empty($context['sandbox'])) {
126
      self::InitializeBatch($query->countQuery()->execute()->fetchField(), $context);
127 128
    }

Pawel G's avatar
Pawel G committed
129 130 131 132 133 134
    // Getting id field name from plugin info, if not defined assuming the name of the first field in the query to be the entity id field name.
    $fields = $query->getFields();
    if (isset($info['field_info']['entity_id']) && isset($fields[$info['field_info']['entity_id']])) {
      $id_field = $info['field_info']['entity_id'];
    }
    else {
135
      //todo: register error
Pawel G's avatar
Pawel G committed
136 137 138 139 140 141 142
    }

    // Getting the name of the route name field if any.
    if (!empty($info['field_info']['route_name'])) {
      $route_name_field = $info['field_info']['route_name'];
    }

143 144 145
    // Getting the name of the route parameter field if any.
    if (!empty($info['field_info']['route_parameters'])) {
      $route_params_field = $info['field_info']['route_parameters'];
Pawel G's avatar
Pawel G committed
146 147 148
    }

    // Creating a query limited to n=batch_process_limit entries.
149 150 151 152 153 154
    $query
      ->condition($id_field, $context['sandbox']['current_id'], '>')
      ->orderBy($id_field);
    if (!empty($batch_info['batch_process_limit']))
      $query->range(0, $batch_info['batch_process_limit']);
    $result = $query->execute()->fetchAll();
Pawel G's avatar
Pawel G committed
155 156

    foreach ($result as $row) {
157
      self::SetCurrentId($row->$id_field, $context);
Pawel G's avatar
Pawel G committed
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

      // Setting route parameters if they exist in the database (menu links).
      if (isset($route_params_field) && !empty($route_parameters = unserialize($row->$route_params_field))) {
        $route_parameters = array(key($route_parameters) => $route_parameters[key($route_parameters)]);
      }
      elseif (!empty($info['path_info']['entity_type'])) {
        $route_parameters = array($info['path_info']['entity_type'] => $row->$id_field);
      }
      else {
        $route_parameters = array();
      }

      // Getting the name of the options field if any.
      if (!empty($info['field_info']['options'])) {
        $options_field = $info['field_info']['options'];
      }

      // Setting options if they exist in the database (menu links)
      $options = isset($options_field) && !empty($options = unserialize($row->$options_field)) ? $options : array();
      $options['absolute'] = TRUE;

      // Setting route name if it exists in the database (menu links)
      if (isset($route_name_field)) {
        $route_name = $row->$route_name_field;
      }
      elseif (isset($info['path_info']['route_name'])) {
        $route_name = $info['path_info']['route_name'];
      }
      else {
        continue;
      }

      $url_object = Url::fromRoute($route_name, $route_parameters, $options);

192
      if (!$url_object->access($batch_info['anonymous_user_account']))
Pawel G's avatar
Pawel G committed
193 194 195 196
        continue;

      // Do not include path if it already exists.
      $path = $url_object->getInternalPath();
197
      if ($batch_info['remove_duplicates'] && self::batchProcessed($path, $context['results']['processed_paths']))
198
        continue;
Pawel G's avatar
Pawel G committed
199 200 201 202 203 204 205 206 207 208 209 210

      $urls = array();
      foreach ($languages as $language) {
        if ($language->getId() === $default_language_id) {
          $urls[$default_language_id] = $url_object->toString();
        }
        else {
          $options['language'] = $language;
          $urls[$language->getId()] = Url::fromRoute($route_name, $route_parameters, $options)
            ->toString();
        }
      }
211
      $context['results']['generate'][] = array(
Pawel G's avatar
Pawel G committed
212 213 214
        'path' => $path,
        'urls' => $urls,
        'options' => $url_object->getOptions(),
215
        'lastmod' => !empty($info['field_info']['lastmod']) ? date_iso8601($row->{$info['field_info']['lastmod']}) : NULL,
Pawel G's avatar
Pawel G committed
216 217 218
        'priority' => !empty($info['bundle_settings']['priority']) ? $info['bundle_settings']['priority'] : NULL,
      );
    }
219 220
    self::setProgressInfo($context, $batch_info);
    self::processSegment($context, $batch_info);
Pawel G's avatar
Pawel G committed
221 222
  }

223 224
 /**
   * Batch function which generates urls to custom paths.
Pawel G's avatar
Pawel G committed
225
   *
226 227 228
   * @param array $custom_paths
   * @param array $batch_info
   * @param array &$context
Pawel G's avatar
Pawel G committed
229
   *
230
   * @see https://api.drupal.org/api/drupal/core!includes!form.inc/group/batch/8
Pawel G's avatar
Pawel G committed
231
   */
232
  public static function generateCustomUrls($custom_paths, $batch_info, &$context) {
Pawel G's avatar
Pawel G committed
233 234

    $languages = \Drupal::languageManager()->getLanguages();
235
    $default_language_id = Simplesitemap::getDefaultLangId();
Pawel G's avatar
Pawel G committed
236

237 238
    // Initializing batch.
    if (empty($context['sandbox'])) {
239
      self::InitializeBatch(count($custom_paths), $context);
240
    }
Pawel G's avatar
Pawel G committed
241 242

    foreach($custom_paths as $i => $custom_path) {
243
      self::SetCurrentId($i, $context);
Pawel G's avatar
Pawel G committed
244 245

      $user_input = $custom_path['path'][0] === '/' ? $custom_path['path'] : '/' . $custom_path['path'];
246
      if (!\Drupal::service('path.validator')->isValid($custom_path['path'])) { //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.
247
        self::registerError(self::PATH_DOES_NOT_EXIST_OR_NO_ACCESS, array('@faulty_path' => $custom_path['path']), 'warning');
Pawel G's avatar
Pawel G committed
248 249
        continue;
      }
250
      $options = array('absolute' => TRUE, 'language' => $languages[$default_language_id]);
Pawel G's avatar
Pawel G committed
251 252
      $url_object = Url::fromUserInput($user_input, $options);

253
      if (!$url_object->access($batch_info['anonymous_user_account']))
Pawel G's avatar
Pawel G committed
254 255 256
        continue;

      $path = $url_object->getInternalPath();
257
      if ($batch_info['remove_duplicates'] && self::batchProcessed($path, $context['results']['processed_paths']))
258
        continue;
Pawel G's avatar
Pawel G committed
259 260 261 262 263 264 265 266 267 268 269

      $urls = array();
      foreach($languages as $language) {
        if ($language->getId() === $default_language_id) {
          $urls[$default_language_id] = $url_object->toString();
        }
        else {
          $options['language'] = $language;
          $urls[$language->getId()] = Url::fromUserInput($user_input, $options)->toString();
        }
      }
270 271

      $context['results']['generate'][] = array(
Pawel G's avatar
Pawel G committed
272 273 274 275 276 277
        'path' => $path,
        'urls' => $urls,
        'options' => $url_object->getOptions(),
        'priority' => !empty($custom_path['priority']) ? $custom_path['priority'] : NULL,
      );
    }
278 279
    self::setProgressInfo($context, $batch_info);
    self::processSegment($context, $batch_info);
280 281
  }

282
  private static function batchProcessed($needle, &$path_pool) {
283 284 285 286 287 288 289
    if (in_array($needle, $path_pool)) {
      return TRUE;
    }
    $path_pool[] = $needle;
    return FALSE;
  }

290
  private static function InitializeBatch($max, &$context) {
291 292 293 294 295 296 297
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_id'] = 0;
    $context['sandbox']['max'] = $max;
    $context['results']['generate'] = !empty($context['results']['generate']) ? $context['results']['generate'] : array();
    $context['results']['processed_paths'] = !empty($context['results']['processed_paths']) ? $context['results']['processed_paths'] : array();
  }

298
  private static function SetCurrentId($id, &$context) {
299 300 301 302 303
    $context['sandbox']['progress']++;
    $context['sandbox']['current_id'] = $id;
  }


304
  private static function setProgressInfo(&$context, $batch_info) {
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
      // Providing progress info to the batch API.
      $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
      // Adding processing message after finishing every batch segment.
      end($context['results']['generate']);
      $last_key = key($context['results']['generate']);
      if (!empty($context['results']['generate'][$last_key]['path'])) {
        $context['message'] = t("Processing path @current out of @max: @path", array(
          '@current' => $context['sandbox']['progress'],
          '@max' => $context['sandbox']['max'],
          '@path' => HTML::escape($context['results']['generate'][$last_key]['path']),
        ));
      }
    }
  }

321
  private static function processSegment(&$context, $batch_info) {
322 323 324 325
    if (!empty($batch_info['max_links']) && count($context['results']['generate']) >= $batch_info['max_links']) {
      $chunks = array_chunk($context['results']['generate'], $batch_info['max_links']);
      foreach ($chunks as $i => $chunk_links) {
        if (count($chunk_links) == $batch_info['max_links']) {
326
          SitemapGenerator::generateSitemap($chunk_links);
327 328 329 330
          $context['results']['generate'] = array_slice($context['results']['generate'], count($chunk_links));
        }
      }
    }
Pawel G's avatar
Pawel G committed
331 332 333 334 335 336 337 338 339 340 341 342 343
  }

  /**
   * Logs and displays an error.
   *
   * @param $message
   *  Untranslated message.
   * @param array $substitutions (optional)
   *  Substitutions (placeholder => substitution) which will replace placeholders
   *  with strings.
   * @param string $type (optional)
   *  Message type (status/warning/error).
   */
344
  private static function registerError($message, $substitutions = array(), $type = 'error') {
Pawel G's avatar
Pawel G committed
345 346 347 348 349
    $message = strtr(t($message), $substitutions);
    \Drupal::logger('simple_sitemap')->notice($message);
    drupal_set_message($message, $type);
  }
}