batch.inc 15 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\Core\Batch\Percentage;
18 19
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
20

21
/**
22
 * Renders the batch processing page based on the current state of the batch.
23 24
 *
 * @see _batch_shutdown()
25 26
 */
function _batch_page() {
27
  $batch = &batch_get();
28

29
  if (!isset($_REQUEST['id'])) {
30 31 32
    return FALSE;
  }

33
  // Retrieve the current state of the batch.
34
  if (!$batch) {
35
    $batch = Drupal::service('batch.storage')->load($_REQUEST['id']);
36 37
    if (!$batch) {
      drupal_set_message(t('No active batch.'), 'error');
38
      return new RedirectResponse(url('<front>', array('absolute' => TRUE)));
39
    }
40 41
  }

42
  // Register database update for the end of processing.
43
  drupal_register_shutdown_function('_batch_shutdown');
44

45
  // Add batch-specific CSS.
46
  foreach ($batch['sets'] as $batch_set) {
47 48 49 50
    if (isset($batch_set['css'])) {
      foreach ($batch_set['css'] as $css) {
        drupal_add_css($css);
      }
51 52 53
    }
  }

54
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
55
  $output = NULL;
56 57
  switch ($op) {
    case 'start':
58 59 60
      // Display the full progress page on startup and on each additional
      // non-JavaScript iteration.
      $output = _batch_progress_page();
61 62 63
      break;

    case 'do':
64
      // JavaScript-based progress page callback.
65
      $output = _batch_do();
66 67 68
      break;

    case 'do_nojs':
69
      // Non-JavaScript-based progress page.
70
      $output = _batch_progress_page();
71 72 73 74 75 76 77 78 79 80 81
      break;

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

  return $output;
}

/**
82
 * Does one execution pass with JavaScript and returns progress to the browser.
83 84 85
 *
 * @see _batch_progress_page_js()
 * @see _batch_process()
86 87
 */
function _batch_do() {
88
  // Perform actual processing.
89
  list($percentage, $message, $label) = _batch_process();
90

91
  return new JsonResponse(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message, 'label' => $label));
92 93 94
}

/**
95
 * Outputs a batch processing page.
96 97
 *
 * @see _batch_process()
98
 */
99
function _batch_progress_page() {
100
  $batch = &batch_get();
101

102
  $current_set = _batch_current_set();
103
  drupal_set_title($current_set['title'], PASS_THROUGH);
104 105 106 107

  $new_op = 'do_nojs';

  if (!isset($batch['running'])) {
108
    // This is the first page so we return some output immediately.
109 110
    $percentage       = 0;
    $message          = $current_set['init_message'];
111
    $label            = '';
112 113 114
    $batch['running'] = TRUE;
  }
  else {
115
    // This is one of the later requests; do some processing first.
116

117 118 119
    // 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.
120
    ob_start();
121
    $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
122
    $fallback = theme('maintenance_page', array('content' => $fallback, 'show_messages' => FALSE));
123 124

    // We strip the end of the page using a marker in the template, so any
125 126 127
    // 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.
128 129 130
    list($fallback) = explode('<!--partial-->', $fallback);
    print $fallback;

131
    // Perform actual processing.
132
    list($percentage, $message, $label) = _batch_process($batch);
133 134 135 136
    if ($percentage == 100) {
      $new_op = 'finished';
    }

137
    // PHP did not die; remove the fallback output.
138 139 140
    ob_end_clean();
  }

141 142 143 144 145 146
  // 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']);
147
  $element = array(
148 149 150
    // Redirect through a 'Refresh' meta tag if JavaScript is disabled.
    '#prefix' => '<noscript>',
    '#suffix' => '</noscript>',
151 152 153 154 155 156 157
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'Refresh',
      'content' => '0; URL=' . $url,
    ),
  );
  drupal_add_html_head($element, 'batch_progress_meta_refresh');
158

159 160 161 162 163 164 165 166 167 168 169
  // Adds JavaScript code and settings for clients where JavaScript is enabled.
  $js_setting = array(
    'batch' => array(
      'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
      'initMessage' => $current_set['init_message'],
      'uri' => $url,
    ),
  );
  drupal_add_js($js_setting, 'setting');
  drupal_add_library('system', 'drupal.batch');

170
  return theme('progress_bar', array('percent' => $percentage, 'message' => $message, 'label' => $label));
171 172 173
}

/**
174
 * Processes sets in a batch.
175 176 177 178 179 180 181 182
 *
 * 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.
183 184
 */
function _batch_process() {
185 186 187
  $batch       = &batch_get();
  $current_set = &_batch_current_set();
  // Indicate that this batch set needs to be initialized.
188
  $set_changed = TRUE;
189

190
  // If this batch was marked for progressive execution (e.g. forms submitted by
191
  // drupal_form_submit()), initialize a timer to determine whether we need to
192 193
  // proceed with the same batch phase when a processing time of 1 second has
  // been exceeded.
194 195 196 197
  if ($batch['progressive']) {
    timer_start('batch_processing');
  }

198 199 200 201 202 203
  if (empty($current_set['start'])) {
    $current_set['start'] = microtime(TRUE);
  }

  $queue = _batch_queue($current_set);

204
  while (!$current_set['success']) {
205 206 207 208
    // 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'])) {
209
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
210 211
    }

212
    $task_message = $label = '';
213
    // Assume a single pass operation and set the completion level to 1 by
214
    // default.
215
    $finished = 1;
216 217 218 219 220

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

      // Build the 'context' array and execute the function call.
221 222 223 224 225 226
      $batch_context = array(
        'sandbox'  => &$current_set['sandbox'],
        'results'  => &$current_set['results'],
        'finished' => &$finished,
        'message'  => &$task_message,
      );
227
      call_user_func_array($function, array_merge($args, array(&$batch_context)));
228

229
      if ($finished >= 1) {
230 231 232 233 234 235 236
        // 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();
      }
237
    }
238

239
    // When all operations in the current batch set are completed, browse
240 241 242 243 244
    // 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.
245 246
    $set_changed = FALSE;
    $old_set = $current_set;
247
    while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
248
      $current_set = &_batch_current_set();
249
      $current_set['start'] = microtime(TRUE);
250
      $set_changed = TRUE;
251
    }
252

253 254
    // At this point, either $current_set contains operations that need to be
    // processed or all sets have been completed.
255
    $queue = _batch_queue($current_set);
256

257
    // If we are in progressive mode, break processing after 1 second.
258
    if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
Dries's avatar
Dries committed
259
      // Record elapsed wall clock time.
260
      $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
261 262 263 264 265
      break;
    }
  }

  if ($batch['progressive']) {
266 267 268 269
    // 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,
270
    // we have to use the info from the new (unprocessed) set.
271
    if ($set_changed && isset($current_set['queue'])) {
272
      // Processing will continue with a fresh batch set.
273
      $remaining        = $current_set['count'];
274
      $total            = $current_set['total'];
275
      $progress_message = $current_set['init_message'];
276
      $task_message     = '';
277 278
    }
    else {
279
      // Processing will continue with the current batch set.
280
      $remaining        = $old_set['count'];
281
      $total            = $old_set['total'];
282 283 284
      $progress_message = $old_set['progress_message'];
    }

285 286
    // Total progress is the number of operations that have fully run plus the
    // completion level of the current operation.
287
    $current    = $total - $remaining + $finished;
288
    $percentage = _batch_api_percentage($total, $current);
289
    $elapsed    = isset($current_set['elapsed']) ? $current_set['elapsed'] : 0;
290
    $values     = array(
291 292 293 294
      '@remaining'  => $remaining,
      '@total'      => $total,
      '@current'    => floor($current),
      '@percentage' => $percentage,
295
      '@elapsed'    => format_interval($elapsed / 1000),
296 297
      // If possible, estimate remaining processing time.
      '@estimate'   => ($current > 0) ? format_interval(($elapsed * ($total - $current) / $current) / 1000) : '-',
298 299
    );
    $message = strtr($progress_message, $values);
300
    if (!empty($task_message)) {
301
      $label = $task_message;
302
    }
303

304
    return array($percentage, $message, $label);
305 306
  }
  else {
307
    // If we are not in progressive mode, the entire batch has been processed.
308 309 310 311
    return _batch_finished();
  }
}

312
/**
313
 * Formats the percent completion for a batch set.
314 315 316 317
 *
 * @param $total
 *   The total number of operations.
 * @param $current
318 319 320 321
 *   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.
322
 *
323 324 325 326 327
 * @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.
328 329
 *
 * @see _batch_process()
330 331
 */
function _batch_api_percentage($total, $current) {
332
  return Percentage::format($total, $current);
333 334
}

335
/**
336
 * Returns the batch set being currently processed.
337 338
 */
function &_batch_current_set() {
339
  $batch = &batch_get();
340 341 342 343
  return $batch['sets'][$batch['current_set']];
}

/**
344
 * Retrieves the next set in a batch.
345 346 347 348 349 350 351
 *
 * 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.
352 353
 */
function _batch_next_set() {
354
  $batch = &batch_get();
355
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
356
    $batch['current_set']++;
357
    $current_set = &_batch_current_set();
358
    if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
359 360
      // We use our stored copies of $form and $form_state to account for
      // possible alterations by previous form submit handlers.
361
      $function($batch['form_state']['complete_form'], $batch['form_state']);
362 363 364 365 366 367
    }
    return TRUE;
  }
}

/**
368
 * Ends the batch processing.
369 370 371
 *
 * Call the 'finished' callback of each batch set to allow custom handling of
 * the results and resolve page redirection.
372 373
 */
function _batch_finished() {
374
  $batch = &batch_get();
375

376
  // Execute the 'finished' callbacks for each batch set, if defined.
377
  foreach ($batch['sets'] as $batch_set) {
378
    if (isset($batch_set['finished'])) {
379
      // Check if the set requires an additional file for function definitions.
380
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
381
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
382 383
      }
      if (function_exists($batch_set['finished'])) {
384 385 386
        $queue = _batch_queue($batch_set);
        $operations = $queue->getAllItems();
        $batch_set['finished']($batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000));
387
      }
388 389 390
    }
  }

391
  // Clean up the batch table and unset the static $batch variable.
392
  if ($batch['progressive']) {
393
    Drupal::service('batch.storage')->delete($batch['id']);
394 395 396 397 398
    foreach ($batch['sets'] as $batch_set) {
      if ($queue = _batch_queue($batch_set)) {
        $queue->deleteQueue();
      }
    }
399 400 401 402 403 404 405
    // Clean-up the session. Not needed for CLI updates.
    if (isset($_SESSION)) {
      unset($_SESSION['batches'][$batch['id']]);
      if (empty($_SESSION['batches'])) {
        unset($_SESSION['batches']);
      }
    }
406
  }
407 408 409 410 411
  $_batch = $batch;
  $batch = NULL;

  // Redirect if needed.
  if ($_batch['progressive']) {
412
    // Revert the 'destination' that was saved in batch_process().
413
    if (isset($_batch['destination'])) {
414
      Drupal::request()->query->set('destination', $_batch['destination']);
415
    }
416

417
    // Determine the target path to redirect to.
418 419 420 421 422
    if (!isset($_batch['form_state']['redirect'])) {
      if (isset($_batch['redirect'])) {
        $_batch['form_state']['redirect'] = $_batch['redirect'];
      }
      else {
423
        $_batch['form_state']['redirect'] = $_batch['source_url'];
424
      }
425 426
    }

427
    // Use drupal_redirect_form() to handle the redirection logic.
428 429 430 431
    $redirect = drupal_redirect_form($_batch['form_state']);
    if (is_object($redirect)) {
      return $redirect;
    }
432

433 434 435 436 437 438
    // 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'];
    }
439 440
    $function = $_batch['redirect_callback'];
    if (function_exists($function)) {
441
      $function($_batch['source_url'], array('query' => array('op' => 'finish', 'id' => $_batch['id'])));
442
    }
443 444 445 446 447 448 449 450
    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);
    }
451 452 453 454
  }
}

/**
455 456 457 458
 * Shutdown function: Stores the current batch data for the next request.
 *
 * @see _batch_page()
 * @see drupal_register_shutdown_function()
459 460 461
 */
function _batch_shutdown() {
  if ($batch = batch_get()) {
462
    Drupal::service('batch.storage')->update($batch);
463 464
  }
}