Skip navigation
Help

batch.inc

  1. drupal
    1. 6 drupal/includes/batch.inc
    2. 7 drupal/includes/batch.inc

Batch processing API for processes to run in multiple HTTP requests.

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 also

form.inc

batch_set()

batch_process()

batch_get()

Functions & methods

NameDescription
batch_loadLoads a batch from the database.
_batch_api_percentageHelper function for _batch_process(): returns the formatted percentage.
_batch_current_setReturn the batch set being currently processed.
_batch_doDo one execution pass in JavaScript-mode and return progress to the browser.
_batch_finishedEnd the batch processing.
_batch_next_setRetrieve the next set in a batch.
_batch_pageState-based dispatcher for the batch processing page.
_batch_processProcess sets in a batch.
_batch_progress_page_jsOutput a batch processing page with JavaScript support.
_batch_progress_page_nojsOutput a batch processing page without JavaScript support.
_batch_shutdownShutdown function; store the current batch data for the next request.
_batch_startInitialize the batch processing.

File

drupal/includes/batch.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Batch processing API for processes to run in multiple HTTP requests.
  5. *
  6. * Note that batches are usually invoked by form submissions, which is
  7. * why the core interaction functions of the batch processing API live in
  8. * form.inc.
  9. *
  10. * @see form.inc
  11. * @see batch_set()
  12. * @see batch_process()
  13. * @see batch_get()
  14. */
  15. /**
  16. * Loads a batch from the database.
  17. *
  18. * @param $id
  19. * The ID of the batch to load. When a progressive batch is being processed,
  20. * the relevant ID is found in $_REQUEST['id'].
  21. * @return
  22. * An array representing the batch, or FALSE if no batch was found.
  23. */
  24. function batch_load($id) {
  25. $batch = db_query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(
  26. ':bid' => $id,
  27. ':token' => drupal_get_token($id),
  28. ))->fetchField();
  29. if ($batch) {
  30. return unserialize($batch);
  31. }
  32. return FALSE;
  33. }
  34. /**
  35. * State-based dispatcher for the batch processing page.
  36. *
  37. * @see _batch_shutdown()
  38. */
  39. function _batch_page() {
  40. $batch = &batch_get();
  41. if (!isset($_REQUEST['id'])) {
  42. return FALSE;
  43. }
  44. // Retrieve the current state of the batch.
  45. if (!$batch) {
  46. $batch = batch_load($_REQUEST['id']);
  47. if (!$batch) {
  48. drupal_set_message(t('No active batch.'), 'error');
  49. drupal_goto();
  50. }
  51. }
  52. // Register database update for the end of processing.
  53. drupal_register_shutdown_function('_batch_shutdown');
  54. // Add batch-specific CSS.
  55. foreach ($batch['sets'] as $batch_set) {
  56. if (isset($batch_set['css'])) {
  57. foreach ($batch_set['css'] as $css) {
  58. drupal_add_css($css);
  59. }
  60. }
  61. }
  62. $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
  63. $output = NULL;
  64. switch ($op) {
  65. case 'start':
  66. $output = _batch_start();
  67. break;
  68. case 'do':
  69. // JavaScript-based progress page callback.
  70. _batch_do();
  71. break;
  72. case 'do_nojs':
  73. // Non-JavaScript-based progress page.
  74. $output = _batch_progress_page_nojs();
  75. break;
  76. case 'finished':
  77. $output = _batch_finished();
  78. break;
  79. }
  80. return $output;
  81. }
  82. /**
  83. * Initialize the batch processing.
  84. *
  85. * JavaScript-enabled clients are identified by the 'has_js' cookie set in
  86. * drupal.js. If no JavaScript-enabled page has been visited during the current
  87. * user's browser session, the non-JavaScript version is returned.
  88. */
  89. function _batch_start() {
  90. if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
  91. return _batch_progress_page_js();
  92. }
  93. else {
  94. return _batch_progress_page_nojs();
  95. }
  96. }
  97. /**
  98. * Output a batch processing page with JavaScript support.
  99. *
  100. * This initializes the batch and error messages. Note that in JavaScript-based
  101. * processing, the batch processing page is displayed only once and updated via
  102. * AHAH requests, so only the first batch set gets to define the page title.
  103. * Titles specified by subsequent batch sets are not displayed.
  104. *
  105. * @see batch_set()
  106. * @see _batch_do()
  107. */
  108. function _batch_progress_page_js() {
  109. $batch = batch_get();
  110. $current_set = _batch_current_set();
  111. drupal_set_title($current_set['title'], PASS_THROUGH);
  112. // Merge required query parameters for batch processing into those provided by
  113. // batch_set() or hook_batch_alter().
  114. $batch['url_options']['query']['id'] = $batch['id'];
  115. $js_setting = array(
  116. 'batch' => array(
  117. 'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
  118. 'initMessage' => $current_set['init_message'],
  119. 'uri' => url($batch['url'], $batch['url_options']),
  120. ),
  121. );
  122. drupal_add_js($js_setting, 'setting');
  123. drupal_add_library('system', 'drupal.batch');
  124. return '<div id="progress"></div>';
  125. }
  126. /**
  127. * Do one execution pass in JavaScript-mode and return progress to the browser.
  128. *
  129. * @see _batch_progress_page_js()
  130. * @see _batch_process()
  131. */
  132. function _batch_do() {
  133. // HTTP POST required.
  134. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  135. drupal_set_message(t('HTTP POST is required.'), 'error');
  136. drupal_set_title(t('Error'));
  137. return '';
  138. }
  139. // Perform actual processing.
  140. list($percentage, $message) = _batch_process();
  141. drupal_json_output(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
  142. }
  143. /**
  144. * Output a batch processing page without JavaScript support.
  145. *
  146. * @see _batch_process()
  147. */
  148. function _batch_progress_page_nojs() {
  149. $batch = &batch_get();
  150. $current_set = _batch_current_set();
  151. drupal_set_title($current_set['title'], PASS_THROUGH);
  152. $new_op = 'do_nojs';
  153. if (!isset($batch['running'])) {
  154. // This is the first page so we return some output immediately.
  155. $percentage = 0;
  156. $message = $current_set['init_message'];
  157. $batch['running'] = TRUE;
  158. }
  159. else {
  160. // This is one of the later requests; do some processing first.
  161. // Error handling: if PHP dies due to a fatal error (e.g. a nonexistent
  162. // function), it will output whatever is in the output buffer, followed by
  163. // the error message.
  164. ob_start();
  165. $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
  166. $fallback = theme('maintenance_page', array('content' => $fallback, 'show_messages' => FALSE));
  167. // We strip the end of the page using a marker in the template, so any
  168. // additional HTML output by PHP shows up inside the page rather than below
  169. // it. While this causes invalid HTML, the same would be true if we didn't,
  170. // as content is not allowed to appear after </html> anyway.
  171. list($fallback) = explode('<!--partial-->', $fallback);
  172. print $fallback;
  173. // Perform actual processing.
  174. list($percentage, $message) = _batch_process($batch);
  175. if ($percentage == 100) {
  176. $new_op = 'finished';
  177. }
  178. // PHP did not die; remove the fallback output.
  179. ob_end_clean();
  180. }
  181. // Merge required query parameters for batch processing into those provided by
  182. // batch_set() or hook_batch_alter().
  183. $batch['url_options']['query']['id'] = $batch['id'];
  184. $batch['url_options']['query']['op'] = $new_op;
  185. $url = url($batch['url'], $batch['url_options']);
  186. $element = array(
  187. '#tag' => 'meta',
  188. '#attributes' => array(
  189. 'http-equiv' => 'Refresh',
  190. 'content' => '0; URL=' . $url,
  191. ),
  192. );
  193. drupal_add_html_head($element, 'batch_progress_meta_refresh');
  194. return theme('progress_bar', array('percent' => $percentage, 'message' => $message));
  195. }
  196. /**
  197. * Process sets in a batch.
  198. *
  199. * If the batch was marked for progressive execution (default), this executes as
  200. * many operations in batch sets until an execution time of 1 second has been
  201. * exceeded. It will continue with the next operation of the same batch set in
  202. * the next request.
  203. *
  204. * @return
  205. * An array containing a completion value (in percent) and a status message.
  206. */
  207. function _batch_process() {
  208. $batch = &batch_get();
  209. $current_set = &_batch_current_set();
  210. // Indicate that this batch set needs to be initialized.
  211. $set_changed = TRUE;
  212. // If this batch was marked for progressive execution (e.g. forms submitted by
  213. // drupal_form_submit()), initialize a timer to determine whether we need to
  214. // proceed with the same batch phase when a processing time of 1 second has
  215. // been exceeded.
  216. if ($batch['progressive']) {
  217. timer_start('batch_processing');
  218. }
  219. if (empty($current_set['start'])) {
  220. $current_set['start'] = microtime(TRUE);
  221. }
  222. $queue = _batch_queue($current_set);
  223. while (!$current_set['success']) {
  224. // If this is the first time we iterate this batch set in the current
  225. // request, we check if it requires an additional file for functions
  226. // definitions.
  227. if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
  228. include_once DRUPAL_ROOT . '/' . $current_set['file'];
  229. }
  230. $task_message = '';
  231. // Assume a single pass operation and set the completion level to 1 by
  232. // default.
  233. $finished = 1;
  234. if ($item = $queue->claimItem()) {
  235. list($function, $args) = $item->data;
  236. // Build the 'context' array and execute the function call.
  237. $batch_context = array(
  238. 'sandbox' => &$current_set['sandbox'],
  239. 'results' => &$current_set['results'],
  240. 'finished' => &$finished,
  241. 'message' => &$task_message,
  242. );
  243. call_user_func_array($function, array_merge($args, array(&$batch_context)));
  244. if ($finished >= 1) {
  245. // Make sure this step is not counted twice when computing $current.
  246. $finished = 0;
  247. // Remove the processed operation and clear the sandbox.
  248. $queue->deleteItem($item);
  249. $current_set['count']--;
  250. $current_set['sandbox'] = array();
  251. }
  252. }
  253. // When all operations in the current batch set are completed, browse
  254. // through the remaining sets, marking them 'successfully processed'
  255. // along the way, until we find a set that contains operations.
  256. // _batch_next_set() executes form submit handlers stored in 'control'
  257. // sets (see form_execute_handlers()), which can in turn add new sets to
  258. // the batch.
  259. $set_changed = FALSE;
  260. $old_set = $current_set;
  261. while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
  262. $current_set = &_batch_current_set();
  263. $current_set['start'] = microtime(TRUE);
  264. $set_changed = TRUE;
  265. }
  266. // At this point, either $current_set contains operations that need to be
  267. // processed or all sets have been completed.
  268. $queue = _batch_queue($current_set);
  269. // If we are in progressive mode, break processing after 1 second.
  270. if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
  271. // Record elapsed wall clock time.
  272. $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
  273. break;
  274. }
  275. }
  276. if ($batch['progressive']) {
  277. // Gather progress information.
  278. // Reporting 100% progress will cause the whole batch to be considered
  279. // processed. If processing was paused right after moving to a new set,
  280. // we have to use the info from the new (unprocessed) set.
  281. if ($set_changed && isset($current_set['queue'])) {
  282. // Processing will continue with a fresh batch set.
  283. $remaining = $current_set['count'];
  284. $total = $current_set['total'];
  285. $progress_message = $current_set['init_message'];
  286. $task_message = '';
  287. }
  288. else {
  289. // Processing will continue with the current batch set.
  290. $remaining = $old_set['count'];
  291. $total = $old_set['total'];
  292. $progress_message = $old_set['progress_message'];
  293. }
  294. // Total progress is the number of operations that have fully run plus the
  295. // completion level of the current operation.
  296. $current = $total - $remaining + $finished;
  297. $percentage = _batch_api_percentage($total, $current);
  298. $elapsed = isset($current_set['elapsed']) ? $current_set['elapsed'] : 0;
  299. $values = array(
  300. '@remaining' => $remaining,
  301. '@total' => $total,
  302. '@current' => floor($current),
  303. '@percentage' => $percentage,
  304. '@elapsed' => format_interval($elapsed / 1000),
  305. // If possible, estimate remaining processing time.
  306. '@estimate' => ($current > 0) ? format_interval(($elapsed * ($total - $current) / $current) / 1000) : '-',
  307. );
  308. $message = strtr($progress_message, $values);
  309. if (!empty($message)) {
  310. $message .= '<br />';
  311. }
  312. if (!empty($task_message)) {
  313. $message .= $task_message;
  314. }
  315. return array($percentage, $message);
  316. }
  317. else {
  318. // If we are not in progressive mode, the entire batch has been processed.
  319. return _batch_finished();
  320. }
  321. }
  322. /**
  323. * Helper function for _batch_process(): returns the formatted percentage.
  324. *
  325. * @param $total
  326. * The total number of operations.
  327. * @param $current
  328. * The number of the current operation. This may be a floating point number
  329. * rather than an integer in the case of a multi-step operation that is not
  330. * yet complete; in that case, the fractional part of $current represents the
  331. * fraction of the operation that has been completed.
  332. * @return
  333. * The properly formatted percentage, as a string. We output percentages
  334. * using the correct number of decimal places so that we never print "100%"
  335. * until we are finished, but we also never print more decimal places than
  336. * are meaningful.
  337. */
  338. function _batch_api_percentage($total, $current) {
  339. if (!$total || $total == $current) {
  340. // If $total doesn't evaluate as true or is equal to the current set, then
  341. // we're finished, and we can return "100".
  342. $percentage = "100";
  343. }
  344. else {
  345. // We add a new digit at 200, 2000, etc. (since, for example, 199/200
  346. // would round up to 100% if we didn't).
  347. $decimal_places = max(0, floor(log10($total / 2.0)) - 1);
  348. do {
  349. // Calculate the percentage to the specified number of decimal places.
  350. $percentage = sprintf('%01.' . $decimal_places . 'f', round($current / $total * 100, $decimal_places));
  351. // When $current is an integer, the above calculation will always be
  352. // correct. However, if $current is a floating point number (in the case
  353. // of a multi-step batch operation that is not yet complete), $percentage
  354. // may be erroneously rounded up to 100%. To prevent that, we add one
  355. // more decimal place and try again.
  356. $decimal_places++;
  357. } while ($percentage == '100');
  358. }
  359. return $percentage;
  360. }
  361. /**
  362. * Return the batch set being currently processed.
  363. */
  364. function &_batch_current_set() {
  365. $batch = &batch_get();
  366. return $batch['sets'][$batch['current_set']];
  367. }
  368. /**
  369. * Retrieve the next set in a batch.
  370. *
  371. * If there is a subsequent set in this batch, assign it as the new set to
  372. * process and execute its form submit handler (if defined), which may add
  373. * further sets to this batch.
  374. *
  375. * @return
  376. * TRUE if a subsequent set was found in the batch.
  377. */
  378. function _batch_next_set() {
  379. $batch = &batch_get();
  380. if (isset($batch['sets'][$batch['current_set'] + 1])) {
  381. $batch['current_set']++;
  382. $current_set = &_batch_current_set();
  383. if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
  384. // We use our stored copies of $form and $form_state to account for
  385. // possible alterations by previous form submit handlers.
  386. $function($batch['form_state']['complete form'], $batch['form_state']);
  387. }
  388. return TRUE;
  389. }
  390. }
  391. /**
  392. * End the batch processing.
  393. *
  394. * Call the 'finished' callback of each batch set to allow custom handling of
  395. * the results and resolve page redirection.
  396. */
  397. function _batch_finished() {
  398. $batch = &batch_get();
  399. // Execute the 'finished' callbacks for each batch set, if defined.
  400. foreach ($batch['sets'] as $batch_set) {
  401. if (isset($batch_set['finished'])) {
  402. // Check if the set requires an additional file for function definitions.
  403. if (isset($batch_set['file']) && is_file($batch_set['file'])) {
  404. include_once DRUPAL_ROOT . '/' . $batch_set['file'];
  405. }
  406. if (function_exists($batch_set['finished'])) {
  407. $queue = _batch_queue($batch_set);
  408. $operations = $queue->getAllItems();
  409. $batch_set['finished']($batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000));
  410. }
  411. }
  412. }
  413. // Clean up the batch table and unset the static $batch variable.
  414. if ($batch['progressive']) {
  415. db_delete('batch')
  416. ->condition('bid', $batch['id'])
  417. ->execute();
  418. foreach ($batch['sets'] as $batch_set) {
  419. if ($queue = _batch_queue($batch_set)) {
  420. $queue->deleteQueue();
  421. }
  422. }
  423. }
  424. $_batch = $batch;
  425. $batch = NULL;
  426. // Clean-up the session. Not needed for CLI updates.
  427. if (isset($_SESSION)) {
  428. unset($_SESSION['batches'][$batch['id']]);
  429. if (empty($_SESSION['batches'])) {
  430. unset($_SESSION['batches']);
  431. }
  432. }
  433. // Redirect if needed.
  434. if ($_batch['progressive']) {
  435. // Revert the 'destination' that was saved in batch_process().
  436. if (isset($_batch['destination'])) {
  437. $_GET['destination'] = $_batch['destination'];
  438. }
  439. // Determine the target path to redirect to.
  440. if (!isset($_batch['form_state']['redirect'])) {
  441. if (isset($_batch['redirect'])) {
  442. $_batch['form_state']['redirect'] = $_batch['redirect'];
  443. }
  444. else {
  445. $_batch['form_state']['redirect'] = $_batch['source_url'];
  446. }
  447. }
  448. // Use drupal_redirect_form() to handle the redirection logic.
  449. drupal_redirect_form($_batch['form_state']);
  450. // If no redirection happened, redirect to the originating page. In case the
  451. // form needs to be rebuilt, save the final $form_state for
  452. // drupal_build_form().
  453. if (!empty($_batch['form_state']['rebuild'])) {
  454. $_SESSION['batch_form_state'] = $_batch['form_state'];
  455. }
  456. $function = $_batch['redirect_callback'];
  457. if (function_exists($function)) {
  458. $function($_batch['source_url'], array('query' => array('op' => 'finish', 'id' => $_batch['id'])));
  459. }
  460. }
  461. }
  462. /**
  463. * Shutdown function; store the current batch data for the next request.
  464. */
  465. function _batch_shutdown() {
  466. if ($batch = batch_get()) {
  467. db_update('batch')
  468. ->fields(array('batch' => serialize($batch)))
  469. ->condition('bid', $batch['id'])
  470. ->execute();
  471. }
  472. }