batch.inc 15.7 KB
Newer Older
1 2 3
<?php

/**
4 5 6
 * @file
 * Batch processing API for processes to run in multiple HTTP requests.
 *
7
 * Note that batches are usually invoked by form submissions, which is
8 9 10 11 12 13 14
 * why the core interaction functions of the batch processing API live in
 * form.inc.
 *
 * @see form.inc
 * @see batch_set()
 * @see batch_process()
 * @see batch_get()
15 16
 */

17
use Drupal\Component\Utility\Timer;
18
use Drupal\Core\Batch\Percentage;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\RedirectResponse;
22

23
/**
24
 * Renders the batch processing page based on the current state of the batch.
25
 *
26 27 28
 * @param \Symfony\Component\HttpFoundation\Request $request
 *   The current request object.
 *
29
 * @see _batch_shutdown()
30
 */
31
function _batch_page(Request $request) {
32
  $batch = &batch_get();
33

34
  if (!($request_id = $request->get('id'))) {
35 36 37
    return FALSE;
  }

38
  // Retrieve the current state of the batch.
39
  if (!$batch) {
40
    $batch = \Drupal::service('batch.storage')->load($request_id);
41 42
    if (!$batch) {
      drupal_set_message(t('No active batch.'), 'error');
43
      return new RedirectResponse(url('<front>', array('absolute' => TRUE)));
44
    }
45 46
  }

47
  // Register database update for the end of processing.
48
  drupal_register_shutdown_function('_batch_shutdown');
49

50
  // Add batch-specific CSS.
51
  $attached = array('#attached' => array('css' => array()));
52
  foreach ($batch['sets'] as $batch_set) {
53 54
    if (isset($batch_set['css'])) {
      foreach ($batch_set['css'] as $css) {
55
        $attached['#attached']['css'][$css] = array();
56
      }
57 58
    }
  }
59
  drupal_render($attached);
60

61
  $op = $request->get('op', '');
62
  $output = NULL;
63 64
  switch ($op) {
    case 'start':
65 66 67
      // Display the full progress page on startup and on each additional
      // non-JavaScript iteration.
      $output = _batch_progress_page();
68 69 70
      break;

    case 'do':
71
      // JavaScript-based progress page callback.
72
      $output = _batch_do();
73 74 75
      break;

    case 'do_nojs':
76
      // Non-JavaScript-based progress page.
77
      $output = _batch_progress_page();
78 79 80 81 82 83 84 85 86 87 88
      break;

    case 'finished':
      $output = _batch_finished();
      break;
  }

  return $output;
}

/**
89
 * Does one execution pass with JavaScript and returns progress to the browser.
90 91 92
 *
 * @see _batch_progress_page_js()
 * @see _batch_process()
93 94
 */
function _batch_do() {
95
  // Perform actual processing.
96
  list($percentage, $message, $label) = _batch_process();
97

98
  return new JsonResponse(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message, 'label' => $label));
99 100 101
}

/**
102
 * Outputs a batch processing page.
103 104
 *
 * @see _batch_process()
105
 */
106
function _batch_progress_page() {
107
  $batch = &batch_get();
108

109
  $current_set = _batch_current_set();
110
  drupal_set_title($current_set['title'], PASS_THROUGH);
111 112 113 114

  $new_op = 'do_nojs';

  if (!isset($batch['running'])) {
115
    // This is the first page so we return some output immediately.
116 117
    $percentage       = 0;
    $message          = $current_set['init_message'];
118
    $label            = '';
119 120 121
    $batch['running'] = TRUE;
  }
  else {
122
    // This is one of the later requests; do some processing first.
123

124 125 126
    // Error handling: if PHP dies due to a fatal error (e.g. a nonexistent
    // function), it will output whatever is in the output buffer, followed by
    // the error message.
127
    ob_start();
128
    $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
129 130 131 132 133
    $fallback = array(
      '#theme' => 'maintenance_page',
      '#content' => $fallback,
      '#show_messages' => FALSE,
    );
134 135

    // We strip the end of the page using a marker in the template, so any
136 137 138
    // additional HTML output by PHP shows up inside the page rather than below
    // it. While this causes invalid HTML, the same would be true if we didn't,
    // as content is not allowed to appear after </html> anyway.
139
    $fallback = drupal_render($fallback);
140 141 142
    list($fallback) = explode('<!--partial-->', $fallback);
    print $fallback;

143
    // Perform actual processing.
144
    list($percentage, $message, $label) = _batch_process($batch);
145 146 147 148
    if ($percentage == 100) {
      $new_op = 'finished';
    }

149
    // PHP did not die; remove the fallback output.
150 151 152
    ob_end_clean();
  }

153 154 155 156 157 158
  // Merge required query parameters for batch processing into those provided by
  // batch_set() or hook_batch_alter().
  $batch['url_options']['query']['id'] = $batch['id'];
  $batch['url_options']['query']['op'] = $new_op;

  $url = url($batch['url'], $batch['url_options']);
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 192 193 194 195

  $build = array(
    '#theme' => 'progress_bar',
    '#percent' => $percentage,
    '#message' => $message,
    '#label' => $label,
    '#attached' => array(
      'drupal_add_html_head' => array(
        array(
          array(
            // Redirect through a 'Refresh' meta tag if JavaScript is disabled.
            '#tag' => 'meta',
            '#noscript' => TRUE,
            '#attributes' => array(
              'http-equiv' => 'Refresh',
              'content' => '0; URL=' . $url,
            ),
          ),
          'batch_progress_meta_refresh',
        ),
      ),
      // Adds JavaScript code and settings for clients where JavaScript is enabled.
      'js' => array(
        array(
          'type' => 'setting',
          'data' => array(
            'batch' => array(
              'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
              'initMessage' => $current_set['init_message'],
              'uri' => $url,
            ),
          ),
        ),
      ),
      'library' => array(
        array('system', 'drupal.batch'),
      ),
196 197
    ),
  );
198
  return drupal_render($build);
199 200 201
}

/**
202
 * Processes sets in a batch.
203 204 205 206 207 208 209 210
 *
 * If the batch was marked for progressive execution (default), this executes as
 * many operations in batch sets until an execution time of 1 second has been
 * exceeded. It will continue with the next operation of the same batch set in
 * the next request.
 *
 * @return
 *   An array containing a completion value (in percent) and a status message.
211 212
 */
function _batch_process() {
213 214 215
  $batch       = &batch_get();
  $current_set = &_batch_current_set();
  // Indicate that this batch set needs to be initialized.
216
  $set_changed = TRUE;
217

218
  // If this batch was marked for progressive execution (e.g. forms submitted by
219
  // drupal_form_submit()), initialize a timer to determine whether we need to
220 221
  // proceed with the same batch phase when a processing time of 1 second has
  // been exceeded.
222
  if ($batch['progressive']) {
223
    Timer::start('batch_processing');
224 225
  }

226 227 228 229 230 231
  if (empty($current_set['start'])) {
    $current_set['start'] = microtime(TRUE);
  }

  $queue = _batch_queue($current_set);

232
  while (!$current_set['success']) {
233 234 235 236
    // If this is the first time we iterate this batch set in the current
    // request, we check if it requires an additional file for functions
    // definitions.
    if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
237
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
238 239
    }

240
    $task_message = $label = '';
241
    // Assume a single pass operation and set the completion level to 1 by
242
    // default.
243
    $finished = 1;
244 245 246 247 248

    if ($item = $queue->claimItem()) {
      list($function, $args) = $item->data;

      // Build the 'context' array and execute the function call.
249 250 251 252 253 254
      $batch_context = array(
        'sandbox'  => &$current_set['sandbox'],
        'results'  => &$current_set['results'],
        'finished' => &$finished,
        'message'  => &$task_message,
      );
255
      call_user_func_array($function, array_merge($args, array(&$batch_context)));
256

257
      if ($finished >= 1) {
258 259 260 261 262 263 264
        // Make sure this step is not counted twice when computing $current.
        $finished = 0;
        // Remove the processed operation and clear the sandbox.
        $queue->deleteItem($item);
        $current_set['count']--;
        $current_set['sandbox'] = array();
      }
265
    }
266

267
    // When all operations in the current batch set are completed, browse
268 269 270 271 272
    // through the remaining sets, marking them 'successfully processed'
    // along the way, until we find a set that contains operations.
    // _batch_next_set() executes form submit handlers stored in 'control'
    // sets (see form_execute_handlers()), which can in turn add new sets to
    // the batch.
273 274
    $set_changed = FALSE;
    $old_set = $current_set;
275
    while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
276
      $current_set = &_batch_current_set();
277
      $current_set['start'] = microtime(TRUE);
278
      $set_changed = TRUE;
279
    }
280

281 282
    // At this point, either $current_set contains operations that need to be
    // processed or all sets have been completed.
283
    $queue = _batch_queue($current_set);
284

285
    // If we are in progressive mode, break processing after 1 second.
286
    if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {
Dries's avatar
Dries committed
287
      // Record elapsed wall clock time.
288
      $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
289 290 291 292 293
      break;
    }
  }

  if ($batch['progressive']) {
294 295 296 297
    // Gather progress information.

    // Reporting 100% progress will cause the whole batch to be considered
    // processed. If processing was paused right after moving to a new set,
298
    // we have to use the info from the new (unprocessed) set.
299
    if ($set_changed && isset($current_set['queue'])) {
300
      // Processing will continue with a fresh batch set.
301
      $remaining        = $current_set['count'];
302
      $total            = $current_set['total'];
303
      $progress_message = $current_set['init_message'];
304
      $task_message     = '';
305 306
    }
    else {
307
      // Processing will continue with the current batch set.
308
      $remaining        = $old_set['count'];
309
      $total            = $old_set['total'];
310 311 312
      $progress_message = $old_set['progress_message'];
    }

313 314
    // Total progress is the number of operations that have fully run plus the
    // completion level of the current operation.
315
    $current    = $total - $remaining + $finished;
316
    $percentage = _batch_api_percentage($total, $current);
317
    $elapsed    = isset($current_set['elapsed']) ? $current_set['elapsed'] : 0;
318
    $values     = array(
319 320 321 322
      '@remaining'  => $remaining,
      '@total'      => $total,
      '@current'    => floor($current),
      '@percentage' => $percentage,
323
      '@elapsed'    => format_interval($elapsed / 1000),
324 325
      // If possible, estimate remaining processing time.
      '@estimate'   => ($current > 0) ? format_interval(($elapsed * ($total - $current) / $current) / 1000) : '-',
326 327
    );
    $message = strtr($progress_message, $values);
328
    if (!empty($task_message)) {
329
      $label = $task_message;
330
    }
331

332
    return array($percentage, $message, $label);
333 334
  }
  else {
335
    // If we are not in progressive mode, the entire batch has been processed.
336 337 338 339
    return _batch_finished();
  }
}

340
/**
341
 * Formats the percent completion for a batch set.
342 343 344 345
 *
 * @param $total
 *   The total number of operations.
 * @param $current
346 347 348 349
 *   The number of the current operation. This may be a floating point number
 *   rather than an integer in the case of a multi-step operation that is not
 *   yet complete; in that case, the fractional part of $current represents the
 *   fraction of the operation that has been completed.
350
 *
351 352 353 354 355
 * @return
 *   The properly formatted percentage, as a string. We output percentages
 *   using the correct number of decimal places so that we never print "100%"
 *   until we are finished, but we also never print more decimal places than
 *   are meaningful.
356 357
 *
 * @see _batch_process()
358 359
 */
function _batch_api_percentage($total, $current) {
360
  return Percentage::format($total, $current);
361 362
}

363
/**
364
 * Returns the batch set being currently processed.
365 366
 */
function &_batch_current_set() {
367
  $batch = &batch_get();
368 369 370 371
  return $batch['sets'][$batch['current_set']];
}

/**
372
 * Retrieves the next set in a batch.
373 374 375 376 377 378 379
 *
 * If there is a subsequent set in this batch, assign it as the new set to
 * process and execute its form submit handler (if defined), which may add
 * further sets to this batch.
 *
 * @return
 *   TRUE if a subsequent set was found in the batch.
380 381
 */
function _batch_next_set() {
382
  $batch = &batch_get();
383
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
384
    $batch['current_set']++;
385
    $current_set = &_batch_current_set();
386
    if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && is_callable($function)) {
387 388
      // We use our stored copies of $form and $form_state to account for
      // possible alterations by previous form submit handlers.
389
      call_user_func_array($function, array($batch['form_state']['complete_form'], &$batch['form_state']));
390 391 392 393 394 395
    }
    return TRUE;
  }
}

/**
396
 * Ends the batch processing.
397 398 399
 *
 * Call the 'finished' callback of each batch set to allow custom handling of
 * the results and resolve page redirection.
400 401
 */
function _batch_finished() {
402
  $batch = &batch_get();
403

404
  // Execute the 'finished' callbacks for each batch set, if defined.
405
  foreach ($batch['sets'] as $batch_set) {
406
    if (isset($batch_set['finished'])) {
407
      // Check if the set requires an additional file for function definitions.
408
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
409
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
410 411
      }
      if (function_exists($batch_set['finished'])) {
412 413 414
        $queue = _batch_queue($batch_set);
        $operations = $queue->getAllItems();
        $batch_set['finished']($batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000));
415
      }
416 417 418
    }
  }

419
  // Clean up the batch table and unset the static $batch variable.
420
  if ($batch['progressive']) {
421
    \Drupal::service('batch.storage')->delete($batch['id']);
422 423 424 425 426
    foreach ($batch['sets'] as $batch_set) {
      if ($queue = _batch_queue($batch_set)) {
        $queue->deleteQueue();
      }
    }
427 428 429 430 431 432 433
    // Clean-up the session. Not needed for CLI updates.
    if (isset($_SESSION)) {
      unset($_SESSION['batches'][$batch['id']]);
      if (empty($_SESSION['batches'])) {
        unset($_SESSION['batches']);
      }
    }
434
  }
435 436 437 438 439
  $_batch = $batch;
  $batch = NULL;

  // Redirect if needed.
  if ($_batch['progressive']) {
440
    // Revert the 'destination' that was saved in batch_process().
441
    if (isset($_batch['destination'])) {
442
      \Drupal::request()->query->set('destination', $_batch['destination']);
443
    }
444

445
    // Determine the target path to redirect to.
446 447 448 449 450
    if (!isset($_batch['form_state']['redirect'])) {
      if (isset($_batch['redirect'])) {
        $_batch['form_state']['redirect'] = $_batch['redirect'];
      }
      else {
451
        $_batch['form_state']['redirect'] = $_batch['source_url'];
452
      }
453 454
    }

455
    // Use drupal_redirect_form() to handle the redirection logic.
456 457 458 459
    $redirect = drupal_redirect_form($_batch['form_state']);
    if (is_object($redirect)) {
      return $redirect;
    }
460

461 462 463 464 465 466
    // If no redirection happened, redirect to the originating page. In case the
    // form needs to be rebuilt, save the final $form_state for
    // drupal_build_form().
    if (!empty($_batch['form_state']['rebuild'])) {
      $_SESSION['batch_form_state'] = $_batch['form_state'];
    }
467 468
    $function = $_batch['redirect_callback'];
    if (function_exists($function)) {
469
      $function($_batch['source_url'], array('query' => array('op' => 'finish', 'id' => $_batch['id'])));
470
    }
471 472 473 474 475 476 477 478
    elseif ($function === NULL) {
      // Default to RedirectResponse objects when nothing specified.
      $url = url($_batch['source_url'], array(
        'absolute' => TRUE,
        'query' => array('op' => 'finish', 'id' => $_batch['id']),
      ));
      return new RedirectResponse($url);
    }
479 480 481 482
  }
}

/**
483 484 485 486
 * Shutdown function: Stores the current batch data for the next request.
 *
 * @see _batch_page()
 * @see drupal_register_shutdown_function()
487 488 489
 */
function _batch_shutdown() {
  if ($batch = batch_get()) {
490
    \Drupal::service('batch.storage')->update($batch);
491 492
  }
}