source: sipes/cord/includes/form.inc @ 6926c6e

stableversion-3.0
Last change on this file since 6926c6e was 6627152, checked in by José Gregorio Puentes <jpuentes@…>, 8 años ago

se actualizo el cord

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