initial import from onelab svn codebase
[plewww.git] / includes / form.inc
1 <?php
2 // $Id: form.inc 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @defgroup form Form generation
6  * @{
7  * Functions to enable output of HTML forms and form elements.
8  *
9  * Drupal uses these functions to achieve consistency in its form presentation,
10  * while at the same time simplifying code and reducing the amount of HTML that
11  * must be explicitly generated by modules. See the reference at
12  * http://api.drupal.org/api/HEAD/file/developer/topics/forms_api_reference.html
13  * and the quickstart guide at
14  * http://api.drupal.org/api/HEAD/file/developer/topics/forms_api.html
15  */
16
17 /**
18  * Check if the key is a property.
19  */
20 function element_property($key) {
21   return $key[0] == '#';
22 }
23
24 /**
25  * Get properties of a form tree element. Properties begin with '#'.
26  */
27 function element_properties($element) {
28   return array_filter(array_keys((array) $element), 'element_property');
29 }
30
31 /**
32  * Check if the key is a child.
33  */
34 function element_child($key) {
35   return $key[0] != '#';
36 }
37
38 /**
39  * Get keys of a form tree element that are not properties (i.e., do not begin with '#').
40  */
41 function element_children($element) {
42   return array_filter(array_keys((array) $element), 'element_child');
43 }
44
45 /**
46  * Processes a form array and produces the HTML output of a form.
47  * If there is input in the $_POST['edit'] variable, this function
48  * will attempt to validate it, using drupal_validate_form(),
49  * and then submit the form using drupal_submit_form().
50  *
51  * @param $form_id
52  *   A unique string identifying the form. Allows each form to be
53  *   themed.  Pass NULL to suppress the form_id parameter (produces
54  *   a shorter URL with method=get)
55  * @param $form
56  *   An associative array containing the structure of the form.
57  * @param $callback
58  *   An optional callback that will be used in addition to the form_id.
59  *
60  */
61 function drupal_get_form($form_id, &$form, $callback = NULL) {
62   global $form_values, $form_submitted, $user, $form_button_counter;
63   static $saved_globals = array();
64
65   // Save globals in case of indirect recursive call
66   array_push($saved_globals, array($form_values, $form_submitted, $form_button_counter));
67
68   $form_values = array();
69   $form_submitted = FALSE;
70   $form_button_counter = array(0, 0);
71
72   $form['#type'] = 'form';
73   if (isset($form['#token'])) {
74     if (variable_get('cache', 0) && !$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET') {
75       unset($form['#token']);
76     }
77     else {
78       // Make sure that a private key is set:
79       if (!variable_get('drupal_private_key', '')) {
80         variable_set('drupal_private_key', mt_rand());
81       }
82
83       $form['form_token'] = array('#type' => 'hidden', '#default_value' => md5(session_id() . $form['#token'] . variable_get('drupal_private_key', '')));
84     }
85   }
86   if (isset($form_id)) {
87     $form['form_id'] = array('#type' => 'hidden', '#value' => $form_id, '#id' => str_replace('_', '-', "edit-$form_id"));
88   }
89   if (!isset($form['#id'])) {
90     $form['#id'] = $form_id;
91   }
92
93   $form += _element_info('form');
94
95   if (!isset($form['#validate'])) {
96     if (function_exists($form_id .'_validate')) {
97       $form['#validate'] = array($form_id .'_validate' => array());
98     }
99     elseif (function_exists($callback .'_validate')) {
100       $form['#validate'] = array($callback .'_validate' => array());
101     }
102   }
103
104   if (!isset($form['#submit'])) {
105     if (function_exists($form_id .'_submit')) {
106       // we set submit here so that it can be altered but use reference for
107       // $form_values because it will change later
108       $form['#submit'] = array($form_id .'_submit' => array());
109     }
110     elseif (function_exists($callback .'_submit')) {
111       $form['#submit'] = array($callback .'_submit' => array());
112     }
113   }
114
115   foreach (module_implements('form_alter') as $module) {
116     $function = $module .'_form_alter';
117     $function($form_id, $form);
118   }
119
120   $form = form_builder($form_id, $form);
121   if (!empty($_POST['edit']) && (($_POST['edit']['form_id'] == $form_id) || ($_POST['edit']['form_id'] == $callback))) {
122     drupal_validate_form($form_id, $form, $callback);
123     // IE does not send a button value when there is only one submit button (and no non-submit buttons)
124     // and you submit by pressing enter.
125     // In that case we accept a submission without button values.
126     if (($form_submitted || (!$form_button_counter[0] && $form_button_counter[1])) && !form_get_errors()) {
127       $redirect = drupal_submit_form($form_id, $form, $callback);
128       if (isset($redirect)) {
129         $goto = $redirect;
130       }
131       if (isset($form['#redirect'])) {
132         $goto = $form['#redirect'];
133       }
134       if ($goto !== FALSE) {
135         if (is_array($goto)) {
136           call_user_func_array('drupal_goto', $goto);
137         }
138         elseif (!isset($goto)) {
139           drupal_goto($_GET['q']);
140         }
141         else {
142           drupal_goto($goto);
143         }
144       }
145     }
146   }
147
148   // Don't override #theme if someone already set it.
149   if (!isset($form['#theme'])) {
150     if (theme_get_function($form_id)) {
151       $form['#theme'] = $form_id;
152     }
153     elseif (theme_get_function($callback)) {
154       $form['#theme'] = $callback;
155     }
156   }
157
158   if (isset($form['#pre_render'])) {
159     foreach ($form['#pre_render'] as $function) {
160       if (function_exists($function)) {
161         $function($form_id, $form);
162       }
163     }
164   }
165
166   $output = form_render($form);
167   // Restore globals
168   list($form_values, $form_submitted, $form_button_counter) = array_pop($saved_globals);
169   return $output;
170 }
171
172 function drupal_validate_form($form_id, $form, $callback = NULL) {
173   global $form_values;
174   static $validated_forms = array();
175
176   if (isset($validated_forms[$form_id])) {
177     return;
178   }
179
180   if (isset($form['#token'])) {
181     if ($form_values['form_token'] != md5(session_id() . $form['#token'] . variable_get('drupal_private_key', ''))) {
182       // setting this error will cause the form to fail validation
183       form_set_error('form_token', t('Validation error, please try again.  If this error persists, please contact the site administrator.'));
184     }
185   }
186
187   _form_validate($form, $form_id);
188   $validated_forms[$form_id] = TRUE;
189 }
190
191 function drupal_submit_form($form_id, $form, $callback = NULL) {
192   global $form_values;
193   $default_args = array($form_id, &$form_values);
194
195   if (isset($form['#submit'])) {
196     foreach ($form['#submit'] as $function => $args) {
197       if (function_exists($function)) {
198         $args = array_merge($default_args, (array) $args);
199         // Since we can only redirect to one page, only the last redirect will work
200         $redirect = call_user_func_array($function, $args);
201         if (isset($redirect)) {
202           $goto = $redirect;
203         }
204       }
205     }
206   }
207   return $goto;
208 }
209
210 function _form_validate($elements, $form_id = NULL) {
211   // Recurse through all children.
212   foreach (element_children($elements) as $key) {
213     if (isset($elements[$key]) && $elements[$key]) {
214       _form_validate($elements[$key]);
215     }
216   }
217   /* Validate the current input */
218   if (!$elements['#validated']) {
219     if (isset($elements['#needs_validation'])) {
220       // An empty textfield returns '' so we use empty(). An empty checkbox
221       // and a textfield could return '0' and empty('0') returns TRUE so we
222       // need a special check for the '0' string.
223       if ($elements['#required'] && empty($elements['#value']) && $elements['#value'] !== '0') {
224         form_error($elements, t('%name field is required.', array('%name' => $elements['#title'])));
225       }
226
227       // Add legal choice check if element has #options. Can be skipped, but then you must validate your own element.
228       if (isset($elements['#options']) && isset($elements['#value']) && !isset($elements['#DANGEROUS_SKIP_CHECK'])) {
229         if ($elements['#type'] == 'select') {
230           $options = form_options_flatten($elements['#options']);
231         }
232         else {
233           $options = $elements['#options'];
234         }
235         if (is_array($elements['#value'])) {
236           $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
237           foreach ($value as $v) {
238             if (!isset($options[$v])) {
239               form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
240               watchdog('form', t('Illegal choice %choice in %name element.', array('%choice' => theme('placeholder', check_plain($v)), '%name' => theme_placeholder(empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']))), WATCHDOG_ERROR);
241             }
242           }
243         }
244         elseif (!isset($options[$elements['#value']])) {
245           form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
246           watchdog('form', t('Illegal choice %choice in %name element.', array('%choice' => theme_placeholder(check_plain($v)), '%name' => theme('placeholder', empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']))), WATCHDOG_ERROR);
247         }
248       }
249     }
250
251     // User-applied checks.
252     if (isset($elements['#validate'])) {
253       foreach ($elements['#validate'] as $function => $args) {
254         $args = array_merge(array($elements), $args);
255         // for the full form we hand over a copy of $form_values
256         if (isset($form_id)) {
257           $args = array_merge(array($form_id, $GLOBALS['form_values']), $args);
258         }
259         if (function_exists($function))  {
260           call_user_func_array($function, $args);
261         }
262       }
263     }
264     $elements['#validated'] = TRUE;
265   }
266 }
267
268 /**
269  * File an error against a form element. If the name of the element is
270  * edit[foo][bar] then you may pass either foo or foo][bar as $name
271  * foo will set an error for all its children.
272  */
273 function form_set_error($name = NULL, $message = '') {
274   static $form = array();
275   if (isset($name) && !isset($form[$name])) {
276     $form[$name] = $message;
277     if ($message) {
278       drupal_set_message($message, 'error');
279     }
280   }
281   return $form;
282 }
283
284 /**
285  * Return an associative array of all errors.
286  */
287 function form_get_errors() {
288   $form = form_set_error();
289   if (!empty($form)) {
290     return $form;
291   }
292 }
293
294 /**
295  * Return the error message filed against the form with the specified name.
296  */
297 function form_get_error($element) {
298   $form = form_set_error();
299   $key = $element['#parents'][0];
300   if (isset($form[$key])) {
301     return $form[$key];
302   }
303   $key = implode('][', $element['#parents']);
304   if (isset($form[$key])) {
305     return $form[$key];
306   }
307 }
308
309 /**
310  * Flag an element as having an error.
311  */
312 function form_error(&$element, $message = '') {
313   $element['#error'] = TRUE;
314   form_set_error(implode('][', $element['#parents']), $message);
315 }
316
317 /**
318  * Adds some required properties to each form element, which are used
319  * internally in the form api. This function also automatically assigns
320  * the value property from the $edit array, provided the element doesn't
321  * already have an assigned value.
322  *
323  * @param $form_id
324  *   A unique string identifying the form. Allows each form to be themed.
325  * @param $form
326  *   An associative array containing the structure of the form.
327  */
328 function form_builder($form_id, $form) {
329   global $form_values, $form_submitted, $form_button_counter;
330
331   // Initialize as unprocessed.
332   $form['#processed'] = FALSE;
333
334   /* Use element defaults */
335   if ((!empty($form['#type'])) && ($info = _element_info($form['#type']))) {
336     // overlay $info onto $form, retaining preexisting keys in $form
337     $form += $info;
338   }
339
340   if (isset($form['#input']) && $form['#input']) {
341     if (!isset($form['#name'])) {
342       $form['#name'] = 'edit[' . implode('][', $form['#parents']) . ']';
343     }
344     if (!isset($form['#id'])) {
345       $form['#id'] =  'edit-' . implode('-', $form['#parents']);
346     }
347
348     $posted = (isset($_POST['edit']) && ($_POST['edit']['form_id'] == $form_id));
349     $edit = $posted ? $_POST['edit'] : array();
350     foreach ($form['#parents'] as $parent) {
351       $edit = isset($edit[$parent]) ? $edit[$parent] : NULL;
352     }
353     if (!isset($form['#value']) && !array_key_exists('#value', $form)) {
354       if ($posted) {
355         switch ($form['#type']) {
356           case 'checkbox':
357             $form['#value'] = !empty($edit) ? $form['#return_value'] : 0;
358             break;
359           case 'select':
360             if (isset($form['#multiple']) && $form['#multiple']) {
361               if (isset($edit) && is_array($edit)) {
362                 $form['#value'] = drupal_map_assoc($edit);
363               }
364               else {
365                 $form['#value'] = array();
366               }
367             }
368             elseif (isset($edit)) {
369               $form['#value'] = $edit;
370             }
371             break;
372           case 'textfield':
373             if (isset($edit)) {
374               // Equate $edit to the form value to ensure it's marked for validation
375               $edit = str_replace(array("\r", "\n"), '', $edit);
376               $form['#value'] = $edit;
377             }
378             break;
379           default:
380             if (isset($edit)) {
381               $form['#value'] = $edit;
382             }
383         }
384         // Mark all posted values for validation
385         if ((isset($form['#value']) && $form['#value'] === $edit) || (isset($form['#required']) && $form['#required'])) {
386           $form['#needs_validation'] = TRUE;
387         }
388       }
389       if (!isset($form['#value'])) {
390         $function = $form['#type'] . '_value';
391         if (function_exists($function)) {
392           $function($form);
393         }
394         else {
395           $form['#value'] = $form['#default_value'];
396         }
397       }
398     }
399     if (isset($form['#executes_submit_callback'])) {
400       // Count submit and non-submit buttons
401       $form_button_counter[$form['#executes_submit_callback']]++;
402       // See if a submit button was pressed
403       if (isset($_POST[$form['#name']]) && $_POST[$form['#name']] == $form['#value']) {
404         $form_submitted = $form_submitted || $form['#executes_submit_callback'];
405       }
406     }
407   }
408
409   // Allow for elements to expand to multiple elements, e.g. radios, checkboxes and files.
410   if (isset($form['#process']) && !$form['#processed']) {
411     foreach ($form['#process'] as $process => $args) {
412       if (function_exists($process)) {
413         $args = array_merge(array($form), $args);
414         $form = call_user_func_array($process, $args);
415       }
416     }
417     $form['#processed'] = TRUE;
418   }
419
420   // Set the $form_values key that gets passed to validate and submit.
421   // We call this after #process gets called so that #process has a
422   // chance to update #value if desired.
423   if (isset($form['#input']) && $form['#input']) {
424     form_set_value($form, $form['#value']);
425   }
426
427   // Recurse through all child elements.
428   $count  = 0;
429   foreach (element_children($form) as $key) {
430     // don't squash an existing tree value
431     if (!isset($form[$key]['#tree'])) {
432       $form[$key]['#tree'] = $form['#tree'];
433     }
434
435     // don't squash existing parents value
436     if (!isset($form[$key]['#parents'])) {
437       // Check to see if a tree of child elements is present. If so, continue down the tree if required.
438       $form[$key]['#parents'] = $form[$key]['#tree'] && $form['#tree'] ? array_merge($form['#parents'], array($key)) : array($key);
439     }
440
441     # Assign a decimal placeholder weight to preserve original array order
442     if (!isset($form[$key]['#weight'])) {
443       $form[$key]['#weight'] = $count/1000;
444     }
445     $form[$key] = form_builder($form_id, $form[$key]);
446     $count++;
447   }
448
449   if (isset($form['#after_build']) && !isset($form['#after_build_done'])) {
450     foreach ($form['#after_build'] as $function) {
451       if (function_exists($function)) {
452         $form = $function($form, $form_values);
453       }
454     }
455     $form['#after_build_done'] = TRUE;
456   }
457
458   return $form;
459 }
460
461 /**
462  * Use this function to make changes to form values in the form validate
463  * phase, so they will be available in the submit phase in $form_values.
464  *
465  * Specifically, if $form['#parents'] is array('foo', 'bar')
466  * and $value is 'baz' then this function will make
467  * $form_values['foo']['bar'] to be 'baz'.
468  *
469  * @param $form
470  *   The form item. Keys used: #parents, #value
471  * @param $value
472  *   The value for the form item.
473  */
474 function form_set_value($form, $value) {
475   global $form_values;
476   _form_set_value($form_values, $form, $form['#parents'], $value);
477 }
478
479 /**
480  * Helper function for form_set_value().
481  *
482  * We iterate of $parents and create nested arrays for them
483  * in $form_values if needed. Then we insert the value in
484  * the right array.
485  */
486 function _form_set_value(&$form_values, $form, $parents, $value) {
487   $parent = array_shift($parents);
488   if (empty($parents)) {
489     $form_values[$parent] = $value;
490   }
491   else {
492     if (!isset($form_values[$parent])) {
493       $form_values[$parent] = array();
494     }
495     _form_set_value($form_values[$parent], $form, $parents, $value);
496   }
497   return $form;
498 }
499
500 /**
501  * Renders a HTML form given a form tree. Recursively iterates over each of
502  * the form elements, generating HTML code. This function is usually
503  * called from within a theme.  To render a form from within a module, use
504  * drupal_get_form().
505  *
506  * @param $elements
507  *   The form tree describing the form.
508  * @return
509  *   The rendered HTML form.
510  */
511 function form_render(&$elements) {
512   if (!isset($elements)) {
513     return NULL;
514   }
515   $content = '';
516   uasort($elements, "_form_sort");
517   if (!isset($elements['#children'])) {
518     $children = element_children($elements);
519     /* Render all the children that use a theme function */
520     if (isset($elements['#theme']) && !$elements['#theme_used']) {
521       $elements['#theme_used'] = TRUE;
522
523       $previous_value = $elements['#value'];
524       $previous_type = $elements['#type'];
525       // If we rendered a single element, then we will skip the renderer.
526       if (empty($children)) {
527         $elements['#printed'] = TRUE;
528       }
529       else {
530         $elements['#value'] = '';
531       }
532       $elements['#type'] = 'markup';
533
534       $content = theme($elements['#theme'], $elements);
535
536       $elements['#value'] = $previous_value;
537       $elements['#type'] = $previous_type;
538       unset($elements['#prefix'], $elements['#suffix']);
539     }
540     /* render each of the children using form_render and concatenate them */
541     if (!isset($content) || $content === '') {
542       foreach ($children as $key) {
543         $content .= form_render($elements[$key]);
544       }
545     }
546   }
547   if (isset($content) && $content !== '') {
548     $elements['#children'] = $content;
549   }
550
551   // Until now, we rendered the children, here we render the element itself
552   if (!isset($elements['#printed'])) {
553     $content = theme(($elements['#type']) ? $elements['#type']: 'markup', $elements);
554     $elements['#printed'] = TRUE;
555   }
556
557   if (isset($content) && $content !== '') {
558     $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
559     $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
560     return $prefix . $content . $suffix;
561   }
562 }
563
564 /**
565  * Function used by uasort in form_render() to sort form by weight.
566  */
567 function _form_sort($a, $b) {
568   $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
569   $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
570   if ($a_weight == $b_weight) {
571     return 0;
572   }
573   return ($a_weight < $b_weight) ? -1 : 1;
574 }
575
576 /**
577  * Retrieve the default properties for the defined element type.
578  */
579 function _element_info($type, $refresh = null) {
580   static $cache;
581
582   $basic_defaults = array(
583     '#description' => NULL,
584     '#attributes' => array(),
585     '#required' => FALSE,
586     '#tree' => FALSE,
587     '#parents' => array()
588   );
589   if (!isset($cache) || $refresh) {
590     $cache = array();
591     foreach (module_implements('elements') as $module) {
592       $elements = module_invoke($module, 'elements');
593       if (isset($elements) && is_array($elements)) {
594         $cache = array_merge_recursive($cache, $elements);
595       }
596     }
597     if (sizeof($cache)) {
598       foreach ($cache as $element_type => $info) {
599         $cache[$element_type] = array_merge_recursive($basic_defaults, $info);
600       }
601     }
602   }
603
604   return $cache[$type];
605 }
606
607 function form_options_flatten($array, $reset = TRUE) {
608   static $return;
609
610   if ($reset) {
611     $return = array();
612   }
613
614   foreach ($array as $key => $value) {
615     if (is_array($value)) {
616       form_options_flatten($value, FALSE);
617     }
618     else {
619       $return[$key] = 1;
620     }
621   }
622
623   return $return;
624 }
625
626 /**
627  * Format a dropdown menu or scrolling selection box.
628  *
629  * @param $element
630  *   An associative array containing the properties of the element.
631  *   Properties used: title, value, options, description, extra, multiple, required
632  * @return
633  *   A themed HTML string representing the form element.
634  *
635  * It is possible to group options together; to do this, change the format of
636  * $options to an associative array in which the keys are group labels, and the
637  * values are associative arrays in the normal $options format.
638  */
639 function theme_select($element) {
640   $select = '';
641   $size = $element['#size'] ? ' size="' . $element['#size'] . '"' : '';
642   _form_set_class($element, array('form-select'));
643   return theme('form_element', $element['#title'], '<select name="'. $element['#name'] .''. ($element['#multiple'] ? '[]' : '') .'"'. ($element['#multiple'] ? ' multiple="multiple" ' : '') . drupal_attributes($element['#attributes']) .' id="' . $element['#id'] .'" '. $size .'>'. form_select_options($element) .'</select>', $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
644 }
645
646 function form_select_options($element, $choices = NULL) {
647   if (!isset($choices)) {
648     $choices = $element['#options'];
649   }
650   // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
651   // isset() fails in this situation.
652   $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
653   $value_is_array = is_array($element['#value']);
654   $options = '';
655   foreach ($choices as $key => $choice) {
656     if (is_array($choice)) {
657       $options .= '<optgroup label="'. $key .'">';
658       $options .= form_select_options($element, $choice);
659       $options .= '</optgroup>';
660     }
661     else {
662       $key = (string)$key;
663       if ($value_valid && ($element['#value'] == $key || ($value_is_array && in_array($key, $element['#value'])))) {
664         $selected = ' selected="selected"';
665       }
666       else {
667         $selected = '';
668       }
669       $options .= '<option value="'. $key .'"'. $selected .'>'. check_plain($choice) .'</option>';
670     }
671   }
672   return $options;
673 }
674
675 /**
676  * Format a group of form items.
677  *
678  * @param $element
679  *   An associative array containing the properties of the element.
680  *   Properties used: attributes, title, value, description, children, collapsible, collapsed
681  * @return
682  *   A themed HTML string representing the form item group.
683  */
684 function theme_fieldset($element) {
685   if ($element['#collapsible']) {
686     drupal_add_js('misc/collapse.js');
687
688     $element['#attributes']['class'] .= ' collapsible';
689     if ($element['#collapsed']) {
690      $element['#attributes']['class'] .= ' collapsed';
691     }
692   }
693
694   return '<fieldset' . drupal_attributes($element['#attributes']) .'>' . ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') . ($element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . $element['#children'] . $element['#value'] . "</fieldset>\n";
695
696 }
697
698 /**
699  * Format a radio button.
700  *
701  * @param $element
702  *   An associative array containing the properties of the element.
703  *   Properties used: required, return_value, value, attributes, title, description
704  * @return
705  *   A themed HTML string representing the form item group.
706  */
707 function theme_radio($element) {
708   _form_set_class($element, array('form-radio'));
709   $output = '<input type="radio" ';
710   $output .= 'name="' . $element['#name'] .'" ';
711   $output .= 'value="'. $element['#return_value'] .'" ';
712   $output .= ($element['#value'] == $element['#return_value']) ? ' checked="checked" ' : ' ';
713   $output .= drupal_attributes($element['#attributes']) .' />';
714   if (!is_null($element['#title'])) {
715     $output = '<label class="option">'. $output .' '. $element['#title'] .'</label>';
716   }
717   return theme('form_element', NULL, $output, $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
718 }
719
720 /**
721  * Format a set of radio buttons.
722  *
723  * @param $element
724  *   An associative array containing the properties of the element.
725  *   Properties used: title, value, options, description, required and attributes.
726  * @return
727  *   A themed HTML string representing the radio button set.
728  */
729 function theme_radios($element) {
730   if ($element['#title'] || $element['#description']) {
731     return theme('form_element', $element['#title'], $element['#children'], $element['#description'], NULL, $element['#required'], form_get_error($element));
732   }
733   else {
734     return $element['#children'];
735   }
736 }
737
738 /**
739  * Format a password_confirm item.
740  *
741  * @param $element
742  *   An associative array containing the properties of the element.
743  *   Properties used: title, value, id, required, error.
744  * @return
745  *   A themed HTML string representing the form item.
746  */
747 function theme_password_confirm($element) {
748   return theme('form_element', $element['#title'], '<div class="container-inline">'. $element['#children']. '</div>', $element['#description'],  $element['#id'], $element['#required'], form_get_error($element));
749 }
750
751 /*
752  * Expand a password_confirm field into two text boxes.
753  */
754 function expand_password_confirm($element) {
755   $element['pass1'] =  array('#type' => 'password', '#size' => 12, '#value' => $element['#value']['pass1']);
756   $element['pass2'] =  array('#type' => 'password', '#size' => 12, '#value' => $element['#value']['pass2']);
757   $element['#validate'] = array('password_confirm_validate' => array());
758   $element['#tree'] = TRUE;
759
760   return $element;
761 }
762
763 /**
764  * Validate password_confirm element.
765  */
766 function password_confirm_validate($form) {
767   $pass1 = trim($form['pass1']['#value']);
768   if (!empty($pass1)) {
769     $pass2 = trim($form['pass2']['#value']);
770     if ($pass1 != $pass2) {
771       form_error($form, t('The specified passwords do not match.'));
772     }
773   }
774   elseif ($form['#required'] && !empty($_POST['edit'])) {
775     form_error($form, t('Password field is required.'));
776   }
777
778   // Password field must be converted from a two-element array into a single
779   // string regardless of validation results.
780   form_set_value($form['pass1'], NULL);
781   form_set_value($form['pass2'], NULL);
782   form_set_value($form, $pass1);
783
784   return $form;
785 }
786
787 /**
788  * Format a date selection element.
789  *
790  * @param $element
791  *   An associative array containing the properties of the element.
792  *   Properties used: title, value, options, description, required and attributes.
793  * @return
794  *   A themed HTML string representing the date selection boxes.
795  */
796 function theme_date($element) {
797   $output = '<div class="container-inline">' . $element['#children'] . '</div>';
798   return theme('form_element', $element['#title'], $output, $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
799 }
800
801 /**
802  * Roll out a single date element.
803  */
804 function expand_date($element) {
805   // Default to current date
806   if (!isset($element['#value'])) {
807     $element['#value'] = array('day' => format_date(time(), 'custom', 'j'),
808                             'month' => format_date(time(), 'custom', 'n'),
809                             'year' => format_date(time(), 'custom', 'Y'));
810   }
811
812   $element['#tree'] = TRUE;
813
814   // Determine the order of day, month, year in the site's chosen date format.
815   $format = variable_get('date_format_short', 'm/d/Y');
816   $sort = array();
817   $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
818   $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
819   $sort['year'] = strpos($format, 'Y');
820   asort($sort);
821   $order = array_keys($sort);
822
823   // Output multi-selector for date
824   foreach ($order as $type) {
825     switch ($type) {
826       case 'day':
827         $options = drupal_map_assoc(range(1, 31));
828         break;
829       case 'month':
830         $options = drupal_map_assoc(range(1, 12), 'map_month');
831         break;
832       case 'year':
833         $options = drupal_map_assoc(range(1900, 2050));
834         break;
835     }
836     $parents = $element['#parents'];
837     $parents[] = $type;
838     $element[$type] = array(
839       '#type' => 'select',
840       '#value' => $element['#value'][$type],
841       '#attributes' => $element['#attributes'],
842       '#options' => $options,
843     );
844   }
845
846   return $element;
847 }
848
849 /**
850  * Validates the FAPI date type to stop dates like 30/Feb/2006
851  */
852 function date_validate($form) {
853   if (!checkdate($form['#value']['month'], $form['#value']['day'], $form['#value']['year'])) {
854     form_error($form, t('The specified date is invalid.'));
855   }
856 }
857
858 /**
859  * Helper function for usage with drupal_map_assoc to display month names.
860  */
861 function map_month($month) {
862   return format_date(gmmktime(0, 0, 0, $month, 2, 1970), 'custom', 'M', 0);
863 }
864
865 /**
866  * Helper function to load value from default value for checkboxes
867  */
868 function checkboxes_value(&$form) {
869   $value = array();
870   foreach ((array)$form['#default_value'] as $key) {
871     $value[$key] = 1;
872   }
873   $form['#value'] = $value;
874 }
875
876 /**
877  * If no default value is set for weight select boxes, use 0.
878  */
879 function weight_value(&$form) {
880   if (isset($form['#default_value'])) {
881     $form['#value'] = $form['#default_value'];
882   }
883   else {
884     $form['#value'] = 0;
885   }
886 }
887
888 /**
889  * Roll out a single radios element to a list of radios,
890  * using the options array as index.
891  */
892 function expand_radios($element) {
893   if (count($element['#options']) > 0) {
894     foreach ($element['#options'] as $key => $choice) {
895       if (!isset($element[$key])) {
896         $element[$key] = array('#type' => 'radio', '#title' => $choice, '#return_value' => $key, '#default_value' => $element['#default_value'], '#attributes' => $element['#attributes'], '#parents' => $element['#parents'], '#spawned' => TRUE);
897       }
898     }
899   }
900   return $element;
901 }
902
903 /**
904  * Format a form item.
905  *
906  * @param $element
907  *   An associative array containing the properties of the element.
908  *   Properties used:  title, value, description, required, error
909  * @return
910  *   A themed HTML string representing the form item.
911  */
912 function theme_item($element) {
913   return theme('form_element', $element['#title'], $element['#value'] . $element['#children'], $element['#description'], $element['#id'], $element['#required'], $element['#error']);
914 }
915
916 /**
917  * Format a checkbox.
918  *
919  * @param $element
920  *   An associative array containing the properties of the element.
921  *   Properties used:  title, value, return_value, description, required
922  * @return
923  *   A themed HTML string representing the checkbox.
924  */
925 function theme_checkbox($element) {
926   _form_set_class($element, array('form-checkbox'));
927   $checkbox = '<input ';
928   $checkbox .= 'type="checkbox" ';
929   $checkbox .= 'name="'. $element['#name'] .'" ';
930   $checkbox .= 'id="'. $element['#id'].'" ' ;
931   $checkbox .= 'value="'. $element['#return_value'] .'" ';
932   $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
933   $checkbox .= drupal_attributes($element['#attributes']) . ' />';
934
935   if (!is_null($element['#title'])) {
936     $checkbox = '<label class="option">'. $checkbox .' '. $element['#title'] .'</label>';
937   }
938
939   return theme('form_element', NULL, $checkbox, $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
940 }
941
942 /**
943  * Format a set of checkboxes.
944  *
945  * @param $element
946  *   An associative array containing the properties of the element.
947  * @return
948  *   A themed HTML string representing the checkbox set.
949  */
950 function theme_checkboxes($element) {
951   if ($element['#title'] || $element['#description']) {
952     return theme('form_element', $element['#title'], $element['#children'], $element['#description'], NULL, $element['#required'], form_get_error($element));
953   }
954   else {
955     return $element['#children'];
956   }
957 }
958
959 function expand_checkboxes($element) {
960   $value = is_array($element['#value']) ? $element['#value'] : array();
961   $element['#tree'] = TRUE;
962   if (count($element['#options']) > 0) {
963     if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
964       $element['#default_value'] = array();
965     }
966     foreach ($element['#options'] as $key => $choice) {
967       if (!isset($element[$key])) {
968         $element[$key] = array('#type' => 'checkbox', '#processed' => TRUE, '#title' => $choice, '#return_value' => $key, '#default_value' => isset($value[$key]), '#attributes' => $element['#attributes']);
969       }
970     }
971   }
972   return $element;
973 }
974
975 function theme_submit($element) {
976   return theme('button', $element);
977 }
978
979 function theme_button($element) {
980   //Make sure not to overwrite classes
981   if (isset($element['#attributes']['class'])) {
982     $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
983   }
984   else {
985     $element['#attributes']['class'] = 'form-'. $element['#button_type'];
986   }
987
988   return '<input type="submit" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ') .'value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
989 }
990
991 /**
992  * Format a hidden form field.
993  *
994  * @param $element
995  *   An associative array containing the properties of the element.
996  *   Properties used:  value, edit
997  * @return
998  *   A themed HTML string representing the hidden form field.
999  */
1000 function theme_hidden($element) {
1001   return '<input type="hidden" name="'. $element['#name'] . '" id="'. $element['#id'] . '" value="'. check_plain($element['#value']) ."\" " . drupal_attributes($element['#attributes']) ." />\n";
1002 }
1003
1004 /**
1005  * Format a textfield.
1006  *
1007  * @param $element
1008  *   An associative array containing the properties of the element.
1009  *   Properties used:  title, value, description, size, maxlength, required, attributes autocomplete_path
1010  * @return
1011  *   A themed HTML string representing the textfield.
1012  */
1013 function theme_textfield($element) {
1014   $size = $element['#size'] ? ' size="' . $element['#size'] . '"' : '';
1015   $class = array('form-text');
1016   $extra = '';
1017   if ($element['#autocomplete_path']) {
1018     drupal_add_js('misc/autocomplete.js');
1019     $class[] = 'form-autocomplete';
1020     $extra =  '<input class="autocomplete" type="hidden" id="'. $element['#id'] .'-autocomplete" value="'. check_url(url($element['#autocomplete_path'], NULL, NULL, TRUE)) .'" disabled="disabled" />';
1021   }
1022   _form_set_class($element, $class);
1023   $output = '<input type="text" maxlength="'. $element['#maxlength'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $size .' value="'. check_plain($element['#value']) .'"'. drupal_attributes($element['#attributes']) .' />';
1024   return theme('form_element', $element['#title'], $output, $element['#description'], $element['#id'], $element['#required'], form_get_error($element)). $extra;
1025 }
1026
1027 /**
1028  * Format a form.
1029  *
1030  * @param $element
1031  *   An associative array containing the properties of the element.
1032  *   Properties used: action, method, attributes, children
1033  * @return
1034  *   A themed HTML string representing the form.
1035  */
1036 function theme_form($element) {
1037   // Anonymous div to satisfy XHTML compliance.
1038   $action = $element['#action'] ? 'action="' . check_url($element['#action']) . '" ' : '';
1039   return '<form '. $action . ' method="'. $element['#method'] .'" '. 'id="'. $element['#id'] .'"'.  drupal_attributes($element['#attributes']) .">\n<div>". $element['#children'] ."\n</div></form>\n";
1040 }
1041
1042 /**
1043  * Format a textarea.
1044  *
1045  * @param $element
1046  *   An associative array containing the properties of the element.
1047  *   Properties used: title, value, description, rows, cols, required, attributes
1048  * @return
1049  *   A themed HTML string representing the textarea.
1050  */
1051 function theme_textarea($element) {
1052   $class = array('form-textarea');
1053   if ($element['#resizable'] !== false) {
1054     drupal_add_js('misc/textarea.js');
1055     $class[] = 'resizable';
1056   }
1057
1058   $cols = $element['#cols'] ? ' cols="'. $element['#cols'] .'"' : '';
1059   _form_set_class($element, $class);
1060   return theme('form_element', $element['#title'], '<textarea'. $cols .' rows="'. $element['#rows'] .'" name="'. $element['#name'] .'" id="' . $element['#id'] .'" '. drupal_attributes($element['#attributes']) .'>'. check_plain($element['#value']) .'</textarea>', $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
1061 }
1062
1063 /**
1064  * Format HTML markup for use in forms.
1065  *
1066  * This is used in more advanced forms, such as theme selection and filter format.
1067  *
1068  * @param $element
1069  *   An associative array containing the properties of the element.
1070  *   Properties used: prefix, value, children and suffix.
1071  * @return
1072  *   A themed HTML string representing the HTML markup.
1073  */
1074
1075 function theme_markup($element) {
1076   return $element['#value'] . $element['#children'];
1077 }
1078
1079 /**
1080 * Format a password field.
1081 *
1082 * @param $element
1083 *   An associative array containing the properties of the element.
1084 *   Properties used:  title, value, description, size, maxlength, required, attributes
1085 * @return
1086 *   A themed HTML string representing the form.
1087 */
1088 function theme_password($element) {
1089   $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : '';
1090
1091   _form_set_class($element, array('form-text'));
1092   $output = '<input type="password" maxlength="'. $element['#maxlength'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $size . drupal_attributes($element['#attributes']) .' />';
1093
1094   return theme('form_element', $element['#title'], $output, $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
1095 }
1096
1097 /**
1098  * Format a weight selection menu.
1099  *
1100  * @param $element
1101  *   An associative array containing the properties of the element.
1102  *   Properties used:  title, delta, description
1103  * @return
1104  *   A themed HTML string representing the form.
1105  */
1106 function theme_weight($element) {
1107   for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
1108     $weights[$n] = $n;
1109   }
1110   $element['#options'] = $weights;
1111   $element['#type'] = 'select';
1112
1113   return form_render($element);
1114 }
1115
1116 /**
1117  * Format a file upload field.
1118  *
1119  * @param $title
1120  *   The label for the file upload field.
1121  * @param $name
1122  *   The internal name used to refer to the field.
1123  * @param $size
1124  *   A measure of the visible size of the field (passed directly to HTML).
1125  * @param $description
1126  *   Explanatory text to display after the form item.
1127  * @param $required
1128  *   Whether the user must upload a file to the field.
1129  * @return
1130  *   A themed HTML string representing the field.
1131  *
1132  * For assistance with handling the uploaded file correctly, see the API
1133  * provided by file.inc.
1134  */
1135 function theme_file($element) {
1136   _form_set_class($element, array('form-file'));
1137   return theme('form_element', $element['#title'], '<input type="file" name="'. $element['#name'] .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '') .' id="'. form_clean_id($element['#id']) .'" size="'. $element['#size'] ."\" />\n", $element['#description'], $element['#id'], $element['#required'], form_get_error($element));
1138 }
1139
1140 /**
1141  * Sets a form element's class attribute.
1142  *
1143  * Adds 'required' and 'error' classes as needed.
1144  *
1145  * @param &$element
1146  *   The form element
1147  * @param $name
1148  *   Array of new class names to be added
1149  */
1150 function _form_set_class(&$element, $class = array()) {
1151   if ($element['#required']) {
1152     $class[] = 'required';
1153   }
1154   if (form_get_error($element)){
1155     $class[] = 'error';
1156   }
1157   if (isset($element['#attributes']['class'])) {
1158     $class[] = $element['#attributes']['class'];
1159   }
1160   $element['#attributes']['class'] = implode(' ', $class);
1161 }
1162
1163 /**
1164  * Remove invalid characters from an HTML ID attribute string.
1165  *
1166  * @param $id
1167  *   The ID to clean
1168  * @return
1169  *   The cleaned ID
1170  */
1171 function form_clean_id($id = NULL) {
1172   $id = str_replace('][', '-', $id);
1173   return $id;
1174 }
1175
1176 /**
1177  * @} End of "defgroup form".
1178  */