Projet

Général

Profil

Paste
Télécharger (186 ko) Statistiques
| Branche: | Révision:

root / htmltest / includes / form.inc @ 85ad3d82

1
<?php
2
 /**
3
 * @file
4
 * Functions for form and batch generation and processing.
5
 */
6

    
7
/**
8
 * @defgroup forms Form builder functions
9
 * @{
10
 * Functions that build an abstract representation of a HTML form.
11
 *
12
 * All modules should declare their form builder functions to be in this
13
 * group and each builder function should reference its validate and submit
14
 * functions using \@see. Conversely, validate and submit functions should
15
 * reference the form builder function using \@see. For examples, of this see
16
 * system_modules_uninstall() or user_pass(), the latter of which has the
17
 * following in its doxygen documentation:
18
 *
19
 * \@ingroup forms
20
 * \@see user_pass_validate().
21
 * \@see user_pass_submit().
22
 *
23
 * @}
24
 */
25

    
26
/**
27
 * @defgroup form_api Form generation
28
 * @{
29
 * Functions to enable the processing and display of HTML forms.
30
 *
31
 * Drupal uses these functions to achieve consistency in its form processing and
32
 * presentation, while simplifying code and reducing the amount of HTML that
33
 * must be explicitly generated by modules.
34
 *
35
 * The primary function used with forms is drupal_get_form(), which is
36
 * used for forms presented interactively to a user. Forms can also be built and
37
 * submitted programmatically without any user input using the
38
 * drupal_form_submit() function.
39
 *
40
 * drupal_get_form() handles retrieving, processing, and displaying a rendered
41
 * HTML form for modules automatically.
42
 *
43
 * Here is an example of how to use drupal_get_form() and a form builder
44
 * function:
45
 * @code
46
 * $form = drupal_get_form('my_module_example_form');
47
 * ...
48
 * function my_module_example_form($form, &$form_state) {
49
 *   $form['submit'] = array(
50
 *     '#type' => 'submit',
51
 *     '#value' => t('Submit'),
52
 *   );
53
 *   return $form;
54
 * }
55
 * function my_module_example_form_validate($form, &$form_state) {
56
 *   // Validation logic.
57
 * }
58
 * function my_module_example_form_submit($form, &$form_state) {
59
 *   // Submission logic.
60
 * }
61
 * @endcode
62
 *
63
 * Or with any number of additional arguments:
64
 * @code
65
 * $extra = "extra";
66
 * $form = drupal_get_form('my_module_example_form', $extra);
67
 * ...
68
 * function my_module_example_form($form, &$form_state, $extra) {
69
 *   $form['submit'] = array(
70
 *     '#type' => 'submit',
71
 *     '#value' => $extra,
72
 *   );
73
 *   return $form;
74
 * }
75
 * @endcode
76
 *
77
 * The $form argument to form-related functions is a structured array containing
78
 * the elements and properties of the form. For information on the array
79
 * components and format, and more detailed explanations of the Form API
80
 * workflow, see the
81
 * @link forms_api_reference.html Form API reference @endlink
82
 * and the
83
 * @link http://drupal.org/node/37775 Form API documentation section. @endlink
84
 * In addition, there is a set of Form API tutorials in
85
 * @link form_example_tutorial.inc the Form Example Tutorial @endlink which
86
 * provide basics all the way up through multistep forms.
87
 *
88
 * In the form builder, validation, submission, and other form functions,
89
 * $form_state is the primary influence on the processing of the form and is
90
 * passed by reference to most functions, so they use it to communicate with
91
 * the form system and each other.
92
 *
93
 * See drupal_build_form() for documentation of $form_state keys.
94
 */
95

    
96
/**
97
 * Returns a renderable form array for a given form ID.
98
 *
99
 * This function should be used instead of drupal_build_form() when $form_state
100
 * is not needed (i.e., when initially rendering the form) and is often
101
 * used as a menu callback.
102
 *
103
 * @param $form_id
104
 *   The unique string identifying the desired form. If a function with that
105
 *   name exists, it is called to build the form array. Modules that need to
106
 *   generate the same form (or very similar forms) using different $form_ids
107
 *   can implement hook_forms(), which maps different $form_id values to the
108
 *   proper form constructor function. Examples may be found in node_forms(),
109
 *   and search_forms().
110
 * @param ...
111
 *   Any additional arguments are passed on to the functions called by
112
 *   drupal_get_form(), including the unique form constructor function. For
113
 *   example, the node_edit form requires that a node object is passed in here
114
 *   when it is called. These are available to implementations of
115
 *   hook_form_alter() and hook_form_FORM_ID_alter() as the array
116
 *   $form_state['build_info']['args'].
117
 *
118
 * @return
119
 *   The form array.
120
 *
121
 * @see drupal_build_form()
122
 */
123
function drupal_get_form($form_id) {
124
  $form_state = array();
125

    
126
  $args = func_get_args();
127
  // Remove $form_id from the arguments.
128
  array_shift($args);
129
  $form_state['build_info']['args'] = $args;
130

    
131
  return drupal_build_form($form_id, $form_state);
132
}
133

    
134
/**
135
 * Builds and process a form based on a form id.
136
 *
137
 * The form may also be retrieved from the cache if the form was built in a
138
 * previous page-load. The form is then passed on for processing, validation
139
 * and submission if there is proper input.
140
 *
141
 * @param $form_id
142
 *   The unique string identifying the desired form. If a function with that
143
 *   name exists, it is called to build the form array. Modules that need to
144
 *   generate the same form (or very similar forms) using different $form_ids
145
 *   can implement hook_forms(), which maps different $form_id values to the
146
 *   proper form constructor function. Examples may be found in node_forms(),
147
 *   and search_forms().
148
 * @param $form_state
149
 *   An array which stores information about the form. This is passed as a
150
 *   reference so that the caller can use it to examine what in the form changed
151
 *   when the form submission process is complete. Furthermore, it may be used
152
 *   to store information related to the processed data in the form, which will
153
 *   persist across page requests when the 'cache' or 'rebuild' flag is set.
154
 *   The following parameters may be set in $form_state to affect how the form
155
 *   is rendered:
156
 *   - build_info: Internal. An associative array of information stored by Form
157
 *     API that is necessary to build and rebuild the form from cache when the
158
 *     original context may no longer be available:
159
 *     - args: A list of arguments to pass to the form constructor.
160
 *     - files: An optional array defining include files that need to be loaded
161
 *       for building the form. Each array entry may be the path to a file or
162
 *       another array containing values for the parameters 'type', 'module' and
163
 *       'name' as needed by module_load_include(). The files listed here are
164
 *       automatically loaded by form_get_cache(). By default the current menu
165
 *       router item's 'file' definition is added, if any. Use
166
 *       form_load_include() to add include files from a form constructor.
167
 *     - form_id: Identification of the primary form being constructed and
168
 *       processed.
169
 *     - base_form_id: Identification for a base form, as declared in a
170
 *       hook_forms() implementation.
171
 *   - rebuild_info: Internal. Similar to 'build_info', but pertaining to
172
 *     drupal_rebuild_form().
173
 *   - rebuild: Normally, after the entire form processing is completed and
174
 *     submit handlers have run, a form is considered to be done and
175
 *     drupal_redirect_form() will redirect the user to a new page using a GET
176
 *     request (so a browser refresh does not re-submit the form). However, if
177
 *     'rebuild' has been set to TRUE, then a new copy of the form is
178
 *     immediately built and sent to the browser, instead of a redirect. This is
179
 *     used for multi-step forms, such as wizards and confirmation forms.
180
 *     Normally, $form_state['rebuild'] is set by a submit handler, since it is
181
 *     usually logic within a submit handler that determines whether a form is
182
 *     done or requires another step. However, a validation handler may already
183
 *     set $form_state['rebuild'] to cause the form processing to bypass submit
184
 *     handlers and rebuild the form instead, even if there are no validation
185
 *     errors.
186
 *   - redirect: Used to redirect the form on submission. It may either be a
187
 *     string containing the destination URL, or an array of arguments
188
 *     compatible with drupal_goto(). See drupal_redirect_form() for complete
189
 *     information.
190
 *   - no_redirect: If set to TRUE the form will NOT perform a drupal_goto(),
191
 *     even if 'redirect' is set.
192
 *   - method: The HTTP form method to use for finding the input for this form.
193
 *     May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method
194
 *     forms do not use form ids so are always considered to be submitted, which
195
 *     can have unexpected effects. The 'get' method should only be used on
196
 *     forms that do not change data, as that is exclusively the domain of
197
 *     'post.'
198
 *   - cache: If set to TRUE the original, unprocessed form structure will be
199
 *     cached, which allows the entire form to be rebuilt from cache. A typical
200
 *     form workflow involves two page requests; first, a form is built and
201
 *     rendered for the user to fill in. Then, the user fills the form in and
202
 *     submits it, triggering a second page request in which the form must be
203
 *     built and processed. By default, $form and $form_state are built from
204
 *     scratch during each of these page requests. Often, it is necessary or
205
 *     desired to persist the $form and $form_state variables from the initial
206
 *     page request to the one that processes the submission. 'cache' can be set
207
 *     to TRUE to do this. A prominent example is an Ajax-enabled form, in which
208
 *     ajax_process_form() enables form caching for all forms that include an
209
 *     element with the #ajax property. (The Ajax handler has no way to build
210
 *     the form itself, so must rely on the cached version.) Note that the
211
 *     persistence of $form and $form_state happens automatically for
212
 *     (multi-step) forms having the 'rebuild' flag set, regardless of the value
213
 *     for 'cache'.
214
 *   - no_cache: If set to TRUE the form will NOT be cached, even if 'cache' is
215
 *     set.
216
 *   - values: An associative array of values submitted to the form. The
217
 *     validation functions and submit functions use this array for nearly all
218
 *     their decision making. (Note that #tree determines whether the values are
219
 *     a flat array or an array whose structure parallels the $form array. See
220
 *     @link forms_api_reference.html Form API reference @endlink for more
221
 *     information.) These are raw and unvalidated, so should not be used
222
 *     without a thorough understanding of security implications. In almost all
223
 *     cases, code should use the data in the 'values' array exclusively. The
224
 *     most common use of this key is for multi-step forms that need to clear
225
 *     some of the user input when setting 'rebuild'. The values correspond to
226
 *     $_POST or $_GET, depending on the 'method' chosen.
227
 *   - always_process: If TRUE and the method is GET, a form_id is not
228
 *     necessary. This should only be used on RESTful GET forms that do NOT
229
 *     write data, as this could lead to security issues. It is useful so that
230
 *     searches do not need to have a form_id in their query arguments to
231
 *     trigger the search.
232
 *   - must_validate: Ordinarily, a form is only validated once, but there are
233
 *     times when a form is resubmitted internally and should be validated
234
 *     again. Setting this to TRUE will force that to happen. This is most
235
 *     likely to occur during Ajax operations.
236
 *   - programmed: If TRUE, the form was submitted programmatically, usually
237
 *     invoked via drupal_form_submit(). Defaults to FALSE.
238
 *   - process_input: Boolean flag. TRUE signifies correct form submission.
239
 *     This is always TRUE for programmed forms coming from drupal_form_submit()
240
 *     (see 'programmed' key), or if the form_id coming from the $_POST data is
241
 *     set and matches the current form_id.
242
 *   - submitted: If TRUE, the form has been submitted. Defaults to FALSE.
243
 *   - executed: If TRUE, the form was submitted and has been processed and
244
 *     executed. Defaults to FALSE.
245
 *   - triggering_element: (read-only) The form element that triggered
246
 *     submission. This is the same as the deprecated
247
 *     $form_state['clicked_button']. It is the element that caused submission,
248
 *     which may or may not be a button (in the case of Ajax forms). This key is
249
 *     often used to distinguish between various buttons in a submit handler,
250
 *     and is also used in Ajax handlers.
251
 *   - clicked_button: Deprecated. Use triggering_element instead.
252
 *   - has_file_element: Internal. If TRUE, there is a file element and Form API
253
 *     will set the appropriate 'enctype' HTML attribute on the form.
254
 *   - groups: Internal. An array containing references to fieldsets to render
255
 *     them within vertical tabs.
256
 *   - storage: $form_state['storage'] is not a special key, and no specific
257
 *     support is provided for it in the Form API. By tradition it was
258
 *     the location where application-specific data was stored for communication
259
 *     between the submit, validation, and form builder functions, especially
260
 *     in a multi-step-style form. Form implementations may use any key(s)
261
 *     within $form_state (other than the keys listed here and other reserved
262
 *     ones used by Form API internals) for this kind of storage. The
263
 *     recommended way to ensure that the chosen key doesn't conflict with ones
264
 *     used by the Form API or other modules is to use the module name as the
265
 *     key name or a prefix for the key name. For example, the Node module uses
266
 *     $form_state['node'] in node editing forms to store information about the
267
 *     node being edited, and this information stays available across successive
268
 *     clicks of the "Preview" button as well as when the "Save" button is
269
 *     finally clicked.
270
 *   - buttons: A list containing copies of all submit and button elements in
271
 *     the form.
272
 *   - complete form: A reference to the $form variable containing the complete
273
 *     form structure. #process, #after_build, #element_validate, and other
274
 *     handlers being invoked on a form element may use this reference to access
275
 *     other information in the form the element is contained in.
276
 *   - temporary: An array holding temporary data accessible during the current
277
 *     page request only. All $form_state properties that are not reserved keys
278
 *     (see form_state_keys_no_cache()) persist throughout a multistep form
279
 *     sequence. Form API provides this key for modules to communicate
280
 *     information across form-related functions during a single page request.
281
 *     It may be used to temporarily save data that does not need to or should
282
 *     not be cached during the whole form workflow; e.g., data that needs to be
283
 *     accessed during the current form build process only. There is no use-case
284
 *     for this functionality in Drupal core.
285
 *   - wrapper_callback: Modules that wish to pre-populate certain forms with
286
 *     common elements, such as back/next/save buttons in multi-step form
287
 *     wizards, may define a form builder function name that returns a form
288
 *     structure, which is passed on to the actual form builder function.
289
 *     Such implementations may either define the 'wrapper_callback' via
290
 *     hook_forms() or have to invoke drupal_build_form() (instead of
291
 *     drupal_get_form()) on their own in a custom menu callback to prepare
292
 *     $form_state accordingly.
293
 *   Information on how certain $form_state properties control redirection
294
 *   behavior after form submission may be found in drupal_redirect_form().
295
 *
296
 * @return
297
 *   The rendered form. This function may also perform a redirect and hence may
298
 *   not return at all, depending upon the $form_state flags that were set.
299
 *
300
 * @see drupal_redirect_form()
301
 */
302
function drupal_build_form($form_id, &$form_state) {
303
  // Ensure some defaults; if already set they will not be overridden.
304
  $form_state += form_state_defaults();
305

    
306
  if (!isset($form_state['input'])) {
307
    $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
308
  }
309

    
310
  if (isset($_SESSION['batch_form_state'])) {
311
    // We've been redirected here after a batch processing. The form has
312
    // already been processed, but needs to be rebuilt. See _batch_finished().
313
    $form_state = $_SESSION['batch_form_state'];
314
    unset($_SESSION['batch_form_state']);
315
    return drupal_rebuild_form($form_id, $form_state);
316
  }
317

    
318
  // If the incoming input contains a form_build_id, we'll check the cache for a
319
  // copy of the form in question. If it's there, we don't have to rebuild the
320
  // form to proceed. In addition, if there is stored form_state data from a
321
  // previous step, we'll retrieve it so it can be passed on to the form
322
  // processing code.
323
  $check_cache = isset($form_state['input']['form_id']) && $form_state['input']['form_id'] == $form_id && !empty($form_state['input']['form_build_id']);
324
  if ($check_cache) {
325
    $form = form_get_cache($form_state['input']['form_build_id'], $form_state);
326
  }
327

    
328
  // If the previous bit of code didn't result in a populated $form object, we
329
  // are hitting the form for the first time and we need to build it from
330
  // scratch.
331
  if (!isset($form)) {
332
    // If we attempted to serve the form from cache, uncacheable $form_state
333
    // keys need to be removed after retrieving and preparing the form, except
334
    // any that were already set prior to retrieving the form.
335
    if ($check_cache) {
336
      $form_state_before_retrieval = $form_state;
337
    }
338

    
339
    $form = drupal_retrieve_form($form_id, $form_state);
340
    drupal_prepare_form($form_id, $form, $form_state);
341

    
342
    // form_set_cache() removes uncacheable $form_state keys defined in
343
    // form_state_keys_no_cache() in order for multi-step forms to work
344
    // properly. This means that form processing logic for single-step forms
345
    // using $form_state['cache'] may depend on data stored in those keys
346
    // during drupal_retrieve_form()/drupal_prepare_form(), but form
347
    // processing should not depend on whether the form is cached or not, so
348
    // $form_state is adjusted to match what it would be after a
349
    // form_set_cache()/form_get_cache() sequence. These exceptions are
350
    // allowed to survive here:
351
    // - always_process: Does not make sense in conjunction with form caching
352
    //   in the first place, since passing form_build_id as a GET parameter is
353
    //   not desired.
354
    // - temporary: Any assigned data is expected to survives within the same
355
    //   page request.
356
    if ($check_cache) {
357
      $uncacheable_keys = array_flip(array_diff(form_state_keys_no_cache(), array('always_process', 'temporary')));
358
      $form_state = array_diff_key($form_state, $uncacheable_keys);
359
      $form_state += $form_state_before_retrieval;
360
    }
361
  }
362

    
363
  // Now that we have a constructed form, process it. This is where:
364
  // - Element #process functions get called to further refine $form.
365
  // - User input, if any, gets incorporated in the #value property of the
366
  //   corresponding elements and into $form_state['values'].
367
  // - Validation and submission handlers are called.
368
  // - If this submission is part of a multistep workflow, the form is rebuilt
369
  //   to contain the information of the next step.
370
  // - If necessary, the form and form state are cached or re-cached, so that
371
  //   appropriate information persists to the next page request.
372
  // All of the handlers in the pipeline receive $form_state by reference and
373
  // can use it to know or update information about the state of the form.
374
  drupal_process_form($form_id, $form, $form_state);
375

    
376
  // If this was a successful submission of a single-step form or the last step
377
  // of a multi-step form, then drupal_process_form() issued a redirect to
378
  // another page, or back to this page, but as a new request. Therefore, if
379
  // we're here, it means that this is either a form being viewed initially
380
  // before any user input, or there was a validation error requiring the form
381
  // to be re-displayed, or we're in a multi-step workflow and need to display
382
  // the form's next step. In any case, we have what we need in $form, and can
383
  // return it for rendering.
384
  return $form;
385
}
386

    
387
/**
388
 * Retrieves default values for the $form_state array.
389
 */
390
function form_state_defaults() {
391
  return array(
392
    'rebuild' => FALSE,
393
    'rebuild_info' => array(),
394
    'redirect' => NULL,
395
    // @todo 'args' is usually set, so no other default 'build_info' keys are
396
    //   appended via += form_state_defaults().
397
    'build_info' => array(
398
      'args' => array(),
399
      'files' => array(),
400
    ),
401
    'temporary' => array(),
402
    'submitted' => FALSE,
403
    'executed' => FALSE,
404
    'programmed' => FALSE,
405
    'cache'=> FALSE,
406
    'method' => 'post',
407
    'groups' => array(),
408
    'buttons' => array(),
409
  );
410
}
411

    
412
/**
413
 * Constructs a new $form from the information in $form_state.
414
 *
415
 * This is the key function for making multi-step forms advance from step to
416
 * step. It is called by drupal_process_form() when all user input processing,
417
 * including calling validation and submission handlers, for the request is
418
 * finished. If a validate or submit handler set $form_state['rebuild'] to TRUE,
419
 * and if other conditions don't preempt a rebuild from happening, then this
420
 * function is called to generate a new $form, the next step in the form
421
 * workflow, to be returned for rendering.
422
 *
423
 * Ajax form submissions are almost always multi-step workflows, so that is one
424
 * common use-case during which form rebuilding occurs. See ajax_form_callback()
425
 * for more information about creating Ajax-enabled forms.
426
 *
427
 * @param $form_id
428
 *   The unique string identifying the desired form. If a function
429
 *   with that name exists, it is called to build the form array.
430
 *   Modules that need to generate the same form (or very similar forms)
431
 *   using different $form_ids can implement hook_forms(), which maps
432
 *   different $form_id values to the proper form constructor function. Examples
433
 *   may be found in node_forms() and search_forms().
434
 * @param $form_state
435
 *   A keyed array containing the current state of the form.
436
 * @param $old_form
437
 *   (optional) A previously built $form. Used to retain the #build_id and
438
 *   #action properties in Ajax callbacks and similar partial form rebuilds. The
439
 *   only properties copied from $old_form are the ones which both exist in
440
 *   $old_form and for which $form_state['rebuild_info']['copy'][PROPERTY] is
441
 *   TRUE. If $old_form is not passed, the entire $form is rebuilt freshly.
442
 *   'rebuild_info' needs to be a separate top-level property next to
443
 *   'build_info', since the contained data must not be cached.
444
 *
445
 * @return
446
 *   The newly built form.
447
 *
448
 * @see drupal_process_form()
449
 * @see ajax_form_callback()
450
 */
451
function drupal_rebuild_form($form_id, &$form_state, $old_form = NULL) {
452
  $form = drupal_retrieve_form($form_id, $form_state);
453

    
454
  // If only parts of the form will be returned to the browser (e.g., Ajax or
455
  // RIA clients), re-use the old #build_id to not require client-side code to
456
  // manually update the hidden 'build_id' input element.
457
  // Otherwise, a new #build_id is generated, to not clobber the previous
458
  // build's data in the form cache; also allowing the user to go back to an
459
  // earlier build, make changes, and re-submit.
460
  // @see drupal_prepare_form()
461
  if (isset($old_form['#build_id']) && !empty($form_state['rebuild_info']['copy']['#build_id'])) {
462
    $form['#build_id'] = $old_form['#build_id'];
463
  }
464
  else {
465
    $form['#build_id'] = 'form-' . drupal_random_key();
466
  }
467

    
468
  // #action defaults to request_uri(), but in case of Ajax and other partial
469
  // rebuilds, the form is submitted to an alternate URL, and the original
470
  // #action needs to be retained.
471
  if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
472
    $form['#action'] = $old_form['#action'];
473
  }
474

    
475
  drupal_prepare_form($form_id, $form, $form_state);
476

    
477
  // Caching is normally done in drupal_process_form(), but what needs to be
478
  // cached is the $form structure before it passes through form_builder(),
479
  // so we need to do it here.
480
  // @todo For Drupal 8, find a way to avoid this code duplication.
481
  if (empty($form_state['no_cache'])) {
482
    form_set_cache($form['#build_id'], $form, $form_state);
483
  }
484

    
485
  // Clear out all group associations as these might be different when
486
  // re-rendering the form.
487
  $form_state['groups'] = array();
488

    
489
  // Return a fully built form that is ready for rendering.
490
  return form_builder($form_id, $form, $form_state);
491
}
492

    
493
/**
494
 * Fetches a form from cache.
495
 */
496
function form_get_cache($form_build_id, &$form_state) {
497
  if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
498
    $form = $cached->data;
499

    
500
    global $user;
501
    if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
502
      if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
503
        // Re-populate $form_state for subsequent rebuilds.
504
        $form_state = $cached->data + $form_state;
505

    
506
        // If the original form is contained in include files, load the files.
507
        // @see form_load_include()
508
        $form_state['build_info'] += array('files' => array());
509
        foreach ($form_state['build_info']['files'] as $file) {
510
          if (is_array($file)) {
511
            $file += array('type' => 'inc', 'name' => $file['module']);
512
            module_load_include($file['type'], $file['module'], $file['name']);
513
          }
514
          elseif (file_exists($file)) {
515
            require_once DRUPAL_ROOT . '/' . $file;
516
          }
517
        }
518
      }
519
      return $form;
520
    }
521
  }
522
}
523

    
524
/**
525
 * Stores a form in the cache.
526
 */
527
function form_set_cache($form_build_id, $form, $form_state) {
528
  // 6 hours cache life time for forms should be plenty.
529
  $expire = 21600;
530

    
531
  // Cache form structure.
532
  if (isset($form)) {
533
    if ($GLOBALS['user']->uid) {
534
      $form['#cache_token'] = drupal_get_token();
535
    }
536
    cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
537
  }
538

    
539
  // Cache form state.
540
  if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
541
    cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
542
  }
543
}
544

    
545
/**
546
 * Returns an array of $form_state keys that shouldn't be cached.
547
 */
548
function form_state_keys_no_cache() {
549
  return array(
550
    // Public properties defined by form constructors and form handlers.
551
    'always_process',
552
    'must_validate',
553
    'rebuild',
554
    'rebuild_info',
555
    'redirect',
556
    'no_redirect',
557
    'temporary',
558
    // Internal properties defined by form processing.
559
    'buttons',
560
    'triggering_element',
561
    'clicked_button',
562
    'complete form',
563
    'groups',
564
    'input',
565
    'method',
566
    'submit_handlers',
567
    'submitted',
568
    'executed',
569
    'validate_handlers',
570
    'values',
571
  );
572
}
573

    
574
/**
575
 * Ensures an include file is loaded whenever the form is processed.
576
 *
577
 * Example:
578
 * @code
579
 *   // Load node.admin.inc from Node module.
580
 *   form_load_include($form_state, 'inc', 'node', 'node.admin');
581
 * @endcode
582
 *
583
 * Use this function instead of module_load_include() from inside a form
584
 * constructor or any form processing logic as it ensures that the include file
585
 * is loaded whenever the form is processed. In contrast to using
586
 * module_load_include() directly, form_load_include() makes sure the include
587
 * file is correctly loaded also if the form is cached.
588
 *
589
 * @param $form_state
590
 *   The current state of the form.
591
 * @param $type
592
 *   The include file's type (file extension).
593
 * @param $module
594
 *   The module to which the include file belongs.
595
 * @param $name
596
 *   (optional) The base file name (without the $type extension). If omitted,
597
 *   $module is used; i.e., resulting in "$module.$type" by default.
598
 *
599
 * @return
600
 *   The filepath of the loaded include file, or FALSE if the include file was
601
 *   not found or has been loaded already.
602
 *
603
 * @see module_load_include()
604
 */
605
function form_load_include(&$form_state, $type, $module, $name = NULL) {
606
  if (!isset($name)) {
607
    $name = $module;
608
  }
609
  if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
610
    // Only add successfully included files to the form state.
611
    if ($result = module_load_include($type, $module, $name)) {
612
      $form_state['build_info']['files']["$module:$name.$type"] = array(
613
        'type' => $type,
614
        'module' => $module,
615
        'name' => $name,
616
      );
617
      return $result;
618
    }
619
  }
620
  return FALSE;
621
}
622

    
623
/**
624
 * Retrieves, populates, and processes a form.
625
 *
626
 * This function allows you to supply values for form elements and submit a
627
 * form for processing. Compare to drupal_get_form(), which also builds and
628
 * processes a form, but does not allow you to supply values.
629
 *
630
 * There is no return value, but you can check to see if there are errors
631
 * by calling form_get_errors().
632
 *
633
 * @param $form_id
634
 *   The unique string identifying the desired form. If a function
635
 *   with that name exists, it is called to build the form array.
636
 *   Modules that need to generate the same form (or very similar forms)
637
 *   using different $form_ids can implement hook_forms(), which maps
638
 *   different $form_id values to the proper form constructor function. Examples
639
 *   may be found in node_forms() and search_forms().
640
 * @param $form_state
641
 *   A keyed array containing the current state of the form. Most important is
642
 *   the $form_state['values'] collection, a tree of data used to simulate the
643
 *   incoming $_POST information from a user's form submission. If a key is not
644
 *   filled in $form_state['values'], then the default value of the respective
645
 *   element is used. To submit an unchecked checkbox or other control that
646
 *   browsers submit by not having a $_POST entry, include the key, but set the
647
 *   value to NULL.
648
 * @param ...
649
 *   Any additional arguments are passed on to the functions called by
650
 *   drupal_form_submit(), including the unique form constructor function.
651
 *   For example, the node_edit form requires that a node object be passed
652
 *   in here when it is called. Arguments that need to be passed by reference
653
 *   should not be included here, but rather placed directly in the $form_state
654
 *   build info array so that the reference can be preserved. For example, a
655
 *   form builder function with the following signature:
656
 *   @code
657
 *   function mymodule_form($form, &$form_state, &$object) {
658
 *   }
659
 *   @endcode
660
 *   would be called via drupal_form_submit() as follows:
661
 *   @code
662
 *   $form_state['values'] = $my_form_values;
663
 *   $form_state['build_info']['args'] = array(&$object);
664
 *   drupal_form_submit('mymodule_form', $form_state);
665
 *   @endcode
666
 * For example:
667
 * @code
668
 * // register a new user
669
 * $form_state = array();
670
 * $form_state['values']['name'] = 'robo-user';
671
 * $form_state['values']['mail'] = 'robouser@example.com';
672
 * $form_state['values']['pass']['pass1'] = 'password';
673
 * $form_state['values']['pass']['pass2'] = 'password';
674
 * $form_state['values']['op'] = t('Create new account');
675
 * drupal_form_submit('user_register_form', $form_state);
676
 * @endcode
677
 */
678
function drupal_form_submit($form_id, &$form_state) {
679
  if (!isset($form_state['build_info']['args'])) {
680
    $args = func_get_args();
681
    array_shift($args);
682
    array_shift($args);
683
    $form_state['build_info']['args'] = $args;
684
  }
685
  // Merge in default values.
686
  $form_state += form_state_defaults();
687

    
688
  // Populate $form_state['input'] with the submitted values before retrieving
689
  // the form, to be consistent with what drupal_build_form() does for
690
  // non-programmatic submissions (form builder functions may expect it to be
691
  // there).
692
  $form_state['input'] = $form_state['values'];
693

    
694
  $form_state['programmed'] = TRUE;
695
  $form = drupal_retrieve_form($form_id, $form_state);
696
  // Programmed forms are always submitted.
697
  $form_state['submitted'] = TRUE;
698

    
699
  // Reset form validation.
700
  $form_state['must_validate'] = TRUE;
701
  form_clear_error();
702

    
703
  drupal_prepare_form($form_id, $form, $form_state);
704
  drupal_process_form($form_id, $form, $form_state);
705
}
706

    
707
/**
708
 * Retrieves the structured array that defines a given form.
709
 *
710
 * @param $form_id
711
 *   The unique string identifying the desired form. If a function
712
 *   with that name exists, it is called to build the form array.
713
 *   Modules that need to generate the same form (or very similar forms)
714
 *   using different $form_ids can implement hook_forms(), which maps
715
 *   different $form_id values to the proper form constructor function.
716
 * @param $form_state
717
 *   A keyed array containing the current state of the form, including the
718
 *   additional arguments to drupal_get_form() or drupal_form_submit() in the
719
 *   'args' component of the array.
720
 */
721
function drupal_retrieve_form($form_id, &$form_state) {
722
  $forms = &drupal_static(__FUNCTION__);
723

    
724
  // Record the $form_id.
725
  $form_state['build_info']['form_id'] = $form_id;
726

    
727
  // Record the filepath of the include file containing the original form, so
728
  // the form builder callbacks can be loaded when the form is being rebuilt
729
  // from cache on a different path (such as 'system/ajax'). See
730
  // form_get_cache(). Don't do this in maintenance mode as Drupal may not be
731
  // fully bootstrapped (i.e. during installation) in which case
732
  // menu_get_item() is not available.
733
  if (!isset($form_state['build_info']['files']['menu']) && !defined('MAINTENANCE_MODE')) {
734
    $item = menu_get_item();
735
    if (!empty($item['include_file'])) {
736
      // Do not use form_load_include() here, as the file is already loaded.
737
      // Anyway, form_get_cache() is able to handle filepaths too.
738
      $form_state['build_info']['files']['menu'] = $item['include_file'];
739
    }
740
  }
741

    
742
  // We save two copies of the incoming arguments: one for modules to use
743
  // when mapping form ids to constructor functions, and another to pass to
744
  // the constructor function itself.
745
  $args = $form_state['build_info']['args'];
746

    
747
  // We first check to see if there's a function named after the $form_id.
748
  // If there is, we simply pass the arguments on to it to get the form.
749
  if (!function_exists($form_id)) {
750
    // In cases where many form_ids need to share a central constructor function,
751
    // such as the node editing form, modules can implement hook_forms(). It
752
    // maps one or more form_ids to the correct constructor functions.
753
    //
754
    // We cache the results of that hook to save time, but that only works
755
    // for modules that know all their form_ids in advance. (A module that
756
    // adds a small 'rate this comment' form to each comment in a list
757
    // would need a unique form_id for each one, for example.)
758
    //
759
    // So, we call the hook if $forms isn't yet populated, OR if it doesn't
760
    // yet have an entry for the requested form_id.
761
    if (!isset($forms) || !isset($forms[$form_id])) {
762
      $forms = module_invoke_all('forms', $form_id, $args);
763
    }
764
    $form_definition = $forms[$form_id];
765
    if (isset($form_definition['callback arguments'])) {
766
      $args = array_merge($form_definition['callback arguments'], $args);
767
    }
768
    if (isset($form_definition['callback'])) {
769
      $callback = $form_definition['callback'];
770
      $form_state['build_info']['base_form_id'] = $callback;
771
    }
772
    // In case $form_state['wrapper_callback'] is not defined already, we also
773
    // allow hook_forms() to define one.
774
    if (!isset($form_state['wrapper_callback']) && isset($form_definition['wrapper_callback'])) {
775
      $form_state['wrapper_callback'] = $form_definition['wrapper_callback'];
776
    }
777
  }
778

    
779
  $form = array();
780
  // We need to pass $form_state by reference in order for forms to modify it,
781
  // since call_user_func_array() requires that referenced variables are passed
782
  // explicitly.
783
  $args = array_merge(array($form, &$form_state), $args);
784

    
785
  // When the passed $form_state (not using drupal_get_form()) defines a
786
  // 'wrapper_callback', then it requests to invoke a separate (wrapping) form
787
  // builder function to pre-populate the $form array with form elements, which
788
  // the actual form builder function ($callback) expects. This allows for
789
  // pre-populating a form with common elements for certain forms, such as
790
  // back/next/save buttons in multi-step form wizards. See drupal_build_form().
791
  if (isset($form_state['wrapper_callback']) && function_exists($form_state['wrapper_callback'])) {
792
    $form = call_user_func_array($form_state['wrapper_callback'], $args);
793
    // Put the prepopulated $form into $args.
794
    $args[0] = $form;
795
  }
796

    
797
  // If $callback was returned by a hook_forms() implementation, call it.
798
  // Otherwise, call the function named after the form id.
799
  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
800
  $form['#form_id'] = $form_id;
801

    
802
  return $form;
803
}
804

    
805
/**
806
 * Processes a form submission.
807
 *
808
 * This function is the heart of form API. The form gets built, validated and in
809
 * appropriate cases, submitted and rebuilt.
810
 *
811
 * @param $form_id
812
 *   The unique string identifying the current form.
813
 * @param $form
814
 *   An associative array containing the structure of the form.
815
 * @param $form_state
816
 *   A keyed array containing the current state of the form. This
817
 *   includes the current persistent storage data for the form, and
818
 *   any data passed along by earlier steps when displaying a
819
 *   multi-step form. Additional information, like the sanitized $_POST
820
 *   data, is also accumulated here.
821
 */
822
function drupal_process_form($form_id, &$form, &$form_state) {
823
  $form_state['values'] = array();
824

    
825
  // With $_GET, these forms are always submitted if requested.
826
  if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
827
    if (!isset($form_state['input']['form_build_id'])) {
828
      $form_state['input']['form_build_id'] = $form['#build_id'];
829
    }
830
    if (!isset($form_state['input']['form_id'])) {
831
      $form_state['input']['form_id'] = $form_id;
832
    }
833
    if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
834
      $form_state['input']['form_token'] = drupal_get_token($form['#token']);
835
    }
836
  }
837

    
838
  // form_builder() finishes building the form by calling element #process
839
  // functions and mapping user input, if any, to #value properties, and also
840
  // storing the values in $form_state['values']. We need to retain the
841
  // unprocessed $form in case it needs to be cached.
842
  $unprocessed_form = $form;
843
  $form = form_builder($form_id, $form, $form_state);
844

    
845
  // Only process the input if we have a correct form submission.
846
  if ($form_state['process_input']) {
847
    drupal_validate_form($form_id, $form, $form_state);
848

    
849
    // drupal_html_id() maintains a cache of element IDs it has seen,
850
    // so it can prevent duplicates. We want to be sure we reset that
851
    // cache when a form is processed, so scenarios that result in
852
    // the form being built behind the scenes and again for the
853
    // browser don't increment all the element IDs needlessly.
854
    if (!form_get_errors()) {
855
      // In case of errors, do not break HTML IDs of other forms.
856
      drupal_static_reset('drupal_html_id');
857
    }
858

    
859
    if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
860
      // Execute form submit handlers.
861
      form_execute_handlers('submit', $form, $form_state);
862

    
863
      // We'll clear out the cached copies of the form and its stored data
864
      // here, as we've finished with them. The in-memory copies are still
865
      // here, though.
866
      if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
867
        cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
868
        cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
869
      }
870

    
871
      // If batches were set in the submit handlers, we process them now,
872
      // possibly ending execution. We make sure we do not react to the batch
873
      // that is already being processed (if a batch operation performs a
874
      // drupal_form_submit).
875
      if ($batch =& batch_get() && !isset($batch['current_set'])) {
876
        // Store $form_state information in the batch definition.
877
        // We need the full $form_state when either:
878
        // - Some submit handlers were saved to be called during batch
879
        //   processing. See form_execute_handlers().
880
        // - The form is multistep.
881
        // In other cases, we only need the information expected by
882
        // drupal_redirect_form().
883
        if ($batch['has_form_submits'] || !empty($form_state['rebuild'])) {
884
          $batch['form_state'] = $form_state;
885
        }
886
        else {
887
          $batch['form_state'] = array_intersect_key($form_state, array_flip(array('programmed', 'rebuild', 'storage', 'no_redirect', 'redirect')));
888
        }
889

    
890
        $batch['progressive'] = !$form_state['programmed'];
891
        batch_process();
892

    
893
        // Execution continues only for programmatic forms.
894
        // For 'regular' forms, we get redirected to the batch processing
895
        // page. Form redirection will be handled in _batch_finished(),
896
        // after the batch is processed.
897
      }
898

    
899
      // Set a flag to indicate the the form has been processed and executed.
900
      $form_state['executed'] = TRUE;
901

    
902
      // Redirect the form based on values in $form_state.
903
      drupal_redirect_form($form_state);
904
    }
905

    
906
    // Don't rebuild or cache form submissions invoked via drupal_form_submit().
907
    if (!empty($form_state['programmed'])) {
908
      return;
909
    }
910

    
911
    // If $form_state['rebuild'] has been set and input has been processed
912
    // without validation errors, we are in a multi-step workflow that is not
913
    // yet complete. A new $form needs to be constructed based on the changes
914
    // made to $form_state during this request. Normally, a submit handler sets
915
    // $form_state['rebuild'] if a fully executed form requires another step.
916
    // However, for forms that have not been fully executed (e.g., Ajax
917
    // submissions triggered by non-buttons), there is no submit handler to set
918
    // $form_state['rebuild']. It would not make sense to redisplay the
919
    // identical form without an error for the user to correct, so we also
920
    // rebuild error-free non-executed forms, regardless of
921
    // $form_state['rebuild'].
922
    // @todo D8: Simplify this logic; considering Ajax and non-HTML front-ends,
923
    //   along with element-level #submit properties, it makes no sense to have
924
    //   divergent form execution based on whether the triggering element has
925
    //   #executes_submit_callback set to TRUE.
926
    if (($form_state['rebuild'] || !$form_state['executed']) && !form_get_errors()) {
927
      // Form building functions (e.g., _form_builder_handle_input_element())
928
      // may use $form_state['rebuild'] to determine if they are running in the
929
      // context of a rebuild, so ensure it is set.
930
      $form_state['rebuild'] = TRUE;
931
      $form = drupal_rebuild_form($form_id, $form_state, $form);
932
    }
933
  }
934

    
935
  // After processing the form, the form builder or a #process callback may
936
  // have set $form_state['cache'] to indicate that the form and form state
937
  // shall be cached. But the form may only be cached if the 'no_cache' property
938
  // is not set to TRUE. Only cache $form as it was prior to form_builder(),
939
  // because form_builder() must run for each request to accommodate new user
940
  // input. Rebuilt forms are not cached here, because drupal_rebuild_form()
941
  // already takes care of that.
942
  if (!$form_state['rebuild'] && $form_state['cache'] && empty($form_state['no_cache'])) {
943
    form_set_cache($form['#build_id'], $unprocessed_form, $form_state);
944
  }
945
}
946

    
947
/**
948
 * Prepares a structured form array.
949
 *
950
 * Adds required elements, executes any hook_form_alter functions, and
951
 * optionally inserts a validation token to prevent tampering.
952
 *
953
 * @param $form_id
954
 *   A unique string identifying the form for validation, submission,
955
 *   theming, and hook_form_alter functions.
956
 * @param $form
957
 *   An associative array containing the structure of the form.
958
 * @param $form_state
959
 *   A keyed array containing the current state of the form. Passed
960
 *   in here so that hook_form_alter() calls can use it, as well.
961
 */
962
function drupal_prepare_form($form_id, &$form, &$form_state) {
963
  global $user;
964

    
965
  $form['#type'] = 'form';
966
  $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
967

    
968
  // Fix the form method, if it is 'get' in $form_state, but not in $form.
969
  if ($form_state['method'] == 'get' && !isset($form['#method'])) {
970
    $form['#method'] = 'get';
971
  }
972

    
973
  // Generate a new #build_id for this form, if none has been set already. The
974
  // form_build_id is used as key to cache a particular build of the form. For
975
  // multi-step forms, this allows the user to go back to an earlier build, make
976
  // changes, and re-submit.
977
  // @see drupal_build_form()
978
  // @see drupal_rebuild_form()
979
  if (!isset($form['#build_id'])) {
980
    $form['#build_id'] = 'form-' . drupal_random_key();
981
  }
982
  $form['form_build_id'] = array(
983
    '#type' => 'hidden',
984
    '#value' => $form['#build_id'],
985
    '#id' => $form['#build_id'],
986
    '#name' => 'form_build_id',
987
    // Form processing and validation requires this value, so ensure the
988
    // submitted form value appears literally, regardless of custom #tree
989
    // and #parents being set elsewhere.
990
    '#parents' => array('form_build_id'),
991
  );
992

    
993
  // Add a token, based on either #token or form_id, to any form displayed to
994
  // authenticated users. This ensures that any submitted form was actually
995
  // requested previously by the user and protects against cross site request
996
  // forgeries.
997
  // This does not apply to programmatically submitted forms. Furthermore, since
998
  // tokens are session-bound and forms displayed to anonymous users are very
999
  // likely cached, we cannot assign a token for them.
1000
  // During installation, there is no $user yet.
1001
  if (!empty($user->uid) && !$form_state['programmed']) {
1002
    // Form constructors may explicitly set #token to FALSE when cross site
1003
    // request forgery is irrelevant to the form, such as search forms.
1004
    if (isset($form['#token']) && $form['#token'] === FALSE) {
1005
      unset($form['#token']);
1006
    }
1007
    // Otherwise, generate a public token based on the form id.
1008
    else {
1009
      $form['#token'] = $form_id;
1010
      $form['form_token'] = array(
1011
        '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
1012
        '#type' => 'token',
1013
        '#default_value' => drupal_get_token($form['#token']),
1014
        // Form processing and validation requires this value, so ensure the
1015
        // submitted form value appears literally, regardless of custom #tree
1016
        // and #parents being set elsewhere.
1017
        '#parents' => array('form_token'),
1018
      );
1019
    }
1020
  }
1021

    
1022
  if (isset($form_id)) {
1023
    $form['form_id'] = array(
1024
      '#type' => 'hidden',
1025
      '#value' => $form_id,
1026
      '#id' => drupal_html_id("edit-$form_id"),
1027
      // Form processing and validation requires this value, so ensure the
1028
      // submitted form value appears literally, regardless of custom #tree
1029
      // and #parents being set elsewhere.
1030
      '#parents' => array('form_id'),
1031
    );
1032
  }
1033
  if (!isset($form['#id'])) {
1034
    $form['#id'] = drupal_html_id($form_id);
1035
  }
1036

    
1037
  $form += element_info('form');
1038
  $form += array('#tree' => FALSE, '#parents' => array());
1039

    
1040
  if (!isset($form['#validate'])) {
1041
    // Ensure that modules can rely on #validate being set.
1042
    $form['#validate'] = array();
1043
    // Check for a handler specific to $form_id.
1044
    if (function_exists($form_id . '_validate')) {
1045
      $form['#validate'][] = $form_id . '_validate';
1046
    }
1047
    // Otherwise check whether this is a shared form and whether there is a
1048
    // handler for the shared $form_id.
1049
    elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_validate')) {
1050
      $form['#validate'][] = $form_state['build_info']['base_form_id'] . '_validate';
1051
    }
1052
  }
1053

    
1054
  if (!isset($form['#submit'])) {
1055
    // Ensure that modules can rely on #submit being set.
1056
    $form['#submit'] = array();
1057
    // Check for a handler specific to $form_id.
1058
    if (function_exists($form_id . '_submit')) {
1059
      $form['#submit'][] = $form_id . '_submit';
1060
    }
1061
    // Otherwise check whether this is a shared form and whether there is a
1062
    // handler for the shared $form_id.
1063
    elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
1064
      $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
1065
    }
1066
  }
1067

    
1068
  // If no #theme has been set, automatically apply theme suggestions.
1069
  // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
1070
  // #theme function only has to care for rendering the inner form elements,
1071
  // not the form itself.
1072
  if (!isset($form['#theme'])) {
1073
    $form['#theme'] = array($form_id);
1074
    if (isset($form_state['build_info']['base_form_id'])) {
1075
      $form['#theme'][] = $form_state['build_info']['base_form_id'];
1076
    }
1077
  }
1078

    
1079
  // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
1080
  // hook_form_FORM_ID_alter() implementations.
1081
  $hooks = array('form');
1082
  if (isset($form_state['build_info']['base_form_id'])) {
1083
    $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
1084
  }
1085
  $hooks[] = 'form_' . $form_id;
1086
  drupal_alter($hooks, $form, $form_state, $form_id);
1087
}
1088

    
1089

    
1090
/**
1091
 * Validates user-submitted form data in the $form_state array.
1092
 *
1093
 * @param $form_id
1094
 *   A unique string identifying the form for validation, submission,
1095
 *   theming, and hook_form_alter functions.
1096
 * @param $form
1097
 *   An associative array containing the structure of the form, which is passed
1098
 *   by reference. Form validation handlers are able to alter the form structure
1099
 *   (like #process and #after_build callbacks during form building) in case of
1100
 *   a validation error. If a validation handler alters the form structure, it
1101
 *   is responsible for validating the values of changed form elements in
1102
 *   $form_state['values'] to prevent form submit handlers from receiving
1103
 *   unvalidated values.
1104
 * @param $form_state
1105
 *   A keyed array containing the current state of the form. The current
1106
 *   user-submitted data is stored in $form_state['values'], though
1107
 *   form validation functions are passed an explicit copy of the
1108
 *   values for the sake of simplicity. Validation handlers can also use
1109
 *   $form_state to pass information on to submit handlers. For example:
1110
 *     $form_state['data_for_submission'] = $data;
1111
 *   This technique is useful when validation requires file parsing,
1112
 *   web service requests, or other expensive requests that should
1113
 *   not be repeated in the submission step.
1114
 */
1115
function drupal_validate_form($form_id, &$form, &$form_state) {
1116
  $validated_forms = &drupal_static(__FUNCTION__, array());
1117

    
1118
  if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
1119
    return;
1120
  }
1121

    
1122
  // If the session token was set by drupal_prepare_form(), ensure that it
1123
  // matches the current user's session.
1124
  if (isset($form['#token'])) {
1125
    if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
1126
      $path = current_path();
1127
      $query = drupal_get_query_parameters();
1128
      $url = url($path, array('query' => $query));
1129

    
1130
      // Setting this error will cause the form to fail validation.
1131
      form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then <a href="@link">reload this page</a>.', array('@link' => $url)));
1132

    
1133
      // Stop here and don't run any further validation handlers, because they
1134
      // could invoke non-safe operations which opens the door for CSRF
1135
      // vulnerabilities.
1136
      $validated_forms[$form_id] = TRUE;
1137
      return;
1138
    }
1139
  }
1140

    
1141
  _form_validate($form, $form_state, $form_id);
1142
  $validated_forms[$form_id] = TRUE;
1143

    
1144
  // If validation errors are limited then remove any non validated form values,
1145
  // so that only values that passed validation are left for submit callbacks.
1146
  if (isset($form_state['triggering_element']['#limit_validation_errors']) && $form_state['triggering_element']['#limit_validation_errors'] !== FALSE) {
1147
    $values = array();
1148
    foreach ($form_state['triggering_element']['#limit_validation_errors'] as $section) {
1149
      // If the section exists within $form_state['values'], even if the value
1150
      // is NULL, copy it to $values.
1151
      $section_exists = NULL;
1152
      $value = drupal_array_get_nested_value($form_state['values'], $section, $section_exists);
1153
      if ($section_exists) {
1154
        drupal_array_set_nested_value($values, $section, $value);
1155
      }
1156
    }
1157
    // A button's #value does not require validation, so for convenience we
1158
    // allow the value of the clicked button to be retained in its normal
1159
    // $form_state['values'] locations, even if these locations are not included
1160
    // in #limit_validation_errors.
1161
    if (isset($form_state['triggering_element']['#button_type'])) {
1162
      $button_value = $form_state['triggering_element']['#value'];
1163

    
1164
      // Like all input controls, the button value may be in the location
1165
      // dictated by #parents. If it is, copy it to $values, but do not override
1166
      // what may already be in $values.
1167
      $parents = $form_state['triggering_element']['#parents'];
1168
      if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
1169
        drupal_array_set_nested_value($values, $parents, $button_value);
1170
      }
1171

    
1172
      // Additionally, form_builder() places the button value in
1173
      // $form_state['values'][BUTTON_NAME]. If it's still there, after
1174
      // validation handlers have run, copy it to $values, but do not override
1175
      // what may already be in $values.
1176
      $name = $form_state['triggering_element']['#name'];
1177
      if (!isset($values[$name]) && isset($form_state['values'][$name]) && $form_state['values'][$name] === $button_value) {
1178
        $values[$name] = $button_value;
1179
      }
1180
    }
1181
    $form_state['values'] = $values;
1182
  }
1183
}
1184

    
1185
/**
1186
 * Redirects the user to a URL after a form has been processed.
1187
 *
1188
 * After a form is submitted and processed, normally the user should be
1189
 * redirected to a new destination page. This function figures out what that
1190
 * destination should be, based on the $form_state array and the 'destination'
1191
 * query string in the request URL, and redirects the user there.
1192
 *
1193
 * Usually (for exceptions, see below) $form_state['redirect'] determines where
1194
 * to redirect the user. This can be set either to a string (the path to
1195
 * redirect to), or an array of arguments for drupal_goto(). If
1196
 * $form_state['redirect'] is missing, the user is usually (again, see below for
1197
 * exceptions) redirected back to the page they came from, where they should see
1198
 * a fresh, unpopulated copy of the form.
1199
 *
1200
 * Here is an example of how to set up a form to redirect to the path 'node':
1201
 * @code
1202
 * $form_state['redirect'] = 'node';
1203
 * @endcode
1204
 * And here is an example of how to redirect to 'node/123?foo=bar#baz':
1205
 * @code
1206
 * $form_state['redirect'] = array(
1207
 *   'node/123',
1208
 *   array(
1209
 *     'query' => array(
1210
 *       'foo' => 'bar',
1211
 *     ),
1212
 *     'fragment' => 'baz',
1213
 *   ),
1214
 * );
1215
 * @endcode
1216
 *
1217
 * There are several exceptions to the "usual" behavior described above:
1218
 * - If $form_state['programmed'] is TRUE, the form submission was usually
1219
 *   invoked via drupal_form_submit(), so any redirection would break the script
1220
 *   that invoked drupal_form_submit() and no redirection is done.
1221
 * - If $form_state['rebuild'] is TRUE, the form is being rebuilt, and no
1222
 *   redirection is done.
1223
 * - If $form_state['no_redirect'] is TRUE, redirection is disabled. This is
1224
 *   set, for instance, by ajax_get_form() to prevent redirection in Ajax
1225
 *   callbacks. $form_state['no_redirect'] should never be set or altered by
1226
 *   form builder functions or form validation/submit handlers.
1227
 * - If $form_state['redirect'] is set to FALSE, redirection is disabled.
1228
 * - If none of the above conditions has prevented redirection, then the
1229
 *   redirect is accomplished by calling drupal_goto(), passing in the value of
1230
 *   $form_state['redirect'] if it is set, or the current path if it is
1231
 *   not. drupal_goto() preferentially uses the value of $_GET['destination']
1232
 *   (the 'destination' URL query string) if it is present, so this will
1233
 *   override any values set by $form_state['redirect']. Note that during
1234
 *   installation, install_goto() is called in place of drupal_goto().
1235
 *
1236
 * @param $form_state
1237
 *   An associative array containing the current state of the form.
1238
 *
1239
 * @see drupal_process_form()
1240
 * @see drupal_build_form()
1241
 */
1242
function drupal_redirect_form($form_state) {
1243
  // Skip redirection for form submissions invoked via drupal_form_submit().
1244
  if (!empty($form_state['programmed'])) {
1245
    return;
1246
  }
1247
  // Skip redirection if rebuild is activated.
1248
  if (!empty($form_state['rebuild'])) {
1249
    return;
1250
  }
1251
  // Skip redirection if it was explicitly disallowed.
1252
  if (!empty($form_state['no_redirect'])) {
1253
    return;
1254
  }
1255
  // Only invoke drupal_goto() if redirect value was not set to FALSE.
1256
  if (!isset($form_state['redirect']) || $form_state['redirect'] !== FALSE) {
1257
    if (isset($form_state['redirect'])) {
1258
      if (is_array($form_state['redirect'])) {
1259
        call_user_func_array('drupal_goto', $form_state['redirect']);
1260
      }
1261
      else {
1262
        // This function can be called from the installer, which guarantees
1263
        // that $redirect will always be a string, so catch that case here
1264
        // and use the appropriate redirect function.
1265
        $function = drupal_installation_attempted() ? 'install_goto' : 'drupal_goto';
1266
        $function($form_state['redirect']);
1267
      }
1268
    }
1269
    drupal_goto(current_path(), array('query' => drupal_get_query_parameters()));
1270
  }
1271
}
1272

    
1273
/**
1274
 * Performs validation on form elements.
1275
 *
1276
 * First ensures required fields are completed, #maxlength is not exceeded, and
1277
 * selected options were in the list of options given to the user. Then calls
1278
 * user-defined validators.
1279
 *
1280
 * @param $elements
1281
 *   An associative array containing the structure of the form.
1282
 * @param $form_state
1283
 *   A keyed array containing the current state of the form. The current
1284
 *   user-submitted data is stored in $form_state['values'], though
1285
 *   form validation functions are passed an explicit copy of the
1286
 *   values for the sake of simplicity. Validation handlers can also
1287
 *   $form_state to pass information on to submit handlers. For example:
1288
 *     $form_state['data_for_submission'] = $data;
1289
 *   This technique is useful when validation requires file parsing,
1290
 *   web service requests, or other expensive requests that should
1291
 *   not be repeated in the submission step.
1292
 * @param $form_id
1293
 *   A unique string identifying the form for validation, submission,
1294
 *   theming, and hook_form_alter functions.
1295
 */
1296
function _form_validate(&$elements, &$form_state, $form_id = NULL) {
1297
  // Also used in the installer, pre-database setup.
1298
  $t = get_t();
1299

    
1300
  // Recurse through all children.
1301
  foreach (element_children($elements) as $key) {
1302
    if (isset($elements[$key]) && $elements[$key]) {
1303
      _form_validate($elements[$key], $form_state);
1304
    }
1305
  }
1306

    
1307
  // Validate the current input.
1308
  if (!isset($elements['#validated']) || !$elements['#validated']) {
1309
    // The following errors are always shown.
1310
    if (isset($elements['#needs_validation'])) {
1311
      // Verify that the value is not longer than #maxlength.
1312
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
1313
        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']))));
1314
      }
1315

    
1316
      if (isset($elements['#options']) && isset($elements['#value'])) {
1317
        if ($elements['#type'] == 'select') {
1318
          $options = form_options_flatten($elements['#options']);
1319
        }
1320
        else {
1321
          $options = $elements['#options'];
1322
        }
1323
        if (is_array($elements['#value'])) {
1324
          $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
1325
          foreach ($value as $v) {
1326
            if (!isset($options[$v])) {
1327
              form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
1328
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
1329
            }
1330
          }
1331
        }
1332
        // Non-multiple select fields always have a value in HTML. If the user
1333
        // does not change the form, it will be the value of the first option.
1334
        // Because of this, form validation for the field will almost always
1335
        // pass, even if the user did not select anything. To work around this
1336
        // browser behavior, required select fields without a #default_value get
1337
        // an additional, first empty option. In case the submitted value is
1338
        // identical to the empty option's value, we reset the element's value
1339
        // to NULL to trigger the regular #required handling below.
1340
        // @see form_process_select()
1341
        elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
1342
          $elements['#value'] = NULL;
1343
          form_set_value($elements, NULL, $form_state);
1344
        }
1345
        elseif (!isset($options[$elements['#value']])) {
1346
          form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
1347
          watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
1348
        }
1349
      }
1350
    }
1351

    
1352
    // While this element is being validated, it may be desired that some calls
1353
    // to form_set_error() be suppressed and not result in a form error, so
1354
    // that a button that implements low-risk functionality (such as "Previous"
1355
    // or "Add more") that doesn't require all user input to be valid can still
1356
    // have its submit handlers triggered. The triggering element's
1357
    // #limit_validation_errors property contains the information for which
1358
    // errors are needed, and all other errors are to be suppressed. The
1359
    // #limit_validation_errors property is ignored if submit handlers will run,
1360
    // but the element doesn't have a #submit property, because it's too large a
1361
    // security risk to have any invalid user input when executing form-level
1362
    // submit handlers.
1363
    if (isset($form_state['triggering_element']['#limit_validation_errors']) && ($form_state['triggering_element']['#limit_validation_errors'] !== FALSE) && !($form_state['submitted'] && !isset($form_state['triggering_element']['#submit']))) {
1364
      form_set_error(NULL, '', $form_state['triggering_element']['#limit_validation_errors']);
1365
    }
1366
    // If submit handlers won't run (due to the submission having been triggered
1367
    // by an element whose #executes_submit_callback property isn't TRUE), then
1368
    // it's safe to suppress all validation errors, and we do so by default,
1369
    // which is particularly useful during an Ajax submission triggered by a
1370
    // non-button. An element can override this default by setting the
1371
    // #limit_validation_errors property. For button element types,
1372
    // #limit_validation_errors defaults to FALSE (via system_element_info()),
1373
    // so that full validation is their default behavior.
1374
    elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) {
1375
      form_set_error(NULL, '', array());
1376
    }
1377
    // As an extra security measure, explicitly turn off error suppression if
1378
    // one of the above conditions wasn't met. Since this is also done at the
1379
    // end of this function, doing it here is only to handle the rare edge case
1380
    // where a validate handler invokes form processing of another form.
1381
    else {
1382
      drupal_static_reset('form_set_error:limit_validation_errors');
1383
    }
1384

    
1385
    // Make sure a value is passed when the field is required.
1386
    if (isset($elements['#needs_validation']) && $elements['#required']) {
1387
      // A simple call to empty() will not cut it here as some fields, like
1388
      // checkboxes, can return a valid value of '0'. Instead, check the
1389
      // length if it's a string, and the item count if it's an array.
1390
      // An unchecked checkbox has a #value of integer 0, different than string
1391
      // '0', which could be a valid value.
1392
      $is_empty_multiple = (!count($elements['#value']));
1393
      $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
1394
      $is_empty_value = ($elements['#value'] === 0);
1395
      if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
1396
        // Although discouraged, a #title is not mandatory for form elements. In
1397
        // case there is no #title, we cannot set a form error message.
1398
        // Instead of setting no #title, form constructors are encouraged to set
1399
        // #title_display to 'invisible' to improve accessibility.
1400
        if (isset($elements['#title'])) {
1401
          form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
1402
        }
1403
        else {
1404
          form_error($elements);
1405
        }
1406
      }
1407
    }
1408

    
1409
    // Call user-defined form level validators.
1410
    if (isset($form_id)) {
1411
      form_execute_handlers('validate', $elements, $form_state);
1412
    }
1413
    // Call any element-specific validators. These must act on the element
1414
    // #value data.
1415
    elseif (isset($elements['#element_validate'])) {
1416
      foreach ($elements['#element_validate'] as $function) {
1417
        $function($elements, $form_state, $form_state['complete form']);
1418
      }
1419
    }
1420
    $elements['#validated'] = TRUE;
1421
  }
1422

    
1423
  // Done validating this element, so turn off error suppression.
1424
  // _form_validate() turns it on again when starting on the next element, if
1425
  // it's still appropriate to do so.
1426
  drupal_static_reset('form_set_error:limit_validation_errors');
1427
}
1428

    
1429
/**
1430
 * Executes custom validation and submission handlers for a given form.
1431
 *
1432
 * Button-specific handlers are checked first. If none exist, the function
1433
 * falls back to form-level handlers.
1434
 *
1435
 * @param $type
1436
 *   The type of handler to execute. 'validate' or 'submit' are the
1437
 *   defaults used by Form API.
1438
 * @param $form
1439
 *   An associative array containing the structure of the form.
1440
 * @param $form_state
1441
 *   A keyed array containing the current state of the form. If the user
1442
 *   submitted the form by clicking a button with custom handler functions
1443
 *   defined, those handlers will be stored here.
1444
 */
1445
function form_execute_handlers($type, &$form, &$form_state) {
1446
  $return = FALSE;
1447
  // If there was a button pressed, use its handlers.
1448
  if (isset($form_state[$type . '_handlers'])) {
1449
    $handlers = $form_state[$type . '_handlers'];
1450
  }
1451
  // Otherwise, check for a form-level handler.
1452
  elseif (isset($form['#' . $type])) {
1453
    $handlers = $form['#' . $type];
1454
  }
1455
  else {
1456
    $handlers = array();
1457
  }
1458

    
1459
  foreach ($handlers as $function) {
1460
    // Check if a previous _submit handler has set a batch, but make sure we
1461
    // do not react to a batch that is already being processed (for instance
1462
    // if a batch operation performs a drupal_form_submit()).
1463
    if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['id'])) {
1464
      // Some previous submit handler has set a batch. To ensure correct
1465
      // execution order, store the call in a special 'control' batch set.
1466
      // See _batch_next_set().
1467
      $batch['sets'][] = array('form_submit' => $function);
1468
      $batch['has_form_submits'] = TRUE;
1469
    }
1470
    else {
1471
      $function($form, $form_state);
1472
    }
1473
    $return = TRUE;
1474
  }
1475
  return $return;
1476
}
1477

    
1478
/**
1479
 * Files an error against a form element.
1480
 *
1481
 * When a validation error is detected, the validator calls form_set_error() to
1482
 * indicate which element needs to be changed and provide an error message. This
1483
 * causes the Form API to not execute the form submit handlers, and instead to
1484
 * re-display the form to the user with the corresponding elements rendered with
1485
 * an 'error' CSS class (shown as red by default).
1486
 *
1487
 * The standard form_set_error() behavior can be changed if a button provides
1488
 * the #limit_validation_errors property. Multistep forms not wanting to
1489
 * validate the whole form can set #limit_validation_errors on buttons to
1490
 * limit validation errors to only certain elements. For example, pressing the
1491
 * "Previous" button in a multistep form should not fire validation errors just
1492
 * because the current step has invalid values. If #limit_validation_errors is
1493
 * set on a clicked button, the button must also define a #submit property
1494
 * (may be set to an empty array). Any #submit handlers will be executed even if
1495
 * there is invalid input, so extreme care should be taken with respect to any
1496
 * actions taken by them. This is typically not a problem with buttons like
1497
 * "Previous" or "Add more" that do not invoke persistent storage of the
1498
 * submitted form values. Do not use the #limit_validation_errors property on
1499
 * buttons that trigger saving of form values to the database.
1500
 *
1501
 * The #limit_validation_errors property is a list of "sections" within
1502
 * $form_state['values'] that must contain valid values. Each "section" is an
1503
 * array with the ordered set of keys needed to reach that part of
1504
 * $form_state['values'] (i.e., the #parents property of the element).
1505
 *
1506
 * Example 1: Allow the "Previous" button to function, regardless of whether any
1507
 * user input is valid.
1508
 *
1509
 * @code
1510
 *   $form['actions']['previous'] = array(
1511
 *     '#type' => 'submit',
1512
 *     '#value' => t('Previous'),
1513
 *     '#limit_validation_errors' => array(),       // No validation.
1514
 *     '#submit' => array('some_submit_function'),  // #submit required.
1515
 *   );
1516
 * @endcode
1517
 *
1518
 * Example 2: Require some, but not all, user input to be valid to process the
1519
 * submission of a "Previous" button.
1520
 *
1521
 * @code
1522
 *   $form['actions']['previous'] = array(
1523
 *     '#type' => 'submit',
1524
 *     '#value' => t('Previous'),
1525
 *     '#limit_validation_errors' => array(
1526
 *       array('step1'),       // Validate $form_state['values']['step1'].
1527
 *       array('foo', 'bar'),  // Validate $form_state['values']['foo']['bar'].
1528
 *     ),
1529
 *     '#submit' => array('some_submit_function'), // #submit required.
1530
 *   );
1531
 * @endcode
1532
 *
1533
 * This will require $form_state['values']['step1'] and everything within it
1534
 * (for example, $form_state['values']['step1']['choice']) to be valid, so
1535
 * calls to form_set_error('step1', $message) or
1536
 * form_set_error('step1][choice', $message) will prevent the submit handlers
1537
 * from running, and result in the error message being displayed to the user.
1538
 * However, calls to form_set_error('step2', $message) and
1539
 * form_set_error('step2][groupX][choiceY', $message) will be suppressed,
1540
 * resulting in the message not being displayed to the user, and the submit
1541
 * handlers will run despite $form_state['values']['step2'] and
1542
 * $form_state['values']['step2']['groupX']['choiceY'] containing invalid
1543
 * values. Errors for an invalid $form_state['values']['foo'] will be
1544
 * suppressed, but errors flagging invalid values for
1545
 * $form_state['values']['foo']['bar'] and everything within it will be
1546
 * flagged and submission prevented.
1547
 *
1548
 * Partial form validation is implemented by suppressing errors rather than by
1549
 * skipping the input processing and validation steps entirely, because some
1550
 * forms have button-level submit handlers that call Drupal API functions that
1551
 * assume that certain data exists within $form_state['values'], and while not
1552
 * doing anything with that data that requires it to be valid, PHP errors
1553
 * would be triggered if the input processing and validation steps were fully
1554
 * skipped.
1555
 *
1556
 * @param $name
1557
 *   The name of the form element. If the #parents property of your form
1558
 *   element is array('foo', 'bar', 'baz') then you may set an error on 'foo'
1559
 *   or 'foo][bar][baz'. Setting an error on 'foo' sets an error for every
1560
 *   element where the #parents array starts with 'foo'.
1561
 * @param $message
1562
 *   The error message to present to the user.
1563
 * @param $limit_validation_errors
1564
 *   Internal use only. The #limit_validation_errors property of the clicked
1565
 *   button, if it exists.
1566
 *
1567
 * @return
1568
 *   Return value is for internal use only. To get a list of errors, use
1569
 *   form_get_errors() or form_get_error().
1570
 *
1571
 * @see http://drupal.org/node/370537
1572
 * @see http://drupal.org/node/763376
1573
 */
1574
function form_set_error($name = NULL, $message = '', $limit_validation_errors = NULL) {
1575
  $form = &drupal_static(__FUNCTION__, array());
1576
  $sections = &drupal_static(__FUNCTION__ . ':limit_validation_errors');
1577
  if (isset($limit_validation_errors)) {
1578
    $sections = $limit_validation_errors;
1579
  }
1580

    
1581
  if (isset($name) && !isset($form[$name])) {
1582
    $record = TRUE;
1583
    if (isset($sections)) {
1584
      // #limit_validation_errors is an array of "sections" within which user
1585
      // input must be valid. If the element is within one of these sections,
1586
      // the error must be recorded. Otherwise, it can be suppressed.
1587
      // #limit_validation_errors can be an empty array, in which case all
1588
      // errors are suppressed. For example, a "Previous" button might want its
1589
      // submit action to be triggered even if none of the submitted values are
1590
      // valid.
1591
      $record = FALSE;
1592
      foreach ($sections as $section) {
1593
        // Exploding by '][' reconstructs the element's #parents. If the
1594
        // reconstructed #parents begin with the same keys as the specified
1595
        // section, then the element's values are within the part of
1596
        // $form_state['values'] that the clicked button requires to be valid,
1597
        // so errors for this element must be recorded. As the exploded array
1598
        // will all be strings, we need to cast every value of the section
1599
        // array to string.
1600
        if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
1601
          $record = TRUE;
1602
          break;
1603
        }
1604
      }
1605
    }
1606
    if ($record) {
1607
      $form[$name] = $message;
1608
      if ($message) {
1609
        drupal_set_message($message, 'error');
1610
      }
1611
    }
1612
  }
1613

    
1614
  return $form;
1615
}
1616

    
1617
/**
1618
 * Clears all errors against all form elements made by form_set_error().
1619
 */
1620
function form_clear_error() {
1621
  drupal_static_reset('form_set_error');
1622
}
1623

    
1624
/**
1625
 * Returns an associative array of all errors.
1626
 */
1627
function form_get_errors() {
1628
  $form = form_set_error();
1629
  if (!empty($form)) {
1630
    return $form;
1631
  }
1632
}
1633

    
1634
/**
1635
 * Returns the error message filed against the given form element.
1636
 *
1637
 * Form errors higher up in the form structure override deeper errors as well as
1638
 * errors on the element itself.
1639
 */
1640
function form_get_error($element) {
1641
  $form = form_set_error();
1642
  $parents = array();
1643
  foreach ($element['#parents'] as $parent) {
1644
    $parents[] = $parent;
1645
    $key = implode('][', $parents);
1646
    if (isset($form[$key])) {
1647
      return $form[$key];
1648
    }
1649
  }
1650
}
1651

    
1652
/**
1653
 * Flags an element as having an error.
1654
 */
1655
function form_error(&$element, $message = '') {
1656
  form_set_error(implode('][', $element['#parents']), $message);
1657
}
1658

    
1659
/**
1660
 * Builds and processes all elements in the structured form array.
1661
 *
1662
 * Adds any required properties to each element, maps the incoming input data
1663
 * to the proper elements, and executes any #process handlers attached to a
1664
 * specific element.
1665
 *
1666
 * This is one of the three primary functions that recursively iterates a form
1667
 * array. This one does it for completing the form building process. The other
1668
 * two are _form_validate() (invoked via drupal_validate_form() and used to
1669
 * invoke validation logic for each element) and drupal_render() (for rendering
1670
 * each element). Each of these three pipelines provides ample opportunity for
1671
 * modules to customize what happens. For example, during this function's life
1672
 * cycle, the following functions get called for each element:
1673
 * - $element['#value_callback']: A function that implements how user input is
1674
 *   mapped to an element's #value property. This defaults to a function named
1675
 *   'form_type_TYPE_value' where TYPE is $element['#type'].
1676
 * - $element['#process']: An array of functions called after user input has
1677
 *   been mapped to the element's #value property. These functions can be used
1678
 *   to dynamically add child elements: for example, for the 'date' element
1679
 *   type, one of the functions in this array is form_process_date(), which adds
1680
 *   the individual 'year', 'month', 'day', etc. child elements. These functions
1681
 *   can also be used to set additional properties or implement special logic
1682
 *   other than adding child elements: for example, for the 'fieldset' element
1683
 *   type, one of the functions in this array is form_process_fieldset(), which
1684
 *   adds the attributes and JavaScript needed to make the fieldset collapsible
1685
 *   if the #collapsible property is set. The #process functions are called in
1686
 *   preorder traversal, meaning they are called for the parent element first,
1687
 *   then for the child elements.
1688
 * - $element['#after_build']: An array of functions called after form_builder()
1689
 *   is done with its processing of the element. These are called in postorder
1690
 *   traversal, meaning they are called for the child elements first, then for
1691
 *   the parent element.
1692
 * There are similar properties containing callback functions invoked by
1693
 * _form_validate() and drupal_render(), appropriate for those operations.
1694
 *
1695
 * Developers are strongly encouraged to integrate the functionality needed by
1696
 * their form or module within one of these three pipelines, using the
1697
 * appropriate callback property, rather than implementing their own recursive
1698
 * traversal of a form array. This facilitates proper integration between
1699
 * multiple modules. For example, module developers are familiar with the
1700
 * relative order in which hook_form_alter() implementations and #process
1701
 * functions run. A custom traversal function that affects the building of a
1702
 * form is likely to not integrate with hook_form_alter() and #process in the
1703
 * expected way. Also, deep recursion within PHP is both slow and memory
1704
 * intensive, so it is best to minimize how often it's done.
1705
 *
1706
 * As stated above, each element's #process functions are executed after its
1707
 * #value has been set. This enables those functions to execute conditional
1708
 * logic based on the current value. However, all of form_builder() runs before
1709
 * drupal_validate_form() is called, so during #process function execution, the
1710
 * element's #value has not yet been validated, so any code that requires
1711
 * validated values must reside within a submit handler.
1712
 *
1713
 * As a security measure, user input is used for an element's #value only if the
1714
 * element exists within $form, is not disabled (as per the #disabled property),
1715
 * and can be accessed (as per the #access property, except that forms submitted
1716
 * using drupal_form_submit() bypass #access restrictions). When user input is
1717
 * ignored due to #disabled and #access restrictions, the element's default
1718
 * value is used.
1719
 *
1720
 * Because of the preorder traversal, where #process functions of an element run
1721
 * before user input for its child elements is processed, and because of the
1722
 * Form API security of user input processing with respect to #access and
1723
 * #disabled described above, this generally means that #process functions
1724
 * should not use an element's (unvalidated) #value to affect the #disabled or
1725
 * #access of child elements. Use-cases where a developer may be tempted to
1726
 * implement such conditional logic usually fall into one of two categories:
1727
 * - Where user input from the current submission must affect the structure of a
1728
 *   form, including properties like #access and #disabled that affect how the
1729
 *   next submission needs to be processed, a multi-step workflow is needed.
1730
 *   This is most commonly implemented with a submit handler setting persistent
1731
 *   data within $form_state based on *validated* values in
1732
 *   $form_state['values'] and setting $form_state['rebuild']. The form building
1733
 *   functions must then be implemented to use the $form_state data to rebuild
1734
 *   the form with the structure appropriate for the new state.
1735
 * - Where user input must affect the rendering of the form without affecting
1736
 *   its structure, the necessary conditional rendering logic should reside
1737
 *   within functions that run during the rendering phase (#pre_render, #theme,
1738
 *   #theme_wrappers, and #post_render).
1739
 *
1740
 * @param $form_id
1741
 *   A unique string identifying the form for validation, submission,
1742
 *   theming, and hook_form_alter functions.
1743
 * @param $element
1744
 *   An associative array containing the structure of the current element.
1745
 * @param $form_state
1746
 *   A keyed array containing the current state of the form. In this
1747
 *   context, it is used to accumulate information about which button
1748
 *   was clicked when the form was submitted, as well as the sanitized
1749
 *   $_POST data.
1750
 */
1751
function form_builder($form_id, &$element, &$form_state) {
1752
  // Initialize as unprocessed.
1753
  $element['#processed'] = FALSE;
1754

    
1755
  // Use element defaults.
1756
  if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
1757
    // Overlay $info onto $element, retaining preexisting keys in $element.
1758
    $element += $info;
1759
    $element['#defaults_loaded'] = TRUE;
1760
  }
1761
  // Assign basic defaults common for all form elements.
1762
  $element += array(
1763
    '#required' => FALSE,
1764
    '#attributes' => array(),
1765
    '#title_display' => 'before',
1766
  );
1767

    
1768
  // Special handling if we're on the top level form element.
1769
  if (isset($element['#type']) && $element['#type'] == 'form') {
1770
    if (!empty($element['#https']) && variable_get('https', FALSE) &&
1771
        !url_is_external($element['#action'])) {
1772
      global $base_root;
1773

    
1774
      // Not an external URL so ensure that it is secure.
1775
      $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
1776
    }
1777

    
1778
    // Store a reference to the complete form in $form_state prior to building
1779
    // the form. This allows advanced #process and #after_build callbacks to
1780
    // perform changes elsewhere in the form.
1781
    $form_state['complete form'] = &$element;
1782

    
1783
    // Set a flag if we have a correct form submission. This is always TRUE for
1784
    // programmed forms coming from drupal_form_submit(), or if the form_id coming
1785
    // from the POST data is set and matches the current form_id.
1786
    if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
1787
      $form_state['process_input'] = TRUE;
1788
    }
1789
    else {
1790
      $form_state['process_input'] = FALSE;
1791
    }
1792

    
1793
    // All form elements should have an #array_parents property.
1794
    $element['#array_parents'] = array();
1795
  }
1796

    
1797
  if (!isset($element['#id'])) {
1798
    $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
1799
  }
1800
  // Handle input elements.
1801
  if (!empty($element['#input'])) {
1802
    _form_builder_handle_input_element($form_id, $element, $form_state);
1803
  }
1804
  // Allow for elements to expand to multiple elements, e.g., radios,
1805
  // checkboxes and files.
1806
  if (isset($element['#process']) && !$element['#processed']) {
1807
    foreach ($element['#process'] as $process) {
1808
      $element = $process($element, $form_state, $form_state['complete form']);
1809
    }
1810
    $element['#processed'] = TRUE;
1811
  }
1812

    
1813
  // We start off assuming all form elements are in the correct order.
1814
  $element['#sorted'] = TRUE;
1815

    
1816
  // Recurse through all child elements.
1817
  $count = 0;
1818
  foreach (element_children($element) as $key) {
1819
    // Prior to checking properties of child elements, their default properties
1820
    // need to be loaded.
1821
    if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
1822
      $element[$key] += $info;
1823
      $element[$key]['#defaults_loaded'] = TRUE;
1824
    }
1825

    
1826
    // Don't squash an existing tree value.
1827
    if (!isset($element[$key]['#tree'])) {
1828
      $element[$key]['#tree'] = $element['#tree'];
1829
    }
1830

    
1831
    // Deny access to child elements if parent is denied.
1832
    if (isset($element['#access']) && !$element['#access']) {
1833
      $element[$key]['#access'] = FALSE;
1834
    }
1835

    
1836
    // Make child elements inherit their parent's #disabled and #allow_focus
1837
    // values unless they specify their own.
1838
    foreach (array('#disabled', '#allow_focus') as $property) {
1839
      if (isset($element[$property]) && !isset($element[$key][$property])) {
1840
        $element[$key][$property] = $element[$property];
1841
      }
1842
    }
1843

    
1844
    // Don't squash existing parents value.
1845
    if (!isset($element[$key]['#parents'])) {
1846
      // Check to see if a tree of child elements is present. If so,
1847
      // continue down the tree if required.
1848
      $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], array($key)) : array($key);
1849
    }
1850
    // Ensure #array_parents follows the actual form structure.
1851
    $array_parents = $element['#array_parents'];
1852
    $array_parents[] = $key;
1853
    $element[$key]['#array_parents'] = $array_parents;
1854

    
1855
    // Assign a decimal placeholder weight to preserve original array order.
1856
    if (!isset($element[$key]['#weight'])) {
1857
      $element[$key]['#weight'] = $count/1000;
1858
    }
1859
    else {
1860
      // If one of the child elements has a weight then we will need to sort
1861
      // later.
1862
      unset($element['#sorted']);
1863
    }
1864
    $element[$key] = form_builder($form_id, $element[$key], $form_state);
1865
    $count++;
1866
  }
1867

    
1868
  // The #after_build flag allows any piece of a form to be altered
1869
  // after normal input parsing has been completed.
1870
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
1871
    foreach ($element['#after_build'] as $function) {
1872
      $element = $function($element, $form_state);
1873
    }
1874
    $element['#after_build_done'] = TRUE;
1875
  }
1876

    
1877
  // If there is a file element, we need to flip a flag so later the
1878
  // form encoding can be set.
1879
  if (isset($element['#type']) && $element['#type'] == 'file') {
1880
    $form_state['has_file_element'] = TRUE;
1881
  }
1882

    
1883
  // Final tasks for the form element after form_builder() has run for all other
1884
  // elements.
1885
  if (isset($element['#type']) && $element['#type'] == 'form') {
1886
    // If there is a file element, we set the form encoding.
1887
    if (isset($form_state['has_file_element'])) {
1888
      $element['#attributes']['enctype'] = 'multipart/form-data';
1889
    }
1890

    
1891
    // If a form contains a single textfield, and the ENTER key is pressed
1892
    // within it, Internet Explorer submits the form with no POST data
1893
    // identifying any submit button. Other browsers submit POST data as though
1894
    // the user clicked the first button. Therefore, to be as consistent as we
1895
    // can be across browsers, if no 'triggering_element' has been identified
1896
    // yet, default it to the first button.
1897
    if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
1898
      $form_state['triggering_element'] = $form_state['buttons'][0];
1899
    }
1900

    
1901
    // If the triggering element specifies "button-level" validation and submit
1902
    // handlers to run instead of the default form-level ones, then add those to
1903
    // the form state.
1904
    foreach (array('validate', 'submit') as $type) {
1905
      if (isset($form_state['triggering_element']['#' . $type])) {
1906
        $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
1907
      }
1908
    }
1909

    
1910
    // If the triggering element executes submit handlers, then set the form
1911
    // state key that's needed for those handlers to run.
1912
    if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
1913
      $form_state['submitted'] = TRUE;
1914
    }
1915

    
1916
    // Special processing if the triggering element is a button.
1917
    if (isset($form_state['triggering_element']['#button_type'])) {
1918
      // Because there are several ways in which the triggering element could
1919
      // have been determined (including from input variables set by JavaScript
1920
      // or fallback behavior implemented for IE), and because buttons often
1921
      // have their #name property not derived from their #parents property, we
1922
      // can't assume that input processing that's happened up until here has
1923
      // resulted in $form_state['values'][BUTTON_NAME] being set. But it's
1924
      // common for forms to have several buttons named 'op' and switch on
1925
      // $form_state['values']['op'] during submit handler execution.
1926
      $form_state['values'][$form_state['triggering_element']['#name']] = $form_state['triggering_element']['#value'];
1927

    
1928
      // @todo Legacy support. Remove in Drupal 8.
1929
      $form_state['clicked_button'] = $form_state['triggering_element'];
1930
    }
1931
  }
1932
  return $element;
1933
}
1934

    
1935
/**
1936
 * Adds the #name and #value properties of an input element before rendering.
1937
 */
1938
function _form_builder_handle_input_element($form_id, &$element, &$form_state) {
1939
  if (!isset($element['#name'])) {
1940
    $name = array_shift($element['#parents']);
1941
    $element['#name'] = $name;
1942
    if ($element['#type'] == 'file') {
1943
      // To make it easier to handle $_FILES in file.inc, we place all
1944
      // file fields in the 'files' array. Also, we do not support
1945
      // nested file names.
1946
      $element['#name'] = 'files[' . $element['#name'] . ']';
1947
    }
1948
    elseif (count($element['#parents'])) {
1949
      $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
1950
    }
1951
    array_unshift($element['#parents'], $name);
1952
  }
1953

    
1954
  // Setting #disabled to TRUE results in user input being ignored, regardless
1955
  // of how the element is themed or whether JavaScript is used to change the
1956
  // control's attributes. However, it's good UI to let the user know that input
1957
  // is not wanted for the control. HTML supports two attributes for this:
1958
  // http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form wants
1959
  // to start a control off with one of these attributes for UI purposes only,
1960
  // but still allow input to be processed if it's sumitted, it can set the
1961
  // desired attribute in #attributes directly rather than using #disabled.
1962
  // However, developers should think carefully about the accessibility
1963
  // implications of doing so: if the form expects input to be enterable under
1964
  // some condition triggered by JavaScript, how would someone who has
1965
  // JavaScript disabled trigger that condition? Instead, developers should
1966
  // consider whether a multi-step form would be more appropriate (#disabled can
1967
  // be changed from step to step). If one still decides to use JavaScript to
1968
  // affect when a control is enabled, then it is best for accessibility for the
1969
  // control to be enabled in the HTML, and disabled by JavaScript on document
1970
  // ready.
1971
  if (!empty($element['#disabled'])) {
1972
    if (!empty($element['#allow_focus'])) {
1973
      $element['#attributes']['readonly'] = 'readonly';
1974
    }
1975
    else {
1976
      $element['#attributes']['disabled'] = 'disabled';
1977
    }
1978
  }
1979

    
1980
  // With JavaScript or other easy hacking, input can be submitted even for
1981
  // elements with #access=FALSE or #disabled=TRUE. For security, these must
1982
  // not be processed. Forms that set #disabled=TRUE on an element do not
1983
  // expect input for the element, and even forms submitted with
1984
  // drupal_form_submit() must not be able to get around this. Forms that set
1985
  // #access=FALSE on an element usually allow access for some users, so forms
1986
  // submitted with drupal_form_submit() may bypass access restriction and be
1987
  // treated as high-privilege users instead.
1988
  $process_input = empty($element['#disabled']) && ($form_state['programmed'] || ($form_state['process_input'] && (!isset($element['#access']) || $element['#access'])));
1989

    
1990
  // Set the element's #value property.
1991
  if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
1992
    $value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
1993
    if ($process_input) {
1994
      // Get the input for the current element. NULL values in the input need to
1995
      // be explicitly distinguished from missing input. (see below)
1996
      $input_exists = NULL;
1997
      $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
1998
      // For browser-submitted forms, the submitted values do not contain values
1999
      // for certain elements (empty multiple select, unchecked checkbox).
2000
      // During initial form processing, we add explicit NULL values for such
2001
      // elements in $form_state['input']. When rebuilding the form, we can
2002
      // distinguish elements having NULL input from elements that were not part
2003
      // of the initially submitted form and can therefore use default values
2004
      // for the latter, if required. Programmatically submitted forms can
2005
      // submit explicit NULL values when calling drupal_form_submit(), so we do
2006
      // not modify $form_state['input'] for them.
2007
      if (!$input_exists && !$form_state['rebuild'] && !$form_state['programmed']) {
2008
        // Add the necessary parent keys to $form_state['input'] and sets the
2009
        // element's input value to NULL.
2010
        drupal_array_set_nested_value($form_state['input'], $element['#parents'], NULL);
2011
        $input_exists = TRUE;
2012
      }
2013
      // If we have input for the current element, assign it to the #value
2014
      // property, optionally filtered through $value_callback.
2015
      if ($input_exists) {
2016
        if (function_exists($value_callback)) {
2017
          $element['#value'] = $value_callback($element, $input, $form_state);
2018
        }
2019
        if (!isset($element['#value']) && isset($input)) {
2020
          $element['#value'] = $input;
2021
        }
2022
      }
2023
      // Mark all posted values for validation.
2024
      if (isset($element['#value']) || (!empty($element['#required']))) {
2025
        $element['#needs_validation'] = TRUE;
2026
      }
2027
    }
2028
    // Load defaults.
2029
    if (!isset($element['#value'])) {
2030
      // Call #type_value without a second argument to request default_value handling.
2031
      if (function_exists($value_callback)) {
2032
        $element['#value'] = $value_callback($element, FALSE, $form_state);
2033
      }
2034
      // Final catch. If we haven't set a value yet, use the explicit default value.
2035
      // Avoid image buttons (which come with garbage value), so we only get value
2036
      // for the button actually clicked.
2037
      if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
2038
        $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
2039
      }
2040
    }
2041
  }
2042

    
2043
  // Determine which element (if any) triggered the submission of the form and
2044
  // keep track of all the clickable buttons in the form for
2045
  // form_state_values_clean(). Enforce the same input processing restrictions
2046
  // as above.
2047
  if ($process_input) {
2048
    // Detect if the element triggered the submission via Ajax.
2049
    if (_form_element_triggered_scripted_submission($element, $form_state)) {
2050
      $form_state['triggering_element'] = $element;
2051
    }
2052

    
2053
    // If the form was submitted by the browser rather than via Ajax, then it
2054
    // can only have been triggered by a button, and we need to determine which
2055
    // button within the constraints of how browsers provide this information.
2056
    if (isset($element['#button_type'])) {
2057
      // All buttons in the form need to be tracked for
2058
      // form_state_values_clean() and for the form_builder() code that handles
2059
      // a form submission containing no button information in $_POST.
2060
      $form_state['buttons'][] = $element;
2061
      if (_form_button_was_clicked($element, $form_state)) {
2062
        $form_state['triggering_element'] = $element;
2063
      }
2064
    }
2065
  }
2066

    
2067
  // Set the element's value in $form_state['values'], but only, if its key
2068
  // does not exist yet (a #value_callback may have already populated it).
2069
  if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
2070
    form_set_value($element, $element['#value'], $form_state);
2071
  }
2072
}
2073

    
2074
/**
2075
 * Detects if an element triggered the form submission via Ajax.
2076
 *
2077
 * This detects button or non-button controls that trigger a form submission via
2078
 * Ajax or some other scriptable environment. These environments can set the
2079
 * special input key '_triggering_element_name' to identify the triggering
2080
 * element. If the name alone doesn't identify the element uniquely, the input
2081
 * key '_triggering_element_value' may also be set to require a match on element
2082
 * value. An example where this is needed is if there are several buttons all
2083
 * named 'op', and only differing in their value.
2084
 */
2085
function _form_element_triggered_scripted_submission($element, &$form_state) {
2086
  if (!empty($form_state['input']['_triggering_element_name']) && $element['#name'] == $form_state['input']['_triggering_element_name']) {
2087
    if (empty($form_state['input']['_triggering_element_value']) || $form_state['input']['_triggering_element_value'] == $element['#value']) {
2088
      return TRUE;
2089
    }
2090
  }
2091
  return FALSE;
2092
}
2093

    
2094
/**
2095
 * Determines if a given button triggered the form submission.
2096
 *
2097
 * This detects button controls that trigger a form submission by being clicked
2098
 * and having the click processed by the browser rather than being captured by
2099
 * JavaScript. Essentially, it detects if the button's name and value are part
2100
 * of the POST data, but with extra code to deal with the convoluted way in
2101
 * which browsers submit data for image button clicks.
2102
 *
2103
 * This does not detect button clicks processed by Ajax (that is done in
2104
 * _form_element_triggered_scripted_submission()) and it does not detect form
2105
 * submissions from Internet Explorer in response to an ENTER key pressed in a
2106
 * textfield (form_builder() has extra code for that).
2107
 *
2108
 * Because this function contains only part of the logic needed to determine
2109
 * $form_state['triggering_element'], it should not be called from anywhere
2110
 * other than within the Form API. Form validation and submit handlers needing
2111
 * to know which button was clicked should get that information from
2112
 * $form_state['triggering_element'].
2113
 */
2114
function _form_button_was_clicked($element, &$form_state) {
2115
  // First detect normal 'vanilla' button clicks. Traditionally, all
2116
  // standard buttons on a form share the same name (usually 'op'),
2117
  // and the specific return value is used to determine which was
2118
  // clicked. This ONLY works as long as $form['#name'] puts the
2119
  // value at the top level of the tree of $_POST data.
2120
  if (isset($form_state['input'][$element['#name']]) && $form_state['input'][$element['#name']] == $element['#value']) {
2121
    return TRUE;
2122
  }
2123
  // When image buttons are clicked, browsers do NOT pass the form element
2124
  // value in $_POST. Instead they pass an integer representing the
2125
  // coordinates of the click on the button image. This means that image
2126
  // buttons MUST have unique $form['#name'] values, but the details of
2127
  // their $_POST data should be ignored.
2128
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
2129
    return TRUE;
2130
  }
2131
  return FALSE;
2132
}
2133

    
2134
/**
2135
 * Removes internal Form API elements and buttons from submitted form values.
2136
 *
2137
 * This function can be used when a module wants to store all submitted form
2138
 * values, for example, by serializing them into a single database column. In
2139
 * such cases, all internal Form API values and all form button elements should
2140
 * not be contained, and this function allows to remove them before the module
2141
 * proceeds to storage. Next to button elements, the following internal values
2142
 * are removed:
2143
 * - form_id
2144
 * - form_token
2145
 * - form_build_id
2146
 * - op
2147
 *
2148
 * @param $form_state
2149
 *   A keyed array containing the current state of the form, including
2150
 *   submitted form values; altered by reference.
2151
 */
2152
function form_state_values_clean(&$form_state) {
2153
  // Remove internal Form API values.
2154
  unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);
2155

    
2156
  // Remove button values.
2157
  // form_builder() collects all button elements in a form. We remove the button
2158
  // value separately for each button element.
2159
  foreach ($form_state['buttons'] as $button) {
2160
    // Remove this button's value from the submitted form values by finding
2161
    // the value corresponding to this button.
2162
    // We iterate over the #parents of this button and move a reference to
2163
    // each parent in $form_state['values']. For example, if #parents is:
2164
    //   array('foo', 'bar', 'baz')
2165
    // then the corresponding $form_state['values'] part will look like this:
2166
    // array(
2167
    //   'foo' => array(
2168
    //     'bar' => array(
2169
    //       'baz' => 'button_value',
2170
    //     ),
2171
    //   ),
2172
    // )
2173
    // We start by (re)moving 'baz' to $last_parent, so we are able unset it
2174
    // at the end of the iteration. Initially, $values will contain a
2175
    // reference to $form_state['values'], but in the iteration we move the
2176
    // reference to $form_state['values']['foo'], and finally to
2177
    // $form_state['values']['foo']['bar'], which is the level where we can
2178
    // unset 'baz' (that is stored in $last_parent).
2179
    $parents = $button['#parents'];
2180
    $last_parent = array_pop($parents);
2181
    $key_exists = NULL;
2182
    $values = &drupal_array_get_nested_value($form_state['values'], $parents, $key_exists);
2183
    if ($key_exists && is_array($values)) {
2184
      unset($values[$last_parent]);
2185
    }
2186
  }
2187
}
2188

    
2189
/**
2190
 * Determines the value for an image button form element.
2191
 *
2192
 * @param $form
2193
 *   The form element whose value is being populated.
2194
 * @param $input
2195
 *   The incoming input to populate the form element. If this is FALSE,
2196
 *   the element's default value should be returned.
2197
 * @param $form_state
2198
 *   A keyed array containing the current state of the form.
2199
 *
2200
 * @return
2201
 *   The data that will appear in the $form_state['values'] collection
2202
 *   for this element. Return nothing to use the default.
2203
 */
2204
function form_type_image_button_value($form, $input, $form_state) {
2205
  if ($input !== FALSE) {
2206
    if (!empty($input)) {
2207
      // If we're dealing with Mozilla or Opera, we're lucky. It will
2208
      // return a proper value, and we can get on with things.
2209
      return $form['#return_value'];
2210
    }
2211
    else {
2212
      // Unfortunately, in IE we never get back a proper value for THIS
2213
      // form element. Instead, we get back two split values: one for the
2214
      // X and one for the Y coordinates on which the user clicked the
2215
      // button. We'll find this element in the #post data, and search
2216
      // in the same spot for its name, with '_x'.
2217
      $input = $form_state['input'];
2218
      foreach (explode('[', $form['#name']) as $element_name) {
2219
        // chop off the ] that may exist.
2220
        if (substr($element_name, -1) == ']') {
2221
          $element_name = substr($element_name, 0, -1);
2222
        }
2223

    
2224
        if (!isset($input[$element_name])) {
2225
          if (isset($input[$element_name . '_x'])) {
2226
            return $form['#return_value'];
2227
          }
2228
          return NULL;
2229
        }
2230
        $input = $input[$element_name];
2231
      }
2232
      return $form['#return_value'];
2233
    }
2234
  }
2235
}
2236

    
2237
/**
2238
 * Determines the value for a checkbox form element.
2239
 *
2240
 * @param $form
2241
 *   The form element whose value is being populated.
2242
 * @param $input
2243
 *   The incoming input to populate the form element. If this is FALSE,
2244
 *   the element's default value should be returned.
2245
 *
2246
 * @return
2247
 *   The data that will appear in the $element_state['values'] collection
2248
 *   for this element. Return nothing to use the default.
2249
 */
2250
function form_type_checkbox_value($element, $input = FALSE) {
2251
  if ($input === FALSE) {
2252
    // Use #default_value as the default value of a checkbox, except change
2253
    // NULL to 0, because _form_builder_handle_input_element() would otherwise
2254
    // replace NULL with empty string, but an empty string is a potentially
2255
    // valid value for a checked checkbox.
2256
    return isset($element['#default_value']) ? $element['#default_value'] : 0;
2257
  }
2258
  else {
2259
    // Checked checkboxes are submitted with a value (possibly '0' or ''):
2260
    // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
2261
    // For checked checkboxes, browsers submit the string version of
2262
    // #return_value, but we return the original #return_value. For unchecked
2263
    // checkboxes, browsers submit nothing at all, but
2264
    // _form_builder_handle_input_element() detects this, and calls this
2265
    // function with $input=NULL. Returning NULL from a value callback means to
2266
    // use the default value, which is not what is wanted when an unchecked
2267
    // checkbox is submitted, so we use integer 0 as the value indicating an
2268
    // unchecked checkbox. Therefore, modules must not use integer 0 as a
2269
    // #return_value, as doing so results in the checkbox always being treated
2270
    // as unchecked. The string '0' is allowed for #return_value. The most
2271
    // common use-case for setting #return_value to either 0 or '0' is for the
2272
    // first option within a 0-indexed array of checkboxes, and for this,
2273
    // form_process_checkboxes() uses the string rather than the integer.
2274
    return isset($input) ? $element['#return_value'] : 0;
2275
  }
2276
}
2277

    
2278
/**
2279
 * Determines the value for a checkboxes form element.
2280
 *
2281
 * @param $element
2282
 *   The form element whose value is being populated.
2283
 * @param $input
2284
 *   The incoming input to populate the form element. If this is FALSE,
2285
 *   the element's default value should be returned.
2286
 *
2287
 * @return
2288
 *   The data that will appear in the $element_state['values'] collection
2289
 *   for this element. Return nothing to use the default.
2290
 */
2291
function form_type_checkboxes_value($element, $input = FALSE) {
2292
  if ($input === FALSE) {
2293
    $value = array();
2294
    $element += array('#default_value' => array());
2295
    foreach ($element['#default_value'] as $key) {
2296
      $value[$key] = $key;
2297
    }
2298
    return $value;
2299
  }
2300
  elseif (is_array($input)) {
2301
    // Programmatic form submissions use NULL to indicate that a checkbox
2302
    // should be unchecked; see drupal_form_submit(). We therefore remove all
2303
    // NULL elements from the array before constructing the return value, to
2304
    // simulate the behavior of web browsers (which do not send unchecked
2305
    // checkboxes to the server at all). This will not affect non-programmatic
2306
    // form submissions, since all values in $_POST are strings.
2307
    foreach ($input as $key => $value) {
2308
      if (!isset($value)) {
2309
        unset($input[$key]);
2310
      }
2311
    }
2312
    return drupal_map_assoc($input);
2313
  }
2314
  else {
2315
    return array();
2316
  }
2317
}
2318

    
2319
/**
2320
 * Determines the value for a tableselect form element.
2321
 *
2322
 * @param $element
2323
 *   The form element whose value is being populated.
2324
 * @param $input
2325
 *   The incoming input to populate the form element. If this is FALSE,
2326
 *   the element's default value should be returned.
2327
 *
2328
 * @return
2329
 *   The data that will appear in the $element_state['values'] collection
2330
 *   for this element. Return nothing to use the default.
2331
 */
2332
function form_type_tableselect_value($element, $input = FALSE) {
2333
  // If $element['#multiple'] == FALSE, then radio buttons are displayed and
2334
  // the default value handling is used.
2335
  if (isset($element['#multiple']) && $element['#multiple']) {
2336
    // Checkboxes are being displayed with the default value coming from the
2337
    // keys of the #default_value property. This differs from the checkboxes
2338
    // element which uses the array values.
2339
    if ($input === FALSE) {
2340
      $value = array();
2341
      $element += array('#default_value' => array());
2342
      foreach ($element['#default_value'] as $key => $flag) {
2343
        if ($flag) {
2344
          $value[$key] = $key;
2345
        }
2346
      }
2347
      return $value;
2348
    }
2349
    else {
2350
      return is_array($input) ? drupal_map_assoc($input) : array();
2351
    }
2352
  }
2353
}
2354

    
2355
/**
2356
 * Form value callback: Determines the value for a #type radios form element.
2357
 *
2358
 * @param $element
2359
 *   The form element whose value is being populated.
2360
 * @param $input
2361
 *   (optional) The incoming input to populate the form element. If FALSE, the
2362
 *   element's default value is returned. Defaults to FALSE.
2363
 *
2364
 * @return
2365
 *   The data that will appear in the $element_state['values'] collection for
2366
 *   this element.
2367
 */
2368
function form_type_radios_value(&$element, $input = FALSE) {
2369
  if ($input !== FALSE) {
2370
    // When there's user input (including NULL), return it as the value.
2371
    // However, if NULL is submitted, _form_builder_handle_input_element() will
2372
    // apply the default value, and we want that validated against #options
2373
    // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
2374
    // be used to indicate that no radio button is selected by default.)
2375
    if (!isset($input) && !empty($element['#default_value'])) {
2376
      $element['#needs_validation'] = TRUE;
2377
    }
2378
    return $input;
2379
  }
2380
  else {
2381
    // For default value handling, simply return #default_value. Additionally,
2382
    // for a NULL default value, set #has_garbage_value to prevent
2383
    // _form_builder_handle_input_element() converting the NULL to an empty
2384
    // string, so that code can distinguish between nothing selected and the
2385
    // selection of a radio button whose value is an empty string.
2386
    $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
2387
    if (!isset($value)) {
2388
      $element['#has_garbage_value'] = TRUE;
2389
    }
2390
    return $value;
2391
  }
2392
}
2393

    
2394
/**
2395
 * Determines the value for a password_confirm form element.
2396
 *
2397
 * @param $element
2398
 *   The form element whose value is being populated.
2399
 * @param $input
2400
 *   The incoming input to populate the form element. If this is FALSE,
2401
 *   the element's default value should be returned.
2402
 *
2403
 * @return
2404
 *   The data that will appear in the $element_state['values'] collection
2405
 *   for this element. Return nothing to use the default.
2406
 */
2407
function form_type_password_confirm_value($element, $input = FALSE) {
2408
  if ($input === FALSE) {
2409
    $element += array('#default_value' => array());
2410
    return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
2411
  }
2412
}
2413

    
2414
/**
2415
 * Determines the value for a select form element.
2416
 *
2417
 * @param $element
2418
 *   The form element whose value is being populated.
2419
 * @param $input
2420
 *   The incoming input to populate the form element. If this is FALSE,
2421
 *   the element's default value should be returned.
2422
 *
2423
 * @return
2424
 *   The data that will appear in the $element_state['values'] collection
2425
 *   for this element. Return nothing to use the default.
2426
 */
2427
function form_type_select_value($element, $input = FALSE) {
2428
  if ($input !== FALSE) {
2429
    if (isset($element['#multiple']) && $element['#multiple']) {
2430
      // If an enabled multi-select submits NULL, it means all items are
2431
      // unselected. A disabled multi-select always submits NULL, and the
2432
      // default value should be used.
2433
      if (empty($element['#disabled'])) {
2434
        return (is_array($input)) ? drupal_map_assoc($input) : array();
2435
      }
2436
      else {
2437
        return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
2438
      }
2439
    }
2440
    // Non-multiple select elements may have an empty option preprended to them
2441
    // (see form_process_select()). When this occurs, usually #empty_value is
2442
    // an empty string, but some forms set #empty_value to integer 0 or some
2443
    // other non-string constant. PHP receives all submitted form input as
2444
    // strings, but if the empty option is selected, set the value to match the
2445
    // empty value exactly.
2446
    elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
2447
      return $element['#empty_value'];
2448
    }
2449
    else {
2450
      return $input;
2451
    }
2452
  }
2453
}
2454

    
2455
/**
2456
 * Determines the value for a textfield form element.
2457
 *
2458
 * @param $element
2459
 *   The form element whose value is being populated.
2460
 * @param $input
2461
 *   The incoming input to populate the form element. If this is FALSE,
2462
 *   the element's default value should be returned.
2463
 *
2464
 * @return
2465
 *   The data that will appear in the $element_state['values'] collection
2466
 *   for this element. Return nothing to use the default.
2467
 */
2468
function form_type_textfield_value($element, $input = FALSE) {
2469
  if ($input !== FALSE && $input !== NULL) {
2470
    // Equate $input to the form value to ensure it's marked for
2471
    // validation.
2472
    return str_replace(array("\r", "\n"), '', $input);
2473
  }
2474
}
2475

    
2476
/**
2477
 * Determines the value for form's token value.
2478
 *
2479
 * @param $element
2480
 *   The form element whose value is being populated.
2481
 * @param $input
2482
 *   The incoming input to populate the form element. If this is FALSE,
2483
 *   the element's default value should be returned.
2484
 *
2485
 * @return
2486
 *   The data that will appear in the $element_state['values'] collection
2487
 *   for this element. Return nothing to use the default.
2488
 */
2489
function form_type_token_value($element, $input = FALSE) {
2490
  if ($input !== FALSE) {
2491
    return (string) $input;
2492
  }
2493
}
2494

    
2495
/**
2496
 * Changes submitted form values during form validation.
2497
 *
2498
 * Use this function to change the submitted value of a form element in a form
2499
 * validation function, so that the changed value persists in $form_state
2500
 * through the remaining validation and submission handlers. It does not change
2501
 * the value in $element['#value'], only in $form_state['values'], which is
2502
 * where submitted values are always stored.
2503
 *
2504
 * Note that form validation functions are specified in the '#validate'
2505
 * component of the form array (the value of $form['#validate'] is an array of
2506
 * validation function names). If the form does not originate in your module,
2507
 * you can implement hook_form_FORM_ID_alter() to add a validation function
2508
 * to $form['#validate'].
2509
 *
2510
 * @param $element
2511
 *   The form element that should have its value updated; in most cases you can
2512
 *   just pass in the element from the $form array, although the only component
2513
 *   that is actually used is '#parents'. If constructing yourself, set
2514
 *   $element['#parents'] to be an array giving the path through the form
2515
 *   array's keys to the element whose value you want to update. For instance,
2516
 *   if you want to update the value of $form['elem1']['elem2'], which should be
2517
 *   stored in $form_state['values']['elem1']['elem2'], you would set
2518
 *   $element['#parents'] = array('elem1','elem2').
2519
 * @param $value
2520
 *   The new value for the form element.
2521
 * @param $form_state
2522
 *   Form state array where the value change should be recorded.
2523
 */
2524
function form_set_value($element, $value, &$form_state) {
2525
  drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
2526
}
2527

    
2528
/**
2529
 * Allows PHP array processing of multiple select options with the same value.
2530
 *
2531
 * Used for form select elements which need to validate HTML option groups
2532
 * and multiple options which may return the same value. Associative PHP arrays
2533
 * cannot handle these structures, since they share a common key.
2534
 *
2535
 * @param $array
2536
 *   The form options array to process.
2537
 *
2538
 * @return
2539
 *   An array with all hierarchical elements flattened to a single array.
2540
 */
2541
function form_options_flatten($array) {
2542
  // Always reset static var when first entering the recursion.
2543
  drupal_static_reset('_form_options_flatten');
2544
  return _form_options_flatten($array);
2545
}
2546

    
2547
/**
2548
 * Iterates over an array and returns a flat array with duplicate keys removed.
2549
 *
2550
 * This function also handles cases where objects are passed as array values.
2551
 */
2552
function _form_options_flatten($array) {
2553
  $return = &drupal_static(__FUNCTION__);
2554

    
2555
  foreach ($array as $key => $value) {
2556
    if (is_object($value)) {
2557
      _form_options_flatten($value->option);
2558
    }
2559
    elseif (is_array($value)) {
2560
      _form_options_flatten($value);
2561
    }
2562
    else {
2563
      $return[$key] = 1;
2564
    }
2565
  }
2566

    
2567
  return $return;
2568
}
2569

    
2570
/**
2571
 * Processes a select list form element.
2572
 *
2573
 * This process callback is mandatory for select fields, since all user agents
2574
 * automatically preselect the first available option of single (non-multiple)
2575
 * select lists.
2576
 *
2577
 * @param $element
2578
 *   The form element to process. Properties used:
2579
 *   - #multiple: (optional) Indicates whether one or more options can be
2580
 *     selected. Defaults to FALSE.
2581
 *   - #default_value: Must be NULL or not set in case there is no value for the
2582
 *     element yet, in which case a first default option is inserted by default.
2583
 *     Whether this first option is a valid option depends on whether the field
2584
 *     is #required or not.
2585
 *   - #required: (optional) Whether the user needs to select an option (TRUE)
2586
 *     or not (FALSE). Defaults to FALSE.
2587
 *   - #empty_option: (optional) The label to show for the first default option.
2588
 *     By default, the label is automatically set to "- Please select -" for a
2589
 *     required field and "- None -" for an optional field.
2590
 *   - #empty_value: (optional) The value for the first default option, which is
2591
 *     used to determine whether the user submitted a value or not.
2592
 *     - If #required is TRUE, this defaults to '' (an empty string).
2593
 *     - If #required is not TRUE and this value isn't set, then no extra option
2594
 *       is added to the select control, leaving the control in a slightly
2595
 *       illogical state, because there's no way for the user to select nothing,
2596
 *       since all user agents automatically preselect the first available
2597
 *       option. But people are used to this being the behavior of select
2598
 *       controls.
2599
 *       @todo Address the above issue in Drupal 8.
2600
 *     - If #required is not TRUE and this value is set (most commonly to an
2601
 *       empty string), then an extra option (see #empty_option above)
2602
 *       representing a "non-selection" is added with this as its value.
2603
 *
2604
 * @see _form_validate()
2605
 */
2606
function form_process_select($element) {
2607
  // #multiple select fields need a special #name.
2608
  if ($element['#multiple']) {
2609
    $element['#attributes']['multiple'] = 'multiple';
2610
    $element['#attributes']['name'] = $element['#name'] . '[]';
2611
  }
2612
  // A non-#multiple select needs special handling to prevent user agents from
2613
  // preselecting the first option without intention. #multiple select lists do
2614
  // not get an empty option, as it would not make sense, user interface-wise.
2615
  else {
2616
    $required = $element['#required'];
2617
    // If the element is required and there is no #default_value, then add an
2618
    // empty option that will fail validation, so that the user is required to
2619
    // make a choice. Also, if there's a value for #empty_value or
2620
    // #empty_option, then add an option that represents emptiness.
2621
    if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
2622
      $element += array(
2623
        '#empty_value' => '',
2624
        '#empty_option' => $required ? t('- Select -') : t('- None -'),
2625
      );
2626
      // The empty option is prepended to #options and purposively not merged
2627
      // to prevent another option in #options mistakenly using the same value
2628
      // as #empty_value.
2629
      $empty_option = array($element['#empty_value'] => $element['#empty_option']);
2630
      $element['#options'] = $empty_option + $element['#options'];
2631
    }
2632
  }
2633
  return $element;
2634
}
2635

    
2636
/**
2637
 * Returns HTML for a select form element.
2638
 *
2639
 * It is possible to group options together; to do this, change the format of
2640
 * $options to an associative array in which the keys are group labels, and the
2641
 * values are associative arrays in the normal $options format.
2642
 *
2643
 * @param $variables
2644
 *   An associative array containing:
2645
 *   - element: An associative array containing the properties of the element.
2646
 *     Properties used: #title, #value, #options, #description, #extra,
2647
 *     #multiple, #required, #name, #attributes, #size.
2648
 *
2649
 * @ingroup themeable
2650
 */
2651
function theme_select($variables) {
2652
  $element = $variables['element'];
2653
  element_set_attributes($element, array('id', 'name', 'size'));
2654
  _form_set_class($element, array('form-select'));
2655

    
2656
  return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
2657
}
2658

    
2659
/**
2660
 * Converts a select form element's options array into HTML.
2661
 *
2662
 * @param $element
2663
 *   An associative array containing the properties of the element.
2664
 * @param $choices
2665
 *   Mixed: Either an associative array of items to list as choices, or an
2666
 *   object with an 'option' member that is an associative array. This
2667
 *   parameter is only used internally and should not be passed.
2668
 *
2669
 * @return
2670
 *   An HTML string of options for the select form element.
2671
 */
2672
function form_select_options($element, $choices = NULL) {
2673
  if (!isset($choices)) {
2674
    $choices = $element['#options'];
2675
  }
2676
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
2677
  // isset() fails in this situation.
2678
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
2679
  $value_is_array = $value_valid && is_array($element['#value']);
2680
  $options = '';
2681
  foreach ($choices as $key => $choice) {
2682
    if (is_array($choice)) {
2683
      $options .= '<optgroup label="' . $key . '">';
2684
      $options .= form_select_options($element, $choice);
2685
      $options .= '</optgroup>';
2686
    }
2687
    elseif (is_object($choice)) {
2688
      $options .= form_select_options($element, $choice->option);
2689
    }
2690
    else {
2691
      $key = (string) $key;
2692
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
2693
        $selected = ' selected="selected"';
2694
      }
2695
      else {
2696
        $selected = '';
2697
      }
2698
      $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
2699
    }
2700
  }
2701
  return $options;
2702
}
2703

    
2704
/**
2705
 * Returns the indexes of a select element's options matching a given key.
2706
 *
2707
 * This function is useful if you need to modify the options that are
2708
 * already in a form element; for example, to remove choices which are
2709
 * not valid because of additional filters imposed by another module.
2710
 * One example might be altering the choices in a taxonomy selector.
2711
 * To correctly handle the case of a multiple hierarchy taxonomy,
2712
 * #options arrays can now hold an array of objects, instead of a
2713
 * direct mapping of keys to labels, so that multiple choices in the
2714
 * selector can have the same key (and label). This makes it difficult
2715
 * to manipulate directly, which is why this helper function exists.
2716
 *
2717
 * This function does not support optgroups (when the elements of the
2718
 * #options array are themselves arrays), and will return FALSE if
2719
 * arrays are found. The caller must either flatten/restore or
2720
 * manually do their manipulations in this case, since returning the
2721
 * index is not sufficient, and supporting this would make the
2722
 * "helper" too complicated and cumbersome to be of any help.
2723
 *
2724
 * As usual with functions that can return array() or FALSE, do not
2725
 * forget to use === and !== if needed.
2726
 *
2727
 * @param $element
2728
 *   The select element to search.
2729
 * @param $key
2730
 *   The key to look for.
2731
 *
2732
 * @return
2733
 *   An array of indexes that match the given $key. Array will be
2734
 *   empty if no elements were found. FALSE if optgroups were found.
2735
 */
2736
function form_get_options($element, $key) {
2737
  $keys = array();
2738
  foreach ($element['#options'] as $index => $choice) {
2739
    if (is_array($choice)) {
2740
      return FALSE;
2741
    }
2742
    elseif (is_object($choice)) {
2743
      if (isset($choice->option[$key])) {
2744
        $keys[] = $index;
2745
      }
2746
    }
2747
    elseif ($index == $key) {
2748
      $keys[] = $index;
2749
    }
2750
  }
2751
  return $keys;
2752
}
2753

    
2754
/**
2755
 * Returns HTML for a fieldset form element and its children.
2756
 *
2757
 * @param $variables
2758
 *   An associative array containing:
2759
 *   - element: An associative array containing the properties of the element.
2760
 *     Properties used: #attributes, #children, #collapsed, #collapsible,
2761
 *     #description, #id, #title, #value.
2762
 *
2763
 * @ingroup themeable
2764
 */
2765
function theme_fieldset($variables) {
2766
  $element = $variables['element'];
2767
  element_set_attributes($element, array('id'));
2768
  _form_set_class($element, array('form-wrapper'));
2769

    
2770
  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
2771
  if (!empty($element['#title'])) {
2772
    // Always wrap fieldset legends in a SPAN for CSS positioning.
2773
    $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
2774
  }
2775
  $output .= '<div class="fieldset-wrapper">';
2776
  if (!empty($element['#description'])) {
2777
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
2778
  }
2779
  $output .= $element['#children'];
2780
  if (isset($element['#value'])) {
2781
    $output .= $element['#value'];
2782
  }
2783
  $output .= '</div>';
2784
  $output .= "</fieldset>\n";
2785
  return $output;
2786
}
2787

    
2788
/**
2789
 * Returns HTML for a radio button form element.
2790
 *
2791
 * Note: The input "name" attribute needs to be sanitized before output, which
2792
 *       is currently done by passing all attributes to drupal_attributes().
2793
 *
2794
 * @param $variables
2795
 *   An associative array containing:
2796
 *   - element: An associative array containing the properties of the element.
2797
 *     Properties used: #required, #return_value, #value, #attributes, #title,
2798
 *     #description
2799
 *
2800
 * @ingroup themeable
2801
 */
2802
function theme_radio($variables) {
2803
  $element = $variables['element'];
2804
  $element['#attributes']['type'] = 'radio';
2805
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
2806

    
2807
  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
2808
    $element['#attributes']['checked'] = 'checked';
2809
  }
2810
  _form_set_class($element, array('form-radio'));
2811

    
2812
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
2813
}
2814

    
2815
/**
2816
 * Returns HTML for a set of radio button form elements.
2817
 *
2818
 * @param $variables
2819
 *   An associative array containing:
2820
 *   - element: An associative array containing the properties of the element.
2821
 *     Properties used: #title, #value, #options, #description, #required,
2822
 *     #attributes, #children.
2823
 *
2824
 * @ingroup themeable
2825
 */
2826
function theme_radios($variables) {
2827
  $element = $variables['element'];
2828
  $attributes = array();
2829
  if (isset($element['#id'])) {
2830
    $attributes['id'] = $element['#id'];
2831
  }
2832
  $attributes['class'] = 'form-radios';
2833
  if (!empty($element['#attributes']['class'])) {
2834
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
2835
  }
2836
  if (isset($element['#attributes']['title'])) {
2837
    $attributes['title'] = $element['#attributes']['title'];
2838
  }
2839
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
2840
}
2841

    
2842
/**
2843
 * Expand a password_confirm field into two text boxes.
2844
 */
2845
function form_process_password_confirm($element) {
2846
  $element['pass1'] =  array(
2847
    '#type' => 'password',
2848
    '#title' => t('Password'),
2849
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
2850
    '#required' => $element['#required'],
2851
    '#attributes' => array('class' => array('password-field')),
2852
  );
2853
  $element['pass2'] =  array(
2854
    '#type' => 'password',
2855
    '#title' => t('Confirm password'),
2856
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
2857
    '#required' => $element['#required'],
2858
    '#attributes' => array('class' => array('password-confirm')),
2859
  );
2860
  $element['#element_validate'] = array('password_confirm_validate');
2861
  $element['#tree'] = TRUE;
2862

    
2863
  if (isset($element['#size'])) {
2864
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
2865
  }
2866

    
2867
  return $element;
2868
}
2869

    
2870
/**
2871
 * Validates a password_confirm element.
2872
 */
2873
function password_confirm_validate($element, &$element_state) {
2874
  $pass1 = trim($element['pass1']['#value']);
2875
  $pass2 = trim($element['pass2']['#value']);
2876
  if (!empty($pass1) || !empty($pass2)) {
2877
    if (strcmp($pass1, $pass2)) {
2878
      form_error($element, t('The specified passwords do not match.'));
2879
    }
2880
  }
2881
  elseif ($element['#required'] && !empty($element_state['input'])) {
2882
    form_error($element, t('Password field is required.'));
2883
  }
2884

    
2885
  // Password field must be converted from a two-element array into a single
2886
  // string regardless of validation results.
2887
  form_set_value($element['pass1'], NULL, $element_state);
2888
  form_set_value($element['pass2'], NULL, $element_state);
2889
  form_set_value($element, $pass1, $element_state);
2890

    
2891
  return $element;
2892

    
2893
}
2894

    
2895
/**
2896
 * Returns HTML for a date selection form element.
2897
 *
2898
 * @param $variables
2899
 *   An associative array containing:
2900
 *   - element: An associative array containing the properties of the element.
2901
 *     Properties used: #title, #value, #options, #description, #required,
2902
 *     #attributes.
2903
 *
2904
 * @ingroup themeable
2905
 */
2906
function theme_date($variables) {
2907
  $element = $variables['element'];
2908

    
2909
  $attributes = array();
2910
  if (isset($element['#id'])) {
2911
    $attributes['id'] = $element['#id'];
2912
  }
2913
  if (!empty($element['#attributes']['class'])) {
2914
    $attributes['class'] = (array) $element['#attributes']['class'];
2915
  }
2916
  $attributes['class'][] = 'container-inline';
2917

    
2918
  return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
2919
}
2920

    
2921
/**
2922
 * Expands a date element into year, month, and day select elements.
2923
 */
2924
function form_process_date($element) {
2925
  // Default to current date
2926
  if (empty($element['#value'])) {
2927
    $element['#value'] = array(
2928
      'day' => format_date(REQUEST_TIME, 'custom', 'j'),
2929
      'month' => format_date(REQUEST_TIME, 'custom', 'n'),
2930
      'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
2931
    );
2932
  }
2933

    
2934
  $element['#tree'] = TRUE;
2935

    
2936
  // Determine the order of day, month, year in the site's chosen date format.
2937
  $format = variable_get('date_format_short', 'm/d/Y - H:i');
2938
  $sort = array();
2939
  $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
2940
  $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
2941
  $sort['year'] = strpos($format, 'Y');
2942
  asort($sort);
2943
  $order = array_keys($sort);
2944

    
2945
  // Output multi-selector for date.
2946
  foreach ($order as $type) {
2947
    switch ($type) {
2948
      case 'day':
2949
        $options = drupal_map_assoc(range(1, 31));
2950
        $title = t('Day');
2951
        break;
2952

    
2953
      case 'month':
2954
        $options = drupal_map_assoc(range(1, 12), 'map_month');
2955
        $title = t('Month');
2956
        break;
2957

    
2958
      case 'year':
2959
        $options = drupal_map_assoc(range(1900, 2050));
2960
        $title = t('Year');
2961
        break;
2962
    }
2963

    
2964
    $element[$type] = array(
2965
      '#type' => 'select',
2966
      '#title' => $title,
2967
      '#title_display' => 'invisible',
2968
      '#value' => $element['#value'][$type],
2969
      '#attributes' => $element['#attributes'],
2970
      '#options' => $options,
2971
    );
2972
  }
2973

    
2974
  return $element;
2975
}
2976

    
2977
/**
2978
 * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
2979
 */
2980
function date_validate($element) {
2981
  if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
2982
    form_error($element, t('The specified date is invalid.'));
2983
  }
2984
}
2985

    
2986
/**
2987
 * Helper function for usage with drupal_map_assoc to display month names.
2988
 */
2989
function map_month($month) {
2990
  $months = &drupal_static(__FUNCTION__, array(
2991
    1 => 'Jan',
2992
    2 => 'Feb',
2993
    3 => 'Mar',
2994
    4 => 'Apr',
2995
    5 => 'May',
2996
    6 => 'Jun',
2997
    7 => 'Jul',
2998
    8 => 'Aug',
2999
    9 => 'Sep',
3000
    10 => 'Oct',
3001
    11 => 'Nov',
3002
    12 => 'Dec',
3003
  ));
3004
  return t($months[$month]);
3005
}
3006

    
3007
/**
3008
 * Sets the value for a weight element, with zero as a default.
3009
 */
3010
function weight_value(&$form) {
3011
  if (isset($form['#default_value'])) {
3012
    $form['#value'] = $form['#default_value'];
3013
  }
3014
  else {
3015
    $form['#value'] = 0;
3016
  }
3017
}
3018

    
3019
/**
3020
 * Expands a radios element into individual radio elements.
3021
 */
3022
function form_process_radios($element) {
3023
  if (count($element['#options']) > 0) {
3024
    $weight = 0;
3025
    foreach ($element['#options'] as $key => $choice) {
3026
      // Maintain order of options as defined in #options, in case the element
3027
      // defines custom option sub-elements, but does not define all option
3028
      // sub-elements.
3029
      $weight += 0.001;
3030

    
3031
      $element += array($key => array());
3032
      // Generate the parents as the autogenerator does, so we will have a
3033
      // unique id for each radio button.
3034
      $parents_for_id = array_merge($element['#parents'], array($key));
3035
      $element[$key] += array(
3036
        '#type' => 'radio',
3037
        '#title' => $choice,
3038
        // The key is sanitized in drupal_attributes() during output from the
3039
        // theme function.
3040
        '#return_value' => $key,
3041
        // Use default or FALSE. A value of FALSE means that the radio button is
3042
        // not 'checked'.
3043
        '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
3044
        '#attributes' => $element['#attributes'],
3045
        '#parents' => $element['#parents'],
3046
        '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
3047
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3048
        '#weight' => $weight,
3049
      );
3050
    }
3051
  }
3052
  return $element;
3053
}
3054

    
3055
/**
3056
 * Returns HTML for a checkbox form element.
3057
 *
3058
 * @param $variables
3059
 *   An associative array containing:
3060
 *   - element: An associative array containing the properties of the element.
3061
 *     Properties used: #title, #value, #return_value, #description, #required,
3062
 *     #attributes, #checked.
3063
 *
3064
 * @ingroup themeable
3065
 */
3066
function theme_checkbox($variables) {
3067
  $element = $variables['element'];
3068
  $element['#attributes']['type'] = 'checkbox';
3069
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
3070

    
3071
  // Unchecked checkbox has #value of integer 0.
3072
  if (!empty($element['#checked'])) {
3073
    $element['#attributes']['checked'] = 'checked';
3074
  }
3075
  _form_set_class($element, array('form-checkbox'));
3076

    
3077
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3078
}
3079

    
3080
/**
3081
 * Returns HTML for a set of checkbox form elements.
3082
 *
3083
 * @param $variables
3084
 *   An associative array containing:
3085
 *   - element: An associative array containing the properties of the element.
3086
 *     Properties used: #children, #attributes.
3087
 *
3088
 * @ingroup themeable
3089
 */
3090
function theme_checkboxes($variables) {
3091
  $element = $variables['element'];
3092
  $attributes = array();
3093
  if (isset($element['#id'])) {
3094
    $attributes['id'] = $element['#id'];
3095
  }
3096
  $attributes['class'][] = 'form-checkboxes';
3097
  if (!empty($element['#attributes']['class'])) {
3098
    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
3099
  }
3100
  if (isset($element['#attributes']['title'])) {
3101
    $attributes['title'] = $element['#attributes']['title'];
3102
  }
3103
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
3104
}
3105

    
3106
/**
3107
 * Adds form element theming to an element if its title or description is set.
3108
 *
3109
 * This is used as a pre render function for checkboxes and radios.
3110
 */
3111
function form_pre_render_conditional_form_element($element) {
3112
  $t = get_t();
3113
  // Set the element's title attribute to show #title as a tooltip, if needed.
3114
  if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
3115
    $element['#attributes']['title'] = $element['#title'];
3116
    if (!empty($element['#required'])) {
3117
      // Append an indication that this field is required.
3118
      $element['#attributes']['title'] .= ' (' . $t('Required') . ')';
3119
    }
3120
  }
3121

    
3122
  if (isset($element['#title']) || isset($element['#description'])) {
3123
    $element['#theme_wrappers'][] = 'form_element';
3124
  }
3125
  return $element;
3126
}
3127

    
3128
/**
3129
 * Sets the #checked property of a checkbox element.
3130
 */
3131
function form_process_checkbox($element, $form_state) {
3132
  $value = $element['#value'];
3133
  $return_value = $element['#return_value'];
3134
  // On form submission, the #value of an available and enabled checked
3135
  // checkbox is #return_value, and the #value of an available and enabled
3136
  // unchecked checkbox is integer 0. On not submitted forms, and for
3137
  // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
3138
  // #default_value (integer 0 if #default_value is NULL). Most of the time,
3139
  // a string comparison of #value and #return_value is sufficient for
3140
  // determining the "checked" state, but a value of TRUE always means checked
3141
  // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
3142
  // means unchecked (even if #return_value is '' or '0').
3143
  if ($value === TRUE || $value === FALSE || $value === 0) {
3144
    $element['#checked'] = (bool) $value;
3145
  }
3146
  else {
3147
    // Compare as strings, so that 15 is not considered equal to '15foo', but 1
3148
    // is considered equal to '1'. This cast does not imply that either #value
3149
    // or #return_value is expected to be a string.
3150
    $element['#checked'] = ((string) $value === (string) $return_value);
3151
  }
3152
  return $element;
3153
}
3154

    
3155
/**
3156
 * Processes a checkboxes form element.
3157
 */
3158
function form_process_checkboxes($element) {
3159
  $value = is_array($element['#value']) ? $element['#value'] : array();
3160
  $element['#tree'] = TRUE;
3161
  if (count($element['#options']) > 0) {
3162
    if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
3163
      $element['#default_value'] = array();
3164
    }
3165
    $weight = 0;
3166
    foreach ($element['#options'] as $key => $choice) {
3167
      // Integer 0 is not a valid #return_value, so use '0' instead.
3168
      // @see form_type_checkbox_value().
3169
      // @todo For Drupal 8, cast all integer keys to strings for consistency
3170
      //   with form_process_radios().
3171
      if ($key === 0) {
3172
        $key = '0';
3173
      }
3174
      // Maintain order of options as defined in #options, in case the element
3175
      // defines custom option sub-elements, but does not define all option
3176
      // sub-elements.
3177
      $weight += 0.001;
3178

    
3179
      $element += array($key => array());
3180
      $element[$key] += array(
3181
        '#type' => 'checkbox',
3182
        '#title' => $choice,
3183
        '#return_value' => $key,
3184
        '#default_value' => isset($value[$key]) ? $key : NULL,
3185
        '#attributes' => $element['#attributes'],
3186
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3187
        '#weight' => $weight,
3188
      );
3189
    }
3190
  }
3191
  return $element;
3192
}
3193

    
3194
/**
3195
 * Processes a form actions container element.
3196
 *
3197
 * @param $element
3198
 *   An associative array containing the properties and children of the
3199
 *   form actions container.
3200
 * @param $form_state
3201
 *   The $form_state array for the form this element belongs to.
3202
 *
3203
 * @return
3204
 *   The processed element.
3205
 */
3206
function form_process_actions($element, &$form_state) {
3207
  $element['#attributes']['class'][] = 'form-actions';
3208
  return $element;
3209
}
3210

    
3211
/**
3212
 * Processes a container element.
3213
 *
3214
 * @param $element
3215
 *   An associative array containing the properties and children of the
3216
 *   container.
3217
 * @param $form_state
3218
 *   The $form_state array for the form this element belongs to.
3219
 *
3220
 * @return
3221
 *   The processed element.
3222
 */
3223
function form_process_container($element, &$form_state) {
3224
  // Generate the ID of the element if it's not explicitly given.
3225
  if (!isset($element['#id'])) {
3226
    $element['#id'] = drupal_html_id(implode('-', $element['#parents']) . '-wrapper');
3227
  }
3228
  return $element;
3229
}
3230

    
3231
/**
3232
 * Returns HTML to wrap child elements in a container.
3233
 *
3234
 * Used for grouped form items. Can also be used as a #theme_wrapper for any
3235
 * renderable element, to surround it with a <div> and add attributes such as
3236
 * classes or an HTML id.
3237
 *
3238
 * @param $variables
3239
 *   An associative array containing:
3240
 *   - element: An associative array containing the properties of the element.
3241
 *     Properties used: #id, #attributes, #children.
3242
 *
3243
 * @ingroup themeable
3244
 */
3245
function theme_container($variables) {
3246
  $element = $variables['element'];
3247

    
3248
  // Special handling for form elements.
3249
  if (isset($element['#array_parents'])) {
3250
    // Assign an html ID.
3251
    if (!isset($element['#attributes']['id'])) {
3252
      $element['#attributes']['id'] = $element['#id'];
3253
    }
3254
    // Add the 'form-wrapper' class.
3255
    $element['#attributes']['class'][] = 'form-wrapper';
3256
  }
3257

    
3258
  return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
3259
}
3260

    
3261
/**
3262
 * Returns HTML for a table with radio buttons or checkboxes.
3263
 *
3264
 * @param $variables
3265
 *   An associative array containing:
3266
 *   - element: An associative array containing the properties and children of
3267
 *     the tableselect element. Properties used: #header, #options, #empty,
3268
 *     and #js_select. The #options property is an array of selection options;
3269
 *     each array element of #options is an array of properties. These
3270
 *     properties can include #attributes, which is added to the
3271
 *     table row's HTML attributes; see theme_table(). An example of per-row
3272
 *     options:
3273
 *     @code
3274
 *     $options = array(
3275
 *       array(
3276
 *         'title' => 'How to Learn Drupal',
3277
 *         'content_type' => 'Article',
3278
 *         'status' => 'published',
3279
 *         '#attributes' => array('class' => array('article-row')),
3280
 *       ),
3281
 *       array(
3282
 *         'title' => 'Privacy Policy',
3283
 *         'content_type' => 'Page',
3284
 *         'status' => 'published',
3285
 *         '#attributes' => array('class' => array('page-row')),
3286
 *       ),
3287
 *     );
3288
 *     $header = array(
3289
 *       'title' => t('Title'),
3290
 *       'content_type' => t('Content type'),
3291
 *       'status' => t('Status'),
3292
 *     );
3293
 *     $form['table'] = array(
3294
 *       '#type' => 'tableselect',
3295
 *       '#header' => $header,
3296
 *       '#options' => $options,
3297
 *       '#empty' => t('No content available.'),
3298
 *     );
3299
 *     @endcode
3300
 *
3301
 * @ingroup themeable
3302
 */
3303
function theme_tableselect($variables) {
3304
  $element = $variables['element'];
3305
  $rows = array();
3306
  $header = $element['#header'];
3307
  if (!empty($element['#options'])) {
3308
    // Generate a table row for each selectable item in #options.
3309
    foreach (element_children($element) as $key) {
3310
      $row = array();
3311

    
3312
      $row['data'] = array();
3313
      if (isset($element['#options'][$key]['#attributes'])) {
3314
        $row += $element['#options'][$key]['#attributes'];
3315
      }
3316
      // Render the checkbox / radio element.
3317
      $row['data'][] = drupal_render($element[$key]);
3318

    
3319
      // As theme_table only maps header and row columns by order, create the
3320
      // correct order by iterating over the header fields.
3321
      foreach ($element['#header'] as $fieldname => $title) {
3322
        $row['data'][] = $element['#options'][$key][$fieldname];
3323
      }
3324
      $rows[] = $row;
3325
    }
3326
    // Add an empty header or a "Select all" checkbox to provide room for the
3327
    // checkboxes/radios in the first table column.
3328
    if ($element['#js_select']) {
3329
      // Add a "Select all" checkbox.
3330
      drupal_add_js('misc/tableselect.js');
3331
      array_unshift($header, array('class' => array('select-all')));
3332
    }
3333
    else {
3334
      // Add an empty header when radio buttons are displayed or a "Select all"
3335
      // checkbox is not desired.
3336
      array_unshift($header, '');
3337
    }
3338
  }
3339
  return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes']));
3340
}
3341

    
3342
/**
3343
 * Creates checkbox or radio elements to populate a tableselect table.
3344
 *
3345
 * @param $element
3346
 *   An associative array containing the properties and children of the
3347
 *   tableselect element.
3348
 *
3349
 * @return
3350
 *   The processed element.
3351
 */
3352
function form_process_tableselect($element) {
3353

    
3354
  if ($element['#multiple']) {
3355
    $value = is_array($element['#value']) ? $element['#value'] : array();
3356
  }
3357
  else {
3358
    // Advanced selection behavior makes no sense for radios.
3359
    $element['#js_select'] = FALSE;
3360
  }
3361

    
3362
  $element['#tree'] = TRUE;
3363

    
3364
  if (count($element['#options']) > 0) {
3365
    if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
3366
      $element['#default_value'] = array();
3367
    }
3368

    
3369
    // Create a checkbox or radio for each item in #options in such a way that
3370
    // the value of the tableselect element behaves as if it had been of type
3371
    // checkboxes or radios.
3372
    foreach ($element['#options'] as $key => $choice) {
3373
      // Do not overwrite manually created children.
3374
      if (!isset($element[$key])) {
3375
        if ($element['#multiple']) {
3376
          $title = '';
3377
          if (!empty($element['#options'][$key]['title']['data']['#title'])) {
3378
            $title = t('Update @title', array(
3379
              '@title' => $element['#options'][$key]['title']['data']['#title'],
3380
            ));
3381
          }
3382
          $element[$key] = array(
3383
            '#type' => 'checkbox',
3384
            '#title' => $title,
3385
            '#title_display' => 'invisible',
3386
            '#return_value' => $key,
3387
            '#default_value' => isset($value[$key]) ? $key : NULL,
3388
            '#attributes' => $element['#attributes'],
3389
          );
3390
        }
3391
        else {
3392
          // Generate the parents as the autogenerator does, so we will have a
3393
          // unique id for each radio button.
3394
          $parents_for_id = array_merge($element['#parents'], array($key));
3395
          $element[$key] = array(
3396
            '#type' => 'radio',
3397
            '#title' => '',
3398
            '#return_value' => $key,
3399
            '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
3400
            '#attributes' => $element['#attributes'],
3401
            '#parents' => $element['#parents'],
3402
            '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
3403
            '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3404
          );
3405
        }
3406
        if (isset($element['#options'][$key]['#weight'])) {
3407
          $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
3408
        }
3409
      }
3410
    }
3411
  }
3412
  else {
3413
    $element['#value'] = array();
3414
  }
3415
  return $element;
3416
}
3417

    
3418
/**
3419
 * Processes a machine-readable name form element.
3420
 *
3421
 * @param $element
3422
 *   The form element to process. Properties used:
3423
 *   - #machine_name: An associative array containing:
3424
 *     - exists: A function name to invoke for checking whether a submitted
3425
 *       machine name value already exists. The submitted value is passed as
3426
 *       argument. In most cases, an existing API or menu argument loader
3427
 *       function can be re-used. The callback is only invoked, if the submitted
3428
 *       value differs from the element's #default_value.
3429
 *     - source: (optional) The #array_parents of the form element containing
3430
 *       the human-readable name (i.e., as contained in the $form structure) to
3431
 *       use as source for the machine name. Defaults to array('name').
3432
 *     - label: (optional) A text to display as label for the machine name value
3433
 *       after the human-readable name form element. Defaults to "Machine name".
3434
 *     - replace_pattern: (optional) A regular expression (without delimiters)
3435
 *       matching disallowed characters in the machine name. Defaults to
3436
 *       '[^a-z0-9_]+'.
3437
 *     - replace: (optional) A character to replace disallowed characters in the
3438
 *       machine name via JavaScript. Defaults to '_' (underscore). When using a
3439
 *       different character, 'replace_pattern' needs to be set accordingly.
3440
 *     - error: (optional) A custom form error message string to show, if the
3441
 *       machine name contains disallowed characters.
3442
 *     - standalone: (optional) Whether the live preview should stay in its own
3443
 *       form element rather than in the suffix of the source element. Defaults
3444
 *       to FALSE.
3445
 *   - #maxlength: (optional) Should be set to the maximum allowed length of the
3446
 *     machine name. Defaults to 64.
3447
 *   - #disabled: (optional) Should be set to TRUE in case an existing machine
3448
 *     name must not be changed after initial creation.
3449
 */
3450
function form_process_machine_name($element, &$form_state) {
3451
  // Apply default form element properties.
3452
  $element += array(
3453
    '#title' => t('Machine-readable name'),
3454
    '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
3455
    '#machine_name' => array(),
3456
    '#field_prefix' => '',
3457
    '#field_suffix' => '',
3458
    '#suffix' => '',
3459
  );
3460
  // A form element that only wants to set one #machine_name property (usually
3461
  // 'source' only) would leave all other properties undefined, if the defaults
3462
  // were defined in hook_element_info(). Therefore, we apply the defaults here.
3463
  $element['#machine_name'] += array(
3464
    'source' => array('name'),
3465
    'target' => '#' . $element['#id'],
3466
    'label' => t('Machine name'),
3467
    'replace_pattern' => '[^a-z0-9_]+',
3468
    'replace' => '_',
3469
    'standalone' => FALSE,
3470
    'field_prefix' => $element['#field_prefix'],
3471
    'field_suffix' => $element['#field_suffix'],
3472
  );
3473

    
3474
  // By default, machine names are restricted to Latin alphanumeric characters.
3475
  // So, default to LTR directionality.
3476
  if (!isset($element['#attributes'])) {
3477
    $element['#attributes'] = array();
3478
  }
3479
  $element['#attributes'] += array('dir' => 'ltr');
3480

    
3481
  // The source element defaults to array('name'), but may have been overidden.
3482
  if (empty($element['#machine_name']['source'])) {
3483
    return $element;
3484
  }
3485

    
3486
  // Retrieve the form element containing the human-readable name from the
3487
  // complete form in $form_state. By reference, because we may need to append
3488
  // a #field_suffix that will hold the live preview.
3489
  $key_exists = NULL;
3490
  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
3491
  if (!$key_exists) {
3492
    return $element;
3493
  }
3494

    
3495
  $suffix_id = $source['#id'] . '-machine-name-suffix';
3496
  $element['#machine_name']['suffix'] = '#' . $suffix_id;
3497

    
3498
  if ($element['#machine_name']['standalone']) {
3499
    $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3500
  }
3501
  else {
3502
    // Append a field suffix to the source form element, which will contain
3503
    // the live preview of the machine name.
3504
    $source += array('#field_suffix' => '');
3505
    $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3506

    
3507
    $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
3508
    drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
3509
  }
3510

    
3511
  $js_settings = array(
3512
    'type' => 'setting',
3513
    'data' => array(
3514
      'machineName' => array(
3515
        '#' . $source['#id'] => $element['#machine_name'],
3516
      ),
3517
    ),
3518
  );
3519
  $element['#attached']['js'][] = 'misc/machine-name.js';
3520
  $element['#attached']['js'][] = $js_settings;
3521

    
3522
  return $element;
3523
}
3524

    
3525
/**
3526
 * Form element validation handler for machine_name elements.
3527
 *
3528
 * Note that #maxlength is validated by _form_validate() already.
3529
 */
3530
function form_validate_machine_name(&$element, &$form_state) {
3531
  // Verify that the machine name not only consists of replacement tokens.
3532
  if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
3533
    form_error($element, t('The machine-readable name must contain unique characters.'));
3534
  }
3535

    
3536
  // Verify that the machine name contains no disallowed characters.
3537
  if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
3538
    if (!isset($element['#machine_name']['error'])) {
3539
      // Since a hyphen is the most common alternative replacement character,
3540
      // a corresponding validation error message is supported here.
3541
      if ($element['#machine_name']['replace'] == '-') {
3542
        form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
3543
      }
3544
      // Otherwise, we assume the default (underscore).
3545
      else {
3546
        form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
3547
      }
3548
    }
3549
    else {
3550
      form_error($element, $element['#machine_name']['error']);
3551
    }
3552
  }
3553

    
3554
  // Verify that the machine name is unique.
3555
  if ($element['#default_value'] !== $element['#value']) {
3556
    $function = $element['#machine_name']['exists'];
3557
    if ($function($element['#value'], $element, $form_state)) {
3558
      form_error($element, t('The machine-readable name is already in use. It must be unique.'));
3559
    }
3560
  }
3561
}
3562

    
3563
/**
3564
 * Arranges fieldsets into groups.
3565
 *
3566
 * @param $element
3567
 *   An associative array containing the properties and children of the
3568
 *   fieldset. Note that $element must be taken by reference here, so processed
3569
 *   child elements are taken over into $form_state.
3570
 * @param $form_state
3571
 *   The $form_state array for the form this fieldset belongs to.
3572
 *
3573
 * @return
3574
 *   The processed element.
3575
 */
3576
function form_process_fieldset(&$element, &$form_state) {
3577
  $parents = implode('][', $element['#parents']);
3578

    
3579
  // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
3580
  // injects a new fieldset.
3581
  $form_state['groups'][$parents]['#group_exists'] = TRUE;
3582
  $element['#groups'] = &$form_state['groups'];
3583

    
3584
  // Process vertical tabs group member fieldsets.
3585
  if (isset($element['#group'])) {
3586
    // Add this fieldset to the defined group (by reference).
3587
    $group = $element['#group'];
3588
    $form_state['groups'][$group][] = &$element;
3589
  }
3590

    
3591
  // Contains form element summary functionalities.
3592
  $element['#attached']['library'][] = array('system', 'drupal.form');
3593

    
3594
  // The .form-wrapper class is required for #states to treat fieldsets like
3595
  // containers.
3596
  if (!isset($element['#attributes']['class'])) {
3597
    $element['#attributes']['class'] = array();
3598
  }
3599

    
3600
  // Collapsible fieldsets
3601
  if (!empty($element['#collapsible'])) {
3602
    $element['#attached']['library'][] = array('system', 'drupal.collapse');
3603
    $element['#attributes']['class'][] = 'collapsible';
3604
    if (!empty($element['#collapsed'])) {
3605
      $element['#attributes']['class'][] = 'collapsed';
3606
    }
3607
  }
3608

    
3609
  return $element;
3610
}
3611

    
3612
/**
3613
 * Adds members of this group as actual elements for rendering.
3614
 *
3615
 * @param $element
3616
 *   An associative array containing the properties and children of the
3617
 *   fieldset.
3618
 *
3619
 * @return
3620
 *   The modified element with all group members.
3621
 */
3622
function form_pre_render_fieldset($element) {
3623
  // Fieldsets may be rendered outside of a Form API context.
3624
  if (!isset($element['#parents']) || !isset($element['#groups'])) {
3625
    return $element;
3626
  }
3627
  // Inject group member elements belonging to this group.
3628
  $parents = implode('][', $element['#parents']);
3629
  $children = element_children($element['#groups'][$parents]);
3630
  if (!empty($children)) {
3631
    foreach ($children as $key) {
3632
      // Break references and indicate that the element should be rendered as
3633
      // group member.
3634
      $child = (array) $element['#groups'][$parents][$key];
3635
      $child['#group_fieldset'] = TRUE;
3636
      // Inject the element as new child element.
3637
      $element[] = $child;
3638

    
3639
      $sort = TRUE;
3640
    }
3641
    // Re-sort the element's children if we injected group member elements.
3642
    if (isset($sort)) {
3643
      $element['#sorted'] = FALSE;
3644
    }
3645
  }
3646

    
3647
  if (isset($element['#group'])) {
3648
    $group = $element['#group'];
3649
    // If this element belongs to a group, but the group-holding element does
3650
    // not exist, we need to render it (at its original location).
3651
    if (!isset($element['#groups'][$group]['#group_exists'])) {
3652
      // Intentionally empty to clarify the flow; we simply return $element.
3653
    }
3654
    // If we injected this element into the group, then we want to render it.
3655
    elseif (!empty($element['#group_fieldset'])) {
3656
      // Intentionally empty to clarify the flow; we simply return $element.
3657
    }
3658
    // Otherwise, this element belongs to a group and the group exists, so we do
3659
    // not render it.
3660
    elseif (element_children($element['#groups'][$group])) {
3661
      $element['#printed'] = TRUE;
3662
    }
3663
  }
3664

    
3665
  return $element;
3666
}
3667

    
3668
/**
3669
 * Creates a group formatted as vertical tabs.
3670
 *
3671
 * @param $element
3672
 *   An associative array containing the properties and children of the
3673
 *   fieldset.
3674
 * @param $form_state
3675
 *   The $form_state array for the form this vertical tab widget belongs to.
3676
 *
3677
 * @return
3678
 *   The processed element.
3679
 */
3680
function form_process_vertical_tabs($element, &$form_state) {
3681
  // Inject a new fieldset as child, so that form_process_fieldset() processes
3682
  // this fieldset like any other fieldset.
3683
  $element['group'] = array(
3684
    '#type' => 'fieldset',
3685
    '#theme_wrappers' => array(),
3686
    '#parents' => $element['#parents'],
3687
  );
3688

    
3689
  // The JavaScript stores the currently selected tab in this hidden
3690
  // field so that the active tab can be restored the next time the
3691
  // form is rendered, e.g. on preview pages or when form validation
3692
  // fails.
3693
  $name = implode('__', $element['#parents']);
3694
  if (isset($form_state['values'][$name . '__active_tab'])) {
3695
    $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
3696
  }
3697
  $element[$name . '__active_tab'] = array(
3698
    '#type' => 'hidden',
3699
    '#default_value' => $element['#default_tab'],
3700
    '#attributes' => array('class' => array('vertical-tabs-active-tab')),
3701
  );
3702

    
3703
  return $element;
3704
}
3705

    
3706
/**
3707
 * Returns HTML for an element's children fieldsets as vertical tabs.
3708
 *
3709
 * @param $variables
3710
 *   An associative array containing:
3711
 *   - element: An associative array containing the properties and children of
3712
 *     the fieldset. Properties used: #children.
3713
 *
3714
 * @ingroup themeable
3715
 */
3716
function theme_vertical_tabs($variables) {
3717
  $element = $variables['element'];
3718
  // Add required JavaScript and Stylesheet.
3719
  drupal_add_library('system', 'drupal.vertical-tabs');
3720

    
3721
  $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
3722
  $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
3723
  return $output;
3724
}
3725

    
3726
/**
3727
 * Returns HTML for a submit button form element.
3728
 *
3729
 * @param $variables
3730
 *   An associative array containing:
3731
 *   - element: An associative array containing the properties of the element.
3732
 *     Properties used: #attributes, #button_type, #name, #value.
3733
 *
3734
 * @ingroup themeable
3735
 */
3736
function theme_submit($variables) {
3737
  return theme('button', $variables['element']);
3738
}
3739

    
3740
/**
3741
 * Returns HTML for a button form element.
3742
 *
3743
 * @param $variables
3744
 *   An associative array containing:
3745
 *   - element: An associative array containing the properties of the element.
3746
 *     Properties used: #attributes, #button_type, #name, #value.
3747
 *
3748
 * @ingroup themeable
3749
 */
3750
function theme_button($variables) {
3751
  $element = $variables['element'];
3752
  $element['#attributes']['type'] = 'submit';
3753
  element_set_attributes($element, array('id', 'name', 'value'));
3754

    
3755
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3756
  if (!empty($element['#attributes']['disabled'])) {
3757
    $element['#attributes']['class'][] = 'form-button-disabled';
3758
  }
3759

    
3760
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3761
}
3762

    
3763
/**
3764
 * Returns HTML for an image button form element.
3765
 *
3766
 * @param $variables
3767
 *   An associative array containing:
3768
 *   - element: An associative array containing the properties of the element.
3769
 *     Properties used: #attributes, #button_type, #name, #value, #title, #src.
3770
 *
3771
 * @ingroup themeable
3772
 */
3773
function theme_image_button($variables) {
3774
  $element = $variables['element'];
3775
  $element['#attributes']['type'] = 'image';
3776
  element_set_attributes($element, array('id', 'name', 'value'));
3777

    
3778
  $element['#attributes']['src'] = file_create_url($element['#src']);
3779
  if (!empty($element['#title'])) {
3780
    $element['#attributes']['alt'] = $element['#title'];
3781
    $element['#attributes']['title'] = $element['#title'];
3782
  }
3783

    
3784
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3785
  if (!empty($element['#attributes']['disabled'])) {
3786
    $element['#attributes']['class'][] = 'form-button-disabled';
3787
  }
3788

    
3789
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3790
}
3791

    
3792
/**
3793
 * Returns HTML for a hidden form element.
3794
 *
3795
 * @param $variables
3796
 *   An associative array containing:
3797
 *   - element: An associative array containing the properties of the element.
3798
 *     Properties used: #name, #value, #attributes.
3799
 *
3800
 * @ingroup themeable
3801
 */
3802
function theme_hidden($variables) {
3803
  $element = $variables['element'];
3804
  $element['#attributes']['type'] = 'hidden';
3805
  element_set_attributes($element, array('name', 'value'));
3806
  return '<input' . drupal_attributes($element['#attributes']) . " />\n";
3807
}
3808

    
3809
/**
3810
 * Returns HTML for a textfield form element.
3811
 *
3812
 * @param $variables
3813
 *   An associative array containing:
3814
 *   - element: An associative array containing the properties of the element.
3815
 *     Properties used: #title, #value, #description, #size, #maxlength,
3816
 *     #required, #attributes, #autocomplete_path.
3817
 *
3818
 * @ingroup themeable
3819
 */
3820
function theme_textfield($variables) {
3821
  $element = $variables['element'];
3822
  $element['#attributes']['type'] = 'text';
3823
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
3824
  _form_set_class($element, array('form-text'));
3825

    
3826
  $extra = '';
3827
  if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
3828
    drupal_add_library('system', 'drupal.autocomplete');
3829
    $element['#attributes']['class'][] = 'form-autocomplete';
3830

    
3831
    $attributes = array();
3832
    $attributes['type'] = 'hidden';
3833
    $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
3834
    $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
3835
    $attributes['disabled'] = 'disabled';
3836
    $attributes['class'][] = 'autocomplete';
3837
    $extra = '<input' . drupal_attributes($attributes) . ' />';
3838
  }
3839

    
3840
  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';
3841

    
3842
  return $output . $extra;
3843
}
3844

    
3845
/**
3846
 * Returns HTML for a form.
3847
 *
3848
 * @param $variables
3849
 *   An associative array containing:
3850
 *   - element: An associative array containing the properties of the element.
3851
 *     Properties used: #action, #method, #attributes, #children
3852
 *
3853
 * @ingroup themeable
3854
 */
3855
function theme_form($variables) {
3856
  $element = $variables['element'];
3857
  if (isset($element['#action'])) {
3858
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
3859
  }
3860
  element_set_attributes($element, array('method', 'id'));
3861
  if (empty($element['#attributes']['accept-charset'])) {
3862
    $element['#attributes']['accept-charset'] = "UTF-8";
3863
  }
3864
  // Anonymous DIV to satisfy XHTML compliance.
3865
  return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
3866
}
3867

    
3868
/**
3869
 * Returns HTML for a textarea form element.
3870
 *
3871
 * @param $variables
3872
 *   An associative array containing:
3873
 *   - element: An associative array containing the properties of the element.
3874
 *     Properties used: #title, #value, #description, #rows, #cols, #required,
3875
 *     #attributes
3876
 *
3877
 * @ingroup themeable
3878
 */
3879
function theme_textarea($variables) {
3880
  $element = $variables['element'];
3881
  element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
3882
  _form_set_class($element, array('form-textarea'));
3883

    
3884
  $wrapper_attributes = array(
3885
    'class' => array('form-textarea-wrapper'),
3886
  );
3887

    
3888
  // Add resizable behavior.
3889
  if (!empty($element['#resizable'])) {
3890
    drupal_add_library('system', 'drupal.textarea');
3891
    $wrapper_attributes['class'][] = 'resizable';
3892
  }
3893

    
3894
  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
3895
  $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
3896
  $output .= '</div>';
3897
  return $output;
3898
}
3899

    
3900
/**
3901
 * Returns HTML for a password form element.
3902
 *
3903
 * @param $variables
3904
 *   An associative array containing:
3905
 *   - element: An associative array containing the properties of the element.
3906
 *     Properties used: #title, #value, #description, #size, #maxlength,
3907
 *     #required, #attributes.
3908
 *
3909
 * @ingroup themeable
3910
 */
3911
function theme_password($variables) {
3912
  $element = $variables['element'];
3913
  $element['#attributes']['type'] = 'password';
3914
  element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
3915
  _form_set_class($element, array('form-text'));
3916

    
3917
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3918
}
3919

    
3920
/**
3921
 * Expands a weight element into a select element.
3922
 */
3923
function form_process_weight($element) {
3924
  $element['#is_weight'] = TRUE;
3925

    
3926
  // If the number of options is small enough, use a select field.
3927
  $max_elements = variable_get('drupal_weight_select_max', DRUPAL_WEIGHT_SELECT_MAX);
3928
  if ($element['#delta'] <= $max_elements) {
3929
    $element['#type'] = 'select';
3930
    for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
3931
      $weights[$n] = $n;
3932
    }
3933
    $element['#options'] = $weights;
3934
    $element += element_info('select');
3935
  }
3936
  // Otherwise, use a text field.
3937
  else {
3938
    $element['#type'] = 'textfield';
3939
    // Use a field big enough to fit most weights.
3940
    $element['#size'] = 10;
3941
    $element['#element_validate'] = array('element_validate_integer');
3942
    $element += element_info('textfield');
3943
  }
3944

    
3945
  return $element;
3946
}
3947

    
3948
/**
3949
 * Returns HTML for a file upload form element.
3950
 *
3951
 * For assistance with handling the uploaded file correctly, see the API
3952
 * provided by file.inc.
3953
 *
3954
 * @param $variables
3955
 *   An associative array containing:
3956
 *   - element: An associative array containing the properties of the element.
3957
 *     Properties used: #title, #name, #size, #description, #required,
3958
 *     #attributes.
3959
 *
3960
 * @ingroup themeable
3961
 */
3962
function theme_file($variables) {
3963
  $element = $variables['element'];
3964
  $element['#attributes']['type'] = 'file';
3965
  element_set_attributes($element, array('id', 'name', 'size'));
3966
  _form_set_class($element, array('form-file'));
3967

    
3968
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3969
}
3970

    
3971
/**
3972
 * Returns HTML for a form element.
3973
 *
3974
 * Each form element is wrapped in a DIV container having the following CSS
3975
 * classes:
3976
 * - form-item: Generic for all form elements.
3977
 * - form-type-#type: The internal element #type.
3978
 * - form-item-#name: The internal form element #name (usually derived from the
3979
 *   $form structure and set via form_builder()).
3980
 * - form-disabled: Only set if the form element is #disabled.
3981
 *
3982
 * In addition to the element itself, the DIV contains a label for the element
3983
 * based on the optional #title_display property, and an optional #description.
3984
 *
3985
 * The optional #title_display property can have these values:
3986
 * - before: The label is output before the element. This is the default.
3987
 *   The label includes the #title and the required marker, if #required.
3988
 * - after: The label is output after the element. For example, this is used
3989
 *   for radio and checkbox #type elements as set in system_element_info().
3990
 *   If the #title is empty but the field is #required, the label will
3991
 *   contain only the required marker.
3992
 * - invisible: Labels are critical for screen readers to enable them to
3993
 *   properly navigate through forms but can be visually distracting. This
3994
 *   property hides the label for everyone except screen readers.
3995
 * - attribute: Set the title attribute on the element to create a tooltip
3996
 *   but output no label element. This is supported only for checkboxes
3997
 *   and radios in form_pre_render_conditional_form_element(). It is used
3998
 *   where a visual label is not needed, such as a table of checkboxes where
3999
 *   the row and column provide the context. The tooltip will include the
4000
 *   title and required marker.
4001
 *
4002
 * If the #title property is not set, then the label and any required marker
4003
 * will not be output, regardless of the #title_display or #required values.
4004
 * This can be useful in cases such as the password_confirm element, which
4005
 * creates children elements that have their own labels and required markers,
4006
 * but the parent element should have neither. Use this carefully because a
4007
 * field without an associated label can cause accessibility challenges.
4008
 *
4009
 * @param $variables
4010
 *   An associative array containing:
4011
 *   - element: An associative array containing the properties of the element.
4012
 *     Properties used: #title, #title_display, #description, #id, #required,
4013
 *     #children, #type, #name.
4014
 *
4015
 * @ingroup themeable
4016
 */
4017
function theme_form_element($variables) {
4018
  $element = &$variables['element'];
4019

    
4020
  // This function is invoked as theme wrapper, but the rendered form element
4021
  // may not necessarily have been processed by form_builder().
4022
  $element += array(
4023
    '#title_display' => 'before',
4024
  );
4025

    
4026
  // Add element #id for #type 'item'.
4027
  if (isset($element['#markup']) && !empty($element['#id'])) {
4028
    $attributes['id'] = $element['#id'];
4029
  }
4030
  // Add element's #type and #name as class to aid with JS/CSS selectors.
4031
  $attributes['class'] = array('form-item');
4032
  if (!empty($element['#type'])) {
4033
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
4034
  }
4035
  if (!empty($element['#name'])) {
4036
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
4037
  }
4038
  // Add a class for disabled elements to facilitate cross-browser styling.
4039
  if (!empty($element['#attributes']['disabled'])) {
4040
    $attributes['class'][] = 'form-disabled';
4041
  }
4042
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
4043

    
4044
  // If #title is not set, we don't display any label or required marker.
4045
  if (!isset($element['#title'])) {
4046
    $element['#title_display'] = 'none';
4047
  }
4048
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
4049
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
4050

    
4051
  switch ($element['#title_display']) {
4052
    case 'before':
4053
    case 'invisible':
4054
      $output .= ' ' . theme('form_element_label', $variables);
4055
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4056
      break;
4057

    
4058
    case 'after':
4059
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
4060
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
4061
      break;
4062

    
4063
    case 'none':
4064
    case 'attribute':
4065
      // Output no label and no required marker, only the children.
4066
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4067
      break;
4068
  }
4069

    
4070
  if (!empty($element['#description'])) {
4071
    $output .= '<div class="description">' . $element['#description'] . "</div>\n";
4072
  }
4073

    
4074
  $output .= "</div>\n";
4075

    
4076
  return $output;
4077
}
4078

    
4079
/**
4080
 * Returns HTML for a marker for required form elements.
4081
 *
4082
 * @param $variables
4083
 *   An associative array containing:
4084
 *   - element: An associative array containing the properties of the element.
4085
 *
4086
 * @ingroup themeable
4087
 */
4088
function theme_form_required_marker($variables) {
4089
  // This is also used in the installer, pre-database setup.
4090
  $t = get_t();
4091
  $attributes = array(
4092
    'class' => 'form-required',
4093
    'title' => $t('This field is required.'),
4094
  );
4095
  return '<span' . drupal_attributes($attributes) . '>*</span>';
4096
}
4097

    
4098
/**
4099
 * Returns HTML for a form element label and required marker.
4100
 *
4101
 * Form element labels include the #title and a #required marker. The label is
4102
 * associated with the element itself by the element #id. Labels may appear
4103
 * before or after elements, depending on theme_form_element() and
4104
 * #title_display.
4105
 *
4106
 * This function will not be called for elements with no labels, depending on
4107
 * #title_display. For elements that have an empty #title and are not required,
4108
 * this function will output no label (''). For required elements that have an
4109
 * empty #title, this will output the required marker alone within the label.
4110
 * The label will use the #id to associate the marker with the field that is
4111
 * required. That is especially important for screenreader users to know
4112
 * which field is required.
4113
 *
4114
 * @param $variables
4115
 *   An associative array containing:
4116
 *   - element: An associative array containing the properties of the element.
4117
 *     Properties used: #required, #title, #id, #value, #description.
4118
 *
4119
 * @ingroup themeable
4120
 */
4121
function theme_form_element_label($variables) {
4122
  $element = $variables['element'];
4123
  // This is also used in the installer, pre-database setup.
4124
  $t = get_t();
4125

    
4126
  // If title and required marker are both empty, output no label.
4127
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
4128
    return '';
4129
  }
4130

    
4131
  // If the element is required, a required marker is appended to the label.
4132
  $required = !empty($element['#required']) ? theme('form_required_marker', array('element' => $element)) : '';
4133

    
4134
  $title = filter_xss_admin($element['#title']);
4135

    
4136
  $attributes = array();
4137
  // Style the label as class option to display inline with the element.
4138
  if ($element['#title_display'] == 'after') {
4139
    $attributes['class'] = 'option';
4140
  }
4141
  // Show label only to screen readers to avoid disruption in visual flows.
4142
  elseif ($element['#title_display'] == 'invisible') {
4143
    $attributes['class'] = 'element-invisible';
4144
  }
4145

    
4146
  if (!empty($element['#id'])) {
4147
    $attributes['for'] = $element['#id'];
4148
  }
4149

    
4150
  // The leading whitespace helps visually separate fields from inline labels.
4151
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title !required', array('!title' => $title, '!required' => $required)) . "</label>\n";
4152
}
4153

    
4154
/**
4155
 * Sets a form element's class attribute.
4156
 *
4157
 * Adds 'required' and 'error' classes as needed.
4158
 *
4159
 * @param $element
4160
 *   The form element.
4161
 * @param $name
4162
 *   Array of new class names to be added.
4163
 */
4164
function _form_set_class(&$element, $class = array()) {
4165
  if (!empty($class)) {
4166
    if (!isset($element['#attributes']['class'])) {
4167
      $element['#attributes']['class'] = array();
4168
    }
4169
    $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
4170
  }
4171
  // This function is invoked from form element theme functions, but the
4172
  // rendered form element may not necessarily have been processed by
4173
  // form_builder().
4174
  if (!empty($element['#required'])) {
4175
    $element['#attributes']['class'][] = 'required';
4176
  }
4177
  if (isset($element['#parents']) && form_get_error($element) !== NULL && !empty($element['#validated'])) {
4178
    $element['#attributes']['class'][] = 'error';
4179
  }
4180
}
4181

    
4182
/**
4183
 * Form element validation handler for integer elements.
4184
 */
4185
function element_validate_integer($element, &$form_state) {
4186
  $value = $element['#value'];
4187
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
4188
    form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
4189
  }
4190
}
4191

    
4192
/**
4193
 * Form element validation handler for integer elements that must be positive.
4194
 */
4195
function element_validate_integer_positive($element, &$form_state) {
4196
  $value = $element['#value'];
4197
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
4198
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
4199
  }
4200
}
4201

    
4202
/**
4203
 * Form element validation handler for number elements.
4204
 */
4205
function element_validate_number($element, &$form_state) {
4206
  $value = $element['#value'];
4207
  if ($value != '' && !is_numeric($value)) {
4208
    form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
4209
  }
4210
}
4211

    
4212
/**
4213
 * @} End of "defgroup form_api".
4214
 */
4215

    
4216
/**
4217
 * @defgroup batch Batch operations
4218
 * @{
4219
 * Creates and processes batch operations.
4220
 *
4221
 * Functions allowing forms processing to be spread out over several page
4222
 * requests, thus ensuring that the processing does not get interrupted
4223
 * because of a PHP timeout, while allowing the user to receive feedback
4224
 * on the progress of the ongoing operations.
4225
 *
4226
 * The API is primarily designed to integrate nicely with the Form API
4227
 * workflow, but can also be used by non-Form API scripts (like update.php)
4228
 * or even simple page callbacks (which should probably be used sparingly).
4229
 *
4230
 * Example:
4231
 * @code
4232
 * $batch = array(
4233
 *   'title' => t('Exporting'),
4234
 *   'operations' => array(
4235
 *     array('my_function_1', array($account->uid, 'story')),
4236
 *     array('my_function_2', array()),
4237
 *   ),
4238
 *   'finished' => 'my_finished_callback',
4239
 *   'file' => 'path_to_file_containing_myfunctions',
4240
 * );
4241
 * batch_set($batch);
4242
 * // Only needed if not inside a form _submit handler.
4243
 * // Setting redirect in batch_process.
4244
 * batch_process('node/1');
4245
 * @endcode
4246
 *
4247
 * Note: if the batch 'title', 'init_message', 'progress_message', or
4248
 * 'error_message' could contain any user input, it is the responsibility of
4249
 * the code calling batch_set() to sanitize them first with a function like
4250
 * check_plain() or filter_xss(). Furthermore, if the batch operation
4251
 * returns any user input in the 'results' or 'message' keys of $context,
4252
 * it must also sanitize them first.
4253
 *
4254
 * Sample batch operations:
4255
 * @code
4256
 * // Simple and artificial: load a node of a given type for a given user
4257
 * function my_function_1($uid, $type, &$context) {
4258
 *   // The $context array gathers batch context information about the execution (read),
4259
 *   // as well as 'return values' for the current operation (write)
4260
 *   // The following keys are provided :
4261
 *   // 'results' (read / write): The array of results gathered so far by
4262
 *   //   the batch processing, for the current operation to append its own.
4263
 *   // 'message' (write): A text message displayed in the progress page.
4264
 *   // The following keys allow for multi-step operations :
4265
 *   // 'sandbox' (read / write): An array that can be freely used to
4266
 *   //   store persistent data between iterations. It is recommended to
4267
 *   //   use this instead of $_SESSION, which is unsafe if the user
4268
 *   //   continues browsing in a separate window while the batch is processing.
4269
 *   // 'finished' (write): A float number between 0 and 1 informing
4270
 *   //   the processing engine of the completion level for the operation.
4271
 *   //   1 (or no value explicitly set) means the operation is finished
4272
 *   //   and the batch processing can continue to the next operation.
4273
 *
4274
 *   $node = node_load(array('uid' => $uid, 'type' => $type));
4275
 *   $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
4276
 *   $context['message'] = check_plain($node->title);
4277
 * }
4278
 *
4279
 * // More advanced example: multi-step operation - load all nodes, five by five
4280
 * function my_function_2(&$context) {
4281
 *   if (empty($context['sandbox'])) {
4282
 *     $context['sandbox']['progress'] = 0;
4283
 *     $context['sandbox']['current_node'] = 0;
4284
 *     $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
4285
 *   }
4286
 *   $limit = 5;
4287
 *   $result = db_select('node')
4288
 *     ->fields('node', array('nid'))
4289
 *     ->condition('nid', $context['sandbox']['current_node'], '>')
4290
 *     ->orderBy('nid')
4291
 *     ->range(0, $limit)
4292
 *     ->execute();
4293
 *   foreach ($result as $row) {
4294
 *     $node = node_load($row->nid, NULL, TRUE);
4295
 *     $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
4296
 *     $context['sandbox']['progress']++;
4297
 *     $context['sandbox']['current_node'] = $node->nid;
4298
 *     $context['message'] = check_plain($node->title);
4299
 *   }
4300
 *   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
4301
 *     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
4302
 *   }
4303
 * }
4304
 * @endcode
4305
 *
4306
 * Sample 'finished' callback:
4307
 * @code
4308
 * function batch_test_finished($success, $results, $operations) {
4309
 *   // The 'success' parameter means no fatal PHP errors were detected. All
4310
 *   // other error management should be handled using 'results'.
4311
 *   if ($success) {
4312
 *     $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
4313
 *   }
4314
 *   else {
4315
 *     $message = t('Finished with an error.');
4316
 *   }
4317
 *   drupal_set_message($message);
4318
 *   // Providing data for the redirected page is done through $_SESSION.
4319
 *   foreach ($results as $result) {
4320
 *     $items[] = t('Loaded node %title.', array('%title' => $result));
4321
 *   }
4322
 *   $_SESSION['my_batch_results'] = $items;
4323
 * }
4324
 * @endcode
4325
 */
4326

    
4327
/**
4328
 * Adds a new batch.
4329
 *
4330
 * Batch operations are added as new batch sets. Batch sets are used to spread
4331
 * processing (primarily, but not exclusively, forms processing) over several
4332
 * page requests. This helps to ensure that the processing is not interrupted
4333
 * due to PHP timeouts, while users are still able to receive feedback on the
4334
 * progress of the ongoing operations. Combining related operations into
4335
 * distinct batch sets provides clean code independence for each batch set,
4336
 * ensuring that two or more batches, submitted independently, can be processed
4337
 * without mutual interference. Each batch set may specify its own set of
4338
 * operations and results, produce its own UI messages, and trigger its own
4339
 * 'finished' callback. Batch sets are processed sequentially, with the progress
4340
 * bar starting afresh for each new set.
4341
 *
4342
 * @param $batch_definition
4343
 *   An associative array defining the batch, with the following elements (all
4344
 *   are optional except as noted):
4345
 *   - operations: (required) Array of function calls to be performed.
4346
 *     Example:
4347
 *     @code
4348
 *     array(
4349
 *       array('my_function_1', array($arg1)),
4350
 *       array('my_function_2', array($arg2_1, $arg2_2)),
4351
 *     )
4352
 *     @endcode
4353
 *   - title: A safe, translated string to use as the title for the progress
4354
 *     page. Defaults to t('Processing').
4355
 *   - init_message: Message displayed while the processing is initialized.
4356
 *     Defaults to t('Initializing.').
4357
 *   - progress_message: Message displayed while processing the batch. Available
4358
 *     placeholders are @current, @remaining, @total, @percentage, @estimate and
4359
 *     @elapsed. Defaults to t('Completed @current of @total.').
4360
 *   - error_message: Message displayed if an error occurred while processing
4361
 *     the batch. Defaults to t('An error has occurred.').
4362
 *   - finished: Name of a function to be executed after the batch has
4363
 *     completed. This should be used to perform any result massaging that may
4364
 *     be needed, and possibly save data in $_SESSION for display after final
4365
 *     page redirection.
4366
 *   - file: Path to the file containing the definitions of the 'operations' and
4367
 *     'finished' functions, for instance if they don't reside in the main
4368
 *     .module file. The path should be relative to base_path(), and thus should
4369
 *     be built using drupal_get_path().
4370
 *   - css: Array of paths to CSS files to be used on the progress page.
4371
 *   - url_options: options passed to url() when constructing redirect URLs for
4372
 *     the batch.
4373
 */
4374
function batch_set($batch_definition) {
4375
  if ($batch_definition) {
4376
    $batch =& batch_get();
4377

    
4378
    // Initialize the batch if needed.
4379
    if (empty($batch)) {
4380
      $batch = array(
4381
        'sets' => array(),
4382
        'has_form_submits' => FALSE,
4383
      );
4384
    }
4385

    
4386
    // Base and default properties for the batch set.
4387
    // Use get_t() to allow batches during installation.
4388
    $t = get_t();
4389
    $init = array(
4390
      'sandbox' => array(),
4391
      'results' => array(),
4392
      'success' => FALSE,
4393
      'start' => 0,
4394
      'elapsed' => 0,
4395
    );
4396
    $defaults = array(
4397
      'title' => $t('Processing'),
4398
      'init_message' => $t('Initializing.'),
4399
      'progress_message' => $t('Completed @current of @total.'),
4400
      'error_message' => $t('An error has occurred.'),
4401
      'css' => array(),
4402
    );
4403
    $batch_set = $init + $batch_definition + $defaults;
4404

    
4405
    // Tweak init_message to avoid the bottom of the page flickering down after
4406
    // init phase.
4407
    $batch_set['init_message'] .= '<br/>&nbsp;';
4408

    
4409
    // The non-concurrent workflow of batch execution allows us to save
4410
    // numberOfItems() queries by handling our own counter.
4411
    $batch_set['total'] = count($batch_set['operations']);
4412
    $batch_set['count'] = $batch_set['total'];
4413

    
4414
    // Add the set to the batch.
4415
    if (empty($batch['id'])) {
4416
      // The batch is not running yet. Simply add the new set.
4417
      $batch['sets'][] = $batch_set;
4418
    }
4419
    else {
4420
      // The set is being added while the batch is running. Insert the new set
4421
      // right after the current one to ensure execution order, and store its
4422
      // operations in a queue.
4423
      $index = $batch['current_set'] + 1;
4424
      $slice1 = array_slice($batch['sets'], 0, $index);
4425
      $slice2 = array_slice($batch['sets'], $index);
4426
      $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
4427
      _batch_populate_queue($batch, $index);
4428
    }
4429
  }
4430
}
4431

    
4432
/**
4433
 * Processes the batch.
4434
 *
4435
 * Unless the batch has been marked with 'progressive' = FALSE, the function
4436
 * issues a drupal_goto and thus ends page execution.
4437
 *
4438
 * This function is generally not needed in form submit handlers;
4439
 * Form API takes care of batches that were set during form submission.
4440
 *
4441
 * @param $redirect
4442
 *   (optional) Path to redirect to when the batch has finished processing.
4443
 * @param $url
4444
 *   (optional - should only be used for separate scripts like update.php)
4445
 *   URL of the batch processing page.
4446
 * @param $redirect_callback
4447
 *   (optional) Specify a function to be called to redirect to the progressive
4448
 *   processing page. By default drupal_goto() will be used to redirect to a
4449
 *   page which will do the progressive page. Specifying another function will
4450
 *   allow the progressive processing to be processed differently.
4451
 */
4452
function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = 'drupal_goto') {
4453
  $batch =& batch_get();
4454

    
4455
  drupal_theme_initialize();
4456

    
4457
  if (isset($batch)) {
4458
    // Add process information
4459
    $process_info = array(
4460
      'current_set' => 0,
4461
      'progressive' => TRUE,
4462
      'url' => $url,
4463
      'url_options' => array(),
4464
      'source_url' => $_GET['q'],
4465
      'redirect' => $redirect,
4466
      'theme' => $GLOBALS['theme_key'],
4467
      'redirect_callback' => $redirect_callback,
4468
    );
4469
    $batch += $process_info;
4470

    
4471
    // The batch is now completely built. Allow other modules to make changes
4472
    // to the batch so that it is easier to reuse batch processes in other
4473
    // environments.
4474
    drupal_alter('batch', $batch);
4475

    
4476
    // Assign an arbitrary id: don't rely on a serial column in the 'batch'
4477
    // table, since non-progressive batches skip database storage completely.
4478
    $batch['id'] = db_next_id();
4479

    
4480
    // Move operations to a job queue. Non-progressive batches will use a
4481
    // memory-based queue.
4482
    foreach ($batch['sets'] as $key => $batch_set) {
4483
      _batch_populate_queue($batch, $key);
4484
    }
4485

    
4486
    // Initiate processing.
4487
    if ($batch['progressive']) {
4488
      // Now that we have a batch id, we can generate the redirection link in
4489
      // the generic error message.
4490
      $t = get_t();
4491
      $batch['error_message'] = $t('Please continue to <a href="@error_url">the error page</a>', array('@error_url' => url($url, array('query' => array('id' => $batch['id'], 'op' => 'finished')))));
4492

    
4493
      // Clear the way for the drupal_goto() redirection to the batch processing
4494
      // page, by saving and unsetting the 'destination', if there is any.
4495
      if (isset($_GET['destination'])) {
4496
        $batch['destination'] = $_GET['destination'];
4497
        unset($_GET['destination']);
4498
      }
4499

    
4500
      // Store the batch.
4501
      db_insert('batch')
4502
        ->fields(array(
4503
          'bid' => $batch['id'],
4504
          'timestamp' => REQUEST_TIME,
4505
          'token' => drupal_get_token($batch['id']),
4506
          'batch' => serialize($batch),
4507
        ))
4508
        ->execute();
4509

    
4510
      // Set the batch number in the session to guarantee that it will stay alive.
4511
      $_SESSION['batches'][$batch['id']] = TRUE;
4512

    
4513
      // Redirect for processing.
4514
      $function = $batch['redirect_callback'];
4515
      if (function_exists($function)) {
4516
        $function($batch['url'], array('query' => array('op' => 'start', 'id' => $batch['id'])));
4517
      }
4518
    }
4519
    else {
4520
      // Non-progressive execution: bypass the whole progressbar workflow
4521
      // and execute the batch in one pass.
4522
      require_once DRUPAL_ROOT . '/includes/batch.inc';
4523
      _batch_process();
4524
    }
4525
  }
4526
}
4527

    
4528
/**
4529
 * Retrieves the current batch.
4530
 */
4531
function &batch_get() {
4532
  // Not drupal_static(), because Batch API operates at a lower level than most
4533
  // use-cases for resetting static variables, and we specifically do not want a
4534
  // global drupal_static_reset() resetting the batch information. Functions
4535
  // that are part of the Batch API and need to reset the batch information may
4536
  // call batch_get() and manipulate the result by reference. Functions that are
4537
  // not part of the Batch API can also do this, but shouldn't.
4538
  static $batch = array();
4539
  return $batch;
4540
}
4541

    
4542
/**
4543
 * Populates a job queue with the operations of a batch set.
4544
 *
4545
 * Depending on whether the batch is progressive or not, the BatchQueue or
4546
 * BatchMemoryQueue handler classes will be used.
4547
 *
4548
 * @param $batch
4549
 *   The batch array.
4550
 * @param $set_id
4551
 *   The id of the set to process.
4552
 *
4553
 * @return
4554
 *   The name and class of the queue are added by reference to the batch set.
4555
 */
4556
function _batch_populate_queue(&$batch, $set_id) {
4557
  $batch_set = &$batch['sets'][$set_id];
4558

    
4559
  if (isset($batch_set['operations'])) {
4560
    $batch_set += array(
4561
      'queue' => array(
4562
        'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
4563
        'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
4564
      ),
4565
    );
4566

    
4567
    $queue = _batch_queue($batch_set);
4568
    $queue->createQueue();
4569
    foreach ($batch_set['operations'] as $operation) {
4570
      $queue->createItem($operation);
4571
    }
4572

    
4573
    unset($batch_set['operations']);
4574
  }
4575
}
4576

    
4577
/**
4578
 * Returns a queue object for a batch set.
4579
 *
4580
 * @param $batch_set
4581
 *   The batch set.
4582
 *
4583
 * @return
4584
 *   The queue object.
4585
 */
4586
function _batch_queue($batch_set) {
4587
  static $queues;
4588

    
4589
  // The class autoloader is not available when running update.php, so make
4590
  // sure the files are manually included.
4591
  if (!isset($queues)) {
4592
    $queues = array();
4593
    require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
4594
    require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
4595
  }
4596

    
4597
  if (isset($batch_set['queue'])) {
4598
    $name = $batch_set['queue']['name'];
4599
    $class = $batch_set['queue']['class'];
4600

    
4601
    if (!isset($queues[$class][$name])) {
4602
      $queues[$class][$name] = new $class($name);
4603
    }
4604
    return $queues[$class][$name];
4605
  }
4606
}
4607

    
4608
/**
4609
 * @} End of "defgroup batch".
4610
 */