~ubuntu-branches/ubuntu/oneiric/drupal5/oneiric

1 by Luigi Gangitano
Import upstream version 5.1
1
<?php
1.1.8 by Emanuele Gentili
Import upstream version 5.10
2
// $Id: form.inc,v 1.174.2.14 2008/08/04 04:00:24 drumm Exp $
1 by Luigi Gangitano
Import upstream version 5.1
3
4
/**
5
 * @defgroup form Form generation
6
 * @{
7
 * Functions to enable the processing and display of HTML forms.
8
 *
9
 * Drupal uses these functions to achieve consistency in its form processing and
10
 * presentation, while simplifying code and reducing the amount of HTML that
11
 * must be explicitly generated by modules.
12
 *
13
 * The drupal_get_form() function handles retrieving, processing, and
14
 * displaying a rendered HTML form for modules automatically. For example:
15
 *
1.1.3 by Stephan Hermann
Import upstream version 5.5
16
 * @code
1 by Luigi Gangitano
Import upstream version 5.1
17
 * // Display the user registration form.
18
 * $output = drupal_get_form('user_register');
1.1.3 by Stephan Hermann
Import upstream version 5.5
19
 * @endcode
1 by Luigi Gangitano
Import upstream version 5.1
20
 *
21
 * Forms can also be built and submitted programmatically without any user input
22
 * using the drupal_execute() function.
23
 *
24
 * For information on the format of the structured arrays used to define forms,
1.1.1 by Michael Bienia
Import upstream version 5.2
25
 * and more detailed explanations of the Form API workflow, see the
1.1.3 by Stephan Hermann
Import upstream version 5.5
26
 * @link http://api.drupal.org/api/file/developer/topics/forms_api_reference.html/5 reference @endlink
27
 * and the @link http://api.drupal.org/api/file/developer/topics/forms_api.html/5 quickstart guide. @endlink
1 by Luigi Gangitano
Import upstream version 5.1
28
 */
29
30
/**
31
 * Retrieves a form from a builder function, passes it on for
32
 * processing, and renders the form or redirects to its destination
33
 * as appropriate. In multi-step form scenarios, it handles properly
34
 * processing the values using the previous step's form definition,
35
 * then rendering the requested step for display.
36
 *
37
 * @param $form_id
38
 *   The unique string identifying the desired form. If a function
39
 *   with that name exists, it is called to build the form array.
40
 *   Modules that need to generate the same form (or very similar forms)
41
 *   using different $form_ids can implement hook_forms(), which maps
42
 *   different $form_id values to the proper form building function. Examples
43
 *   may be found in node_forms(), search_forms(), and user_forms().
44
 * @param ...
45
 *   Any additional arguments needed by the form building function.
46
 * @return
47
 *   The rendered form.
48
 */
49
function drupal_get_form($form_id) {
50
  // In multi-step form scenarios, the incoming $_POST values are not
51
  // necessarily intended for the current form. We need to build
52
  // a copy of the previously built form for validation and processing,
53
  // then go on to the one that was requested if everything works.
54
55
  $form_build_id = md5(mt_rand());
56
  if (isset($_POST['form_build_id']) && isset($_SESSION['form'][$_POST['form_build_id']]['args']) && $_POST['form_id'] == $form_id) {
57
    // There's a previously stored multi-step form. We should handle
58
    // IT first.
59
    $stored = TRUE;
60
    $args = $_SESSION['form'][$_POST['form_build_id']]['args'];
61
    $form = call_user_func_array('drupal_retrieve_form', $args);
62
    $form['#build_id'] = $_POST['form_build_id'];
63
  }
64
  else {
65
    // We're coming in fresh; build things as they would be. If the
66
    // form's #multistep flag is set, store the build parameters so
67
    // the same form can be reconstituted for validation.
68
    $args = func_get_args();
69
    $form = call_user_func_array('drupal_retrieve_form', $args);
70
    if (isset($form['#multistep']) && $form['#multistep']) {
71
      // Clean up old multistep form session data.
72
      _drupal_clean_form_sessions();
73
      $_SESSION['form'][$form_build_id] = array('timestamp' => time(), 'args' => $args);
74
      $form['#build_id'] = $form_build_id;
75
    }
76
    $stored = FALSE;
77
  }
78
79
  // Process the form, submit it, and store any errors if necessary.
80
  drupal_process_form($args[0], $form);
81
82
  if ($stored && !form_get_errors()) {
83
    // If it's a stored form and there were no errors, we processed the
84
    // stored form successfully. Now we need to build the form that was
85
    // actually requested. We always pass in the current $_POST values
86
    // to the builder function, as values from one stage of a multistep
87
    // form can determine how subsequent steps are displayed.
88
    $args = func_get_args();
89
    $args[] = $_POST;
90
    $form = call_user_func_array('drupal_retrieve_form', $args);
91
    unset($_SESSION['form'][$_POST['form_build_id']]);
92
    if (isset($form['#multistep']) && $form['#multistep']) {
93
      $_SESSION['form'][$form_build_id] = array('timestamp' => time(), 'args' => $args);
94
      $form['#build_id'] = $form_build_id;
95
    }
96
    drupal_prepare_form($args[0], $form);
97
  }
98
99
  return drupal_render_form($args[0], $form);
100
}
101
102
103
/**
104
 * Remove form information that's at least a day old from the
105
 * $_SESSION['form'] array.
106
 */
107
function _drupal_clean_form_sessions() {
108
  if (isset($_SESSION['form'])) {
109
    foreach ($_SESSION['form'] as $build_id => $data) {
110
      if ($data['timestamp'] < (time() - 84600)) {
111
        unset($_SESSION['form'][$build_id]);
112
      }
113
    }
114
  }
115
}
116
117
118
/**
119
 * Retrieves a form using a form_id, populates it with $form_values,
120
 * processes it, and returns any validation errors encountered. This
121
 * function is the programmatic counterpart to drupal_get_form().
122
 *
123
 * @param $form_id
124
 *   The unique string identifying the desired form. If a function
125
 *   with that name exists, it is called to build the form array.
126
 *   Modules that need to generate the same form (or very similar forms)
127
 *   using different $form_ids can implement hook_forms(), which maps
128
 *   different $form_id values to the proper form building function. Examples
129
 *   may be found in node_forms(), search_forms(), and user_forms().
130
 * @param $form_values
131
 *   An array of values mirroring the values returned by a given form
132
 *   when it is submitted by a user.
133
 * @param ...
134
 *   Any additional arguments needed by the form building function.
135
 * @return
136
 *   Any form validation errors encountered.
137
 *
138
 * For example:
139
 *
140
 * // register a new user
141
 * $values['name'] = 'robo-user';
142
 * $values['mail'] = 'robouser@example.com';
143
 * $values['pass'] = 'password';
144
 * drupal_execute('user_register', $values);
145
 *
146
 * // Create a new node
147
 * $node = array('type' => 'story');
148
 * $values['title'] = 'My node';
149
 * $values['body'] = 'This is the body text!';
150
 * $values['name'] = 'robo-user';
151
 * drupal_execute('story_node_form', $values, $node);
152
 */
153
function drupal_execute($form_id, $form_values) {
154
  $args = func_get_args();
155
156
  $form_id = array_shift($args);
157
  $form_values = array_shift($args);
158
  array_unshift($args, $form_id);
159
160
  if (isset($form_values)) {
161
    $form = call_user_func_array('drupal_retrieve_form', $args);
162
    $form['#post'] = $form_values;
163
    return drupal_process_form($form_id, $form);
164
  }
165
}
166
167
/**
168
 * Retrieves the structured array that defines a given form.
169
 *
170
 * @param $form_id
171
 *   The unique string identifying the desired form. If a function
172
 *   with that name exists, it is called to build the form array.
173
 *   Modules that need to generate the same form (or very similar forms)
174
 *   using different $form_ids can implement hook_forms(), which maps
175
 *   different $form_id values to the proper form building function.
176
 * @param ...
177
 *   Any additional arguments needed by the form building function.
178
 */
179
function drupal_retrieve_form($form_id) {
180
  static $forms;
181
182
  // We save two copies of the incoming arguments: one for modules to use
183
  // when mapping form ids to builder functions, and another to pass to
184
  // the builder function itself. We shift out the first argument -- the
185
  // $form_id itself -- from the list to pass into the builder function,
186
  // since it's already known.
187
  $args = func_get_args();
188
  $saved_args = $args;
189
  array_shift($args);
190
191
  // We first check to see if there's a function named after the $form_id.
192
  // If there is, we simply pass the arguments on to it to get the form.
193
  if (!function_exists($form_id)) {
194
    // In cases where many form_ids need to share a central builder function,
195
    // such as the node editing form, modules can implement hook_forms(). It
196
    // maps one or more form_ids to the correct builder functions.
197
    //
198
    // We cache the results of that hook to save time, but that only works
199
    // for modules that know all their form_ids in advance. (A module that
200
    // adds a small 'rate this comment' form to each comment in a list
201
    // would need a unique form_id for each one, for example.)
202
    //
203
    // So, we call the hook if $forms isn't yet populated, OR if it doesn't
204
    // yet have an entry for the requested form_id.
205
    if (!isset($forms) || !isset($forms[$form_id])) {
206
      $forms = module_invoke_all('forms', $saved_args);
207
    }
208
    $form_definition = $forms[$form_id];
209
    if (isset($form_definition['callback arguments'])) {
210
      $args = array_merge($form_definition['callback arguments'], $args);
211
    }
212
    if (isset($form_definition['callback'])) {
213
      $callback = $form_definition['callback'];
214
    }
215
  }
216
  // If $callback was returned by a hook_forms() implementation, call it.
217
  // Otherwise, call the function named after the form id.
218
  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
219
220
  // We store the original function arguments, rather than the final $arg
221
  // value, so that form_alter functions can see what was originally
222
  // passed to drupal_retrieve_form(). This allows the contents of #parameters
223
  // to be saved and passed in at a later date to recreate the form.
224
  $form['#parameters'] = $saved_args;
225
  return $form;
226
}
227
228
/**
229
 * This function is the heart of form API. The form gets built, validated and in
230
 * appropriate cases, submitted.
231
 *
232
 * @param $form_id
233
 *   The unique string identifying the current form.
234
 * @param $form
235
 *   An associative array containing the structure of the form.
236
 * @return
237
 *   The path to redirect the user to upon completion.
238
 */
239
function drupal_process_form($form_id, &$form) {
240
  global $form_values, $form_submitted, $user, $form_button_counter;
241
  static $saved_globals = array();
242
  // In some scenarios, this function can be called recursively. Pushing any pre-existing
243
  // $form_values and form submission data lets us start fresh without clobbering work done
244
  // in earlier recursive calls.
245
  array_push($saved_globals, array($form_values, $form_submitted, $form_button_counter));
246
247
  $form_values = array();
248
  $form_submitted = FALSE;
249
  $form_button_counter = array(0, 0);
250
251
  drupal_prepare_form($form_id, $form);
1.1.1 by Michael Bienia
Import upstream version 5.2
252
  if (($form['#programmed']) || (!empty($_POST) && (($_POST['form_id'] == $form_id)))) {
1 by Luigi Gangitano
Import upstream version 5.1
253
    drupal_validate_form($form_id, $form);
254
    // IE does not send a button value when there is only one submit button (and no non-submit buttons)
255
    // and you submit by pressing enter.
256
    // In that case we accept a submission without button values.
257
    if ((($form['#programmed']) || $form_submitted || (!$form_button_counter[0] && $form_button_counter[1])) && !form_get_errors()) {
258
      $redirect = drupal_submit_form($form_id, $form);
259
      if (!$form['#programmed']) {
260
        drupal_redirect_form($form, $redirect);
261
      }
262
    }
263
  }
264
265
  // We've finished calling functions that alter the global values, so we can
266
  // restore the ones that were there before this function was called.
267
  list($form_values, $form_submitted, $form_button_counter) = array_pop($saved_globals);
268
  return $redirect;
269
}
270
271
/**
272
 * Prepares a structured form array by adding required elements,
273
 * executing any hook_form_alter functions, and optionally inserting
274
 * a validation token to prevent tampering.
275
 *
276
 * @param $form_id
277
 *   A unique string identifying the form for validation, submission,
278
 *   theming, and hook_form_alter functions.
279
 * @param $form
280
 *   An associative array containing the structure of the form.
281
 */
282
function drupal_prepare_form($form_id, &$form) {
283
  global $user;
284
285
  $form['#type'] = 'form';
286
287
  if (!isset($form['#post'])) {
288
    $form['#post'] = $_POST;
289
    $form['#programmed'] = FALSE;
290
  }
291
  else {
292
    $form['#programmed'] = TRUE;
293
  }
294
295
  // In multi-step form scenarios, this id is used to identify
296
  // a unique instance of a particular form for retrieval.
297
  if (isset($form['#build_id'])) {
298
    $form['form_build_id'] = array(
299
      '#type' => 'hidden',
300
      '#value' => $form['#build_id'],
301
      '#id' => $form['#build_id'],
302
      '#name' => 'form_build_id',
303
    );
304
  }
305
306
  // If $base is set, it is used in place of $form_id when constructing validation,
307
  // submission, and theming functions. Useful for mapping many similar or duplicate
308
  // forms with different $form_ids to the same processing functions.
309
  if (isset($form['#base'])) {
310
    $base = $form['#base'];
311
  }
312
313
  // Add a token, based on either #token or form_id, to any form displayed to
314
  // authenticated users. This ensures that any submitted form was actually
315
  // requested previously by the user and protects against cross site request
316
  // forgeries.
317
  if (isset($form['#token'])) {
318
    if ($form['#token'] === FALSE || $user->uid == 0 || $form['#programmed']) {
319
      unset($form['#token']);
320
    }
321
    else {
322
      $form['form_token'] = array('#type' => 'token', '#default_value' => drupal_get_token($form['#token']));
323
    }
324
  }
325
  else if ($user->uid && !$form['#programmed']) {
326
    $form['#token'] = $form_id;
327
    $form['form_token'] = array(
328
      '#id' => form_clean_id('edit-'. $form_id .'-form-token'),
329
      '#type' => 'token',
330
      '#default_value' => drupal_get_token($form['#token']),
331
    );
332
  }
333
334
335
  if (isset($form_id)) {
336
    $form['form_id'] = array('#type' => 'hidden', '#value' => $form_id, '#id' => form_clean_id("edit-$form_id"));
337
  }
338
  if (!isset($form['#id'])) {
339
    $form['#id'] = form_clean_id($form_id);
340
  }
341
342
  $form += _element_info('form');
343
344
  if (!isset($form['#validate'])) {
345
    if (function_exists($form_id .'_validate')) {
346
      $form['#validate'] = array($form_id .'_validate' => array());
347
    }
348
    elseif (function_exists($base .'_validate')) {
349
      $form['#validate'] = array($base .'_validate' => array());
350
    }
351
  }
352
353
  if (!isset($form['#submit'])) {
354
    if (function_exists($form_id .'_submit')) {
355
      // We set submit here so that it can be altered.
356
      $form['#submit'] = array($form_id .'_submit' => array());
357
    }
358
    elseif (function_exists($base .'_submit')) {
359
      $form['#submit'] = array($base .'_submit' => array());
360
    }
361
  }
362
363
  foreach (module_implements('form_alter') as $module) {
364
    $function = $module .'_form_alter';
365
    $function($form_id, $form);
366
  }
367
368
  $form = form_builder($form_id, $form);
369
}
370
371
372
/**
373
 * Validates user-submitted form data from a global variable using
374
 * the validate functions defined in a structured form array.
375
 *
376
 * @param $form_id
377
 *   A unique string identifying the form for validation, submission,
378
 *   theming, and hook_form_alter functions.
379
 * @param $form
380
 *   An associative array containing the structure of the form.
381
 *
382
 */
383
function drupal_validate_form($form_id, $form) {
384
  global $form_values;
385
  static $validated_forms = array();
386
387
  if (isset($validated_forms[$form_id])) {
388
    return;
389
  }
390
391
  // If the session token was set by drupal_prepare_form(), ensure that it
392
  // matches the current user's session.
393
  if (isset($form['#token'])) {
394
    if (!drupal_valid_token($form_values['form_token'], $form['#token'])) {
395
      // Setting this error will cause the form to fail validation.
396
      form_set_error('form_token', t('Validation error, please try again. If this error persists, please contact the site administrator.'));
397
    }
398
  }
399
400
  _form_validate($form, $form_id);
401
  $validated_forms[$form_id] = TRUE;
402
}
403
404
/**
405
 * Processes user-submitted form data from a global variable using
406
 * the submit functions defined in a structured form array.
407
 *
408
 * @param $form_id
409
 *   A unique string identifying the form for validation, submission,
410
 *   theming, and hook_form_alter functions.
411
 * @param $form
412
 *   An associative array containing the structure of the form.
413
 * @return
414
 *   A string containing the path of the page to display when processing
415
 *   is complete.
416
 *
417
 */
418
function drupal_submit_form($form_id, $form) {
419
  global $form_values;
420
  $default_args = array($form_id, &$form_values);
1.1.1 by Michael Bienia
Import upstream version 5.2
421
  $submitted = FALSE;
422
  $goto = NULL;
1 by Luigi Gangitano
Import upstream version 5.1
423
424
  if (isset($form['#submit'])) {
425
    foreach ($form['#submit'] as $function => $args) {
426
      if (function_exists($function)) {
427
        $args = array_merge($default_args, (array) $args);
428
        // Since we can only redirect to one page, only the last redirect
429
        // will work.
430
        $redirect = call_user_func_array($function, $args);
1.1.1 by Michael Bienia
Import upstream version 5.2
431
        $submitted = TRUE;
1 by Luigi Gangitano
Import upstream version 5.1
432
        if (isset($redirect)) {
433
          $goto = $redirect;
434
        }
435
      }
436
    }
437
  }
1.1.1 by Michael Bienia
Import upstream version 5.2
438
1 by Luigi Gangitano
Import upstream version 5.1
439
  return $goto;
440
}
441
442
/**
443
 * Renders a structured form array into themed HTML.
444
 *
445
 * @param $form_id
446
 *   A unique string identifying the form for validation, submission,
447
 *   theming, and hook_form_alter functions.
448
 * @param $form
449
 *   An associative array containing the structure of the form.
450
 * @return
451
 *   A string containing the path of the page to display when processing
452
 *   is complete.
453
 *
454
 */
455
function drupal_render_form($form_id, &$form) {
456
  // Don't override #theme if someone already set it.
457
  if (isset($form['#base'])) {
458
    $base = $form['#base'];
459
  }
460
461
  if (!isset($form['#theme'])) {
462
    if (theme_get_function($form_id)) {
463
      $form['#theme'] = $form_id;
464
    }
465
    elseif (theme_get_function($base)) {
466
      $form['#theme'] = $base;
467
    }
468
  }
469
470
  if (isset($form['#pre_render'])) {
471
    foreach ($form['#pre_render'] as $function) {
472
      if (function_exists($function)) {
473
        $function($form_id, $form);
474
      }
475
    }
476
  }
477
478
  $output = drupal_render($form);
479
  return $output;
480
}
481
482
/**
483
 * Redirect the user to a URL after a form has been processed.
484
 *
485
 * @param $form
486
 *   An associative array containing the structure of the form.
487
 * @param $redirect
488
 *   An optional string containing the destination path to redirect
489
 *   to if none is specified by the form.
490
 *
491
 */
492
function drupal_redirect_form($form, $redirect = NULL) {
493
  if (isset($redirect)) {
494
    $goto = $redirect;
495
  }
496
  if (isset($form['#redirect'])) {
497
    $goto = $form['#redirect'];
498
  }
499
  if ($goto !== FALSE) {
500
    if (is_array($goto)) {
501
      call_user_func_array('drupal_goto', $goto);
502
    }
503
    elseif (!isset($goto)) {
504
      drupal_goto($_GET['q']);
505
    }
506
    else {
507
      drupal_goto($goto);
508
    }
509
  }
510
}
511
512
/**
513
 * Performs validation on form elements. First ensures required fields are
514
 * completed, #maxlength is not exceeded, and selected options were in the
515
 * list of options given to the user. Then calls user-defined validators.
516
 *
517
 * @param $elements
518
 *   An associative array containing the structure of the form.
519
 * @param $form_id
520
 *   A unique string identifying the form for validation, submission,
521
 *   theming, and hook_form_alter functions.
522
 */
523
function _form_validate($elements, $form_id = NULL) {
524
  // Recurse through all children.
525
  foreach (element_children($elements) as $key) {
526
    if (isset($elements[$key]) && $elements[$key]) {
527
      _form_validate($elements[$key]);
528
    }
529
  }
530
  /* Validate the current input */
531
  if (!isset($elements['#validated']) || !$elements['#validated']) {
532
    if (isset($elements['#needs_validation'])) {
1.1.8 by Emanuele Gentili
Import upstream version 5.10
533
      // Make sure a value is passed when the field is required.
534
      // A simple call to empty() will not cut it here as some fields, like
535
      // checkboxes, can return a valid value of '0'. Instead, check the
536
      // length if it's a string, and the item count if it's an array.
537
      if ($elements['#required'] && (!count($elements['#value']) || (is_string($elements['#value']) && strlen(trim($elements['#value'])) == 0))) {
1 by Luigi Gangitano
Import upstream version 5.1
538
        form_error($elements, t('!name field is required.', array('!name' => $elements['#title'])));
539
      }
540
541
      // Verify that the value is not longer than #maxlength.
542
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
543
        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']))));
544
      }
545
546
       // Add legal choice check if element has #options. Can be skipped, but
547
       // then you must validate your own element.
548
      if (isset($elements['#options']) && isset($elements['#value']) && !isset($elements['#DANGEROUS_SKIP_CHECK'])) {
549
        if ($elements['#type'] == 'select') {
550
          $options = form_options_flatten($elements['#options']);
551
        }
552
        else {
553
          $options = $elements['#options'];
554
        }
555
        if (is_array($elements['#value'])) {
556
          $value = $elements['#type'] == 'checkboxes' ? array_keys(array_filter($elements['#value'])) : $elements['#value'];
557
          foreach ($value as $v) {
558
            if (!isset($options[$v])) {
559
              form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
560
              watchdog('form', t('Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'])), WATCHDOG_ERROR);
561
            }
562
          }
563
        }
564
        elseif (!isset($options[$elements['#value']])) {
565
          form_error($elements, t('An illegal choice has been detected. Please contact the site administrator.'));
566
          watchdog('form', t('Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'])), WATCHDOG_ERROR);
567
        }
568
      }
569
    }
570
571
    // Call user-defined validators.
572
    if (isset($elements['#validate'])) {
573
      foreach ($elements['#validate'] as $function => $args) {
574
        $args = array_merge(array($elements), $args);
575
        // For the full form we hand over a copy of $form_values.
576
        if (isset($form_id)) {
577
          $args = array_merge(array($form_id, $GLOBALS['form_values']), $args);
578
        }
579
        if (function_exists($function))  {
580
          call_user_func_array($function, $args);
581
        }
582
      }
583
    }
584
    $elements['#validated'] = TRUE;
585
  }
586
}
587
588
/**
589
 * File an error against a form element. If the name of the element is
590
 * edit[foo][bar] then you may pass either foo or foo][bar as $name
591
 * foo will set an error for all its children.
592
 */
593
function form_set_error($name = NULL, $message = '') {
594
  static $form = array();
595
  if (isset($name) && !isset($form[$name])) {
596
    $form[$name] = $message;
597
    if ($message) {
598
      drupal_set_message($message, 'error');
599
    }
600
  }
601
  return $form;
602
}
603
604
/**
605
 * Return an associative array of all errors.
606
 */
607
function form_get_errors() {
608
  $form = form_set_error();
609
  if (!empty($form)) {
610
    return $form;
611
  }
612
}
613
614
/**
615
 * Return the error message filed against the form with the specified name.
616
 */
617
function form_get_error($element) {
618
  $form = form_set_error();
619
  $key = $element['#parents'][0];
620
  if (isset($form[$key])) {
621
    return $form[$key];
622
  }
623
  $key = implode('][', $element['#parents']);
624
  if (isset($form[$key])) {
625
    return $form[$key];
626
  }
627
}
628
629
/**
630
 * Flag an element as having an error.
631
 */
632
function form_error(&$element, $message = '') {
633
  $element['#error'] = TRUE;
634
  form_set_error(implode('][', $element['#parents']), $message);
635
}
636
637
/**
638
 * Adds some required properties to each form element, which are used
639
 * internally in the form API. This function also automatically assigns
640
 * the value property from the $edit array, provided the element doesn't
641
 * already have an assigned value.
642
 *
643
 * @param $form_id
644
 *   A unique string identifying the form for validation, submission,
645
 *   theming, and hook_form_alter functions.
646
 * @param $form
647
 *   An associative array containing the structure of the form.
648
 */
649
function form_builder($form_id, $form) {
650
  global $form_values, $form_submitted, $form_button_counter;
651
652
  // Initialize as unprocessed.
653
  $form['#processed'] = FALSE;
654
655
  /* Use element defaults */
656
  if ((!empty($form['#type'])) && ($info = _element_info($form['#type']))) {
657
    // Overlay $info onto $form, retaining preexisting keys in $form.
658
    $form += $info;
659
  }
660
661
  if (isset($form['#input']) && $form['#input']) {
662
    if (!isset($form['#name'])) {
663
      $name = array_shift($form['#parents']);
664
      $form['#name'] = $name;
665
      if ($form['#type'] == 'file') {
666
        // To make it easier to handle $_FILES in file.inc, we place all
667
        // file fields in the 'files' array. Also, we do not support
668
        // nested file names.
669
        $form['#name'] = 'files['. $form['#name'] .']';
670
      }
671
      elseif (count($form['#parents'])) {
672
        $form['#name'] .= '['. implode('][', $form['#parents']) .']';
673
      }
674
      array_unshift($form['#parents'], $name);
675
    }
676
    if (!isset($form['#id'])) {
677
      $form['#id'] = form_clean_id('edit-'. implode('-', $form['#parents']));
678
    }
679
680
    if (isset($form['#disabled']) && $form['#disabled']) {
681
      $form['#attributes']['disabled'] = 'disabled';
682
    }
683
684
    if (!isset($form['#value']) && !array_key_exists('#value', $form)) {
685
      if (($form['#programmed']) || ((!isset($form['#access']) || $form['#access']) && isset($form['#post']) && (isset($form['#post']['form_id']) && $form['#post']['form_id'] == $form_id))) {
686
        $edit = $form['#post'];
687
        foreach ($form['#parents'] as $parent) {
688
          $edit = isset($edit[$parent]) ? $edit[$parent] : NULL;
689
        }
690
        if (!$form['#programmed'] || isset($edit)) {
691
          switch ($form['#type']) {
692
            case 'checkbox':
693
              $form['#value'] = !empty($edit) ? $form['#return_value'] : 0;
694
              break;
695
696
            case 'select':
697
              if (isset($form['#multiple']) && $form['#multiple']) {
698
                if (isset($edit) && is_array($edit)) {
699
                  $form['#value'] = drupal_map_assoc($edit);
700
                }
701
                else {
702
                  $form['#value'] = array();
703
                }
704
              }
705
              elseif (isset($edit)) {
706
                $form['#value'] = $edit;
707
              }
708
              break;
709
710
            case 'textfield':
711
              if (isset($edit)) {
712
                // Equate $edit to the form value to ensure it's marked for
713
                // validation.
714
                $edit = str_replace(array("\r", "\n"), '', $edit);
715
                $form['#value'] = $edit;
716
              }
717
              break;
718
719
            case 'token':
720
              $form['#value'] = (string)$edit;
721
              break;
722
723
            default:
724
              if (isset($edit)) {
725
                $form['#value'] = $edit;
726
              }
727
          }
728
          // Mark all posted values for validation.
729
          if ((isset($form['#value']) && $form['#value'] === $edit) || (isset($form['#required']) && $form['#required'])) {
730
            $form['#needs_validation'] = TRUE;
731
          }
732
        }
733
      }
734
      if (!isset($form['#value'])) {
735
        $function = $form['#type'] . '_value';
736
        if (function_exists($function)) {
737
          $function($form);
738
        }
739
        else {
740
          $form['#value'] = isset($form['#default_value']) ? $form['#default_value'] : '';
741
        }
742
      }
743
    }
744
    if (isset($form['#executes_submit_callback'])) {
745
      // Count submit and non-submit buttons.
746
      $form_button_counter[$form['#executes_submit_callback']]++;
747
      // See if a submit button was pressed.
748
      if (isset($form['#post'][$form['#name']]) && $form['#post'][$form['#name']] == $form['#value']) {
749
        $form_submitted = $form_submitted || $form['#executes_submit_callback'];
750
751
        // In most cases, we want to use form_set_value() to manipulate the
752
        // global variables. In this special case, we want to make sure that
753
        // the value of this element is listed in $form_variables under 'op'.
754
        $form_values[$form['#name']] = $form['#value'];
755
      }
756
    }
757
  }
758
759
  // Allow for elements to expand to multiple elements, e.g., radios,
760
  // checkboxes and files.
761
  if (isset($form['#process']) && !$form['#processed']) {
762
    foreach ($form['#process'] as $process => $args) {
763
      if (function_exists($process)) {
764
        $args = array_merge(array($form), array($edit), $args);
765
        $form = call_user_func_array($process, $args);
766
      }
767
    }
768
    $form['#processed'] = TRUE;
769
  }
770
771
  // Set the $form_values key that gets passed to validate and submit.
772
  // We call this after #process gets called so that #process has a
773
  // chance to update #value if desired.
774
  if (isset($form['#input']) && $form['#input']) {
775
    form_set_value($form, $form['#value']);
776
  }
777
778
  // We start off assuming all form elements are in the correct order.
779
  $form['#sorted'] = TRUE;
780
781
  // Recurse through all child elements.
782
  $count = 0;
783
  foreach (element_children($form) as $key) {
784
    $form[$key]['#post'] = $form['#post'];
785
    $form[$key]['#programmed'] = $form['#programmed'];
786
    // Don't squash an existing tree value.
787
    if (!isset($form[$key]['#tree'])) {
788
      $form[$key]['#tree'] = $form['#tree'];
789
    }
790
791
    // Deny access to child elements if parent is denied.
792
    if (isset($form['#access']) && !$form['#access']) {
793
      $form[$key]['#access'] = FALSE;
794
    }
795
796
    // Don't squash existing parents value.
797
    if (!isset($form[$key]['#parents'])) {
798
      // Check to see if a tree of child elements is present. If so,
799
      // continue down the tree if required.
800
      $form[$key]['#parents'] = $form[$key]['#tree'] && $form['#tree'] ? array_merge($form['#parents'], array($key)) : array($key);
801
    }
802
803
    // Assign a decimal placeholder weight to preserve original array order.
804
    if (!isset($form[$key]['#weight'])) {
805
      $form[$key]['#weight'] = $count/1000;
806
    }
807
    else {
808
      // If one of the child elements has a weight then we will need to sort
809
      // later.
810
      unset($form['#sorted']);
811
    }
812
    $form[$key] = form_builder($form_id, $form[$key]);
813
    $count++;
814
  }
815
816
  if (isset($form['#after_build']) && !isset($form['#after_build_done'])) {
817
    foreach ($form['#after_build'] as $function) {
818
      if (function_exists($function)) {
819
        $form = $function($form, $form_values);
820
      }
821
    }
822
    $form['#after_build_done'] = TRUE;
823
  }
824
825
  return $form;
826
}
827
828
/**
829
 * Use this function to make changes to form values in the form validate
830
 * phase, so they will be available in the submit phase in $form_values.
831
 *
832
 * Specifically, if $form['#parents'] is array('foo', 'bar')
833
 * and $value is 'baz' then this function will make
834
 * $form_values['foo']['bar'] to be 'baz'.
835
 *
836
 * @param $form
837
 *   The form item. Keys used: #parents, #value
838
 * @param $value
839
 *   The value for the form item.
840
 */
841
function form_set_value($form, $value) {
842
  global $form_values;
843
  _form_set_value($form_values, $form, $form['#parents'], $value);
844
}
845
846
/**
847
 * Helper function for form_set_value().
848
 *
849
 * We iterate over $parents and create nested arrays for them
850
 * in $form_values if needed. Then we insert the value into
851
 * the right array.
852
 */
853
function _form_set_value(&$form_values, $form, $parents, $value) {
854
  $parent = array_shift($parents);
855
  if (empty($parents)) {
856
    $form_values[$parent] = $value;
857
  }
858
  else {
859
    if (!isset($form_values[$parent])) {
860
      $form_values[$parent] = array();
861
    }
862
    _form_set_value($form_values[$parent], $form, $parents, $value);
863
  }
864
  return $form;
865
}
866
867
/**
868
 * Retrieve the default properties for the defined element type.
869
 */
870
function _element_info($type, $refresh = NULL) {
871
  static $cache;
872
873
  $basic_defaults = array(
874
    '#description' => NULL,
875
    '#attributes' => array(),
876
    '#required' => FALSE,
877
    '#tree' => FALSE,
878
    '#parents' => array()
879
  );
880
  if (!isset($cache) || $refresh) {
881
    $cache = array();
882
    foreach (module_implements('elements') as $module) {
883
      $elements = module_invoke($module, 'elements');
884
      if (isset($elements) && is_array($elements)) {
885
        $cache = array_merge_recursive($cache, $elements);
886
      }
887
    }
888
    if (sizeof($cache)) {
889
      foreach ($cache as $element_type => $info) {
890
        $cache[$element_type] = array_merge_recursive($basic_defaults, $info);
891
      }
892
    }
893
  }
894
895
  return $cache[$type];
896
}
897
898
function form_options_flatten($array, $reset = TRUE) {
899
  static $return;
900
901
  if ($reset) {
902
    $return = array();
903
  }
904
905
  foreach ($array as $key => $value) {
906
    if (is_object($value)) {
907
      form_options_flatten($value->option, FALSE);
908
    }
909
    else if (is_array($value)) {
910
      form_options_flatten($value, FALSE);
911
    }
912
    else {
913
      $return[$key] = 1;
914
    }
915
  }
916
917
  return $return;
918
}
919
920
/**
921
 * Format a dropdown menu or scrolling selection box.
922
 *
923
 * @param $element
924
 *   An associative array containing the properties of the element.
925
 *   Properties used: title, value, options, description, extra, multiple, required
926
 * @return
927
 *   A themed HTML string representing the form element.
928
 *
929
 * It is possible to group options together; to do this, change the format of
930
 * $options to an associative array in which the keys are group labels, and the
931
 * values are associative arrays in the normal $options format.
932
 */
933
function theme_select($element) {
934
  $select = '';
935
  $size = $element['#size'] ? ' size="' . $element['#size'] . '"' : '';
936
  _form_set_class($element, array('form-select'));
937
  $multiple = isset($element['#multiple']) && $element['#multiple'];
938
  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>');
939
}
940
941
function form_select_options($element, $choices = NULL) {
942
  if (!isset($choices)) {
943
    $choices = $element['#options'];
944
  }
945
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
946
  // isset() fails in this situation.
947
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
948
  $value_is_array = is_array($element['#value']);
949
  $options = '';
950
  foreach ($choices as $key => $choice) {
951
    if (is_array($choice)) {
952
      $options .= '<optgroup label="'. $key .'">';
953
      $options .= form_select_options($element, $choice);
954
      $options .= '</optgroup>';
955
    }
956
    elseif (is_object($choice)) {
957
      $options .= form_select_options($element, $choice->option);
958
    }
959
    else {
960
      $key = (string)$key;
1.1.1 by Michael Bienia
Import upstream version 5.2
961
      if ($value_valid && (!$value_is_array && (string)$element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
1 by Luigi Gangitano
Import upstream version 5.1
962
        $selected = ' selected="selected"';
963
      }
964
      else {
965
        $selected = '';
966
      }
967
      $options .= '<option value="'. check_plain($key) .'"'. $selected .'>'. check_plain($choice) .'</option>';
968
    }
969
  }
970
  return $options;
971
}
972
973
/**
974
 * Traverses a select element's #option array looking for any values
975
 * that hold the given key. Returns an array of indexes that match.
976
 *
977
 * This function is useful if you need to modify the options that are
978
 * already in a form element; for example, to remove choices which are
979
 * not valid because of additional filters imposed by another module.
980
 * One example might be altering the choices in a taxonomy selector.
981
 * To correctly handle the case of a multiple hierarchy taxonomy,
982
 * #options arrays can now hold an array of objects, instead of a
983
 * direct mapping of keys to labels, so that multiple choices in the
984
 * selector can have the same key (and label). This makes it difficult
985
 * to manipulate directly, which is why this helper function exists.
986
 *
987
 * This function does not support optgroups (when the elements of the
988
 * #options array are themselves arrays), and will return FALSE if
989
 * arrays are found. The caller must either flatten/restore or
990
 * manually do their manipulations in this case, since returning the
991
 * index is not sufficient, and supporting this would make the
992
 * "helper" too complicated and cumbersome to be of any help.
993
 *
994
 * As usual with functions that can return array() or FALSE, do not
995
 * forget to use === and !== if needed.
996
 *
997
 * @param $element
998
 *   The select element to search.
999
 * @param $key
1000
 *   The key to look for.
1001
 * @return
1002
 *   An array of indexes that match the given $key. Array will be
1003
 *   empty if no elements were found. FALSE if optgroups were found.
1004
 */
1005
function form_get_options($element, $key) {
1006
  $keys = array();
1007
  foreach ($element['#options'] as $index => $choice) {
1008
    if (is_array($choice)) {
1009
      return FALSE;
1010
    }
1011
    else if (is_object($choice)) {
1012
      if (isset($choice->option[$key])) {
1013
        $keys[] = $index;
1014
      }
1015
    }
1016
    else if ($index == $key) {
1017
      $keys[] = $index;
1018
    }
1019
  }
1020
  return $keys;
1021
}
1022
1023
/**
1024
 * Format a group of form items.
1025
 *
1026
 * @param $element
1027
 *   An associative array containing the properties of the element.
1028
 *   Properties used: attributes, title, value, description, children, collapsible, collapsed
1029
 * @return
1030
 *   A themed HTML string representing the form item group.
1031
 */
1032
function theme_fieldset($element) {
1033
  if ($element['#collapsible']) {
1034
    drupal_add_js('misc/collapse.js');
1035
1036
    if (!isset($element['#attributes']['class'])) {
1037
      $element['#attributes']['class'] = '';
1038
    }
1039
1040
    $element['#attributes']['class'] .= ' collapsible';
1041
    if ($element['#collapsed']) {
1042
     $element['#attributes']['class'] .= ' collapsed';
1043
    }
1044
  }
1045
1046
  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";
1047
}
1048
1049
/**
1050
 * Format a radio button.
1051
 *
1052
 * @param $element
1053
 *   An associative array containing the properties of the element.
1054
 *   Properties used: required, return_value, value, attributes, title, description
1055
 * @return
1056
 *   A themed HTML string representing the form item group.
1057
 */
1058
function theme_radio($element) {
1059
  _form_set_class($element, array('form-radio'));
1060
  $output = '<input type="radio" ';
1061
  $output .= 'name="' . $element['#name'] .'" ';
1062
  $output .= 'value="'. $element['#return_value'] .'" ';
1063
  $output .= (check_plain($element['#value']) == $element['#return_value']) ? ' checked="checked" ' : ' ';
1064
  $output .= drupal_attributes($element['#attributes']) .' />';
1065
  if (!is_null($element['#title'])) {
1066
    $output = '<label class="option">'. $output .' '. $element['#title'] .'</label>';
1067
  }
1068
1069
  unset($element['#title']);
1070
  return theme('form_element', $element, $output);
1071
}
1072
1073
/**
1074
 * Format a set of radio buttons.
1075
 *
1076
 * @param $element
1077
 *   An associative array containing the properties of the element.
1078
 *   Properties used: title, value, options, description, required and attributes.
1079
 * @return
1080
 *   A themed HTML string representing the radio button set.
1081
 */
1082
function theme_radios($element) {
1083
  $class = 'form-radios';
1084
  if (isset($element['#attributes']['class'])) {
1085
    $class .= ' '. $element['#attributes']['class'];
1086
  }
1087
  $element['#children'] = '<div class="'. $class .'">'. $element['#children'] .'</div>';
1088
  if ($element['#title'] || $element['#description']) {
1089
    unset($element['#id']);
1090
    return theme('form_element', $element, $element['#children']);
1091
  }
1092
  else {
1093
    return $element['#children'];
1094
  }
1095
}
1096
1097
/**
1098
 * Format a password_confirm item.
1099
 *
1100
 * @param $element
1101
 *   An associative array containing the properties of the element.
1102
 *   Properties used: title, value, id, required, error.
1103
 * @return
1104
 *   A themed HTML string representing the form item.
1105
 */
1106
function theme_password_confirm($element) {
1107
  return theme('form_element', $element, $element['#children']);
1108
}
1109
1110
/*
1111
 * Expand a password_confirm field into two text boxes.
1112
 */
1113
function expand_password_confirm($element) {
1114
  $element['pass1'] =  array(
1115
    '#type' => 'password',
1116
    '#title' => t('Password'),
1117
    '#value' => $element['#value']['pass1'],
1.1.1 by Michael Bienia
Import upstream version 5.2
1118
    '#required' => $element['#required'],
1 by Luigi Gangitano
Import upstream version 5.1
1119
  );
1120
  $element['pass2'] =  array(
1121
    '#type' => 'password',
1122
    '#title' => t('Confirm password'),
1123
    '#value' => $element['#value']['pass2'],
1.1.1 by Michael Bienia
Import upstream version 5.2
1124
    '#required' => $element['#required'],
1 by Luigi Gangitano
Import upstream version 5.1
1125
  );
1126
  $element['#validate'] = array('password_confirm_validate' => array());
1127
  $element['#tree'] = TRUE;
1128
1129
  if (isset($element['#size'])) {
1130
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
1131
  }
1132
1133
  return $element;
1134
}
1135
1136
/**
1137
 * Validate password_confirm element.
1138
 */
1139
function password_confirm_validate($form) {
1140
  $pass1 = trim($form['pass1']['#value']);
1141
  if (!empty($pass1)) {
1142
    $pass2 = trim($form['pass2']['#value']);
1143
    if ($pass1 != $pass2) {
1144
      form_error($form, t('The specified passwords do not match.'));
1145
    }
1146
  }
1147
  elseif ($form['#required'] && !empty($form['#post'])) {
1148
    form_error($form, t('Password field is required.'));
1149
  }
1150
1151
  // Password field must be converted from a two-element array into a single
1152
  // string regardless of validation results.
1153
  form_set_value($form['pass1'], NULL);
1154
  form_set_value($form['pass2'], NULL);
1155
  form_set_value($form, $pass1);
1156
1157
  return $form;
1158
}
1159
1160
/**
1161
 * Format a date selection element.
1162
 *
1163
 * @param $element
1164
 *   An associative array containing the properties of the element.
1165
 *   Properties used: title, value, options, description, required and attributes.
1166
 * @return
1167
 *   A themed HTML string representing the date selection boxes.
1168
 */
1169
function theme_date($element) {
1170
  return theme('form_element', $element, '<div class="container-inline">'. $element['#children'] .'</div>');
1171
}
1172
1173
/**
1174
 * Roll out a single date element.
1175
 */
1176
function expand_date($element) {
1177
  // Default to current date
1.1.1 by Michael Bienia
Import upstream version 5.2
1178
  if (empty($element['#value'])) {
1 by Luigi Gangitano
Import upstream version 5.1
1179
    $element['#value'] = array('day' => format_date(time(), 'custom', 'j'),
1180
                            'month' => format_date(time(), 'custom', 'n'),
1181
                            'year' => format_date(time(), 'custom', 'Y'));
1182
  }
1183
1184
  $element['#tree'] = TRUE;
1185
1186
  // Determine the order of day, month, year in the site's chosen date format.
1187
  $format = variable_get('date_format_short', 'm/d/Y - H:i');
1188
  $sort = array();
1189
  $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
1190
  $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
1191
  $sort['year'] = strpos($format, 'Y');
1192
  asort($sort);
1193
  $order = array_keys($sort);
1194
1195
  // Output multi-selector for date.
1196
  foreach ($order as $type) {
1197
    switch ($type) {
1198
      case 'day':
1199
        $options = drupal_map_assoc(range(1, 31));
1200
        break;
1201
      case 'month':
1202
        $options = drupal_map_assoc(range(1, 12), 'map_month');
1203
        break;
1204
      case 'year':
1205
        $options = drupal_map_assoc(range(1900, 2050));
1206
        break;
1207
    }
1208
    $parents = $element['#parents'];
1209
    $parents[] = $type;
1210
    $element[$type] = array(
1211
      '#type' => 'select',
1212
      '#value' => $element['#value'][$type],
1213
      '#attributes' => $element['#attributes'],
1214
      '#options' => $options,
1215
    );
1216
  }
1217
1218
  return $element;
1219
}
1220
1221
/**
1222
 * Validates the date type to stop dates like February 30, 2006.
1223
 */
1224
function date_validate($form) {
1225
  if (!checkdate($form['#value']['month'], $form['#value']['day'], $form['#value']['year'])) {
1226
    form_error($form, t('The specified date is invalid.'));
1227
  }
1228
}
1229
1230
/**
1231
 * Helper function for usage with drupal_map_assoc to display month names.
1232
 */
1233
function map_month($month) {
1234
  return format_date(gmmktime(0, 0, 0, $month, 2, 1970), 'custom', 'M', 0);
1235
}
1236
1237
/**
1238
 * Helper function to load value from default value for checkboxes.
1239
 */
1240
function checkboxes_value(&$form) {
1241
  $value = array();
1242
  foreach ((array)$form['#default_value'] as $key) {
1243
    $value[$key] = 1;
1244
  }
1245
  $form['#value'] = $value;
1246
}
1247
1248
/**
1249
 * If no default value is set for weight select boxes, use 0.
1250
 */
1251
function weight_value(&$form) {
1252
  if (isset($form['#default_value'])) {
1253
    $form['#value'] = $form['#default_value'];
1254
  }
1255
  else {
1256
    $form['#value'] = 0;
1257
  }
1258
}
1259
1260
/**
1261
 * Roll out a single radios element to a list of radios,
1262
 * using the options array as index.
1263
 */
1264
function expand_radios($element) {
1265
  if (count($element['#options']) > 0) {
1266
    foreach ($element['#options'] as $key => $choice) {
1267
      if (!isset($element[$key])) {
1268
        $element[$key] = array('#type' => 'radio', '#title' => $choice, '#return_value' => check_plain($key), '#default_value' => $element['#default_value'], '#attributes' => $element['#attributes'], '#parents' => $element['#parents'], '#spawned' => TRUE);
1269
      }
1270
    }
1271
  }
1272
  return $element;
1273
}
1274
1275
/**
1276
 * Format a form item.
1277
 *
1278
 * @param $element
1279
 *   An associative array containing the properties of the element.
1280
 *   Properties used:  title, value, description, required, error
1281
 * @return
1282
 *   A themed HTML string representing the form item.
1283
 */
1284
function theme_item($element) {
1285
  return theme('form_element', $element, $element['#value'] . $element['#children']);
1286
}
1287
1288
/**
1289
 * Format a checkbox.
1290
 *
1291
 * @param $element
1292
 *   An associative array containing the properties of the element.
1293
 *   Properties used:  title, value, return_value, description, required
1294
 * @return
1295
 *   A themed HTML string representing the checkbox.
1296
 */
1297
function theme_checkbox($element) {
1298
  _form_set_class($element, array('form-checkbox'));
1299
  $checkbox = '<input ';
1300
  $checkbox .= 'type="checkbox" ';
1301
  $checkbox .= 'name="'. $element['#name'] .'" ';
1302
  $checkbox .= 'id="'. $element['#id'].'" ' ;
1303
  $checkbox .= 'value="'. $element['#return_value'] .'" ';
1304
  $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
1305
  $checkbox .= drupal_attributes($element['#attributes']) . ' />';
1306
1307
  if (!is_null($element['#title'])) {
1308
    $checkbox = '<label class="option">'. $checkbox .' '. $element['#title'] .'</label>';
1309
  }
1310
1311
  unset($element['#title']);
1312
  return theme('form_element', $element, $checkbox);
1313
}
1314
1315
/**
1316
 * Format a set of checkboxes.
1317
 *
1318
 * @param $element
1319
 *   An associative array containing the properties of the element.
1320
 * @return
1321
 *   A themed HTML string representing the checkbox set.
1322
 */
1323
function theme_checkboxes($element) {
1324
  $class = 'form-checkboxes';
1325
  if (isset($element['#attributes']['class'])) {
1326
    $class .= ' '. $element['#attributes']['class'];
1327
  }
1328
  $element['#children'] = '<div class="'. $class .'">'. $element['#children'] .'</div>';
1329
  if ($element['#title'] || $element['#description']) {
1330
    unset($element['#id']);
1331
    return theme('form_element', $element, $element['#children']);
1332
  }
1333
  else {
1334
    return $element['#children'];
1335
  }
1336
}
1337
1338
function expand_checkboxes($element) {
1339
  $value = is_array($element['#value']) ? $element['#value'] : array();
1340
  $element['#tree'] = TRUE;
1341
  if (count($element['#options']) > 0) {
1342
    if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
1343
      $element['#default_value'] = array();
1344
    }
1345
    foreach ($element['#options'] as $key => $choice) {
1346
      if (!isset($element[$key])) {
1347
        $element[$key] = array('#type' => 'checkbox', '#processed' => TRUE, '#title' => $choice, '#return_value' => $key, '#default_value' => isset($value[$key]), '#attributes' => $element['#attributes']);
1348
      }
1349
    }
1350
  }
1351
  return $element;
1352
}
1353
1354
function theme_submit($element) {
1355
  return theme('button', $element);
1356
}
1357
1358
function theme_button($element) {
1359
  // Make sure not to overwrite classes.
1360
  if (isset($element['#attributes']['class'])) {
1361
    $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
1362
  }
1363
  else {
1364
    $element['#attributes']['class'] = 'form-'. $element['#button_type'];
1365
  }
1366
1367
  return '<input type="submit" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ')  .'id="'. $element['#id'].'" value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
1368
}
1369
1370
/**
1371
 * Format a hidden form field.
1372
 *
1373
 * @param $element
1374
 *   An associative array containing the properties of the element.
1375
 *   Properties used:  value, edit
1376
 * @return
1377
 *   A themed HTML string representing the hidden form field.
1378
 */
1379
function theme_hidden($element) {
1380
  return '<input type="hidden" name="'. $element['#name'] . '" id="'. $element['#id'] . '" value="'. check_plain($element['#value']) ."\" " . drupal_attributes($element['#attributes']) ." />\n";
1381
}
1382
1383
function theme_token($element) {
1384
  return theme('hidden', $element);
1385
}
1386
1387
/**
1388
 * Format a textfield.
1389
 *
1390
 * @param $element
1391
 *   An associative array containing the properties of the element.
1392
 *   Properties used:  title, value, description, size, maxlength, required, attributes autocomplete_path
1393
 * @return
1394
 *   A themed HTML string representing the textfield.
1395
 */
1396
function theme_textfield($element) {
1397
  $size = $element['#size'] ? ' size="' . $element['#size'] . '"' : '';
1398
  $class = array('form-text');
1399
  $extra = '';
1400
  $output = '';
1401
1402
  if ($element['#autocomplete_path']) {
1403
    drupal_add_js('misc/autocomplete.js');
1404
    $class[] = 'form-autocomplete';
1405
    $extra =  '<input class="autocomplete" type="hidden" id="'. $element['#id'] .'-autocomplete" value="'. check_url(url($element['#autocomplete_path'], NULL, NULL, TRUE)) .'" disabled="disabled" />';
1406
  }
1407
  _form_set_class($element, $class);
1408
1409
  if (isset($element['#field_prefix'])) {
1410
    $output .= '<span class="field-prefix">'. $element['#field_prefix'] .'</span> ';
1411
  }
1412
1413
  $output .= '<input type="text" maxlength="'. $element['#maxlength'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $size .' value="'. check_plain($element['#value']) .'"'. drupal_attributes($element['#attributes']) .' />';
1414
1415
  if (isset($element['#field_suffix'])) {
1416
    $output .= ' <span class="field-suffix">'. $element['#field_suffix'] .'</span>';
1417
  }
1418
1419
  return theme('form_element', $element, $output). $extra;
1420
}
1421
1422
/**
1423
 * Format a form.
1424
 *
1425
 * @param $element
1426
 *   An associative array containing the properties of the element.
1427
 *   Properties used: action, method, attributes, children
1428
 * @return
1429
 *   A themed HTML string representing the form.
1430
 */
1431
function theme_form($element) {
1432
  // Anonymous div to satisfy XHTML compliance.
1433
  $action = $element['#action'] ? 'action="' . check_url($element['#action']) . '" ' : '';
1.1.4 by Emanuele Gentili
Import upstream version 5.6
1434
  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";
1 by Luigi Gangitano
Import upstream version 5.1
1435
}
1436
1437
/**
1438
 * Format a textarea.
1439
 *
1440
 * @param $element
1441
 *   An associative array containing the properties of the element.
1442
 *   Properties used: title, value, description, rows, cols, required, attributes
1443
 * @return
1444
 *   A themed HTML string representing the textarea.
1445
 */
1446
function theme_textarea($element) {
1447
  $class = array('form-textarea');
1448
  if ($element['#resizable'] !== FALSE) {
1449
    drupal_add_js('misc/textarea.js');
1450
    $class[] = 'resizable';
1451
  }
1452
1453
  $cols = $element['#cols'] ? ' cols="'. $element['#cols'] .'"' : '';
1454
  _form_set_class($element, $class);
1455
  return theme('form_element', $element, '<textarea'. $cols .' rows="'. $element['#rows'] .'" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. drupal_attributes($element['#attributes']) .'>'. check_plain($element['#value']) .'</textarea>');
1456
}
1457
1458
/**
1459
 * Format HTML markup for use in forms.
1460
 *
1461
 * This is used in more advanced forms, such as theme selection and filter format.
1462
 *
1463
 * @param $element
1464
 *   An associative array containing the properties of the element.
1465
 *   Properties used: value, children.
1466
 * @return
1467
 *   A themed HTML string representing the HTML markup.
1468
 */
1469
1470
function theme_markup($element) {
1471
  return (isset($element['#value']) ? $element['#value'] : '') . (isset($element['#children']) ? $element['#children'] : '');
1472
}
1473
1474
/**
1475
* Format a password field.
1476
*
1477
* @param $element
1478
*   An associative array containing the properties of the element.
1479
*   Properties used:  title, value, description, size, maxlength, required, attributes
1480
* @return
1481
*   A themed HTML string representing the form.
1482
*/
1483
function theme_password($element) {
1484
  $size = $element['#size'] ? ' size="'. $element['#size'] .'" ' : '';
1485
  $maxlength = $element['#maxlength'] ? ' maxlength="'. $element['#maxlength'] .'" ' : '';
1486
1487
  _form_set_class($element, array('form-text'));
1488
  $output = '<input type="password" name="'. $element['#name'] .'" id="'. $element['#id'] .'" '. $maxlength . $size . drupal_attributes($element['#attributes']) .' />';
1489
  return theme('form_element', $element, $output);
1490
}
1491
1492
/**
1493
 * Expand weight elements into selects.
1494
 */
1495
function process_weight($element) {
1496
  for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
1497
    $weights[$n] = $n;
1498
  }
1499
  $element['#options'] = $weights;
1500
  $element['#type'] = 'select';
1501
  $element['#is_weight'] = TRUE;
1502
  return $element;
1503
}
1504
1505
/**
1506
 * Format a file upload field.
1507
 *
1508
 * @param $title
1509
 *   The label for the file upload field.
1510
 * @param $name
1511
 *   The internal name used to refer to the field.
1512
 * @param $size
1513
 *   A measure of the visible size of the field (passed directly to HTML).
1514
 * @param $description
1515
 *   Explanatory text to display after the form item.
1516
 * @param $required
1517
 *   Whether the user must upload a file to the field.
1518
 * @return
1519
 *   A themed HTML string representing the field.
1520
 *
1521
 * For assistance with handling the uploaded file correctly, see the API
1522
 * provided by file.inc.
1523
 */
1524
function theme_file($element) {
1525
  _form_set_class($element, array('form-file'));
1526
  return theme('form_element', $element, '<input type="file" name="'. $element['#name'] .'"'. ($element['#attributes'] ? ' '. drupal_attributes($element['#attributes']) : '') .' id="'. $element['#id'] .'" size="'. $element['#size'] ."\" />\n");
1527
}
1528
1529
/**
1530
 * Return a themed form element.
1531
 *
1532
 * @param element
1533
 *   An associative array containing the properties of the element.
1534
 *   Properties used: title, description, id, required
1535
 * @param $value
1536
 *   The form element's data.
1537
 * @return
1538
 *   A string representing the form element.
1539
 */
1540
function theme_form_element($element, $value) {
1541
  $output  = '<div class="form-item">'."\n";
1542
  $required = !empty($element['#required']) ? '<span class="form-required" title="'. t('This field is required.') .'">*</span>' : '';
1543
1544
  if (!empty($element['#title'])) {
1545
    $title = $element['#title'];
1546
    if (!empty($element['#id'])) {
1547
      $output .= ' <label for="'. $element['#id'] .'">'. t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
1548
    }
1549
    else {
1550
      $output .= ' <label>'. t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
1551
    }
1552
  }
1553
1554
  $output .= " $value\n";
1555
1556
  if (!empty($element['#description'])) {
1557
    $output .= ' <div class="description">'. $element['#description'] ."</div>\n";
1558
  }
1559
1560
  $output .= "</div>\n";
1561
1562
  return $output;
1563
}
1564
1565
/**
1566
 * Sets a form element's class attribute.
1567
 *
1568
 * Adds 'required' and 'error' classes as needed.
1569
 *
1570
 * @param &$element
1571
 *   The form element.
1572
 * @param $name
1573
 *   Array of new class names to be added.
1574
 */
1575
function _form_set_class(&$element, $class = array()) {
1576
  if ($element['#required']) {
1577
    $class[] = 'required';
1578
  }
1579
  if (form_get_error($element)){
1580
    $class[] = 'error';
1581
  }
1582
  if (isset($element['#attributes']['class'])) {
1583
    $class[] = $element['#attributes']['class'];
1584
  }
1585
  $element['#attributes']['class'] = implode(' ', $class);
1586
}
1587
1588
/**
1589
 * Remove invalid characters from an HTML ID attribute string.
1590
 *
1591
 * @param $id
1592
 *   The ID to clean.
1593
 * @return
1594
 *   The cleaned ID.
1595
 */
1596
function form_clean_id($id = NULL) {
1597
  $id = str_replace(array('][', '_', ' '), '-', $id);
1598
  return $id;
1599
}
1600
1601
/**
1602
 * @} End of "defgroup form".
1603
 */