Code coverage for /20081101/includes/batch.inc

Line #Times calledCode
1
<?php
2
// $Id: batch.inc,v 1.27 2008/11/01 18:32:22 dries Exp $
3
4
/**
5
 * @file Batch processing API for processes to run in multiple HTTP
requests.
6
 */
7
8
/**
9
 * State-based dispatcher for the batch processing page.
10
 */
118
function _batch_page() {
128
  $batch =& batch_get();
13
148
  if (!isset($_REQUEST['id'])) {
150
    return FALSE;
160
  }
17
18
  // Retrieve the current state of batch from db.
198
  $batch = db_query("SELECT batch FROM {batch} WHERE bid = :bid AND token =
:token", array(
208
    ':bid' => $_REQUEST['id'],
218
    ':token' => drupal_get_token($_REQUEST['id']))
228
  )->fetchField();
23
248
  $batch = unserialize($batch);
25
26
  // Register database update for end of processing.
278
  register_shutdown_function('_batch_shutdown');
28
29
  // Add batch-specific css.
308
  foreach ($batch['sets'] as $batch_set) {
318
    foreach ($batch_set['css'] as $css) {
328
      drupal_add_css($css);
338
    }
348
  }
35
368
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
378
  $output = NULL;
38
  switch ($op) {
398
    case 'start':
402
      $output = _batch_start();
412
      break;
42
436
    case 'do':
44
      // JS-version AJAX callback.
450
      _batch_do();
460
      break;
47
486
    case 'do_nojs':
49
      // Non-JS progress page.
504
      $output = _batch_progress_page_nojs();
512
      break;
52
532
    case 'finished':
542
      $output = _batch_finished();
550
      break;
560
  }
57
584
  return $output;
590
}
60
61
/**
62
 * Initiate the batch processing
63
 */
648
function _batch_start() {
65
  // Choose between the JS and non-JS version.
66
  // JS-enabled users are identified through the 'has_js' cookie set in
drupal.js.
67
  // If the user did not visit any JS enabled page during his browser
session,
68
  // he gets the non-JS version...
692
  if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
700
    return _batch_progress_page_js();
710
  }
72
  else {
732
    return _batch_progress_page_nojs();
74
  }
750
}
76
77
/**
78
 * Batch processing page with JavaScript support.
79
 */
808
function _batch_progress_page_js() {
810
  $batch = batch_get();
82
83
  // The first batch set gets to set the page title and the initialization
and
84
  // error messages. Only safe strings should be passed in to batch_set().
850
  $current_set = _batch_current_set();
860
  drupal_set_title($current_set['title'], PASS_THROUGH);
870
  drupal_add_js('misc/progress.js', array('type' => 'core', 'cache' =>
FALSE));
88
890
  $url = url($batch['url'], array('query' => array('id' => $batch['id'])));
90
  $js_setting = array(
91
    'batch' => array(
920
      'errorMessage' => $current_set['error_message'] . '<br/>' .
$batch['error_message'],
930
      'initMessage' => $current_set['init_message'],
940
      'uri' => $url,
950
    ),
960
  );
970
  drupal_add_js($js_setting, 'setting');
980
  drupal_add_js('misc/batch.js', array('type' => 'core', 'cache' =>
FALSE));
99
1000
  $output = '<div id="progress"></div>';
1010
  return $output;
1020
}
103
104
/**
105
 * Do one pass of execution and inform back the browser about progression
106
 * (used for JavaScript-mode only).
107
 */
1088
function _batch_do() {
109
  // HTTP POST required
1100
  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
1110
    drupal_set_message(t('HTTP POST is required.'), 'error');
1120
    drupal_set_title(t('Error'));
1130
    return '';
1140
  }
115
116
  // Perform actual processing.
1170
  list($percentage, $message) = _batch_process();
118
1190
  drupal_json(array('status' => TRUE, 'percentage' => $percentage,
'message' => $message));
1200
}
121
122
/**
123
 * Batch processing page without JavaScript support.
124
 */
1258
function _batch_progress_page_nojs() {
1266
  $batch =& batch_get();
1276
  $current_set = _batch_current_set();
128
1296
  drupal_set_title($current_set['title'], PASS_THROUGH);
130
1316
  $new_op = 'do_nojs';
132
1336
  if (!isset($batch['running'])) {
134
    // This is the first page so we return some output immediately.
1352
    $percentage = 0;
1362
    $message = $current_set['init_message'];
1372
    $batch['running'] = TRUE;
1382
  }
139
  else {
140
    // This is one of the later requests: do some processing first.
141
142
    // Error handling: if PHP dies due to a fatal error (e.g. non-existant
143
    // function), it will output whatever is in the output buffer,
144
    // followed by the error message.
1454
    ob_start();
1464
    $fallback = $current_set['error_message'] . '<br/>' .
$batch['error_message'];
1474
    $fallback = theme('maintenance_page', $fallback, FALSE, FALSE);
148
149
    // We strip the end of the page using a marker in the template, so any
150
    // additional HTML output by PHP shows up inside the page rather than
151
    // below it. While this causes invalid HTML, the same would be true if
152
    // we didn't, as content is not allowed to appear after </html> anyway.
1534
    list($fallback) = explode('<!--partial-->', $fallback);
1544
    print $fallback;
155
156
    // Perform actual processing.
1574
    list($percentage, $message) = _batch_process($batch);
1582
    if ($percentage == 100) {
1592
      $new_op = 'finished';
1602
    }
161
162
    // PHP did not die : remove the fallback output.
1632
    ob_end_clean();
164
  }
165
1664
  $url = url($batch['url'], array('query' => array('id' => $batch['id'],
'op' => $new_op)));
1674
  drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL=' . $url
. '">');
1684
  $output = theme('progress_bar', $percentage, $message);
1694
  return $output;
1700
}
171
172
/**
173
 * 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
 */
1768
function _batch_process() {
1774
  $batch =& batch_get();
1784
  $current_set =& _batch_current_set();
1794
  $set_changed = TRUE;
180
1814
  if ($batch['progressive']) {
1824
    timer_start('batch_processing');
1834
  }
184
1854
  while (!$current_set['success']) {
186
    // If this is the first time we iterate this batch set in the current
187
    // request, we check if it requires an additional file for functions
188
    // definitions.
1894
    if ($set_changed && isset($current_set['file']) &&
is_file($current_set['file'])) {
1900
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
1910
    }
192
1934
    $task_message = '';
194
    // We assume a single pass operation and set the completion level
195
    // to 1 by default.
1964
    $finished = 1;
1974
    if ((list($function, $args) = reset($current_set['operations'])) &&
function_exists($function)) {
198
      // Build the 'context' array, execute the function call,
199
      // and retrieve the user message.
2004
      $batch_context = array('sandbox' => &$current_set['sandbox'],
'results' => &$current_set['results'], 'finished' => &$finished, 'message'
=> &$task_message);
201
      // Process the current operation.
2024
      call_user_func_array($function, array_merge($args,
array(&$batch_context)));
2032
    }
204
2052
    if ($finished == 1) {
206
      // Make sure this step isn't counted double when computing $current.
2072
      $finished = 0;
208
      // Remove the operation and clear the sandbox.
2092
      array_shift($current_set['operations']);
2102
      $current_set['sandbox'] = array();
2112
    }
212
213
    // If the batch set is completed, browse through the remaining sets,
214
    // executing 'control sets' (stored form submit handlers) along the way
-
215
    // this might in turn insert new batch sets.
216
    // Stop when we find a set that actually has operations.
2172
    $set_changed = FALSE;
2182
    $old_set = $current_set;
2192
    while (empty($current_set['operations']) && ($current_set['success'] =
TRUE) && _batch_next_set()) {
2200
      $current_set =& _batch_current_set();
2210
      $set_changed = TRUE;
2220
    }
223
    // At this point, either $current_set is a 'real' batch set (has
operations),
224
    // or all sets have been completed.
225
226
    // If we're in progressive mode, stop after 1 second.
2272
    if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
2282
      break;
2290
    }
2300
  }
231
2322
  if ($batch['progressive']) {
233
    // Gather progress information.
234
235
    // Reporting 100% progress will cause the whole batch to be considered
236
    // processed. If processing was paused right after moving to a new set,
237
    // we have to use the info from the new (unprocessed) one.
2382
    if ($set_changed && isset($current_set['operations'])) {
239
      // Processing will continue with a fresh batch set.
2400
      $remaining = count($current_set['operations']);
2410
      $total = $current_set['total'];
2420
      $progress_message = $current_set['init_message'];
2430
      $task_message = '';
2440
    }
245
    else {
2462
      $remaining = count($old_set['operations']);
2472
      $total = $old_set['total'];
2482
      $progress_message = $old_set['progress_message'];
249
    }
250
2512
    $current    = $total - $remaining + $finished;
2522
    $percentage = $total ? floor($current / $total * 100) : 100;
253
    $values = array(
2542
      '@remaining'  => $remaining,
2552
      '@total'      => $total,
2562
      '@current'    => floor($current),
2572
      '@percentage' => $percentage,
2582
    );
2592
    $message = strtr($progress_message, $values);
2602
    if (!empty($message)) {
261
      $message .= '<br/>';
2622
    }
2630
    $message .= $task_message ? $task_message : '&nbsp';
264
265
    return array($percentage, $message);
2660
  }
267
  else {
268
    // If we're not in progressive mode, the whole batch has been processed
by now.
2690
    return _batch_finished();
270
  }
271
272
}
273
2748
/**
2756
 * Retrieve the batch set being currently processed.
2766
 */
2770
function &_batch_current_set() {
278
  $batch =& batch_get();
279
  return $batch['sets'][$batch['current_set']];
280
}
281
282
/**
283
 * Move execution to the next batch set if any, executing the stored
2848
 * form _submit handlers along the way (thus possibly inserting
2852
 * additional batch sets).
2862
 */
2870
function _batch_next_set() {
2880
  $batch =& batch_get();
2890
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
290
    $batch['current_set']++;
291
    $current_set =& _batch_current_set();
2920
    if (isset($current_set['form_submit']) && ($function =
$current_set['form_submit']) && function_exists($function)) {
2930
      // We use our stored copies of $form and $form_state, to account for
2940
      // possible alteration by the submit handlers.
2950
      $function($batch['form'], $batch['form_state']);
2962
    }
297
    return TRUE;
298
  }
299
}
300
301
/**
302
 * End the batch processing:
3038
 * Call the 'finished' callbacks to allow custom handling of results,
3042
 * and resolve page redirection.
305
 */
306
function _batch_finished() {
3072
  $batch =& batch_get();
3082
309
  // Execute the 'finished' callbacks for each batch set.
3102
  foreach ($batch['sets'] as $key => $batch_set) {
3110
    if (isset($batch_set['finished'])) {
3120
      // Check if the set requires an additional file for functions
definitions.
3132
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
3142
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
3152
      }
3162
      if (function_exists($batch_set['finished'])) {
3172
        $batch_set['finished']($batch_set['success'],
$batch_set['results'], $batch_set['operations']);
318
      }
319
    }
3202
  }
3212
3222
  // Cleanup the batch table and unset the global $batch variable.
3232
  if ($batch['progressive']) {
3242
    db_delete('batch')
3252
      ->condition('bid', $batch['id'])
3262
      ->execute();
327
  }
328
  $_batch = $batch;
3292
  $batch = NULL;
330
3312
  // Redirect if needed.
3320
  if ($_batch['progressive']) {
3330
    // Put back the 'destination' that was saved in batch_process().
334
    if (isset($_batch['destination'])) {
335
      $_REQUEST['destination'] = $_batch['destination'];
336
    }
3372
3380
    // Use $_batch['form_state']['redirect'], or $_batch['redirect'],
3390
    // or $_batch['source_page'].
3402
    if (isset($_batch['form_state']['redirect'])) {
3410
      $redirect = $_batch['form_state']['redirect'];
3420
    }
343
    elseif (isset($_batch['redirect'])) {
3442
      $redirect = $_batch['redirect'];
345
    }
346
    else {
347
      $redirect = $_batch['source_page'];
3482
    }
3492
3502
    // Let drupal_redirect_form handle redirection logic.
3510
    $form = isset($batch['form']) ? $batch['form'] : array();
352
    if (empty($_batch['form_state']['rebuild']) &&
empty($_batch['form_state']['storage'])) {
353
      drupal_redirect_form($form, $redirect);
354
    }
355
3560
    // We get here if $form['#redirect'] was FALSE, or if the form is a
3570
    // multi-step form. We save the final $form_state value to be retrieved
3580
    // by drupal_get_form, and we redirect to the originating page.
3590
    $_SESSION['batch_form_state'] = $_batch['form_state'];
360
    drupal_goto($_batch['source_page']);
361
  }
362
}
363
364
/**
3658
 * Shutdown function: store the batch data for next request,
3660
 * or clear the table if the batch is finished.
3670
 */
3680
function _batch_shutdown() {
3690
  if ($batch = batch_get()) {
3700
    db_update('batch')
3710
      ->fields(array('batch' => serialize($batch)))
3720
      ->condition('bid', $batch['id'])
3738
      ->execute();
374
  }
375
}
376