form.inc

  1. cis7 includes/form.inc
  2. cis7 sites/all/themes/local_contrib/zurb-foundation/inc/form.inc
  3. cis7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  4. cle7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  5. cle7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  6. cle7 includes/form.inc
  7. cle7 sites/all/themes/local_contrib/bootstrap/includes/form.inc
  8. cle7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  9. ecd7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  10. ecd7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  11. ecd7 includes/form.inc
  12. elmsmedia7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  13. elmsmedia7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  14. elmsmedia7 includes/form.inc
  15. harmony7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  16. harmony7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  17. harmony7 includes/form.inc
  18. icor7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  19. icor7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  20. icor7 includes/form.inc
  21. meedjum_blog7 includes/form.inc
  22. meedjum_blog7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc
  23. meedjum_blog7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  24. mooc7 sites/all/themes/local_contrib/zurb_foundation/inc/form.inc
  25. mooc7 includes/form.inc
  26. mooc7 sites/all/modules/ulmus/ctools/plugins/content_types/form/form.inc

Functions for form and batch generation and processing.

Functions

Namesort descending Description
batch_get Retrieves the current batch.
batch_process Processes the batch.
batch_set Adds a new batch.
date_validate Validates the date type to prevent invalid dates (e.g., February 30, 2006).
drupal_build_form Builds and process a form based on a form id.
drupal_form_submit Retrieves, populates, and processes a form.
drupal_get_form Returns a renderable form array for a given form ID.
drupal_prepare_form Prepares a structured form array.
drupal_process_form Processes a form submission.
drupal_rebuild_form Constructs a new $form from the information in $form_state.
drupal_redirect_form Redirects the user to a URL after a form has been processed.
drupal_retrieve_form Retrieves the structured array that defines a given form.
drupal_validate_form Validates user-submitted form data in the $form_state array.
element_validate_integer Form element validation handler for integer elements.
element_validate_integer_positive Form element validation handler for integer elements that must be positive.
element_validate_number Form element validation handler for number elements.
form_builder Builds and processes all elements in the structured form array.
form_clear_error Clears all errors against all form elements made by form_set_error().
form_error Flags an element as having an error.
form_execute_handlers Executes custom validation and submission handlers for a given form.
form_get_cache Fetches a form from cache.
form_get_error Returns the error message filed against the given form element.
form_get_errors Returns an associative array of all errors.
form_get_options Returns the indexes of a select element's options matching a given key.
form_load_include Ensures an include file is loaded whenever the form is processed.
form_options_flatten Allows PHP array processing of multiple select options with the same value.
form_pre_render_conditional_form_element Adds form element theming to an element if its title or description is set.
form_pre_render_fieldset Adds members of this group as actual elements for rendering.
form_process_actions Processes a form actions container element.
form_process_checkbox Sets the #checked property of a checkbox element.
form_process_checkboxes Processes a checkboxes form element.
form_process_container Processes a container element.
form_process_date Expands a date element into year, month, and day select elements.
form_process_fieldset Arranges fieldsets into groups.
form_process_machine_name Processes a machine-readable name form element.
form_process_password_confirm Expand a password_confirm field into two text boxes.
form_process_radios Expands a radios element into individual radio elements.
form_process_select Processes a select list form element.
form_process_tableselect Creates checkbox or radio elements to populate a tableselect table.
form_process_vertical_tabs Creates a group formatted as vertical tabs.
form_process_weight Expands a weight element into a select element.
form_select_options Converts a select form element's options array into HTML.
form_set_cache Stores a form in the cache.
form_set_error Files an error against a form element.
form_set_value Changes submitted form values during form validation.
form_state_defaults Retrieves default values for the $form_state array.
form_state_keys_no_cache Returns an array of $form_state keys that shouldn't be cached.
form_state_values_clean Removes internal Form API elements and buttons from submitted form values.
form_type_checkboxes_value Determines the value for a checkboxes form element.
form_type_checkbox_value Determines the value for a checkbox form element.
form_type_image_button_value Determines the value for an image button form element.
form_type_password_confirm_value Determines the value for a password_confirm form element.
form_type_radios_value Form value callback: Determines the value for a #type radios form element.
form_type_select_value Determines the value for a select form element.
form_type_tableselect_value Determines the value for a tableselect form element.
form_type_textfield_value Determines the value for a textfield form element.
form_type_token_value Determines the value for form's token value.
form_validate_machine_name Form element validation handler for machine_name elements.
map_month Helper function for usage with drupal_map_assoc to display month names.
password_confirm_validate Validates a password_confirm element.
theme_button Returns HTML for a button form element.
theme_checkbox Returns HTML for a checkbox form element.
theme_checkboxes Returns HTML for a set of checkbox form elements.
theme_container Returns HTML to wrap child elements in a container.
theme_date Returns HTML for a date selection form element.
theme_fieldset Returns HTML for a fieldset form element and its children.
theme_file Returns HTML for a file upload form element.
theme_form Returns HTML for a form.
theme_form_element Returns HTML for a form element.
theme_form_element_label Returns HTML for a form element label and required marker.
theme_form_required_marker Returns HTML for a marker for required form elements.
theme_hidden Returns HTML for a hidden form element.
theme_image_button Returns HTML for an image button form element.
theme_password Returns HTML for a password form element.
theme_radio Returns HTML for a radio button form element.
theme_radios Returns HTML for a set of radio button form elements.
theme_select Returns HTML for a select form element.
theme_submit Returns HTML for a submit button form element.
theme_tableselect Returns HTML for a table with radio buttons or checkboxes.
theme_textarea Returns HTML for a textarea form element.
theme_textfield Returns HTML for a textfield form element.
theme_vertical_tabs Returns HTML for an element's children fieldsets as vertical tabs.
weight_value Sets the value for a weight element, with zero as a default.
_batch_populate_queue Populates a job queue with the operations of a batch set.
_batch_queue Returns a queue object for a batch set.
_form_builder_handle_input_element Adds the #name and #value properties of an input element before rendering.
_form_button_was_clicked Determines if a given button triggered the form submission.
_form_element_triggered_scripted_submission Detects if an element triggered the form submission via Ajax.
_form_options_flatten Iterates over an array and returns a flat array with duplicate keys removed.
_form_set_class Sets a form element's class attribute.
_form_validate Performs validation on form elements.

File

includes/form.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions for form and batch generation and processing.
  5. */
  6. /**
  7. * @defgroup forms Form builder functions
  8. * @{
  9. * Functions that build an abstract representation of a HTML form.
  10. *
  11. * All modules should declare their form builder functions to be in this
  12. * group and each builder function should reference its validate and submit
  13. * functions using \@see. Conversely, validate and submit functions should
  14. * reference the form builder function using \@see. For examples, of this see
  15. * system_modules_uninstall() or user_pass(), the latter of which has the
  16. * following in its doxygen documentation:
  17. *
  18. * \@ingroup forms
  19. * \@see user_pass_validate().
  20. * \@see user_pass_submit().
  21. *
  22. * @}
  23. */
  24. /**
  25. * @defgroup form_api Form generation
  26. * @{
  27. * Functions to enable the processing and display of HTML forms.
  28. *
  29. * Drupal uses these functions to achieve consistency in its form processing and
  30. * presentation, while simplifying code and reducing the amount of HTML that
  31. * must be explicitly generated by modules.
  32. *
  33. * The primary function used with forms is drupal_get_form(), which is
  34. * used for forms presented interactively to a user. Forms can also be built and
  35. * submitted programmatically without any user input using the
  36. * drupal_form_submit() function.
  37. *
  38. * drupal_get_form() handles retrieving, processing, and displaying a rendered
  39. * HTML form for modules automatically.
  40. *
  41. * Here is an example of how to use drupal_get_form() and a form builder
  42. * function:
  43. * @code
  44. * $form = drupal_get_form('my_module_example_form');
  45. * ...
  46. * function my_module_example_form($form, &$form_state) {
  47. * $form['submit'] = array(
  48. * '#type' => 'submit',
  49. * '#value' => t('Submit'),
  50. * );
  51. * return $form;
  52. * }
  53. * function my_module_example_form_validate($form, &$form_state) {
  54. * // Validation logic.
  55. * }
  56. * function my_module_example_form_submit($form, &$form_state) {
  57. * // Submission logic.
  58. * }
  59. * @endcode
  60. *
  61. * Or with any number of additional arguments:
  62. * @code
  63. * $extra = "extra";
  64. * $form = drupal_get_form('my_module_example_form', $extra);
  65. * ...
  66. * function my_module_example_form($form, &$form_state, $extra) {
  67. * $form['submit'] = array(
  68. * '#type' => 'submit',
  69. * '#value' => $extra,
  70. * );
  71. * return $form;
  72. * }
  73. * @endcode
  74. *
  75. * The $form argument to form-related functions is a structured array containing
  76. * the elements and properties of the form. For information on the array
  77. * components and format, and more detailed explanations of the Form API
  78. * workflow, see the
  79. * @link forms_api_reference.html Form API reference @endlink
  80. * and the
  81. * @link http://drupal.org/node/37775 Form API documentation section. @endlink
  82. * In addition, there is a set of Form API tutorials in
  83. * @link form_example_tutorial.inc the Form Example Tutorial @endlink which
  84. * provide basics all the way up through multistep forms.
  85. *
  86. * In the form builder, validation, submission, and other form functions,
  87. * $form_state is the primary influence on the processing of the form and is
  88. * passed by reference to most functions, so they use it to communicate with
  89. * the form system and each other.
  90. *
  91. * See drupal_build_form() for documentation of $form_state keys.
  92. */
  93. /**
  94. * Returns a renderable form array for a given form ID.
  95. *
  96. * This function should be used instead of drupal_build_form() when $form_state
  97. * is not needed (i.e., when initially rendering the form) and is often
  98. * used as a menu callback.
  99. *
  100. * @param $form_id
  101. * The unique string identifying the desired form. If a function with that
  102. * name exists, it is called to build the form array. Modules that need to
  103. * generate the same form (or very similar forms) using different $form_ids
  104. * can implement hook_forms(), which maps different $form_id values to the
  105. * proper form constructor function. Examples may be found in node_forms(),
  106. * and search_forms().
  107. * @param ...
  108. * Any additional arguments are passed on to the functions called by
  109. * drupal_get_form(), including the unique form constructor function. For
  110. * example, the node_edit form requires that a node object is passed in here
  111. * when it is called. These are available to implementations of
  112. * hook_form_alter() and hook_form_FORM_ID_alter() as the array
  113. * $form_state['build_info']['args'].
  114. *
  115. * @return
  116. * The form array.
  117. *
  118. * @see drupal_build_form()
  119. */
  120. function drupal_get_form($form_id) {
  121. $form_state = array();
  122. $args = func_get_args();
  123. // Remove $form_id from the arguments.
  124. array_shift($args);
  125. $form_state['build_info']['args'] = $args;
  126. return drupal_build_form($form_id, $form_state);
  127. }
  128. /**
  129. * Builds and process a form based on a form id.
  130. *
  131. * The form may also be retrieved from the cache if the form was built in a
  132. * previous page-load. The form is then passed on for processing, validation
  133. * and submission if there is proper input.
  134. *
  135. * @param $form_id
  136. * The unique string identifying the desired form. If a function with that
  137. * name exists, it is called to build the form array. Modules that need to
  138. * generate the same form (or very similar forms) using different $form_ids
  139. * can implement hook_forms(), which maps different $form_id values to the
  140. * proper form constructor function. Examples may be found in node_forms(),
  141. * and search_forms().
  142. * @param $form_state
  143. * An array which stores information about the form. This is passed as a
  144. * reference so that the caller can use it to examine what in the form changed
  145. * when the form submission process is complete. Furthermore, it may be used
  146. * to store information related to the processed data in the form, which will
  147. * persist across page requests when the 'cache' or 'rebuild' flag is set.
  148. * The following parameters may be set in $form_state to affect how the form
  149. * is rendered:
  150. * - build_info: Internal. An associative array of information stored by Form
  151. * API that is necessary to build and rebuild the form from cache when the
  152. * original context may no longer be available:
  153. * - args: A list of arguments to pass to the form constructor.
  154. * - files: An optional array defining include files that need to be loaded
  155. * for building the form. Each array entry may be the path to a file or
  156. * another array containing values for the parameters 'type', 'module' and
  157. * 'name' as needed by module_load_include(). The files listed here are
  158. * automatically loaded by form_get_cache(). By default the current menu
  159. * router item's 'file' definition is added, if any. Use
  160. * form_load_include() to add include files from a form constructor.
  161. * - form_id: Identification of the primary form being constructed and
  162. * processed.
  163. * - base_form_id: Identification for a base form, as declared in a
  164. * hook_forms() implementation.
  165. * - immutable: If this flag is set to TRUE, a new form build id is
  166. * generated when the form is loaded from the cache. If it is subsequently
  167. * saved to the cache again, it will have another cache id and therefore
  168. * the original form and form-state will remain unaltered. This is
  169. * important when page caching is enabled in order to prevent form state
  170. * from leaking between anonymous users.
  171. * - rebuild_info: Internal. Similar to 'build_info', but pertaining to
  172. * drupal_rebuild_form().
  173. * - rebuild: Normally, after the entire form processing is completed and
  174. * submit handlers have run, a form is considered to be done and
  175. * drupal_redirect_form() will redirect the user to a new page using a GET
  176. * request (so a browser refresh does not re-submit the form). However, if
  177. * 'rebuild' has been set to TRUE, then a new copy of the form is
  178. * immediately built and sent to the browser, instead of a redirect. This is
  179. * used for multi-step forms, such as wizards and confirmation forms.
  180. * Normally, $form_state['rebuild'] is set by a submit handler, since it is
  181. * usually logic within a submit handler that determines whether a form is
  182. * done or requires another step. However, a validation handler may already
  183. * set $form_state['rebuild'] to cause the form processing to bypass submit
  184. * handlers and rebuild the form instead, even if there are no validation
  185. * errors.
  186. * - redirect: Used to redirect the form on submission. It may either be a
  187. * string containing the destination URL, or an array of arguments
  188. * compatible with drupal_goto(). See drupal_redirect_form() for complete
  189. * information.
  190. * - no_redirect: If set to TRUE the form will NOT perform a drupal_goto(),
  191. * even if 'redirect' is set.
  192. * - method: The HTTP form method to use for finding the input for this form.
  193. * May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method
  194. * forms do not use form ids so are always considered to be submitted, which
  195. * can have unexpected effects. The 'get' method should only be used on
  196. * forms that do not change data, as that is exclusively the domain of
  197. * 'post.'
  198. * - cache: If set to TRUE the original, unprocessed form structure will be
  199. * cached, which allows the entire form to be rebuilt from cache. A typical
  200. * form workflow involves two page requests; first, a form is built and
  201. * rendered for the user to fill in. Then, the user fills the form in and
  202. * submits it, triggering a second page request in which the form must be
  203. * built and processed. By default, $form and $form_state are built from
  204. * scratch during each of these page requests. Often, it is necessary or
  205. * desired to persist the $form and $form_state variables from the initial
  206. * page request to the one that processes the submission. 'cache' can be set
  207. * to TRUE to do this. A prominent example is an Ajax-enabled form, in which
  208. * ajax_process_form() enables form caching for all forms that include an
  209. * element with the #ajax property. (The Ajax handler has no way to build
  210. * the form itself, so must rely on the cached version.) Note that the
  211. * persistence of $form and $form_state happens automatically for
  212. * (multi-step) forms having the 'rebuild' flag set, regardless of the value
  213. * for 'cache'.
  214. * - no_cache: If set to TRUE the form will NOT be cached, even if 'cache' is
  215. * set.
  216. * - values: An associative array of values submitted to the form. The
  217. * validation functions and submit functions use this array for nearly all
  218. * their decision making. (Note that #tree determines whether the values are
  219. * a flat array or an array whose structure parallels the $form array. See
  220. * @link forms_api_reference.html Form API reference @endlink for more
  221. * information.) These are raw and unvalidated, so should not be used
  222. * without a thorough understanding of security implications. In almost all
  223. * cases, code should use the data in the 'values' array exclusively. The
  224. * most common use of this key is for multi-step forms that need to clear
  225. * some of the user input when setting 'rebuild'. The values correspond to
  226. * $_POST or $_GET, depending on the 'method' chosen.
  227. * - always_process: If TRUE and the method is GET, a form_id is not
  228. * necessary. This should only be used on RESTful GET forms that do NOT
  229. * write data, as this could lead to security issues. It is useful so that
  230. * searches do not need to have a form_id in their query arguments to
  231. * trigger the search.
  232. * - must_validate: Ordinarily, a form is only validated once, but there are
  233. * times when a form is resubmitted internally and should be validated
  234. * again. Setting this to TRUE will force that to happen. This is most
  235. * likely to occur during Ajax operations.
  236. * - programmed: If TRUE, the form was submitted programmatically, usually
  237. * invoked via drupal_form_submit(). Defaults to FALSE.
  238. * - programmed_bypass_access_check: If TRUE, programmatic form submissions
  239. * are processed without taking #access into account. Set this to FALSE
  240. * when submitting a form programmatically with values that may have been
  241. * input by the user executing the current request; this will cause #access
  242. * to be respected as it would on a normal form submission. Defaults to
  243. * TRUE.
  244. * - process_input: Boolean flag. TRUE signifies correct form submission.
  245. * This is always TRUE for programmed forms coming from drupal_form_submit()
  246. * (see 'programmed' key), or if the form_id coming from the $_POST data is
  247. * set and matches the current form_id.
  248. * - submitted: If TRUE, the form has been submitted. Defaults to FALSE.
  249. * - executed: If TRUE, the form was submitted and has been processed and
  250. * executed. Defaults to FALSE.
  251. * - triggering_element: (read-only) The form element that triggered
  252. * submission. This is the same as the deprecated
  253. * $form_state['clicked_button']. It is the element that caused submission,
  254. * which may or may not be a button (in the case of Ajax forms). This key is
  255. * often used to distinguish between various buttons in a submit handler,
  256. * and is also used in Ajax handlers.
  257. * - clicked_button: Deprecated. Use triggering_element instead.
  258. * - has_file_element: Internal. If TRUE, there is a file element and Form API
  259. * will set the appropriate 'enctype' HTML attribute on the form.
  260. * - groups: Internal. An array containing references to fieldsets to render
  261. * them within vertical tabs.
  262. * - storage: $form_state['storage'] is not a special key, and no specific
  263. * support is provided for it in the Form API. By tradition it was
  264. * the location where application-specific data was stored for communication
  265. * between the submit, validation, and form builder functions, especially
  266. * in a multi-step-style form. Form implementations may use any key(s)
  267. * within $form_state (other than the keys listed here and other reserved
  268. * ones used by Form API internals) for this kind of storage. The
  269. * recommended way to ensure that the chosen key doesn't conflict with ones
  270. * used by the Form API or other modules is to use the module name as the
  271. * key name or a prefix for the key name. For example, the Node module uses
  272. * $form_state['node'] in node editing forms to store information about the
  273. * node being edited, and this information stays available across successive
  274. * clicks of the "Preview" button as well as when the "Save" button is
  275. * finally clicked.
  276. * - buttons: A list containing copies of all submit and button elements in
  277. * the form.
  278. * - complete form: A reference to the $form variable containing the complete
  279. * form structure. #process, #after_build, #element_validate, and other
  280. * handlers being invoked on a form element may use this reference to access
  281. * other information in the form the element is contained in.
  282. * - temporary: An array holding temporary data accessible during the current
  283. * page request only. All $form_state properties that are not reserved keys
  284. * (see form_state_keys_no_cache()) persist throughout a multistep form
  285. * sequence. Form API provides this key for modules to communicate
  286. * information across form-related functions during a single page request.
  287. * It may be used to temporarily save data that does not need to or should
  288. * not be cached during the whole form workflow; e.g., data that needs to be
  289. * accessed during the current form build process only. There is no use-case
  290. * for this functionality in Drupal core.
  291. * - wrapper_callback: Modules that wish to pre-populate certain forms with
  292. * common elements, such as back/next/save buttons in multi-step form
  293. * wizards, may define a form builder function name that returns a form
  294. * structure, which is passed on to the actual form builder function.
  295. * Such implementations may either define the 'wrapper_callback' via
  296. * hook_forms() or have to invoke drupal_build_form() (instead of
  297. * drupal_get_form()) on their own in a custom menu callback to prepare
  298. * $form_state accordingly.
  299. * Information on how certain $form_state properties control redirection
  300. * behavior after form submission may be found in drupal_redirect_form().
  301. *
  302. * @return
  303. * The rendered form. This function may also perform a redirect and hence may
  304. * not return at all, depending upon the $form_state flags that were set.
  305. *
  306. * @see drupal_redirect_form()
  307. */
  308. function drupal_build_form($form_id, &$form_state) {
  309. // Ensure some defaults; if already set they will not be overridden.
  310. $form_state += form_state_defaults();
  311. if (!isset($form_state['input'])) {
  312. $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
  313. }
  314. if (isset($_SESSION['batch_form_state'])) {
  315. // We've been redirected here after a batch processing. The form has
  316. // already been processed, but needs to be rebuilt. See _batch_finished().
  317. $form_state = $_SESSION['batch_form_state'];
  318. unset($_SESSION['batch_form_state']);
  319. return drupal_rebuild_form($form_id, $form_state);
  320. }
  321. // If the incoming input contains a form_build_id, we'll check the cache for a
  322. // copy of the form in question. If it's there, we don't have to rebuild the
  323. // form to proceed. In addition, if there is stored form_state data from a
  324. // previous step, we'll retrieve it so it can be passed on to the form
  325. // processing code.
  326. $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
  327. if ($check_cache) {
  328. $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
  329. }
  330. // If the previous bit of code didn't result in a populated $form object, we
  331. // are hitting the form for the first time and we need to build it from
  332. // scratch.
  333. if (!isset($form)) {
  334. // If we attempted to serve the form from cache, uncacheable $form_state
  335. // keys need to be removed after retrieving and preparing the form, except
  336. // any that were already set prior to retrieving the form.
  337. if ($check_cache) {
  338. $form_state_before_retrieval = $form_state;
  339. }
  340. $form = drupal_retrieve_form($form_id, $form_state);
  341. drupal_prepare_form($form_id, $form, $form_state);
  342. // form_set_cache() removes uncacheable $form_state keys defined in
  343. // form_state_keys_no_cache() in order for multi-step forms to work
  344. // properly. This means that form processing logic for single-step forms
  345. // using $form_state['cache'] may depend on data stored in those keys
  346. // during drupal_retrieve_form()/drupal_prepare_form(), but form
  347. // processing should not depend on whether the form is cached or not, so
  348. // $form_state is adjusted to match what it would be after a
  349. // form_set_cache()/form_get_cache() sequence. These exceptions are
  350. // allowed to survive here:
  351. // - always_process: Does not make sense in conjunction with form caching
  352. // in the first place, since passing form_build_id as a GET parameter is
  353. // not desired.
  354. // - temporary: Any assigned data is expected to survives within the same
  355. // page request.
  356. if ($check_cache) {
  357. $uncacheable_keys = array_flip(array_diff(form_state_keys_no_cache(), array('always_process', 'temporary')));
  358. $form_state = array_diff_key($form_state, $uncacheable_keys);
  359. $form_state += $form_state_before_retrieval;
  360. }
  361. }
  362. // Now that we have a constructed form, process it. This is where:
  363. // - Element #process functions get called to further refine $form.
  364. // - User input, if any, gets incorporated in the #value property of the
  365. // corresponding elements and into $form_state['values'].
  366. // - Validation and submission handlers are called.
  367. // - If this submission is part of a multistep workflow, the form is rebuilt
  368. // to contain the information of the next step.
  369. // - If necessary, the form and form state are cached or re-cached, so that
  370. // appropriate information persists to the next page request.
  371. // All of the handlers in the pipeline receive $form_state by reference and
  372. // can use it to know or update information about the state of the form.
  373. drupal_process_form($form_id, $form, $form_state);
  374. // If this was a successful submission of a single-step form or the last step
  375. // of a multi-step form, then drupal_process_form() issued a redirect to
  376. // another page, or back to this page, but as a new request. Therefore, if
  377. // we're here, it means that this is either a form being viewed initially
  378. // before any user input, or there was a validation error requiring the form
  379. // to be re-displayed, or we're in a multi-step workflow and need to display
  380. // the form's next step. In any case, we have what we need in $form, and can
  381. // return it for rendering.
  382. return $form;
  383. }
  384. /**
  385. * Retrieves default values for the $form_state array.
  386. */
  387. function form_state_defaults() {
  388. return array(
  389. 'rebuild' => FALSE,
  390. 'rebuild_info' => array(),
  391. 'redirect' => NULL,
  392. // @todo 'args' is usually set, so no other default 'build_info' keys are
  393. // appended via += form_state_defaults().
  394. 'build_info' => array(
  395. 'args' => array(),
  396. 'files' => array(),
  397. ),
  398. 'temporary' => array(),
  399. 'submitted' => FALSE,
  400. 'executed' => FALSE,
  401. 'programmed' => FALSE,
  402. 'programmed_bypass_access_check' => TRUE,
  403. 'cache'=> FALSE,
  404. 'method' => 'post',
  405. 'groups' => array(),
  406. 'buttons' => array(),
  407. );
  408. }
  409. /**
  410. * Constructs a new $form from the information in $form_state.
  411. *
  412. * This is the key function for making multi-step forms advance from step to
  413. * step. It is called by drupal_process_form() when all user input processing,
  414. * including calling validation and submission handlers, for the request is
  415. * finished. If a validate or submit handler set $form_state['rebuild'] to TRUE,
  416. * and if other conditions don't preempt a rebuild from happening, then this
  417. * function is called to generate a new $form, the next step in the form
  418. * workflow, to be returned for rendering.
  419. *
  420. * Ajax form submissions are almost always multi-step workflows, so that is one
  421. * common use-case during which form rebuilding occurs. See ajax_form_callback()
  422. * for more information about creating Ajax-enabled forms.
  423. *
  424. * @param $form_id
  425. * The unique string identifying the desired form. If a function
  426. * with that name exists, it is called to build the form array.
  427. * Modules that need to generate the same form (or very similar forms)
  428. * using different $form_ids can implement hook_forms(), which maps
  429. * different $form_id values to the proper form constructor function. Examples
  430. * may be found in node_forms() and search_forms().
  431. * @param $form_state
  432. * A keyed array containing the current state of the form.
  433. * @param $old_form
  434. * (optional) A previously built $form. Used to retain the #build_id and
  435. * #action properties in Ajax callbacks and similar partial form rebuilds. The
  436. * only properties copied from $old_form are the ones which both exist in
  437. * $old_form and for which $form_state['rebuild_info']['copy'][PROPERTY] is
  438. * TRUE. If $old_form is not passed, the entire $form is rebuilt freshly.
  439. * 'rebuild_info' needs to be a separate top-level property next to
  440. * 'build_info', since the contained data must not be cached.
  441. *
  442. * @return
  443. * The newly built form.
  444. *
  445. * @see drupal_process_form()
  446. * @see ajax_form_callback()
  447. */
  448. function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
  449. $form = drupal_retrieve_form($form_id, $form_state);
  450. // If only parts of the form will be returned to the browser (e.g., Ajax or
  451. // RIA clients), or if the form already had a new build ID regenerated when it
  452. // was retrieved from the form cache, reuse the existing #build_id.
  453. // Otherwise, a new #build_id is generated, to not clobber the previous
  454. // build's data in the form cache; also allowing the user to go back to an
  455. // earlier build, make changes, and re-submit.
  456. // @see drupal_prepare_form()
  457. $enforce_old_build_id = isset($old_form['#build_id']) && !empty($form_state['rebuild_info']['copy']['#build_id']);
  458. $old_form_is_mutable_copy = isset($old_form['#build_id_old']);
  459. if ($enforce_old_build_id || $old_form_is_mutable_copy) {
  460. $form['#build_id'] = $old_form['#build_id'];
  461. if ($old_form_is_mutable_copy) {
  462. $form['#build_id_old'] = $old_form['#build_id_old'];
  463. }
  464. }
  465. else {
  466. if (isset($old_form['#build_id'])) {
  467. $form['#build_id_old'] = $old_form['#build_id'];
  468. }
  469. $form['#build_id'] = 'form-' . drupal_random_key();
  470. }
  471. // #action defaults to request_uri(), but in case of Ajax and other partial
  472. // rebuilds, the form is submitted to an alternate URL, and the original
  473. // #action needs to be retained.
  474. if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
  475. $form['#action'] = $old_form['#action'];
  476. }
  477. drupal_prepare_form($form_id, $form, $form_state);
  478. // Caching is normally done in drupal_process_form(), but what needs to be
  479. // cached is the $form structure before it passes through form_builder(),
  480. // so we need to do it here.
  481. // @todo For Drupal 8, find a way to avoid this code duplication.
  482. if (empty($form_state['no_cache'])) {
  483. form_set_cache($form['#build_id'], $form, $form_state);
  484. }
  485. // Clear out all group associations as these might be different when
  486. // re-rendering the form.
  487. $form_state['groups'] = array();
  488. // Return a fully built form that is ready for rendering.
  489. return form_builder($form_id, $form, $form_state);
  490. }
  491. /**
  492. * Fetches a form from cache.
  493. */
  494. function form_get_cache($form_build_id, &$form_state) {
  495. if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
  496. $form = $cached->data;
  497. global $user;
  498. if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
  499. if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
  500. // Re-populate $form_state for subsequent rebuilds.
  501. $form_state = $cached->data + $form_state;
  502. // If the original form is contained in include files, load the files.
  503. // @see form_load_include()
  504. $form_state['build_info'] += array('files' => array());
  505. foreach ($form_state['build_info']['files'] as $file) {
  506. if (is_array($file)) {
  507. $file += array('type' => 'inc', 'name' => $file['module']);
  508. module_load_include($file['type'], $file['module'], $file['name']);
  509. }
  510. elseif (file_exists($file)) {
  511. require_once DRUPAL_ROOT . '/' . $file;
  512. }
  513. }
  514. }
  515. // Generate a new #build_id if the cached form was rendered on a cacheable
  516. // page.
  517. if (!empty($form_state['build_info']['immutable'])) {
  518. $form['#build_id_old'] = $form['#build_id'];
  519. $form['#build_id'] = 'form-' . drupal_random_key();
  520. $form['form_build_id']['#value'] = $form['#build_id'];
  521. $form['form_build_id']['#id'] = $form['#build_id'];
  522. unset($form_state['build_info']['immutable']);
  523. }
  524. return $form;
  525. }
  526. }
  527. }
  528. /**
  529. * Stores a form in the cache.
  530. */
  531. function form_set_cache($form_build_id, $form, $form_state) {
  532. // 6 hours cache life time for forms should be plenty.
  533. $expire = 21600;
  534. // Ensure that the form build_id embedded in the form structure is the same as
  535. // the one passed in as a parameter. This is an additional safety measure to
  536. // prevent legacy code operating directly with form_get_cache and
  537. // form_set_cache from accidentally overwriting immutable form state.
  538. if ($form['#build_id'] != $form_build_id) {
  539. watchdog('form', 'Form build-id mismatch detected while attempting to store a form in the cache.', array(), WATCHDOG_ERROR);
  540. return;
  541. }
  542. // Cache form structure.
  543. if (isset($form)) {
  544. if ($GLOBALS['user']->uid) {
  545. $form['#cache_token'] = drupal_get_token();
  546. }
  547. unset($form['#build_id_old']);
  548. cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
  549. }
  550. // Cache form state.
  551. if (variable_get('cache', 0) && drupal_page_is_cacheable()) {
  552. $form_state['build_info']['immutable'] = TRUE;
  553. }
  554. if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
  555. cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
  556. }
  557. }
  558. /**
  559. * Returns an array of $form_state keys that shouldn't be cached.
  560. */
  561. function form_state_keys_no_cache() {
  562. return array(
  563. // Public properties defined by form constructors and form handlers.
  564. 'always_process',
  565. 'must_validate',
  566. 'rebuild',
  567. 'rebuild_info',
  568. 'redirect',
  569. 'no_redirect',
  570. 'temporary',
  571. // Internal properties defined by form processing.
  572. 'buttons',
  573. 'triggering_element',
  574. 'clicked_button',
  575. 'complete form',
  576. 'groups',
  577. 'input',
  578. 'method',
  579. 'submit_handlers',
  580. 'submitted',
  581. 'executed',
  582. 'validate_handlers',
  583. 'values',
  584. );
  585. }
  586. /**
  587. * Ensures an include file is loaded whenever the form is processed.
  588. *
  589. * Example:
  590. * @code
  591. * // Load node.admin.inc from Node module.
  592. * form_load_include($form_state, 'inc', 'node', 'node.admin');
  593. * @endcode
  594. *
  595. * Use this function instead of module_load_include() from inside a form
  596. * constructor or any form processing logic as it ensures that the include file
  597. * is loaded whenever the form is processed. In contrast to using
  598. * module_load_include() directly, form_load_include() makes sure the include
  599. * file is correctly loaded also if the form is cached.
  600. *
  601. * @param $form_state
  602. * The current state of the form.
  603. * @param $type
  604. * The include file's type (file extension).
  605. * @param $module
  606. * The module to which the include file belongs.
  607. * @param $name
  608. * (optional) The base file name (without the $type extension). If omitted,
  609. * $module is used; i.e., resulting in "$module.$type" by default.
  610. *
  611. * @return
  612. * The filepath of the loaded include file, or FALSE if the include file was
  613. * not found or has been loaded already.
  614. *
  615. * @see module_load_include()
  616. */
  617. function form_load_include(&$form_state, $type, $module, $name = NULL) {
  618. if (!isset($name)) {
  619. $name = $module;
  620. }
  621. if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
  622. // Only add successfully included files to the form state.
  623. if ($result = module_load_include($type, $module, $name)) {
  624. $form_state['build_info']['files']["$module:$name.$type"] = array(
  625. 'type' => $type,
  626. 'module' => $module,
  627. 'name' => $name,
  628. );
  629. return $result;
  630. }
  631. }
  632. return FALSE;
  633. }
  634. /**
  635. * Retrieves, populates, and processes a form.
  636. *
  637. * This function allows you to supply values for form elements and submit a
  638. * form for processing. Compare to drupal_get_form(), which also builds and
  639. * processes a form, but does not allow you to supply values.
  640. *
  641. * There is no return value, but you can check to see if there are errors
  642. * by calling form_get_errors().
  643. *
  644. * @param $form_id
  645. * The unique string identifying the desired form. If a function
  646. * with that name exists, it is called to build the form array.
  647. * Modules that need to generate the same form (or very similar forms)
  648. * using different $form_ids can implement hook_forms(), which maps
  649. * different $form_id values to the proper form constructor function. Examples
  650. * may be found in node_forms() and search_forms().
  651. * @param $form_state
  652. * A keyed array containing the current state of the form. Most important is
  653. * the $form_state['values'] collection, a tree of data used to simulate the
  654. * incoming $_POST information from a user's form submission. If a key is not
  655. * filled in $form_state['values'], then the default value of the respective
  656. * element is used. To submit an unchecked checkbox or other control that
  657. * browsers submit by not having a $_POST entry, include the key, but set the
  658. * value to NULL.
  659. * @param ...
  660. * Any additional arguments are passed on to the functions called by
  661. * drupal_form_submit(), including the unique form constructor function.
  662. * For example, the node_edit form requires that a node object be passed
  663. * in here when it is called. Arguments that need to be passed by reference
  664. * should not be included here, but rather placed directly in the $form_state
  665. * build info array so that the reference can be preserved. For example, a
  666. * form builder function with the following signature:
  667. * @code
  668. * function mymodule_form($form, &$form_state, &$object) {
  669. * }
  670. * @endcode
  671. * would be called via drupal_form_submit() as follows:
  672. * @code
  673. * $form_state['values'] = $my_form_values;
  674. * $form_state['build_info']['args'] = array(&$object);
  675. * drupal_form_submit('mymodule_form', $form_state);
  676. * @endcode
  677. * For example:
  678. * @code
  679. * // register a new user
  680. * $form_state = array();
  681. * $form_state['values']['name'] = 'robo-user';
  682. * $form_state['values']['mail'] = 'robouser@example.com';
  683. * $form_state['values']['pass']['pass1'] = 'password';
  684. * $form_state['values']['pass']['pass2'] = 'password';
  685. * $form_state['values']['op'] = t('Create new account');
  686. * drupal_form_submit('user_register_form', $form_state);
  687. * @endcode
  688. */
  689. function drupal_form_submit($form_id, &$form_state) {
  690. if (!isset($form_state['build_info']['args'])) {
  691. $args = func_get_args();
  692. array_shift($args);
  693. array_shift($args);
  694. $form_state['build_info']['args'] = $args;
  695. }
  696. // Merge in default values.
  697. $form_state += form_state_defaults();
  698. // Populate $form_state['input'] with the submitted values before retrieving
  699. // the form, to be consistent with what drupal_build_form() does for
  700. // non-programmatic submissions (form builder functions may expect it to be
  701. // there).
  702. $form_state['input'] = $form_state['values'];
  703. $form_state['programmed'] = TRUE;
  704. $form = drupal_retrieve_form($form_id, $form_state);
  705. // Programmed forms are always submitted.
  706. $form_state['submitted'] = TRUE;
  707. // Reset form validation.
  708. $form_state['must_validate'] = TRUE;
  709. form_clear_error();
  710. drupal_prepare_form($form_id, $form, $form_state);
  711. drupal_process_form($form_id, $form, $form_state);
  712. }
  713. /**
  714. * Retrieves the structured array that defines a given form.
  715. *
  716. * @param $form_id
  717. * The unique string identifying the desired form. If a function
  718. * with that name exists, it is called to build the form array.
  719. * Modules that need to generate the same form (or very similar forms)
  720. * using different $form_ids can implement hook_forms(), which maps
  721. * different $form_id values to the proper form constructor function.
  722. * @param $form_state
  723. * A keyed array containing the current state of the form, including the
  724. * additional arguments to drupal_get_form() or drupal_form_submit() in the
  725. * 'args' component of the array.
  726. */
  727. function drupal_retrieve_form($form_id, &$form_state) {
  728. $forms = &drupal_static(__FUNCTION__);
  729. // Record the $form_id.
  730. $form_state['build_info']['form_id'] = $form_id;
  731. // Record the filepath of the include file containing the original form, so
  732. // the form builder callbacks can be loaded when the form is being rebuilt
  733. // from cache on a different path (such as 'system/ajax'). See
  734. // form_get_cache(). Don't do this in maintenance mode as Drupal may not be
  735. // fully bootstrapped (i.e. during installation) in which case
  736. // menu_get_item() is not available.
  737. if (!isset($form_state['build_info']['files']['menu']) && !defined('MAINTENANCE_MODE')) {
  738. $item = menu_get_item();
  739. if (!empty($item['include_file'])) {
  740. // Do not use form_load_include() here, as the file is already loaded.
  741. // Anyway, form_get_cache() is able to handle filepaths too.
  742. $form_state['build_info']['files']['menu'] = $item['include_file'];
  743. }
  744. }
  745. // We save two copies of the incoming arguments: one for modules to use
  746. // when mapping form ids to constructor functions, and another to pass to
  747. // the constructor function itself.
  748. $args = $form_state['build_info']['args'];
  749. // We first check to see if there's a function named after the $form_id.
  750. // If there is, we simply pass the arguments on to it to get the form.
  751. if (!function_exists($form_id)) {
  752. // In cases where many form_ids need to share a central constructor function,
  753. // such as the node editing form, modules can implement hook_forms(). It
  754. // maps one or more form_ids to the correct constructor functions.
  755. //
  756. // We cache the results of that hook to save time, but that only works
  757. // for modules that know all their form_ids in advance. (A module that
  758. // adds a small 'rate this comment' form to each comment in a list
  759. // would need a unique form_id for each one, for example.)
  760. //
  761. // So, we call the hook if $forms isn't yet populated, OR if it doesn't
  762. // yet have an entry for the requested form_id.
  763. if (!isset($forms) || !isset($forms[$form_id])) {
  764. $forms = module_invoke_all('forms', $form_id, $args);
  765. }
  766. $form_definition = $forms[$form_id];
  767. if (isset($form_definition['callback arguments'])) {
  768. $args = array_merge($form_definition['callback arguments'], $args);
  769. }
  770. if (isset($form_definition['callback'])) {
  771. $callback = $form_definition['callback'];
  772. $form_state['build_info']['base_form_id'] = $callback;
  773. }
  774. // In case $form_state['wrapper_callback'] is not defined already, we also
  775. // allow hook_forms() to define one.
  776. if (!isset($form_state['wrapper_callback']) && isset($form_definition['wrapper_callback'])) {
  777. $form_state['wrapper_callback'] = $form_definition['wrapper_callback'];
  778. }
  779. }
  780. $form = array();
  781. // We need to pass $form_state by reference in order for forms to modify it,
  782. // since call_user_func_array() requires that referenced variables are passed
  783. // explicitly.
  784. $args = array_merge(array($form, &$form_state), $args);
  785. // When the passed $form_state (not using drupal_get_form()) defines a
  786. // 'wrapper_callback', then it requests to invoke a separate (wrapping) form
  787. // builder function to pre-populate the $form array with form elements, which
  788. // the actual form builder function ($callback) expects. This allows for
  789. // pre-populating a form with common elements for certain forms, such as
  790. // back/next/save buttons in multi-step form wizards. See drupal_build_form().
  791. if (isset($form_state['wrapper_callback']) && function_exists($form_state['wrapper_callback'])) {
  792. $form = call_user_func_array($form_state['wrapper_callback'], $args);
  793. // Put the prepopulated $form into $args.
  794. $args[0] = $form;
  795. }
  796. // If $callback was returned by a hook_forms() implementation, call it.
  797. // Otherwise, call the function named after the form id.
  798. $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
  799. $form['#form_id'] = $form_id;
  800. return $form;
  801. }
  802. /**
  803. * Processes a form submission.
  804. *
  805. * This function is the heart of form API. The form gets built, validated and in
  806. * appropriate cases, submitted and rebuilt.
  807. *
  808. * @param $form_id
  809. * The unique string identifying the current form.
  810. * @param $form
  811. * An associative array containing the structure of the form.
  812. * @param $form_state
  813. * A keyed array containing the current state of the form. This
  814. * includes the current persistent storage data for the form, and
  815. * any data passed along by earlier steps when displaying a
  816. * multi-step form. Additional information, like the sanitized $_POST
  817. * data, is also accumulated here.
  818. */
  819. function drupal_process_form($form_id, &$form, &$form_state) {
  820. $form_state['values'] = array();
  821. // With $_GET, these forms are always submitted if requested.
  822. if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
  823. if (!isset($form_state['input']['form_build_id'])) {
  824. $form_state['input']['form_build_id'] = $form['#build_id'];
  825. }
  826. if (!isset($form_state['input']['form_id'])) {
  827. $form_state['input']['form_id'] = $form_id;
  828. }
  829. if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
  830. $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  831. }
  832. }
  833. // form_builder() finishes building the form by calling element #process
  834. // functions and mapping user input, if any, to #value properties, and also
  835. // storing the values in $form_state['values']. We need to retain the
  836. // unprocessed $form in case it needs to be cached.
  837. $unprocessed_form = $form;
  838. $form = form_builder($form_id, $form, $form_state);
  839. // Only process the input if we have a correct form submission.
  840. if ($form_state['process_input']) {
  841. drupal_validate_form($form_id, $form, $form_state);
  842. // drupal_html_id() maintains a cache of element IDs it has seen,
  843. // so it can prevent duplicates. We want to be sure we reset that
  844. // cache when a form is processed, so scenarios that result in
  845. // the form being built behind the scenes and again for the
  846. // browser don't increment all the element IDs needlessly.
  847. if (!form_get_errors()) {
  848. // In case of errors, do not break HTML IDs of other forms.
  849. drupal_static_reset('drupal_html_id');
  850. }
  851. if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
  852. // Execute form submit handlers.
  853. form_execute_handlers('submit', $form, $form_state);
  854. // We'll clear out the cached copies of the form and its stored data
  855. // here, as we've finished with them. The in-memory copies are still
  856. // here, though.
  857. if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
  858. cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
  859. cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
  860. }
  861. // If batches were set in the submit handlers, we process them now,
  862. // possibly ending execution. We make sure we do not react to the batch
  863. // that is already being processed (if a batch operation performs a
  864. // drupal_form_submit).
  865. if ($batch =& batch_get() && !isset($batch['current_set'])) {
  866. // Store $form_state information in the batch definition.
  867. // We need the full $form_state when either:
  868. // - Some submit handlers were saved to be called during batch
  869. // processing. See form_execute_handlers().
  870. // - The form is multistep.
  871. // In other cases, we only need the information expected by
  872. // drupal_redirect_form().
  873. if ($batch['has_form_submits'] || !empty($form_state['rebuild'])) {
  874. $batch['form_state'] = $form_state;
  875. }
  876. else {
  877. $batch['form_state'] = array_intersect_key($form_state, array_flip(array('programmed', 'rebuild', 'storage', 'no_redirect', 'redirect')));
  878. }
  879. $batch['progressive'] = !$form_state['programmed'];
  880. batch_process();
  881. // Execution continues only for programmatic forms.
  882. // For 'regular' forms, we get redirected to the batch processing
  883. // page. Form redirection will be handled in _batch_finished(),
  884. // after the batch is processed.
  885. }
  886. // Set a flag to indicate the the form has been processed and executed.
  887. $form_state['executed'] = TRUE;
  888. // Redirect the form based on values in $form_state.
  889. drupal_redirect_form($form_state);
  890. }
  891. // Don't rebuild or cache form submissions invoked via drupal_form_submit().
  892. if (!empty($form_state['programmed'])) {
  893. return;
  894. }
  895. // If $form_state['rebuild'] has been set and input has been processed
  896. // without validation errors, we are in a multi-step workflow that is not
  897. // yet complete. A new $form needs to be constructed based on the changes
  898. // made to $form_state during this request. Normally, a submit handler sets
  899. // $form_state['rebuild'] if a fully executed form requires another step.
  900. // However, for forms that have not been fully executed (e.g., Ajax
  901. // submissions triggered by non-buttons), there is no submit handler to set
  902. // $form_state['rebuild']. It would not make sense to redisplay the
  903. // identical form without an error for the user to correct, so we also
  904. // rebuild error-free non-executed forms, regardless of
  905. // $form_state['rebuild'].
  906. // @todo D8: Simplify this logic; considering Ajax and non-HTML front-ends,
  907. // along with element-level #submit properties, it makes no sense to have
  908. // divergent form execution based on whether the triggering element has
  909. // #executes_submit_callback set to TRUE.
  910. if (($form_state['rebuild'] || !$form_state['executed']) && !form_get_errors()) {
  911. // Form building functions (e.g., _form_builder_handle_input_element())
  912. // may use $form_state['rebuild'] to determine if they are running in the
  913. // context of a rebuild, so ensure it is set.
  914. $form_state['rebuild'] = TRUE;
  915. $form = drupal_rebuild_form($form_id, $form_state, $form);
  916. }
  917. }
  918. // After processing the form, the form builder or a #process callback may
  919. // have set $form_state['cache'] to indicate that the form and form state
  920. // shall be cached. But the form may only be cached if the 'no_cache' property
  921. // is not set to TRUE. Only cache $form as it was prior to form_builder(),
  922. // because form_builder() must run for each request to accommodate new user
  923. // input. Rebuilt forms are not cached here, because drupal_rebuild_form()
  924. // already takes care of that.
  925. if (!$form_state['rebuild'] && $form_state['cache'] && empty($form_state['no_cache'])) {
  926. form_set_cache($form['#build_id'], $unprocessed_form, $form_state);
  927. }
  928. }
  929. /**
  930. * Prepares a structured form array.
  931. *
  932. * Adds required elements, executes any hook_form_alter functions, and
  933. * optionally inserts a validation token to prevent tampering.
  934. *
  935. * @param $form_id
  936. * A unique string identifying the form for validation, submission,
  937. * theming, and hook_form_alter functions.
  938. * @param $form
  939. * An associative array containing the structure of the form.
  940. * @param $form_state
  941. * A keyed array containing the current state of the form. Passed
  942. * in here so that hook_form_alter() calls can use it, as well.
  943. */
  944. function drupal_prepare_form($form_id, &$form, &$form_state) {
  945. global $user;
  946. $form['#type'] = 'form';
  947. $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
  948. // Fix the form method, if it is 'get' in $form_state, but not in $form.
  949. if ($form_state['method'] == 'get' && !isset($form['#method'])) {
  950. $form['#method'] = 'get';
  951. }
  952. // Generate a new #build_id for this form, if none has been set already. The
  953. // form_build_id is used as key to cache a particular build of the form. For
  954. // multi-step forms, this allows the user to go back to an earlier build, make
  955. // changes, and re-submit.
  956. // @see drupal_build_form()
  957. // @see drupal_rebuild_form()
  958. if (!isset($form['#build_id'])) {
  959. $form['#build_id'] = 'form-' . drupal_random_key();
  960. }
  961. $form['form_build_id'] = array(
  962. '#type' => 'hidden',
  963. '#value' => $form['#build_id'],
  964. '#id' => $form['#build_id'],
  965. '#name' => 'form_build_id',
  966. // Form processing and validation requires this value, so ensure the
  967. // submitted form value appears literally, regardless of custom #tree
  968. // and #parents being set elsewhere.
  969. '#parents' => array('form_build_id'),
  970. );
  971. // Add a token, based on either #token or form_id, to any form displayed to
  972. // authenticated users. This ensures that any submitted form was actually
  973. // requested previously by the user and protects against cross site request
  974. // forgeries.
  975. // This does not apply to programmatically submitted forms. Furthermore, since
  976. // tokens are session-bound and forms displayed to anonymous users are very
  977. // likely cached, we cannot assign a token for them.
  978. // During installation, there is no $user yet.
  979. if (!empty($user->uid) && !$form_state['programmed']) {
  980. // Form constructors may explicitly set #token to FALSE when cross site
  981. // request forgery is irrelevant to the form, such as search forms.
  982. if (isset($form['#token']) && $form['#token'] === FALSE) {
  983. unset($form['#token']);
  984. }
  985. // Otherwise, generate a public token based on the form id.
  986. else {
  987. $form['#token'] = $form_id;
  988. $form['form_token'] = array(
  989. '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
  990. '#type' => 'token',
  991. '#default_value' => drupal_get_token($form['#token']),
  992. // Form processing and validation requires this value, so ensure the
  993. // submitted form value appears literally, regardless of custom #tree
  994. // and #parents being set elsewhere.
  995. '#parents' => array('form_token'),
  996. );
  997. }
  998. }
  999. if (isset($form_id)) {
  1000. $form['form_id'] = array(
  1001. '#type' => 'hidden',
  1002. '#value' => $form_id,
  1003. '#id' => drupal_html_id("edit-$form_id"),
  1004. // Form processing and validation requires this value, so ensure the
  1005. // submitted form value appears literally, regardless of custom #tree
  1006. // and #parents being set elsewhere.
  1007. '#parents' => array('form_id'),
  1008. );
  1009. }
  1010. if (!isset($form['#id'])) {
  1011. $form['#id'] = drupal_html_id($form_id);
  1012. }
  1013. $form += element_info('form');
  1014. $form += array('#tree' => FALSE, '#parents' => array());
  1015. if (!isset($form['#validate'])) {
  1016. // Ensure that modules can rely on #validate being set.
  1017. $form['#validate'] = array();
  1018. // Check for a handler specific to $form_id.
  1019. if (function_exists($form_id . '_validate')) {
  1020. $form['#validate'][] = $form_id . '_validate';
  1021. }
  1022. // Otherwise check whether this is a shared form and whether there is a
  1023. // handler for the shared $form_id.
  1024. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_validate')) {
  1025. $form['#validate'][] = $form_state['build_info']['base_form_id'] . '_validate';
  1026. }
  1027. }
  1028. if (!isset($form['#submit'])) {
  1029. // Ensure that modules can rely on #submit being set.
  1030. $form['#submit'] = array();
  1031. // Check for a handler specific to $form_id.
  1032. if (function_exists($form_id . '_submit')) {
  1033. $form['#submit'][] = $form_id . '_submit';
  1034. }
  1035. // Otherwise check whether this is a shared form and whether there is a
  1036. // handler for the shared $form_id.
  1037. elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
  1038. $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
  1039. }
  1040. }
  1041. // If no #theme has been set, automatically apply theme suggestions.
  1042. // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
  1043. // #theme function only has to care for rendering the inner form elements,
  1044. // not the form itself.
  1045. if (!isset($form['#theme'])) {
  1046. $form['#theme'] = array($form_id);
  1047. if (isset($form_state['build_info']['base_form_id'])) {
  1048. $form['#theme'][] = $form_state['build_info']['base_form_id'];
  1049. }
  1050. }
  1051. // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
  1052. // hook_form_FORM_ID_alter() implementations.
  1053. $hooks = array('form');
  1054. if (isset($form_state['build_info']['base_form_id'])) {
  1055. $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
  1056. }
  1057. $hooks[] = 'form_' . $form_id;
  1058. drupal_alter($hooks, $form, $form_state, $form_id);
  1059. }
  1060. /**
  1061. * Validates user-submitted form data in the $form_state array.
  1062. *
  1063. * @param $form_id
  1064. * A unique string identifying the form for validation, submission,
  1065. * theming, and hook_form_alter functions.
  1066. * @param $form
  1067. * An associative array containing the structure of the form, which is passed
  1068. * by reference. Form validation handlers are able to alter the form structure
  1069. * (like #process and #after_build callbacks during form building) in case of
  1070. * a validation error. If a validation handler alters the form structure, it
  1071. * is responsible for validating the values of changed form elements in
  1072. * $form_state['values'] to prevent form submit handlers from receiving
  1073. * unvalidated values.
  1074. * @param $form_state
  1075. * A keyed array containing the current state of the form. The current
  1076. * user-submitted data is stored in $form_state['values'], though
  1077. * form validation functions are passed an explicit copy of the
  1078. * values for the sake of simplicity. Validation handlers can also use
  1079. * $form_state to pass information on to submit handlers. For example:
  1080. * $form_state['data_for_submission'] = $data;
  1081. * This technique is useful when validation requires file parsing,
  1082. * web service requests, or other expensive requests that should
  1083. * not be repeated in the submission step.
  1084. */
  1085. function drupal_validate_form($form_id, &$form, &$form_state) {
  1086. $validated_forms = &drupal_static(__FUNCTION__, array());
  1087. if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
  1088. return;
  1089. }
  1090. // If the session token was set by drupal_prepare_form(), ensure that it
  1091. // matches the current user's session.
  1092. if (isset($form['#token'])) {
  1093. if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
  1094. $path = current_path();
  1095. $query = drupal_get_query_parameters();
  1096. $url = url($path, array('query' => $query));
  1097. // Setting this error will cause the form to fail validation.
  1098. form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
  1099. // Stop here and don't run any further validation handlers, because they
  1100. // could invoke non-safe operations which opens the door for CSRF
  1101. // vulnerabilities.
  1102. $validated_forms[$form_id] = TRUE;
  1103. return;
  1104. }
  1105. }
  1106. _form_validate($form, $form_state, $form_id);
  1107. $validated_forms[$form_id] = TRUE;
  1108. // If validation errors are limited then remove any non validated form values,
  1109. // so that only values that passed validation are left for submit callbacks.
  1110. if (isset($form_state['triggering_element']['#limit_validation_errors']) && $form_state['triggering_element']['#limit_validation_errors'] !== FALSE) {
  1111. $values = array();
  1112. foreach ($form_state['triggering_element']['#limit_validation_errors'] as $section) {
  1113. // If the section exists within $form_state['values'], even if the value
  1114. // is NULL, copy it to $values.
  1115. $section_exists = NULL;
  1116. $value = drupal_array_get_nested_value($form_state['values'], $section, $section_exists);
  1117. if ($section_exists) {
  1118. drupal_array_set_nested_value($values, $section, $value);
  1119. }
  1120. }
  1121. // A button's #value does not require validation, so for convenience we
  1122. // allow the value of the clicked button to be retained in its normal
  1123. // $form_state['values'] locations, even if these locations are not included
  1124. // in #limit_validation_errors.
  1125. if (isset($form_state['triggering_element']['#button_type'])) {
  1126. $button_value = $form_state['triggering_element']['#value'];
  1127. // Like all input controls, the button value may be in the location
  1128. // dictated by #parents. If it is, copy it to $values, but do not override
  1129. // what may already be in $values.
  1130. $parents = $form_state['triggering_element']['#parents'];
  1131. if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
  1132. drupal_array_set_nested_value($values, $parents, $button_value);
  1133. }
  1134. // Additionally, form_builder() places the button value in
  1135. // $form_state['values'][BUTTON_NAME]. If it's still there, after
  1136. // validation handlers have run, copy it to $values, but do not override
  1137. // what may already be in $values.
  1138. $name = $form_state['triggering_element']['#name'];
  1139. if (!isset($values[$name]) && isset($form_state['values'][$name]) && $form_state['values'][$name] === $button_value) {
  1140. $values[$name] = $button_value;
  1141. }
  1142. }
  1143. $form_state['values'] = $values;
  1144. }
  1145. }
  1146. /**
  1147. * Redirects the user to a URL after a form has been processed.
  1148. *
  1149. * After a form is submitted and processed, normally the user should be
  1150. * redirected to a new destination page. This function figures out what that
  1151. * destination should be, based on the $form_state array and the 'destination'
  1152. * query string in the request URL, and redirects the user there.
  1153. *
  1154. * Usually (for exceptions, see below) $form_state['redirect'] determines where
  1155. * to redirect the user. This can be set either to a string (the path to
  1156. * redirect to), or an array of arguments for drupal_goto(). If
  1157. * $form_state['redirect'] is missing, the user is usually (again, see below for
  1158. * exceptions) redirected back to the page they came from, where they should see
  1159. * a fresh, unpopulated copy of the form.
  1160. *
  1161. * Here is an example of how to set up a form to redirect to the path 'node':
  1162. * @code
  1163. * $form_state['redirect'] = 'node';
  1164. * @endcode
  1165. * And here is an example of how to redirect to 'node/123?foo=bar#baz':
  1166. * @code
  1167. * $form_state['redirect'] = array(
  1168. * 'node/123',
  1169. * array(
  1170. * 'query' => array(
  1171. * 'foo' => 'bar',
  1172. * ),
  1173. * 'fragment' => 'baz',
  1174. * ),
  1175. * );
  1176. * @endcode
  1177. *
  1178. * There are several exceptions to the "usual" behavior described above:
  1179. * - If $form_state['programmed'] is TRUE, the form submission was usually
  1180. * invoked via drupal_form_submit(), so any redirection would break the script
  1181. * that invoked drupal_form_submit() and no redirection is done.
  1182. * - If $form_state['rebuild'] is TRUE, the form is being rebuilt, and no
  1183. * redirection is done.
  1184. * - If $form_state['no_redirect'] is TRUE, redirection is disabled. This is
  1185. * set, for instance, by ajax_get_form() to prevent redirection in Ajax
  1186. * callbacks. $form_state['no_redirect'] should never be set or altered by
  1187. * form builder functions or form validation/submit handlers.
  1188. * - If $form_state['redirect'] is set to FALSE, redirection is disabled.
  1189. * - If none of the above conditions has prevented redirection, then the
  1190. * redirect is accomplished by calling drupal_goto(), passing in the value of
  1191. * $form_state['redirect'] if it is set, or the current path if it is
  1192. * not. drupal_goto() preferentially uses the value of $_GET['destination']
  1193. * (the 'destination' URL query string) if it is present, so this will
  1194. * override any values set by $form_state['redirect']. Note that during
  1195. * installation, install_goto() is called in place of drupal_goto().
  1196. *
  1197. * @param $form_state
  1198. * An associative array containing the current state of the form.
  1199. *
  1200. * @see drupal_process_form()
  1201. * @see drupal_build_form()
  1202. */
  1203. function drupal_redirect_form($form_state) {
  1204. // Skip redirection for form submissions invoked via drupal_form_submit().
  1205. if (!empty($form_state['programmed'])) {
  1206. return;
  1207. }
  1208. // Skip redirection if rebuild is activated.
  1209. if (!empty($form_state['rebuild'])) {
  1210. return;
  1211. }
  1212. // Skip redirection if it was explicitly disallowed.
  1213. if (!empty($form_state['no_redirect'])) {
  1214. return;
  1215. }
  1216. // Only invoke drupal_goto() if redirect value was not set to FALSE.
  1217. if (!isset($form_state['redirect']) || $form_state['redirect'] !== FALSE) {
  1218. if (isset($form_state['redirect'])) {
  1219. if (is_array($form_state['redirect'])) {
  1220. call_user_func_array('drupal_goto', $form_state['redirect']);
  1221. }
  1222. else {
  1223. // This function can be called from the installer, which guarantees
  1224. // that $redirect will always be a string, so catch that case here
  1225. // and use the appropriate redirect function.
  1226. $function = drupal_installation_attempted() ? 'install_goto' : 'drupal_goto';
  1227. $function($form_state['redirect']);
  1228. }
  1229. }
  1230. drupal_goto(current_path(), array('query' => drupal_get_query_parameters()));
  1231. }
  1232. }
  1233. /**
  1234. * Performs validation on form elements.
  1235. *
  1236. * First ensures required fields are completed, #maxlength is not exceeded, and
  1237. * selected options were in the list of options given to the user. Then calls
  1238. * user-defined validators.
  1239. *
  1240. * @param $elements
  1241. * An associative array containing the structure of the form.
  1242. * @param $form_state
  1243. * A keyed array containing the current state of the form. The current
  1244. * user-submitted data is stored in $form_state['values'], though
  1245. * form validation functions are passed an explicit copy of the
  1246. * values for the sake of simplicity. Validation handlers can also
  1247. * $form_state to pass information on to submit handlers. For example:
  1248. * $form_state['data_for_submission'] = $data;
  1249. * This technique is useful when validation requires file parsing,
  1250. * web service requests, or other expensive requests that should
  1251. * not be repeated in the submission step.
  1252. * @param $form_id
  1253. * A unique string identifying the form for validation, submission,
  1254. * theming, and hook_form_alter functions.
  1255. */
  1256. function _form_validate(&$elements, &$form_state, $form_id = NULL) {
  1257. // Also used in the installer, pre-database setup.
  1258. $t = get_t();
  1259. // Recurse through all children.
  1260. foreach (element_children($elements) as $key) {
  1261. if (isset($elements[$key]) && $elements[$key]) {
  1262. _form_validate($elements[$key], $form_state);
  1263. }
  1264. }
  1265. // Validate the current input.
  1266. if (!isset($elements['#validated']) || !$elements['#validated']) {
  1267. // The following errors are always shown.
  1268. if (isset($elements['#needs_validation'])) {
  1269. // Verify that the value is not longer than #maxlength.
  1270. if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
  1271. 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']))));
  1272. }
  1273. if (isset($elements['#options']) && isset($elements['#value'])) {
  1274. if ($elements['#type'] == 'select') {
  1275. $options = form_options_flatten($elements['#options']);
  1276. }
  1277. else {
  1278. $options = $elements['#options'];
  1279. }
  1280. if (is_array($elements['#value'])) {
  1281. $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
  1282. foreach ($value as $v) {
  1283. if (!isset($options[$v])) {
  1284. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1285. watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1286. }
  1287. }
  1288. }
  1289. // Non-multiple select fields always have a value in HTML. If the user
  1290. // does not change the form, it will be the value of the first option.
  1291. // Because of this, form validation for the field will almost always
  1292. // pass, even if the user did not select anything. To work around this
  1293. // browser behavior, required select fields without a #default_value get
  1294. // an additional, first empty option. In case the submitted value is
  1295. // identical to the empty option's value, we reset the element's value
  1296. // to NULL to trigger the regular #required handling below.
  1297. // @see form_process_select()
  1298. elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
  1299. $elements['#value'] = NULL;
  1300. form_set_value($elements, NULL, $form_state);
  1301. }
  1302. elseif (!isset($options[$elements['#value']])) {
  1303. form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
  1304. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
  1305. }
  1306. }
  1307. }
  1308. // While this element is being validated, it may be desired that some calls
  1309. // to form_set_error() be suppressed and not result in a form error, so
  1310. // that a button that implements low-risk functionality (such as "Previous"
  1311. // or "Add more") that doesn't require all user input to be valid can still
  1312. // have its submit handlers triggered. The triggering element's
  1313. // #limit_validation_errors property contains the information for which
  1314. // errors are needed, and all other errors are to be suppressed. The
  1315. // #limit_validation_errors property is ignored if submit handlers will run,
  1316. // but the element doesn't have a #submit property, because it's too large a
  1317. // security risk to have any invalid user input when executing form-level
  1318. // submit handlers.
  1319. if (isset($form_state['triggering_element']['#limit_validation_errors']) && ($form_state['triggering_element']['#limit_validation_errors'] !== FALSE) && !($form_state['submitted'] && !isset($form_state['triggering_element']['#submit']))) {
  1320. form_set_error(NULL, '', $form_state['triggering_element']['#limit_validation_errors']);
  1321. }
  1322. // If submit handlers won't run (due to the submission having been triggered
  1323. // by an element whose #executes_submit_callback property isn't TRUE), then
  1324. // it's safe to suppress all validation errors, and we do so by default,
  1325. // which is particularly useful during an Ajax submission triggered by a
  1326. // non-button. An element can override this default by setting the
  1327. // #limit_validation_errors property. For button element types,
  1328. // #limit_validation_errors defaults to FALSE (via system_element_info()),
  1329. // so that full validation is their default behavior.
  1330. elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) {
  1331. form_set_error(NULL, '', array());
  1332. }
  1333. // As an extra security measure, explicitly turn off error suppression if
  1334. // one of the above conditions wasn't met. Since this is also done at the
  1335. // end of this function, doing it here is only to handle the rare edge case
  1336. // where a validate handler invokes form processing of another form.
  1337. else {
  1338. drupal_static_reset('form_set_error:limit_validation_errors');
  1339. }
  1340. // Make sure a value is passed when the field is required.
  1341. if (isset($elements['#needs_validation']) && $elements['#required']) {
  1342. // A simple call to empty() will not cut it here as some fields, like
  1343. // checkboxes, can return a valid value of '0'. Instead, check the
  1344. // length if it's a string, and the item count if it's an array.
  1345. // An unchecked checkbox has a #value of integer 0, different than string
  1346. // '0', which could be a valid value.
  1347. $is_empty_multiple = (!count($elements['#value']));
  1348. $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
  1349. $is_empty_value = ($elements['#value'] === 0);
  1350. if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
  1351. // Although discouraged, a #title is not mandatory for form elements. In
  1352. // case there is no #title, we cannot set a form error message.
  1353. // Instead of setting no #title, form constructors are encouraged to set
  1354. // #title_display to 'invisible' to improve accessibility.
  1355. if (isset($elements['#title'])) {
  1356. form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
  1357. }
  1358. else {
  1359. form_error($elements);
  1360. }
  1361. }
  1362. }
  1363. // Call user-defined form level validators.
  1364. if (isset($form_id)) {
  1365. form_execute_handlers('validate', $elements, $form_state);
  1366. }
  1367. // Call any element-specific validators. These must act on the element
  1368. // #value data.
  1369. elseif (isset($elements['#element_validate'])) {
  1370. foreach ($elements['#element_validate'] as $function) {
  1371. $function($elements, $form_state, $form_state['complete form']);
  1372. }
  1373. }
  1374. $elements['#validated'] = TRUE;
  1375. }
  1376. // Done validating this element, so turn off error suppression.
  1377. // _form_validate() turns it on again when starting on the next element, if
  1378. // it's still appropriate to do so.
  1379. drupal_static_reset('form_set_error:limit_validation_errors');
  1380. }
  1381. /**
  1382. * Executes custom validation and submission handlers for a given form.
  1383. *
  1384. * Button-specific handlers are checked first. If none exist, the function
  1385. * falls back to form-level handlers.
  1386. *
  1387. * @param $type
  1388. * The type of handler to execute. 'validate' or 'submit' are the
  1389. * defaults used by Form API.
  1390. * @param $form
  1391. * An associative array containing the structure of the form.
  1392. * @param $form_state
  1393. * A keyed array containing the current state of the form. If the user
  1394. * submitted the form by clicking a button with custom handler functions
  1395. * defined, those handlers will be stored here.
  1396. */
  1397. function form_execute_handlers($type, &$form, &$form_state) {
  1398. $return = FALSE;
  1399. // If there was a button pressed, use its handlers.
  1400. if (isset($form_state[$type . '_handlers'])) {
  1401. $handlers = $form_state[$type . '_handlers'];
  1402. }
  1403. // Otherwise, check for a form-level handler.
  1404. elseif (isset($form['#' . $type])) {
  1405. $handlers = $form['#' . $type];
  1406. }
  1407. else {
  1408. $handlers = array();
  1409. }
  1410. foreach ($handlers as $function) {
  1411. // Check if a previous _submit handler has set a batch, but make sure we
  1412. // do not react to a batch that is already being processed (for instance
  1413. // if a batch operation performs a drupal_form_submit()).
  1414. if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['id'])) {
  1415. // Some previous submit handler has set a batch. To ensure correct
  1416. // execution order, store the call in a special 'control' batch set.
  1417. // See _batch_next_set().
  1418. $batch['sets'][] = array('form_submit' => $function);
  1419. $batch['has_form_submits'] = TRUE;
  1420. }
  1421. else {
  1422. $function($form, $form_state);
  1423. }
  1424. $return = TRUE;
  1425. }
  1426. return $return;
  1427. }
  1428. /**
  1429. * Files an error against a form element.
  1430. *
  1431. * When a validation error is detected, the validator calls form_set_error() to
  1432. * indicate which element needs to be changed and provide an error message. This
  1433. * causes the Form API to not execute the form submit handlers, and instead to
  1434. * re-display the form to the user with the corresponding elements rendered with
  1435. * an 'error' CSS class (shown as red by default).
  1436. *
  1437. * The standard form_set_error() behavior can be changed if a button provides
  1438. * the #limit_validation_errors property. Multistep forms not wanting to
  1439. * validate the whole form can set #limit_validation_errors on buttons to
  1440. * limit validation errors to only certain elements. For example, pressing the
  1441. * "Previous" button in a multistep form should not fire validation errors just
  1442. * because the current step has invalid values. If #limit_validation_errors is
  1443. * set on a clicked button, the button must also define a #submit property
  1444. * (may be set to an empty array). Any #submit handlers will be executed even if
  1445. * there is invalid input, so extreme care should be taken with respect to any
  1446. * actions taken by them. This is typically not a problem with buttons like
  1447. * "Previous" or "Add more" that do not invoke persistent storage of the
  1448. * submitted form values. Do not use the #limit_validation_errors property on
  1449. * buttons that trigger saving of form values to the database.
  1450. *
  1451. * The #limit_validation_errors property is a list of "sections" within
  1452. * $form_state['values'] that must contain valid values. Each "section" is an
  1453. * array with the ordered set of keys needed to reach that part of
  1454. * $form_state['values'] (i.e., the #parents property of the element).
  1455. *
  1456. * Example 1: Allow the "Previous" button to function, regardless of whether any
  1457. * user input is valid.
  1458. *
  1459. * @code
  1460. * $form['actions']['previous'] = array(
  1461. * '#type' => 'submit',
  1462. * '#value' => t('Previous'),
  1463. * '#limit_validation_errors' => array(), // No validation.
  1464. * '#submit' => array('some_submit_function'), // #submit required.
  1465. * );
  1466. * @endcode
  1467. *
  1468. * Example 2: Require some, but not all, user input to be valid to process the
  1469. * submission of a "Previous" button.
  1470. *
  1471. * @code
  1472. * $form['actions']['previous'] = array(
  1473. * '#type' => 'submit',
  1474. * '#value' => t('Previous'),
  1475. * '#limit_validation_errors' => array(
  1476. * array('step1'), // Validate $form_state['values']['step1'].
  1477. * array('foo', 'bar'), // Validate $form_state['values']['foo']['bar'].
  1478. * ),
  1479. * '#submit' => array('some_submit_function'), // #submit required.
  1480. * );
  1481. * @endcode
  1482. *
  1483. * This will require $form_state['values']['step1'] and everything within it
  1484. * (for example, $form_state['values']['step1']['choice']) to be valid, so
  1485. * calls to form_set_error('step1', $message) or
  1486. * form_set_error('step1][choice', $message) will prevent the submit handlers
  1487. * from running, and result in the error message being displayed to the user.
  1488. * However, calls to form_set_error('step2', $message) and
  1489. * form_set_error('step2][groupX][choiceY', $message) will be suppressed,
  1490. * resulting in the message not being displayed to the user, and the submit
  1491. * handlers will run despite $form_state['values']['step2'] and
  1492. * $form_state['values']['step2']['groupX']['choiceY'] containing invalid
  1493. * values. Errors for an invalid $form_state['values']['foo'] will be
  1494. * suppressed, but errors flagging invalid values for
  1495. * $form_state['values']['foo']['bar'] and everything within it will be
  1496. * flagged and submission prevented.
  1497. *
  1498. * Partial form validation is implemented by suppressing errors rather than by
  1499. * skipping the input processing and validation steps entirely, because some
  1500. * forms have button-level submit handlers that call Drupal API functions that
  1501. * assume that certain data exists within $form_state['values'], and while not
  1502. * doing anything with that data that requires it to be valid, PHP errors
  1503. * would be triggered if the input processing and validation steps were fully
  1504. * skipped.
  1505. *
  1506. * @param $name
  1507. * The name of the form element. If the #parents property of your form
  1508. * element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
  1509. * or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
  1510. * element where the #parents array starts with 'foo'.
  1511. * @param $message
  1512. * The error message to present to the user.
  1513. * @param $limit_validation_errors
  1514. * Internal use only. The #limit_validation_errors property of the clicked
  1515. * button, if it exists.
  1516. *
  1517. * @return
  1518. * Return value is for internal use only. To get a list of errors, use
  1519. * form_get_errors() or form_get_error().
  1520. *
  1521. * @see http://drupal.org/node/370537
  1522. * @see http://drupal.org/node/763376
  1523. */
  1524. function form_set_error($name = NULL, $message = '', $limit_validation_errors = NULL) {
  1525. $form = &drupal_static(__FUNCTION__, array());
  1526. $sections = &drupal_static(__FUNCTION__ . ':limit_validation_errors');
  1527. if (isset($limit_validation_errors)) {
  1528. $sections = $limit_validation_errors;
  1529. }
  1530. if (isset($name) && !isset($form[$name])) {
  1531. $record = TRUE;
  1532. if (isset($sections)) {
  1533. // #limit_validation_errors is an array of "sections" within which user
  1534. // input must be valid. If the element is within one of these sections,
  1535. // the error must be recorded. Otherwise, it can be suppressed.
  1536. // #limit_validation_errors can be an empty array, in which case all
  1537. // errors are suppressed. For example, a "Previous" button might want its
  1538. // submit action to be triggered even if none of the submitted values are
  1539. // valid.
  1540. $record = FALSE;
  1541. foreach ($sections as $section) {
  1542. // Exploding by '][' reconstructs the element's #parents. If the
  1543. // reconstructed #parents begin with the same keys as the specified
  1544. // section, then the element's values are within the part of
  1545. // $form_state['values'] that the clicked button requires to be valid,
  1546. // so errors for this element must be recorded. As the exploded array
  1547. // will all be strings, we need to cast every value of the section
  1548. // array to string.
  1549. if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
  1550. $record = TRUE;
  1551. break;
  1552. }
  1553. }
  1554. }
  1555. if ($record) {
  1556. $form[$name] = $message;
  1557. if ($message) {
  1558. drupal_set_message($message, 'error');
  1559. }
  1560. }
  1561. }
  1562. return $form;
  1563. }
  1564. /**
  1565. * Clears all errors against all form elements made by form_set_error().
  1566. */
  1567. function form_clear_error() {
  1568. drupal_static_reset('form_set_error');
  1569. }
  1570. /**
  1571. * Returns an associative array of all errors.
  1572. */
  1573. function form_get_errors() {
  1574. $form = form_set_error();
  1575. if (!empty($form)) {
  1576. return $form;
  1577. }
  1578. }
  1579. /**
  1580. * Returns the error message filed against the given form element.
  1581. *
  1582. * Form errors higher up in the form structure override deeper errors as well as
  1583. * errors on the element itself.
  1584. */
  1585. function form_get_error($element) {
  1586. $form = form_set_error();
  1587. $parents = array();
  1588. foreach ($element['#parents'] as $parent) {
  1589. $parents[] = $parent;
  1590. $key = implode('][', $parents);
  1591. if (isset($form[$key])) {
  1592. return $form[$key];
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. * Flags an element as having an error.
  1598. */
  1599. function form_error(&$element, $message = '') {
  1600. form_set_error(implode('][', $element['#parents']), $message);
  1601. }
  1602. /**
  1603. * Builds and processes all elements in the structured form array.
  1604. *
  1605. * Adds any required properties to each element, maps the incoming input data
  1606. * to the proper elements, and executes any #process handlers attached to a
  1607. * specific element.
  1608. *
  1609. * This is one of the three primary functions that recursively iterates a form
  1610. * array. This one does it for completing the form building process. The other
  1611. * two are _form_validate() (invoked via drupal_validate_form() and used to
  1612. * invoke validation logic for each element) and drupal_render() (for rendering
  1613. * each element). Each of these three pipelines provides ample opportunity for
  1614. * modules to customize what happens. For example, during this function's life
  1615. * cycle, the following functions get called for each element:
  1616. * - $element['#value_callback']: A function that implements how user input is
  1617. * mapped to an element's #value property. This defaults to a function named
  1618. * 'form_type_TYPE_value' where TYPE is $element['#type'].
  1619. * - $element['#process']: An array of functions called after user input has
  1620. * been mapped to the element's #value property. These functions can be used
  1621. * to dynamically add child elements: for example, for the 'date' element
  1622. * type, one of the functions in this array is form_process_date(), which adds
  1623. * the individual 'year', 'month', 'day', etc. child elements. These functions
  1624. * can also be used to set additional properties or implement special logic
  1625. * other than adding child elements: for example, for the 'fieldset' element
  1626. * type, one of the functions in this array is form_process_fieldset(), which
  1627. * adds the attributes and JavaScript needed to make the fieldset collapsible
  1628. * if the #collapsible property is set. The #process functions are called in
  1629. * preorder traversal, meaning they are called for the parent element first,
  1630. * then for the child elements.
  1631. * - $element['#after_build']: An array of functions called after form_builder()
  1632. * is done with its processing of the element. These are called in postorder
  1633. * traversal, meaning they are called for the child elements first, then for
  1634. * the parent element.
  1635. * There are similar properties containing callback functions invoked by
  1636. * _form_validate() and drupal_render(), appropriate for those operations.
  1637. *
  1638. * Developers are strongly encouraged to integrate the functionality needed by
  1639. * their form or module within one of these three pipelines, using the
  1640. * appropriate callback property, rather than implementing their own recursive
  1641. * traversal of a form array. This facilitates proper integration between
  1642. * multiple modules. For example, module developers are familiar with the
  1643. * relative order in which hook_form_alter() implementations and #process
  1644. * functions run. A custom traversal function that affects the building of a
  1645. * form is likely to not integrate with hook_form_alter() and #process in the
  1646. * expected way. Also, deep recursion within PHP is both slow and memory
  1647. * intensive, so it is best to minimize how often it's done.
  1648. *
  1649. * As stated above, each element's #process functions are executed after its
  1650. * #value has been set. This enables those functions to execute conditional
  1651. * logic based on the current value. However, all of form_builder() runs before
  1652. * drupal_validate_form() is called, so during #process function execution, the
  1653. * element's #value has not yet been validated, so any code that requires
  1654. * validated values must reside within a submit handler.
  1655. *
  1656. * As a security measure, user input is used for an element's #value only if the
  1657. * element exists within $form, is not disabled (as per the #disabled property),
  1658. * and can be accessed (as per the #access property, except that forms submitted
  1659. * using drupal_form_submit() bypass #access restrictions). When user input is
  1660. * ignored due to #disabled and #access restrictions, the element's default
  1661. * value is used.
  1662. *
  1663. * Because of the preorder traversal, where #process functions of an element run
  1664. * before user input for its child elements is processed, and because of the
  1665. * Form API security of user input processing with respect to #access and
  1666. * #disabled described above, this generally means that #process functions
  1667. * should not use an element's (unvalidated) #value to affect the #disabled or
  1668. * #access of child elements. Use-cases where a developer may be tempted to
  1669. * implement such conditional logic usually fall into one of two categories:
  1670. * - Where user input from the current submission must affect the structure of a
  1671. * form, including properties like #access and #disabled that affect how the
  1672. * next submission needs to be processed, a multi-step workflow is needed.
  1673. * This is most commonly implemented with a submit handler setting persistent
  1674. * data within $form_state based on *validated* values in
  1675. * $form_state['values'] and setting $form_state['rebuild']. The form building
  1676. * functions must then be implemented to use the $form_state data to rebuild
  1677. * the form with the structure appropriate for the new state.
  1678. * - Where user input must affect the rendering of the form without affecting
  1679. * its structure, the necessary conditional rendering logic should reside
  1680. * within functions that run during the rendering phase (#pre_render, #theme,
  1681. * #theme_wrappers, and #post_render).
  1682. *
  1683. * @param $form_id
  1684. * A unique string identifying the form for validation, submission,
  1685. * theming, and hook_form_alter functions.
  1686. * @param $element
  1687. * An associative array containing the structure of the current element.
  1688. * @param $form_state
  1689. * A keyed array containing the current state of the form. In this
  1690. * context, it is used to accumulate information about which button
  1691. * was clicked when the form was submitted, as well as the sanitized
  1692. * $_POST data.
  1693. */
  1694. function form_builder($form_id, &$element, &$form_state) {
  1695. // Initialize as unprocessed.
  1696. $element['#processed'] = FALSE;
  1697. // Use element defaults.
  1698. if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
  1699. // Overlay $info onto $element, retaining preexisting keys in $element.
  1700. $element += $info;
  1701. $element['#defaults_loaded'] = TRUE;
  1702. }
  1703. // Assign basic defaults common for all form elements.
  1704. $element += array(
  1705. '#required' => FALSE,
  1706. '#attributes' => array(),
  1707. '#title_display' => 'before',
  1708. );
  1709. // Special handling if we're on the top level form element.
  1710. if (isset($element['#type']) && $element['#type'] == 'form') {
  1711. if (!empty($element['#https']) && variable_get('https', FALSE) &&
  1712. !url_is_external($element['#action'])) {
  1713. global $base_root;
  1714. // Not an external URL so ensure that it is secure.
  1715. $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
  1716. }
  1717. // Store a reference to the complete form in $form_state prior to building
  1718. // the form. This allows advanced #process and #after_build callbacks to
  1719. // perform changes elsewhere in the form.
  1720. $form_state['complete form'] = &$element;
  1721. // Set a flag if we have a correct form submission. This is always TRUE for
  1722. // programmed forms coming from drupal_form_submit(), or if the form_id coming
  1723. // from the POST data is set and matches the current form_id.
  1724. if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
  1725. $form_state['process_input'] = TRUE;
  1726. }
  1727. else {
  1728. $form_state['process_input'] = FALSE;
  1729. }
  1730. // All form elements should have an #array_parents property.
  1731. $element['#array_parents'] = array();
  1732. }
  1733. if (!isset($element['#id'])) {
  1734. $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
  1735. }
  1736. // Handle input elements.
  1737. if (!empty($element['#input'])) {
  1738. _form_builder_handle_input_element($form_id, $element, $form_state);
  1739. }
  1740. // Allow for elements to expand to multiple elements, e.g., radios,
  1741. // checkboxes and files.
  1742. if (isset($element['#process']) && !$element['#processed']) {
  1743. foreach ($element['#process'] as $process) {
  1744. $element = $process($element, $form_state, $form_state['complete form']);
  1745. }
  1746. $element['#processed'] = TRUE;
  1747. }
  1748. // We start off assuming all form elements are in the correct order.
  1749. $element['#sorted'] = TRUE;
  1750. // Recurse through all child elements.
  1751. $count = 0;
  1752. foreach (element_children($element) as $key) {
  1753. // Prior to checking properties of child elements, their default properties
  1754. // need to be loaded.
  1755. if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
  1756. $element[$key] += $info;
  1757. $element[$key]['#defaults_loaded'] = TRUE;
  1758. }
  1759. // Don't squash an existing tree value.
  1760. if (!isset($element[$key]['#tree'])) {
  1761. $element[$key]['#tree'] = $element['#tree'];
  1762. }
  1763. // Deny access to child elements if parent is denied.
  1764. if (isset($element['#access']) && !$element['#access']) {
  1765. $element[$key]['#access'] = FALSE;
  1766. }
  1767. // Make child elements inherit their parent's #disabled and #allow_focus
  1768. // values unless they specify their own.
  1769. foreach (array('#disabled', '#allow_focus') as $property) {
  1770. if (isset($element[$property]) && !isset($element[$key][$property])) {
  1771. $element[$key][$property] = $element[$property];
  1772. }
  1773. }
  1774. // Don't squash existing parents value.
  1775. if (!isset($element[$key]['#parents'])) {
  1776. // Check to see if a tree of child elements is present. If so,
  1777. // continue down the tree if required.
  1778. $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], array($key)) : array($key);
  1779. }
  1780. // Ensure #array_parents follows the actual form structure.
  1781. $array_parents = $element['#array_parents'];
  1782. $array_parents[] = $key;
  1783. $element[$key]['#array_parents'] = $array_parents;
  1784. // Assign a decimal placeholder weight to preserve original array order.
  1785. if (!isset($element[$key]['#weight'])) {
  1786. $element[$key]['#weight'] = $count/1000;
  1787. }
  1788. else {
  1789. // If one of the child elements has a weight then we will need to sort
  1790. // later.
  1791. unset($element['#sorted']);
  1792. }
  1793. $element[$key] = form_builder($form_id, $element[$key], $form_state);
  1794. $count++;
  1795. }
  1796. // The #after_build flag allows any piece of a form to be altered
  1797. // after normal input parsing has been completed.
  1798. if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
  1799. foreach ($element['#after_build'] as $function) {
  1800. $element = $function($element, $form_state);
  1801. }
  1802. $element['#after_build_done'] = TRUE;
  1803. }
  1804. // If there is a file element, we need to flip a flag so later the
  1805. // form encoding can be set.
  1806. if (isset($element['#type']) && $element['#type'] == 'file') {
  1807. $form_state['has_file_element'] = TRUE;
  1808. }
  1809. // Final tasks for the form element after form_builder() has run for all other
  1810. // elements.
  1811. if (isset($element['#type']) && $element['#type'] == 'form') {
  1812. // If there is a file element, we set the form encoding.
  1813. if (isset($form_state['has_file_element'])) {
  1814. $element['#attributes']['enctype'] = 'multipart/form-data';
  1815. }
  1816. // If a form contains a single textfield, and the ENTER key is pressed
  1817. // within it, Internet Explorer submits the form with no POST data
  1818. // identifying any submit button. Other browsers submit POST data as though
  1819. // the user clicked the first button. Therefore, to be as consistent as we
  1820. // can be across browsers, if no 'triggering_element' has been identified
  1821. // yet, default it to the first button.
  1822. if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
  1823. $form_state['triggering_element'] = $form_state['buttons'][0];
  1824. }
  1825. // If the triggering element specifies "button-level" validation and submit
  1826. // handlers to run instead of the default form-level ones, then add those to
  1827. // the form state.
  1828. foreach (array('validate', 'submit') as $type) {
  1829. if (isset($form_state['triggering_element']['#' . $type])) {
  1830. $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
  1831. }
  1832. }
  1833. // If the triggering element executes submit handlers, then set the form
  1834. // state key that's needed for those handlers to run.
  1835. if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
  1836. $form_state['submitted'] = TRUE;
  1837. }
  1838. // Special processing if the triggering element is a button.
  1839. if (isset($form_state['triggering_element']['#button_type'])) {
  1840. // Because there are several ways in which the triggering element could
  1841. // have been determined (including from input variables set by JavaScript
  1842. // or fallback behavior implemented for IE), and because buttons often
  1843. // have their #name property not derived from their #parents property, we
  1844. // can't assume that input processing that's happened up until here has
  1845. // resulted in $form_state['values'][BUTTON_NAME] being set. But it's
  1846. // common for forms to have several buttons named 'op' and switch on
  1847. // $form_state['values']['op'] during submit handler execution.
  1848. $form_state['values'][$form_state['triggering_element']['#name']] = $form_state['triggering_element']['#value'];
  1849. // @todo Legacy support. Remove in Drupal 8.
  1850. $form_state['clicked_button'] = $form_state['triggering_element'];
  1851. }
  1852. }
  1853. return $element;
  1854. }
  1855. /**
  1856. * Adds the #name and #value properties of an input element before rendering.
  1857. */
  1858. function _form_builder_handle_input_element($form_id, &$element, &$form_state) {
  1859. if (!isset($element['#name'])) {
  1860. $name = array_shift($element['#parents']);
  1861. $element['#name'] = $name;
  1862. if ($element['#type'] == 'file') {
  1863. // To make it easier to handle $_FILES in file.inc, we place all
  1864. // file fields in the 'files' array. Also, we do not support
  1865. // nested file names.
  1866. $element['#name'] = 'files[' . $element['#name'] . ']';
  1867. }
  1868. elseif (count($element['#parents'])) {
  1869. $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
  1870. }
  1871. array_unshift($element['#parents'], $name);
  1872. }
  1873. // Setting #disabled to TRUE results in user input being ignored, regardless
  1874. // of how the element is themed or whether JavaScript is used to change the
  1875. // control's attributes. However, it's good UI to let the user know that input
  1876. // is not wanted for the control. HTML supports two attributes for this:
  1877. // http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form wants
  1878. // to start a control off with one of these attributes for UI purposes only,
  1879. // but still allow input to be processed if it's sumitted, it can set the
  1880. // desired attribute in #attributes directly rather than using #disabled.
  1881. // However, developers should think carefully about the accessibility
  1882. // implications of doing so: if the form expects input to be enterable under
  1883. // some condition triggered by JavaScript, how would someone who has
  1884. // JavaScript disabled trigger that condition? Instead, developers should
  1885. // consider whether a multi-step form would be more appropriate (#disabled can
  1886. // be changed from step to step). If one still decides to use JavaScript to
  1887. // affect when a control is enabled, then it is best for accessibility for the
  1888. // control to be enabled in the HTML, and disabled by JavaScript on document
  1889. // ready.
  1890. if (!empty($element['#disabled'])) {
  1891. if (!empty($element['#allow_focus'])) {
  1892. $element['#attributes']['readonly'] = 'readonly';
  1893. }
  1894. else {
  1895. $element['#attributes']['disabled'] = 'disabled';
  1896. }
  1897. }
  1898. // With JavaScript or other easy hacking, input can be submitted even for
  1899. // elements with #access=FALSE or #disabled=TRUE. For security, these must
  1900. // not be processed. Forms that set #disabled=TRUE on an element do not
  1901. // expect input for the element, and even forms submitted with
  1902. // drupal_form_submit() must not be able to get around this. Forms that set
  1903. // #access=FALSE on an element usually allow access for some users, so forms
  1904. // submitted with drupal_form_submit() may bypass access restriction and be
  1905. // treated as high-privilege users instead.
  1906. $process_input = empty($element['#disabled']) && (($form_state['programmed'] && $form_state['programmed_bypass_access_check']) || ($form_state['process_input'] && (!isset($element['#access']) || $element['#access'])));
  1907. // Set the element's #value property.
  1908. if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
  1909. $value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
  1910. if ($process_input) {
  1911. // Get the input for the current element. NULL values in the input need to
  1912. // be explicitly distinguished from missing input. (see below)
  1913. $input_exists = NULL;
  1914. $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
  1915. // For browser-submitted forms, the submitted values do not contain values
  1916. // for certain elements (empty multiple select, unchecked checkbox).
  1917. // During initial form processing, we add explicit NULL values for such
  1918. // elements in $form_state['input']. When rebuilding the form, we can
  1919. // distinguish elements having NULL input from elements that were not part
  1920. // of the initially submitted form and can therefore use default values
  1921. // for the latter, if required. Programmatically submitted forms can
  1922. // submit explicit NULL values when calling drupal_form_submit(), so we do
  1923. // not modify $form_state['input'] for them.
  1924. if (!$input_exists && !$form_state['rebuild'] && !$form_state['programmed']) {
  1925. // Add the necessary parent keys to $form_state['input'] and sets the
  1926. // element's input value to NULL.
  1927. drupal_array_set_nested_value($form_state['input'], $element['#parents'], NULL);
  1928. $input_exists = TRUE;
  1929. }
  1930. // If we have input for the current element, assign it to the #value
  1931. // property, optionally filtered through $value_callback.
  1932. if ($input_exists) {
  1933. if (function_exists($value_callback)) {
  1934. $element['#value'] = $value_callback($element, $input, $form_state);
  1935. }
  1936. if (!isset($element['#value']) && isset($input)) {
  1937. $element['#value'] = $input;
  1938. }
  1939. }
  1940. // Mark all posted values for validation.
  1941. if (isset($element['#value']) || (!empty($element['#required']))) {
  1942. $element['#needs_validation'] = TRUE;
  1943. }
  1944. }
  1945. // Load defaults.
  1946. if (!isset($element['#value'])) {
  1947. // Call #type_value without a second argument to request default_value handling.
  1948. if (function_exists($value_callback)) {
  1949. $element['#value'] = $value_callback($element, FALSE, $form_state);
  1950. }
  1951. // Final catch. If we haven't set a value yet, use the explicit default value.
  1952. // Avoid image buttons (which come with garbage value), so we only get value
  1953. // for the button actually clicked.
  1954. if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
  1955. $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
  1956. }
  1957. }
  1958. }
  1959. // Determine which element (if any) triggered the submission of the form and
  1960. // keep track of all the clickable buttons in the form for
  1961. // form_state_values_clean(). Enforce the same input processing restrictions
  1962. // as above.
  1963. if ($process_input) {
  1964. // Detect if the element triggered the submission via Ajax.
  1965. if (_form_element_triggered_scripted_submission($element, $form_state)) {
  1966. $form_state['triggering_element'] = $element;
  1967. }
  1968. // If the form was submitted by the browser rather than via Ajax, then it
  1969. // can only have been triggered by a button, and we need to determine which
  1970. // button within the constraints of how browsers provide this information.
  1971. if (isset($element['#button_type'])) {
  1972. // All buttons in the form need to be tracked for
  1973. // form_state_values_clean() and for the form_builder() code that handles
  1974. // a form submission containing no button information in $_POST.
  1975. $form_state['buttons'][] = $element;
  1976. if (_form_button_was_clicked($element, $form_state)) {
  1977. $form_state['triggering_element'] = $element;
  1978. }
  1979. }
  1980. }
  1981. // Set the element's value in $form_state['values'], but only, if its key
  1982. // does not exist yet (a #value_callback may have already populated it).
  1983. if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  1984. form_set_value($element, $element['#value'], $form_state);
  1985. }
  1986. }
  1987. /**
  1988. * Detects if an element triggered the form submission via Ajax.
  1989. *
  1990. * This detects button or non-button controls that trigger a form submission via
  1991. * Ajax or some other scriptable environment. These environments can set the
  1992. * special input key '_triggering_element_name' to identify the triggering
  1993. * element. If the name alone doesn't identify the element uniquely, the input
  1994. * key '_triggering_element_value' may also be set to require a match on element
  1995. * value. An example where this is needed is if there are several buttons all
  1996. * named 'op', and only differing in their value.
  1997. */
  1998. function _form_element_triggered_scripted_submission($element, &$form_state) {
  1999. if (!empty($form_state['input']['_triggering_element_name']) && $element['#name'] == $form_state['input']['_triggering_element_name']) {
  2000. if (empty($form_state['input']['_triggering_element_value']) || $form_state['input']['_triggering_element_value'] == $element['#value']) {
  2001. return TRUE;
  2002. }
  2003. }
  2004. return FALSE;
  2005. }
  2006. /**
  2007. * Determines if a given button triggered the form submission.
  2008. *
  2009. * This detects button controls that trigger a form submission by being clicked
  2010. * and having the click processed by the browser rather than being captured by
  2011. * JavaScript. Essentially, it detects if the button's name and value are part
  2012. * of the POST data, but with extra code to deal with the convoluted way in
  2013. * which browsers submit data for image button clicks.
  2014. *
  2015. * This does not detect button clicks processed by Ajax (that is done in
  2016. * _form_element_triggered_scripted_submission()) and it does not detect form
  2017. * submissions from Internet Explorer in response to an ENTER key pressed in a
  2018. * textfield (form_builder() has extra code for that).
  2019. *
  2020. * Because this function contains only part of the logic needed to determine
  2021. * $form_state['triggering_element'], it should not be called from anywhere
  2022. * other than within the Form API. Form validation and submit handlers needing
  2023. * to know which button was clicked should get that information from
  2024. * $form_state['triggering_element'].
  2025. */
  2026. function _form_button_was_clicked($element, &$form_state) {
  2027. // First detect normal 'vanilla' button clicks. Traditionally, all
  2028. // standard buttons on a form share the same name (usually 'op'),
  2029. // and the specific return value is used to determine which was
  2030. // clicked. This ONLY works as long as $form['#name'] puts the
  2031. // value at the top level of the tree of $_POST data.
  2032. if (isset($form_state['input'][$element['#name']]) && $form_state['input'][$element['#name']] == $element['#value']) {
  2033. return TRUE;
  2034. }
  2035. // When image buttons are clicked, browsers do NOT pass the form element
  2036. // value in $_POST. Instead they pass an integer representing the
  2037. // coordinates of the click on the button image. This means that image
  2038. // buttons MUST have unique $form['#name'] values, but the details of
  2039. // their $_POST data should be ignored.
  2040. elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
  2041. return TRUE;
  2042. }
  2043. return FALSE;
  2044. }
  2045. /**
  2046. * Removes internal Form API elements and buttons from submitted form values.
  2047. *
  2048. * This function can be used when a module wants to store all submitted form
  2049. * values, for example, by serializing them into a single database column. In
  2050. * such cases, all internal Form API values and all form button elements should
  2051. * not be contained, and this function allows to remove them before the module
  2052. * proceeds to storage. Next to button elements, the following internal values
  2053. * are removed:
  2054. * - form_id
  2055. * - form_token
  2056. * - form_build_id
  2057. * - op
  2058. *
  2059. * @param $form_state
  2060. * A keyed array containing the current state of the form, including
  2061. * submitted form values; altered by reference.
  2062. */
  2063. function form_state_values_clean(&$form_state) {
  2064. // Remove internal Form API values.
  2065. unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);
  2066. // Remove button values.
  2067. // form_builder() collects all button elements in a form. We remove the button
  2068. // value separately for each button element.
  2069. foreach ($form_state['buttons'] as $button) {
  2070. // Remove this button's value from the submitted form values by finding
  2071. // the value corresponding to this button.
  2072. // We iterate over the #parents of this button and move a reference to
  2073. // each parent in $form_state['values']. For example, if #parents is:
  2074. // array('foo', 'bar', 'baz')
  2075. // then the corresponding $form_state['values'] part will look like this:
  2076. // array(
  2077. // 'foo' => array(
  2078. // 'bar' => array(
  2079. // 'baz' => 'button_value',
  2080. // ),
  2081. // ),
  2082. // )
  2083. // We start by (re)moving 'baz' to $last_parent, so we are able unset it
  2084. // at the end of the iteration. Initially, $values will contain a
  2085. // reference to $form_state['values'], but in the iteration we move the
  2086. // reference to $form_state['values']['foo'], and finally to
  2087. // $form_state['values']['foo']['bar'], which is the level where we can
  2088. // unset 'baz' (that is stored in $last_parent).
  2089. $parents = $button['#parents'];
  2090. $last_parent = array_pop($parents);
  2091. $key_exists = NULL;
  2092. $values = &drupal_array_get_nested_value($form_state['values'], $parents, $key_exists);
  2093. if ($key_exists && is_array($values)) {
  2094. unset($values[$last_parent]);
  2095. }
  2096. }
  2097. }
  2098. /**
  2099. * Determines the value for an image button form element.
  2100. *
  2101. * @param $form
  2102. * The form element whose value is being populated.
  2103. * @param $input
  2104. * The incoming input to populate the form element. If this is FALSE,
  2105. * the element's default value should be returned.
  2106. * @param $form_state
  2107. * A keyed array containing the current state of the form.
  2108. *
  2109. * @return
  2110. * The data that will appear in the $form_state['values'] collection
  2111. * for this element. Return nothing to use the default.
  2112. */
  2113. function form_type_image_button_value($form, $input, $form_state) {
  2114. if ($input !== FALSE) {
  2115. if (!empty($input)) {
  2116. // If we're dealing with Mozilla or Opera, we're lucky. It will
  2117. // return a proper value, and we can get on with things.
  2118. return $form['#return_value'];
  2119. }
  2120. else {
  2121. // Unfortunately, in IE we never get back a proper value for THIS
  2122. // form element. Instead, we get back two split values: one for the
  2123. // X and one for the Y coordinates on which the user clicked the
  2124. // button. We'll find this element in the #post data, and search
  2125. // in the same spot for its name, with '_x'.
  2126. $input = $form_state['input'];
  2127. foreach (explode('[', $form['#name']) as $element_name) {
  2128. // chop off the ] that may exist.
  2129. if (substr($element_name, -1) == ']') {
  2130. $element_name = substr($element_name, 0, -1);
  2131. }
  2132. if (!isset($input[$element_name])) {
  2133. if (isset($input[$element_name . '_x'])) {
  2134. return $form['#return_value'];
  2135. }
  2136. return NULL;
  2137. }
  2138. $input = $input[$element_name];
  2139. }
  2140. return $form['#return_value'];
  2141. }
  2142. }
  2143. }
  2144. /**
  2145. * Determines the value for a checkbox form element.
  2146. *
  2147. * @param $form
  2148. * The form element whose value is being populated.
  2149. * @param $input
  2150. * The incoming input to populate the form element. If this is FALSE,
  2151. * the element's default value should be returned.
  2152. *
  2153. * @return
  2154. * The data that will appear in the $element_state['values'] collection
  2155. * for this element. Return nothing to use the default.
  2156. */
  2157. function form_type_checkbox_value($element, $input = FALSE) {
  2158. if ($input === FALSE) {
  2159. // Use #default_value as the default value of a checkbox, except change
  2160. // NULL to 0, because _form_builder_handle_input_element() would otherwise
  2161. // replace NULL with empty string, but an empty string is a potentially
  2162. // valid value for a checked checkbox.
  2163. return isset($element['#default_value']) ? $element['#default_value'] : 0;
  2164. }
  2165. else {
  2166. // Checked checkboxes are submitted with a value (possibly '0' or ''):
  2167. // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
  2168. // For checked checkboxes, browsers submit the string version of
  2169. // #return_value, but we return the original #return_value. For unchecked
  2170. // checkboxes, browsers submit nothing at all, but
  2171. // _form_builder_handle_input_element() detects this, and calls this
  2172. // function with $input=NULL. Returning NULL from a value callback means to
  2173. // use the default value, which is not what is wanted when an unchecked
  2174. // checkbox is submitted, so we use integer 0 as the value indicating an
  2175. // unchecked checkbox. Therefore, modules must not use integer 0 as a
  2176. // #return_value, as doing so results in the checkbox always being treated
  2177. // as unchecked. The string '0' is allowed for #return_value. The most
  2178. // common use-case for setting #return_value to either 0 or '0' is for the
  2179. // first option within a 0-indexed array of checkboxes, and for this,
  2180. // form_process_checkboxes() uses the string rather than the integer.
  2181. return isset($input) ? $element['#return_value'] : 0;
  2182. }
  2183. }
  2184. /**
  2185. * Determines the value for a checkboxes form element.
  2186. *
  2187. * @param $element
  2188. * The form element whose value is being populated.
  2189. * @param $input
  2190. * The incoming input to populate the form element. If this is FALSE,
  2191. * the element's default value should be returned.
  2192. *
  2193. * @return
  2194. * The data that will appear in the $element_state['values'] collection
  2195. * for this element. Return nothing to use the default.
  2196. */
  2197. function form_type_checkboxes_value($element, $input = FALSE) {
  2198. if ($input === FALSE) {
  2199. $value = array();
  2200. $element += array('#default_value' => array());
  2201. foreach ($element['#default_value'] as $key) {
  2202. $value[$key] = $key;
  2203. }
  2204. return $value;
  2205. }
  2206. elseif (is_array($input)) {
  2207. // Programmatic form submissions use NULL to indicate that a checkbox
  2208. // should be unchecked; see drupal_form_submit(). We therefore remove all
  2209. // NULL elements from the array before constructing the return value, to
  2210. // simulate the behavior of web browsers (which do not send unchecked
  2211. // checkboxes to the server at all). This will not affect non-programmatic
  2212. // form submissions, since all values in $_POST are strings.
  2213. foreach ($input as $key => $value) {
  2214. if (!isset($value)) {
  2215. unset($input[$key]);
  2216. }
  2217. }
  2218. return drupal_map_assoc($input);
  2219. }
  2220. else {
  2221. return array();
  2222. }
  2223. }
  2224. /**
  2225. * Determines the value for a tableselect form element.
  2226. *
  2227. * @param $element
  2228. * The form element whose value is being populated.
  2229. * @param $input
  2230. * The incoming input to populate the form element. If this is FALSE,
  2231. * the element's default value should be returned.
  2232. *
  2233. * @return
  2234. * The data that will appear in the $element_state['values'] collection
  2235. * for this element. Return nothing to use the default.
  2236. */
  2237. function form_type_tableselect_value($element, $input = FALSE) {
  2238. // If $element['#multiple'] == FALSE, then radio buttons are displayed and
  2239. // the default value handling is used.
  2240. if (isset($element['#multiple']) && $element['#multiple']) {
  2241. // Checkboxes are being displayed with the default value coming from the
  2242. // keys of the #default_value property. This differs from the checkboxes
  2243. // element which uses the array values.
  2244. if ($input === FALSE) {
  2245. $value = array();
  2246. $element += array('#default_value' => array());
  2247. foreach ($element['#default_value'] as $key => $flag) {
  2248. if ($flag) {
  2249. $value[$key] = $key;
  2250. }
  2251. }
  2252. return $value;
  2253. }
  2254. else {
  2255. return is_array($input) ? drupal_map_assoc($input) : array();
  2256. }
  2257. }
  2258. }
  2259. /**
  2260. * Form value callback: Determines the value for a #type radios form element.
  2261. *
  2262. * @param $element
  2263. * The form element whose value is being populated.
  2264. * @param $input
  2265. * (optional) The incoming input to populate the form element. If FALSE, the
  2266. * element's default value is returned. Defaults to FALSE.
  2267. *
  2268. * @return
  2269. * The data that will appear in the $element_state['values'] collection for
  2270. * this element.
  2271. */
  2272. function form_type_radios_value(&$element, $input = FALSE) {
  2273. if ($input !== FALSE) {
  2274. // When there's user input (including NULL), return it as the value.
  2275. // However, if NULL is submitted, _form_builder_handle_input_element() will
  2276. // apply the default value, and we want that validated against #options
  2277. // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
  2278. // be used to indicate that no radio button is selected by default.)
  2279. if (!isset($input) && !empty($element['#default_value'])) {
  2280. $element['#needs_validation'] = TRUE;
  2281. }
  2282. return $input;
  2283. }
  2284. else {
  2285. // For default value handling, simply return #default_value. Additionally,
  2286. // for a NULL default value, set #has_garbage_value to prevent
  2287. // _form_builder_handle_input_element() converting the NULL to an empty
  2288. // string, so that code can distinguish between nothing selected and the
  2289. // selection of a radio button whose value is an empty string.
  2290. $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
  2291. if (!isset($value)) {
  2292. $element['#has_garbage_value'] = TRUE;
  2293. }
  2294. return $value;
  2295. }
  2296. }
  2297. /**
  2298. * Determines the value for a password_confirm form element.
  2299. *
  2300. * @param $element
  2301. * The form element whose value is being populated.
  2302. * @param $input
  2303. * The incoming input to populate the form element. If this is FALSE,
  2304. * the element's default value should be returned.
  2305. *
  2306. * @return
  2307. * The data that will appear in the $element_state['values'] collection
  2308. * for this element. Return nothing to use the default.
  2309. */
  2310. function form_type_password_confirm_value($element, $input = FALSE) {
  2311. if ($input === FALSE) {
  2312. $element += array('#default_value' => array());
  2313. return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
  2314. }
  2315. }
  2316. /**
  2317. * Determines the value for a select form element.
  2318. *
  2319. * @param $element
  2320. * The form element whose value is being populated.
  2321. * @param $input
  2322. * The incoming input to populate the form element. If this is FALSE,
  2323. * the element's default value should be returned.
  2324. *
  2325. * @return
  2326. * The data that will appear in the $element_state['values'] collection
  2327. * for this element. Return nothing to use the default.
  2328. */
  2329. function form_type_select_value($element, $input = FALSE) {
  2330. if ($input !== FALSE) {
  2331. if (isset($element['#multiple']) && $element['#multiple']) {
  2332. // If an enabled multi-select submits NULL, it means all items are
  2333. // unselected. A disabled multi-select always submits NULL, and the
  2334. // default value should be used.
  2335. if (empty($element['#disabled'])) {
  2336. return (is_array($input)) ? drupal_map_assoc($input) : array();
  2337. }
  2338. else {
  2339. return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
  2340. }
  2341. }
  2342. // Non-multiple select elements may have an empty option preprended to them
  2343. // (see form_process_select()). When this occurs, usually #empty_value is
  2344. // an empty string, but some forms set #empty_value to integer 0 or some
  2345. // other non-string constant. PHP receives all submitted form input as
  2346. // strings, but if the empty option is selected, set the value to match the
  2347. // empty value exactly.
  2348. elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
  2349. return $element['#empty_value'];
  2350. }
  2351. else {
  2352. return $input;
  2353. }
  2354. }
  2355. }
  2356. /**
  2357. * Determines the value for a textfield form element.
  2358. *
  2359. * @param $element
  2360. * The form element whose value is being populated.
  2361. * @param $input
  2362. * The incoming input to populate the form element. If this is FALSE,
  2363. * the element's default value should be returned.
  2364. *
  2365. * @return
  2366. * The data that will appear in the $element_state['values'] collection
  2367. * for this element. Return nothing to use the default.
  2368. */
  2369. function form_type_textfield_value($element, $input = FALSE) {
  2370. if ($input !== FALSE && $input !== NULL) {
  2371. // Equate $input to the form value to ensure it's marked for
  2372. // validation.
  2373. return str_replace(array("\r", "\n"), '', $input);
  2374. }
  2375. }
  2376. /**
  2377. * Determines the value for form's token value.
  2378. *
  2379. * @param $element
  2380. * The form element whose value is being populated.
  2381. * @param $input
  2382. * The incoming input to populate the form element. If this is FALSE,
  2383. * the element's default value should be returned.
  2384. *
  2385. * @return
  2386. * The data that will appear in the $element_state['values'] collection
  2387. * for this element. Return nothing to use the default.
  2388. */
  2389. function form_type_token_value($element, $input = FALSE) {
  2390. if ($input !== FALSE) {
  2391. return (string) $input;
  2392. }
  2393. }
  2394. /**
  2395. * Changes submitted form values during form validation.
  2396. *
  2397. * Use this function to change the submitted value of a form element in a form
  2398. * validation function, so that the changed value persists in $form_state
  2399. * through the remaining validation and submission handlers. It does not change
  2400. * the value in $element['#value'], only in $form_state['values'], which is
  2401. * where submitted values are always stored.
  2402. *
  2403. * Note that form validation functions are specified in the '#validate'
  2404. * component of the form array (the value of $form['#validate'] is an array of
  2405. * validation function names). If the form does not originate in your module,
  2406. * you can implement hook_form_FORM_ID_alter() to add a validation function
  2407. * to $form['#validate'].
  2408. *
  2409. * @param $element
  2410. * The form element that should have its value updated; in most cases you can
  2411. * just pass in the element from the $form array, although the only component
  2412. * that is actually used is '#parents'. If constructing yourself, set
  2413. * $element['#parents'] to be an array giving the path through the form
  2414. * array's keys to the element whose value you want to update. For instance,
  2415. * if you want to update the value of $form['elem1']['elem2'], which should be
  2416. * stored in $form_state['values']['elem1']['elem2'], you would set
  2417. * $element['#parents'] = array('elem1','elem2').
  2418. * @param $value
  2419. * The new value for the form element.
  2420. * @param $form_state
  2421. * Form state array where the value change should be recorded.
  2422. */
  2423. function form_set_value($element, $value, &$form_state) {
  2424. drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
  2425. }
  2426. /**
  2427. * Allows PHP array processing of multiple select options with the same value.
  2428. *
  2429. * Used for form select elements which need to validate HTML option groups
  2430. * and multiple options which may return the same value. Associative PHP arrays
  2431. * cannot handle these structures, since they share a common key.
  2432. *
  2433. * @param $array
  2434. * The form options array to process.
  2435. *
  2436. * @return
  2437. * An array with all hierarchical elements flattened to a single array.
  2438. */
  2439. function form_options_flatten($array) {
  2440. // Always reset static var when first entering the recursion.
  2441. drupal_static_reset('_form_options_flatten');
  2442. return _form_options_flatten($array);
  2443. }
  2444. /**
  2445. * Iterates over an array and returns a flat array with duplicate keys removed.
  2446. *
  2447. * This function also handles cases where objects are passed as array values.
  2448. */
  2449. function _form_options_flatten($array) {
  2450. $return = &drupal_static(__FUNCTION__);
  2451. foreach ($array as $key => $value) {
  2452. if (is_object($value)) {
  2453. _form_options_flatten($value->option);
  2454. }
  2455. elseif (is_array($value)) {
  2456. _form_options_flatten($value);
  2457. }
  2458. else {
  2459. $return[$key] = 1;
  2460. }
  2461. }
  2462. return $return;
  2463. }
  2464. /**
  2465. * Processes a select list form element.
  2466. *
  2467. * This process callback is mandatory for select fields, since all user agents
  2468. * automatically preselect the first available option of single (non-multiple)
  2469. * select lists.
  2470. *
  2471. * @param $element
  2472. * The form element to process. Properties used:
  2473. * - #multiple: (optional) Indicates whether one or more options can be
  2474. * selected. Defaults to FALSE.
  2475. * - #default_value: Must be NULL or not set in case there is no value for the
  2476. * element yet, in which case a first default option is inserted by default.
  2477. * Whether this first option is a valid option depends on whether the field
  2478. * is #required or not.
  2479. * - #required: (optional) Whether the user needs to select an option (TRUE)
  2480. * or not (FALSE). Defaults to FALSE.
  2481. * - #empty_option: (optional) The label to show for the first default option.
  2482. * By default, the label is automatically set to "- Please select -" for a
  2483. * required field and "- None -" for an optional field.
  2484. * - #empty_value: (optional) The value for the first default option, which is
  2485. * used to determine whether the user submitted a value or not.
  2486. * - If #required is TRUE, this defaults to '' (an empty string).
  2487. * - If #required is not TRUE and this value isn't set, then no extra option
  2488. * is added to the select control, leaving the control in a slightly
  2489. * illogical state, because there's no way for the user to select nothing,
  2490. * since all user agents automatically preselect the first available
  2491. * option. But people are used to this being the behavior of select
  2492. * controls.
  2493. * @todo Address the above issue in Drupal 8.
  2494. * - If #required is not TRUE and this value is set (most commonly to an
  2495. * empty string), then an extra option (see #empty_option above)
  2496. * representing a "non-selection" is added with this as its value.
  2497. *
  2498. * @see _form_validate()
  2499. */
  2500. function form_process_select($element) {
  2501. // #multiple select fields need a special #name.
  2502. if ($element['#multiple']) {
  2503. $element['#attributes']['multiple'] = 'multiple';
  2504. $element['#attributes']['name'] = $element['#name'] . '[]';
  2505. }
  2506. // A non-#multiple select needs special handling to prevent user agents from
  2507. // preselecting the first option without intention. #multiple select lists do
  2508. // not get an empty option, as it would not make sense, user interface-wise.
  2509. else {
  2510. $required = $element['#required'];
  2511. // If the element is required and there is no #default_value, then add an
  2512. // empty option that will fail validation, so that the user is required to
  2513. // make a choice. Also, if there's a value for #empty_value or
  2514. // #empty_option, then add an option that represents emptiness.
  2515. if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
  2516. $element += array(
  2517. '#empty_value' => '',
  2518. '#empty_option' => $required ? t('- Select -') : t('- None -'),
  2519. );
  2520. // The empty option is prepended to #options and purposively not merged
  2521. // to prevent another option in #options mistakenly using the same value
  2522. // as #empty_value.
  2523. $empty_option = array($element['#empty_value'] => $element['#empty_option']);
  2524. $element['#options'] = $empty_option + $element['#options'];
  2525. }
  2526. }
  2527. return $element;
  2528. }
  2529. /**
  2530. * Returns HTML for a select form element.
  2531. *
  2532. * It is possible to group options together; to do this, change the format of
  2533. * $options to an associative array in which the keys are group labels, and the
  2534. * values are associative arrays in the normal $options format.
  2535. *
  2536. * @param $variables
  2537. * An associative array containing:
  2538. * - element: An associative array containing the properties of the element.
  2539. * Properties used: #title, #value, #options, #description, #extra,
  2540. * #multiple, #required, #name, #attributes, #size.
  2541. *
  2542. * @ingroup themeable
  2543. */
  2544. function theme_select($variables) {
  2545. $element = $variables['element'];
  2546. element_set_attributes($element, array('id', 'name', 'size'));
  2547. _form_set_class($element, array('form-select'));
  2548. return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
  2549. }
  2550. /**
  2551. * Converts a select form element's options array into HTML.
  2552. *
  2553. * @param $element
  2554. * An associative array containing the properties of the element.
  2555. * @param $choices
  2556. * Mixed: Either an associative array of items to list as choices, or an
  2557. * object with an 'option' member that is an associative array. This
  2558. * parameter is only used internally and should not be passed.
  2559. *
  2560. * @return
  2561. * An HTML string of options for the select form element.
  2562. */
  2563. function form_select_options($element, $choices = NULL) {
  2564. if (!isset($choices)) {
  2565. $choices = $element['#options'];
  2566. }
  2567. // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  2568. // isset() fails in this situation.
  2569. $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  2570. $value_is_array = $value_valid && is_array($element['#value']);
  2571. $options = '';
  2572. foreach ($choices as $key => $choice) {
  2573. if (is_array($choice)) {
  2574. $options .= '<optgroup label="' . $key . '">';
  2575. $options .= form_select_options($element, $choice);
  2576. $options .= '</optgroup>';
  2577. }
  2578. elseif (is_object($choice)) {
  2579. $options .= form_select_options($element, $choice->option);
  2580. }
  2581. else {
  2582. $key = (string) $key;
  2583. if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
  2584. $selected = ' selected="selected"';
  2585. }
  2586. else {
  2587. $selected = '';
  2588. }
  2589. $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
  2590. }
  2591. }
  2592. return $options;
  2593. }
  2594. /**
  2595. * Returns the indexes of a select element's options matching a given key.
  2596. *
  2597. * This function is useful if you need to modify the options that are
  2598. * already in a form element; for example, to remove choices which are
  2599. * not valid because of additional filters imposed by another module.
  2600. * One example might be altering the choices in a taxonomy selector.
  2601. * To correctly handle the case of a multiple hierarchy taxonomy,
  2602. * #options arrays can now hold an array of objects, instead of a
  2603. * direct mapping of keys to labels, so that multiple choices in the
  2604. * selector can have the same key (and label). This makes it difficult
  2605. * to manipulate directly, which is why this helper function exists.
  2606. *
  2607. * This function does not support optgroups (when the elements of the
  2608. * #options array are themselves arrays), and will return FALSE if
  2609. * arrays are found. The caller must either flatten/restore or
  2610. * manually do their manipulations in this case, since returning the
  2611. * index is not sufficient, and supporting this would make the
  2612. * "helper" too complicated and cumbersome to be of any help.
  2613. *
  2614. * As usual with functions that can return array() or FALSE, do not
  2615. * forget to use === and !== if needed.
  2616. *
  2617. * @param $element
  2618. * The select element to search.
  2619. * @param $key
  2620. * The key to look for.
  2621. *
  2622. * @return
  2623. * An array of indexes that match the given $key. Array will be
  2624. * empty if no elements were found. FALSE if optgroups were found.
  2625. */
  2626. function form_get_options($element, $key) {
  2627. $keys = array();
  2628. foreach ($element['#options'] as $index => $choice) {
  2629. if (is_array($choice)) {
  2630. return FALSE;
  2631. }
  2632. elseif (is_object($choice)) {
  2633. if (isset($choice->option[$key])) {
  2634. $keys[] = $index;
  2635. }
  2636. }
  2637. elseif ($index == $key) {
  2638. $keys[] = $index;
  2639. }
  2640. }
  2641. return $keys;
  2642. }
  2643. /**
  2644. * Returns HTML for a fieldset form element and its children.
  2645. *
  2646. * @param $variables
  2647. * An associative array containing:
  2648. * - element: An associative array containing the properties of the element.
  2649. * Properties used: #attributes, #children, #collapsed, #collapsible,
  2650. * #description, #id, #title, #value.
  2651. *
  2652. * @ingroup themeable
  2653. */
  2654. function theme_fieldset($variables) {
  2655. $element = $variables['element'];
  2656. element_set_attributes($element, array('id'));
  2657. _form_set_class($element, array('form-wrapper'));
  2658. $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  2659. if (!empty($element['#title'])) {
  2660. // Always wrap fieldset legends in a SPAN for CSS positioning.
  2661. $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
  2662. }
  2663. $output .= '<div class="fieldset-wrapper">';
  2664. if (!empty($element['#description'])) {
  2665. $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
  2666. }
  2667. $output .= $element['#children'];
  2668. if (isset($element['#value'])) {
  2669. $output .= $element['#value'];
  2670. }
  2671. $output .= '</div>';
  2672. $output .= "</fieldset>\n";
  2673. return $output;
  2674. }
  2675. /**
  2676. * Returns HTML for a radio button form element.
  2677. *
  2678. * Note: The input "name" attribute needs to be sanitized before output, which
  2679. * is currently done by passing all attributes to drupal_attributes().
  2680. *
  2681. * @param $variables
  2682. * An associative array containing:
  2683. * - element: An associative array containing the properties of the element.
  2684. * Properties used: #required, #return_value, #value, #attributes, #title,
  2685. * #description
  2686. *
  2687. * @ingroup themeable
  2688. */
  2689. function theme_radio($variables) {
  2690. $element = $variables['element'];
  2691. $element['#attributes']['type'] = 'radio';
  2692. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  2693. if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
  2694. $element['#attributes']['checked'] = 'checked';
  2695. }
  2696. _form_set_class($element, array('form-radio'));
  2697. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  2698. }
  2699. /**
  2700. * Returns HTML for a set of radio button form elements.
  2701. *
  2702. * @param $variables
  2703. * An associative array containing:
  2704. * - element: An associative array containing the properties of the element.
  2705. * Properties used: #title, #value, #options, #description, #required,
  2706. * #attributes, #children.
  2707. *
  2708. * @ingroup themeable
  2709. */
  2710. function theme_radios($variables) {
  2711. $element = $variables['element'];
  2712. $attributes = array();
  2713. if (isset($element['#id'])) {
  2714. $attributes['id'] = $element['#id'];
  2715. }
  2716. $attributes['class'] = 'form-radios';
  2717. if (!empty($element['#attributes']['class'])) {
  2718. $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  2719. }
  2720. if (isset($element['#attributes']['title'])) {
  2721. $attributes['title'] = $element['#attributes']['title'];
  2722. }
  2723. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  2724. }
  2725. /**
  2726. * Expand a password_confirm field into two text boxes.
  2727. */
  2728. function form_process_password_confirm($element) {
  2729. $element['pass1'] = array(
  2730. '#type' => 'password',
  2731. '#title' => t('Password'),
  2732. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
  2733. '#required' => $element['#required'],
  2734. '#attributes' => array('class' => array('password-field')),
  2735. );
  2736. $element['pass2'] = array(
  2737. '#type' => 'password',
  2738. '#title' => t('Confirm password'),
  2739. '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
  2740. '#required' => $element['#required'],
  2741. '#attributes' => array('class' => array('password-confirm')),
  2742. );
  2743. $element['#element_validate'] = array('password_confirm_validate');
  2744. $element['#tree'] = TRUE;
  2745. if (isset($element['#size'])) {
  2746. $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
  2747. }
  2748. return $element;
  2749. }
  2750. /**
  2751. * Validates a password_confirm element.
  2752. */
  2753. function password_confirm_validate($element, &$element_state) {
  2754. $pass1 = trim($element['pass1']['#value']);
  2755. $pass2 = trim($element['pass2']['#value']);
  2756. if (!empty($pass1) || !empty($pass2)) {
  2757. if (strcmp($pass1, $pass2)) {
  2758. form_error($element, t('The specified passwords do not match.'));
  2759. }
  2760. }
  2761. elseif ($element['#required'] && !empty($element_state['input'])) {
  2762. form_error($element, t('Password field is required.'));
  2763. }
  2764. // Password field must be converted from a two-element array into a single
  2765. // string regardless of validation results.
  2766. form_set_value($element['pass1'], NULL, $element_state);
  2767. form_set_value($element['pass2'], NULL, $element_state);
  2768. form_set_value($element, $pass1, $element_state);
  2769. return $element;
  2770. }
  2771. /**
  2772. * Returns HTML for a date selection form element.
  2773. *
  2774. * @param $variables
  2775. * An associative array containing:
  2776. * - element: An associative array containing the properties of the element.
  2777. * Properties used: #title, #value, #options, #description, #required,
  2778. * #attributes.
  2779. *
  2780. * @ingroup themeable
  2781. */
  2782. function theme_date($variables) {
  2783. $element = $variables['element'];
  2784. $attributes = array();
  2785. if (isset($element['#id'])) {
  2786. $attributes['id'] = $element['#id'];
  2787. }
  2788. if (!empty($element['#attributes']['class'])) {
  2789. $attributes['class'] = (array) $element['#attributes']['class'];
  2790. }
  2791. $attributes['class'][] = 'container-inline';
  2792. return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
  2793. }
  2794. /**
  2795. * Expands a date element into year, month, and day select elements.
  2796. */
  2797. function form_process_date($element) {
  2798. // Default to current date
  2799. if (empty($element['#value'])) {
  2800. $element['#value'] = array(
  2801. 'day' => format_date(REQUEST_TIME, 'custom', 'j'),
  2802. 'month' => format_date(REQUEST_TIME, 'custom', 'n'),
  2803. 'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
  2804. );
  2805. }
  2806. $element['#tree'] = TRUE;
  2807. // Determine the order of day, month, year in the site's chosen date format.
  2808. $format = variable_get('date_format_short', 'm/d/Y - H:i');
  2809. $sort = array();
  2810. $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
  2811. $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
  2812. $sort['year'] = strpos($format, 'Y');
  2813. asort($sort);
  2814. $order = array_keys($sort);
  2815. // Output multi-selector for date.
  2816. foreach ($order as $type) {
  2817. switch ($type) {
  2818. case 'day':
  2819. $options = drupal_map_assoc(range(1, 31));
  2820. $title = t('Day');
  2821. break;
  2822. case 'month':
  2823. $options = drupal_map_assoc(range(1, 12), 'map_month');
  2824. $title = t('Month');
  2825. break;
  2826. case 'year':
  2827. $options = drupal_map_assoc(range(1900, 2050));
  2828. $title = t('Year');
  2829. break;
  2830. }
  2831. $element[$type] = array(
  2832. '#type' => 'select',
  2833. '#title' => $title,
  2834. '#title_display' => 'invisible',
  2835. '#value' => $element['#value'][$type],
  2836. '#attributes' => $element['#attributes'],
  2837. '#options' => $options,
  2838. );
  2839. }
  2840. return $element;
  2841. }
  2842. /**
  2843. * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
  2844. */
  2845. function date_validate($element) {
  2846. if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
  2847. form_error($element, t('The specified date is invalid.'));
  2848. }
  2849. }
  2850. /**
  2851. * Helper function for usage with drupal_map_assoc to display month names.
  2852. */
  2853. function map_month($month) {
  2854. $months = &drupal_static(__FUNCTION__, array(
  2855. 1 => 'Jan',
  2856. 2 => 'Feb',
  2857. 3 => 'Mar',
  2858. 4 => 'Apr',
  2859. 5 => 'May',
  2860. 6 => 'Jun',
  2861. 7 => 'Jul',
  2862. 8 => 'Aug',
  2863. 9 => 'Sep',
  2864. 10 => 'Oct',
  2865. 11 => 'Nov',
  2866. 12 => 'Dec',
  2867. ));
  2868. return t($months[$month]);
  2869. }
  2870. /**
  2871. * Sets the value for a weight element, with zero as a default.
  2872. */
  2873. function weight_value(&$form) {
  2874. if (isset($form['#default_value'])) {
  2875. $form['#value'] = $form['#default_value'];
  2876. }
  2877. else {
  2878. $form['#value'] = 0;
  2879. }
  2880. }
  2881. /**
  2882. * Expands a radios element into individual radio elements.
  2883. */
  2884. function form_process_radios($element) {
  2885. if (count($element['#options']) > 0) {
  2886. $weight = 0;
  2887. foreach ($element['#options'] as $key => $choice) {
  2888. // Maintain order of options as defined in #options, in case the element
  2889. // defines custom option sub-elements, but does not define all option
  2890. // sub-elements.
  2891. $weight += 0.001;
  2892. $element += array($key => array());
  2893. // Generate the parents as the autogenerator does, so we will have a
  2894. // unique id for each radio button.
  2895. $parents_for_id = array_merge($element['#parents'], array($key));
  2896. $element[$key] += array(
  2897. '#type' => 'radio',
  2898. '#title' => $choice,
  2899. // The key is sanitized in drupal_attributes() during output from the
  2900. // theme function.
  2901. '#return_value' => $key,
  2902. // Use default or FALSE. A value of FALSE means that the radio button is
  2903. // not 'checked'.
  2904. '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
  2905. '#attributes' => $element['#attributes'],
  2906. '#parents' => $element['#parents'],
  2907. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  2908. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  2909. '#weight' => $weight,
  2910. );
  2911. }
  2912. }
  2913. return $element;
  2914. }
  2915. /**
  2916. * Returns HTML for a checkbox form element.
  2917. *
  2918. * @param $variables
  2919. * An associative array containing:
  2920. * - element: An associative array containing the properties of the element.
  2921. * Properties used: #title, #value, #return_value, #description, #required,
  2922. * #attributes, #checked.
  2923. *
  2924. * @ingroup themeable
  2925. */
  2926. function theme_checkbox($variables) {
  2927. $element = $variables['element'];
  2928. $element['#attributes']['type'] = 'checkbox';
  2929. element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
  2930. // Unchecked checkbox has #value of integer 0.
  2931. if (!empty($element['#checked'])) {
  2932. $element['#attributes']['checked'] = 'checked';
  2933. }
  2934. _form_set_class($element, array('form-checkbox'));
  2935. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  2936. }
  2937. /**
  2938. * Returns HTML for a set of checkbox form elements.
  2939. *
  2940. * @param $variables
  2941. * An associative array containing:
  2942. * - element: An associative array containing the properties of the element.
  2943. * Properties used: #children, #attributes.
  2944. *
  2945. * @ingroup themeable
  2946. */
  2947. function theme_checkboxes($variables) {
  2948. $element = $variables['element'];
  2949. $attributes = array();
  2950. if (isset($element['#id'])) {
  2951. $attributes['id'] = $element['#id'];
  2952. }
  2953. $attributes['class'][] = 'form-checkboxes';
  2954. if (!empty($element['#attributes']['class'])) {
  2955. $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
  2956. }
  2957. if (isset($element['#attributes']['title'])) {
  2958. $attributes['title'] = $element['#attributes']['title'];
  2959. }
  2960. return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
  2961. }
  2962. /**
  2963. * Adds form element theming to an element if its title or description is set.
  2964. *
  2965. * This is used as a pre render function for checkboxes and radios.
  2966. */
  2967. function form_pre_render_conditional_form_element($element) {
  2968. $t = get_t();
  2969. // Set the element's title attribute to show #title as a tooltip, if needed.
  2970. if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
  2971. $element['#attributes']['title'] = $element['#title'];
  2972. if (!empty($element['#required'])) {
  2973. // Append an indication that this field is required.
  2974. $element['#attributes']['title'] .= ' (' . $t('Required') . ')';
  2975. }
  2976. }
  2977. if (isset($element['#title']) || isset($element['#description'])) {
  2978. $element['#theme_wrappers'][] = 'form_element';
  2979. }
  2980. return $element;
  2981. }
  2982. /**
  2983. * Sets the #checked property of a checkbox element.
  2984. */
  2985. function form_process_checkbox($element, $form_state) {
  2986. $value = $element['#value'];
  2987. $return_value = $element['#return_value'];
  2988. // On form submission, the #value of an available and enabled checked
  2989. // checkbox is #return_value, and the #value of an available and enabled
  2990. // unchecked checkbox is integer 0. On not submitted forms, and for
  2991. // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
  2992. // #default_value (integer 0 if #default_value is NULL). Most of the time,
  2993. // a string comparison of #value and #return_value is sufficient for
  2994. // determining the "checked" state, but a value of TRUE always means checked
  2995. // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
  2996. // means unchecked (even if #return_value is '' or '0').
  2997. if ($value === TRUE || $value === FALSE || $value === 0) {
  2998. $element['#checked'] = (bool) $value;
  2999. }
  3000. else {
  3001. // Compare as strings, so that 15 is not considered equal to '15foo', but 1
  3002. // is considered equal to '1'. This cast does not imply that either #value
  3003. // or #return_value is expected to be a string.
  3004. $element['#checked'] = ((string) $value === (string) $return_value);
  3005. }
  3006. return $element;
  3007. }
  3008. /**
  3009. * Processes a checkboxes form element.
  3010. */
  3011. function form_process_checkboxes($element) {
  3012. $value = is_array($element['#value']) ? $element['#value'] : array();
  3013. $element['#tree'] = TRUE;
  3014. if (count($element['#options']) > 0) {
  3015. if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
  3016. $element['#default_value'] = array();
  3017. }
  3018. $weight = 0;
  3019. foreach ($element['#options'] as $key => $choice) {
  3020. // Integer 0 is not a valid #return_value, so use '0' instead.
  3021. // @see form_type_checkbox_value().
  3022. // @todo For Drupal 8, cast all integer keys to strings for consistency
  3023. // with form_process_radios().
  3024. if ($key === 0) {
  3025. $key = '0';
  3026. }
  3027. // Maintain order of options as defined in #options, in case the element
  3028. // defines custom option sub-elements, but does not define all option
  3029. // sub-elements.
  3030. $weight += 0.001;
  3031. $element += array($key => array());
  3032. $element[$key] += array(
  3033. '#type' => 'checkbox',
  3034. '#title' => $choice,
  3035. '#return_value' => $key,
  3036. '#default_value' => isset($value[$key]) ? $key : NULL,
  3037. '#attributes' => $element['#attributes'],
  3038. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3039. '#weight' => $weight,
  3040. );
  3041. }
  3042. }
  3043. return $element;
  3044. }
  3045. /**
  3046. * Processes a form actions container element.
  3047. *
  3048. * @param $element
  3049. * An associative array containing the properties and children of the
  3050. * form actions container.
  3051. * @param $form_state
  3052. * The $form_state array for the form this element belongs to.
  3053. *
  3054. * @return
  3055. * The processed element.
  3056. */
  3057. function form_process_actions($element, &$form_state) {
  3058. $element['#attributes']['class'][] = 'form-actions';
  3059. return $element;
  3060. }
  3061. /**
  3062. * Processes a container element.
  3063. *
  3064. * @param $element
  3065. * An associative array containing the properties and children of the
  3066. * container.
  3067. * @param $form_state
  3068. * The $form_state array for the form this element belongs to.
  3069. *
  3070. * @return
  3071. * The processed element.
  3072. */
  3073. function form_process_container($element, &$form_state) {
  3074. // Generate the ID of the element if it's not explicitly given.
  3075. if (!isset($element['#id'])) {
  3076. $element['#id'] = drupal_html_id(implode('-', $element['#parents']) . '-wrapper');
  3077. }
  3078. return $element;
  3079. }
  3080. /**
  3081. * Returns HTML to wrap child elements in a container.
  3082. *
  3083. * Used for grouped form items. Can also be used as a #theme_wrapper for any
  3084. * renderable element, to surround it with a <div> and add attributes such as
  3085. * classes or an HTML id.
  3086. *
  3087. * @param $variables
  3088. * An associative array containing:
  3089. * - element: An associative array containing the properties of the element.
  3090. * Properties used: #id, #attributes, #children.
  3091. *
  3092. * @ingroup themeable
  3093. */
  3094. function theme_container($variables) {
  3095. $element = $variables['element'];
  3096. // Special handling for form elements.
  3097. if (isset($element['#array_parents'])) {
  3098. // Assign an html ID.
  3099. if (!isset($element['#attributes']['id'])) {
  3100. $element['#attributes']['id'] = $element['#id'];
  3101. }
  3102. // Add the 'form-wrapper' class.
  3103. $element['#attributes']['class'][] = 'form-wrapper';
  3104. }
  3105. return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
  3106. }
  3107. /**
  3108. * Returns HTML for a table with radio buttons or checkboxes.
  3109. *
  3110. * @param $variables
  3111. * An associative array containing:
  3112. * - element: An associative array containing the properties and children of
  3113. * the tableselect element. Properties used: #header, #options, #empty,
  3114. * and #js_select. The #options property is an array of selection options;
  3115. * each array element of #options is an array of properties. These
  3116. * properties can include #attributes, which is added to the
  3117. * table row's HTML attributes; see theme_table(). An example of per-row
  3118. * options:
  3119. * @code
  3120. * $options = array(
  3121. * array(
  3122. * 'title' => 'How to Learn Drupal',
  3123. * 'content_type' => 'Article',
  3124. * 'status' => 'published',
  3125. * '#attributes' => array('class' => array('article-row')),
  3126. * ),
  3127. * array(
  3128. * 'title' => 'Privacy Policy',
  3129. * 'content_type' => 'Page',
  3130. * 'status' => 'published',
  3131. * '#attributes' => array('class' => array('page-row')),
  3132. * ),
  3133. * );
  3134. * $header = array(
  3135. * 'title' => t('Title'),
  3136. * 'content_type' => t('Content type'),
  3137. * 'status' => t('Status'),
  3138. * );
  3139. * $form['table'] = array(
  3140. * '#type' => 'tableselect',
  3141. * '#header' => $header,
  3142. * '#options' => $options,
  3143. * '#empty' => t('No content available.'),
  3144. * );
  3145. * @endcode
  3146. *
  3147. * @ingroup themeable
  3148. */
  3149. function theme_tableselect($variables) {
  3150. $element = $variables['element'];
  3151. $rows = array();
  3152. $header = $element['#header'];
  3153. if (!empty($element['#options'])) {
  3154. // Generate a table row for each selectable item in #options.
  3155. foreach (element_children($element) as $key) {
  3156. $row = array();
  3157. $row['data'] = array();
  3158. if (isset($element['#options'][$key]['#attributes'])) {
  3159. $row += $element['#options'][$key]['#attributes'];
  3160. }
  3161. // Render the checkbox / radio element.
  3162. $row['data'][] = drupal_render($element[$key]);
  3163. // As theme_table only maps header and row columns by order, create the
  3164. // correct order by iterating over the header fields.
  3165. foreach ($element['#header'] as $fieldname => $title) {
  3166. $row['data'][] = $element['#options'][$key][$fieldname];
  3167. }
  3168. $rows[] = $row;
  3169. }
  3170. // Add an empty header or a "Select all" checkbox to provide room for the
  3171. // checkboxes/radios in the first table column.
  3172. if ($element['#js_select']) {
  3173. // Add a "Select all" checkbox.
  3174. drupal_add_js('misc/tableselect.js');
  3175. array_unshift($header, array('class' => array('select-all')));
  3176. }
  3177. else {
  3178. // Add an empty header when radio buttons are displayed or a "Select all"
  3179. // checkbox is not desired.
  3180. array_unshift($header, '');
  3181. }
  3182. }
  3183. return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes']));
  3184. }
  3185. /**
  3186. * Creates checkbox or radio elements to populate a tableselect table.
  3187. *
  3188. * @param $element
  3189. * An associative array containing the properties and children of the
  3190. * tableselect element.
  3191. *
  3192. * @return
  3193. * The processed element.
  3194. */
  3195. function form_process_tableselect($element) {
  3196. if ($element['#multiple']) {
  3197. $value = is_array($element['#value']) ? $element['#value'] : array();
  3198. }
  3199. else {
  3200. // Advanced selection behavior makes no sense for radios.
  3201. $element['#js_select'] = FALSE;
  3202. }
  3203. $element['#tree'] = TRUE;
  3204. if (count($element['#options']) > 0) {
  3205. if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
  3206. $element['#default_value'] = array();
  3207. }
  3208. // Create a checkbox or radio for each item in #options in such a way that
  3209. // the value of the tableselect element behaves as if it had been of type
  3210. // checkboxes or radios.
  3211. foreach ($element['#options'] as $key => $choice) {
  3212. // Do not overwrite manually created children.
  3213. if (!isset($element[$key])) {
  3214. if ($element['#multiple']) {
  3215. $title = '';
  3216. if (!empty($element['#options'][$key]['title']['data']['#title'])) {
  3217. $title = t('Update @title', array(
  3218. '@title' => $element['#options'][$key]['title']['data']['#title'],
  3219. ));
  3220. }
  3221. $element[$key] = array(
  3222. '#type' => 'checkbox',
  3223. '#title' => $title,
  3224. '#title_display' => 'invisible',
  3225. '#return_value' => $key,
  3226. '#default_value' => isset($value[$key]) ? $key : NULL,
  3227. '#attributes' => $element['#attributes'],
  3228. );
  3229. }
  3230. else {
  3231. // Generate the parents as the autogenerator does, so we will have a
  3232. // unique id for each radio button.
  3233. $parents_for_id = array_merge($element['#parents'], array($key));
  3234. $element[$key] = array(
  3235. '#type' => 'radio',
  3236. '#title' => '',
  3237. '#return_value' => $key,
  3238. '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
  3239. '#attributes' => $element['#attributes'],
  3240. '#parents' => $element['#parents'],
  3241. '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
  3242. '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
  3243. );
  3244. }
  3245. if (isset($element['#options'][$key]['#weight'])) {
  3246. $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
  3247. }
  3248. }
  3249. }
  3250. }
  3251. else {
  3252. $element['#value'] = array();
  3253. }
  3254. return $element;
  3255. }
  3256. /**
  3257. * Processes a machine-readable name form element.
  3258. *
  3259. * @param $element
  3260. * The form element to process. Properties used:
  3261. * - #machine_name: An associative array containing:
  3262. * - exists: A function name to invoke for checking whether a submitted
  3263. * machine name value already exists. The submitted value is passed as
  3264. * argument. In most cases, an existing API or menu argument loader
  3265. * function can be re-used. The callback is only invoked, if the submitted
  3266. * value differs from the element's #default_value.
  3267. * - source: (optional) The #array_parents of the form element containing
  3268. * the human-readable name (i.e., as contained in the $form structure) to
  3269. * use as source for the machine name. Defaults to array('name').
  3270. * - label: (optional) A text to display as label for the machine name value
  3271. * after the human-readable name form element. Defaults to "Machine name".
  3272. * - replace_pattern: (optional) A regular expression (without delimiters)
  3273. * matching disallowed characters in the machine name. Defaults to
  3274. * '[^a-z0-9_]+'.
  3275. * - replace: (optional) A character to replace disallowed characters in the
  3276. * machine name via JavaScript. Defaults to '_' (underscore). When using a
  3277. * different character, 'replace_pattern' needs to be set accordingly.
  3278. * - error: (optional) A custom form error message string to show, if the
  3279. * machine name contains disallowed characters.
  3280. * - standalone: (optional) Whether the live preview should stay in its own
  3281. * form element rather than in the suffix of the source element. Defaults
  3282. * to FALSE.
  3283. * - #maxlength: (optional) Should be set to the maximum allowed length of the
  3284. * machine name. Defaults to 64.
  3285. * - #disabled: (optional) Should be set to TRUE in case an existing machine
  3286. * name must not be changed after initial creation.
  3287. */
  3288. function form_process_machine_name($element, &$form_state) {
  3289. // Apply default form element properties.
  3290. $element += array(
  3291. '#title' => t('Machine-readable name'),
  3292. '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
  3293. '#machine_name' => array(),
  3294. '#field_prefix' => '',
  3295. '#field_suffix' => '',
  3296. '#suffix' => '',
  3297. );
  3298. // A form element that only wants to set one #machine_name property (usually
  3299. // 'source' only) would leave all other properties undefined, if the defaults
  3300. // were defined in hook_element_info(). Therefore, we apply the defaults here.
  3301. $element['#machine_name'] += array(
  3302. 'source' => array('name'),
  3303. 'target' => '#' . $element['#id'],
  3304. 'label' => t('Machine name'),
  3305. 'replace_pattern' => '[^a-z0-9_]+',
  3306. 'replace' => '_',
  3307. 'standalone' => FALSE,
  3308. 'field_prefix' => $element['#field_prefix'],
  3309. 'field_suffix' => $element['#field_suffix'],
  3310. );
  3311. // By default, machine names are restricted to Latin alphanumeric characters.
  3312. // So, default to LTR directionality.
  3313. if (!isset($element['#attributes'])) {
  3314. $element['#attributes'] = array();
  3315. }
  3316. $element['#attributes'] += array('dir' => 'ltr');
  3317. // The source element defaults to array('name'), but may have been overidden.
  3318. if (empty($element['#machine_name']['source'])) {
  3319. return $element;
  3320. }
  3321. // Retrieve the form element containing the human-readable name from the
  3322. // complete form in $form_state. By reference, because we may need to append
  3323. // a #field_suffix that will hold the live preview.
  3324. $key_exists = NULL;
  3325. $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
  3326. if (!$key_exists) {
  3327. return $element;
  3328. }
  3329. $suffix_id = $source['#id'] . '-machine-name-suffix';
  3330. $element['#machine_name']['suffix'] = '#' . $suffix_id;
  3331. if ($element['#machine_name']['standalone']) {
  3332. $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3333. }
  3334. else {
  3335. // Append a field suffix to the source form element, which will contain
  3336. // the live preview of the machine name.
  3337. $source += array('#field_suffix' => '');
  3338. $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
  3339. $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
  3340. drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
  3341. }
  3342. $js_settings = array(
  3343. 'type' => 'setting',
  3344. 'data' => array(
  3345. 'machineName' => array(
  3346. '#' . $source['#id'] => $element['#machine_name'],
  3347. ),
  3348. ),
  3349. );
  3350. $element['#attached']['js'][] = 'misc/machine-name.js';
  3351. $element['#attached']['js'][] = $js_settings;
  3352. return $element;
  3353. }
  3354. /**
  3355. * Form element validation handler for machine_name elements.
  3356. *
  3357. * Note that #maxlength is validated by _form_validate() already.
  3358. */
  3359. function form_validate_machine_name(&$element, &$form_state) {
  3360. // Verify that the machine name not only consists of replacement tokens.
  3361. if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
  3362. form_error($element, t('The machine-readable name must contain unique characters.'));
  3363. }
  3364. // Verify that the machine name contains no disallowed characters.
  3365. if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
  3366. if (!isset($element['#machine_name']['error'])) {
  3367. // Since a hyphen is the most common alternative replacement character,
  3368. // a corresponding validation error message is supported here.
  3369. if ($element['#machine_name']['replace'] == '-') {
  3370. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
  3371. }
  3372. // Otherwise, we assume the default (underscore).
  3373. else {
  3374. form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
  3375. }
  3376. }
  3377. else {
  3378. form_error($element, $element['#machine_name']['error']);
  3379. }
  3380. }
  3381. // Verify that the machine name is unique.
  3382. if ($element['#default_value'] !== $element['#value']) {
  3383. $function = $element['#machine_name']['exists'];
  3384. if ($function($element['#value'], $element, $form_state)) {
  3385. form_error($element, t('The machine-readable name is already in use. It must be unique.'));
  3386. }
  3387. }
  3388. }
  3389. /**
  3390. * Arranges fieldsets into groups.
  3391. *
  3392. * @param $element
  3393. * An associative array containing the properties and children of the
  3394. * fieldset. Note that $element must be taken by reference here, so processed
  3395. * child elements are taken over into $form_state.
  3396. * @param $form_state
  3397. * The $form_state array for the form this fieldset belongs to.
  3398. *
  3399. * @return
  3400. * The processed element.
  3401. */
  3402. function form_process_fieldset(&$element, &$form_state) {
  3403. $parents = implode('][', $element['#parents']);
  3404. // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
  3405. // injects a new fieldset.
  3406. $form_state['groups'][$parents]['#group_exists'] = TRUE;
  3407. $element['#groups'] = &$form_state['groups'];
  3408. // Process vertical tabs group member fieldsets.
  3409. if (isset($element['#group'])) {
  3410. // Add this fieldset to the defined group (by reference).
  3411. $group = $element['#group'];
  3412. $form_state['groups'][$group][] = &$element;
  3413. }
  3414. // Contains form element summary functionalities.
  3415. $element['#attached']['library'][] = array('system', 'drupal.form');
  3416. // The .form-wrapper class is required for #states to treat fieldsets like
  3417. // containers.
  3418. if (!isset($element['#attributes']['class'])) {
  3419. $element['#attributes']['class'] = array();
  3420. }
  3421. // Collapsible fieldsets
  3422. if (!empty($element['#collapsible'])) {
  3423. $element['#attached']['library'][] = array('system', 'drupal.collapse');
  3424. $element['#attributes']['class'][] = 'collapsible';
  3425. if (!empty($element['#collapsed'])) {
  3426. $element['#attributes']['class'][] = 'collapsed';
  3427. }
  3428. }
  3429. return $element;
  3430. }
  3431. /**
  3432. * Adds members of this group as actual elements for rendering.
  3433. *
  3434. * @param $element
  3435. * An associative array containing the properties and children of the
  3436. * fieldset.
  3437. *
  3438. * @return
  3439. * The modified element with all group members.
  3440. */
  3441. function form_pre_render_fieldset($element) {
  3442. // Fieldsets may be rendered outside of a Form API context.
  3443. if (!isset($element['#parents']) || !isset($element['#groups'])) {
  3444. return $element;
  3445. }
  3446. // Inject group member elements belonging to this group.
  3447. $parents = implode('][', $element['#parents']);
  3448. $children = element_children($element['#groups'][$parents]);
  3449. if (!empty($children)) {
  3450. foreach ($children as $key) {
  3451. // Break references and indicate that the element should be rendered as
  3452. // group member.
  3453. $child = (array) $element['#groups'][$parents][$key];
  3454. $child['#group_fieldset'] = TRUE;
  3455. // Inject the element as new child element.
  3456. $element[] = $child;
  3457. $sort = TRUE;
  3458. }
  3459. // Re-sort the element's children if we injected group member elements.
  3460. if (isset($sort)) {
  3461. $element['#sorted'] = FALSE;
  3462. }
  3463. }
  3464. if (isset($element['#group'])) {
  3465. $group = $element['#group'];
  3466. // If this element belongs to a group, but the group-holding element does
  3467. // not exist, we need to render it (at its original location).
  3468. if (!isset($element['#groups'][$group]['#group_exists'])) {
  3469. // Intentionally empty to clarify the flow; we simply return $element.
  3470. }
  3471. // If we injected this element into the group, then we want to render it.
  3472. elseif (!empty($element['#group_fieldset'])) {
  3473. // Intentionally empty to clarify the flow; we simply return $element.
  3474. }
  3475. // Otherwise, this element belongs to a group and the group exists, so we do
  3476. // not render it.
  3477. elseif (element_children($element['#groups'][$group])) {
  3478. $element['#printed'] = TRUE;
  3479. }
  3480. }
  3481. return $element;
  3482. }
  3483. /**
  3484. * Creates a group formatted as vertical tabs.
  3485. *
  3486. * @param $element
  3487. * An associative array containing the properties and children of the
  3488. * fieldset.
  3489. * @param $form_state
  3490. * The $form_state array for the form this vertical tab widget belongs to.
  3491. *
  3492. * @return
  3493. * The processed element.
  3494. */
  3495. function form_process_vertical_tabs($element, &$form_state) {
  3496. // Inject a new fieldset as child, so that form_process_fieldset() processes
  3497. // this fieldset like any other fieldset.
  3498. $element['group'] = array(
  3499. '#type' => 'fieldset',
  3500. '#theme_wrappers' => array(),
  3501. '#parents' => $element['#parents'],
  3502. );
  3503. // The JavaScript stores the currently selected tab in this hidden
  3504. // field so that the active tab can be restored the next time the
  3505. // form is rendered, e.g. on preview pages or when form validation
  3506. // fails.
  3507. $name = implode('__', $element['#parents']);
  3508. if (isset($form_state['values'][$name . '__active_tab'])) {
  3509. $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
  3510. }
  3511. $element[$name . '__active_tab'] = array(
  3512. '#type' => 'hidden',
  3513. '#default_value' => $element['#default_tab'],
  3514. '#attributes' => array('class' => array('vertical-tabs-active-tab')),
  3515. );
  3516. return $element;
  3517. }
  3518. /**
  3519. * Returns HTML for an element's children fieldsets as vertical tabs.
  3520. *
  3521. * @param $variables
  3522. * An associative array containing:
  3523. * - element: An associative array containing the properties and children of
  3524. * the fieldset. Properties used: #children.
  3525. *
  3526. * @ingroup themeable
  3527. */
  3528. function theme_vertical_tabs($variables) {
  3529. $element = $variables['element'];
  3530. // Add required JavaScript and Stylesheet.
  3531. drupal_add_library('system', 'drupal.vertical-tabs');
  3532. $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
  3533. $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
  3534. return $output;
  3535. }
  3536. /**
  3537. * Returns HTML for a submit button form element.
  3538. *
  3539. * @param $variables
  3540. * An associative array containing:
  3541. * - element: An associative array containing the properties of the element.
  3542. * Properties used: #attributes, #button_type, #name, #value.
  3543. *
  3544. * @ingroup themeable
  3545. */
  3546. function theme_submit($variables) {
  3547. return theme('button', $variables['element']);
  3548. }
  3549. /**
  3550. * Returns HTML for a button form element.
  3551. *
  3552. * @param $variables
  3553. * An associative array containing:
  3554. * - element: An associative array containing the properties of the element.
  3555. * Properties used: #attributes, #button_type, #name, #value.
  3556. *
  3557. * @ingroup themeable
  3558. */
  3559. function theme_button($variables) {
  3560. $element = $variables['element'];
  3561. $element['#attributes']['type'] = 'submit';
  3562. element_set_attributes($element, array('id', 'name', 'value'));
  3563. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3564. if (!empty($element['#attributes']['disabled'])) {
  3565. $element['#attributes']['class'][] = 'form-button-disabled';
  3566. }
  3567. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3568. }
  3569. /**
  3570. * Returns HTML for an image button form element.
  3571. *
  3572. * @param $variables
  3573. * An associative array containing:
  3574. * - element: An associative array containing the properties of the element.
  3575. * Properties used: #attributes, #button_type, #name, #value, #title, #src.
  3576. *
  3577. * @ingroup themeable
  3578. */
  3579. function theme_image_button($variables) {
  3580. $element = $variables['element'];
  3581. $element['#attributes']['type'] = 'image';
  3582. element_set_attributes($element, array('id', 'name', 'value'));
  3583. $element['#attributes']['src'] = file_create_url($element['#src']);
  3584. if (!empty($element['#title'])) {
  3585. $element['#attributes']['alt'] = $element['#title'];
  3586. $element['#attributes']['title'] = $element['#title'];
  3587. }
  3588. $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  3589. if (!empty($element['#attributes']['disabled'])) {
  3590. $element['#attributes']['class'][] = 'form-button-disabled';
  3591. }
  3592. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3593. }
  3594. /**
  3595. * Returns HTML for a hidden form element.
  3596. *
  3597. * @param $variables
  3598. * An associative array containing:
  3599. * - element: An associative array containing the properties of the element.
  3600. * Properties used: #name, #value, #attributes.
  3601. *
  3602. * @ingroup themeable
  3603. */
  3604. function theme_hidden($variables) {
  3605. $element = $variables['element'];
  3606. $element['#attributes']['type'] = 'hidden';
  3607. element_set_attributes($element, array('name', 'value'));
  3608. return '<input' . drupal_attributes($element['#attributes']) . " />\n";
  3609. }
  3610. /**
  3611. * Returns HTML for a textfield form element.
  3612. *
  3613. * @param $variables
  3614. * An associative array containing:
  3615. * - element: An associative array containing the properties of the element.
  3616. * Properties used: #title, #value, #description, #size, #maxlength,
  3617. * #required, #attributes, #autocomplete_path.
  3618. *
  3619. * @ingroup themeable
  3620. */
  3621. function theme_textfield($variables) {
  3622. $element = $variables['element'];
  3623. $element['#attributes']['type'] = 'text';
  3624. element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  3625. _form_set_class($element, array('form-text'));
  3626. $extra = '';
  3627. if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
  3628. drupal_add_library('system', 'drupal.autocomplete');
  3629. $element['#attributes']['class'][] = 'form-autocomplete';
  3630. $attributes = array();
  3631. $attributes['type'] = 'hidden';
  3632. $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
  3633. $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
  3634. $attributes['disabled'] = 'disabled';
  3635. $attributes['class'][] = 'autocomplete';
  3636. $extra = '<input' . drupal_attributes($attributes) . ' />';
  3637. }
  3638. $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
  3639. return $output . $extra;
  3640. }
  3641. /**
  3642. * Returns HTML for a form.
  3643. *
  3644. * @param $variables
  3645. * An associative array containing:
  3646. * - element: An associative array containing the properties of the element.
  3647. * Properties used: #action, #method, #attributes, #children
  3648. *
  3649. * @ingroup themeable
  3650. */
  3651. function theme_form($variables) {
  3652. $element = $variables['element'];
  3653. if (isset($element['#action'])) {
  3654. $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  3655. }
  3656. element_set_attributes($element, array('method', 'id'));
  3657. if (empty($element['#attributes']['accept-charset'])) {
  3658. $element['#attributes']['accept-charset'] = "UTF-8";
  3659. }
  3660. // Anonymous DIV to satisfy XHTML compliance.
  3661. return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
  3662. }
  3663. /**
  3664. * Returns HTML for a textarea form element.
  3665. *
  3666. * @param $variables
  3667. * An associative array containing:
  3668. * - element: An associative array containing the properties of the element.
  3669. * Properties used: #title, #value, #description, #rows, #cols, #required,
  3670. * #attributes
  3671. *
  3672. * @ingroup themeable
  3673. */
  3674. function theme_textarea($variables) {
  3675. $element = $variables['element'];
  3676. element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
  3677. _form_set_class($element, array('form-textarea'));
  3678. $wrapper_attributes = array(
  3679. 'class' => array('form-textarea-wrapper'),
  3680. );
  3681. // Add resizable behavior.
  3682. if (!empty($element['#resizable'])) {
  3683. drupal_add_library('system', 'drupal.textarea');
  3684. $wrapper_attributes['class'][] = 'resizable';
  3685. }
  3686. $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
  3687. $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
  3688. $output .= '</div>';
  3689. return $output;
  3690. }
  3691. /**
  3692. * Returns HTML for a password form element.
  3693. *
  3694. * @param $variables
  3695. * An associative array containing:
  3696. * - element: An associative array containing the properties of the element.
  3697. * Properties used: #title, #value, #description, #size, #maxlength,
  3698. * #required, #attributes.
  3699. *
  3700. * @ingroup themeable
  3701. */
  3702. function theme_password($variables) {
  3703. $element = $variables['element'];
  3704. $element['#attributes']['type'] = 'password';
  3705. element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
  3706. _form_set_class($element, array('form-text'));
  3707. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3708. }
  3709. /**
  3710. * Expands a weight element into a select element.
  3711. */
  3712. function form_process_weight($element) {
  3713. $element['#is_weight'] = TRUE;
  3714. // If the number of options is small enough, use a select field.
  3715. $max_elements = variable_get('drupal_weight_select_max', DRUPAL_WEIGHT_SELECT_MAX);
  3716. if ($element['#delta'] <= $max_elements) {
  3717. $element['#type'] = 'select';
  3718. for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
  3719. $weights[$n] = $n;
  3720. }
  3721. $element['#options'] = $weights;
  3722. $element += element_info('select');
  3723. }
  3724. // Otherwise, use a text field.
  3725. else {
  3726. $element['#type'] = 'textfield';
  3727. // Use a field big enough to fit most weights.
  3728. $element['#size'] = 10;
  3729. $element['#element_validate'] = array('element_validate_integer');
  3730. $element += element_info('textfield');
  3731. }
  3732. return $element;
  3733. }
  3734. /**
  3735. * Returns HTML for a file upload form element.
  3736. *
  3737. * For assistance with handling the uploaded file correctly, see the API
  3738. * provided by file.inc.
  3739. *
  3740. * @param $variables
  3741. * An associative array containing:
  3742. * - element: An associative array containing the properties of the element.
  3743. * Properties used: #title, #name, #size, #description, #required,
  3744. * #attributes.
  3745. *
  3746. * @ingroup themeable
  3747. */
  3748. function theme_file($variables) {
  3749. $element = $variables['element'];
  3750. $element['#attributes']['type'] = 'file';
  3751. element_set_attributes($element, array('id', 'name', 'size'));
  3752. _form_set_class($element, array('form-file'));
  3753. return '<input' . drupal_attributes($element['#attributes']) . ' />';
  3754. }
  3755. /**
  3756. * Returns HTML for a form element.
  3757. *
  3758. * Each form element is wrapped in a DIV container having the following CSS
  3759. * classes:
  3760. * - form-item: Generic for all form elements.
  3761. * - form-type-#type: The internal element #type.
  3762. * - form-item-#name: The internal form element #name (usually derived from the
  3763. * $form structure and set via form_builder()).
  3764. * - form-disabled: Only set if the form element is #disabled.
  3765. *
  3766. * In addition to the element itself, the DIV contains a label for the element
  3767. * based on the optional #title_display property, and an optional #description.
  3768. *
  3769. * The optional #title_display property can have these values:
  3770. * - before: The label is output before the element. This is the default.
  3771. * The label includes the #title and the required marker, if #required.
  3772. * - after: The label is output after the element. For example, this is used
  3773. * for radio and checkbox #type elements as set in system_element_info().
  3774. * If the #title is empty but the field is #required, the label will
  3775. * contain only the required marker.
  3776. * - invisible: Labels are critical for screen readers to enable them to
  3777. * properly navigate through forms but can be visually distracting. This
  3778. * property hides the label for everyone except screen readers.
  3779. * - attribute: Set the title attribute on the element to create a tooltip
  3780. * but output no label element. This is supported only for checkboxes
  3781. * and radios in form_pre_render_conditional_form_element(). It is used
  3782. * where a visual label is not needed, such as a table of checkboxes where
  3783. * the row and column provide the context. The tooltip will include the
  3784. * title and required marker.
  3785. *
  3786. * If the #title property is not set, then the label and any required marker
  3787. * will not be output, regardless of the #title_display or #required values.
  3788. * This can be useful in cases such as the password_confirm element, which
  3789. * creates children elements that have their own labels and required markers,
  3790. * but the parent element should have neither. Use this carefully because a
  3791. * field without an associated label can cause accessibility challenges.
  3792. *
  3793. * @param $variables
  3794. * An associative array containing:
  3795. * - element: An associative array containing the properties of the element.
  3796. * Properties used: #title, #title_display, #description, #id, #required,
  3797. * #children, #type, #name.
  3798. *
  3799. * @ingroup themeable
  3800. */
  3801. function theme_form_element($variables) {
  3802. $element = &$variables['element'];
  3803. // This function is invoked as theme wrapper, but the rendered form element
  3804. // may not necessarily have been processed by form_builder().
  3805. $element += array(
  3806. '#title_display' => 'before',
  3807. );
  3808. // Add element #id for #type 'item'.
  3809. if (isset($element['#markup']) && !empty($element['#id'])) {
  3810. $attributes['id'] = $element['#id'];
  3811. }
  3812. // Add element's #type and #name as class to aid with JS/CSS selectors.
  3813. $attributes['class'] = array('form-item');
  3814. if (!empty($element['#type'])) {
  3815. $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
  3816. }
  3817. if (!empty($element['#name'])) {
  3818. $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  3819. }
  3820. // Add a class for disabled elements to facilitate cross-browser styling.
  3821. if (!empty($element['#attributes']['disabled'])) {
  3822. $attributes['class'][] = 'form-disabled';
  3823. }
  3824. $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
  3825. // If #title is not set, we don't display any label or required marker.
  3826. if (!isset($element['#title'])) {
  3827. $element['#title_display'] = 'none';
  3828. }
  3829. $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
  3830. $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
  3831. switch ($element['#title_display']) {
  3832. case 'before':
  3833. case 'invisible':
  3834. $output .= ' ' . theme('form_element_label', $variables);
  3835. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3836. break;
  3837. case 'after':
  3838. $output .= ' ' . $prefix . $element['#children'] . $suffix;
  3839. $output .= ' ' . theme('form_element_label', $variables) . "\n";
  3840. break;
  3841. case 'none':
  3842. case 'attribute':
  3843. // Output no label and no required marker, only the children.
  3844. $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
  3845. break;
  3846. }
  3847. if (!empty($element['#description'])) {
  3848. $output .= '<div class="description">' . $element['#description'] . "</div>\n";
  3849. }
  3850. $output .= "</div>\n";
  3851. return $output;
  3852. }
  3853. /**
  3854. * Returns HTML for a marker for required form elements.
  3855. *
  3856. * @param $variables
  3857. * An associative array containing:
  3858. * - element: An associative array containing the properties of the element.
  3859. *
  3860. * @ingroup themeable
  3861. */
  3862. function theme_form_required_marker($variables) {
  3863. // This is also used in the installer, pre-database setup.
  3864. $t = get_t();
  3865. $attributes = array(
  3866. 'class' => 'form-required',
  3867. 'title' => $t('This field is required.'),
  3868. );
  3869. return '<span' . drupal_attributes($attributes) . '>*</span>';
  3870. }
  3871. /**
  3872. * Returns HTML for a form element label and required marker.
  3873. *
  3874. * Form element labels include the #title and a #required marker. The label is
  3875. * associated with the element itself by the element #id. Labels may appear
  3876. * before or after elements, depending on theme_form_element() and
  3877. * #title_display.
  3878. *
  3879. * This function will not be called for elements with no labels, depending on
  3880. * #title_display. For elements that have an empty #title and are not required,
  3881. * this function will output no label (''). For required elements that have an
  3882. * empty #title, this will output the required marker alone within the label.
  3883. * The label will use the #id to associate the marker with the field that is
  3884. * required. That is especially important for screenreader users to know
  3885. * which field is required.
  3886. *
  3887. * @param $variables
  3888. * An associative array containing:
  3889. * - element: An associative array containing the properties of the element.
  3890. * Properties used: #required, #title, #id, #value, #description.
  3891. *
  3892. * @ingroup themeable
  3893. */
  3894. function theme_form_element_label($variables) {
  3895. $element = $variables['element'];
  3896. // This is also used in the installer, pre-database setup.
  3897. $t = get_t();
  3898. // If title and required marker are both empty, output no label.
  3899. if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
  3900. return '';
  3901. }
  3902. // If the element is required, a required marker is appended to the label.
  3903. $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
  3904. $title = filter_xss_admin($element['#title']);
  3905. $attributes = array();
  3906. // Style the label as class option to display inline with the element.
  3907. if ($element['#title_display'] == 'after') {
  3908. $attributes['class'] = 'option';
  3909. }
  3910. // Show label only to screen readers to avoid disruption in visual flows.
  3911. elseif ($element['#title_display'] == 'invisible') {
  3912. $attributes['class'] = 'element-invisible';
  3913. }
  3914. if (!empty($element['#id'])) {
  3915. $attributes['for'] = $element['#id'];
  3916. }
  3917. // The leading whitespace helps visually separate fields from inline labels.
  3918. return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
  3919. }
  3920. /**
  3921. * Sets a form element's class attribute.
  3922. *
  3923. * Adds 'required' and 'error' classes as needed.
  3924. *
  3925. * @param $element
  3926. * The form element.
  3927. * @param $name
  3928. * Array of new class names to be added.
  3929. */
  3930. function _form_set_class(&$element, $class = array()) {
  3931. if (!empty($class)) {
  3932. if (!isset($element['#attributes']['class'])) {
  3933. $element['#attributes']['class'] = array();
  3934. }
  3935. $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
  3936. }
  3937. // This function is invoked from form element theme functions, but the
  3938. // rendered form element may not necessarily have been processed by
  3939. // form_builder().
  3940. if (!empty($element['#required'])) {
  3941. $element['#attributes']['class'][] = 'required';
  3942. }
  3943. if (isset($element['#parents']) && form_get_error($element) !== NULL && !empty($element['#validated'])) {
  3944. $element['#attributes']['class'][] = 'error';
  3945. }
  3946. }
  3947. /**
  3948. * Form element validation handler for integer elements.
  3949. */
  3950. function element_validate_integer($element, &$form_state) {
  3951. $value = $element['#value'];
  3952. if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
  3953. form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
  3954. }
  3955. }
  3956. /**
  3957. * Form element validation handler for integer elements that must be positive.
  3958. */
  3959. function element_validate_integer_positive($element, &$form_state) {
  3960. $value = $element['#value'];
  3961. if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
  3962. form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
  3963. }
  3964. }
  3965. /**
  3966. * Form element validation handler for number elements.
  3967. */
  3968. function element_validate_number($element, &$form_state) {
  3969. $value = $element['#value'];
  3970. if ($value != '' && !is_numeric($value)) {
  3971. form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
  3972. }
  3973. }
  3974. /**
  3975. * @} End of "defgroup form_api".
  3976. */
  3977. /**
  3978. * @defgroup batch Batch operations
  3979. * @{
  3980. * Creates and processes batch operations.
  3981. *
  3982. * Functions allowing forms processing to be spread out over several page
  3983. * requests, thus ensuring that the processing does not get interrupted
  3984. * because of a PHP timeout, while allowing the user to receive feedback
  3985. * on the progress of the ongoing operations.
  3986. *
  3987. * The API is primarily designed to integrate nicely with the Form API
  3988. * workflow, but can also be used by non-Form API scripts (like update.php)
  3989. * or even simple page callbacks (which should probably be used sparingly).
  3990. *
  3991. * Example:
  3992. * @code
  3993. * $batch = array(
  3994. * 'title' => t('Exporting'),
  3995. * 'operations' => array(
  3996. * array('my_function_1', array($account->uid, 'story')),
  3997. * array('my_function_2', array()),
  3998. * ),
  3999. * 'finished' => 'my_finished_callback',
  4000. * 'file' => 'path_to_file_containing_myfunctions',
  4001. * );
  4002. * batch_set($batch);
  4003. * // Only needed if not inside a form _submit handler.
  4004. * // Setting redirect in batch_process.
  4005. * batch_process('node/1');
  4006. * @endcode
  4007. *
  4008. * Note: if the batch 'title', 'init_message', 'progress_message', or
  4009. * 'error_message' could contain any user input, it is the responsibility of
  4010. * the code calling batch_set() to sanitize them first with a function like
  4011. * check_plain() or filter_xss(). Furthermore, if the batch operation
  4012. * returns any user input in the 'results' or 'message' keys of $context,
  4013. * it must also sanitize them first.
  4014. *
  4015. * Sample batch operations:
  4016. * @code
  4017. * // Simple and artificial: load a node of a given type for a given user
  4018. * function my_function_1($uid, $type, &$context) {
  4019. * // The $context array gathers batch context information about the execution (read),
  4020. * // as well as 'return values' for the current operation (write)
  4021. * // The following keys are provided :
  4022. * // 'results' (read / write): The array of results gathered so far by
  4023. * // the batch processing, for the current operation to append its own.
  4024. * // 'message' (write): A text message displayed in the progress page.
  4025. * // The following keys allow for multi-step operations :
  4026. * // 'sandbox' (read / write): An array that can be freely used to
  4027. * // store persistent data between iterations. It is recommended to
  4028. * // use this instead of $_SESSION, which is unsafe if the user
  4029. * // continues browsing in a separate window while the batch is processing.
  4030. * // 'finished' (write): A float number between 0 and 1 informing
  4031. * // the processing engine of the completion level for the operation.
  4032. * // 1 (or no value explicitly set) means the operation is finished
  4033. * // and the batch processing can continue to the next operation.
  4034. *
  4035. * $node = node_load(array('uid' => $uid, 'type' => $type));
  4036. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  4037. * $context['message'] = check_plain($node->title);
  4038. * }
  4039. *
  4040. * // More advanced example: multi-step operation - load all nodes, five by five
  4041. * function my_function_2(&$context) {
  4042. * if (empty($context['sandbox'])) {
  4043. * $context['sandbox']['progress'] = 0;
  4044. * $context['sandbox']['current_node'] = 0;
  4045. * $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
  4046. * }
  4047. * $limit = 5;
  4048. * $result = db_select('node')
  4049. * ->fields('node', array('nid'))
  4050. * ->condition('nid', $context['sandbox']['current_node'], '>')
  4051. * ->orderBy('nid')
  4052. * ->range(0, $limit)
  4053. * ->execute();
  4054. * foreach ($result as $row) {
  4055. * $node = node_load($row->nid, NULL, TRUE);
  4056. * $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
  4057. * $context['sandbox']['progress']++;
  4058. * $context['sandbox']['current_node'] = $node->nid;
  4059. * $context['message'] = check_plain($node->title);
  4060. * }
  4061. * if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
  4062. * $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  4063. * }
  4064. * }
  4065. * @endcode
  4066. *
  4067. * Sample 'finished' callback:
  4068. * @code
  4069. * function batch_test_finished($success, $results, $operations) {
  4070. * // The 'success' parameter means no fatal PHP errors were detected. All
  4071. * // other error management should be handled using 'results'.
  4072. * if ($success) {
  4073. * $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
  4074. * }
  4075. * else {
  4076. * $message = t('Finished with an error.');
  4077. * }
  4078. * drupal_set_message($message);
  4079. * // Providing data for the redirected page is done through $_SESSION.
  4080. * foreach ($results as $result) {
  4081. * $items[] = t('Loaded node %title.', array('%title' => $result));
  4082. * }
  4083. * $_SESSION['my_batch_results'] = $items;
  4084. * }
  4085. * @endcode
  4086. */
  4087. /**
  4088. * Adds a new batch.
  4089. *
  4090. * Batch operations are added as new batch sets. Batch sets are used to spread
  4091. * processing (primarily, but not exclusively, forms processing) over several
  4092. * page requests. This helps to ensure that the processing is not interrupted
  4093. * due to PHP timeouts, while users are still able to receive feedback on the
  4094. * progress of the ongoing operations. Combining related operations into
  4095. * distinct batch sets provides clean code independence for each batch set,
  4096. * ensuring that two or more batches, submitted independently, can be processed
  4097. * without mutual interference. Each batch set may specify its own set of
  4098. * operations and results, produce its own UI messages, and trigger its own
  4099. * 'finished' callback. Batch sets are processed sequentially, with the progress
  4100. * bar starting afresh for each new set.
  4101. *
  4102. * @param $batch_definition
  4103. * An associative array defining the batch, with the following elements (all
  4104. * are optional except as noted):
  4105. * - operations: (required) Array of function calls to be performed.
  4106. * Example:
  4107. * @code
  4108. * array(
  4109. * array('my_function_1', array($arg1)),
  4110. * array('my_function_2', array($arg2_1, $arg2_2)),
  4111. * )
  4112. * @endcode
  4113. * - title: A safe, translated string to use as the title for the progress
  4114. * page. Defaults to t('Processing').
  4115. * - init_message: Message displayed while the processing is initialized.
  4116. * Defaults to t('Initializing.').
  4117. * - progress_message: Message displayed while processing the batch. Available
  4118. * placeholders are @current, @remaining, @total, @percentage, @estimate and
  4119. * @elapsed. Defaults to t('Completed @current of @total.').
  4120. * - error_message: Message displayed if an error occurred while processing
  4121. * the batch. Defaults to t('An error has occurred.').
  4122. * - finished: Name of a function to be executed after the batch has
  4123. * completed. This should be used to perform any result massaging that may
  4124. * be needed, and possibly save data in $_SESSION for display after final
  4125. * page redirection.
  4126. * - file: Path to the file containing the definitions of the 'operations' and
  4127. * 'finished' functions, for instance if they don't reside in the main
  4128. * .module file. The path should be relative to base_path(), and thus should
  4129. * be built using drupal_get_path().
  4130. * - css: Array of paths to CSS files to be used on the progress page.
  4131. * - url_options: options passed to url() when constructing redirect URLs for
  4132. * the batch.
  4133. */
  4134. function batch_set($batch_definition) {
  4135. if ($batch_definition) {
  4136. $batch =& batch_get();
  4137. // Initialize the batch if needed.
  4138. if (empty($batch)) {
  4139. $batch = array(
  4140. 'sets' => array(),
  4141. 'has_form_submits' => FALSE,
  4142. );
  4143. }
  4144. // Base and default properties for the batch set.
  4145. // Use get_t() to allow batches during installation.
  4146. $t = get_t();
  4147. $init = array(
  4148. 'sandbox' => array(),
  4149. 'results' => array(),
  4150. 'success' => FALSE,
  4151. 'start' => 0,
  4152. 'elapsed' => 0,
  4153. );
  4154. $defaults = array(
  4155. 'title' => $t('Processing'),
  4156. 'init_message' => $t('Initializing.'),
  4157. 'progress_message' => $t('Completed @current of @total.'),
  4158. 'error_message' => $t('An error has occurred.'),
  4159. 'css' => array(),
  4160. );
  4161. $batch_set = $init + $batch_definition + $defaults;
  4162. // Tweak init_message to avoid the bottom of the page flickering down after
  4163. // init phase.
  4164. $batch_set['init_message'] .= '<br/>&nbsp;';
  4165. // The non-concurrent workflow of batch execution allows us to save
  4166. // numberOfItems() queries by handling our own counter.
  4167. $batch_set['total'] = count($batch_set['operations']);
  4168. $batch_set['count'] = $batch_set['total'];
  4169. // Add the set to the batch.
  4170. if (empty($batch['id'])) {
  4171. // The batch is not running yet. Simply add the new set.
  4172. $batch['sets'][] = $batch_set;
  4173. }
  4174. else {
  4175. // The set is being added while the batch is running. Insert the new set
  4176. // right after the current one to ensure execution order, and store its
  4177. // operations in a queue.
  4178. $index = $batch['current_set'] + 1;
  4179. $slice1 = array_slice($batch['sets'], 0, $index);
  4180. $slice2 = array_slice($batch['sets'], $index);
  4181. $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
  4182. _batch_populate_queue($batch, $index);
  4183. }
  4184. }
  4185. }
  4186. /**
  4187. * Processes the batch.
  4188. *
  4189. * Unless the batch has been marked with 'progressive' = FALSE, the function
  4190. * issues a drupal_goto and thus ends page execution.
  4191. *
  4192. * This function is generally not needed in form submit handlers;
  4193. * Form API takes care of batches that were set during form submission.
  4194. *
  4195. * @param $redirect
  4196. * (optional) Path to redirect to when the batch has finished processing.
  4197. * @param $url
  4198. * (optional - should only be used for separate scripts like update.php)
  4199. * URL of the batch processing page.
  4200. * @param $redirect_callback
  4201. * (optional) Specify a function to be called to redirect to the progressive
  4202. * processing page. By default drupal_goto() will be used to redirect to a
  4203. * page which will do the progressive page. Specifying another function will
  4204. * allow the progressive processing to be processed differently.
  4205. */
  4206. function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = 'drupal_goto') {
  4207. $batch =& batch_get();
  4208. drupal_theme_initialize();
  4209. if (isset($batch)) {
  4210. // Add process information
  4211. $process_info = array(
  4212. 'current_set' => 0,
  4213. 'progressive' => TRUE,
  4214. 'url' => $url,
  4215. 'url_options' => array(),
  4216. 'source_url' => $_GET['q'],
  4217. 'redirect' => $redirect,
  4218. 'theme' => $GLOBALS['theme_key'],
  4219. 'redirect_callback' => $redirect_callback,
  4220. );
  4221. $batch += $process_info;
  4222. // The batch is now completely built. Allow other modules to make changes
  4223. // to the batch so that it is easier to reuse batch processes in other
  4224. // environments.
  4225. drupal_alter('batch', $batch);
  4226. // Assign an arbitrary id: don't rely on a serial column in the 'batch'
  4227. // table, since non-progressive batches skip database storage completely.
  4228. $batch['id'] = db_next_id();
  4229. // Move operations to a job queue. Non-progressive batches will use a
  4230. // memory-based queue.
  4231. foreach ($batch['sets'] as $key => $batch_set) {
  4232. _batch_populate_queue($batch, $key);
  4233. }
  4234. // Initiate processing.
  4235. if ($batch['progressive']) {
  4236. // Now that we have a batch id, we can generate the redirection link in
  4237. // the generic error message.
  4238. $t = get_t();
  4239. $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')))));
  4240. // Clear the way for the drupal_goto() redirection to the batch processing
  4241. // page, by saving and unsetting the 'destination', if there is any.
  4242. if (isset($_GET['destination'])) {
  4243. $batch['destination'] = $_GET['destination'];
  4244. unset($_GET['destination']);
  4245. }
  4246. // Store the batch.
  4247. db_insert('batch')
  4248. ->fields(array(
  4249. 'bid' => $batch['id'],
  4250. 'timestamp' => REQUEST_TIME,
  4251. 'token' => drupal_get_token($batch['id']),
  4252. 'batch' => serialize($batch),
  4253. ))
  4254. ->execute();
  4255. // Set the batch number in the session to guarantee that it will stay alive.
  4256. $_SESSION['batches'][$batch['id']] = TRUE;
  4257. // Redirect for processing.
  4258. $function = $batch['redirect_callback'];
  4259. if (function_exists($function)) {
  4260. $function($batch['url'], array('query' => array('op' => 'start', 'id' => $batch['id'])));
  4261. }
  4262. }
  4263. else {
  4264. // Non-progressive execution: bypass the whole progressbar workflow
  4265. // and execute the batch in one pass.
  4266. require_once DRUPAL_ROOT . '/includes/batch.inc';
  4267. _batch_process();
  4268. }
  4269. }
  4270. }
  4271. /**
  4272. * Retrieves the current batch.
  4273. */
  4274. function &batch_get() {
  4275. // Not drupal_static(), because Batch API operates at a lower level than most
  4276. // use-cases for resetting static variables, and we specifically do not want a
  4277. // global drupal_static_reset() resetting the batch information. Functions
  4278. // that are part of the Batch API and need to reset the batch information may
  4279. // call batch_get() and manipulate the result by reference. Functions that are
  4280. // not part of the Batch API can also do this, but shouldn't.
  4281. static $batch = array();
  4282. return $batch;
  4283. }
  4284. /**
  4285. * Populates a job queue with the operations of a batch set.
  4286. *
  4287. * Depending on whether the batch is progressive or not, the BatchQueue or
  4288. * BatchMemoryQueue handler classes will be used.
  4289. *
  4290. * @param $batch
  4291. * The batch array.
  4292. * @param $set_id
  4293. * The id of the set to process.
  4294. *
  4295. * @return
  4296. * The name and class of the queue are added by reference to the batch set.
  4297. */
  4298. function _batch_populate_queue(&$batch, $set_id) {
  4299. $batch_set = &$batch['sets'][$set_id];
  4300. if (isset($batch_set['operations'])) {
  4301. $batch_set += array(
  4302. 'queue' => array(
  4303. 'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
  4304. 'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
  4305. ),
  4306. );
  4307. $queue = _batch_queue($batch_set);
  4308. $queue->createQueue();
  4309. foreach ($batch_set['operations'] as $operation) {
  4310. $queue->createItem($operation);
  4311. }
  4312. unset($batch_set['operations']);
  4313. }
  4314. }
  4315. /**
  4316. * Returns a queue object for a batch set.
  4317. *
  4318. * @param $batch_set
  4319. * The batch set.
  4320. *
  4321. * @return
  4322. * The queue object.
  4323. */
  4324. function _batch_queue($batch_set) {
  4325. static $queues;
  4326. // The class autoloader is not available when running update.php, so make
  4327. // sure the files are manually included.
  4328. if (!isset($queues)) {
  4329. $queues = array();
  4330. require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
  4331. require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
  4332. }
  4333. if (isset($batch_set['queue'])) {
  4334. $name = $batch_set['queue']['name'];
  4335. $class = $batch_set['queue']['class'];
  4336. if (!isset($queues[$class][$name])) {
  4337. $queues[$class][$name] = new $class($name);
  4338. }
  4339. return $queues[$class][$name];
  4340. }
  4341. }
  4342. /**
  4343. * @} End of "defgroup batch".
  4344. */