5 * Batch processing API for processes to run in multiple HTTP requests.
7 * Note that batches are usually invoked by form submissions, which is
8 * why the core interaction functions of the batch processing API live in
13 * @see batch_process()
17 use Drupal\Component\Utility\Timer;
18 use Drupal\Component\Utility\UrlHelper;
19 use Drupal\Core\Batch\Percentage;
20 use Drupal\Core\Form\FormState;
22 use Symfony\Component\HttpFoundation\JsonResponse;
23 use Symfony\Component\HttpFoundation\Request;
24 use Symfony\Component\HttpFoundation\RedirectResponse;
27 * Renders the batch processing page based on the current state of the batch.
29 * @param \Symfony\Component\HttpFoundation\Request $request
30 * The current request object.
32 * @see _batch_shutdown()
34 function _batch_page(Request $request) {
35 $batch = &batch_get();
37 if (!($request_id = $request->query->get('id'))) {
41 // Retrieve the current state of the batch.
43 $batch = \Drupal::service('batch.storage')->load($request_id);
45 \Drupal::messenger()->addError(t('No active batch.'));
46 return new RedirectResponse(\Drupal::url('<front>', [], ['absolute' => TRUE]));
50 // We need to store the updated batch information in the batch storage after
51 // processing the batch. In order for the error page to work correctly this
52 // needs to be done even in case of a PHP fatal error in which case the end of
53 // this function is never reached. Therefore we register a shutdown function
54 // to handle this case. Because with FastCGI and fastcgi_finish_request()
55 // shutdown functions are called after the HTTP connection is closed, updating
56 // the batch information in a shutdown function would lead to race conditions
57 // between consecutive requests if the batch processing continues. In case of
58 // a fatal error the processing stops anyway, so it works even with FastCGI.
59 // However, we must ensure to only update in the shutdown phase in this
60 // particular case we track whether the batch information still needs to be
62 // @see _batch_shutdown()
63 // @see \Symfony\Component\HttpFoundation\Response::send()
64 drupal_register_shutdown_function('_batch_shutdown');
65 _batch_needs_update(TRUE);
69 // Add batch-specific libraries.
70 foreach ($batch['sets'] as $batch_set) {
71 if (isset($batch_set['library'])) {
72 foreach ($batch_set['library'] as $library) {
73 $build['#attached']['library'][] = $library;
78 $op = $request->query->get('op', '');
82 // Display the full progress page on startup and on each additional
83 // non-JavaScript iteration.
84 $current_set = _batch_current_set();
85 $build['#title'] = $current_set['title'];
86 $build['content'] = _batch_progress_page();
92 // JavaScript-based progress page callback.
93 $response = _batch_do();
97 // _batch_finished() returns a RedirectResponse.
98 $response = _batch_finished();
103 \Drupal::service('batch.storage')->update($batch);
105 _batch_needs_update(FALSE);
111 * Checks whether the batch information needs to be updated in the storage.
113 * @param bool $new_value
114 * (optional) A new value to set.
117 * TRUE if the batch information needs to be updated; FALSE otherwise.
119 function _batch_needs_update($new_value = NULL) {
120 $needs_update = &drupal_static(__FUNCTION__, FALSE);
122 if (isset($new_value)) {
123 $needs_update = $new_value;
126 return $needs_update;
130 * Does one execution pass with JavaScript and returns progress to the browser.
132 * @see _batch_progress_page_js()
133 * @see _batch_process()
135 function _batch_do() {
136 // Perform actual processing.
137 list($percentage, $message, $label) = _batch_process();
139 return new JsonResponse(['status' => TRUE, 'percentage' => $percentage, 'message' => $message, 'label' => $label]);
143 * Outputs a batch processing page.
145 * @see _batch_process()
147 function _batch_progress_page() {
148 $batch = &batch_get();
150 $current_set = _batch_current_set();
154 if (!isset($batch['running'])) {
155 // This is the first page so we return some output immediately.
157 $message = $current_set['init_message'];
159 $batch['running'] = TRUE;
162 // This is one of the later requests; do some processing first.
164 // Error handling: if PHP dies due to a fatal error (e.g. a nonexistent
165 // function), it will output whatever is in the output buffer, followed by
166 // the error message.
168 $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
170 // We strip the end of the page using a marker in the template, so any
171 // additional HTML output by PHP shows up inside the page rather than below
172 // it. While this causes invalid HTML, the same would be true if we didn't,
173 // as content is not allowed to appear after </html> anyway.
174 $bare_html_page_renderer = \Drupal::service('bare_html_page_renderer');
175 $response = $bare_html_page_renderer->renderBarePage(['#markup' => $fallback], $current_set['title'], 'maintenance_page', [
176 '#show_messages' => FALSE,
179 // Just use the content of the response.
180 $fallback = $response->getContent();
182 list($fallback) = explode('<!--partial-->', $fallback);
185 // Perform actual processing.
186 list($percentage, $message, $label) = _batch_process($batch);
187 if ($percentage == 100) {
188 $new_op = 'finished';
191 // PHP did not die; remove the fallback output.
195 // Merge required query parameters for batch processing into those provided by
196 // batch_set() or hook_batch_alter().
197 $query_options = $batch['url']->getOption('query');
198 $query_options['id'] = $batch['id'];
199 $query_options['op'] = $new_op;
200 $batch['url']->setOption('query', $query_options);
202 $url = $batch['url']->toString(TRUE)->getGeneratedUrl();
205 '#theme' => 'progress_bar',
206 '#percent' => $percentage,
207 '#message' => ['#markup' => $message],
213 // Redirect through a 'Refresh' meta tag if JavaScript is disabled.
217 'http-equiv' => 'Refresh',
218 'content' => '0; URL=' . $url,
221 'batch_progress_meta_refresh',
224 // Adds JavaScript code and settings for clients where JavaScript is enabled.
225 'drupalSettings' => [
227 'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
228 'initMessage' => $current_set['init_message'],
241 * Processes sets in a batch.
243 * If the batch was marked for progressive execution (default), this executes as
244 * many operations in batch sets until an execution time of 1 second has been
245 * exceeded. It will continue with the next operation of the same batch set in
249 * An array containing a completion value (in percent) and a status message.
251 function _batch_process() {
252 $batch = &batch_get();
253 $current_set = &_batch_current_set();
254 // Indicate that this batch set needs to be initialized.
257 // If this batch was marked for progressive execution (e.g. forms submitted by
258 // \Drupal::formBuilder()->submitForm(), initialize a timer to determine
259 // whether we need to proceed with the same batch phase when a processing time
260 // of 1 second has been exceeded.
261 if ($batch['progressive']) {
262 Timer::start('batch_processing');
265 if (empty($current_set['start'])) {
266 $current_set['start'] = microtime(TRUE);
269 $queue = _batch_queue($current_set);
271 while (!$current_set['success']) {
272 // If this is the first time we iterate this batch set in the current
273 // request, we check if it requires an additional file for functions
275 if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
276 include_once \Drupal::root() . '/' . $current_set['file'];
279 $task_message = $label = '';
280 // Assume a single pass operation and set the completion level to 1 by
284 if ($item = $queue->claimItem()) {
285 list($callback, $args) = $item->data;
287 // Build the 'context' array and execute the function call.
289 'sandbox' => &$current_set['sandbox'],
290 'results' => &$current_set['results'],
291 'finished' => &$finished,
292 'message' => &$task_message,
294 call_user_func_array($callback, array_merge($args, [&$batch_context]));
296 if ($finished >= 1) {
297 // Make sure this step is not counted twice when computing $current.
299 // Remove the processed operation and clear the sandbox.
300 $queue->deleteItem($item);
301 $current_set['count']--;
302 $current_set['sandbox'] = [];
306 // When all operations in the current batch set are completed, browse
307 // through the remaining sets, marking them 'successfully processed'
308 // along the way, until we find a set that contains operations.
309 // _batch_next_set() executes form submit handlers stored in 'control'
310 // sets (see \Drupal::service('form_submitter')), which can in turn add new
311 // sets to the batch.
312 $set_changed = FALSE;
313 $old_set = $current_set;
314 while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
315 $current_set = &_batch_current_set();
316 $current_set['start'] = microtime(TRUE);
320 // At this point, either $current_set contains operations that need to be
321 // processed or all sets have been completed.
322 $queue = _batch_queue($current_set);
324 // If we are in progressive mode, break processing after 1 second.
325 if ($batch['progressive'] && Timer::read('batch_processing') > 1000) {
326 // Record elapsed wall clock time.
327 $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
332 if ($batch['progressive']) {
333 // Gather progress information.
335 // Reporting 100% progress will cause the whole batch to be considered
336 // processed. If processing was paused right after moving to a new set,
337 // we have to use the info from the new (unprocessed) set.
338 if ($set_changed && isset($current_set['queue'])) {
339 // Processing will continue with a fresh batch set.
340 $remaining = $current_set['count'];
341 $total = $current_set['total'];
342 $progress_message = $current_set['init_message'];
346 // Processing will continue with the current batch set.
347 $remaining = $old_set['count'];
348 $total = $old_set['total'];
349 $progress_message = $old_set['progress_message'];
352 // Total progress is the number of operations that have fully run plus the
353 // completion level of the current operation.
354 $current = $total - $remaining + $finished;
355 $percentage = _batch_api_percentage($total, $current);
356 $elapsed = isset($current_set['elapsed']) ? $current_set['elapsed'] : 0;
358 '@remaining' => $remaining,
360 '@current' => floor($current),
361 '@percentage' => $percentage,
362 '@elapsed' => \Drupal::service('date.formatter')->formatInterval($elapsed / 1000),
363 // If possible, estimate remaining processing time.
364 '@estimate' => ($current > 0) ? \Drupal::service('date.formatter')->formatInterval(($elapsed * ($total - $current) / $current) / 1000) : '-',
366 $message = strtr($progress_message, $values);
367 if (!empty($task_message)) {
368 $label = $task_message;
371 return [$percentage, $message, $label];
374 // If we are not in progressive mode, the entire batch has been processed.
375 return _batch_finished();
380 * Formats the percent completion for a batch set.
383 * The total number of operations.
384 * @param int|float $current
385 * The number of the current operation. This may be a floating point number
386 * rather than an integer in the case of a multi-step operation that is not
387 * yet complete; in that case, the fractional part of $current represents the
388 * fraction of the operation that has been completed.
391 * The properly formatted percentage, as a string. We output percentages
392 * using the correct number of decimal places so that we never print "100%"
393 * until we are finished, but we also never print more decimal places than
396 * @see _batch_process()
398 function _batch_api_percentage($total, $current) {
399 return Percentage::format($total, $current);
403 * Returns the batch set being currently processed.
405 function &_batch_current_set() {
406 $batch = &batch_get();
407 return $batch['sets'][$batch['current_set']];
411 * Retrieves the next set in a batch.
413 * If there is a subsequent set in this batch, assign it as the new set to
414 * process and execute its form submit handler (if defined), which may add
415 * further sets to this batch.
418 * TRUE if a subsequent set was found in the batch; no value will be returned
419 * if no subsequent set was found.
421 function _batch_next_set() {
422 $batch = &batch_get();
423 if (isset($batch['sets'][$batch['current_set'] + 1])) {
424 $batch['current_set']++;
425 $current_set = &_batch_current_set();
426 if (isset($current_set['form_submit']) && ($callback = $current_set['form_submit']) && is_callable($callback)) {
427 // We use our stored copies of $form and $form_state to account for
428 // possible alterations by previous form submit handlers.
429 $complete_form = &$batch['form_state']->getCompleteForm();
430 call_user_func_array($callback, [&$complete_form, &$batch['form_state']]);
437 * Ends the batch processing.
439 * Call the 'finished' callback of each batch set to allow custom handling of
440 * the results and resolve page redirection.
442 function _batch_finished() {
443 $batch = &batch_get();
444 $batch_finished_redirect = NULL;
446 // Execute the 'finished' callbacks for each batch set, if defined.
447 foreach ($batch['sets'] as $batch_set) {
448 if (isset($batch_set['finished'])) {
449 // Check if the set requires an additional file for function definitions.
450 if (isset($batch_set['file']) && is_file($batch_set['file'])) {
451 include_once \Drupal::root() . '/' . $batch_set['file'];
453 if (is_callable($batch_set['finished'])) {
454 $queue = _batch_queue($batch_set);
455 $operations = $queue->getAllItems();
456 $batch_set_result = call_user_func_array($batch_set['finished'], [$batch_set['success'], $batch_set['results'], $operations, \Drupal::service('date.formatter')->formatInterval($batch_set['elapsed'] / 1000)]);
457 // If a batch 'finished' callback requested a redirect after the batch
458 // is complete, save that for later use. If more than one batch set
459 // returned a redirect, the last one is used.
460 if ($batch_set_result instanceof RedirectResponse) {
461 $batch_finished_redirect = $batch_set_result;
467 // Clean up the batch table and unset the static $batch variable.
468 if ($batch['progressive']) {
469 \Drupal::service('batch.storage')->delete($batch['id']);
470 foreach ($batch['sets'] as $batch_set) {
471 if ($queue = _batch_queue($batch_set)) {
472 $queue->deleteQueue();
475 // Clean-up the session. Not needed for CLI updates.
476 if (isset($_SESSION)) {
477 unset($_SESSION['batches'][$batch['id']]);
478 if (empty($_SESSION['batches'])) {
479 unset($_SESSION['batches']);
486 // Redirect if needed.
487 if ($_batch['progressive']) {
488 // Revert the 'destination' that was saved in batch_process().
489 if (isset($_batch['destination'])) {
490 \Drupal::request()->query->set('destination', $_batch['destination']);
493 // Determine the target path to redirect to. If a batch 'finished' callback
494 // returned a redirect response object, use that. Otherwise, fall back on
495 // the form redirection.
496 if (isset($batch_finished_redirect)) {
497 return $batch_finished_redirect;
499 elseif (!isset($_batch['form_state'])) {
500 $_batch['form_state'] = new FormState();
502 if ($_batch['form_state']->getRedirect() === NULL) {
503 $redirect = $_batch['batch_redirect'] ?: $_batch['source_url'];
504 // Any path with a scheme does not correspond to a route.
505 if (!$redirect instanceof Url) {
506 $options = UrlHelper::parse($redirect);
507 if (parse_url($options['path'], PHP_URL_SCHEME)) {
508 $redirect = Url::fromUri($options['path'], $options);
511 $redirect = \Drupal::pathValidator()->getUrlIfValid($options['path']);
513 // Stay on the same page if the redirect was invalid.
514 $redirect = Url::fromRoute('<current>');
516 $redirect->setOptions($options);
519 $_batch['form_state']->setRedirectUrl($redirect);
522 // Use \Drupal\Core\Form\FormSubmitterInterface::redirectForm() to handle
523 // the redirection logic.
524 $redirect = \Drupal::service('form_submitter')->redirectForm($_batch['form_state']);
525 if (is_object($redirect)) {
529 // If no redirection happened, redirect to the originating page. In case the
530 // form needs to be rebuilt, save the final $form_state for
531 // \Drupal\Core\Form\FormBuilderInterface::buildForm().
532 if ($_batch['form_state']->isRebuilding()) {
533 $_SESSION['batch_form_state'] = $_batch['form_state'];
535 $callback = $_batch['redirect_callback'];
536 $_batch['source_url']->mergeOptions(['query' => ['op' => 'finish', 'id' => $_batch['id']]]);
537 if (is_callable($callback)) {
538 $callback($_batch['source_url'], $_batch['source_url']->getOption('query'));
540 elseif ($callback === NULL) {
541 // Default to RedirectResponse objects when nothing specified.
542 return new RedirectResponse($_batch['source_url']->setAbsolute()->toString());
548 * Shutdown function: Stores the current batch data for the next request.
551 * @see drupal_register_shutdown_function()
553 function _batch_shutdown() {
554 if (($batch = batch_get()) && _batch_needs_update()) {
555 \Drupal::service('batch.storage')->update($batch);