Skip navigation
Help

form.inc

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

Functions & methods

NameDescription
batch_getRetrieves the current batch.
batch_processProcesses the batch.
batch_setOpens a new batch.
date_validateValidates the date type to stop dates like February 30, 2006.
drupal_executeRetrieves, populates, and processes a form.
drupal_get_formRetrieves a form from a constructor function, or from the cache if the form was built in a previous page-load. The form is then passed on for processing, after and rendered for display if necessary.
drupal_prepare_formPrepares a structured form array by adding required elements, executing any hook_form_alter functions, and optionally inserting a validation token to prevent tampering.
drupal_process_formThis function is the heart of form API. The form gets built, validated and in appropriate cases, submitted.
drupal_rebuild_formRetrieves a form, caches it and processes it with an empty $_POST.
drupal_redirect_formRedirect the user to a URL after a form has been processed.
drupal_render_formRenders a structured form array into themed HTML.
drupal_retrieve_formRetrieves the structured array that defines a given form.
drupal_validate_formValidates user-submitted form data from the $form_state using the validate functions defined in a structured form array.
expand_checkboxes
expand_dateRoll out a single date element.
expand_password_confirmExpand a password_confirm field into two text boxes.
expand_radiosRoll out a single radios element to a list of radios, using the options array as index.
form_builderWalk through the structured form array, adding any required properties to each element and mapping the incoming $_POST data to the proper elements.
form_clean_idPrepare an HTML ID attribute string for a form item.
form_errorFlag an element as having an error.
form_execute_handlersA helper function used to execute custom validation and submission handlers for a given form. Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
form_expand_ahahAdd AHAH information about a form element to the page to communicate with javascript. If #ahah[path] is set on an element, this additional javascript is added to the page header to attach the AHAH behaviors. See ahah.js for more information.
form_get_cacheFetch a form from cache.
form_get_errorReturn the error message filed against the form with the specified name.
form_get_errorsReturn an associative array of all errors.
form_get_optionsTraverses a select element's #option array looking for any values that hold the given key. Returns an array of indexes that match.
form_options_flatten
form_select_options
form_set_cacheStore a form in the cache.
form_set_errorFile an error against a form element.
form_set_valueChange submitted form values during the form processing cycle.
form_type_checkboxes_valueHelper function to determine the value for a checkboxes form element.
form_type_checkbox_valueHelper function to determine the value for a checkbox form element.
form_type_image_button_valueHelper function to determine the value for an image button form element.
form_type_password_confirm_valueHelper function to determine the value for a password_confirm form element.
form_type_select_valueHelper function to determine the value for a select form element.
form_type_textfield_valueHelper function to determine the value for a textfield form element.
form_type_token_valueHelper function to determine the value for form's token value.
map_monthHelper function for usage with drupal_map_assoc to display month names.
password_confirm_validateValidate password_confirm element.
process_weightExpand weight elements into selects.
theme_buttonTheme a form button.
theme_checkboxFormat a checkbox.
theme_checkboxesFormat a set of checkboxes.
theme_dateFormat a date selection element.
theme_fieldsetFormat a group of form items.
theme_fileFormat a file upload field.
theme_formFormat a form.
theme_form_elementReturn a themed form element.
theme_hiddenFormat a hidden form field.
theme_image_buttonTheme a form image button.
theme_itemFormat a form item.
theme_markup
theme_passwordFormat a password field.
theme_password_confirmFormat a password_confirm item.
theme_radioFormat a radio button.
theme_radiosFormat a set of radio buttons.
theme_selectFormat a dropdown menu or scrolling selection box.
theme_submitTheme a form submit button.
theme_textareaFormat a textarea.
theme_textfieldFormat a textfield.
theme_tokenFormat a form token.
weight_valueIf no default value is set for weight select boxes, use 0.
_element_infoRetrieve the default properties for the defined element type.
_form_builder_handle_input_elementPopulate the #value and #name properties of input elements so they can be processed and rendered. Also, execute any #process handlers attached to a specific element.
_form_builder_ie_cleanupIn IE, if only one submit button is present, AND the enter key is used to submit the form, no form value is sent for it and our normal button detection code will never detect a match. We call this function after all other button-detection is complete…
_form_button_was_clickedHelper function to handle the sometimes-convoluted logic of button click detection.
_form_set_classSets a form element's class attribute.
_form_set_valueHelper function for form_set_value().
_form_validatePerforms validation on form elements. First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validators.

File

drupal/includes/form.inc
View source
  1. <?php
  2. /**
  3. * @defgroup forms Form builder functions
  4. * @{
  5. * Functions that build an abstract representation of a HTML form.
  6. *
  7. * All modules should declare their form builder functions to be in this
  8. * group and each builder function should reference its validate and submit
  9. * functions using \@see. Conversely, validate and submit functions should
  10. * reference the form builder function using \@see. For examples, of this see
  11. * system_modules_uninstall() or user_pass(), the latter of which has the
  12. * following in its doxygen documentation:
  13. *
  14. * \@ingroup forms
  15. * \@see user_pass_validate().
  16. * \@see user_pass_submit().
  17. *
  18. * @} End of "defgroup forms".
  19. */
  20. /**
  21. * @defgroup form_api Form generation
  22. * @{
  23. * Functions to enable the processing and display of HTML forms.
  24. *
  25. * Drupal uses these functions to achieve consistency in its form processing and
  26. * presentation, while simplifying code and reducing the amount of HTML that
  27. * must be explicitly generated by modules.
  28. *
  29. * The drupal_get_form() function handles retrieving, processing, and
  30. * displaying a rendered HTML form for modules automatically. For example:
  31. *
  32. * @code
  33. * // Display the user registration form.
  34. * $output = drupal_get_form('user_register');
  35. * @endcode
  36. *
  37. * Forms can also be built and submitted programmatically without any user input
  38. * using the drupal_execute() function.
  39. *
  40. * For information on the format of the structured arrays used to define forms,
  41. * and more detailed explanations of the Form API workflow, see the
  42. * @link http://api.drupal.org/api/file/developer/topics/forms_api_reference.html/6 reference @endlink
  43. * and the @link http://drupal.org/node/204270 Form API guide. @endlink
  44. */
  45. /**
  46. * Retrieves a form from a constructor function, or from the cache if
  47. * the form was built in a previous page-load. The form is then passed
  48. * on for processing, after and rendered for display if necessary.
  49. *
  50. * @param $form_id
  51. * The unique string identifying the desired form. If a function
  52. * with that name exists, it is called to build the form array.
  53. * Modules that need to generate the same form (or very similar forms)
  54. * using different $form_ids can implement hook_forms(), which maps
  55. * different $form_id values to the proper form constructor function. Examples
  56. * may be found in node_forms(), search_forms(), and user_forms().
  57. * @param ...
  58. * Any additional arguments are passed on to the functions called by
  59. * drupal_get_form(), including the unique form constructor function.
  60. * For example, the node_edit form requires that a node object be passed
  61. * in here when it is called. These are available to implementations of
  62. * hook_form_alter() and hook_form_FORM_ID_alter() as the array
  63. * $form['#parameters'].
  64. * @return
  65. * The rendered form.
  66. */
  67. function drupal_get_form($form_id) {
  68. $form_state = array('storage' => NULL, 'submitted' => FALSE);
  69. $args = func_get_args();
  70. $cacheable = FALSE;
  71. if (isset($_SESSION['batch_form_state'])) {
  72. // We've been redirected here after a batch processing : the form has
  73. // already been processed, so we grab the post-process $form_state value
  74. // and move on to form display. See _batch_finished() function.
  75. $form_state = $_SESSION['batch_form_state'];
  76. unset($_SESSION['batch_form_state']);
  77. }
  78. else {
  79. // If the incoming $_POST contains a form_build_id, we'll check the
  80. // cache for a copy of the form in question. If it's there, we don't
  81. // have to rebuild the form to proceed. In addition, if there is stored
  82. // form_state data from a previous step, we'll retrieve it so it can
  83. // be passed on to the form processing code.
  84. if (isset($_POST['form_id']) && $_POST['form_id'] == $form_id && !empty($_POST['form_build_id'])) {
  85. $form = form_get_cache($_POST['form_build_id'], $form_state);
  86. }
  87. // If the previous bit of code didn't result in a populated $form
  88. // object, we're hitting the form for the first time and we need
  89. // to build it from scratch.
  90. if (!isset($form)) {
  91. $form_state['post'] = $_POST;
  92. // Use a copy of the function's arguments for manipulation
  93. $args_temp = $args;
  94. $args_temp[0] = &$form_state;
  95. array_unshift($args_temp, $form_id);
  96. $form = call_user_func_array('drupal_retrieve_form', $args_temp);
  97. $form_build_id = 'form-'. md5(uniqid(mt_rand(), TRUE));
  98. $form['#build_id'] = $form_build_id;
  99. drupal_prepare_form($form_id, $form, $form_state);
  100. // Store a copy of the unprocessed form for caching and indicate that it
  101. // is cacheable if #cache will be set.
  102. $original_form = $form;
  103. $cacheable = TRUE;
  104. unset($form_state['post']);
  105. }
  106. $form['#post'] = $_POST;
  107. // Now that we know we have a form, we'll process it (validating,
  108. // submitting, and handling the results returned by its submission
  109. // handlers. Submit handlers accumulate data in the form_state by
  110. // altering the $form_state variable, which is passed into them by
  111. // reference.
  112. drupal_process_form($form_id, $form, $form_state);
  113. if ($cacheable && !empty($form['#cache'])) {
  114. // Caching is done past drupal_process_form so #process callbacks can
  115. // set #cache.
  116. form_set_cache($form_build_id, $original_form, $form_state);
  117. }
  118. }
  119. // Most simple, single-step forms will be finished by this point --
  120. // drupal_process_form() usually redirects to another page (or to
  121. // a 'fresh' copy of the form) once processing is complete. If one
  122. // of the form's handlers has set $form_state['redirect'] to FALSE,
  123. // the form will simply be re-rendered with the values still in its
  124. // fields.
  125. //
  126. // If $form_state['storage'] or $form_state['rebuild'] has been set
  127. // and input has been processed, we know that we're in a complex
  128. // multi-part process of some sort and the form's workflow is NOT
  129. // complete. We need to construct a fresh copy of the form, passing
  130. // in the latest $form_state in addition to any other variables passed
  131. // into drupal_get_form().
  132. if ((!empty($form_state['storage']) || !empty($form_state['rebuild'])) && !empty($form_state['process_input']) && !form_get_errors()) {
  133. $form = drupal_rebuild_form($form_id, $form_state, $args);
  134. }
  135. // If we haven't redirected to a new location by now, we want to
  136. // render whatever form array is currently in hand.
  137. return drupal_render_form($form_id, $form);
  138. }
  139. /**
  140. * Retrieves a form, caches it and processes it with an empty $_POST.
  141. *
  142. * This function clears $_POST and passes the empty $_POST to the form_builder.
  143. * To preserve some parts from $_POST, pass them in $form_state.
  144. *
  145. * If your AHAH callback simulates the pressing of a button, then your AHAH
  146. * callback will need to do the same as what drupal_get_form would do when the
  147. * button is pressed: get the form from the cache, run drupal_process_form over
  148. * it and then if it needs rebuild, run drupal_rebuild_form over it. Then send
  149. * back a part of the returned form.
  150. * $form_state['clicked_button']['#array_parents'] will help you to find which
  151. * part.
  152. *
  153. * @param $form_id
  154. * The unique string identifying the desired form. If a function
  155. * with that name exists, it is called to build the form array.
  156. * Modules that need to generate the same form (or very similar forms)
  157. * using different $form_ids can implement hook_forms(), which maps
  158. * different $form_id values to the proper form constructor function. Examples
  159. * may be found in node_forms(), search_forms(), and user_forms().
  160. * @param $form_state
  161. * A keyed array containing the current state of the form. Most
  162. * important is the $form_state['storage'] collection.
  163. * @param $args
  164. * Any additional arguments are passed on to the functions called by
  165. * drupal_get_form(), plus the original form_state in the beginning. If you
  166. * are getting a form from the cache, use $form['#parameters'] to shift off
  167. * the $form_id from its beginning then the resulting array can be used as
  168. * $arg here.
  169. * @param $form_build_id
  170. * If the AHAH callback calling this function only alters part of the form,
  171. * then pass in the existing form_build_id so we can re-cache with the same
  172. * csid.
  173. * @return
  174. * The newly built form.
  175. */
  176. function drupal_rebuild_form($form_id, &$form_state, $args, $form_build_id = NULL) {
  177. // Remove the first argument. This is $form_id.when called from
  178. // drupal_get_form and the original $form_state when called from some AHAH
  179. // callback. Neither is needed. After that, put in the current state.
  180. $args[0] = &$form_state;
  181. // And the form_id.
  182. array_unshift($args, $form_id);
  183. $form = call_user_func_array('drupal_retrieve_form', $args);
  184. if (!isset($form_build_id)) {
  185. // We need a new build_id for the new version of the form.
  186. $form_build_id = 'form-'. md5(uniqid(mt_rand(), TRUE));
  187. }
  188. $form['#build_id'] = $form_build_id;
  189. drupal_prepare_form($form_id, $form, $form_state);
  190. // Now, we cache the form structure so it can be retrieved later for
  191. // validation. If $form_state['storage'] is populated, we'll also cache
  192. // it so that it can be used to resume complex multi-step processes.
  193. form_set_cache($form_build_id, $form, $form_state);
  194. // Clear out all post data, as we don't want the previous step's
  195. // data to pollute this one and trigger validate/submit handling,
  196. // then process the form for rendering.
  197. $_POST = array();
  198. $form['#post'] = array();
  199. drupal_process_form($form_id, $form, $form_state);
  200. return $form;
  201. }
  202. /**
  203. * Store a form in the cache.
  204. */
  205. function form_set_cache($form_build_id, $form, $form_state) {
  206. global $user;
  207. // 6 hours cache life time for forms should be plenty.
  208. $expire = 21600;
  209. if ($user->uid) {
  210. $form['#cache_token'] = drupal_get_token();
  211. }
  212. cache_set('form_'. $form_build_id, $form, 'cache_form', time() + $expire);
  213. if (!empty($form_state['storage'])) {
  214. cache_set('storage_'. $form_build_id, $form_state['storage'], 'cache_form', time() + $expire);
  215. }
  216. }
  217. /**
  218. * Fetch a form from cache.
  219. */
  220. function form_get_cache($form_build_id, &$form_state) {
  221. global $user;
  222. if ($cached = cache_get('form_'. $form_build_id, 'cache_form')) {
  223. $form = $cached->data;
  224. if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
  225. if ($cached = cache_get('storage_'. $form_build_id, 'cache_form')) {
  226. $form_state['storage'] = $cached->data;
  227. }
  228. return $form;
  229. }
  230. }
  231. }
  232. /**
  233. * Retrieves, populates, and processes a form.
  234. *
  235. * This function allows you to supply values for form elements and submit a
  236. * form for processing. Compare to drupal_get_form(), which also builds and
  237. * processes a form, but does not allow you to supply values.
  238. *
  239. * There is no return value, but you can check to see if there are errors by
  240. * calling form_get_errors().
  241. *
  242. * @param $form_id
  243. * The unique string identifying the desired form. If a function
  244. * with that name exists, it is called to build the form array.
  245. * Modules that need to generate the same form (or very similar forms)
  246. * using different $form_ids can implement hook_forms(), which maps
  247. * different $form_id values to the proper form constructor function. Examples
  248. * may be found in node_forms(), search_forms(), and user_forms().
  249. * @param $form_state
  250. * A keyed array containing the current state of the form. Most
  251. * important is the $form_state['values'] collection, a tree of data
  252. * used to simulate the incoming $_POST information from a user's
  253. * form submission.
  254. * @param ...
  255. * Any additional arguments are passed on to the functions called by
  256. * drupal_execute(), including the unique form constructor function.
  257. * For example, the node_edit form requires that a node object be passed
  258. * in here when it is called.
  259. * For example:
  260. * @code
  261. * // register a new user
  262. * $form_state = array();
  263. * $form_state['values']['name'] = 'robo-user';
  264. * $form_state['values']['mail'] = 'robouser@example.com';
  265. * $form_state['values']['pass']['pass1'] = 'password';
  266. * $form_state['values']['pass']['pass2'] = 'password';
  267. * $form_state['values']['op'] = t('Create new account');
  268. * drupal_execute('user_register', $form_state);
  269. *
  270. * // Create a new node
  271. * $form_state = array();
  272. * module_load_include('inc', 'node', 'node.pages');
  273. * $node = array('type' => 'story');
  274. * $form_state['values']['title'] = 'My node';
  275. * $form_state['values']['body'] = 'This is the body text!';
  276. * $form_state['values']['name'] = 'robo-user';
  277. * $form_state['values']['op'] = t('Save');
  278. * drupal_execute('story_node_form', $form_state, (object)$node);
  279. * @endcode
  280. */
  281. function drupal_execute($form_id, &$form_state) {
  282. $args = func_get_args();
  283. // Make sure $form_state is passed around by reference.
  284. $args[1] = &$form_state;
  285. $form = call_user_func_array('drupal_retrieve_form', $args);
  286. $form['#post'] = $form_state['values'];
  287. drupal_prepare_form($form_id, $form, $form_state);
  288. drupal_process_form($form_id, $form, $form_state);
  289. }
  290. /**
  291. * Retrieves the structured array that defines a given form.
  292. *
  293. * @param $form_id
  294. * The unique string identifying the desired form. If a function
  295. * with that name exists, it is called to build the form array.
  296. * Modules that need to generate the same form (or very similar forms)
  297. * using different $form_ids can implement hook_forms(), which maps
  298. * different $form_id values to the proper form constructor function.
  299. * @param $form_state
  300. * A keyed array containing the current state of the form.
  301. * @param ...
  302. * Any additional arguments needed by the unique form constructor
  303. * function. Generally, these are any arguments passed into the
  304. * drupal_get_form() or drupal_execute() functions after the first
  305. * argument. If a module implements hook_forms(), it can examine
  306. * these additional arguments and conditionally return different
  307. * builder functions as well.
  308. */
  309. function drupal_retrieve_form($form_id, &$form_state) {
  310. static $forms;
  311. // We save two copies of the incoming arguments: one for modules to use
  312. // when mapping form ids to constructor functions, and another to pass to
  313. // the constructor function itself. We shift out the first argument -- the
  314. // $form_id itself -- from the list to pass into the constructor function,
  315. // since it's already known.
  316. $args = func_get_args();
  317. $saved_args = $args;
  318. array_shift($args);
  319. if (isset($form_state)) {
  320. array_shift($args);
  321. }
  322. // We first check to see if there's a function named after the $form_id.
  323. // If there is, we simply pass the arguments on to it to get the form.
  324. if (!function_exists($form_id)) {
  325. // In cases where many form_ids need to share a central constructor function,
  326. // such as the node editing form, modules can implement hook_forms(). It
  327. // maps one or more form_ids to the correct constructor functions.
  328. //
  329. // We cache the results of that hook to save time, but that only works
  330. // for modules that know all their form_ids in advance. (A module that
  331. // adds a small 'rate this comment' form to each comment in a list
  332. // would need a unique form_id for each one, for example.)
  333. //
  334. // So, we call the hook if $forms isn't yet populated, OR if it doesn't
  335. // yet have an entry for the requested form_id.
  336. if (!isset($forms) || !isset($forms[$form_id])) {
  337. $forms = module_invoke_all('forms', $form_id, $args);
  338. }
  339. $form_definition = $forms[$form_id];
  340. if (isset($form_definition['callback arguments'])) {
  341. $args = array_merge($form_definition['callback arguments'], $args);
  342. }
  343. if (isset($form_definition['callback'])) {
  344. $callback = $form_definition['callback'];
  345. }
  346. }
  347. array_unshift($args, NULL);
  348. $args[0] = &$form_state;
  349. // If $callback was returned by a hook_forms() implementation, call it.
  350. // Otherwise, call the function named after the form id.
  351. $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
  352. // We store the original function arguments, rather than the final $arg
  353. // value, so that form_alter functions can see what was originally
  354. // passed to drupal_retrieve_form(). This allows the contents of #parameters
  355. // to be saved and passed in at a later date to recreate the form.
  356. $form['#parameters'] = $saved_args;
  357. return $form;
  358. }
  359. /**
  360. * This function is the heart of form API. The form gets built, validated and in
  361. * appropriate cases, submitted.
  362. *
  363. * @param $form_id
  364. * The unique string identifying the current form.
  365. * @param $form
  366. * An associative array containing the structure of the form.
  367. * @param $form_state
  368. * A keyed array containing the current state of the form. This
  369. * includes the current persistent storage data for the form, and
  370. * any data passed along by earlier steps when displaying a
  371. * multi-step form. Additional information, like the sanitized $_POST
  372. * data, is also accumulated here.
  373. */
  374. function drupal_process_form($form_id, &$form, &$form_state) {
  375. $form_state['values'] = array();
  376. $form = form_builder($form_id, $form, $form_state);
  377. // Only process the form if it is programmed or the form_id coming
  378. // from the POST data is set and matches the current form_id.
  379. if ((!empty($form['#programmed'])) || (!empty($form['#post']) && (isset($form['#post']['form_id']) && ($form['#post']['form_id'] == $form_id)))) {
  380. $form_state['process_input'] = TRUE;
  381. drupal_validate_form($form_id, $form, $form_state);
  382. // form_clean_id() maintains a cache of element IDs it has seen,
  383. // so it can prevent duplicates. We want to be sure we reset that
  384. // cache when a form is processed, so scenerios that result in
  385. // the form being built behind the scenes and again for the
  386. // browser don't increment all the element IDs needlessly.
  387. form_clean_id(NULL, TRUE);
  388. if ((!empty($form_state['submitted'])) && !form_get_errors() && empty($form_state['rebuild'])) {
  389. $form_state['redirect'] = NULL;
  390. form_execute_handlers('submit', $form, $form_state);
  391. // We'll clear out the cached copies of the form and its stored data
  392. // here, as we've finished with them. The in-memory copies are still
  393. // here, though.
  394. if (variable_get('cache', CACHE_DISABLED) == CACHE_DISABLED && !empty($form_state['values']['form_build_id'])) {
  395. cache_clear_all('form_'. $form_state['values']['form_build_id'], 'cache_form');
  396. cache_clear_all('storage_'. $form_state['values']['form_build_id'], 'cache_form');
  397. }
  398. // If batches were set in the submit handlers, we process them now,
  399. // possibly ending execution. We make sure we do not react to the batch
  400. // that is already being processed (if a batch operation performs a
  401. // drupal_execute).
  402. if ($batch =& batch_get() && !isset($batch['current_set'])) {
  403. // The batch uses its own copies of $form and $form_state for
  404. // late execution of submit handers and post-batch redirection.
  405. $batch['form'] = $form;
  406. $batch['form_state'] = $form_state;
  407. $batch['progressive'] = !$form['#programmed'];
  408. batch_process();
  409. // Execution continues only for programmatic forms.
  410. // For 'regular' forms, we get redirected to the batch processing
  411. // page. Form redirection will be handled in _batch_finished(),
  412. // after the batch is processed.
  413. }
  414. // If no submit handlers have populated the $form_state['storage']
  415. // bundle, and the $form_state['rebuild'] flag has not been set,
  416. // we're finished and should redirect to a new destination page
  417. // if one has been set (and a fresh, unpopulated copy of the form
  418. // if one hasn't). If the form was called by drupal_execute(),
  419. // however, we'll skip this and let the calling function examine
  420. // the resulting $form_state bundle itself.
  421. if (!$form['#programmed'] && empty($form_state['rebuild']) && empty($form_state['storage'])) {
  422. drupal_redirect_form($form, $form_state['redirect']);
  423. }
  424. }
  425. }
  426. }
  427. /**
  428. * Prepares a structured form array by adding required elements,
  429. * executing any hook_form_alter functions, and optionally inserting
  430. * a validation token to prevent tampering.
  431. *
  432. * @param $form_id
  433. * A unique string identifying the form for validation, submission,
  434. * theming, and hook_form_alter functions.
  435. * @param $form
  436. * An associative array containing the structure of the form.
  437. * @param $form_state
  438. * A keyed array containing the current state of the form. Passed
  439. * in here so that hook_form_alter() calls can use it, as well.
  440. */
  441. function drupal_prepare_form($form_id, &$form, &$form_state) {
  442. global $user;
  443. $form['#type'] = 'form';
  444. $form['#programmed'] = isset($form['#post']);
  445. if (isset($form['#build_id'])) {
  446. $form['form_build_id'] = array(
  447. '#type' => 'hidden',
  448. '#value' => $form['#build_id'],
  449. '#id' => $form['#build_id'],
  450. '#name' => 'form_build_id',
  451. );
  452. }
  453. // Add a token, based on either #token or form_id, to any form displayed to
  454. // authenticated users. This ensures that any submitted form was actually
  455. // requested previously by the user and protects against cross site request
  456. // forgeries.
  457. if (isset($form['#token'])) {
  458. if ($form['#token'] === FALSE || $user->uid == 0 || $form['#programmed']) {
  459. unset($form['#token']);
  460. }
  461. else {
  462. $form['form_token'] = array('#type' => 'token', '#default_value' => drupal_get_token($form['#token']));
  463. }
  464. }
  465. else if (isset($user->uid) && $user->uid && !$form['#programmed']) {
  466. $form['#token'] = $form_id;
  467. $form['form_token'] = array(
  468. '#id' => form_clean_id('edit-'. $form_id .'-form-token'),
  469. '#type' => 'token',
  470. '#default_value' => drupal_get_token($form['#token']),
  471. );
  472. }
  473. if (isset($form_id)) {
  474. $form['form_id'] = array(
  475. '#type' => 'hidden',
  476. '#value' => $form_id,
  477. '#id' => form_clean_id("edit-$form_id"),
  478. );
  479. }
  480. if (!isset($form['#id'])) {
  481. $form['#id'] = form_clean_id($form_id);
  482. }
  483. $form += _element_info('form');
  484. if (!isset($form['#validate'])) {
  485. if (function_exists($form_id .'_validate')) {
  486. $form['#validate'] = array($form_id .'_validate');
  487. }
  488. }
  489. if (!isset($form['#submit'])) {
  490. if (function_exists($form_id .'_submit')) {
  491. // We set submit here so that it can be altered.
  492. $form['#submit'] = array($form_id .'_submit');
  493. }
  494. }
  495. // Normally, we would call drupal_alter($form_id, $form, $form_state).
  496. // However, drupal_alter() normally supports just one byref parameter. Using
  497. // the __drupal_alter_by_ref key, we can store any additional parameters
  498. // that need to be altered, and they'll be split out into additional params
  499. // for the hook_form_alter() implementations.
  500. // @todo: Remove this in Drupal 7.
  501. $data = &$form;
  502. $data['__drupal_alter_by_ref'] = array(&$form_state);
  503. drupal_alter('form_'. $form_id, $data);
  504. // __drupal_alter_by_ref is unset in the drupal_alter() function, we need
  505. // to repopulate it to ensure both calls get the data.
  506. $data['__drupal_alter_by_ref'] = array(&$form_state);
  507. drupal_alter('form', $data, $form_id);
  508. }
  509. /**
  510. * Validates user-submitted form data from the $form_state using
  511. * the validate functions defined in a structured form array.
  512. *
  513. * @param $form_id
  514. * A unique string identifying the form for validation, submission,
  515. * theming, and hook_form_alter functions.
  516. * @param $form
  517. * An associative array containing the structure of the form.
  518. * @param $form_state
  519. * A keyed array containing the current state of the form. The current
  520. * user-submitted data is stored in $form_state['values'], though
  521. * form validation functions are passed an explicit copy of the
  522. * values for the sake of simplicity. Validation handlers can also
  523. * $form_state to pass information on to submit handlers. For example:
  524. * $form_state['data_for_submision'] = $data;
  525. * This technique is useful when validation requires file parsing,
  526. * web service requests, or other expensive requests that should
  527. * not be repeated in the submission step.
  528. */
  529. function drupal_validate_form($form_id, $form, &$form_state) {
  530. static $validated_forms = array();
  531. if (isset($validated_forms[$form_id])) {
  532. return;
  533. }
  534. // If the session token was set by drupal_prepare_form(), ensure that it
  535. // matches the current user's session.
  536. if (isset($form['#token'])) {
  537. if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
  538. // Setting this error will cause the form to fail validation.
  539. form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
  540. }
  541. }
  542. _form_validate($form, $form_state, $form_id);
  543. $validated_forms[$form_id] = TRUE;
  544. }
  545. /**
  546. * Renders a structured form array into themed HTML.
  547. *
  548. * @param $form_id
  549. * A unique string identifying the form for validation, submission,
  550. * theming, and hook_form_alter functions.
  551. * @param $form
  552. * An associative array containing the structure of the form.
  553. * @return
  554. * A string containing the themed HTML.
  555. */
  556. function drupal_render_form($form_id, &$form) {
  557. // Don't override #theme if someone already set it.
  558. if (!isset($form['#theme'])) {
  559. init_theme();
  560. $registry = theme_get_registry();
  561. if (isset($registry[$form_id])) {
  562. $form['#theme'] = $form_id;
  563. }
  564. }
  565. $output = drupal_render($form);
  566. return $output;
  567. }
  568. /**
  569. * Redirect the user to a URL after a form has been processed.
  570. *
  571. * @param $form
  572. * An associative array containing the structure of the form.
  573. * @param $redirect
  574. * An optional value containing the destination path to redirect
  575. * to if none is specified by the form.
  576. */
  577. function drupal_redirect_form($form, $redirect = NULL) {
  578. $goto = NULL;
  579. if (isset($redirect)) {
  580. $goto = $redirect;
  581. }
  582. if ($goto !== FALSE && isset($form['#redirect'])) {
  583. $goto = $form['#redirect'];
  584. }
  585. if (!isset($goto) || ($goto !== FALSE)) {
  586. if (isset($goto)) {
  587. if (is_array($goto)) {
  588. call_user_func_array('drupal_goto', $goto);
  589. }
  590. else {
  591. drupal_goto($goto);
  592. }
  593. }
  594. drupal_goto($_GET['q']);
  595. }
  596. }
  597. /**
  598. * Performs validation on form elements. First ensures required fields are
  599. * completed, #maxlength is not exceeded, and selected options were in the
  600. * list of options given to the user. Then calls user-defined validators.
  601. *
  602. * @param $elements
  603. * An associative array containing the structure of the form.
  604. * @param $form_state
  605. * A keyed array containing the current state of the form. The current
  606. * user-submitted data is stored in $form_state['values'], though
  607. * form validation functions are passed an explicit copy of the
  608. * values for the sake of simplicity. Validation handlers can also
  609. * $form_state to pass information on to submit handlers. For example:
  610. * $form_state['data_for_submision'] = $data;
  611. * This technique is useful when validation requires file parsing,
  612. * web service requests, or other expensive requests that should
  613. * not be repeated in the submission step.
  614. * @param $form_id
  615. * A unique string identifying the form for validation, submission,
  616. * theming, and hook_form_alter functions.
  617. */
  618. function _form_validate($elements, &$form_state, $form_id = NULL) {
  619. static $complete_form;
  620. // Also used in the installer, pre-database setup.
  621. $t = get_t();
  622. // Recurse through all children.
  623. foreach (element_children($elements) as $key) {
  624. if (isset($elements[$key]) && $elements[$key]) {
  625. _form_validate($elements[$key], $form_state);
  626. }
  627. }
  628. // Validate the current input.
  629. if (!isset($elements['#validated']) || !$elements['#validated']) {
  630. if (isset($elements['#needs_validation'])) {
  631. // Make sure a value is passed when the field is required.
  632. // A simple call to empty() will not cut it here as some fields, like
  633. // checkboxes, can return a valid value of '0'. Instead, check the
  634. // length if it's a string, and the item count if it's an array.
  635. if ($elements['#required'] && (!count($elements['#value']) || (is_string($elements['#value']) && strlen(trim($elements['#value'])) == 0))) {
  636. form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
  637. }
  638. // Verify that the value is not longer than #maxlength.
  639. if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
  640. form_error($elements, $t('!name cannot be longer than %max characters but is currently %length characters long.', array('!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => drupal_strlen($elements['#value']))));
  641. }
  642. if (isset($elements['#options']) && isset($elements['#value'])) {
  643. if ($elements['#type'] == 'select') {
  644. $options = form_options_flatten($elements['#options']);
  645. }
  646. else {
  647. $options = $elements['#options'];
  648. }
  649. if (is_array($elements['#value'])) {
  650. $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
  651. foreach ($value as $v) {
  652. if (!isset($options[$v])) {
  653. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  654. watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  655. }
  656. }
  657. }
  658. elseif (!isset($options[$elements['#value']])) {
  659. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  660. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  661. }
  662. }
  663. }
  664. // Call user-defined form level validators and store a copy of the full
  665. // form so that element-specific validators can examine the entire structure
  666. // if necessary.
  667. if (isset($form_id)) {
  668. form_execute_handlers('validate', $elements, $form_state);
  669. $complete_form = $elements;
  670. }
  671. // Call any element-specific validators. These must act on the element
  672. // #value data.
  673. elseif (isset($elements['#element_validate'])) {
  674. foreach ($elements['#element_validate'] as $function) {
  675. if (function_exists($function)) {
  676. $function($elements, $form_state, $complete_form);
  677. }
  678. }
  679. }
  680. $elements['#validated'] = TRUE;
  681. }
  682. }
  683. /**
  684. * A helper function used to execute custom validation and submission
  685. * handlers for a given form. Button-specific handlers are checked
  686. * first. If none exist, the function falls back to form-level handlers.
  687. *
  688. * @param $type
  689. * The type of handler to execute. 'validate' or 'submit' are the
  690. * defaults used by Form API.
  691. * @param $form
  692. * An associative array containing the structure of the form.
  693. * @param $form_state
  694. * A keyed array containing the current state of the form. If the user
  695. * submitted the form by clicking a button with custom handler functions
  696. * defined, those handlers will be stored here.
  697. */
  698. function form_execute_handlers($type, &$form, &$form_state) {
  699. $return = FALSE;
  700. if (isset($form_state[$type .'_handlers'])) {
  701. $handlers = $form_state[$type .'_handlers'];
  702. }
  703. elseif (isset($form['#'. $type])) {
  704. $handlers = $form['#'. $type];
  705. }
  706. else {
  707. $handlers = array();
  708. }
  709. foreach ($handlers as $function) {
  710. if (function_exists($function)) {
  711. // Check to see if a previous _submit handler has set a batch, but
  712. // make sure we do not react to a batch that is already being processed
  713. // (for instance if a batch operation performs a drupal_execute()).
  714. if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['current_set'])) {
  715. // Some previous _submit handler has set a batch. We store the call
  716. // in a special 'control' batch set, for execution at the correct
  717. // time during the batch processing workflow.
  718. $batch['sets'][] = array('form_submit' => $function);
  719. }
  720. else {
  721. $function($form, $form_state);
  722. }
  723. $return = TRUE;
  724. }
  725. }
  726. return $return;
  727. }
  728. /**
  729. * File an error against a form element.
  730. *
  731. * @param $name
  732. * The name of the form element. If the #parents property of your form
  733. * element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
  734. * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
  735. * element where the #parents array starts with 'foo'.
  736. * @param $message
  737. * The error message to present to the user.
  738. * @param $reset
  739. * Reset the form errors static cache.
  740. * @return
  741. * Never use the return value of this function, use form_get_errors and
  742. * form_get_error instead.
  743. */
  744. function form_set_error($name = NULL, $message = '', $reset = FALSE) {
  745. static $form = array();
  746. if ($reset) {
  747. $form = array();
  748. }
  749. if (isset($name) && !isset($form[$name])) {
  750. $form[$name] = $message;
  751. if ($message) {
  752. drupal_set_message($message, 'error');
  753. }
  754. }
  755. return $form;
  756. }
  757. /**
  758. * Return an associative array of all errors.
  759. */
  760. function form_get_errors() {
  761. $form = form_set_error();
  762. if (!empty($form)) {
  763. return $form;
  764. }
  765. }
  766. /**
  767. * Return the error message filed against the form with the specified name.
  768. */
  769. function form_get_error($element) {
  770. $form = form_set_error();
  771. $key = $element['#parents'][0];
  772. if (isset($form[$key])) {
  773. return $form[$key];
  774. }
  775. $key = implode('][', $element['#parents']);
  776. if (isset($form[$key])) {
  777. return $form[$key];
  778. }
  779. }
  780. /**
  781. * Flag an element as having an error.
  782. */
  783. function form_error(&$element, $message = '') {
  784. form_set_error(implode('][', $element['#parents']), $message);
  785. }
  786. /**
  787. * Walk through the structured form array, adding any required
  788. * properties to each element and mapping the incoming $_POST
  789. * data to the proper elements.
  790. *
  791. * @param $form_id
  792. * A unique string identifying the form for validation, submission,
  793. * theming, and hook_form_alter functions.
  794. * @param $form
  795. * An associative array containing the structure of the form.
  796. * @param $form_state
  797. * A keyed array containing the current state of the form. In this
  798. * context, it is used to accumulate information about which button
  799. * was clicked when the form was submitted, as well as the sanitized
  800. * $_POST data.
  801. */
  802. function form_builder($form_id, $form, &$form_state) {
  803. static $complete_form, $cache;
  804. // Initialize as unprocessed.
  805. $form['#processed'] = FALSE;
  806. // Use element defaults.
  807. if ((!empty($form['#type'])) && ($info = _element_info($form['#type']))) {
  808. // Overlay $info onto $form, retaining preexisting keys in $form.
  809. $form += $info;
  810. }
  811. if (isset($form['#type']) && $form['#type'] == 'form') {
  812. $cache = NULL;
  813. $complete_form = $form;
  814. if (!empty($form['#programmed'])) {
  815. $form_state['submitted'] = TRUE;
  816. }
  817. }
  818. if (isset($form['#input']) && $form['#input']) {
  819. _form_builder_handle_input_element($form_id, $form, $form_state, $complete_form);
  820. }
  821. $form['#defaults_loaded'] = TRUE;
  822. // We start off assuming all form elements are in the correct order.
  823. $form['#sorted'] = TRUE;
  824. // Recurse through all child elements.
  825. $count = 0;
  826. foreach (element_children($form) as $key) {
  827. $form[$key]['#post'] = $form['#post'];
  828. $form[$key]['#programmed'] = $form['#programmed'];
  829. // Don't squash an existing tree value.
  830. if (!isset($form[$key]['#tree'])) {
  831. $form[$key]['#tree'] = $form['#tree'];
  832. }
  833. // Deny access to child elements if parent is denied.
  834. if (isset($form['#access']) && !$form['#access']) {
  835. $form[$key]['#access'] = FALSE;
  836. }
  837. // Don't squash existing parents value.
  838. if (!isset($form[$key]['#parents'])) {
  839. // Check to see if a tree of child elements is present. If so,
  840. // continue down the tree if required.
  841. $form[$key]['#parents'] = $form[$key]['#tree'] && $form['#tree'] ? array_merge($form['#parents'], array($key)) : array($key);
  842. $array_parents = isset($form['#array_parents']) ? $form['#array_parents'] : array();
  843. $array_parents[] = $key;
  844. $form[$key]['#array_parents'] = $array_parents;
  845. }
  846. // Assign a decimal placeholder weight to preserve original array order.
  847. if (!isset($form[$key]['#weight'])) {
  848. $form[$key]['#weight'] = $count/1000;
  849. }
  850. else {
  851. // If one of the child elements has a weight then we will need to sort
  852. // later.
  853. unset($form['#sorted']);
  854. }
  855. $form[$key] = form_builder($form_id, $form[$key], $form_state);
  856. $count++;
  857. }
  858. // The #after_build flag allows any piece of a form to be altered
  859. // after normal input parsing has been completed.
  860. if (isset($form['#after_build']) && !isset($form['#after_build_done'])) {
  861. foreach ($form['#after_build'] as $function) {
  862. $form = $function($form, $form_state);
  863. $form['#after_build_done'] = TRUE;
  864. }
  865. }
  866. // Now that we've processed everything, we can go back to handle the funky
  867. // Internet Explorer button-click scenario.
  868. _form_builder_ie_cleanup($form, $form_state);
  869. // We shoud keep the buttons array until the IE clean up function
  870. // has recognized the submit button so the form has been marked
  871. // as submitted. If we already know which button was submitted,
  872. // we don't need the array.
  873. if (!empty($form_state['submitted'])) {
  874. unset($form_state['buttons']);
  875. }
  876. // If some callback set #cache, we need to flip a static flag so later it
  877. // can be found.
  878. if (!empty($form['#cache'])) {
  879. $cache = $form['#cache'];
  880. }
  881. // We are on the top form, we can copy back #cache if it's set.
  882. if (isset($form['#type']) && $form['#type'] == 'form' && isset($cache)) {
  883. $form['#cache'] = TRUE;
  884. }
  885. return $form;
  886. }
  887. /**
  888. * Populate the #value and #name properties of input elements so they
  889. * can be processed and rendered. Also, execute any #process handlers
  890. * attached to a specific element.
  891. */
  892. function _form_builder_handle_input_element($form_id, &$form, &$form_state, $complete_form) {
  893. if (!isset($form['#name'])) {
  894. $name = array_shift($form['#parents']);
  895. $form['#name'] = $name;
  896. if ($form['#type'] == 'file') {
  897. // To make it easier to handle $_FILES in file.inc, we place all
  898. // file fields in the 'files' array. Also, we do not support
  899. // nested file names.
  900. $form['#name'] = 'files['. $form['#name'] .']';
  901. }
  902. elseif (count($form['#parents'])) {
  903. $form['#name'] .= '['. implode('][', $form['#parents']) .']';
  904. }
  905. array_unshift($form['#parents'], $name);
  906. }
  907. if (!isset($form['#id'])) {
  908. $form['#id'] = form_clean_id('edit-'. implode('-', $form['#parents']));
  909. }
  910. if (!empty($form['#disabled'])) {
  911. $form['#attributes']['disabled'] = 'disabled';
  912. }
  913. if (!isset($form['#value']) && !array_key_exists('#value', $form)) {
  914. $function = !empty($form['#value_callback']) ? $form['#value_callback'] : 'form_type_'. $form['#type'] .'_value';
  915. if (($form['#programmed']) || ((!isset($form['#access']) || $form['#access']) && isset($form['#post']) && (isset($form['#post']['form_id']) && $form['#post']['form_id'] == $form_id))) {
  916. $edit = $form['#post'];
  917. foreach ($form['#parents'] as $parent) {
  918. $edit = isset($edit[$parent]) ? $edit[$parent] : NULL;
  919. }
  920. if (!$form['#programmed'] || isset($edit)) {
  921. // Call #type_value to set the form value;
  922. if (function_exists($function)) {
  923. $form['#value'] = $function($form, $edit);
  924. }
  925. if (!isset($form['#value']) && isset($edit)) {
  926. $form['#value'] = $edit;
  927. }
  928. }
  929. // Mark all posted values for validation.
  930. if (isset($form['#value']) || (isset($form['#required']) && $form['#required'])) {
  931. $form['#needs_validation'] = TRUE;
  932. }
  933. }
  934. // Load defaults.
  935. if (!isset($form['#value'])) {
  936. // Call #type_value without a second argument to request default_value handling.
  937. if (function_exists($function)) {
  938. $form['#value'] = $function($form);
  939. }
  940. // Final catch. If we haven't set a value yet, use the explicit default value.
  941. // Avoid image buttons (which come with garbage value), so we only get value
  942. // for the button actually clicked.
  943. if (!isset($form['#value']) && empty($form['#has_garbage_value'])) {
  944. $form['#value'] = isset($form['#default_value']) ? $form['#default_value'] : '';
  945. }
  946. }
  947. }
  948. // Determine which button (if any) was clicked to submit the form.
  949. // We compare the incoming values with the buttons defined in the form,
  950. // and flag the one that matches. We have to do some funky tricks to
  951. // deal with Internet Explorer's handling of single-button forms, though.
  952. if (!empty($form['#post']) && isset($form['#executes_submit_callback'])) {
  953. // First, accumulate a collection of buttons, divided into two bins:
  954. // those that execute full submit callbacks and those that only validate.
  955. $button_type = $form['#executes_submit_callback'] ? 'submit' : 'button';
  956. $form_state['buttons'][$button_type][] = $form;
  957. if (_form_button_was_clicked($form)) {
  958. $form_state['submitted'] = $form_state['submitted'] || $form['#executes_submit_callback'];
  959. // In most cases, we want to use form_set_value() to manipulate
  960. // the global variables. In this special case, we want to make sure that
  961. // the value of this element is listed in $form_variables under 'op'.
  962. $form_state['values'][$form['#name']] = $form['#value'];
  963. $form_state['clicked_button'] = $form;
  964. if (isset($form['#validate'])) {
  965. $form_state['validate_handlers'] = $form['#validate'];
  966. }
  967. if (isset($form['#submit'])) {
  968. $form_state['submit_handlers'] = $form['#submit'];
  969. }
  970. }
  971. }
  972. // Allow for elements to expand to multiple elements, e.g., radios,
  973. // checkboxes and files.
  974. if (isset($form['#process']) && !$form['#processed']) {
  975. foreach ($form['#process'] as $process) {
  976. if (function_exists($process)) {
  977. $form = $process($form, isset($edit) ? $edit : NULL, $form_state, $complete_form);
  978. }
  979. }
  980. $form['#processed'] = TRUE;
  981. }
  982. form_set_value($form, $form['#value'], $form_state);
  983. }
  984. /**
  985. * Helper function to handle the sometimes-convoluted logic of button
  986. * click detection.
  987. *
  988. * In Internet Explorer, if ONLY one submit button is present, AND the
  989. * enter key is used to submit the form, no form value is sent for it
  990. * and we'll never detect a match. That special case is handled by
  991. * _form_builder_ie_cleanup().
  992. */
  993. function _form_button_was_clicked($form) {
  994. // First detect normal 'vanilla' button clicks. Traditionally, all
  995. // standard buttons on a form share the same name (usually 'op'),
  996. // and the specific return value is used to determine which was
  997. // clicked. This ONLY works as long as $form['#name'] puts the
  998. // value at the top level of the tree of $_POST data.
  999. if (isset($form['#post'][$form['#name']]) && $form['#post'][$form['#name']] == $form['#value']) {
  1000. return TRUE;
  1001. }
  1002. // When image buttons are clicked, browsers do NOT pass the form element
  1003. // value in $_POST. Instead they pass an integer representing the
  1004. // coordinates of the click on the button image. This means that image
  1005. // buttons MUST have unique $form['#name'] values, but the details of
  1006. // their $_POST data should be ignored.
  1007. elseif (!empty($form['#has_garbage_value']) && isset($form['#value']) && $form['#value'] !== '') {
  1008. return TRUE;
  1009. }
  1010. return FALSE;
  1011. }
  1012. /**
  1013. * In IE, if only one submit button is present, AND the enter key is
  1014. * used to submit the form, no form value is sent for it and our normal
  1015. * button detection code will never detect a match. We call this
  1016. * function after all other button-detection is complete to check
  1017. * for the proper conditions, and treat the single button on the form
  1018. * as 'clicked' if they are met.
  1019. */
  1020. function _form_builder_ie_cleanup($form, &$form_state) {
  1021. // Quick check to make sure we're always looking at the full form
  1022. // and not a sub-element.
  1023. if (!empty($form['#type']) && $form['#type'] == 'form') {
  1024. // If we haven't recognized a submission yet, and there's a single
  1025. // submit button, we know that we've hit the right conditions. Grab
  1026. // the first one and treat it as the clicked button.
  1027. if (empty($form_state['submitted']) && !empty($form_state['buttons']['submit']) && empty($form_state['buttons']['button'])) {
  1028. $button = $form_state['buttons']['submit'][0];
  1029. // Set up all the $form_state information that would have been
  1030. // populated had the button been recognized earlier.
  1031. $form_state['submitted'] = TRUE;
  1032. $form_state['submit_handlers'] = empty($button['#submit']) ? NULL : $button['#submit'];
  1033. $form_state['validate_handlers'] = empty($button['#validate']) ? NULL : $button['#validate'];
  1034. $form_state['values'][$button['#name']] = $button['#value'];
  1035. $form_state['clicked_button'] = $button;
  1036. }
  1037. }
  1038. }
  1039. /**
  1040. * Helper function to determine the value for an image button form element.
  1041. *
  1042. * @param $form
  1043. * The form element whose value is being populated.
  1044. * @param $edit
  1045. * The incoming POST data to populate the form element. If this is FALSE,
  1046. * the element's default value should be returned.
  1047. * @return
  1048. * The data that will appear in the $form_state['values'] collection
  1049. * for this element. Return nothing to use the default.
  1050. */
  1051. function form_type_image_button_value($form, $edit = FALSE) {
  1052. if ($edit !== FALSE) {
  1053. if (!empty($edit)) {
  1054. // If we're dealing with Mozilla or Opera, we're lucky. It will
  1055. // return a proper value, and we can get on with things.
  1056. return $form['#return_value'];
  1057. }
  1058. else {
  1059. // Unfortunately, in IE we never get back a proper value for THIS
  1060. // form element. Instead, we get back two split values: one for the
  1061. // X and one for the Y coordinates on which the user clicked the
  1062. // button. We'll find this element in the #post data, and search
  1063. // in the same spot for its name, with '_x'.
  1064. $post = $form['#post'];
  1065. foreach (split('\[', $form['#name']) as $element_name) {
  1066. // chop off the ] that may exist.
  1067. if (substr($element_name, -1) == ']') {
  1068. $element_name = substr($element_name, 0, -1);
  1069. }
  1070. if (!isset($post[$element_name])) {
  1071. if (isset($post[$element_name .'_x'])) {
  1072. return $form['#return_value'];
  1073. }
  1074. return NULL;
  1075. }
  1076. $post = $post[$element_name];
  1077. }
  1078. return $form['#return_value'];
  1079. }
  1080. }
  1081. }
  1082. /**
  1083. * Helper function to determine the value for a checkbox form element.
  1084. *
  1085. * @param $form
  1086. * The form element whose value is being populated.
  1087. * @param $edit
  1088. * The incoming POST data to populate the form element. If this is FALSE,
  1089. * the element's default value should be returned.
  1090. * @return
  1091. * The data that will appear in the $form_state['values'] collection
  1092. * for this element. Return nothing to use the default.
  1093. */
  1094. function form_type_checkbox_value($form, $edit = FALSE) {
  1095. if ($edit !== FALSE) {
  1096. if (empty($form['#disabled'])) {
  1097. return !empty($edit) ? $form['#return_value'] : 0;
  1098. }
  1099. else {
  1100. return $form['#default_value'];
  1101. }
  1102. }
  1103. }
  1104. /**
  1105. * Helper function to determine the value for a checkboxes form element.
  1106. *
  1107. * @param $form
  1108. * The form element whose value is being populated.
  1109. * @param $edit
  1110. * The incoming POST data to populate the form element. If this is FALSE,
  1111. * the element's default value should be returned.
  1112. * @return
  1113. * The data that will appear in the $form_state['values'] collection
  1114. * for this element. Return nothing to use the default.
  1115. */
  1116. function form_type_checkboxes_value($form, $edit = FALSE) {
  1117. if ($edit === FALSE) {
  1118. $value = array();
  1119. $form += array('#default_value' => array());
  1120. foreach ($form['#default_value'] as $key) {
  1121. $value[$key] = 1;
  1122. }
  1123. return $value;
  1124. }
  1125. elseif (!isset($edit)) {
  1126. return array();
  1127. }
  1128. }
  1129. /**
  1130. * Helper function to determine the value for a password_confirm form
  1131. * element.
  1132. *
  1133. * @param $form
  1134. * The form element whose value is being populated.
  1135. * @param $edit
  1136. * The incoming POST data to populate the form element. If this is FALSE,
  1137. * the element's default value should be returned.
  1138. * @return
  1139. * The data that will appear in the $form_state['values'] collection
  1140. * for this element. Return nothing to use the default.
  1141. */
  1142. function form_type_password_confirm_value($form, $edit = FALSE) {
  1143. if ($edit === FALSE) {
  1144. $form += array('#default_value' => array());
  1145. return $form['#default_value'] + array('pass1' => '', 'pass2' => '');
  1146. }
  1147. }
  1148. /**
  1149. * Helper function to determine the value for a select form element.
  1150. *
  1151. * @param $form
  1152. * The form element whose value is being populated.
  1153. * @param $edit
  1154. * The incoming POST data to populate the form element. If this is FALSE,
  1155. * the element's default value should be returned.
  1156. * @return
  1157. * The data that will appear in the $form_state['values'] collection
  1158. * for this element. Return nothing to use the default.
  1159. */
  1160. function form_type_select_value($form, $edit = FALSE) {
  1161. if ($edit !== FALSE) {
  1162. if (isset($form['#multiple']) && $form['#multiple']) {
  1163. return (is_array($edit)) ? drupal_map_assoc($edit) : array();
  1164. }
  1165. else {
  1166. return $edit;
  1167. }
  1168. }
  1169. }
  1170. /**
  1171. * Helper function to determine the value for a textfield form element.
  1172. *
  1173. * @param $form
  1174. * The form element whose value is being populated.
  1175. * @param $edit
  1176. * The incoming POST data to populate the form element. If this is FALSE,
  1177. * the element's default value should be returned.
  1178. * @return
  1179. * The data that will appear in the $form_state['values'] collection
  1180. * for this element. Return nothing to use the default.
  1181. */
  1182. function form_type_textfield_value($form, $edit = FALSE) {
  1183. if ($edit !== FALSE) {
  1184. // Equate $edit to the form value to ensure it's marked for
  1185. // validation.
  1186. return str_replace(array("\r", "\n"), '', $edit);
  1187. }
  1188. }
  1189. /**
  1190. * Helper function to determine the value for form's token value.
  1191. *
  1192. * @param $form
  1193. * The form element whose value is being populated.
  1194. * @param $edit
  1195. * The incoming POST data to populate the form element. If this is FALSE,
  1196. * the element's default value should be returned.
  1197. * @return
  1198. * The data that will appear in the $form_state['values'] collection
  1199. * for this element. Return nothing to use the default.
  1200. */
  1201. function form_type_token_value($form, $edit = FALSE) {
  1202. if ($edit !== FALSE) {
  1203. return (string)$edit;
  1204. }
  1205. }
  1206. /**
  1207. * Change submitted form values during the form processing cycle.
  1208. *
  1209. * Use this function to change the submitted value of a form item in the
  1210. * validation phase so that it persists in $form_state through to the
  1211. * submission handlers in the submission phase.
  1212. *
  1213. * Since $form_state['values'] can either be a flat array of values, or a tree
  1214. * of nested values, some care must be taken when using this function.
  1215. * Specifically, $form_item['#parents'] is an array that describes the branch of
  1216. * the tree whose value should be updated. For example, if we wanted to update
  1217. * $form_state['values']['one']['two'] to 'new value', we'd pass in
  1218. * $form_item['#parents'] = array('one', 'two') and $value = 'new value'.
  1219. *
  1220. * @param $form_item
  1221. * The form item that should have its value updated. Keys used: #parents,
  1222. * #value. In most cases you can just pass in the right element from the $form
  1223. * array.
  1224. * @param $value
  1225. * The new value for the form item.
  1226. * @param $form_state
  1227. * The array where the value change should be recorded.
  1228. */
  1229. function form_set_value($form_item, $value, &$form_state) {
  1230. _form_set_value($form_state['values'], $form_item, $form_item['#parents'], $value);
  1231. }
  1232. /**
  1233. * Helper function for form_set_value().
  1234. *
  1235. * We iterate over $parents and create nested arrays for them
  1236. * in $form_state['values'] if needed. Then we insert the value into
  1237. * the right array.
  1238. */
  1239. function _form_set_value(&$form_values, $form_item, $parents, $value) {
  1240. $parent = array_shift($parents);
  1241. if (empty($parents)) {
  1242. $form_values[$parent] = $value;
  1243. }
  1244. else {
  1245. if (!isset($form_values[$parent])) {
  1246. $form_values[$parent] = array();
  1247. }
  1248. _form_set_value($form_values[$parent], $form_item, $parents, $value);
  1249. }
  1250. }
  1251. /**
  1252. * Retrieve the default properties for the defined element type.
  1253. */
  1254. function _element_info($type, $refresh = NULL) {
  1255. static $cache;
  1256. $basic_defaults = array(
  1257. '#description' => NULL,
  1258. '#attributes' => array(),
  1259. '#required' => FALSE,
  1260. '#tree' => FALSE,
  1261. '#parents' => array()
  1262. );
  1263. if (!isset($cache) || $refresh) {
  1264. $cache = array();
  1265. foreach (module_implements('elements') as $module) {
  1266. $elements = module_invoke($module, 'elements');
  1267. if (isset($elements) && is_array($elements)) {
  1268. $cache = array_merge_recursive($cache, $elements);
  1269. }
  1270. }
  1271. if (sizeof($cache)) {
  1272. foreach ($cache as $element_type => $info) {
  1273. $cache[$element_type] = array_merge_recursive($basic_defaults, $info);
  1274. }
  1275. }
  1276. }
  1277. return $cache[$type];
  1278. }
  1279. function form_options_flatten($array, $reset = TRUE) {
  1280. static $return;
  1281. if ($reset) {
  1282. $return = array();
  1283. }
  1284. foreach ($array as $key => $value) {
  1285. if (is_object($value)) {
  1286. form_options_flatten($value->option, FALSE);
  1287. }
  1288. else if (is_array($value)) {
  1289. form_options_flatten($value, FALSE);
  1290. }
  1291. else {
  1292. $return[$key] = 1;
  1293. }
  1294. }
  1295. return $return;
  1296. }
  1297. /**
  1298. * Format a dropdown menu or scrolling selection box.
  1299. *
  1300. * @param $element
  1301. * An associative array containing the properties of the element.
  1302. * Properties used: title, value, options, description, extra, multiple, required
  1303. * @return
  1304. * A themed HTML string representing the form element.
  1305. *
  1306. * @ingroup themeable
  1307. *
  1308. * It is possible to group options together; to do this, change the format of
  1309. * $options to an associative array in which the keys are group labels, and the
  1310. * values are associative arrays in the normal $options format.
  1311. */
  1312. function theme_select($element) {
  1313. $select = '';
  1314. $size = $element['#size'] ? ' size="'. $element['#size'] .'"' : '';
  1315. _form_set_class($element, array('form-select'));
  1316. $multiple = $element['#multiple'];
  1317. return theme('form_element', $element, '<select name="'. $element['#name'] .''. ($multiple ? '[]' : '') .'"'. ($multiple ? ' multiple="multiple" ' : '') . drupal_attributes($element['#attributes']) .' id="'. $element['#id'] .'" '. $size .'>'. form_select_options($element) .'</select>');
  1318. }
  1319. function form_select_options($element, $choices = NULL) {
  1320. if (!isset($choices)) {
  1321. $choices = $element['#options'];
  1322. }
  1323. // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  1324. // isset() fails in this situation.
  1325. $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  1326. $value_is_array = is_array($element['#value']);
  1327. $options = '';
  1328. foreach ($choices as $key => $choice) {
  1329. if (is_array($choice)) {
  1330. $options .= '<optgroup label="'. $key .'">';
  1331. $options .= form_select_options($element, $choice);
  1332. $options .= '</optgroup>';
  1333. }
  1334. elseif (is_object($choice)) {
  1335. $options .= form_select_options($element, $choice->option);
  1336. }
  1337. else {
  1338. $key = (string)$key;
  1339. if ($value_valid && (!$value_is_array && (string)$element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
  1340. $selected = ' selected="selected"';
  1341. }
  1342. else {
  1343. $selected = '';
  1344. }
  1345. $options .= '<option value="'. check_plain($key) .'"'. $selected .'>'. check_plain($choice) .'</option>';
  1346. }
  1347. }
  1348. return $options;
  1349. }
  1350. /**
  1351. * Traverses a select element's #option array looking for any values
  1352. * that hold the given key. Returns an array of indexes that match.
  1353. *
  1354. * This function is useful if you need to modify the options that are
  1355. * already in a form element; for example, to remove choices which are
  1356. * not valid because of additional filters imposed by another module.
  1357. * One example might be altering the choices in a taxonomy selector.
  1358. * To correctly handle the case of a multiple hierarchy taxonomy,
  1359. * #options arrays can now hold an array of objects, instead of a
  1360. * direct mapping of keys to labels, so that multiple choices in the
  1361. * selector can have the same key (and label). This makes it difficult
  1362. * to manipulate directly, which is why this helper function exists.
  1363. *
  1364. * This function does not support optgroups (when the elements of the
  1365. * #options array are themselves arrays), and will return FALSE if
  1366. * arrays are found. The caller must either flatten/restore or
  1367. * manually do their manipulations in this case, since returning the
  1368. * index is not sufficient, and supporting this would make the
  1369. * "helper" too complicated and cumbersome to be of any help.
  1370. *
  1371. * As usual with functions that can return array() or FALSE, do not
  1372. * forget to use === and !== if needed.
  1373. *
  1374. * @param $element
  1375. * The select element to search.
  1376. * @param $key
  1377. * The key to look for.
  1378. * @return
  1379. * An array of indexes that match the given $key. Array will be
  1380. * empty if no elements were found. FALSE if optgroups were found.
  1381. */
  1382. function form_get_options($element, $key) {
  1383. $keys = array();
  1384. foreach ($element['#options'] as $index => $choice) {
  1385. if (is_array($choice)) {
  1386. return FALSE;
  1387. }
  1388. else if (is_object($choice)) {
  1389. if (isset($choice->option[$key])) {
  1390. $keys[] = $index;
  1391. }
  1392. }
  1393. else if ($index == $key) {
  1394. $keys[] = $index;
  1395. }
  1396. }
  1397. return $keys;
  1398. }
  1399. /**
  1400. * Format a group of form items.
  1401. *
  1402. * @param $element
  1403. * An associative array containing the properties of the element.
  1404. * Properties used: attributes, title, value, description, children, collapsible, collapsed
  1405. * @return
  1406. * A themed HTML string representing the form item group.
  1407. *
  1408. * @ingroup themeable
  1409. */
  1410. function theme_fieldset($element) {
  1411. if (!empty($element['#collapsible'])) {
  1412. drupal_add_js('misc/collapse.js');
  1413. if (!isset($element['#attributes']['class'])) {
  1414. $element['#attributes']['class'] = '';
  1415. }
  1416. $element['#attributes']['class'] .= ' collapsible';
  1417. if (!empty($element['#collapsed'])) {
  1418. $element['#attributes']['class'] .= ' collapsed';
  1419. }
  1420. }
  1421. return '<fieldset'. drupal_attributes($element['#attributes']) .'>'. ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') . (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . (!empty($element['#children']) ? $element['#children'] : '') . (isset($element['#value']) ? $element['#value'] : '') ."</fieldset>\n";
  1422. }
  1423. /**
  1424. * Format a radio button.
  1425. *
  1426. * @param $element
  1427. * An associative array containing the properties of the element.
  1428. * Properties used: required, return_value, value, attributes, title, description
  1429. * @return
  1430. * A themed HTML string representing the form item group.
  1431. *
  1432. * @ingroup themeable
  1433. */
  1434. function theme_radio($element) {
  1435. _form_set_class($element, array('form-radio'));
  1436. $output = '<input type="radio" ';
  1437. $output .= 'id="'. $element['#id'] .'" ';
  1438. $output .= 'name="'. $element['#name'] .'" ';
  1439. $output .= 'value="'. $element['#return_value'] .'" ';
  1440. $output .= (check_plain($element['#value']) == $element['#return_value']) ? ' checked="checked" ' : ' ';
  1441. $output .= drupal_attributes($element['#attributes']) .' />';
  1442. if (!is_null($element['#title'])) {
  1443. $output = '<label class="option" for="'. $element['#id'] .'">'. $output .' '. $element['#title'] .'</label>';
  1444. }
  1445. unset($element['#title']);
  1446. return theme('form_element', $element, $output);
  1447. }
  1448. /**
  1449. * Format a set of radio buttons.
  1450. *
  1451. * @param $element
  1452. * An associative array containing the properties of the element.
  1453. * Properties used: title, value, options, description, required and attributes.
  1454. * @return
  1455. * A themed HTML string representing the radio button set.
  1456. *
  1457. * @ingroup themeable
  1458. */
  1459. function theme_radios($element) {
  1460. $class = 'form-radios';
  1461. if (isset($element['#attributes']['class'])) {
  1462. $class .= ' '. $element['#attributes']['class'];
  1463. }
  1464. $element['#children'] = '<div class="'. $class .'">'. (!empty($element['#children']) ? $element['#children'] : '') .'</div>';
  1465. if ($element['#title'] || $element['#description']) {
  1466. unset($element['#id']);
  1467. return theme('form_element', $element, $element['#children']);
  1468. }
  1469. else {
  1470. return $element['#children'];
  1471. }
  1472. }
  1473. /**
  1474. * Format a password_confirm item.
  1475. *
  1476. * @param $element
  1477. * An associative array containing the properties of the element.
  1478. * Properties used: title, value, id, required, error.
  1479. * @return
  1480. * A themed HTML string representing the form item.
  1481. *
  1482. * @ingroup themeable
  1483. */
  1484. function theme_password_confirm($element) {
  1485. return theme('form_element', $element, $element['#children']);
  1486. }
  1487. /**
  1488. * Expand a password_confirm field into two text boxes.
  1489. */
  1490. function expand_password_confirm($element) {
  1491. $element['pass1'] = array(
  1492. '#type' => 'password',
  1493. '#title' => t('Password'),
  1494. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
  1495. '#required' => $element['#required'],
  1496. '#attributes' => array('class' => 'password-field'),
  1497. );
  1498. $element['pass2'] = array(
  1499. '#type' => 'password',
  1500. '#title' => t('Confirm password'),
  1501. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
  1502. '#required' => $element['#required'],
  1503. '#attributes' => array('class' => 'password-confirm'),
  1504. );
  1505. $element['#element_validate'] = array('password_confirm_validate');
  1506. $element['#tree'] = TRUE;
  1507. if (isset($element['#size'])) {
  1508. $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  1509. }
  1510. return $element;
  1511. }
  1512. /**
  1513. * Validate password_confirm element.
  1514. */
  1515. function password_confirm_validate($form, &$form_state) {
  1516. $pass1 = trim($form['pass1']['#value']);
  1517. if (!empty($pass1)) {
  1518. $pass2 = trim($form['pass2']['#value']);
  1519. if (strcmp($pass1, $pass2)) {
  1520. form_error($form, t('The specified passwords do not match.'));
  1521. }
  1522. }
  1523. elseif ($form['#required'] && !empty($form['#post'])) {
  1524. form_error($form, t('Password field is required.'));
  1525. }
  1526. // Password field must be converted from a two-element array into a single
  1527. // string regardless of validation results.
  1528. form_set_value($form['pass1'], NULL, $form_state);
  1529. form_set_value($form['pass2'], NULL, $form_state);
  1530. form_set_value($form, $pass1, $form_state);
  1531. return $form;
  1532. }
  1533. /**
  1534. * Format a date selection element.
  1535. *
  1536. * @param $element
  1537. * An associative array containing the properties of the element.
  1538. * Properties used: title, value, options, description, required and attributes.
  1539. * @return
  1540. * A themed HTML string representing the date selection boxes.
  1541. *
  1542. * @ingroup themeable
  1543. */
  1544. function theme_date($element) {
  1545. return theme('form_element', $element, '<div class="container-inline">'. $element['#children'] .'</div>');
  1546. }
  1547. /**
  1548. * Roll out a single date element.
  1549. */
  1550. function expand_date($element) {
  1551. // Default to current date
  1552. if (empty($element['#value'])) {
  1553. $element['#value'] = array('day' => format_date(time(), 'custom', 'j'),
  1554. 'month' => format_date(time(), 'custom', 'n'),
  1555. 'year' => format_date(time(), 'custom', 'Y'));
  1556. }
  1557. $element['#tree'] = TRUE;
  1558. // Determine the order of day, month, year in the site's chosen date format.
  1559. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  1560. $sort = array();
  1561. $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
  1562. $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
  1563. $sort['year'] = strpos($format, 'Y');
  1564. asort($sort);
  1565. $order = array_keys($sort);
  1566. // Output multi-selector for date.
  1567. foreach ($order as $type) {
  1568. switch ($type) {
  1569. case 'day':
  1570. $options = drupal_map_assoc(range(1, 31));
  1571. break;
  1572. case 'month':
  1573. $options = drupal_map_assoc(range(1, 12), 'map_month');
  1574. break;
  1575. case 'year':
  1576. $options = drupal_map_assoc(range(1900, 2050));
  1577. break;
  1578. }
  1579. $parents = $element['#parents'];
  1580. $parents[] = $type;
  1581. $element[$type] = array(
  1582. '#type' => 'select',
  1583. '#value' => $element['#value'][$type],
  1584. '#attributes' => $element['#attributes'],
  1585. '#options' => $options,
  1586. );
  1587. }
  1588. return $element;
  1589. }
  1590. /**
  1591. * Validates the date type to stop dates like February 30, 2006.
  1592. */
  1593. function date_validate($element) {
  1594. if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
  1595. form_error($element, t('The specified date is invalid.'));
  1596. }
  1597. }
  1598. /**
  1599. * Helper function for usage with drupal_map_assoc to display month names.
  1600. */
  1601. function map_month($month) {
  1602. return format_date(gmmktime(0, 0, 0, $month, 2, 1970), 'custom', 'M', 0);
  1603. }
  1604. /**
  1605. * If no default value is set for weight select boxes, use 0.
  1606. */
  1607. function weight_value(&$form) {
  1608. if (isset($form['#default_value'])) {
  1609. $form['#value'] = $form['#default_value'];
  1610. }
  1611. else {
  1612. $form['#value'] = 0;
  1613. }
  1614. }
  1615. /**
  1616. * Roll out a single radios element to a list of radios,
  1617. * using the options array as index.
  1618. */
  1619. function expand_radios($element) {
  1620. if (count($element['#options']) > 0) {
  1621. foreach ($element['#options'] as $key => $choice) {
  1622. if (!isset($element[$key])) {
  1623. // Generate the parents as the autogenerator does, so we will have a
  1624. // unique id for each radio button.
  1625. $parents_for_id = array_merge($element['#parents'], array($key));
  1626. $element[$key] = array(
  1627. '#type' => 'radio',
  1628. '#title' => $choice,
  1629. '#return_value' => check_plain($key),
  1630. '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : NULL,
  1631. '#attributes' => $element['#attributes'],
  1632. '#parents' => $element['#parents'],
  1633. '#id' => form_clean_id('edit-'. implode('-', $parents_for_id)),
  1634. '#ahah' => isset($element['#ahah']) ? $element['#ahah'] : NULL,
  1635. );
  1636. }
  1637. }
  1638. }
  1639. return $element;
  1640. }
  1641. /**
  1642. * Add AHAH information about a form element to the page to communicate with
  1643. * javascript. If #ahah[path] is set on an element, this additional javascript is
  1644. * added to the page header to attach the AHAH behaviors. See ahah.js for more
  1645. * information.
  1646. *
  1647. * @param $element
  1648. * An associative array containing the properties of the element.
  1649. * Properties used: ahah_event, ahah_path, ahah_wrapper, ahah_parameters,
  1650. * ahah_effect.
  1651. * @return
  1652. * None. Additional code is added to the header of the page using
  1653. * drupal_add_js.
  1654. */
  1655. function form_expand_ahah($element) {
  1656. static $js_added = array();
  1657. // Add a reasonable default event handler if none specified.
  1658. if (isset($element['#ahah']['path']) && !isset($element['#ahah']['event'])) {
  1659. switch ($element['#type']) {
  1660. case 'submit':
  1661. case 'button':
  1662. case 'image_button':
  1663. // Use the mousedown instead of the click event because form
  1664. // submission via pressing the enter key triggers a click event on
  1665. // submit inputs, inappropriately triggering AHAH behaviors.
  1666. $element['#ahah']['event'] = 'mousedown';
  1667. // Attach an additional event handler so that AHAH behaviours
  1668. // can be triggered still via keyboard input.
  1669. $element['#ahah']['keypress'] = TRUE;
  1670. break;
  1671. case 'password':
  1672. case 'textfield':
  1673. case 'textarea':
  1674. $element['#ahah']['event'] = 'blur';
  1675. break;
  1676. case 'radio':
  1677. case 'checkbox':
  1678. case 'select':
  1679. $element['#ahah']['event'] = 'change';
  1680. break;
  1681. }
  1682. }
  1683. // Adding the same javascript settings twice will cause a recursion error,
  1684. // we avoid the problem by checking if the javascript has already been added.
  1685. if (isset($element['#ahah']['path']) && isset($element['#ahah']['event']) && !isset($js_added[$element['#id']])) {
  1686. drupal_add_js('misc/jquery.form.js');
  1687. drupal_add_js('misc/ahah.js');
  1688. $ahah_binding = array(
  1689. 'url' => url($element['#ahah']['path']),
  1690. 'event' => $element['#ahah']['event'],
  1691. 'keypress' => empty($element['#ahah']['keypress']) ? NULL : $element['#ahah']['keypress'],
  1692. 'wrapper' => empty($element['#ahah']['wrapper']) ? NULL : $element['#ahah']['wrapper'],
  1693. 'selector' => empty($element['#ahah']['selector']) ? '#'. $element['#id'] : $element['#ahah']['selector'],
  1694. 'effect' => empty($element['#ahah']['effect']) ? 'none' : $element['#ahah']['effect'],
  1695. 'method' => empty($element['#ahah']['method']) ? 'replace' : $element['#ahah']['method'],
  1696. 'progress' => empty($element['#ahah']['progress']) ? array('type' => 'throbber') : $element['#ahah']['progress'],
  1697. 'button' => isset($element['#executes_submit_callback']) ? array($element['#name'] => $element['#value']) : FALSE,
  1698. );
  1699. // Convert a simple #ahah[progress] type string into an array.
  1700. if (is_string($ahah_binding['progress'])) {
  1701. $ahah_binding['progress'] = array('type' => $ahah_binding['progress']);
  1702. }
  1703. // Change progress path to a full url.
  1704. if (isset($ahah_binding['progress']['path'])) {
  1705. $ahah_binding['progress']['url'] = url($ahah_binding['progress']['path']);
  1706. }
  1707. // Add progress.js if we're doing a bar display.
  1708. if ($ahah_binding['progress']['type'] == 'bar') {
  1709. drupal_add_js('misc/progress.js');
  1710. }
  1711. drupal_add_js(array('ahah' => array($element['#id'] => $ahah_binding)), 'setting');
  1712. $js_added[$element['#id']] = TRUE;
  1713. $element['#cache'] = TRUE;
  1714. }
  1715. return $element;
  1716. }
  1717. /**
  1718. * Format a form item.
  1719. *
  1720. * @param $element
  1721. * An associative array containing the properties of the element.
  1722. * Properties used: title, value, description, required, error
  1723. * @return
  1724. * A themed HTML string representing the form item.
  1725. *
  1726. * @ingroup themeable
  1727. */
  1728. function theme_item($element) {
  1729. return theme('form_element', $element, $element['#value'] . (!empty($element['#children']) ? $element['#children'] : ''));
  1730. }
  1731. /**
  1732. * Format a checkbox.
  1733. *
  1734. * @param $element
  1735. * An associative array containing the properties of the element.
  1736. * Properties used: title, value, return_value, description, required
  1737. * @return
  1738. * A themed HTML string representing the checkbox.
  1739. *
  1740. * @ingroup themeable
  1741. */
  1742. function theme_checkbox($element) {
  1743. _form_set_class($element, array('form-checkbox'));
  1744. $checkbox = '<input ';
  1745. $checkbox .= 'type="checkbox" ';
  1746. $checkbox .= 'name="'. $element['#name'] .'" ';
  1747. $checkbox .= 'id="'. $element['#id'] .'" ' ;
  1748. $checkbox .= 'value="'. $element['#return_value'] .'" ';
  1749. $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
  1750. $checkbox .= drupal_attributes($element['#attributes']) .' />';
  1751. if (!is_null($element['#title'])) {
  1752. $checkbox = '<label class="option" for="'. $element['#id'] .'">'. $checkbox .' '. $element['#title'] .'</label>';
  1753. }
  1754. unset($element['#title']);
  1755. return theme('form_element', $element, $checkbox);
  1756. }
  1757. /**
  1758. * Format a set of checkboxes.
  1759. *
  1760. * @param $element
  1761. * An associative array containing the properties of the element.
  1762. * @return
  1763. * A themed HTML string representing the checkbox set.
  1764. *
  1765. * @ingroup themeable
  1766. */
  1767. function theme_checkboxes($element) {
  1768. $class = 'form-checkboxes';
  1769. if (isset($element['#attributes']['class'])) {
  1770. $class .= ' '. $element['#attributes']['class'];
  1771. }
  1772. $element['#children'] = '<div class="'. $class .'">'. (!empty($element['#children']) ? $element['#children'] : '') .'</div>';
  1773. if ($element['#title'] || $element['#description']) {
  1774. unset($element['#id']);
  1775. return theme('form_element', $element, $element['#children']);
  1776. }
  1777. else {
  1778. return $element['#children'];
  1779. }
  1780. }
  1781. function expand_checkboxes($element) {
  1782. $value = is_array($element['#value']) ? $element['#value'] : array();
  1783. $element['#tree'] = TRUE;
  1784. if (count($element['#options']) > 0) {
  1785. if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
  1786. $element['#default_value'] = array();
  1787. }
  1788. foreach ($element['#options'] as $key => $choice) {
  1789. if (!isset($element[$key])) {
  1790. $element[$key] = array(
  1791. '#type' => 'checkbox',
  1792. '#processed' => TRUE,
  1793. '#title' => $choice,
  1794. '#return_value' => $key,
  1795. '#default_value' => isset($value[$key]),
  1796. '#attributes' => $element['#attributes'],
  1797. '#ahah' => isset($element['#ahah']) ? $element['#ahah'] : NULL,
  1798. );
  1799. }
  1800. }
  1801. }
  1802. return $element;
  1803. }
  1804. /**
  1805. * Theme a form submit button.
  1806. *
  1807. * @ingroup themeable
  1808. */
  1809. function theme_submit($element) {
  1810. return theme('button', $element);
  1811. }
  1812. /**
  1813. * Theme a form button.
  1814. *
  1815. * @ingroup themeable
  1816. */
  1817. function theme_button($element) {
  1818. // Make sure not to overwrite classes.
  1819. if (isset($element['#attributes']['class'])) {
  1820. $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
  1821. }
  1822. else {
  1823. $element['#attributes']['class'] = 'form-'. $element['#button_type'];
  1824. }
  1825. return '<input type="submit" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ') .'id="'. $element['#id'] .'" value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
  1826. }
  1827. /**
  1828. * Theme a form image button.
  1829. *
  1830. * @ingroup themeable
  1831. */
  1832. function theme_image_button($element) {
  1833. // Make sure not to overwrite classes.
  1834. if (isset($element['#attributes']['class'])) {
  1835. $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
  1836. }
  1837. else {
  1838. $element['#attributes']['class'] = 'form-'. $element['#button_type'];
  1839. }
  1840. return '<input type="image" name="'. $element['#name'] .'" '.
  1841. (!empty($element['#value']) ? ('value="'. check_plain($element['#value']) .'" ') : '') .
  1842. 'id="'. $element['#id'] .'" '.
  1843. drupal_attributes($element['#attributes']) .
  1844. ' src="'. base_path() . $element['#src'] .'" '.
  1845. (!empty($element['#title']) ? 'alt="'. check_plain($element['#title']) .'" title="'. check_plain($element['#title']) .'" ' : '' ) .
  1846. "/>\n";
  1847. }
  1848. /**
  1849. * Format a hidden form field.
  1850. *
  1851. * @param $element
  1852. * An associative array containing the properties of the element.
  1853. * Properties used: value, edit
  1854. * @return
  1855. * A themed HTML string representing the hidden form field.
  1856. *
  1857. * @ingroup themeable
  1858. */
  1859. function theme_hidden($element) {
  1860. return '<input type="hidden" name="'. $element['#name'] .'" id="'. $element['#id'] .'" value="'. check_plain($element['#value']) ."\" ". drupal_attributes($element['#attributes']) ." />\n";
  1861. }
  1862. /**
  1863. * Format a form token.
  1864. *
  1865. * @ingroup themeable
  1866. */
  1867. function theme_token($element) {
  1868. return theme('hidden', $element);
  1869. }
  1870. /**
  1871. * Format a textfield.
  1872. *
  1873. * @param $element
  1874. * An associative array containing the properties of the element.
  1875. * Properties used: title, value, description, size, maxlength, required, attributes autocomplete_path
  1876. * @return
  1877. * A themed HTML string representing the textfield.
  1878. *
  1879. * @ingroup themeable
  1880. */
  1881. function theme_textfield($element) {
  1882. $size = empty($element['#size']) ? '' : ' size="'. $element['#size'] .'"';
  1883. $maxlength = empty($element['#maxlength']) ? '' : ' maxlength="'. $element['#maxlength'] .'"';
  1884. $class = array('form-text');
  1885. $extra = '';
  1886. $output = '';
  1887. if ($element['#autocomplete_path'] && menu_valid_path(array('link_path' => $element['#autocomplete_path']))) {
  1888. drupal_add_js('misc/autocomplete.js');
  1889. $class[] = 'form-autocomplete';
  1890. $extra = '<input class="autocomplete" type="hidden" id="'. $element['#id'] .'-autocomplete" value="'. check_url(url($element['#autocomplete_path'], array('absolute' => TRUE))) .'" disabled="disabled" />';
  1891. }
  1892. _form_set_class($element, $class);
  1893. if (isset($element['#field_prefix'])) {
  1894. $output .= '<span class="field-prefix">'. $element['#field_prefix'] .'</span> ';
  1895. }
  1896. $output .= '<input type="text"'. $maxlength .' name="'. $element['#name'] .'" id="'. $element['#id'] .'"'. $size .' value="'. check_plain($element['#value']) .'"'. drupal_attributes($element['#attributes']) .' />';
  1897. if (isset($element['#field_suffix'])) {
  1898. $output .= ' <span class="field-suffix">'. $element['#field_suffix'] .'</span>';
  1899. }
  1900. return theme('form_element', $element, $output) . $extra;
  1901. }
  1902. /**
  1903. * Format a form.
  1904. *
  1905. * @param $element
  1906. * An associative array containing the properties of the element.
  1907. * Properties used: action, method, attributes, children
  1908. * @return
  1909. * A themed HTML string representing the form.
  1910. *
  1911. * @ingroup themeable
  1912. */
  1913. function theme_form($element) {
  1914. // Anonymous div to satisfy XHTML compliance.
  1915. $action = $element['#action'] ? 'action="'. check_url($element['#action']) .'" ' : '';
  1916. return '<form '. $action .' accept-charset="UTF-8" method="'. $element['#method'] .'" id="'. $element['#id'] .'"'. drupal_attributes($element['#attributes']) .">\n<div>". $element['#children'] ."\n</div></form>\n";
  1917. }
  1918. /**
  1919. * Format a textarea.
  1920. *
  1921. * @param $element
  1922. * An associative array containing the properties of the element.
  1923. * Properties used: title, value, description, rows, cols, required, attributes
  1924. * @return
  1925. * A themed HTML string representing the textarea.
  1926. *
  1927. * @ingroup themeable
  1928. */
  1929. function theme_textarea($element) {
  1930. $class = array('form-textarea');
  1931. // Add teaser behavior (must come before resizable)
  1932. if (!empty($element['#teaser'])) {
  1933. drupal_add_js('misc/teaser.js');
  1934. // Note: arrays are merged in drupal_get_js().
  1935. drupal_add_js(array('teaserCheckbox' => array($element['#id'] => $element['#teaser_checkbox'])), 'setting');
  1936. drupal_add_js(array('teaser' => array($element['#id'] => $element['#teaser'])), 'setting');
  1937. $class[] = 'teaser';
  1938. }
  1939. // Add resizable behavior
  1940. if ($element['#resizable'] !== FALSE) {
  1941. drupal_add_js('misc/textarea.js');
  1942. $class[] = 'resizable';
  1943. }
  1944. _form_set_class($element, $class);
  1945. return theme('form_element', $element, '<textarea cols="'. $element['#cols'] .'" rows="'. $element['#rows'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. drupal_attributes($element['#attributes']) .'>'. check_plain($element['#value']) .'</textarea>');
  1946. }
  1947. /**
  1948. * Format HTML markup for use in forms.
  1949. *
  1950. * This is used in more advanced forms, such as theme selection and filter format.
  1951. *
  1952. * @param $element
  1953. * An associative array containing the properties of the element.
  1954. * Properties used: value, children.
  1955. * @return
  1956. * A themed HTML string representing the HTML markup.
  1957. *
  1958. * @ingroup themeable
  1959. */
  1960. function theme_markup($element) {
  1961. return (isset($element['#value']) ? $element['#value'] : '') . (isset($element['#children']) ? $element['#children'] : '');
  1962. }
  1963. /**
  1964. * Format a password field.
  1965. *
  1966. * @param $element
  1967. * An associative array containing the properties of the element.
  1968. * Properties used: title, value, description, size, maxlength, required, attributes
  1969. * @return
  1970. * A themed HTML string representing the form.
  1971. *
  1972. * @ingroup themeable
  1973. */
  1974. function theme_password($element) {
  1975. $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : '';
  1976. $maxlength = $element['#maxlength'] ? ' maxlength="'. $element['#maxlength'] .'" ' : '';
  1977. _form_set_class($element, array('form-text'));
  1978. $output = '<input type="password" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $maxlength . $size . drupal_attributes($element['#attributes']) .' />';
  1979. return theme('form_element', $element, $output);
  1980. }
  1981. /**
  1982. * Expand weight elements into selects.
  1983. */
  1984. function process_weight($element) {
  1985. for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
  1986. $weights[$n] = $n;
  1987. }
  1988. $element['#options'] = $weights;
  1989. $element['#type'] = 'select';
  1990. $element['#is_weight'] = TRUE;
  1991. $element += _element_info('select');
  1992. return $element;
  1993. }
  1994. /**
  1995. * Format a file upload field.
  1996. *
  1997. * @param $title
  1998. * The label for the file upload field.
  1999. * @param $name
  2000. * The internal name used to refer to the field.
  2001. * @param $size
  2002. * A measure of the visible size of the field (passed directly to HTML).
  2003. * @param $description
  2004. * Explanatory text to display after the form item.
  2005. * @param $required
  2006. * Whether the user must upload a file to the field.
  2007. * @return
  2008. * A themed HTML string representing the field.
  2009. *
  2010. * @ingroup themeable
  2011. *
  2012. * For assistance with handling the uploaded file correctly, see the API
  2013. * provided by file.inc.
  2014. */
  2015. function theme_file($element) {
  2016. _form_set_class($element, array('form-file'));
  2017. return theme('form_element', $element, '<input type="file" name="'. $element['#name'] .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '') .' id="'. $element['#id'] .'" size="'. $element['#size'] ."\" />\n");
  2018. }
  2019. /**
  2020. * Return a themed form element.
  2021. *
  2022. * @param element
  2023. * An associative array containing the properties of the element.
  2024. * Properties used: title, description, id, required
  2025. * @param $value
  2026. * The form element's data.
  2027. * @return
  2028. * A string representing the form element.
  2029. *
  2030. * @ingroup themeable
  2031. */
  2032. function theme_form_element($element, $value) {
  2033. // This is also used in the installer, pre-database setup.
  2034. $t = get_t();
  2035. $output = '<div class="form-item"';
  2036. if (!empty($element['#id'])) {
  2037. $output .= ' id="'. $element['#id'] .'-wrapper"';
  2038. }
  2039. $output .= ">\n";
  2040. $required = !empty($element['#required']) ? '<span class="form-required" title="'. $t('This field is required.') .'">*</span>' : '';
  2041. if (!empty($element['#title'])) {
  2042. $title = $element['#title'];
  2043. if (!empty($element['#id'])) {
  2044. $output .= ' <label for="'. $element['#id'] .'">'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
  2045. }
  2046. else {
  2047. $output .= ' <label>'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
  2048. }
  2049. }
  2050. $output .= " $value\n";
  2051. if (!empty($element['#description'])) {
  2052. $output .= ' <div class="description">'. $element['#description'] ."</div>\n";
  2053. }
  2054. $output .= "</div>\n";
  2055. return $output;
  2056. }
  2057. /**
  2058. * Sets a form element's class attribute.
  2059. *
  2060. * Adds 'required' and 'error' classes as needed.
  2061. *
  2062. * @param &$element
  2063. * The form element.
  2064. * @param $name
  2065. * Array of new class names to be added.
  2066. */
  2067. function _form_set_class(&$element, $class = array()) {
  2068. if ($element['#required']) {
  2069. $class[] = 'required';
  2070. }
  2071. if (form_get_error($element)) {
  2072. $class[] = 'error';
  2073. }
  2074. if (isset($element['#attributes']['class'])) {
  2075. $class[] = $element['#attributes']['class'];
  2076. }
  2077. $element['#attributes']['class'] = implode(' ', $class);
  2078. }
  2079. /**
  2080. * Prepare an HTML ID attribute string for a form item.
  2081. *
  2082. * Remove invalid characters and guarantee uniqueness.
  2083. *
  2084. * @param $id
  2085. * The ID to clean.
  2086. * @param $flush
  2087. * If set to TRUE, the function will flush and reset the static array
  2088. * which is built to test the uniqueness of element IDs. This is only
  2089. * used if a form has completed the validation process. This parameter
  2090. * should never be set to TRUE if this function is being called to
  2091. * assign an ID to the #ID element.
  2092. * @return
  2093. * The cleaned ID.
  2094. */
  2095. function form_clean_id($id = NULL, $flush = FALSE) {
  2096. static $seen_ids = array();
  2097. if ($flush) {
  2098. $seen_ids = array();
  2099. return;
  2100. }
  2101. $id = str_replace(array('][', '_', ' '), '-', $id);
  2102. // Ensure IDs are unique. The first occurrence is held but left alone.
  2103. // Subsequent occurrences get a number appended to them. This incrementing
  2104. // will almost certainly break code that relies on explicit HTML IDs in
  2105. // forms that appear more than once on the page, but the alternative is
  2106. // outputting duplicate IDs, which would break JS code and XHTML
  2107. // validity anyways. For now, it's an acceptable stopgap solution.
  2108. if (isset($seen_ids[$id])) {
  2109. $id = $id .'-'. $seen_ids[$id]++;
  2110. }
  2111. else {
  2112. $seen_ids[$id] = 1;
  2113. }
  2114. return $id;
  2115. }
  2116. /**
  2117. * @} End of "defgroup form_api".
  2118. */
  2119. /**
  2120. * @defgroup batch Batch operations
  2121. * @{
  2122. * Functions allowing forms processing to be spread out over several page
  2123. * requests, thus ensuring that the processing does not get interrupted
  2124. * because of a PHP timeout, while allowing the user to receive feedback
  2125. * on the progress of the ongoing operations.
  2126. *
  2127. * The API is primarily designed to integrate nicely with the Form API
  2128. * workflow, but can also be used by non-FAPI scripts (like update.php)
  2129. * or even simple page callbacks (which should probably be used sparingly).
  2130. *
  2131. * Example:
  2132. * @code
  2133. * $batch = array(
  2134. * 'title' => t('Exporting'),
  2135. * 'operations' => array(
  2136. * array('my_function_1', array($account->uid, 'story')),
  2137. * array('my_function_2', array()),
  2138. * ),
  2139. * 'finished' => 'my_finished_callback',
  2140. * 'file' => 'path_to_file_containing_myfunctions',
  2141. * );
  2142. * batch_set($batch);
  2143. * // only needed if not inside a form _submit handler :
  2144. * batch_process();
  2145. * @endcode
  2146. *
  2147. * Note: if the batch 'title', 'init_message', 'progress_message', or
  2148. * 'error_message' could contain any user input, it is the responsibility of
  2149. * the code calling batch_set() to sanitize them first with a function like
  2150. * check_plain() or filter_xss().
  2151. *
  2152. * Sample batch operations:
  2153. * @code
  2154. * // Simple and artificial: load a node of a given type for a given user
  2155. * function my_function_1($uid, $type, &$context) {
  2156. * // The $context array gathers batch context information about the execution (read),
  2157. * // as well as 'return values' for the current operation (write)
  2158. * // The following keys are provided :
  2159. * // 'results' (read / write): The array of results gathered so far by
  2160. * // the batch processing, for the current operation to append its own.
  2161. * // 'message' (write): A text message displayed in the progress page.
  2162. * // The following keys allow for multi-step operations :
  2163. * // 'sandbox' (read / write): An array that can be freely used to
  2164. * // store persistent data between iterations. It is recommended to
  2165. * // use this instead of $_SESSION, which is unsafe if the user
  2166. * // continues browsing in a separate window while the batch is processing.
  2167. * // 'finished' (write): A float number between 0 and 1 informing
  2168. * // the processing engine of the completion level for the operation.
  2169. * // 1 (or no value explicitly set) means the operation is finished
  2170. * // and the batch processing can continue to the next operation.
  2171. *
  2172. * $node = node_load(array('uid' => $uid, 'type' => $type));
  2173. * $context['results'][] = $node->nid .' : '. $node->title;
  2174. * $context['message'] = $node->title;
  2175. * }
  2176. *
  2177. * // More advanced example: multi-step operation - load all nodes, five by five
  2178. * function my_function_2(&$context) {
  2179. * if (empty($context['sandbox'])) {
  2180. * $context['sandbox']['progress'] = 0;
  2181. * $context['sandbox']['current_node'] = 0;
  2182. * $context['sandbox']['max'] = db_result(db_query('SELECT COUNT(DISTINCT nid) FROM {node}'));
  2183. * }
  2184. * $limit = 5;
  2185. * $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit);
  2186. * while ($row = db_fetch_array($result)) {
  2187. * $node = node_load($row['nid'], NULL, TRUE);
  2188. * $context['results'][] = $node->nid .' : '. $node->title;
  2189. * $context['sandbox']['progress']++;
  2190. * $context['sandbox']['current_node'] = $node->nid;
  2191. * $context['message'] = $node->title;
  2192. * }
  2193. * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  2194. * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  2195. * }
  2196. * }
  2197. * @endcode
  2198. *
  2199. * Sample 'finished' callback:
  2200. * @code
  2201. * function batch_test_finished($success, $results, $operations) {
  2202. * if ($success) {
  2203. * $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  2204. * }
  2205. * else {
  2206. * $message = t('Finished with an error.');
  2207. * }
  2208. * drupal_set_message($message);
  2209. * // Providing data for the redirected page is done through $_SESSION.
  2210. * foreach ($results as $result) {
  2211. * $items[] = t('Loaded node %title.', array('%title' => $result));
  2212. * }
  2213. * $_SESSION['my_batch_results'] = $items;
  2214. * }
  2215. * @endcode
  2216. */
  2217. /**
  2218. * Opens a new batch.
  2219. *
  2220. * @param $batch
  2221. * An array defining the batch. The following keys can be used -- only
  2222. * 'operations' is required, and batch_init() provides default values for
  2223. * the messages.
  2224. * - 'operations': Array of function calls to be performed.
  2225. * Example:
  2226. * @code
  2227. * array(
  2228. * array('my_function_1', array($arg1)),
  2229. * array('my_function_2', array($arg2_1, $arg2_2)),
  2230. * )
  2231. * @endcode
  2232. * - 'title': Title for the progress page. Only safe strings should be passed.
  2233. * Defaults to t('Processing').
  2234. * - 'init_message': Message displayed while the processing is initialized.
  2235. * Defaults to t('Initializing.').
  2236. * - 'progress_message': Message displayed while processing the batch.
  2237. * Available placeholders are @current, @remaining, @total, @percentage,
  2238. * @estimate and @elapsed. Defaults to t('Completed @current of @total.').
  2239. * - 'error_message': Message displayed if an error occurred while processing
  2240. * the batch. Defaults to t('An error has occurred.').
  2241. * - 'finished': Name of a function to be executed after the batch has
  2242. * completed. This should be used to perform any result massaging that
  2243. * may be needed, and possibly save data in $_SESSION for display after
  2244. * final page redirection.
  2245. * - 'file': Path to the file containing the definitions of the
  2246. * 'operations' and 'finished' functions, for instance if they don't
  2247. * reside in the main .module file. The path should be relative to
  2248. * base_path(), and thus should be built using drupal_get_path().
  2249. *
  2250. * Operations are added as new batch sets. Batch sets are used to ensure
  2251. * clean code independence, ensuring that several batches submitted by
  2252. * different parts of the code (core / contrib modules) can be processed
  2253. * correctly while not interfering or having to cope with each other. Each
  2254. * batch set gets to specify his own UI messages, operates on its own set
  2255. * of operations and results, and triggers its own 'finished' callback.
  2256. * Batch sets are processed sequentially, with the progress bar starting
  2257. * fresh for every new set.
  2258. */
  2259. function batch_set($batch_definition) {
  2260. if ($batch_definition) {
  2261. $batch =& batch_get();
  2262. // Initialize the batch
  2263. if (empty($batch)) {
  2264. $batch = array(
  2265. 'sets' => array(),
  2266. );
  2267. }
  2268. $init = array(
  2269. 'sandbox' => array(),
  2270. 'results' => array(),
  2271. 'success' => FALSE,
  2272. );
  2273. // Use get_t() to allow batches at install time.
  2274. $t = get_t();
  2275. $defaults = array(
  2276. 'title' => $t('Processing'),
  2277. 'init_message' => $t('Initializing.'),
  2278. 'progress_message' => $t('Remaining @remaining of @total.'),
  2279. 'error_message' => $t('An error has occurred.'),
  2280. );
  2281. $batch_set = $init + $batch_definition + $defaults;
  2282. // Tweak init_message to avoid the bottom of the page flickering down after init phase.
  2283. $batch_set['init_message'] .= '<br/>&nbsp;';
  2284. $batch_set['total'] = count($batch_set['operations']);
  2285. // If the batch is being processed (meaning we are executing a stored submit handler),
  2286. // insert the new set after the current one.
  2287. if (isset($batch['current_set'])) {
  2288. // array_insert does not exist...
  2289. $slice1 = array_slice($batch['sets'], 0, $batch['current_set'] + 1);
  2290. $slice2 = array_slice($batch['sets'], $batch['current_set'] + 1);
  2291. $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
  2292. }
  2293. else {
  2294. $batch['sets'][] = $batch_set;
  2295. }
  2296. }
  2297. }
  2298. /**
  2299. * Processes the batch.
  2300. *
  2301. * Unless the batch has been marked with 'progressive' = FALSE, the function
  2302. * issues a drupal_goto and thus ends page execution.
  2303. *
  2304. * This function is not needed in form submit handlers; Form API takes care
  2305. * of batches that were set during form submission.
  2306. *
  2307. * @param $redirect
  2308. * (optional) Path to redirect to when the batch has finished processing.
  2309. * @param $url
  2310. * (optional - should only be used for separate scripts like update.php)
  2311. * URL of the batch processing page.
  2312. */
  2313. function batch_process($redirect = NULL, $url = NULL) {
  2314. $batch =& batch_get();
  2315. if (isset($batch)) {
  2316. // Add process information
  2317. $url = isset($url) ? $url : 'batch';
  2318. $process_info = array(
  2319. 'current_set' => 0,
  2320. 'progressive' => TRUE,
  2321. 'url' => isset($url) ? $url : 'batch',
  2322. 'source_page' => $_GET['q'],
  2323. 'redirect' => $redirect,
  2324. );
  2325. $batch += $process_info;
  2326. if ($batch['progressive']) {
  2327. // Clear the way for the drupal_goto redirection to the batch processing
  2328. // page, by saving and unsetting the 'destination' if any, on both places
  2329. // drupal_goto looks for it.
  2330. if (isset($_REQUEST['destination'])) {
  2331. $batch['destination'] = $_REQUEST['destination'];
  2332. unset($_REQUEST['destination']);
  2333. }
  2334. elseif (isset($_REQUEST['edit']['destination'])) {
  2335. $batch['destination'] = $_REQUEST['edit']['destination'];
  2336. unset($_REQUEST['edit']['destination']);
  2337. }
  2338. // Initiate db storage in order to get a batch id. We have to provide
  2339. // at least an empty string for the (not null) 'token' column.
  2340. db_query("INSERT INTO {batch} (token, timestamp) VALUES ('', %d)", time());
  2341. $batch['id'] = db_last_insert_id('batch', 'bid');
  2342. // Now that we have a batch id, we can generate the redirection link in
  2343. // the generic error message.
  2344. $t = get_t();
  2345. $batch['error_message'] = $t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
  2346. // Actually store the batch data and the token generated form the batch id.
  2347. db_query("UPDATE {batch} SET token = '%s', batch = '%s' WHERE bid = %d", drupal_get_token($batch['id']), serialize($batch), $batch['id']);
  2348. drupal_goto($batch['url'], 'op=start&id='. $batch['id']);
  2349. }
  2350. else {
  2351. // Non-progressive execution: bypass the whole progressbar workflow
  2352. // and execute the batch in one pass.
  2353. require_once './includes/batch.inc';
  2354. _batch_process();
  2355. }
  2356. }
  2357. }
  2358. /**
  2359. * Retrieves the current batch.
  2360. */
  2361. function &batch_get() {
  2362. static $batch = array();
  2363. return $batch;
  2364. }
  2365. /**
  2366. * @} End of "defgroup batch".
  2367. */