batch.inc 15.6 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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * Loads a batch from the database.
 *
 * @param $id
 *   The ID of the batch to load. When a progressive batch is being processed,
 *   the relevant ID is found in $_REQUEST['id'].
 * @return
 *   An array representing the batch, or FALSE if no batch was found.
 */
function batch_load($id) {
  $batch = db_query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(
    ':bid' => $id,
    ':token' => drupal_get_token($id),
  ))->fetchField();
  if ($batch) {
    return unserialize($batch);
  }
  return FALSE;
}

39
/**
40
 * State-based dispatcher for the batch processing page.
41
42
 *
 * @see _batch_shutdown()
43
44
 */
function _batch_page() {
45
  $batch = &batch_get();
46

47
  if (!isset($_REQUEST['id'])) {
48
49
50
    return FALSE;
  }

51
  // Retrieve the current state of the batch.
52
  if (!$batch) {
53
54
55
56
57
    $batch = batch_load($_REQUEST['id']);
    if (!$batch) {
      drupal_set_message(t('No active batch.'), 'error');
      drupal_goto();
    }
58
59
  }

60
  // Register database update for the end of processing.
61
62
  register_shutdown_function('_batch_shutdown');

63
  // Add batch-specific CSS.
64
65
66
67
68
69
  foreach ($batch['sets'] as $batch_set) {
    foreach ($batch_set['css'] as $css) {
      drupal_add_css($css);
    }
  }

70
  $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
71
  $output = NULL;
72
73
74
75
76
77
  switch ($op) {
    case 'start':
      $output = _batch_start();
      break;

    case 'do':
78
      // JavaScript-based progress page callback.
79
      _batch_do();
80
81
82
      break;

    case 'do_nojs':
83
      // Non-JavaScript-based progress page.
84
85
86
87
88
89
90
91
92
93
94
95
      $output = _batch_progress_page_nojs();
      break;

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

  return $output;
}

/**
96
97
98
99
100
 * 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.
101
102
103
104
105
106
107
108
109
110
111
 */
function _batch_start() {
  if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
    return _batch_progress_page_js();
  }
  else {
    return _batch_progress_page_nojs();
  }
}

/**
112
113
114
115
116
117
118
119
120
 * 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()
121
122
123
124
 */
function _batch_progress_page_js() {
  $batch = batch_get();

125
  $current_set = _batch_current_set();
126
  drupal_set_title($current_set['title'], PASS_THROUGH);
127

128
129
130
131
  // Merge required query parameters for batch processing into those provided by
  // batch_set() or hook_batch_alter().
  $batch['url_options']['query']['id'] = $batch['id'];

132
133
  $js_setting = array(
    'batch' => array(
134
      'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
135
      'initMessage' => $current_set['init_message'],
136
      'uri' => url($batch['url'], $batch['url_options']),
137
138
139
    ),
  );
  drupal_add_js($js_setting, 'setting');
140
  drupal_add_js('misc/progress.js', array('cache' => FALSE));
141
  drupal_add_js('misc/batch.js', array('cache' => FALSE));
142

143
  return '<div id="progress"></div>';
144
145
146
}

/**
147
148
149
150
 * Do one pass of execution in JavaScript-mode and return progress to the browser.
 *
 * @see _batch_progress_page_js()
 * @see _batch_process()
151
152
 */
function _batch_do() {
153
  // HTTP POST required.
154
155
156
157
158
159
  if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    drupal_set_message(t('HTTP POST is required.'), 'error');
    drupal_set_title(t('Error'));
    return '';
  }

160
  // Perform actual processing.
161
162
  list($percentage, $message) = _batch_process();

163
  drupal_json_output(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
164
165
166
}

/**
167
168
169
 * Output a batch processing page without JavaScript support.
 *
 * @see _batch_process()
170
171
 */
function _batch_progress_page_nojs() {
172
  $batch = &batch_get();
173

174
  $current_set = _batch_current_set();
175
  drupal_set_title($current_set['title'], PASS_THROUGH);
176
177
178
179

  $new_op = 'do_nojs';

  if (!isset($batch['running'])) {
180
    // This is the first page so we return some output immediately.
181
182
    $percentage       = 0;
    $message          = $current_set['init_message'];
183
184
185
    $batch['running'] = TRUE;
  }
  else {
186
    // This is one of the later requests; do some processing first.
187

188
189
190
    // 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.
191
    ob_start();
192
    $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
193
    $fallback = theme('maintenance_page', array('content' => $fallback, 'show_messages' => FALSE));
194
195

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

202
    // Perform actual processing.
203
204
205
206
207
    list($percentage, $message) = _batch_process($batch);
    if ($percentage == 100) {
      $new_op = 'finished';
    }

208
    // PHP did not die; remove the fallback output.
209
210
211
    ob_end_clean();
  }

212
213
214
215
216
217
  // 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']);
218
219
220
221
222
223
224
225
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      'http-equiv' => 'Refresh',
      'content' => '0; URL=' . $url,
    ),
  );
  drupal_add_html_head($element, 'batch_progress_meta_refresh');
226

227
  return theme('progress_bar', array('percent' => $percentage, 'message' => $message));
228
229
230
}

/**
231
232
233
234
235
236
237
238
239
 * 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.
240
241
 */
function _batch_process() {
242
243
244
  $batch       = &batch_get();
  $current_set = &_batch_current_set();
  // Indicate that this batch set needs to be initialized.
245
  $set_changed = TRUE;
246

247
  // If this batch was marked for progressive execution (e.g. forms submitted by
248
  // drupal_form_submit()), initialize a timer to determine whether we need to
249
250
  // proceed with the same batch phase when a processing time of 1 second has
  // been exceeded.
251
252
253
254
  if ($batch['progressive']) {
    timer_start('batch_processing');
  }

255
  while (!$current_set['success']) {
256
257
258
259
    // 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'])) {
260
      include_once DRUPAL_ROOT . '/' . $current_set['file'];
261
262
    }

263
    $task_message = '';
264
265
    // We assume a single pass operation and set the completion level to 1 by
    // default.
266
    $finished = 1;
267
    if ((list($function, $args) = reset($current_set['operations'])) && function_exists($function)) {
268
269
270
271
272
273
274
275
      // 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,
      );
276
      // Process the current operation.
277
278
      call_user_func_array($function, array_merge($args, array(&$batch_context)));
    }
279

280
    if ($finished == 1) {
281
      // Make sure this step is not counted twice when computing $current.
282
      $finished = 0;
283
      // Remove the processed operation and clear the sandbox.
284
285
      array_shift($current_set['operations']);
      $current_set['sandbox'] = array();
286
    }
287

288
289
290
291
    // 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.
292
293
    $set_changed = FALSE;
    $old_set = $current_set;
294
    while (empty($current_set['operations']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
295
      $current_set = &_batch_current_set();
296
      $set_changed = TRUE;
297
    }
298
299
    // At this point, either $current_set contains operations that need to be
    // processed or all sets have been completed.
300

301
    // If we are in progressive mode, break processing after 1 second.
302
    if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
Dries's avatar
Dries committed
303
      // Record elapsed wall clock time.
304
      $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
305
306
307
308
309
      break;
    }
  }

  if ($batch['progressive']) {
310
311
312
313
    // 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,
314
    // we have to use the info from the new (unprocessed) set.
315
316
    if ($set_changed && isset($current_set['operations'])) {
      // Processing will continue with a fresh batch set.
317
318
      $remaining        = count($current_set['operations']);
      $total            = $current_set['total'];
319
      $progress_message = $current_set['init_message'];
320
      $task_message     = '';
321
322
    }
    else {
323
324
325
      // Processing will continue with the current batch set.
      $remaining        = count($old_set['operations']);
      $total            = $old_set['total'];
326
327
328
      $progress_message = $old_set['progress_message'];
    }

329
330
331
    $current = $total - $remaining + $finished;
    $percentage = _batch_api_percentage($total, $current);

332
333
334
    $elapsed    = $current_set['elapsed'];
    // Estimate remaining with percentage in floating format.
    $estimate   = $elapsed * ($total - $current) / $current;
335
    $values     = array(
336
337
338
339
      '@remaining'  => $remaining,
      '@total'      => $total,
      '@current'    => floor($current),
      '@percentage' => $percentage,
340
341
      '@elapsed'    => format_interval($elapsed / 1000),
      '@estimate'   => format_interval($estimate / 1000),
342
343
344
    );
    $message = strtr($progress_message, $values);
    if (!empty($message)) {
345
346
347
348
      $message .= '<br />';
    }
    if (!empty($task_message)) {
      $message .= $task_message;
349
    }
350
351
352
353

    return array($percentage, $message);
  }
  else {
354
    // If we are not in progressive mode, the entire batch has been processed.
355
356
357
358
    return _batch_finished();
  }
}

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**
 * Helper function for _batch_process(): returns the formatted percentage.
 *
 * @param $total
 *   The total number of operations.
 * @param $current
 *   The number of the current operation.
 * @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.
 */
function _batch_api_percentage($total, $current) {
  if (!$total || $total == $current) {
    // If $total doesn't evaluate as true or is equal to the current set, then
    // we're finished, and we can return "100".
    $percentage = "100";
  }
  else {
    // We add a new digit at 200, 2000, etc. (since, for example, 199/200
    // would round up to 100% if we didn't).
    $decimal_places = max(0, floor(log10($total / 2.0)) - 1);
    $percentage = sprintf('%01.' . $decimal_places . 'f', round($current / $total * 100, $decimal_places));
  }
  return $percentage;
}

387
/**
388
 * Return the batch set being currently processed.
389
390
 */
function &_batch_current_set() {
391
  $batch = &batch_get();
392
393
394
395
  return $batch['sets'][$batch['current_set']];
}

/**
396
397
398
399
400
401
402
403
 * 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.
404
405
 */
function _batch_next_set() {
406
  $batch = &batch_get();
407
  if (isset($batch['sets'][$batch['current_set'] + 1])) {
408
    $batch['current_set']++;
409
    $current_set = &_batch_current_set();
410
    if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
411
412
      // 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
413
      $function($batch['form'], $batch['form_state']);
414
415
416
417
418
419
    }
    return TRUE;
  }
}

/**
420
421
422
423
 * End the batch processing.
 *
 * Call the 'finished' callback of each batch set to allow custom handling of
 * the results and resolve page redirection.
424
425
 */
function _batch_finished() {
426
  $batch = &batch_get();
427

428
  // Execute the 'finished' callbacks for each batch set, if defined.
429
  foreach ($batch['sets'] as $key => $batch_set) {
430
    if (isset($batch_set['finished'])) {
431
      // Check if the set requires an additional file for function definitions.
432
      if (isset($batch_set['file']) && is_file($batch_set['file'])) {
433
        include_once DRUPAL_ROOT . '/' . $batch_set['file'];
434
435
      }
      if (function_exists($batch_set['finished'])) {
436
437
        // 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));
438
      }
439
440
441
    }
  }

442
  // Clean up the batch table and unset the static $batch variable.
443
  if ($batch['progressive']) {
444
445
446
    db_delete('batch')
      ->condition('bid', $batch['id'])
      ->execute();
447
  }
448
449
450
  $_batch = $batch;
  $batch = NULL;

451
452
453
454
455
456
  // Clean-up the session.
  unset($_SESSION['batches'][$batch['id']]);
  if (empty($_SESSION['batches'])) {
    unset($_SESSION['batches']);
  }

457
458
  // Redirect if needed.
  if ($_batch['progressive']) {
459
    // Revert the 'destination' that was saved in batch_process().
460
    if (isset($_batch['destination'])) {
461
      $_GET['destination'] = $_batch['destination'];
462
    }
463

464
    // Determine the target path to redirect to.
465
466
467
468
469
    if (!isset($_batch['form_state']['redirect'])) {
      if (isset($_batch['redirect'])) {
        $_batch['form_state']['redirect'] = $_batch['redirect'];
      }
      else {
470
        $_batch['form_state']['redirect'] = $_batch['source_url'];
471
      }
472
473
    }

474
    // Use drupal_redirect_form() to handle the redirection logic.
475
    drupal_redirect_form($_batch['form_state']);
476

477
478
    // If no redirection happened, save the final $form_state value to be
    // retrieved by drupal_get_form() and redirect to the originating page.
479
    $_SESSION['batch_form_state'] = $_batch['form_state'];
480
481
    $function = $_batch['redirect_callback'];
    if (function_exists($function)) {
482
      $function($_batch['source_url'], array('query' => array('op' => 'finish', 'id' => $_batch['id'])));
483
    }
484
485
486
487
  }
}

/**
488
 * Shutdown function; store the current batch data for the next request.
489
490
491
 */
function _batch_shutdown() {
  if ($batch = batch_get()) {
492
493
494
495
    db_update('batch')
      ->fields(array('batch' => serialize($batch)))
      ->condition('bid', $batch['id'])
      ->execute();
496
497
  }
}
498