form.inc

Archivo

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

Functions

Nombreorden descendente Descripción
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_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_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.