batch.inc 13.5 KB
Newer Older
1
<?php
2
// $Id$
3

4

5
/**
6 7 8 9 10 11 12 13 14 15 16
 * @file
 * Batch processing API for processes to run in multiple HTTP requests.
 *
 * Please note that batches are usually invoked by form submissions, which is
 * 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()
17 18 19
 */

/**
20
 * State-based dispatcher for the batch processing page.
21 22
 *
 * @see _batch_shutdown()
23 24
 */
function _batch_page() {
25
  $batch = &batch_get();
26

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

31 32 33 34 35 36 37 38
  // Retrieve the current state of batch from db.
  $batch = db_query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(
    ':bid' => $_REQUEST['id'],
    ':token' => drupal_get_token($_REQUEST['id']))
  )->fetchField();

  $batch = unserialize($batch);

39
  // Register database update for the end of processing.
40 41
  register_shutdown_function('_batch_shutdown');

42
  // Add batch-specific CSS.
43 44 45 46 47 48
  foreach ($batch['sets'] as $batch_set) {
    foreach ($batch_set['css'] as $css) {
      drupal_add_css($css);
    }
  }

49
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
50
  $output = NULL;
51 52 53 54 55 56
  switch ($op) {
    case 'start':
      $output = _batch_start();
      break;

    case 'do':
57
      // JavaScript-based progress page callback.
58
      _batch_do();
59 60 61
      break;

    case 'do_nojs':
62
      // Non-JavaScript-based progress page.
63 64 65 66 67 68 69 70 71 72 73 74
      $output = _batch_progress_page_nojs();
      break;

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

  return $output;
}

/**
75 76 77 78 79
 * Initialize the batch processing.
 *
 * JavaScript-enabled clients are identified by the 'has_js' cookie set in
 * drupal.js. If no JavaScript-enabled page has been visited during the current
 * user's browser session, the non-JavaScript version is returned.
80 81 82 83 84 85 86 87 88 89 90
 */
function _batch_start() {
  if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
    return _batch_progress_page_js();
  }
  else {
    return _batch_progress_page_nojs();
  }
}

/**
91 92 93 94 95 96 97 98 99
 * Output a batch processing page with JavaScript support.
 *
 * This initializes the batch and error messages. Note that in JavaScript-based
 * processing, the batch processing page is displayed only once and updated via
 * AHAH requests, so only the first batch set gets to define the page title.
 * Titles specified by subsequent batch sets are not displayed.
 *
 * @see batch_set()
 * @see _batch_do()
100 101 102 103
 */
function _batch_progress_page_js() {
  $batch = batch_get();

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

  $js_setting = array(
    'batch' => array(
109
      'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
110
      'initMessage' => $current_set['init_message'],
111
      'uri' => url($batch['url'], array('query' => array('id' => $batch['id']))),
112 113 114
    ),
  );
  drupal_add_js($js_setting, 'setting');
115
  drupal_add_js('misc/progress.js', array('cache' => FALSE));
116
  drupal_add_js('misc/batch.js', array('cache' => FALSE));
117

118
  return '<div id="progress"></div>';
119 120 121
}

/**
122 123 124 125
 * Do one pass of execution in JavaScript-mode and return progress to the browser.
 *
 * @see _batch_progress_page_js()
 * @see _batch_process()
126 127
 */
function _batch_do() {
128
  // HTTP POST required.
129 130 131 132 133 134
  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    drupal_set_message(t('HTTP POST is required.'), 'error');
    drupal_set_title(t('Error'));
    return '';
  }

135
  // Perform actual processing.
136 137
  list($percentage, $message) = _batch_process();

138
  drupal_json(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
139 140 141
}

/**
142 143 144
 * Output a batch processing page without JavaScript support.
 *
 * @see _batch_process()
145 146
 */
function _batch_progress_page_nojs() {
147
  $batch = &batch_get();
148

149
  $current_set = _batch_current_set();
150
  drupal_set_title($current_set['title'], PASS_THROUGH);
151 152 153 154

  $new_op = 'do_nojs';

  if (!isset($batch['running'])) {
155
    // This is the first page so we return some output immediately.
156 157
    $percentage       = 0;
    $message          = $current_set['init_message'];
158 159 160
    $batch['running'] = TRUE;
  }
  else {
161
    // This is one of the later requests; do some processing first.
162

163 164 165
    // 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.
166
    ob_start();
167
    $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
168
    $fallback = theme('maintenance_page', $fallback, FALSE, FALSE);
169 170

    // We strip the end of the page using a marker in the template, so any
171 172 173
    // 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.
174 175 176
    list($fallback) = explode('<!--partial-->', $fallback);
    print $fallback;

177
    // Perform actual processing.
178 179 180 181 182
    list($percentage, $message) = _batch_process($batch);
    if ($percentage == 100) {
      $new_op = 'finished';
    }

183
    // PHP did not die; remove the fallback output.
184 185 186 187
    ob_end_clean();
  }

  $url = url($batch['url'], array('query' => array('id' => $batch['id'], 'op' => $new_op)));
188
  drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL=' . $url . '">');
189 190

  return theme('progress_bar', $percentage, $message);
191 192 193
}

/**
194 195 196 197 198 199 200 201 202
 * Process sets in a batch.
 *
 * 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.
203 204
 */
function _batch_process() {
205 206 207
  $batch       = &batch_get();
  $current_set = &_batch_current_set();
  // Indicate that this batch set needs to be initialized.
208
  $set_changed = TRUE;
209

210 211 212 213
  // If this batch was marked for progressive execution (e.g. forms submitted by
  // drupal_execute()), initialize a timer to determine whether we need to
  // proceed with the same batch phase when a processing time of 1 second has
  // been exceeded.
214 215 216 217
  if ($batch['progressive']) {
    timer_start('batch_processing');
  }

218
  while (!$current_set['success']) {
219 220 221 222
    // 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'])) {
223
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
224 225
    }

226
    $task_message = '';
227 228
    // We assume a single pass operation and set the completion level to 1 by
    // default.
229
    $finished = 1;
230
    if ((list($function, $args) = reset($current_set['operations'])) && function_exists($function)) {
231 232 233 234 235 236 237 238
      // Build the 'context' array, execute the function call, and retrieve the
      // user message.
      $batch_context = array(
        'sandbox'  => &$current_set['sandbox'],
        'results'  => &$current_set['results'],
        'finished' => &$finished,
        'message'  => &$task_message,
      );
239
      // Process the current operation.
240 241
      call_user_func_array($function, array_merge($args, array(&$batch_context)));
    }
242

243
    if ($finished == 1) {
244
      // Make sure this step is not counted twice when computing $current.
245
      $finished = 0;
246
      // Remove the processed operation and clear the sandbox.
247 248
      array_shift($current_set['operations']);
      $current_set['sandbox'] = array();
249
    }
250

251 252 253 254
    // When all operations in the current batch set are completed, browse
    // through the remaining sets until we find a set that contains operations.
    // Note that _batch_next_set() executes stored form submit handlers in
    // remaining batch sets, which can add new sets to the batch.
255 256
    $set_changed = FALSE;
    $old_set = $current_set;
257
    while (empty($current_set['operations']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
258
      $current_set = &_batch_current_set();
259
      $set_changed = TRUE;
260
    }
261 262
    // At this point, either $current_set contains operations that need to be
    // processed or all sets have been completed.
263

264
    // If we are in progressive mode, break processing after 1 second.
265
    if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
266 267
      // Record elapsed wall clock time. 
      $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
268 269 270 271 272
      break;
    }
  }

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

292
    $current    = $total - $remaining + $finished;
293
    $percentage = $total ? floor($current / $total * 100) : 100;
294 295 296
    $elapsed    = $current_set['elapsed'];
    // Estimate remaining with percentage in floating format.
    $estimate   = $elapsed * ($total - $current) / $current;
297
    $values     = array(
298 299 300 301
      '@remaining'  => $remaining,
      '@total'      => $total,
      '@current'    => floor($current),
      '@percentage' => $percentage,
302 303
      '@elapsed'    => format_interval($elapsed / 1000),
      '@estimate'   => format_interval($estimate / 1000),
304 305 306
    );
    $message = strtr($progress_message, $values);
    if (!empty($message)) {
307 308 309 310
      $message .= '<br />';
    }
    if (!empty($task_message)) {
      $message .= $task_message;
311
    }
312 313 314 315

    return array($percentage, $message);
  }
  else {
316
    // If we are not in progressive mode, the entire batch has been processed.
317 318 319 320 321
    return _batch_finished();
  }
}

/**
322
 * Return the batch set being currently processed.
323 324
 */
function &_batch_current_set() {
325
  $batch = &batch_get();
326 327 328 329
  return $batch['sets'][$batch['current_set']];
}

/**
330 331 332 333 334 335 336 337
 * Retrieve the next set in a batch.
 *
 * 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.
338 339
 */
function _batch_next_set() {
340
  $batch = &batch_get();
341
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
342
    $batch['current_set']++;
343
    $current_set = &_batch_current_set();
344
    if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
345 346
      // We use our stored copies of $form and $form_state to account for
      // possible alterations by previous form submit handlers.
Dries's avatar
Dries committed
347
      $function($batch['form'], $batch['form_state']);
348 349 350 351 352 353
    }
    return TRUE;
  }
}

/**
354 355 356 357
 * End the batch processing.
 *
 * Call the 'finished' callback of each batch set to allow custom handling of
 * the results and resolve page redirection.
358 359
 */
function _batch_finished() {
360
  $batch = &batch_get();
361

362
  // Execute the 'finished' callbacks for each batch set, if defined.
363
  foreach ($batch['sets'] as $key => $batch_set) {
364
    if (isset($batch_set['finished'])) {
365
      // Check if the set requires an additional file for function definitions.
366
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
367
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
368 369
      }
      if (function_exists($batch_set['finished'])) {
370 371
        // Format the elapsed time when batch complete.
        $batch_set['finished']($batch_set['success'], $batch_set['results'], $batch_set['operations'], format_interval($batch_set['elapsed'] / 1000));
372
      }
373 374 375
    }
  }

376
  // Clean up the batch table and unset the static $batch variable.
377
  if ($batch['progressive']) {
378 379 380
    db_delete('batch')
      ->condition('bid', $batch['id'])
      ->execute();
381
  }
382 383 384 385 386
  $_batch = $batch;
  $batch = NULL;

  // Redirect if needed.
  if ($_batch['progressive']) {
387
    // Revert the 'destination' that was saved in batch_process().
388 389 390
    if (isset($_batch['destination'])) {
      $_REQUEST['destination'] = $_batch['destination'];
    }
391

392
    // Determine the target path to redirect to.
393 394 395 396 397 398 399 400 401 402
    if (isset($_batch['form_state']['redirect'])) {
      $redirect = $_batch['form_state']['redirect'];
    }
    elseif (isset($_batch['redirect'])) {
      $redirect = $_batch['redirect'];
    }
    else {
      $redirect = $_batch['source_page'];
    }

403
    // Use drupal_redirect_form() to handle the redirection logic.
404 405 406 407 408
    $form = isset($batch['form']) ? $batch['form'] : array();
    if (empty($_batch['form_state']['rebuild']) && empty($_batch['form_state']['storage'])) {
      drupal_redirect_form($form, $redirect);
    }

409 410
    // We get here if $form['#redirect'] was FALSE, or if the form is a
    // multi-step form. We save the final $form_state value to be retrieved
411
    // by drupal_get_form(), and redirect to the originating page.
412
    $_SESSION['batch_form_state'] = $_batch['form_state'];
413 414 415 416 417
    drupal_goto($_batch['source_page']);
  }
}

/**
418
 * Shutdown function; store the current batch data for the next request.
419 420 421
 */
function _batch_shutdown() {
  if ($batch = batch_get()) {
422 423 424 425
    db_update('batch')
      ->fields(array('batch' => serialize($batch)))
      ->condition('bid', $batch['id'])
      ->execute();
426 427
  }
}
428