batch.inc 11.7 KB
Newer Older
1
<?php
2
// $Id$
3 4 5 6 7 8

/**
 * @file Batch processing API for processes to run in multiple HTTP requests.
 */

/**
9
 * State-based dispatcher for the batch processing page.
10 11 12 13
 */
function _batch_page() {
  $batch =& batch_get();

14
  if (!isset($_REQUEST['id'])) {
15 16 17
    return FALSE;
  }

18 19 20 21 22 23 24 25
  // 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);

26 27 28
  // Register database update for end of processing.
  register_shutdown_function('_batch_shutdown');

29 30 31 32 33 34 35
  // Add batch-specific css.
  foreach ($batch['sets'] as $batch_set) {
    foreach ($batch_set['css'] as $css) {
      drupal_add_css($css);
    }
  }

36
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
37
  $output = NULL;
38 39 40 41 42 43
  switch ($op) {
    case 'start':
      $output = _batch_start();
      break;

    case 'do':
44
      // JS-version AJAX callback.
45
      _batch_do();
46 47 48
      break;

    case 'do_nojs':
49
      // Non-JS progress page.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
      $output = _batch_progress_page_nojs();
      break;

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

  return $output;
}

/**
 * Initiate the batch processing
 */
function _batch_start() {
  // Choose between the JS and non-JS version.
  // JS-enabled users are identified through the 'has_js' cookie set in drupal.js.
  // If the user did not visit any JS enabled page during his browser session,
  // he gets the non-JS version...
  if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
    return _batch_progress_page_js();
  }
  else {
    return _batch_progress_page_nojs();
  }
}

/**
 * Batch processing page with JavaScript support.
 */
function _batch_progress_page_js() {
  $batch = batch_get();

83 84
  // The first batch set gets to set the page title and the initialization and
  // error messages. Only safe strings should be passed in to batch_set().
85
  $current_set = _batch_current_set();
86
  drupal_set_title($current_set['title'], PASS_THROUGH);
87
  drupal_add_js('misc/progress.js', array('type' => 'core', 'cache' => FALSE));
88 89 90 91

  $url = url($batch['url'], array('query' => array('id' => $batch['id'])));
  $js_setting = array(
    'batch' => array(
92
      'errorMessage' => $current_set['error_message'] . '<br/>' . $batch['error_message'],
93 94 95 96 97
      'initMessage' => $current_set['init_message'],
      'uri' => $url,
    ),
  );
  drupal_add_js($js_setting, 'setting');
98
  drupal_add_js('misc/batch.js', array('type' => 'core', 'cache' => FALSE));
99 100 101 102 103 104

  $output = '<div id="progress"></div>';
  return $output;
}

/**
105 106
 * Do one pass of execution and inform back the browser about progression
 * (used for JavaScript-mode only).
107 108 109 110 111 112 113 114 115
 */
function _batch_do() {
  // HTTP POST required
  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    drupal_set_message(t('HTTP POST is required.'), 'error');
    drupal_set_title(t('Error'));
    return '';
  }

116
  // Perform actual processing.
117 118
  list($percentage, $message) = _batch_process();

119
  drupal_json(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
120 121 122 123 124 125 126 127 128
}

/**
 * Batch processing page without JavaScript support.
 */
function _batch_progress_page_nojs() {
  $batch =& batch_get();
  $current_set = _batch_current_set();

129
  drupal_set_title($current_set['title'], PASS_THROUGH);
130 131 132 133

  $new_op = 'do_nojs';

  if (!isset($batch['running'])) {
134
    // This is the first page so we return some output immediately.
135 136 137 138 139 140 141 142 143 144 145
    $percentage = 0;
    $message = $current_set['init_message'];
    $batch['running'] = TRUE;
  }
  else {
    // This is one of the later requests: do some processing first.

    // Error handling: if PHP dies due to a fatal error (e.g. non-existant
    // function), it will output whatever is in the output buffer,
    // followed by the error message.
    ob_start();
146
    $fallback = $current_set['error_message'] . '<br/>' . $batch['error_message'];
147
    $fallback = theme('maintenance_page', $fallback, FALSE, FALSE);
148 149 150 151 152 153 154 155

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

156
    // Perform actual processing.
157 158 159 160 161
    list($percentage, $message) = _batch_process($batch);
    if ($percentage == 100) {
      $new_op = 'finished';
    }

162
    // PHP did not die : remove the fallback output.
163 164 165 166
    ob_end_clean();
  }

  $url = url($batch['url'], array('query' => array('id' => $batch['id'], 'op' => $new_op)));
167
  drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL=' . $url . '">');
168 169 170 171 172 173
  $output = theme('progress_bar', $percentage, $message);
  return $output;
}

/**
 * Advance batch processing for 1 second (or process the whole batch if it
174
 * was not set for progressive execution - e.g forms submitted by drupal_execute).
175 176 177 178
 */
function _batch_process() {
  $batch =& batch_get();
  $current_set =& _batch_current_set();
179
  $set_changed = TRUE;
180

181 182 183 184
  if ($batch['progressive']) {
    timer_start('batch_processing');
  }

185
  while (!$current_set['success']) {
186 187 188 189
    // 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'])) {
190
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
191 192
    }

193
    $task_message = '';
194 195 196
    // We assume a single pass operation and set the completion level
    // to 1 by default.
    $finished = 1;
197
    if ((list($function, $args) = reset($current_set['operations'])) && function_exists($function)) {
198 199
      // Build the 'context' array, execute the function call,
      // and retrieve the user message.
200
      $batch_context = array('sandbox' => &$current_set['sandbox'], 'results' => &$current_set['results'], 'finished' => &$finished, 'message' => &$task_message);
201
      // Process the current operation.
202 203
      call_user_func_array($function, array_merge($args, array(&$batch_context)));
    }
204

205
    if ($finished == 1) {
206
      // Make sure this step isn't counted double when computing $current.
207
      $finished = 0;
208
      // Remove the operation and clear the sandbox.
209 210
      array_shift($current_set['operations']);
      $current_set['sandbox'] = array();
211
    }
212

213
    // If the batch set is completed, browse through the remaining sets,
214 215 216
    // executing 'control sets' (stored form submit handlers) along the way -
    // this might in turn insert new batch sets.
    // Stop when we find a set that actually has operations.
217 218
    $set_changed = FALSE;
    $old_set = $current_set;
219 220
    while (empty($current_set['operations']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
      $current_set =& _batch_current_set();
221
      $set_changed = TRUE;
222
    }
223 224
    // At this point, either $current_set is a 'real' batch set (has operations),
    // or all sets have been completed.
225

226
    // If we're in progressive mode, stop after 1 second.
227
    if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
228 229 230 231 232
      break;
    }
  }

  if ($batch['progressive']) {
233 234 235 236
    // 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,
237
    // we have to use the info from the new (unprocessed) one.
238 239 240 241 242 243 244 245 246 247 248 249 250
    if ($set_changed && isset($current_set['operations'])) {
      // Processing will continue with a fresh batch set.
      $remaining = count($current_set['operations']);
      $total = $current_set['total'];
      $progress_message = $current_set['init_message'];
      $task_message = '';
    }
    else {
      $remaining = count($old_set['operations']);
      $total = $old_set['total'];
      $progress_message = $old_set['progress_message'];
    }

251
    $current    = $total - $remaining + $finished;
252
    $percentage = $total ? floor($current / $total * 100) : 100;
253 254 255 256 257
    $values = array(
      '@remaining'  => $remaining,
      '@total'      => $total,
      '@current'    => floor($current),
      '@percentage' => $percentage,
258 259 260 261 262
    );
    $message = strtr($progress_message, $values);
    if (!empty($message)) {
      $message .= '<br/>';
    }
263
    $message .= $task_message ? $task_message : '&nbsp';
264 265 266 267

    return array($percentage, $message);
  }
  else {
268
    // If we're not in progressive mode, the whole batch has been processed by now.
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    return _batch_finished();
  }

}

/**
 * Retrieve the batch set being currently processed.
 */
function &_batch_current_set() {
  $batch =& batch_get();
  return $batch['sets'][$batch['current_set']];
}

/**
 * Move execution to the next batch set if any, executing the stored
284
 * form _submit handlers along the way (thus possibly inserting
285
 * additional batch sets).
286 287 288
 */
function _batch_next_set() {
  $batch =& batch_get();
289
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
290 291
    $batch['current_set']++;
    $current_set =& _batch_current_set();
292 293 294
    if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
      // We use our stored copies of $form and $form_state, to account for
      // possible alteration by the submit handlers.
Dries's avatar
Dries committed
295
      $function($batch['form'], $batch['form_state']);
296 297 298 299 300 301
    }
    return TRUE;
  }
}

/**
302
 * End the batch processing:
303 304 305 306 307 308
 * Call the 'finished' callbacks to allow custom handling of results,
 * and resolve page redirection.
 */
function _batch_finished() {
  $batch =& batch_get();

309
  // Execute the 'finished' callbacks for each batch set.
310
  foreach ($batch['sets'] as $key => $batch_set) {
311 312 313
    if (isset($batch_set['finished'])) {
      // Check if the set requires an additional file for functions definitions.
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
314
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
315 316 317 318
      }
      if (function_exists($batch_set['finished'])) {
        $batch_set['finished']($batch_set['success'], $batch_set['results'], $batch_set['operations']);
      }
319 320 321 322
    }
  }

  // Cleanup the batch table and unset the global $batch variable.
323
  if ($batch['progressive']) {
324 325 326
    db_delete('batch')
      ->condition('bid', $batch['id'])
      ->execute();
327
  }
328 329 330 331 332
  $_batch = $batch;
  $batch = NULL;

  // Redirect if needed.
  if ($_batch['progressive']) {
333
    // Put back the 'destination' that was saved in batch_process().
334 335 336
    if (isset($_batch['destination'])) {
      $_REQUEST['destination'] = $_batch['destination'];
    }
337

338 339
    // Use $_batch['form_state']['redirect'], or $_batch['redirect'],
    // or $_batch['source_page'].
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    if (isset($_batch['form_state']['redirect'])) {
      $redirect = $_batch['form_state']['redirect'];
    }
    elseif (isset($_batch['redirect'])) {
      $redirect = $_batch['redirect'];
    }
    else {
      $redirect = $_batch['source_page'];
    }

    // Let drupal_redirect_form handle redirection logic.
    $form = isset($batch['form']) ? $batch['form'] : array();
    if (empty($_batch['form_state']['rebuild']) && empty($_batch['form_state']['storage'])) {
      drupal_redirect_form($form, $redirect);
    }

356 357 358
    // 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
    // by drupal_get_form, and we redirect to the originating page.
359
    $_SESSION['batch_form_state'] = $_batch['form_state'];
360 361 362 363 364
    drupal_goto($_batch['source_page']);
  }
}

/**
365 366
 * Shutdown function: store the batch data for next request,
 * or clear the table if the batch is finished.
367 368 369
 */
function _batch_shutdown() {
  if ($batch = batch_get()) {
370 371 372 373
    db_update('batch')
      ->fields(array('batch' => serialize($batch)))
      ->condition('bid', $batch['id'])
      ->execute();
374 375
  }
}