batch.inc

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

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

File

drupal-6.x/includes/batch.inc
View source
  1. <?php
  2. /**
  3. * @file Batch processing API for processes to run in multiple HTTP requests.
  4. */
  5. /**
  6. * State-based dispatcher for the batch processing page.
  7. */
  8. function _batch_page() {
  9. $batch =& batch_get();
  10. // Retrieve the current state of batch from db.
  11. if (isset($_REQUEST['id']) && $data = db_result(db_query("SELECT batch FROM {batch} WHERE bid = %d AND token = '%s'", $_REQUEST['id'], drupal_get_token($_REQUEST['id'])))) {
  12. $batch = unserialize($data);
  13. }
  14. else {
  15. return FALSE;
  16. }
  17. // Register database update for end of processing.
  18. register_shutdown_function('_batch_shutdown');
  19. $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
  20. $output = NULL;
  21. switch ($op) {
  22. case 'start':
  23. $output = _batch_start();
  24. break;
  25. case 'do':
  26. // JS-version AJAX callback.
  27. _batch_do();
  28. break;
  29. case 'do_nojs':
  30. // Non-JS progress page.
  31. $output = _batch_progress_page_nojs();
  32. break;
  33. case 'finished':
  34. $output = _batch_finished();
  35. break;
  36. }
  37. return $output;
  38. }
  39. /**
  40. * Initiate the batch processing
  41. */
  42. function _batch_start() {
  43. // Choose between the JS and non-JS version.
  44. // JS-enabled users are identified through the 'has_js' cookie set in drupal.js.
  45. // If the user did not visit any JS enabled page during his browser session,
  46. // he gets the non-JS version...
  47. if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
  48. return _batch_progress_page_js();
  49. }
  50. else {
  51. return _batch_progress_page_nojs();
  52. }
  53. }
  54. /**
  55. * Batch processing page with JavaScript support.
  56. */
  57. function _batch_progress_page_js() {
  58. $batch = batch_get();
  59. // The first batch set gets to set the page title
  60. // and the initialization and error messages.
  61. $current_set = _batch_current_set();
  62. drupal_set_title($current_set['title']);
  63. drupal_add_js('misc/progress.js', 'core', 'header', FALSE, FALSE);
  64. $url = url($batch['url'], array('query' => array('id' => $batch['id'])));
  65. $js_setting = array(
  66. 'batch' => array(
  67. 'errorMessage' => $current_set['error_message'] .'<br/>'. $batch['error_message'],
  68. 'initMessage' => $current_set['init_message'],
  69. 'uri' => $url,
  70. ),
  71. );
  72. drupal_add_js($js_setting, 'setting');
  73. drupal_add_js('misc/batch.js', 'core', 'header', FALSE, FALSE);
  74. $output = '<div id="progress"></div>';
  75. return $output;
  76. }
  77. /**
  78. * Do one pass of execution and inform back the browser about progression
  79. * (used for JavaScript-mode only).
  80. */
  81. function _batch_do() {
  82. // HTTP POST required
  83. if ($_SERVER['REQUEST_METHOD'] != 'POST') {
  84. drupal_set_message(t('HTTP POST is required.'), 'error');
  85. drupal_set_title(t('Error'));
  86. return '';
  87. }
  88. // Perform actual processing.
  89. list($percentage, $message) = _batch_process();
  90. drupal_json(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
  91. }
  92. /**
  93. * Batch processing page without JavaScript support.
  94. */
  95. function _batch_progress_page_nojs() {
  96. $batch =& batch_get();
  97. $current_set = _batch_current_set();
  98. drupal_set_title($current_set['title']);
  99. $new_op = 'do_nojs';
  100. if (!isset($batch['running'])) {
  101. // This is the first page so we return some output immediately.
  102. $percentage = 0;
  103. $message = $current_set['init_message'];
  104. $batch['running'] = TRUE;
  105. }
  106. else {
  107. // This is one of the later requests: do some processing first.
  108. // Error handling: if PHP dies due to a fatal error (e.g. non-existant
  109. // function), it will output whatever is in the output buffer,
  110. // followed by the error message.
  111. ob_start();
  112. $fallback = $current_set['error_message'] .'<br/>'. $batch['error_message'];
  113. drupal_maintenance_theme();
  114. $fallback = theme('maintenance_page', $fallback, FALSE, FALSE);
  115. // We strip the end of the page using a marker in the template, so any
  116. // additional HTML output by PHP shows up inside the page rather than
  117. // below it. While this causes invalid HTML, the same would be true if
  118. // we didn't, as content is not allowed to appear after </html> anyway.
  119. list($fallback) = explode('<!--partial-->', $fallback);
  120. print $fallback;
  121. // Perform actual processing.
  122. list($percentage, $message) = _batch_process($batch);
  123. if ($percentage == 100) {
  124. $new_op = 'finished';
  125. }
  126. // PHP did not die : remove the fallback output.
  127. ob_end_clean();
  128. }
  129. $url = url($batch['url'], array('query' => array('id' => $batch['id'], 'op' => $new_op)));
  130. drupal_set_html_head('<meta http-equiv="Refresh" content="0; URL='. $url .'">');
  131. $output = theme('progress_bar', $percentage, $message);
  132. return $output;
  133. }
  134. /**
  135. * Advance batch processing for 1 second (or process the whole batch if it
  136. * was not set for progressive execution - e.g forms submitted by drupal_execute).
  137. */
  138. function _batch_process() {
  139. $batch =& batch_get();
  140. $current_set =& _batch_current_set();
  141. $set_changed = TRUE;
  142. if ($batch['progressive']) {
  143. timer_start('batch_processing');
  144. }
  145. while (!$current_set['success']) {
  146. // If this is the first time we iterate this batch set in the current
  147. // request, we check if it requires an additional file for functions
  148. // definitions.
  149. if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
  150. include_once($current_set['file']);
  151. }
  152. $finished = 1;
  153. $task_message = '';
  154. if ((list($function, $args) = reset($current_set['operations'])) && function_exists($function)) {
  155. // Build the 'context' array, execute the function call,
  156. // and retrieve the user message.
  157. $batch_context = array('sandbox' => &$current_set['sandbox'], 'results' => &$current_set['results'], 'finished' => &$finished, 'message' => &$task_message);
  158. // Process the current operation.
  159. call_user_func_array($function, array_merge($args, array(&$batch_context)));
  160. }
  161. if ($finished >= 1) {
  162. // Make sure this step isn't counted double when computing $current.
  163. $finished = 0;
  164. // Remove the operation and clear the sandbox.
  165. array_shift($current_set['operations']);
  166. $current_set['sandbox'] = array();
  167. }
  168. // If the batch set is completed, browse through the remaining sets,
  169. // executing 'control sets' (stored form submit handlers) along the way -
  170. // this might in turn insert new batch sets.
  171. // Stop when we find a set that actually has operations.
  172. $set_changed = FALSE;
  173. $old_set = $current_set;
  174. while (empty($current_set['operations']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
  175. $current_set =& _batch_current_set();
  176. $set_changed = TRUE;
  177. }
  178. // At this point, either $current_set is a 'real' batch set (has operations),
  179. // or all sets have been completed.
  180. // If we're in progressive mode, stop after 1 second.
  181. if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
  182. break;
  183. }
  184. }
  185. if ($batch['progressive']) {
  186. // Gather progress information.
  187. // Reporting 100% progress will cause the whole batch to be considered
  188. // processed. If processing was paused right after moving to a new set,
  189. // we have to use the info from the new (unprocessed) one.
  190. if ($set_changed && isset($current_set['operations'])) {
  191. // Processing will continue with a fresh batch set.
  192. $remaining = count($current_set['operations']);
  193. $total = $current_set['total'];
  194. $progress_message = $current_set['init_message'];
  195. $task_message = '';
  196. }
  197. else {
  198. $remaining = count($old_set['operations']);
  199. $total = $old_set['total'];
  200. $progress_message = $old_set['progress_message'];
  201. }
  202. $current = $total - $remaining + $finished;
  203. $percentage = $total ? floor($current / $total * 100) : 100;
  204. $values = array(
  205. '@remaining' => $remaining,
  206. '@total' => $total,
  207. '@current' => floor($current),
  208. '@percentage' => $percentage,
  209. );
  210. $message = strtr($progress_message, $values) .'<br/>';
  211. $message .= $task_message ? $task_message : '&nbsp;';
  212. return array($percentage, $message);
  213. }
  214. else {
  215. // If we're not in progressive mode, the whole batch has been processed by now.
  216. return _batch_finished();
  217. }
  218. }
  219. /**
  220. * Retrieve the batch set being currently processed.
  221. */
  222. function &_batch_current_set() {
  223. $batch =& batch_get();
  224. return $batch['sets'][$batch['current_set']];
  225. }
  226. /**
  227. * Move execution to the next batch set if any, executing the stored
  228. * form _submit handlers along the way (thus possibly inserting
  229. * additional batch sets).
  230. */
  231. function _batch_next_set() {
  232. $batch =& batch_get();
  233. if (isset($batch['sets'][$batch['current_set'] + 1])) {
  234. $batch['current_set']++;
  235. $current_set =& _batch_current_set();
  236. if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
  237. // We use our stored copies of $form and $form_state, to account for
  238. // possible alteration by the submit handlers.
  239. $function($batch['form'], $batch['form_state']);
  240. }
  241. return TRUE;
  242. }
  243. }
  244. /**
  245. * End the batch processing:
  246. * Call the 'finished' callbacks to allow custom handling of results,
  247. * and resolve page redirection.
  248. */
  249. function _batch_finished() {
  250. $batch =& batch_get();
  251. // Execute the 'finished' callbacks for each batch set.
  252. foreach ($batch['sets'] as $key => $batch_set) {
  253. if (isset($batch_set['finished'])) {
  254. // Check if the set requires an additional file for functions definitions.
  255. if (isset($batch_set['file']) && is_file($batch_set['file'])) {
  256. include_once($batch_set['file']);
  257. }
  258. if (function_exists($batch_set['finished'])) {
  259. $batch_set['finished']($batch_set['success'], $batch_set['results'], $batch_set['operations']);
  260. }
  261. }
  262. }
  263. // Cleanup the batch table and unset the global $batch variable.
  264. if ($batch['progressive']) {
  265. db_query("DELETE FROM {batch} WHERE bid = %d", $batch['id']);
  266. }
  267. $_batch = $batch;
  268. $batch = NULL;
  269. // Redirect if needed.
  270. if ($_batch['progressive']) {
  271. // Put back the 'destination' that was saved in batch_process().
  272. if (isset($_batch['destination'])) {
  273. $_REQUEST['destination'] = $_batch['destination'];
  274. }
  275. // Use $_batch['form_state']['redirect'], or $_batch['redirect'],
  276. // or $_batch['source_page'].
  277. if (isset($_batch['form_state']['redirect'])) {
  278. $redirect = $_batch['form_state']['redirect'];
  279. }
  280. elseif (isset($_batch['redirect'])) {
  281. $redirect = $_batch['redirect'];
  282. }
  283. else {
  284. $redirect = $_batch['source_page'];
  285. }
  286. // Let drupal_redirect_form handle redirection logic.
  287. $form = isset($batch['form']) ? $batch['form'] : array();
  288. if (empty($_batch['form_state']['rebuild']) && empty($_batch['form_state']['storage'])) {
  289. drupal_redirect_form($form, $redirect);
  290. }
  291. // We get here if $form['#redirect'] was FALSE, or if the form is a
  292. // multi-step form. We save the final $form_state value to be retrieved
  293. // by drupal_get_form, and we redirect to the originating page.
  294. $_SESSION['batch_form_state'] = $_batch['form_state'];
  295. drupal_goto($_batch['source_page']);
  296. }
  297. }
  298. /**
  299. * Shutdown function: store the batch data for next request,
  300. * or clear the table if the batch is finished.
  301. */
  302. function _batch_shutdown() {
  303. if ($batch = batch_get()) {
  304. db_query("UPDATE {batch} SET batch = '%s' WHERE bid = %d", serialize($batch), $batch['id']);
  305. }
  306. }