1. 8.2.x core/includes/form.inc
  2. 8.0.x core/includes/form.inc
  3. 8.1.x core/includes/form.inc
  4. 8.3.x core/includes/form.inc
  5. 4.7.x includes/form.inc
  6. 5.x includes/form.inc
  7. 6.x includes/form.inc
  8. 7.x includes/form.inc

File

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

Functions

Namesort descending Description
batch_get Retrieves the current batch.
batch_process Processes the batch.
batch_set Opens a new batch.
date_validate Validates the date type to stop dates like February 30, 2006.
drupal_execute Retrieves, populates, and processes a form.
drupal_get_form Retrieves a form from a constructor function, or from the cache if the form was built in a previous page-load. The form is then passed on for processing, after and rendered for display if necessary.
drupal_prepare_form Prepares a structured form array by adding required elements, executing any hook_form_alter functions, and optionally inserting a validation token to prevent tampering.
drupal_process_form This function is the heart of form API. The form gets built, validated and in appropriate cases, submitted.
drupal_rebuild_form Retrieves a form, caches it and processes it with an empty $_POST.
drupal_redirect_form Redirect the user to a URL after a form has been processed.
drupal_render_form Renders a structured form array into themed HTML.
drupal_retrieve_form Retrieves the structured array that defines a given form.
drupal_validate_form Validates user-submitted form data from the $form_state using the validate functions defined in a structured form array.
expand_checkboxes
expand_date Roll out a single date element.
expand_password_confirm Expand a password_confirm field into two text boxes.
expand_radios Roll out a single radios element to a list of radios, using the options array as index.
form_builder Walk through the structured form array, adding any required properties to each element and mapping the incoming $_POST data to the proper elements.
form_build_id_map Maintain a map of immutable form_build_ids to cloned form.
form_clean_id Prepare an HTML ID attribute string for a form item.
form_error Flag an element as having an error.
form_execute_handlers A helper function used to execute custom validation and submission handlers for a given form. Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
form_expand_ahah Add AHAH information about a form element to the page to communicate with javascript. If #ahah[path] is set on an element, this additional javascript is added to the page header to attach the AHAH behaviors. See ahah.js for more information.
form_get_cache Fetch a form from cache.
form_get_error Return the error message filed against the form with the specified name.
form_get_errors Return an associative array of all errors.
form_get_options Traverses a select element's #option array looking for any values that hold the given key. Returns an array of indexes that match.
form_options_flatten
form_process_autocomplete Process function to prepare autocomplete data.
form_select_options
form_set_cache Store a form in the cache.
form_set_error File an error against a form element.
form_set_value Change submitted form values during the form processing cycle.
form_type_checkboxes_value Helper function to determine the value for a checkboxes form element.
form_type_checkbox_value Helper function to determine the value for a checkbox form element.
form_type_image_button_value Helper function to determine the value for an image button form element.
form_type_password_confirm_value Helper function to determine the value for a password_confirm form element.
form_type_select_value Helper function to determine the value for a select form element.
form_type_textfield_value Helper function to determine the value for a textfield form element.
form_type_token_value Helper function to determine the value for form's token value.
map_month Helper function for usage with drupal_map_assoc to display month names.
password_confirm_validate Validate password_confirm element.
process_weight Expand weight elements into selects.
theme_button Theme a form button.
theme_checkbox Format a checkbox.
theme_checkboxes Format a set of checkboxes.
theme_date Format a date selection element.
theme_fieldset Format a group of form items.
theme_file Format a file upload field.
theme_form Format a form.
theme_form_element Return a themed form element.
theme_hidden Format a hidden form field.
theme_image_button Theme a form image button.
theme_item Format a form item.
theme_markup
theme_password Format a password field.
theme_password_confirm Format a password_confirm item.
theme_radio Format a radio button.
theme_radios Format a set of radio buttons.
theme_select Format a dropdown menu or scrolling selection box.
theme_submit Theme a form submit button.
theme_textarea Format a textarea.
theme_textfield Format a textfield.
theme_token Format a form token.
weight_value If no default value is set for weight select boxes, use 0.
_element_info Retrieve the default properties for the defined element type.
_form_builder_handle_input_element Populate the #value and #name properties of input elements so they can be processed and rendered. Also, execute any #process handlers attached to a specific element.
_form_builder_ie_cleanup In IE, if only one submit button is present, AND the enter key is used to submit the form, no form value is sent for it and our normal button detection code will never detect a match. We call this function after all other button-detection is complete…
_form_button_was_clicked Helper function to handle the sometimes-convoluted logic of button click detection.
_form_set_class Sets a form element's class attribute.
_form_set_value Helper function for form_set_value().
_form_validate Performs validation on form elements. First ensures required fields are completed, #maxlength is not exceeded, and selected options were in the list of options given to the user. Then calls user-defined validators.