Projet

Général

Profil

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

root / drupal7 / includes / form.inc @ f7a2490e

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
 *   - programmed_bypass_access_check: If TRUE, programmatic form submissions
239
 *     are processed without taking #access into account. Set this to FALSE
240
 *     when submitting a form programmatically with values that may have been
241
 *     input by the user executing the current request; this will cause #access
242
 *     to be respected as it would on a normal form submission. Defaults to
243
 *     TRUE.
244
 *   - process_input: Boolean flag. TRUE signifies correct form submission.
245
 *     This is always TRUE for programmed forms coming from drupal_form_submit()
246
 *     (see 'programmed' key), or if the form_id coming from the $_POST data is
247
 *     set and matches the current form_id.
248
 *   - submitted: If TRUE, the form has been submitted. Defaults to FALSE.
249
 *   - executed: If TRUE, the form was submitted and has been processed and
250
 *     executed. Defaults to FALSE.
251
 *   - triggering_element: (read-only) The form element that triggered
252
 *     submission. This is the same as the deprecated
253
 *     $form_state['clicked_button']. It is the element that caused submission,
254
 *     which may or may not be a button (in the case of Ajax forms). This key is
255
 *     often used to distinguish between various buttons in a submit handler,
256
 *     and is also used in Ajax handlers.
257
 *   - clicked_button: Deprecated. Use triggering_element instead.
258
 *   - has_file_element: Internal. If TRUE, there is a file element and Form API
259
 *     will set the appropriate 'enctype' HTML attribute on the form.
260
 *   - groups: Internal. An array containing references to fieldsets to render
261
 *     them within vertical tabs.
262
 *   - storage: $form_state['storage'] is not a special key, and no specific
263
 *     support is provided for it in the Form API. By tradition it was
264
 *     the location where application-specific data was stored for communication
265
 *     between the submit, validation, and form builder functions, especially
266
 *     in a multi-step-style form. Form implementations may use any key(s)
267
 *     within $form_state (other than the keys listed here and other reserved
268
 *     ones used by Form API internals) for this kind of storage. The
269
 *     recommended way to ensure that the chosen key doesn't conflict with ones
270
 *     used by the Form API or other modules is to use the module name as the
271
 *     key name or a prefix for the key name. For example, the Node module uses
272
 *     $form_state['node'] in node editing forms to store information about the
273
 *     node being edited, and this information stays available across successive
274
 *     clicks of the "Preview" button as well as when the "Save" button is
275
 *     finally clicked.
276
 *   - buttons: A list containing copies of all submit and button elements in
277
 *     the form.
278
 *   - complete form: A reference to the $form variable containing the complete
279
 *     form structure. #process, #after_build, #element_validate, and other
280
 *     handlers being invoked on a form element may use this reference to access
281
 *     other information in the form the element is contained in.
282
 *   - temporary: An array holding temporary data accessible during the current
283
 *     page request only. All $form_state properties that are not reserved keys
284
 *     (see form_state_keys_no_cache()) persist throughout a multistep form
285
 *     sequence. Form API provides this key for modules to communicate
286
 *     information across form-related functions during a single page request.
287
 *     It may be used to temporarily save data that does not need to or should
288
 *     not be cached during the whole form workflow; e.g., data that needs to be
289
 *     accessed during the current form build process only. There is no use-case
290
 *     for this functionality in Drupal core.
291
 *   - wrapper_callback: Modules that wish to pre-populate certain forms with
292
 *     common elements, such as back/next/save buttons in multi-step form
293
 *     wizards, may define a form builder function name that returns a form
294
 *     structure, which is passed on to the actual form builder function.
295
 *     Such implementations may either define the 'wrapper_callback' via
296
 *     hook_forms() or have to invoke drupal_build_form() (instead of
297
 *     drupal_get_form()) on their own in a custom menu callback to prepare
298
 *     $form_state accordingly.
299
 *   Information on how certain $form_state properties control redirection
300
 *   behavior after form submission may be found in drupal_redirect_form().
301
 *
302
 * @return
303
 *   The rendered form. This function may also perform a redirect and hence may
304
 *   not return at all, depending upon the $form_state flags that were set.
305
 *
306
 * @see drupal_redirect_form()
307
 */
308
function drupal_build_form($form_id, &$form_state) {
309
  // Ensure some defaults; if already set they will not be overridden.
310
  $form_state += form_state_defaults();
311

    
312
  if (!isset($form_state['input'])) {
313
    $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
314
  }
315

    
316
  if (isset($_SESSION['batch_form_state'])) {
317
    // We've been redirected here after a batch processing. The form has
318
    // already been processed, but needs to be rebuilt. See _batch_finished().
319
    $form_state = $_SESSION['batch_form_state'];
320
    unset($_SESSION['batch_form_state']);
321
    return drupal_rebuild_form($form_id, $form_state);
322
  }
323

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

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

    
345
    $form = drupal_retrieve_form($form_id, $form_state);
346
    drupal_prepare_form($form_id, $form, $form_state);
347

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

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

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

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

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

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

    
475
  // #action defaults to request_uri(), but in case of Ajax and other partial
476
  // rebuilds, the form is submitted to an alternate URL, and the original
477
  // #action needs to be retained.
478
  if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
479
    $form['#action'] = $old_form['#action'];
480
  }
481

    
482
  drupal_prepare_form($form_id, $form, $form_state);
483

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

    
492
  // Clear out all group associations as these might be different when
493
  // re-rendering the form.
494
  $form_state['groups'] = array();
495

    
496
  // Return a fully built form that is ready for rendering.
497
  return form_builder($form_id, $form, $form_state);
498
}
499

    
500
/**
501
 * Fetches a form from cache.
502
 */
503
function form_get_cache($form_build_id, &$form_state) {
504
  if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
505
    $form = $cached->data;
506

    
507
    global $user;
508
    if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
509
      if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
510
        // Re-populate $form_state for subsequent rebuilds.
511
        $form_state = $cached->data + $form_state;
512

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

    
531
/**
532
 * Stores a form in the cache.
533
 */
534
function form_set_cache($form_build_id, $form, $form_state) {
535
  // 6 hours cache life time for forms should be plenty.
536
  $expire = 21600;
537

    
538
  // Cache form structure.
539
  if (isset($form)) {
540
    if ($GLOBALS['user']->uid) {
541
      $form['#cache_token'] = drupal_get_token();
542
    }
543
    cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
544
  }
545

    
546
  // Cache form state.
547
  if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
548
    cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
549
  }
550
}
551

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

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

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

    
695
  // Populate $form_state['input'] with the submitted values before retrieving
696
  // the form, to be consistent with what drupal_build_form() does for
697
  // non-programmatic submissions (form builder functions may expect it to be
698
  // there).
699
  $form_state['input'] = $form_state['values'];
700

    
701
  $form_state['programmed'] = TRUE;
702
  $form = drupal_retrieve_form($form_id, $form_state);
703
  // Programmed forms are always submitted.
704
  $form_state['submitted'] = TRUE;
705

    
706
  // Reset form validation.
707
  $form_state['must_validate'] = TRUE;
708
  form_clear_error();
709

    
710
  drupal_prepare_form($form_id, $form, $form_state);
711
  drupal_process_form($form_id, $form, $form_state);
712
}
713

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

    
731
  // Record the $form_id.
732
  $form_state['build_info']['form_id'] = $form_id;
733

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

    
749
  // We save two copies of the incoming arguments: one for modules to use
750
  // when mapping form ids to constructor functions, and another to pass to
751
  // the constructor function itself.
752
  $args = $form_state['build_info']['args'];
753

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

    
786
  $form = array();
787
  // We need to pass $form_state by reference in order for forms to modify it,
788
  // since call_user_func_array() requires that referenced variables are passed
789
  // explicitly.
790
  $args = array_merge(array($form, &$form_state), $args);
791

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

    
804
  // If $callback was returned by a hook_forms() implementation, call it.
805
  // Otherwise, call the function named after the form id.
806
  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
807
  $form['#form_id'] = $form_id;
808

    
809
  return $form;
810
}
811

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

    
832
  // With $_GET, these forms are always submitted if requested.
833
  if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
834
    if (!isset($form_state['input']['form_build_id'])) {
835
      $form_state['input']['form_build_id'] = $form['#build_id'];
836
    }
837
    if (!isset($form_state['input']['form_id'])) {
838
      $form_state['input']['form_id'] = $form_id;
839
    }
840
    if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
841
      $form_state['input']['form_token'] = drupal_get_token($form['#token']);
842
    }
843
  }
844

    
845
  // form_builder() finishes building the form by calling element #process
846
  // functions and mapping user input, if any, to #value properties, and also
847
  // storing the values in $form_state['values']. We need to retain the
848
  // unprocessed $form in case it needs to be cached.
849
  $unprocessed_form = $form;
850
  $form = form_builder($form_id, $form, $form_state);
851

    
852
  // Only process the input if we have a correct form submission.
853
  if ($form_state['process_input']) {
854
    drupal_validate_form($form_id, $form, $form_state);
855

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

    
866
    if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
867
      // Execute form submit handlers.
868
      form_execute_handlers('submit', $form, $form_state);
869

    
870
      // We'll clear out the cached copies of the form and its stored data
871
      // here, as we've finished with them. The in-memory copies are still
872
      // here, though.
873
      if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
874
        cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
875
        cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
876
      }
877

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

    
897
        $batch['progressive'] = !$form_state['programmed'];
898
        batch_process();
899

    
900
        // Execution continues only for programmatic forms.
901
        // For 'regular' forms, we get redirected to the batch processing
902
        // page. Form redirection will be handled in _batch_finished(),
903
        // after the batch is processed.
904
      }
905

    
906
      // Set a flag to indicate the the form has been processed and executed.
907
      $form_state['executed'] = TRUE;
908

    
909
      // Redirect the form based on values in $form_state.
910
      drupal_redirect_form($form_state);
911
    }
912

    
913
    // Don't rebuild or cache form submissions invoked via drupal_form_submit().
914
    if (!empty($form_state['programmed'])) {
915
      return;
916
    }
917

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

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

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

    
972
  $form['#type'] = 'form';
973
  $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
974

    
975
  // Fix the form method, if it is 'get' in $form_state, but not in $form.
976
  if ($form_state['method'] == 'get' && !isset($form['#method'])) {
977
    $form['#method'] = 'get';
978
  }
979

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

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

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

    
1044
  $form += element_info('form');
1045
  $form += array('#tree' => FALSE, '#parents' => array());
1046

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

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

    
1075
  // If no #theme has been set, automatically apply theme suggestions.
1076
  // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
1077
  // #theme function only has to care for rendering the inner form elements,
1078
  // not the form itself.
1079
  if (!isset($form['#theme'])) {
1080
    $form['#theme'] = array($form_id);
1081
    if (isset($form_state['build_info']['base_form_id'])) {
1082
      $form['#theme'][] = $form_state['build_info']['base_form_id'];
1083
    }
1084
  }
1085

    
1086
  // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
1087
  // hook_form_FORM_ID_alter() implementations.
1088
  $hooks = array('form');
1089
  if (isset($form_state['build_info']['base_form_id'])) {
1090
    $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
1091
  }
1092
  $hooks[] = 'form_' . $form_id;
1093
  drupal_alter($hooks, $form, $form_state, $form_id);
1094
}
1095

    
1096

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

    
1125
  if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
1126
    return;
1127
  }
1128

    
1129
  // If the session token was set by drupal_prepare_form(), ensure that it
1130
  // matches the current user's session.
1131
  if (isset($form['#token'])) {
1132
    if (!drupal_valid_token($form_state['values']['form_token'], $form['#token'])) {
1133
      $path = current_path();
1134
      $query = drupal_get_query_parameters();
1135
      $url = url($path, array('query' => $query));
1136

    
1137
      // Setting this error will cause the form to fail validation.
1138
      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)));
1139

    
1140
      // Stop here and don't run any further validation handlers, because they
1141
      // could invoke non-safe operations which opens the door for CSRF
1142
      // vulnerabilities.
1143
      $validated_forms[$form_id] = TRUE;
1144
      return;
1145
    }
1146
  }
1147

    
1148
  _form_validate($form, $form_state, $form_id);
1149
  $validated_forms[$form_id] = TRUE;
1150

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

    
1171
      // Like all input controls, the button value may be in the location
1172
      // dictated by #parents. If it is, copy it to $values, but do not override
1173
      // what may already be in $values.
1174
      $parents = $form_state['triggering_element']['#parents'];
1175
      if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
1176
        drupal_array_set_nested_value($values, $parents, $button_value);
1177
      }
1178

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

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

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

    
1307
  // Recurse through all children.
1308
  foreach (element_children($elements) as $key) {
1309
    if (isset($elements[$key]) && $elements[$key]) {
1310
      _form_validate($elements[$key], $form_state);
1311
    }
1312
  }
1313

    
1314
  // Validate the current input.
1315
  if (!isset($elements['#validated']) || !$elements['#validated']) {
1316
    // The following errors are always shown.
1317
    if (isset($elements['#needs_validation'])) {
1318
      // Verify that the value is not longer than #maxlength.
1319
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
1320
        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']))));
1321
      }
1322

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

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

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

    
1416
    // Call user-defined form level validators.
1417
    if (isset($form_id)) {
1418
      form_execute_handlers('validate', $elements, $form_state);
1419
    }
1420
    // Call any element-specific validators. These must act on the element
1421
    // #value data.
1422
    elseif (isset($elements['#element_validate'])) {
1423
      foreach ($elements['#element_validate'] as $function) {
1424
        $function($elements, $form_state, $form_state['complete form']);
1425
      }
1426
    }
1427
    $elements['#validated'] = TRUE;
1428
  }
1429

    
1430
  // Done validating this element, so turn off error suppression.
1431
  // _form_validate() turns it on again when starting on the next element, if
1432
  // it's still appropriate to do so.
1433
  drupal_static_reset('form_set_error:limit_validation_errors');
1434
}
1435

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

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

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

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

    
1621
  return $form;
1622
}
1623

    
1624
/**
1625
 * Clears all errors against all form elements made by form_set_error().
1626
 */
1627
function form_clear_error() {
1628
  drupal_static_reset('form_set_error');
1629
}
1630

    
1631
/**
1632
 * Returns an associative array of all errors.
1633
 */
1634
function form_get_errors() {
1635
  $form = form_set_error();
1636
  if (!empty($form)) {
1637
    return $form;
1638
  }
1639
}
1640

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

    
1659
/**
1660
 * Flags an element as having an error.
1661
 */
1662
function form_error(&$element, $message = '') {
1663
  form_set_error(implode('][', $element['#parents']), $message);
1664
}
1665

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

    
1762
  // Use element defaults.
1763
  if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
1764
    // Overlay $info onto $element, retaining preexisting keys in $element.
1765
    $element += $info;
1766
    $element['#defaults_loaded'] = TRUE;
1767
  }
1768
  // Assign basic defaults common for all form elements.
1769
  $element += array(
1770
    '#required' => FALSE,
1771
    '#attributes' => array(),
1772
    '#title_display' => 'before',
1773
  );
1774

    
1775
  // Special handling if we're on the top level form element.
1776
  if (isset($element['#type']) && $element['#type'] == 'form') {
1777
    if (!empty($element['#https']) && variable_get('https', FALSE) &&
1778
        !url_is_external($element['#action'])) {
1779
      global $base_root;
1780

    
1781
      // Not an external URL so ensure that it is secure.
1782
      $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
1783
    }
1784

    
1785
    // Store a reference to the complete form in $form_state prior to building
1786
    // the form. This allows advanced #process and #after_build callbacks to
1787
    // perform changes elsewhere in the form.
1788
    $form_state['complete form'] = &$element;
1789

    
1790
    // Set a flag if we have a correct form submission. This is always TRUE for
1791
    // programmed forms coming from drupal_form_submit(), or if the form_id coming
1792
    // from the POST data is set and matches the current form_id.
1793
    if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
1794
      $form_state['process_input'] = TRUE;
1795
    }
1796
    else {
1797
      $form_state['process_input'] = FALSE;
1798
    }
1799

    
1800
    // All form elements should have an #array_parents property.
1801
    $element['#array_parents'] = array();
1802
  }
1803

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

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

    
1823
  // Recurse through all child elements.
1824
  $count = 0;
1825
  foreach (element_children($element) as $key) {
1826
    // Prior to checking properties of child elements, their default properties
1827
    // need to be loaded.
1828
    if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
1829
      $element[$key] += $info;
1830
      $element[$key]['#defaults_loaded'] = TRUE;
1831
    }
1832

    
1833
    // Don't squash an existing tree value.
1834
    if (!isset($element[$key]['#tree'])) {
1835
      $element[$key]['#tree'] = $element['#tree'];
1836
    }
1837

    
1838
    // Deny access to child elements if parent is denied.
1839
    if (isset($element['#access']) && !$element['#access']) {
1840
      $element[$key]['#access'] = FALSE;
1841
    }
1842

    
1843
    // Make child elements inherit their parent's #disabled and #allow_focus
1844
    // values unless they specify their own.
1845
    foreach (array('#disabled', '#allow_focus') as $property) {
1846
      if (isset($element[$property]) && !isset($element[$key][$property])) {
1847
        $element[$key][$property] = $element[$property];
1848
      }
1849
    }
1850

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

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

    
1875
  // The #after_build flag allows any piece of a form to be altered
1876
  // after normal input parsing has been completed.
1877
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
1878
    foreach ($element['#after_build'] as $function) {
1879
      $element = $function($element, $form_state);
1880
    }
1881
    $element['#after_build_done'] = TRUE;
1882
  }
1883

    
1884
  // If there is a file element, we need to flip a flag so later the
1885
  // form encoding can be set.
1886
  if (isset($element['#type']) && $element['#type'] == 'file') {
1887
    $form_state['has_file_element'] = TRUE;
1888
  }
1889

    
1890
  // Final tasks for the form element after form_builder() has run for all other
1891
  // elements.
1892
  if (isset($element['#type']) && $element['#type'] == 'form') {
1893
    // If there is a file element, we set the form encoding.
1894
    if (isset($form_state['has_file_element'])) {
1895
      $element['#attributes']['enctype'] = 'multipart/form-data';
1896
    }
1897

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

    
1908
    // If the triggering element specifies "button-level" validation and submit
1909
    // handlers to run instead of the default form-level ones, then add those to
1910
    // the form state.
1911
    foreach (array('validate', 'submit') as $type) {
1912
      if (isset($form_state['triggering_element']['#' . $type])) {
1913
        $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
1914
      }
1915
    }
1916

    
1917
    // If the triggering element executes submit handlers, then set the form
1918
    // state key that's needed for those handlers to run.
1919
    if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
1920
      $form_state['submitted'] = TRUE;
1921
    }
1922

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

    
1935
      // @todo Legacy support. Remove in Drupal 8.
1936
      $form_state['clicked_button'] = $form_state['triggering_element'];
1937
    }
1938
  }
1939
  return $element;
1940
}
1941

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

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

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

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

    
2050
  // Determine which element (if any) triggered the submission of the form and
2051
  // keep track of all the clickable buttons in the form for
2052
  // form_state_values_clean(). Enforce the same input processing restrictions
2053
  // as above.
2054
  if ($process_input) {
2055
    // Detect if the element triggered the submission via Ajax.
2056
    if (_form_element_triggered_scripted_submission($element, $form_state)) {
2057
      $form_state['triggering_element'] = $element;
2058
    }
2059

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

    
2074
  // Set the element's value in $form_state['values'], but only, if its key
2075
  // does not exist yet (a #value_callback may have already populated it).
2076
  if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
2077
    form_set_value($element, $element['#value'], $form_state);
2078
  }
2079
}
2080

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

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

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

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

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

    
2231
        if (!isset($input[$element_name])) {
2232
          if (isset($input[$element_name . '_x'])) {
2233
            return $form['#return_value'];
2234
          }
2235
          return NULL;
2236
        }
2237
        $input = $input[$element_name];
2238
      }
2239
      return $form['#return_value'];
2240
    }
2241
  }
2242
}
2243

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

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

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

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

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

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

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

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

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

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

    
2554
/**
2555
 * Iterates over an array and returns a flat array with duplicate keys removed.
2556
 *
2557
 * This function also handles cases where objects are passed as array values.
2558
 */
2559
function _form_options_flatten($array) {
2560
  $return = &drupal_static(__FUNCTION__);
2561

    
2562
  foreach ($array as $key => $value) {
2563
    if (is_object($value)) {
2564
      _form_options_flatten($value->option);
2565
    }
2566
    elseif (is_array($value)) {
2567
      _form_options_flatten($value);
2568
    }
2569
    else {
2570
      $return[$key] = 1;
2571
    }
2572
  }
2573

    
2574
  return $return;
2575
}
2576

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

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

    
2663
  return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
2664
}
2665

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

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

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

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

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

    
2814
  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
2815
    $element['#attributes']['checked'] = 'checked';
2816
  }
2817
  _form_set_class($element, array('form-radio'));
2818

    
2819
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
2820
}
2821

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

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

    
2870
  if (isset($element['#size'])) {
2871
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
2872
  }
2873

    
2874
  return $element;
2875
}
2876

    
2877
/**
2878
 * Validates a password_confirm element.
2879
 */
2880
function password_confirm_validate($element, &$element_state) {
2881
  $pass1 = trim($element['pass1']['#value']);
2882
  $pass2 = trim($element['pass2']['#value']);
2883
  if (!empty($pass1) || !empty($pass2)) {
2884
    if (strcmp($pass1, $pass2)) {
2885
      form_error($element, t('The specified passwords do not match.'));
2886
    }
2887
  }
2888
  elseif ($element['#required'] && !empty($element_state['input'])) {
2889
    form_error($element, t('Password field is required.'));
2890
  }
2891

    
2892
  // Password field must be converted from a two-element array into a single
2893
  // string regardless of validation results.
2894
  form_set_value($element['pass1'], NULL, $element_state);
2895
  form_set_value($element['pass2'], NULL, $element_state);
2896
  form_set_value($element, $pass1, $element_state);
2897

    
2898
  return $element;
2899

    
2900
}
2901

    
2902
/**
2903
 * Returns HTML for a date selection form element.
2904
 *
2905
 * @param $variables
2906
 *   An associative array containing:
2907
 *   - element: An associative array containing the properties of the element.
2908
 *     Properties used: #title, #value, #options, #description, #required,
2909
 *     #attributes.
2910
 *
2911
 * @ingroup themeable
2912
 */
2913
function theme_date($variables) {
2914
  $element = $variables['element'];
2915

    
2916
  $attributes = array();
2917
  if (isset($element['#id'])) {
2918
    $attributes['id'] = $element['#id'];
2919
  }
2920
  if (!empty($element['#attributes']['class'])) {
2921
    $attributes['class'] = (array) $element['#attributes']['class'];
2922
  }
2923
  $attributes['class'][] = 'container-inline';
2924

    
2925
  return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
2926
}
2927

    
2928
/**
2929
 * Expands a date element into year, month, and day select elements.
2930
 */
2931
function form_process_date($element) {
2932
  // Default to current date
2933
  if (empty($element['#value'])) {
2934
    $element['#value'] = array(
2935
      'day' => format_date(REQUEST_TIME, 'custom', 'j'),
2936
      'month' => format_date(REQUEST_TIME, 'custom', 'n'),
2937
      'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
2938
    );
2939
  }
2940

    
2941
  $element['#tree'] = TRUE;
2942

    
2943
  // Determine the order of day, month, year in the site's chosen date format.
2944
  $format = variable_get('date_format_short', 'm/d/Y - H:i');
2945
  $sort = array();
2946
  $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
2947
  $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
2948
  $sort['year'] = strpos($format, 'Y');
2949
  asort($sort);
2950
  $order = array_keys($sort);
2951

    
2952
  // Output multi-selector for date.
2953
  foreach ($order as $type) {
2954
    switch ($type) {
2955
      case 'day':
2956
        $options = drupal_map_assoc(range(1, 31));
2957
        $title = t('Day');
2958
        break;
2959

    
2960
      case 'month':
2961
        $options = drupal_map_assoc(range(1, 12), 'map_month');
2962
        $title = t('Month');
2963
        break;
2964

    
2965
      case 'year':
2966
        $options = drupal_map_assoc(range(1900, 2050));
2967
        $title = t('Year');
2968
        break;
2969
    }
2970

    
2971
    $element[$type] = array(
2972
      '#type' => 'select',
2973
      '#title' => $title,
2974
      '#title_display' => 'invisible',
2975
      '#value' => $element['#value'][$type],
2976
      '#attributes' => $element['#attributes'],
2977
      '#options' => $options,
2978
    );
2979
  }
2980

    
2981
  return $element;
2982
}
2983

    
2984
/**
2985
 * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
2986
 */
2987
function date_validate($element) {
2988
  if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
2989
    form_error($element, t('The specified date is invalid.'));
2990
  }
2991
}
2992

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

    
3014
/**
3015
 * Sets the value for a weight element, with zero as a default.
3016
 */
3017
function weight_value(&$form) {
3018
  if (isset($form['#default_value'])) {
3019
    $form['#value'] = $form['#default_value'];
3020
  }
3021
  else {
3022
    $form['#value'] = 0;
3023
  }
3024
}
3025

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

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

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

    
3078
  // Unchecked checkbox has #value of integer 0.
3079
  if (!empty($element['#checked'])) {
3080
    $element['#attributes']['checked'] = 'checked';
3081
  }
3082
  _form_set_class($element, array('form-checkbox'));
3083

    
3084
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3085
}
3086

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

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

    
3129
  if (isset($element['#title']) || isset($element['#description'])) {
3130
    $element['#theme_wrappers'][] = 'form_element';
3131
  }
3132
  return $element;
3133
}
3134

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

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

    
3186
      $element += array($key => array());
3187
      $element[$key] += array(
3188
        '#type' => 'checkbox',
3189
        '#title' => $choice,
3190
        '#return_value' => $key,
3191
        '#default_value' => isset($value[$key]) ? $key : NULL,
3192
        '#attributes' => $element['#attributes'],
3193
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3194
        '#weight' => $weight,
3195
      );
3196
    }
3197
  }
3198
  return $element;
3199
}
3200

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

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

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

    
3255
  // Special handling for form elements.
3256
  if (isset($element['#array_parents'])) {
3257
    // Assign an html ID.
3258
    if (!isset($element['#attributes']['id'])) {
3259
      $element['#attributes']['id'] = $element['#id'];
3260
    }
3261
    // Add the 'form-wrapper' class.
3262
    $element['#attributes']['class'][] = 'form-wrapper';
3263
  }
3264

    
3265
  return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
3266
}
3267

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

    
3319
      $row['data'] = array();
3320
      if (isset($element['#options'][$key]['#attributes'])) {
3321
        $row += $element['#options'][$key]['#attributes'];
3322
      }
3323
      // Render the checkbox / radio element.
3324
      $row['data'][] = drupal_render($element[$key]);
3325

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

    
3349
/**
3350
 * Creates checkbox or radio elements to populate a tableselect table.
3351
 *
3352
 * @param $element
3353
 *   An associative array containing the properties and children of the
3354
 *   tableselect element.
3355
 *
3356
 * @return
3357
 *   The processed element.
3358
 */
3359
function form_process_tableselect($element) {
3360

    
3361
  if ($element['#multiple']) {
3362
    $value = is_array($element['#value']) ? $element['#value'] : array();
3363
  }
3364
  else {
3365
    // Advanced selection behavior makes no sense for radios.
3366
    $element['#js_select'] = FALSE;
3367
  }
3368

    
3369
  $element['#tree'] = TRUE;
3370

    
3371
  if (count($element['#options']) > 0) {
3372
    if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
3373
      $element['#default_value'] = array();
3374
    }
3375

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

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

    
3481
  // By default, machine names are restricted to Latin alphanumeric characters.
3482
  // So, default to LTR directionality.
3483
  if (!isset($element['#attributes'])) {
3484
    $element['#attributes'] = array();
3485
  }
3486
  $element['#attributes'] += array('dir' => 'ltr');
3487

    
3488
  // The source element defaults to array('name'), but may have been overidden.
3489
  if (empty($element['#machine_name']['source'])) {
3490
    return $element;
3491
  }
3492

    
3493
  // Retrieve the form element containing the human-readable name from the
3494
  // complete form in $form_state. By reference, because we may need to append
3495
  // a #field_suffix that will hold the live preview.
3496
  $key_exists = NULL;
3497
  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
3498
  if (!$key_exists) {
3499
    return $element;
3500
  }
3501

    
3502
  $suffix_id = $source['#id'] . '-machine-name-suffix';
3503
  $element['#machine_name']['suffix'] = '#' . $suffix_id;
3504

    
3505
  if ($element['#machine_name']['standalone']) {
3506
    $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3507
  }
3508
  else {
3509
    // Append a field suffix to the source form element, which will contain
3510
    // the live preview of the machine name.
3511
    $source += array('#field_suffix' => '');
3512
    $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3513

    
3514
    $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
3515
    drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
3516
  }
3517

    
3518
  $js_settings = array(
3519
    'type' => 'setting',
3520
    'data' => array(
3521
      'machineName' => array(
3522
        '#' . $source['#id'] => $element['#machine_name'],
3523
      ),
3524
    ),
3525
  );
3526
  $element['#attached']['js'][] = 'misc/machine-name.js';
3527
  $element['#attached']['js'][] = $js_settings;
3528

    
3529
  return $element;
3530
}
3531

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

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

    
3561
  // Verify that the machine name is unique.
3562
  if ($element['#default_value'] !== $element['#value']) {
3563
    $function = $element['#machine_name']['exists'];
3564
    if ($function($element['#value'], $element, $form_state)) {
3565
      form_error($element, t('The machine-readable name is already in use. It must be unique.'));
3566
    }
3567
  }
3568
}
3569

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

    
3586
  // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
3587
  // injects a new fieldset.
3588
  $form_state['groups'][$parents]['#group_exists'] = TRUE;
3589
  $element['#groups'] = &$form_state['groups'];
3590

    
3591
  // Process vertical tabs group member fieldsets.
3592
  if (isset($element['#group'])) {
3593
    // Add this fieldset to the defined group (by reference).
3594
    $group = $element['#group'];
3595
    $form_state['groups'][$group][] = &$element;
3596
  }
3597

    
3598
  // Contains form element summary functionalities.
3599
  $element['#attached']['library'][] = array('system', 'drupal.form');
3600

    
3601
  // The .form-wrapper class is required for #states to treat fieldsets like
3602
  // containers.
3603
  if (!isset($element['#attributes']['class'])) {
3604
    $element['#attributes']['class'] = array();
3605
  }
3606

    
3607
  // Collapsible fieldsets
3608
  if (!empty($element['#collapsible'])) {
3609
    $element['#attached']['library'][] = array('system', 'drupal.collapse');
3610
    $element['#attributes']['class'][] = 'collapsible';
3611
    if (!empty($element['#collapsed'])) {
3612
      $element['#attributes']['class'][] = 'collapsed';
3613
    }
3614
  }
3615

    
3616
  return $element;
3617
}
3618

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

    
3646
      $sort = TRUE;
3647
    }
3648
    // Re-sort the element's children if we injected group member elements.
3649
    if (isset($sort)) {
3650
      $element['#sorted'] = FALSE;
3651
    }
3652
  }
3653

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

    
3672
  return $element;
3673
}
3674

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

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

    
3710
  return $element;
3711
}
3712

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

    
3728
  $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
3729
  $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
3730
  return $output;
3731
}
3732

    
3733
/**
3734
 * Returns HTML for a submit button form element.
3735
 *
3736
 * @param $variables
3737
 *   An associative array containing:
3738
 *   - element: An associative array containing the properties of the element.
3739
 *     Properties used: #attributes, #button_type, #name, #value.
3740
 *
3741
 * @ingroup themeable
3742
 */
3743
function theme_submit($variables) {
3744
  return theme('button', $variables['element']);
3745
}
3746

    
3747
/**
3748
 * Returns HTML for a button form element.
3749
 *
3750
 * @param $variables
3751
 *   An associative array containing:
3752
 *   - element: An associative array containing the properties of the element.
3753
 *     Properties used: #attributes, #button_type, #name, #value.
3754
 *
3755
 * @ingroup themeable
3756
 */
3757
function theme_button($variables) {
3758
  $element = $variables['element'];
3759
  $element['#attributes']['type'] = 'submit';
3760
  element_set_attributes($element, array('id', 'name', 'value'));
3761

    
3762
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3763
  if (!empty($element['#attributes']['disabled'])) {
3764
    $element['#attributes']['class'][] = 'form-button-disabled';
3765
  }
3766

    
3767
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3768
}
3769

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

    
3785
  $element['#attributes']['src'] = file_create_url($element['#src']);
3786
  if (!empty($element['#title'])) {
3787
    $element['#attributes']['alt'] = $element['#title'];
3788
    $element['#attributes']['title'] = $element['#title'];
3789
  }
3790

    
3791
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3792
  if (!empty($element['#attributes']['disabled'])) {
3793
    $element['#attributes']['class'][] = 'form-button-disabled';
3794
  }
3795

    
3796
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3797
}
3798

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

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

    
3833
  $extra = '';
3834
  if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
3835
    drupal_add_library('system', 'drupal.autocomplete');
3836
    $element['#attributes']['class'][] = 'form-autocomplete';
3837

    
3838
    $attributes = array();
3839
    $attributes['type'] = 'hidden';
3840
    $attributes['id'] = $element['#attributes']['id'] . '-autocomplete';
3841
    $attributes['value'] = url($element['#autocomplete_path'], array('absolute' => TRUE));
3842
    $attributes['disabled'] = 'disabled';
3843
    $attributes['class'][] = 'autocomplete';
3844
    $extra = '<input' . drupal_attributes($attributes) . ' />';
3845
  }
3846

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

    
3849
  return $output . $extra;
3850
}
3851

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

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

    
3891
  $wrapper_attributes = array(
3892
    'class' => array('form-textarea-wrapper'),
3893
  );
3894

    
3895
  // Add resizable behavior.
3896
  if (!empty($element['#resizable'])) {
3897
    drupal_add_library('system', 'drupal.textarea');
3898
    $wrapper_attributes['class'][] = 'resizable';
3899
  }
3900

    
3901
  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
3902
  $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
3903
  $output .= '</div>';
3904
  return $output;
3905
}
3906

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

    
3924
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3925
}
3926

    
3927
/**
3928
 * Expands a weight element into a select element.
3929
 */
3930
function form_process_weight($element) {
3931
  $element['#is_weight'] = TRUE;
3932

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

    
3952
  return $element;
3953
}
3954

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

    
3975
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3976
}
3977

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

    
4027
  // This function is invoked as theme wrapper, but the rendered form element
4028
  // may not necessarily have been processed by form_builder().
4029
  $element += array(
4030
    '#title_display' => 'before',
4031
  );
4032

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

    
4051
  // If #title is not set, we don't display any label or required marker.
4052
  if (!isset($element['#title'])) {
4053
    $element['#title_display'] = 'none';
4054
  }
4055
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
4056
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
4057

    
4058
  switch ($element['#title_display']) {
4059
    case 'before':
4060
    case 'invisible':
4061
      $output .= ' ' . theme('form_element_label', $variables);
4062
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4063
      break;
4064

    
4065
    case 'after':
4066
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
4067
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
4068
      break;
4069

    
4070
    case 'none':
4071
    case 'attribute':
4072
      // Output no label and no required marker, only the children.
4073
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4074
      break;
4075
  }
4076

    
4077
  if (!empty($element['#description'])) {
4078
    $output .= '<div class="description">' . $element['#description'] . "</div>\n";
4079
  }
4080

    
4081
  $output .= "</div>\n";
4082

    
4083
  return $output;
4084
}
4085

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

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

    
4133
  // If title and required marker are both empty, output no label.
4134
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
4135
    return '';
4136
  }
4137

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

    
4141
  $title = filter_xss_admin($element['#title']);
4142

    
4143
  $attributes = array();
4144
  // Style the label as class option to display inline with the element.
4145
  if ($element['#title_display'] == 'after') {
4146
    $attributes['class'] = 'option';
4147
  }
4148
  // Show label only to screen readers to avoid disruption in visual flows.
4149
  elseif ($element['#title_display'] == 'invisible') {
4150
    $attributes['class'] = 'element-invisible';
4151
  }
4152

    
4153
  if (!empty($element['#id'])) {
4154
    $attributes['for'] = $element['#id'];
4155
  }
4156

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

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

    
4189
/**
4190
 * Form element validation handler for integer elements.
4191
 */
4192
function element_validate_integer($element, &$form_state) {
4193
  $value = $element['#value'];
4194
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
4195
    form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
4196
  }
4197
}
4198

    
4199
/**
4200
 * Form element validation handler for integer elements that must be positive.
4201
 */
4202
function element_validate_integer_positive($element, &$form_state) {
4203
  $value = $element['#value'];
4204
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
4205
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
4206
  }
4207
}
4208

    
4209
/**
4210
 * Form element validation handler for number elements.
4211
 */
4212
function element_validate_number($element, &$form_state) {
4213
  $value = $element['#value'];
4214
  if ($value != '' && !is_numeric($value)) {
4215
    form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
4216
  }
4217
}
4218

    
4219
/**
4220
 * @} End of "defgroup form_api".
4221
 */
4222

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

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

    
4385
    // Initialize the batch if needed.
4386
    if (empty($batch)) {
4387
      $batch = array(
4388
        'sets' => array(),
4389
        'has_form_submits' => FALSE,
4390
      );
4391
    }
4392

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

    
4412
    // Tweak init_message to avoid the bottom of the page flickering down after
4413
    // init phase.
4414
    $batch_set['init_message'] .= '<br/>&nbsp;';
4415

    
4416
    // The non-concurrent workflow of batch execution allows us to save
4417
    // numberOfItems() queries by handling our own counter.
4418
    $batch_set['total'] = count($batch_set['operations']);
4419
    $batch_set['count'] = $batch_set['total'];
4420

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

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

    
4462
  drupal_theme_initialize();
4463

    
4464
  if (isset($batch)) {
4465
    // Add process information
4466
    $process_info = array(
4467
      'current_set' => 0,
4468
      'progressive' => TRUE,
4469
      'url' => $url,
4470
      'url_options' => array(),
4471
      'source_url' => $_GET['q'],
4472
      'redirect' => $redirect,
4473
      'theme' => $GLOBALS['theme_key'],
4474
      'redirect_callback' => $redirect_callback,
4475
    );
4476
    $batch += $process_info;
4477

    
4478
    // The batch is now completely built. Allow other modules to make changes
4479
    // to the batch so that it is easier to reuse batch processes in other
4480
    // environments.
4481
    drupal_alter('batch', $batch);
4482

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

    
4487
    // Move operations to a job queue. Non-progressive batches will use a
4488
    // memory-based queue.
4489
    foreach ($batch['sets'] as $key => $batch_set) {
4490
      _batch_populate_queue($batch, $key);
4491
    }
4492

    
4493
    // Initiate processing.
4494
    if ($batch['progressive']) {
4495
      // Now that we have a batch id, we can generate the redirection link in
4496
      // the generic error message.
4497
      $t = get_t();
4498
      $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')))));
4499

    
4500
      // Clear the way for the drupal_goto() redirection to the batch processing
4501
      // page, by saving and unsetting the 'destination', if there is any.
4502
      if (isset($_GET['destination'])) {
4503
        $batch['destination'] = $_GET['destination'];
4504
        unset($_GET['destination']);
4505
      }
4506

    
4507
      // Store the batch.
4508
      db_insert('batch')
4509
        ->fields(array(
4510
          'bid' => $batch['id'],
4511
          'timestamp' => REQUEST_TIME,
4512
          'token' => drupal_get_token($batch['id']),
4513
          'batch' => serialize($batch),
4514
        ))
4515
        ->execute();
4516

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

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

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

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

    
4566
  if (isset($batch_set['operations'])) {
4567
    $batch_set += array(
4568
      'queue' => array(
4569
        'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
4570
        'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
4571
      ),
4572
    );
4573

    
4574
    $queue = _batch_queue($batch_set);
4575
    $queue->createQueue();
4576
    foreach ($batch_set['operations'] as $operation) {
4577
      $queue->createItem($operation);
4578
    }
4579

    
4580
    unset($batch_set['operations']);
4581
  }
4582
}
4583

    
4584
/**
4585
 * Returns a queue object for a batch set.
4586
 *
4587
 * @param $batch_set
4588
 *   The batch set.
4589
 *
4590
 * @return
4591
 *   The queue object.
4592
 */
4593
function _batch_queue($batch_set) {
4594
  static $queues;
4595

    
4596
  // The class autoloader is not available when running update.php, so make
4597
  // sure the files are manually included.
4598
  if (!isset($queues)) {
4599
    $queues = array();
4600
    require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
4601
    require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
4602
  }
4603

    
4604
  if (isset($batch_set['queue'])) {
4605
    $name = $batch_set['queue']['name'];
4606
    $class = $batch_set['queue']['class'];
4607

    
4608
    if (!isset($queues[$class][$name])) {
4609
      $queues[$class][$name] = new $class($name);
4610
    }
4611
    return $queues[$class][$name];
4612
  }
4613
}
4614

    
4615
/**
4616
 * @} End of "defgroup batch".
4617
 */