Projet

Général

Profil

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

root / drupal7 / includes / form.inc @ 7c856df4

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
 * - \@ingroup forms
19
 * - \@see user_pass_validate()
20
 * - \@see user_pass_submit()
21
 *
22
 * @}
23
 */
24

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

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

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

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

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

    
317
  if (!isset($form_state['input'])) {
318
    $form_state['input'] = $form_state['method'] == 'get' ? $_GET : $_POST;
319
  }
320

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

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

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

    
350
    $form = drupal_retrieve_form($form_id, $form_state);
351
    drupal_prepare_form($form_id, $form, $form_state);
352

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

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

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

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

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

    
466
  // If only parts of the form will be returned to the browser (e.g., Ajax or
467
  // RIA clients), or if the form already had a new build ID regenerated when it
468
  // was retrieved from the form cache, reuse the existing #build_id.
469
  // Otherwise, a new #build_id is generated, to not clobber the previous
470
  // build's data in the form cache; also allowing the user to go back to an
471
  // earlier build, make changes, and re-submit.
472
  // @see drupal_prepare_form()
473
  $enforce_old_build_id = isset($old_form['#build_id']) && !empty($form_state['rebuild_info']['copy']['#build_id']);
474
  $old_form_is_mutable_copy = isset($old_form['#build_id_old']);
475
  if ($enforce_old_build_id || $old_form_is_mutable_copy) {
476
    $form['#build_id'] = $old_form['#build_id'];
477
    if ($old_form_is_mutable_copy) {
478
      $form['#build_id_old'] = $old_form['#build_id_old'];
479
    }
480
  }
481
  else {
482
    if (isset($old_form['#build_id'])) {
483
      $form['#build_id_old'] = $old_form['#build_id'];
484
    }
485
    $form['#build_id'] = 'form-' . drupal_random_key();
486
  }
487

    
488
  // #action defaults to request_uri(), but in case of Ajax and other partial
489
  // rebuilds, the form is submitted to an alternate URL, and the original
490
  // #action needs to be retained.
491
  if (isset($old_form['#action']) && !empty($form_state['rebuild_info']['copy']['#action'])) {
492
    $form['#action'] = $old_form['#action'];
493
  }
494

    
495
  drupal_prepare_form($form_id, $form, $form_state);
496

    
497
  // Caching is normally done in drupal_process_form(), but what needs to be
498
  // cached is the $form structure before it passes through form_builder(),
499
  // so we need to do it here.
500
  // @todo For Drupal 8, find a way to avoid this code duplication.
501
  if (empty($form_state['no_cache'])) {
502
    form_set_cache($form['#build_id'], $form, $form_state);
503
  }
504

    
505
  // Clear out all group associations as these might be different when
506
  // re-rendering the form.
507
  $form_state['groups'] = array();
508

    
509
  // Return a fully built form that is ready for rendering.
510
  return form_builder($form_id, $form, $form_state);
511
}
512

    
513
/**
514
 * Fetches a form from cache.
515
 */
516
function form_get_cache($form_build_id, &$form_state) {
517
  if ($cached = cache_get('form_' . $form_build_id, 'cache_form')) {
518
    $form = $cached->data;
519

    
520
    global $user;
521
    if ((isset($form['#cache_token']) && drupal_valid_token($form['#cache_token'])) || (!isset($form['#cache_token']) && !$user->uid)) {
522
      if ($cached = cache_get('form_state_' . $form_build_id, 'cache_form')) {
523
        // Re-populate $form_state for subsequent rebuilds.
524
        $form_state = $cached->data + $form_state;
525

    
526
        // If the original form is contained in include files, load the files.
527
        // @see form_load_include()
528
        $form_state['build_info'] += array('files' => array());
529
        foreach ($form_state['build_info']['files'] as $file) {
530
          if (is_array($file)) {
531
            $file += array('type' => 'inc', 'name' => $file['module']);
532
            module_load_include($file['type'], $file['module'], $file['name']);
533
          }
534
          elseif (file_exists($file)) {
535
            require_once DRUPAL_ROOT . '/' . $file;
536
          }
537
        }
538
      }
539
      // Generate a new #build_id if the cached form was rendered on a cacheable
540
      // page.
541
      if (!empty($form_state['build_info']['immutable'])) {
542
        $form['#build_id_old'] = $form['#build_id'];
543
        $form['#build_id'] = 'form-' . drupal_random_key();
544
        $form['form_build_id']['#value'] = $form['#build_id'];
545
        $form['form_build_id']['#id'] = $form['#build_id'];
546
        unset($form_state['build_info']['immutable']);
547
      }
548
      return $form;
549
    }
550
  }
551
}
552

    
553
/**
554
 * Stores a form in the cache.
555
 */
556
function form_set_cache($form_build_id, $form, $form_state) {
557
  // 6 hours cache life time for forms should be plenty.
558
  $expire = 21600;
559

    
560
  // Ensure that the form build_id embedded in the form structure is the same as
561
  // the one passed in as a parameter. This is an additional safety measure to
562
  // prevent legacy code operating directly with form_get_cache and
563
  // form_set_cache from accidentally overwriting immutable form state.
564
  if ($form['#build_id'] != $form_build_id) {
565
    watchdog('form', 'Form build-id mismatch detected while attempting to store a form in the cache.', array(), WATCHDOG_ERROR);
566
    return;
567
  }
568

    
569
  // Cache form structure.
570
  if (isset($form)) {
571
    if ($GLOBALS['user']->uid) {
572
      $form['#cache_token'] = drupal_get_token();
573
    }
574
    unset($form['#build_id_old']);
575
    cache_set('form_' . $form_build_id, $form, 'cache_form', REQUEST_TIME + $expire);
576
  }
577

    
578
  // Cache form state.
579
  if (variable_get('cache', 0) && drupal_page_is_cacheable()) {
580
    $form_state['build_info']['immutable'] = TRUE;
581
  }
582
  if ($data = array_diff_key($form_state, array_flip(form_state_keys_no_cache()))) {
583
    cache_set('form_state_' . $form_build_id, $data, 'cache_form', REQUEST_TIME + $expire);
584
  }
585
}
586

    
587
/**
588
 * Returns an array of $form_state keys that shouldn't be cached.
589
 */
590
function form_state_keys_no_cache() {
591
  return array(
592
    // Public properties defined by form constructors and form handlers.
593
    'always_process',
594
    'must_validate',
595
    'rebuild',
596
    'rebuild_info',
597
    'redirect',
598
    'no_redirect',
599
    'temporary',
600
    // Internal properties defined by form processing.
601
    'buttons',
602
    'triggering_element',
603
    'clicked_button',
604
    'complete form',
605
    'groups',
606
    'input',
607
    'method',
608
    'submit_handlers',
609
    'submitted',
610
    'executed',
611
    'validate_handlers',
612
    'values',
613
  );
614
}
615

    
616
/**
617
 * Ensures an include file is loaded whenever the form is processed.
618
 *
619
 * Example:
620
 * @code
621
 *   // Load node.admin.inc from Node module.
622
 *   form_load_include($form_state, 'inc', 'node', 'node.admin');
623
 * @endcode
624
 *
625
 * Use this function instead of module_load_include() from inside a form
626
 * constructor or any form processing logic as it ensures that the include file
627
 * is loaded whenever the form is processed. In contrast to using
628
 * module_load_include() directly, form_load_include() makes sure the include
629
 * file is correctly loaded also if the form is cached.
630
 *
631
 * @param $form_state
632
 *   The current state of the form.
633
 * @param $type
634
 *   The include file's type (file extension).
635
 * @param $module
636
 *   The module to which the include file belongs.
637
 * @param $name
638
 *   (optional) The base file name (without the $type extension). If omitted,
639
 *   $module is used; i.e., resulting in "$module.$type" by default.
640
 *
641
 * @return
642
 *   The filepath of the loaded include file, or FALSE if the include file was
643
 *   not found or has been loaded already.
644
 *
645
 * @see module_load_include()
646
 */
647
function form_load_include(&$form_state, $type, $module, $name = NULL) {
648
  if (!isset($name)) {
649
    $name = $module;
650
  }
651
  if (!isset($form_state['build_info']['files']["$module:$name.$type"])) {
652
    // Only add successfully included files to the form state.
653
    if ($result = module_load_include($type, $module, $name)) {
654
      $form_state['build_info']['files']["$module:$name.$type"] = array(
655
        'type' => $type,
656
        'module' => $module,
657
        'name' => $name,
658
      );
659
      return $result;
660
    }
661
  }
662
  return FALSE;
663
}
664

    
665
/**
666
 * Retrieves, populates, and processes a form.
667
 *
668
 * This function allows you to supply values for form elements and submit a
669
 * form for processing. Compare to drupal_get_form(), which also builds and
670
 * processes a form, but does not allow you to supply values.
671
 *
672
 * There is no return value, but you can check to see if there are errors
673
 * by calling form_get_errors().
674
 *
675
 * @param $form_id
676
 *   The unique string identifying the desired form. If a function
677
 *   with that name exists, it is called to build the form array.
678
 *   Modules that need to generate the same form (or very similar forms)
679
 *   using different $form_ids can implement hook_forms(), which maps
680
 *   different $form_id values to the proper form constructor function. Examples
681
 *   may be found in node_forms() and search_forms().
682
 * @param $form_state
683
 *   A keyed array containing the current state of the form. Most important is
684
 *   the $form_state['values'] collection, a tree of data used to simulate the
685
 *   incoming $_POST information from a user's form submission. If a key is not
686
 *   filled in $form_state['values'], then the default value of the respective
687
 *   element is used. To submit an unchecked checkbox or other control that
688
 *   browsers submit by not having a $_POST entry, include the key, but set the
689
 *   value to NULL.
690
 * @param ...
691
 *   Any additional arguments are passed on to the functions called by
692
 *   drupal_form_submit(), including the unique form constructor function.
693
 *   For example, the node_edit form requires that a node object be passed
694
 *   in here when it is called. Arguments that need to be passed by reference
695
 *   should not be included here, but rather placed directly in the $form_state
696
 *   build info array so that the reference can be preserved. For example, a
697
 *   form builder function with the following signature:
698
 *   @code
699
 *   function mymodule_form($form, &$form_state, &$object) {
700
 *   }
701
 *   @endcode
702
 *   would be called via drupal_form_submit() as follows:
703
 *   @code
704
 *   $form_state['values'] = $my_form_values;
705
 *   $form_state['build_info']['args'] = array(&$object);
706
 *   drupal_form_submit('mymodule_form', $form_state);
707
 *   @endcode
708
 * For example:
709
 * @code
710
 * // register a new user
711
 * $form_state = array();
712
 * $form_state['values']['name'] = 'robo-user';
713
 * $form_state['values']['mail'] = 'robouser@example.com';
714
 * $form_state['values']['pass']['pass1'] = 'password';
715
 * $form_state['values']['pass']['pass2'] = 'password';
716
 * $form_state['values']['op'] = t('Create new account');
717
 * drupal_form_submit('user_register_form', $form_state);
718
 * @endcode
719
 */
720
function drupal_form_submit($form_id, &$form_state) {
721
  if (!isset($form_state['build_info']['args'])) {
722
    $args = func_get_args();
723
    array_shift($args);
724
    array_shift($args);
725
    $form_state['build_info']['args'] = $args;
726
  }
727
  // Merge in default values.
728
  $form_state += form_state_defaults();
729

    
730
  // Populate $form_state['input'] with the submitted values before retrieving
731
  // the form, to be consistent with what drupal_build_form() does for
732
  // non-programmatic submissions (form builder functions may expect it to be
733
  // there).
734
  $form_state['input'] = $form_state['values'];
735

    
736
  $form_state['programmed'] = TRUE;
737
  $form = drupal_retrieve_form($form_id, $form_state);
738
  // Programmed forms are always submitted.
739
  $form_state['submitted'] = TRUE;
740

    
741
  // Reset form validation.
742
  $form_state['must_validate'] = TRUE;
743
  form_clear_error();
744

    
745
  drupal_prepare_form($form_id, $form, $form_state);
746
  drupal_process_form($form_id, $form, $form_state);
747
}
748

    
749
/**
750
 * Retrieves the structured array that defines a given form.
751
 *
752
 * @param $form_id
753
 *   The unique string identifying the desired form. If a function
754
 *   with that name exists, it is called to build the form array.
755
 *   Modules that need to generate the same form (or very similar forms)
756
 *   using different $form_ids can implement hook_forms(), which maps
757
 *   different $form_id values to the proper form constructor function.
758
 * @param $form_state
759
 *   A keyed array containing the current state of the form, including the
760
 *   additional arguments to drupal_get_form() or drupal_form_submit() in the
761
 *   'args' component of the array.
762
 */
763
function drupal_retrieve_form($form_id, &$form_state) {
764
  $forms = &drupal_static(__FUNCTION__);
765

    
766
  // Record the $form_id.
767
  $form_state['build_info']['form_id'] = $form_id;
768

    
769
  // Record the filepath of the include file containing the original form, so
770
  // the form builder callbacks can be loaded when the form is being rebuilt
771
  // from cache on a different path (such as 'system/ajax'). See
772
  // form_get_cache(). Don't do this in maintenance mode as Drupal may not be
773
  // fully bootstrapped (i.e. during installation) in which case
774
  // menu_get_item() is not available.
775
  if (!isset($form_state['build_info']['files']['menu']) && !defined('MAINTENANCE_MODE')) {
776
    $item = menu_get_item();
777
    if (!empty($item['include_file'])) {
778
      // Do not use form_load_include() here, as the file is already loaded.
779
      // Anyway, form_get_cache() is able to handle filepaths too.
780
      $form_state['build_info']['files']['menu'] = $item['include_file'];
781
    }
782
  }
783

    
784
  // We save two copies of the incoming arguments: one for modules to use
785
  // when mapping form ids to constructor functions, and another to pass to
786
  // the constructor function itself.
787
  $args = $form_state['build_info']['args'];
788

    
789
  // We first check to see if there's a function named after the $form_id.
790
  // If there is, we simply pass the arguments on to it to get the form.
791
  if (!function_exists($form_id)) {
792
    // In cases where many form_ids need to share a central constructor function,
793
    // such as the node editing form, modules can implement hook_forms(). It
794
    // maps one or more form_ids to the correct constructor functions.
795
    //
796
    // We cache the results of that hook to save time, but that only works
797
    // for modules that know all their form_ids in advance. (A module that
798
    // adds a small 'rate this comment' form to each comment in a list
799
    // would need a unique form_id for each one, for example.)
800
    //
801
    // So, we call the hook if $forms isn't yet populated, OR if it doesn't
802
    // yet have an entry for the requested form_id.
803
    if (!isset($forms) || !isset($forms[$form_id])) {
804
      $forms = module_invoke_all('forms', $form_id, $args);
805
    }
806
    $form_definition = $forms[$form_id];
807
    if (isset($form_definition['callback arguments'])) {
808
      $args = array_merge($form_definition['callback arguments'], $args);
809
    }
810
    if (isset($form_definition['callback'])) {
811
      $callback = $form_definition['callback'];
812
      $form_state['build_info']['base_form_id'] = $callback;
813
    }
814
    // In case $form_state['wrapper_callback'] is not defined already, we also
815
    // allow hook_forms() to define one.
816
    if (!isset($form_state['wrapper_callback']) && isset($form_definition['wrapper_callback'])) {
817
      $form_state['wrapper_callback'] = $form_definition['wrapper_callback'];
818
    }
819
  }
820

    
821
  $form = array();
822
  // We need to pass $form_state by reference in order for forms to modify it,
823
  // since call_user_func_array() requires that referenced variables are passed
824
  // explicitly.
825
  $args = array_merge(array($form, &$form_state), $args);
826

    
827
  // When the passed $form_state (not using drupal_get_form()) defines a
828
  // 'wrapper_callback', then it requests to invoke a separate (wrapping) form
829
  // builder function to pre-populate the $form array with form elements, which
830
  // the actual form builder function ($callback) expects. This allows for
831
  // pre-populating a form with common elements for certain forms, such as
832
  // back/next/save buttons in multi-step form wizards. See drupal_build_form().
833
  if (isset($form_state['wrapper_callback']) && function_exists($form_state['wrapper_callback'])) {
834
    $form = call_user_func_array($form_state['wrapper_callback'], $args);
835
    // Put the prepopulated $form into $args.
836
    $args[0] = $form;
837
  }
838

    
839
  // If $callback was returned by a hook_forms() implementation, call it.
840
  // Otherwise, call the function named after the form id.
841
  $form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
842
  $form['#form_id'] = $form_id;
843

    
844
  return $form;
845
}
846

    
847
/**
848
 * Processes a form submission.
849
 *
850
 * This function is the heart of form API. The form gets built, validated and in
851
 * appropriate cases, submitted and rebuilt.
852
 *
853
 * @param $form_id
854
 *   The unique string identifying the current form.
855
 * @param $form
856
 *   An associative array containing the structure of the form.
857
 * @param $form_state
858
 *   A keyed array containing the current state of the form. This
859
 *   includes the current persistent storage data for the form, and
860
 *   any data passed along by earlier steps when displaying a
861
 *   multi-step form. Additional information, like the sanitized $_POST
862
 *   data, is also accumulated here.
863
 */
864
function drupal_process_form($form_id, &$form, &$form_state) {
865
  $form_state['values'] = array();
866

    
867
  // With $_GET, these forms are always submitted if requested.
868
  if ($form_state['method'] == 'get' && !empty($form_state['always_process'])) {
869
    if (!isset($form_state['input']['form_build_id'])) {
870
      $form_state['input']['form_build_id'] = $form['#build_id'];
871
    }
872
    if (!isset($form_state['input']['form_id'])) {
873
      $form_state['input']['form_id'] = $form_id;
874
    }
875
    if (!isset($form_state['input']['form_token']) && isset($form['#token'])) {
876
      $form_state['input']['form_token'] = drupal_get_token($form['#token']);
877
    }
878
  }
879

    
880
  // form_builder() finishes building the form by calling element #process
881
  // functions and mapping user input, if any, to #value properties, and also
882
  // storing the values in $form_state['values']. We need to retain the
883
  // unprocessed $form in case it needs to be cached.
884
  $unprocessed_form = $form;
885
  $form = form_builder($form_id, $form, $form_state);
886

    
887
  // Only process the input if we have a correct form submission.
888
  if ($form_state['process_input']) {
889
    drupal_validate_form($form_id, $form, $form_state);
890

    
891
    // drupal_html_id() maintains a cache of element IDs it has seen,
892
    // so it can prevent duplicates. We want to be sure we reset that
893
    // cache when a form is processed, so scenarios that result in
894
    // the form being built behind the scenes and again for the
895
    // browser don't increment all the element IDs needlessly.
896
    if (!form_get_errors()) {
897
      // In case of errors, do not break HTML IDs of other forms.
898
      drupal_static_reset('drupal_html_id');
899
    }
900

    
901
    if ($form_state['submitted'] && !form_get_errors() && !$form_state['rebuild']) {
902
      // Execute form submit handlers.
903
      form_execute_handlers('submit', $form, $form_state);
904

    
905
      // We'll clear out the cached copies of the form and its stored data
906
      // here, as we've finished with them. The in-memory copies are still
907
      // here, though.
908
      if (!variable_get('cache', 0) && !empty($form_state['values']['form_build_id'])) {
909
        cache_clear_all('form_' . $form_state['values']['form_build_id'], 'cache_form');
910
        cache_clear_all('form_state_' . $form_state['values']['form_build_id'], 'cache_form');
911
      }
912

    
913
      // If batches were set in the submit handlers, we process them now,
914
      // possibly ending execution. We make sure we do not react to the batch
915
      // that is already being processed (if a batch operation performs a
916
      // drupal_form_submit).
917
      if ($batch =& batch_get() && !isset($batch['current_set'])) {
918
        // Store $form_state information in the batch definition.
919
        // We need the full $form_state when either:
920
        // - Some submit handlers were saved to be called during batch
921
        //   processing. See form_execute_handlers().
922
        // - The form is multistep.
923
        // In other cases, we only need the information expected by
924
        // drupal_redirect_form().
925
        if ($batch['has_form_submits'] || !empty($form_state['rebuild'])) {
926
          $batch['form_state'] = $form_state;
927
        }
928
        else {
929
          $batch['form_state'] = array_intersect_key($form_state, array_flip(array('programmed', 'rebuild', 'storage', 'no_redirect', 'redirect')));
930
        }
931

    
932
        $batch['progressive'] = !$form_state['programmed'];
933
        batch_process();
934

    
935
        // Execution continues only for programmatic forms.
936
        // For 'regular' forms, we get redirected to the batch processing
937
        // page. Form redirection will be handled in _batch_finished(),
938
        // after the batch is processed.
939
      }
940

    
941
      // Set a flag to indicate that the form has been processed and executed.
942
      $form_state['executed'] = TRUE;
943

    
944
      // Redirect the form based on values in $form_state.
945
      drupal_redirect_form($form_state);
946
    }
947

    
948
    // Don't rebuild or cache form submissions invoked via drupal_form_submit().
949
    if (!empty($form_state['programmed'])) {
950
      return;
951
    }
952

    
953
    // If $form_state['rebuild'] has been set and input has been processed
954
    // without validation errors, we are in a multi-step workflow that is not
955
    // yet complete. A new $form needs to be constructed based on the changes
956
    // made to $form_state during this request. Normally, a submit handler sets
957
    // $form_state['rebuild'] if a fully executed form requires another step.
958
    // However, for forms that have not been fully executed (e.g., Ajax
959
    // submissions triggered by non-buttons), there is no submit handler to set
960
    // $form_state['rebuild']. It would not make sense to redisplay the
961
    // identical form without an error for the user to correct, so we also
962
    // rebuild error-free non-executed forms, regardless of
963
    // $form_state['rebuild'].
964
    // @todo D8: Simplify this logic; considering Ajax and non-HTML front-ends,
965
    //   along with element-level #submit properties, it makes no sense to have
966
    //   divergent form execution based on whether the triggering element has
967
    //   #executes_submit_callback set to TRUE.
968
    if (($form_state['rebuild'] || !$form_state['executed']) && !form_get_errors()) {
969
      // Form building functions (e.g., _form_builder_handle_input_element())
970
      // may use $form_state['rebuild'] to determine if they are running in the
971
      // context of a rebuild, so ensure it is set.
972
      $form_state['rebuild'] = TRUE;
973
      $form = drupal_rebuild_form($form_id, $form_state, $form);
974
    }
975
  }
976

    
977
  // After processing the form, the form builder or a #process callback may
978
  // have set $form_state['cache'] to indicate that the form and form state
979
  // shall be cached. But the form may only be cached if the 'no_cache' property
980
  // is not set to TRUE. Only cache $form as it was prior to form_builder(),
981
  // because form_builder() must run for each request to accommodate new user
982
  // input. Rebuilt forms are not cached here, because drupal_rebuild_form()
983
  // already takes care of that.
984
  if (!$form_state['rebuild'] && $form_state['cache'] && empty($form_state['no_cache'])) {
985
    form_set_cache($form['#build_id'], $unprocessed_form, $form_state);
986
  }
987
}
988

    
989
/**
990
 * Prepares a structured form array.
991
 *
992
 * Adds required elements, executes any hook_form_alter functions, and
993
 * optionally inserts a validation token to prevent tampering.
994
 *
995
 * @param $form_id
996
 *   A unique string identifying the form for validation, submission,
997
 *   theming, and hook_form_alter functions.
998
 * @param $form
999
 *   An associative array containing the structure of the form.
1000
 * @param $form_state
1001
 *   A keyed array containing the current state of the form. Passed
1002
 *   in here so that hook_form_alter() calls can use it, as well.
1003
 */
1004
function drupal_prepare_form($form_id, &$form, &$form_state) {
1005
  global $user;
1006

    
1007
  $form['#type'] = 'form';
1008
  $form_state['programmed'] = isset($form_state['programmed']) ? $form_state['programmed'] : FALSE;
1009

    
1010
  // Fix the form method, if it is 'get' in $form_state, but not in $form.
1011
  if ($form_state['method'] == 'get' && !isset($form['#method'])) {
1012
    $form['#method'] = 'get';
1013
  }
1014

    
1015
  // Generate a new #build_id for this form, if none has been set already. The
1016
  // form_build_id is used as key to cache a particular build of the form. For
1017
  // multi-step forms, this allows the user to go back to an earlier build, make
1018
  // changes, and re-submit.
1019
  // @see drupal_build_form()
1020
  // @see drupal_rebuild_form()
1021
  if (!isset($form['#build_id'])) {
1022
    $form['#build_id'] = 'form-' . drupal_random_key();
1023
  }
1024
  $form['form_build_id'] = array(
1025
    '#type' => 'hidden',
1026
    '#value' => $form['#build_id'],
1027
    '#id' => $form['#build_id'],
1028
    '#name' => 'form_build_id',
1029
    // Form processing and validation requires this value, so ensure the
1030
    // submitted form value appears literally, regardless of custom #tree
1031
    // and #parents being set elsewhere.
1032
    '#parents' => array('form_build_id'),
1033
  );
1034

    
1035
  // Add a token, based on either #token or form_id, to any form displayed to
1036
  // authenticated users. This ensures that any submitted form was actually
1037
  // requested previously by the user and protects against cross site request
1038
  // forgeries.
1039
  // This does not apply to programmatically submitted forms. Furthermore, since
1040
  // tokens are session-bound and forms displayed to anonymous users are very
1041
  // likely cached, we cannot assign a token for them.
1042
  // During installation, there is no $user yet.
1043
  if (!empty($user->uid) && !$form_state['programmed']) {
1044
    // Form constructors may explicitly set #token to FALSE when cross site
1045
    // request forgery is irrelevant to the form, such as search forms.
1046
    if (isset($form['#token']) && $form['#token'] === FALSE) {
1047
      unset($form['#token']);
1048
    }
1049
    // Otherwise, generate a public token based on the form id.
1050
    else {
1051
      $form['#token'] = $form_id;
1052
      $form['form_token'] = array(
1053
        '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
1054
        '#type' => 'token',
1055
        '#default_value' => drupal_get_token($form['#token']),
1056
        // Form processing and validation requires this value, so ensure the
1057
        // submitted form value appears literally, regardless of custom #tree
1058
        // and #parents being set elsewhere.
1059
        '#parents' => array('form_token'),
1060
      );
1061
    }
1062
  }
1063

    
1064
  if (isset($form_id)) {
1065
    $form['form_id'] = array(
1066
      '#type' => 'hidden',
1067
      '#value' => $form_id,
1068
      '#id' => drupal_html_id("edit-$form_id"),
1069
      // Form processing and validation requires this value, so ensure the
1070
      // submitted form value appears literally, regardless of custom #tree
1071
      // and #parents being set elsewhere.
1072
      '#parents' => array('form_id'),
1073
    );
1074
  }
1075
  if (!isset($form['#id'])) {
1076
    $form['#id'] = drupal_html_id($form_id);
1077
  }
1078

    
1079
  $form += element_info('form');
1080
  $form += array('#tree' => FALSE, '#parents' => array());
1081

    
1082
  if (!isset($form['#validate'])) {
1083
    // Ensure that modules can rely on #validate being set.
1084
    $form['#validate'] = array();
1085
    // Check for a handler specific to $form_id.
1086
    if (function_exists($form_id . '_validate')) {
1087
      $form['#validate'][] = $form_id . '_validate';
1088
    }
1089
    // Otherwise check whether this is a shared form and whether there is a
1090
    // handler for the shared $form_id.
1091
    elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_validate')) {
1092
      $form['#validate'][] = $form_state['build_info']['base_form_id'] . '_validate';
1093
    }
1094
  }
1095

    
1096
  if (!isset($form['#submit'])) {
1097
    // Ensure that modules can rely on #submit being set.
1098
    $form['#submit'] = array();
1099
    // Check for a handler specific to $form_id.
1100
    if (function_exists($form_id . '_submit')) {
1101
      $form['#submit'][] = $form_id . '_submit';
1102
    }
1103
    // Otherwise check whether this is a shared form and whether there is a
1104
    // handler for the shared $form_id.
1105
    elseif (isset($form_state['build_info']['base_form_id']) && function_exists($form_state['build_info']['base_form_id'] . '_submit')) {
1106
      $form['#submit'][] = $form_state['build_info']['base_form_id'] . '_submit';
1107
    }
1108
  }
1109

    
1110
  // If no #theme has been set, automatically apply theme suggestions.
1111
  // theme_form() itself is in #theme_wrappers and not #theme. Therefore, the
1112
  // #theme function only has to care for rendering the inner form elements,
1113
  // not the form itself.
1114
  if (!isset($form['#theme'])) {
1115
    $form['#theme'] = array($form_id);
1116
    if (isset($form_state['build_info']['base_form_id'])) {
1117
      $form['#theme'][] = $form_state['build_info']['base_form_id'];
1118
    }
1119
  }
1120

    
1121
  // Invoke hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and
1122
  // hook_form_FORM_ID_alter() implementations.
1123
  $hooks = array('form');
1124
  if (isset($form_state['build_info']['base_form_id'])) {
1125
    $hooks[] = 'form_' . $form_state['build_info']['base_form_id'];
1126
  }
1127
  $hooks[] = 'form_' . $form_id;
1128
  drupal_alter($hooks, $form, $form_state, $form_id);
1129
}
1130

    
1131
/**
1132
 * Helper function to call form_set_error() if there is a token error.
1133
 */
1134
function _drupal_invalid_token_set_form_error() {
1135
  $path = current_path();
1136
  $query = drupal_get_query_parameters();
1137
  $url = url($path, array('query' => $query));
1138

    
1139
  // Setting this error will cause the form to fail validation.
1140
  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)));
1141
}
1142

    
1143
/**
1144
 * Validates user-submitted form data in the $form_state array.
1145
 *
1146
 * @param $form_id
1147
 *   A unique string identifying the form for validation, submission,
1148
 *   theming, and hook_form_alter functions.
1149
 * @param $form
1150
 *   An associative array containing the structure of the form, which is passed
1151
 *   by reference. Form validation handlers are able to alter the form structure
1152
 *   (like #process and #after_build callbacks during form building) in case of
1153
 *   a validation error. If a validation handler alters the form structure, it
1154
 *   is responsible for validating the values of changed form elements in
1155
 *   $form_state['values'] to prevent form submit handlers from receiving
1156
 *   unvalidated values.
1157
 * @param $form_state
1158
 *   A keyed array containing the current state of the form. The current
1159
 *   user-submitted data is stored in $form_state['values'], though
1160
 *   form validation functions are passed an explicit copy of the
1161
 *   values for the sake of simplicity. Validation handlers can also use
1162
 *   $form_state to pass information on to submit handlers. For example:
1163
 *     $form_state['data_for_submission'] = $data;
1164
 *   This technique is useful when validation requires file parsing,
1165
 *   web service requests, or other expensive requests that should
1166
 *   not be repeated in the submission step.
1167
 */
1168
function drupal_validate_form($form_id, &$form, &$form_state) {
1169
  $validated_forms = &drupal_static(__FUNCTION__, array());
1170

    
1171
  if (isset($validated_forms[$form_id]) && empty($form_state['must_validate'])) {
1172
    return;
1173
  }
1174

    
1175
  // If the session token was set by drupal_prepare_form(), ensure that it
1176
  // matches the current user's session. This is duplicate to code in
1177
  // form_builder() but left to protect any custom form handling code.
1178
  if (isset($form['#token'])) {
1179
    if (!drupal_valid_token($form_state['values']['form_token'], $form['#token']) || !empty($form_state['invalid_token'])) {
1180
      _drupal_invalid_token_set_form_error();
1181
      // Stop here and don't run any further validation handlers, because they
1182
      // could invoke non-safe operations which opens the door for CSRF
1183
      // vulnerabilities.
1184
      $validated_forms[$form_id] = TRUE;
1185
      return;
1186
    }
1187
  }
1188

    
1189
  _form_validate($form, $form_state, $form_id);
1190
  $validated_forms[$form_id] = TRUE;
1191

    
1192
  // If validation errors are limited then remove any non validated form values,
1193
  // so that only values that passed validation are left for submit callbacks.
1194
  if (isset($form_state['triggering_element']['#limit_validation_errors']) && $form_state['triggering_element']['#limit_validation_errors'] !== FALSE) {
1195
    $values = array();
1196
    foreach ($form_state['triggering_element']['#limit_validation_errors'] as $section) {
1197
      // If the section exists within $form_state['values'], even if the value
1198
      // is NULL, copy it to $values.
1199
      $section_exists = NULL;
1200
      $value = drupal_array_get_nested_value($form_state['values'], $section, $section_exists);
1201
      if ($section_exists) {
1202
        drupal_array_set_nested_value($values, $section, $value);
1203
      }
1204
    }
1205
    // A button's #value does not require validation, so for convenience we
1206
    // allow the value of the clicked button to be retained in its normal
1207
    // $form_state['values'] locations, even if these locations are not included
1208
    // in #limit_validation_errors.
1209
    if (isset($form_state['triggering_element']['#button_type'])) {
1210
      $button_value = $form_state['triggering_element']['#value'];
1211

    
1212
      // Like all input controls, the button value may be in the location
1213
      // dictated by #parents. If it is, copy it to $values, but do not override
1214
      // what may already be in $values.
1215
      $parents = $form_state['triggering_element']['#parents'];
1216
      if (!drupal_array_nested_key_exists($values, $parents) && drupal_array_get_nested_value($form_state['values'], $parents) === $button_value) {
1217
        drupal_array_set_nested_value($values, $parents, $button_value);
1218
      }
1219

    
1220
      // Additionally, form_builder() places the button value in
1221
      // $form_state['values'][BUTTON_NAME]. If it's still there, after
1222
      // validation handlers have run, copy it to $values, but do not override
1223
      // what may already be in $values.
1224
      $name = $form_state['triggering_element']['#name'];
1225
      if (!isset($values[$name]) && isset($form_state['values'][$name]) && $form_state['values'][$name] === $button_value) {
1226
        $values[$name] = $button_value;
1227
      }
1228
    }
1229
    $form_state['values'] = $values;
1230
  }
1231
}
1232

    
1233
/**
1234
 * Redirects the user to a URL after a form has been processed.
1235
 *
1236
 * After a form is submitted and processed, normally the user should be
1237
 * redirected to a new destination page. This function figures out what that
1238
 * destination should be, based on the $form_state array and the 'destination'
1239
 * query string in the request URL, and redirects the user there.
1240
 *
1241
 * Usually (for exceptions, see below) $form_state['redirect'] determines where
1242
 * to redirect the user. This can be set either to a string (the path to
1243
 * redirect to), or an array of arguments for drupal_goto(). If
1244
 * $form_state['redirect'] is missing, the user is usually (again, see below for
1245
 * exceptions) redirected back to the page they came from, where they should see
1246
 * a fresh, unpopulated copy of the form.
1247
 *
1248
 * Here is an example of how to set up a form to redirect to the path 'node':
1249
 * @code
1250
 * $form_state['redirect'] = 'node';
1251
 * @endcode
1252
 * And here is an example of how to redirect to 'node/123?foo=bar#baz':
1253
 * @code
1254
 * $form_state['redirect'] = array(
1255
 *   'node/123',
1256
 *   array(
1257
 *     'query' => array(
1258
 *       'foo' => 'bar',
1259
 *     ),
1260
 *     'fragment' => 'baz',
1261
 *   ),
1262
 * );
1263
 * @endcode
1264
 *
1265
 * There are several exceptions to the "usual" behavior described above:
1266
 * - If $form_state['programmed'] is TRUE, the form submission was usually
1267
 *   invoked via drupal_form_submit(), so any redirection would break the script
1268
 *   that invoked drupal_form_submit() and no redirection is done.
1269
 * - If $form_state['rebuild'] is TRUE, the form is being rebuilt, and no
1270
 *   redirection is done.
1271
 * - If $form_state['no_redirect'] is TRUE, redirection is disabled. This is
1272
 *   set, for instance, by ajax_get_form() to prevent redirection in Ajax
1273
 *   callbacks. $form_state['no_redirect'] should never be set or altered by
1274
 *   form builder functions or form validation/submit handlers.
1275
 * - If $form_state['redirect'] is set to FALSE, redirection is disabled.
1276
 * - If none of the above conditions has prevented redirection, then the
1277
 *   redirect is accomplished by calling drupal_goto(), passing in the value of
1278
 *   $form_state['redirect'] if it is set, or the current path if it is
1279
 *   not. drupal_goto() preferentially uses the value of $_GET['destination']
1280
 *   (the 'destination' URL query string) if it is present, so this will
1281
 *   override any values set by $form_state['redirect']. Note that during
1282
 *   installation, install_goto() is called in place of drupal_goto().
1283
 *
1284
 * @param $form_state
1285
 *   An associative array containing the current state of the form.
1286
 *
1287
 * @see drupal_process_form()
1288
 * @see drupal_build_form()
1289
 */
1290
function drupal_redirect_form($form_state) {
1291
  // Skip redirection for form submissions invoked via drupal_form_submit().
1292
  if (!empty($form_state['programmed'])) {
1293
    return;
1294
  }
1295
  // Skip redirection if rebuild is activated.
1296
  if (!empty($form_state['rebuild'])) {
1297
    return;
1298
  }
1299
  // Skip redirection if it was explicitly disallowed.
1300
  if (!empty($form_state['no_redirect'])) {
1301
    return;
1302
  }
1303
  // Only invoke drupal_goto() if redirect value was not set to FALSE.
1304
  if (!isset($form_state['redirect']) || $form_state['redirect'] !== FALSE) {
1305
    if (isset($form_state['redirect'])) {
1306
      if (is_array($form_state['redirect'])) {
1307
        call_user_func_array('drupal_goto', $form_state['redirect']);
1308
      }
1309
      else {
1310
        // This function can be called from the installer, which guarantees
1311
        // that $redirect will always be a string, so catch that case here
1312
        // and use the appropriate redirect function.
1313
        $function = drupal_installation_attempted() ? 'install_goto' : 'drupal_goto';
1314
        $function($form_state['redirect']);
1315
      }
1316
    }
1317
    drupal_goto(current_path(), array('query' => drupal_get_query_parameters()));
1318
  }
1319
}
1320

    
1321
/**
1322
 * Performs validation on form elements.
1323
 *
1324
 * First ensures required fields are completed, #maxlength is not exceeded, and
1325
 * selected options were in the list of options given to the user. Then calls
1326
 * user-defined validators.
1327
 *
1328
 * @param $elements
1329
 *   An associative array containing the structure of the form.
1330
 * @param $form_state
1331
 *   A keyed array containing the current state of the form. The current
1332
 *   user-submitted data is stored in $form_state['values'], though
1333
 *   form validation functions are passed an explicit copy of the
1334
 *   values for the sake of simplicity. Validation handlers can also
1335
 *   $form_state to pass information on to submit handlers. For example:
1336
 *     $form_state['data_for_submission'] = $data;
1337
 *   This technique is useful when validation requires file parsing,
1338
 *   web service requests, or other expensive requests that should
1339
 *   not be repeated in the submission step.
1340
 * @param $form_id
1341
 *   A unique string identifying the form for validation, submission,
1342
 *   theming, and hook_form_alter functions.
1343
 */
1344
function _form_validate(&$elements, &$form_state, $form_id = NULL) {
1345
  // Also used in the installer, pre-database setup.
1346
  $t = get_t();
1347

    
1348
  // Recurse through all children.
1349
  foreach (element_children($elements) as $key) {
1350
    if (isset($elements[$key]) && $elements[$key]) {
1351
      _form_validate($elements[$key], $form_state);
1352
    }
1353
  }
1354

    
1355
  // Validate the current input.
1356
  if (!isset($elements['#validated']) || !$elements['#validated']) {
1357
    // The following errors are always shown.
1358
    if (isset($elements['#needs_validation'])) {
1359
      // Verify that the value is not longer than #maxlength.
1360
      if (isset($elements['#maxlength']) && drupal_strlen($elements['#value']) > $elements['#maxlength']) {
1361
        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']))));
1362
      }
1363

    
1364
      if (isset($elements['#options']) && isset($elements['#value'])) {
1365
        if ($elements['#type'] == 'select') {
1366
          $options = form_options_flatten($elements['#options']);
1367
        }
1368
        else {
1369
          $options = $elements['#options'];
1370
        }
1371
        if (is_array($elements['#value'])) {
1372
          $value = in_array($elements['#type'], array('checkboxes', 'tableselect')) ? array_keys($elements['#value']) : $elements['#value'];
1373
          foreach ($value as $v) {
1374
            if (!isset($options[$v])) {
1375
              form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
1376
              watchdog('form', 'Illegal choice %choice in !name element.', array('%choice' => $v, '!name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
1377
            }
1378
          }
1379
        }
1380
        // Non-multiple select fields always have a value in HTML. If the user
1381
        // does not change the form, it will be the value of the first option.
1382
        // Because of this, form validation for the field will almost always
1383
        // pass, even if the user did not select anything. To work around this
1384
        // browser behavior, required select fields without a #default_value get
1385
        // an additional, first empty option. In case the submitted value is
1386
        // identical to the empty option's value, we reset the element's value
1387
        // to NULL to trigger the regular #required handling below.
1388
        // @see form_process_select()
1389
        elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
1390
          $elements['#value'] = NULL;
1391
          form_set_value($elements, NULL, $form_state);
1392
        }
1393
        elseif (!isset($options[$elements['#value']])) {
1394
          form_error($elements, $t('An illegal choice has been detected. Please contact the site administrator.'));
1395
          watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']), WATCHDOG_ERROR);
1396
        }
1397
      }
1398
    }
1399

    
1400
    // While this element is being validated, it may be desired that some calls
1401
    // to form_set_error() be suppressed and not result in a form error, so
1402
    // that a button that implements low-risk functionality (such as "Previous"
1403
    // or "Add more") that doesn't require all user input to be valid can still
1404
    // have its submit handlers triggered. The triggering element's
1405
    // #limit_validation_errors property contains the information for which
1406
    // errors are needed, and all other errors are to be suppressed. The
1407
    // #limit_validation_errors property is ignored if submit handlers will run,
1408
    // but the element doesn't have a #submit property, because it's too large a
1409
    // security risk to have any invalid user input when executing form-level
1410
    // submit handlers.
1411
    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']))) {
1412
      form_set_error(NULL, '', $form_state['triggering_element']['#limit_validation_errors']);
1413
    }
1414
    // If submit handlers won't run (due to the submission having been triggered
1415
    // by an element whose #executes_submit_callback property isn't TRUE), then
1416
    // it's safe to suppress all validation errors, and we do so by default,
1417
    // which is particularly useful during an Ajax submission triggered by a
1418
    // non-button. An element can override this default by setting the
1419
    // #limit_validation_errors property. For button element types,
1420
    // #limit_validation_errors defaults to FALSE (via system_element_info()),
1421
    // so that full validation is their default behavior.
1422
    elseif (isset($form_state['triggering_element']) && !isset($form_state['triggering_element']['#limit_validation_errors']) && !$form_state['submitted']) {
1423
      form_set_error(NULL, '', array());
1424
    }
1425
    // As an extra security measure, explicitly turn off error suppression if
1426
    // one of the above conditions wasn't met. Since this is also done at the
1427
    // end of this function, doing it here is only to handle the rare edge case
1428
    // where a validate handler invokes form processing of another form.
1429
    else {
1430
      drupal_static_reset('form_set_error:limit_validation_errors');
1431
    }
1432

    
1433
    // Make sure a value is passed when the field is required.
1434
    if (isset($elements['#needs_validation']) && $elements['#required']) {
1435
      // A simple call to empty() will not cut it here as some fields, like
1436
      // checkboxes, can return a valid value of '0'. Instead, check the
1437
      // length if it's a string, and the item count if it's an array.
1438
      // An unchecked checkbox has a #value of integer 0, different than string
1439
      // '0', which could be a valid value.
1440
      $is_empty_multiple = (!count($elements['#value']));
1441
      $is_empty_string = (is_string($elements['#value']) && drupal_strlen(trim($elements['#value'])) == 0);
1442
      $is_empty_value = ($elements['#value'] === 0);
1443
      if ($is_empty_multiple || $is_empty_string || $is_empty_value) {
1444
        // Although discouraged, a #title is not mandatory for form elements. In
1445
        // case there is no #title, we cannot set a form error message.
1446
        // Instead of setting no #title, form constructors are encouraged to set
1447
        // #title_display to 'invisible' to improve accessibility.
1448
        if (isset($elements['#title'])) {
1449
          form_error($elements, $t('!name field is required.', array('!name' => $elements['#title'])));
1450
        }
1451
        else {
1452
          form_error($elements);
1453
        }
1454
      }
1455
    }
1456

    
1457
    // Call user-defined form level validators.
1458
    if (isset($form_id)) {
1459
      form_execute_handlers('validate', $elements, $form_state);
1460
    }
1461
    // Call any element-specific validators. These must act on the element
1462
    // #value data.
1463
    elseif (isset($elements['#element_validate'])) {
1464
      foreach ($elements['#element_validate'] as $function) {
1465
        $function($elements, $form_state, $form_state['complete form']);
1466
      }
1467
    }
1468
    $elements['#validated'] = TRUE;
1469
  }
1470

    
1471
  // Done validating this element, so turn off error suppression.
1472
  // _form_validate() turns it on again when starting on the next element, if
1473
  // it's still appropriate to do so.
1474
  drupal_static_reset('form_set_error:limit_validation_errors');
1475
}
1476

    
1477
/**
1478
 * Executes custom validation and submission handlers for a given form.
1479
 *
1480
 * Button-specific handlers are checked first. If none exist, the function
1481
 * falls back to form-level handlers.
1482
 *
1483
 * @param $type
1484
 *   The type of handler to execute. 'validate' or 'submit' are the
1485
 *   defaults used by Form API.
1486
 * @param $form
1487
 *   An associative array containing the structure of the form.
1488
 * @param $form_state
1489
 *   A keyed array containing the current state of the form. If the user
1490
 *   submitted the form by clicking a button with custom handler functions
1491
 *   defined, those handlers will be stored here.
1492
 */
1493
function form_execute_handlers($type, &$form, &$form_state) {
1494
  $return = FALSE;
1495
  // If there was a button pressed, use its handlers.
1496
  if (isset($form_state[$type . '_handlers'])) {
1497
    $handlers = $form_state[$type . '_handlers'];
1498
  }
1499
  // Otherwise, check for a form-level handler.
1500
  elseif (isset($form['#' . $type])) {
1501
    $handlers = $form['#' . $type];
1502
  }
1503
  else {
1504
    $handlers = array();
1505
  }
1506

    
1507
  foreach ($handlers as $function) {
1508
    // Check if a previous _submit handler has set a batch, but make sure we
1509
    // do not react to a batch that is already being processed (for instance
1510
    // if a batch operation performs a drupal_form_submit()).
1511
    if ($type == 'submit' && ($batch =& batch_get()) && !isset($batch['id'])) {
1512
      // Some previous submit handler has set a batch. To ensure correct
1513
      // execution order, store the call in a special 'control' batch set.
1514
      // See _batch_next_set().
1515
      $batch['sets'][] = array('form_submit' => $function);
1516
      $batch['has_form_submits'] = TRUE;
1517
    }
1518
    else {
1519
      $function($form, $form_state);
1520
    }
1521
    $return = TRUE;
1522
  }
1523
  return $return;
1524
}
1525

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

    
1629
  if (isset($name) && !isset($form[$name])) {
1630
    $record = TRUE;
1631
    if (isset($sections)) {
1632
      // #limit_validation_errors is an array of "sections" within which user
1633
      // input must be valid. If the element is within one of these sections,
1634
      // the error must be recorded. Otherwise, it can be suppressed.
1635
      // #limit_validation_errors can be an empty array, in which case all
1636
      // errors are suppressed. For example, a "Previous" button might want its
1637
      // submit action to be triggered even if none of the submitted values are
1638
      // valid.
1639
      $record = FALSE;
1640
      foreach ($sections as $section) {
1641
        // Exploding by '][' reconstructs the element's #parents. If the
1642
        // reconstructed #parents begin with the same keys as the specified
1643
        // section, then the element's values are within the part of
1644
        // $form_state['values'] that the clicked button requires to be valid,
1645
        // so errors for this element must be recorded. As the exploded array
1646
        // will all be strings, we need to cast every value of the section
1647
        // array to string.
1648
        if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
1649
          $record = TRUE;
1650
          break;
1651
        }
1652
      }
1653
    }
1654
    if ($record) {
1655
      $form[$name] = $message;
1656
      if ($message) {
1657
        drupal_set_message($message, 'error');
1658
      }
1659
    }
1660
  }
1661

    
1662
  return $form;
1663
}
1664

    
1665
/**
1666
 * Clears all errors against all form elements made by form_set_error().
1667
 */
1668
function form_clear_error() {
1669
  drupal_static_reset('form_set_error');
1670
}
1671

    
1672
/**
1673
 * Returns an associative array of all errors.
1674
 */
1675
function form_get_errors() {
1676
  $form = form_set_error();
1677
  if (!empty($form)) {
1678
    return $form;
1679
  }
1680
}
1681

    
1682
/**
1683
 * Returns the error message filed against the given form element.
1684
 *
1685
 * Form errors higher up in the form structure override deeper errors as well as
1686
 * errors on the element itself.
1687
 */
1688
function form_get_error($element) {
1689
  $form = form_set_error();
1690
  $parents = array();
1691
  foreach ($element['#parents'] as $parent) {
1692
    $parents[] = $parent;
1693
    $key = implode('][', $parents);
1694
    if (isset($form[$key])) {
1695
      return $form[$key];
1696
    }
1697
  }
1698
}
1699

    
1700
/**
1701
 * Flags an element as having an error.
1702
 */
1703
function form_error(&$element, $message = '') {
1704
  form_set_error(implode('][', $element['#parents']), $message);
1705
}
1706

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

    
1803
  // Use element defaults.
1804
  if (isset($element['#type']) && empty($element['#defaults_loaded']) && ($info = element_info($element['#type']))) {
1805
    // Overlay $info onto $element, retaining preexisting keys in $element.
1806
    $element += $info;
1807
    $element['#defaults_loaded'] = TRUE;
1808
  }
1809
  // Assign basic defaults common for all form elements.
1810
  $element += array(
1811
    '#required' => FALSE,
1812
    '#attributes' => array(),
1813
    '#title_display' => 'before',
1814
  );
1815

    
1816
  // Special handling if we're on the top level form element.
1817
  if (isset($element['#type']) && $element['#type'] == 'form') {
1818
    if (!empty($element['#https']) && variable_get('https', FALSE) &&
1819
        !url_is_external($element['#action'])) {
1820
      global $base_root;
1821

    
1822
      // Not an external URL so ensure that it is secure.
1823
      $element['#action'] = str_replace('http://', 'https://', $base_root) . $element['#action'];
1824
    }
1825

    
1826
    // Store a reference to the complete form in $form_state prior to building
1827
    // the form. This allows advanced #process and #after_build callbacks to
1828
    // perform changes elsewhere in the form.
1829
    $form_state['complete form'] = &$element;
1830

    
1831
    // Set a flag if we have a correct form submission. This is always TRUE for
1832
    // programmed forms coming from drupal_form_submit(), or if the form_id coming
1833
    // from the POST data is set and matches the current form_id.
1834
    if ($form_state['programmed'] || (!empty($form_state['input']) && (isset($form_state['input']['form_id']) && ($form_state['input']['form_id'] == $form_id)))) {
1835
      $form_state['process_input'] = TRUE;
1836
      // If the session token was set by drupal_prepare_form(), ensure that it
1837
      // matches the current user's session.
1838
      $form_state['invalid_token'] = FALSE;
1839
      if (isset($element['#token'])) {
1840
        if (empty($form_state['input']['form_token']) || !drupal_valid_token($form_state['input']['form_token'], $element['#token'])) {
1841
          // Set an early form error to block certain input processing since that
1842
          // opens the door for CSRF vulnerabilities.
1843
          _drupal_invalid_token_set_form_error();
1844
          // This value is checked in _form_builder_handle_input_element().
1845
          $form_state['invalid_token'] = TRUE;
1846
          // Make sure file uploads do not get processed.
1847
          $_FILES = array();
1848
        }
1849
      }
1850
    }
1851
    else {
1852
      $form_state['process_input'] = FALSE;
1853
    }
1854

    
1855
    // All form elements should have an #array_parents property.
1856
    $element['#array_parents'] = array();
1857
  }
1858

    
1859
  if (!isset($element['#id'])) {
1860
    $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
1861
  }
1862
  // Handle input elements.
1863
  if (!empty($element['#input'])) {
1864
    _form_builder_handle_input_element($form_id, $element, $form_state);
1865
  }
1866
  // Allow for elements to expand to multiple elements, e.g., radios,
1867
  // checkboxes and files.
1868
  if (isset($element['#process']) && !$element['#processed']) {
1869
    foreach ($element['#process'] as $process) {
1870
      $element = $process($element, $form_state, $form_state['complete form']);
1871
    }
1872
    $element['#processed'] = TRUE;
1873
  }
1874

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

    
1878
  // Recurse through all child elements.
1879
  $count = 0;
1880
  foreach (element_children($element) as $key) {
1881
    // Prior to checking properties of child elements, their default properties
1882
    // need to be loaded.
1883
    if (isset($element[$key]['#type']) && empty($element[$key]['#defaults_loaded']) && ($info = element_info($element[$key]['#type']))) {
1884
      $element[$key] += $info;
1885
      $element[$key]['#defaults_loaded'] = TRUE;
1886
    }
1887

    
1888
    // Don't squash an existing tree value.
1889
    if (!isset($element[$key]['#tree'])) {
1890
      $element[$key]['#tree'] = $element['#tree'];
1891
    }
1892

    
1893
    // Deny access to child elements if parent is denied.
1894
    if (isset($element['#access']) && !$element['#access']) {
1895
      $element[$key]['#access'] = FALSE;
1896
    }
1897

    
1898
    // Make child elements inherit their parent's #disabled and #allow_focus
1899
    // values unless they specify their own.
1900
    foreach (array('#disabled', '#allow_focus') as $property) {
1901
      if (isset($element[$property]) && !isset($element[$key][$property])) {
1902
        $element[$key][$property] = $element[$property];
1903
      }
1904
    }
1905

    
1906
    // Don't squash existing parents value.
1907
    if (!isset($element[$key]['#parents'])) {
1908
      // Check to see if a tree of child elements is present. If so,
1909
      // continue down the tree if required.
1910
      $element[$key]['#parents'] = $element[$key]['#tree'] && $element['#tree'] ? array_merge($element['#parents'], array($key)) : array($key);
1911
    }
1912
    // Ensure #array_parents follows the actual form structure.
1913
    $array_parents = $element['#array_parents'];
1914
    $array_parents[] = $key;
1915
    $element[$key]['#array_parents'] = $array_parents;
1916

    
1917
    // Assign a decimal placeholder weight to preserve original array order.
1918
    if (!isset($element[$key]['#weight'])) {
1919
      $element[$key]['#weight'] = $count/1000;
1920
    }
1921
    else {
1922
      // If one of the child elements has a weight then we will need to sort
1923
      // later.
1924
      unset($element['#sorted']);
1925
    }
1926
    $element[$key] = form_builder($form_id, $element[$key], $form_state);
1927
    $count++;
1928
  }
1929

    
1930
  // The #after_build flag allows any piece of a form to be altered
1931
  // after normal input parsing has been completed.
1932
  if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
1933
    foreach ($element['#after_build'] as $function) {
1934
      $element = $function($element, $form_state);
1935
    }
1936
    $element['#after_build_done'] = TRUE;
1937
  }
1938

    
1939
  // If there is a file element, we need to flip a flag so later the
1940
  // form encoding can be set.
1941
  if (isset($element['#type']) && $element['#type'] == 'file') {
1942
    $form_state['has_file_element'] = TRUE;
1943
  }
1944

    
1945
  // Final tasks for the form element after form_builder() has run for all other
1946
  // elements.
1947
  if (isset($element['#type']) && $element['#type'] == 'form') {
1948
    // If there is a file element, we set the form encoding.
1949
    if (isset($form_state['has_file_element'])) {
1950
      $element['#attributes']['enctype'] = 'multipart/form-data';
1951
    }
1952

    
1953
    // Allow Ajax submissions to the form action to bypass verification. This is
1954
    // especially useful for multipart forms, which cannot be verified via a
1955
    // response header.
1956
    $element['#attached']['js'][] = array(
1957
      'type' => 'setting',
1958
      'data' => array(
1959
        'urlIsAjaxTrusted' => array(
1960
          $element['#action'] => TRUE,
1961
        ),
1962
      ),
1963
    );
1964

    
1965
    // If a form contains a single textfield, and the ENTER key is pressed
1966
    // within it, Internet Explorer submits the form with no POST data
1967
    // identifying any submit button. Other browsers submit POST data as though
1968
    // the user clicked the first button. Therefore, to be as consistent as we
1969
    // can be across browsers, if no 'triggering_element' has been identified
1970
    // yet, default it to the first button.
1971
    if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
1972
      $form_state['triggering_element'] = $form_state['buttons'][0];
1973
    }
1974

    
1975
    // If the triggering element specifies "button-level" validation and submit
1976
    // handlers to run instead of the default form-level ones, then add those to
1977
    // the form state.
1978
    foreach (array('validate', 'submit') as $type) {
1979
      if (isset($form_state['triggering_element']['#' . $type])) {
1980
        $form_state[$type . '_handlers'] = $form_state['triggering_element']['#' . $type];
1981
      }
1982
    }
1983

    
1984
    // If the triggering element executes submit handlers, then set the form
1985
    // state key that's needed for those handlers to run.
1986
    if (!empty($form_state['triggering_element']['#executes_submit_callback'])) {
1987
      $form_state['submitted'] = TRUE;
1988
    }
1989

    
1990
    // Special processing if the triggering element is a button.
1991
    if (isset($form_state['triggering_element']['#button_type'])) {
1992
      // Because there are several ways in which the triggering element could
1993
      // have been determined (including from input variables set by JavaScript
1994
      // or fallback behavior implemented for IE), and because buttons often
1995
      // have their #name property not derived from their #parents property, we
1996
      // can't assume that input processing that's happened up until here has
1997
      // resulted in $form_state['values'][BUTTON_NAME] being set. But it's
1998
      // common for forms to have several buttons named 'op' and switch on
1999
      // $form_state['values']['op'] during submit handler execution.
2000
      $form_state['values'][$form_state['triggering_element']['#name']] = $form_state['triggering_element']['#value'];
2001

    
2002
      // @todo Legacy support. Remove in Drupal 8.
2003
      $form_state['clicked_button'] = $form_state['triggering_element'];
2004
    }
2005
  }
2006
  return $element;
2007
}
2008

    
2009
/**
2010
 * Adds the #name and #value properties of an input element before rendering.
2011
 */
2012
function _form_builder_handle_input_element($form_id, &$element, &$form_state) {
2013
  static $safe_core_value_callbacks = array(
2014
    'form_type_token_value',
2015
    'form_type_textarea_value',
2016
    'form_type_textfield_value',
2017
    'form_type_checkbox_value',
2018
    'form_type_checkboxes_value',
2019
    'form_type_radios_value',
2020
    'form_type_password_confirm_value',
2021
    'form_type_select_value',
2022
    'form_type_tableselect_value',
2023
    'list_boolean_allowed_values_callback',
2024
  );
2025

    
2026
  if (!isset($element['#name'])) {
2027
    $name = array_shift($element['#parents']);
2028
    $element['#name'] = $name;
2029
    if ($element['#type'] == 'file') {
2030
      // To make it easier to handle $_FILES in file.inc, we place all
2031
      // file fields in the 'files' array. Also, we do not support
2032
      // nested file names.
2033
      $element['#name'] = 'files[' . $element['#name'] . ']';
2034
    }
2035
    elseif (count($element['#parents'])) {
2036
      $element['#name'] .= '[' . implode('][', $element['#parents']) . ']';
2037
    }
2038
    array_unshift($element['#parents'], $name);
2039
  }
2040

    
2041
  // Setting #disabled to TRUE results in user input being ignored, regardless
2042
  // of how the element is themed or whether JavaScript is used to change the
2043
  // control's attributes. However, it's good UI to let the user know that input
2044
  // is not wanted for the control. HTML supports two attributes for this:
2045
  // http://www.w3.org/TR/html401/interact/forms.html#h-17.12. If a form wants
2046
  // to start a control off with one of these attributes for UI purposes only,
2047
  // but still allow input to be processed if it's sumitted, it can set the
2048
  // desired attribute in #attributes directly rather than using #disabled.
2049
  // However, developers should think carefully about the accessibility
2050
  // implications of doing so: if the form expects input to be enterable under
2051
  // some condition triggered by JavaScript, how would someone who has
2052
  // JavaScript disabled trigger that condition? Instead, developers should
2053
  // consider whether a multi-step form would be more appropriate (#disabled can
2054
  // be changed from step to step). If one still decides to use JavaScript to
2055
  // affect when a control is enabled, then it is best for accessibility for the
2056
  // control to be enabled in the HTML, and disabled by JavaScript on document
2057
  // ready.
2058
  if (!empty($element['#disabled'])) {
2059
    if (!empty($element['#allow_focus'])) {
2060
      $element['#attributes']['readonly'] = 'readonly';
2061
    }
2062
    else {
2063
      $element['#attributes']['disabled'] = 'disabled';
2064
    }
2065
  }
2066

    
2067
  // With JavaScript or other easy hacking, input can be submitted even for
2068
  // elements with #access=FALSE or #disabled=TRUE. For security, these must
2069
  // not be processed. Forms that set #disabled=TRUE on an element do not
2070
  // expect input for the element, and even forms submitted with
2071
  // drupal_form_submit() must not be able to get around this. Forms that set
2072
  // #access=FALSE on an element usually allow access for some users, so forms
2073
  // submitted with drupal_form_submit() may bypass access restriction and be
2074
  // treated as high-privilege users instead.
2075
  $process_input = empty($element['#disabled']) && (($form_state['programmed'] && $form_state['programmed_bypass_access_check']) || ($form_state['process_input'] && (!isset($element['#access']) || $element['#access'])));
2076

    
2077
  // Set the element's #value property.
2078
  if (!isset($element['#value']) && !array_key_exists('#value', $element)) {
2079
    $value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';
2080
    if ($process_input) {
2081
      // Get the input for the current element. NULL values in the input need to
2082
      // be explicitly distinguished from missing input. (see below)
2083
      $input_exists = NULL;
2084
      $input = drupal_array_get_nested_value($form_state['input'], $element['#parents'], $input_exists);
2085
      // For browser-submitted forms, the submitted values do not contain values
2086
      // for certain elements (empty multiple select, unchecked checkbox).
2087
      // During initial form processing, we add explicit NULL values for such
2088
      // elements in $form_state['input']. When rebuilding the form, we can
2089
      // distinguish elements having NULL input from elements that were not part
2090
      // of the initially submitted form and can therefore use default values
2091
      // for the latter, if required. Programmatically submitted forms can
2092
      // submit explicit NULL values when calling drupal_form_submit(), so we do
2093
      // not modify $form_state['input'] for them.
2094
      if (!$input_exists && !$form_state['rebuild'] && !$form_state['programmed']) {
2095
        // Add the necessary parent keys to $form_state['input'] and sets the
2096
        // element's input value to NULL.
2097
        drupal_array_set_nested_value($form_state['input'], $element['#parents'], NULL);
2098
        $input_exists = TRUE;
2099
      }
2100
      // If we have input for the current element, assign it to the #value
2101
      // property, optionally filtered through $value_callback.
2102
      if ($input_exists) {
2103
        if (function_exists($value_callback)) {
2104
          // Skip all value callbacks except safe ones like text if the CSRF
2105
          // token was invalid.
2106
          if (empty($form_state['invalid_token']) || in_array($value_callback, $safe_core_value_callbacks)) {
2107
            $element['#value'] = $value_callback($element, $input, $form_state);
2108
          }
2109
          else {
2110
            $input = NULL;
2111
          }
2112
        }
2113
        if (!isset($element['#value']) && isset($input)) {
2114
          $element['#value'] = $input;
2115
        }
2116
      }
2117
      // Mark all posted values for validation.
2118
      if (isset($element['#value']) || (!empty($element['#required']))) {
2119
        $element['#needs_validation'] = TRUE;
2120
      }
2121
    }
2122
    // Load defaults.
2123
    if (!isset($element['#value'])) {
2124
      // Call #type_value without a second argument to request default_value handling.
2125
      if (function_exists($value_callback)) {
2126
        $element['#value'] = $value_callback($element, FALSE, $form_state);
2127
      }
2128
      // Final catch. If we haven't set a value yet, use the explicit default value.
2129
      // Avoid image buttons (which come with garbage value), so we only get value
2130
      // for the button actually clicked.
2131
      if (!isset($element['#value']) && empty($element['#has_garbage_value'])) {
2132
        $element['#value'] = isset($element['#default_value']) ? $element['#default_value'] : '';
2133
      }
2134
    }
2135
  }
2136

    
2137
  // Determine which element (if any) triggered the submission of the form and
2138
  // keep track of all the clickable buttons in the form for
2139
  // form_state_values_clean(). Enforce the same input processing restrictions
2140
  // as above.
2141
  if ($process_input) {
2142
    // Detect if the element triggered the submission via Ajax.
2143
    if (_form_element_triggered_scripted_submission($element, $form_state)) {
2144
      $form_state['triggering_element'] = $element;
2145
    }
2146

    
2147
    // If the form was submitted by the browser rather than via Ajax, then it
2148
    // can only have been triggered by a button, and we need to determine which
2149
    // button within the constraints of how browsers provide this information.
2150
    if (isset($element['#button_type'])) {
2151
      // All buttons in the form need to be tracked for
2152
      // form_state_values_clean() and for the form_builder() code that handles
2153
      // a form submission containing no button information in $_POST.
2154
      $form_state['buttons'][] = $element;
2155
      if (_form_button_was_clicked($element, $form_state)) {
2156
        $form_state['triggering_element'] = $element;
2157
      }
2158
    }
2159
  }
2160

    
2161
  // Set the element's value in $form_state['values'], but only, if its key
2162
  // does not exist yet (a #value_callback may have already populated it).
2163
  if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
2164
    form_set_value($element, $element['#value'], $form_state);
2165
  }
2166
}
2167

    
2168
/**
2169
 * Detects if an element triggered the form submission via Ajax.
2170
 *
2171
 * This detects button or non-button controls that trigger a form submission via
2172
 * Ajax or some other scriptable environment. These environments can set the
2173
 * special input key '_triggering_element_name' to identify the triggering
2174
 * element. If the name alone doesn't identify the element uniquely, the input
2175
 * key '_triggering_element_value' may also be set to require a match on element
2176
 * value. An example where this is needed is if there are several buttons all
2177
 * named 'op', and only differing in their value.
2178
 */
2179
function _form_element_triggered_scripted_submission($element, &$form_state) {
2180
  if (!empty($form_state['input']['_triggering_element_name']) && $element['#name'] == $form_state['input']['_triggering_element_name']) {
2181
    if (empty($form_state['input']['_triggering_element_value']) || $form_state['input']['_triggering_element_value'] == $element['#value']) {
2182
      return TRUE;
2183
    }
2184
  }
2185
  return FALSE;
2186
}
2187

    
2188
/**
2189
 * Determines if a given button triggered the form submission.
2190
 *
2191
 * This detects button controls that trigger a form submission by being clicked
2192
 * and having the click processed by the browser rather than being captured by
2193
 * JavaScript. Essentially, it detects if the button's name and value are part
2194
 * of the POST data, but with extra code to deal with the convoluted way in
2195
 * which browsers submit data for image button clicks.
2196
 *
2197
 * This does not detect button clicks processed by Ajax (that is done in
2198
 * _form_element_triggered_scripted_submission()) and it does not detect form
2199
 * submissions from Internet Explorer in response to an ENTER key pressed in a
2200
 * textfield (form_builder() has extra code for that).
2201
 *
2202
 * Because this function contains only part of the logic needed to determine
2203
 * $form_state['triggering_element'], it should not be called from anywhere
2204
 * other than within the Form API. Form validation and submit handlers needing
2205
 * to know which button was clicked should get that information from
2206
 * $form_state['triggering_element'].
2207
 */
2208
function _form_button_was_clicked($element, &$form_state) {
2209
  // First detect normal 'vanilla' button clicks. Traditionally, all
2210
  // standard buttons on a form share the same name (usually 'op'),
2211
  // and the specific return value is used to determine which was
2212
  // clicked. This ONLY works as long as $form['#name'] puts the
2213
  // value at the top level of the tree of $_POST data.
2214
  if (isset($form_state['input'][$element['#name']]) && $form_state['input'][$element['#name']] == $element['#value']) {
2215
    return TRUE;
2216
  }
2217
  // When image buttons are clicked, browsers do NOT pass the form element
2218
  // value in $_POST. Instead they pass an integer representing the
2219
  // coordinates of the click on the button image. This means that image
2220
  // buttons MUST have unique $form['#name'] values, but the details of
2221
  // their $_POST data should be ignored.
2222
  elseif (!empty($element['#has_garbage_value']) && isset($element['#value']) && $element['#value'] !== '') {
2223
    return TRUE;
2224
  }
2225
  return FALSE;
2226
}
2227

    
2228
/**
2229
 * Removes internal Form API elements and buttons from submitted form values.
2230
 *
2231
 * This function can be used when a module wants to store all submitted form
2232
 * values, for example, by serializing them into a single database column. In
2233
 * such cases, all internal Form API values and all form button elements should
2234
 * not be contained, and this function allows to remove them before the module
2235
 * proceeds to storage. Next to button elements, the following internal values
2236
 * are removed:
2237
 * - form_id
2238
 * - form_token
2239
 * - form_build_id
2240
 * - op
2241
 *
2242
 * @param $form_state
2243
 *   A keyed array containing the current state of the form, including
2244
 *   submitted form values; altered by reference.
2245
 */
2246
function form_state_values_clean(&$form_state) {
2247
  // Remove internal Form API values.
2248
  unset($form_state['values']['form_id'], $form_state['values']['form_token'], $form_state['values']['form_build_id'], $form_state['values']['op']);
2249

    
2250
  // Remove button values.
2251
  // form_builder() collects all button elements in a form. We remove the button
2252
  // value separately for each button element.
2253
  foreach ($form_state['buttons'] as $button) {
2254
    // Remove this button's value from the submitted form values by finding
2255
    // the value corresponding to this button.
2256
    // We iterate over the #parents of this button and move a reference to
2257
    // each parent in $form_state['values']. For example, if #parents is:
2258
    //   array('foo', 'bar', 'baz')
2259
    // then the corresponding $form_state['values'] part will look like this:
2260
    // array(
2261
    //   'foo' => array(
2262
    //     'bar' => array(
2263
    //       'baz' => 'button_value',
2264
    //     ),
2265
    //   ),
2266
    // )
2267
    // We start by (re)moving 'baz' to $last_parent, so we are able unset it
2268
    // at the end of the iteration. Initially, $values will contain a
2269
    // reference to $form_state['values'], but in the iteration we move the
2270
    // reference to $form_state['values']['foo'], and finally to
2271
    // $form_state['values']['foo']['bar'], which is the level where we can
2272
    // unset 'baz' (that is stored in $last_parent).
2273
    $parents = $button['#parents'];
2274
    $last_parent = array_pop($parents);
2275
    $key_exists = NULL;
2276
    $values = &drupal_array_get_nested_value($form_state['values'], $parents, $key_exists);
2277
    if ($key_exists && is_array($values)) {
2278
      unset($values[$last_parent]);
2279
    }
2280
  }
2281
}
2282

    
2283
/**
2284
 * Determines the value for an image button form element.
2285
 *
2286
 * @param $form
2287
 *   The form element whose value is being populated.
2288
 * @param $input
2289
 *   The incoming input to populate the form element. If this is FALSE,
2290
 *   the element's default value should be returned.
2291
 * @param $form_state
2292
 *   A keyed array containing the current state of the form.
2293
 *
2294
 * @return
2295
 *   The data that will appear in the $form_state['values'] collection
2296
 *   for this element. Return nothing to use the default.
2297
 */
2298
function form_type_image_button_value($form, $input, $form_state) {
2299
  if ($input !== FALSE) {
2300
    if (!empty($input)) {
2301
      // If we're dealing with Mozilla or Opera, we're lucky. It will
2302
      // return a proper value, and we can get on with things.
2303
      return $form['#return_value'];
2304
    }
2305
    else {
2306
      // Unfortunately, in IE we never get back a proper value for THIS
2307
      // form element. Instead, we get back two split values: one for the
2308
      // X and one for the Y coordinates on which the user clicked the
2309
      // button. We'll find this element in the #post data, and search
2310
      // in the same spot for its name, with '_x'.
2311
      $input = $form_state['input'];
2312
      foreach (explode('[', $form['#name']) as $element_name) {
2313
        // chop off the ] that may exist.
2314
        if (substr($element_name, -1) == ']') {
2315
          $element_name = substr($element_name, 0, -1);
2316
        }
2317

    
2318
        if (!isset($input[$element_name])) {
2319
          if (isset($input[$element_name . '_x'])) {
2320
            return $form['#return_value'];
2321
          }
2322
          return NULL;
2323
        }
2324
        $input = $input[$element_name];
2325
      }
2326
      return $form['#return_value'];
2327
    }
2328
  }
2329
}
2330

    
2331
/**
2332
 * Determines the value for a checkbox form element.
2333
 *
2334
 * @param $form
2335
 *   The form element whose value is being populated.
2336
 * @param $input
2337
 *   The incoming input to populate the form element. If this is FALSE,
2338
 *   the element's default value should be returned.
2339
 *
2340
 * @return
2341
 *   The data that will appear in the $element_state['values'] collection
2342
 *   for this element. Return nothing to use the default.
2343
 */
2344
function form_type_checkbox_value($element, $input = FALSE) {
2345
  if ($input === FALSE) {
2346
    // Use #default_value as the default value of a checkbox, except change
2347
    // NULL to 0, because _form_builder_handle_input_element() would otherwise
2348
    // replace NULL with empty string, but an empty string is a potentially
2349
    // valid value for a checked checkbox.
2350
    return isset($element['#default_value']) ? $element['#default_value'] : 0;
2351
  }
2352
  else {
2353
    // Checked checkboxes are submitted with a value (possibly '0' or ''):
2354
    // http://www.w3.org/TR/html401/interact/forms.html#successful-controls.
2355
    // For checked checkboxes, browsers submit the string version of
2356
    // #return_value, but we return the original #return_value. For unchecked
2357
    // checkboxes, browsers submit nothing at all, but
2358
    // _form_builder_handle_input_element() detects this, and calls this
2359
    // function with $input=NULL. Returning NULL from a value callback means to
2360
    // use the default value, which is not what is wanted when an unchecked
2361
    // checkbox is submitted, so we use integer 0 as the value indicating an
2362
    // unchecked checkbox. Therefore, modules must not use integer 0 as a
2363
    // #return_value, as doing so results in the checkbox always being treated
2364
    // as unchecked. The string '0' is allowed for #return_value. The most
2365
    // common use-case for setting #return_value to either 0 or '0' is for the
2366
    // first option within a 0-indexed array of checkboxes, and for this,
2367
    // form_process_checkboxes() uses the string rather than the integer.
2368
    return isset($input) ? $element['#return_value'] : 0;
2369
  }
2370
}
2371

    
2372
/**
2373
 * Determines the value for a checkboxes form element.
2374
 *
2375
 * @param $element
2376
 *   The form element whose value is being populated.
2377
 * @param $input
2378
 *   The incoming input to populate the form element. If this is FALSE,
2379
 *   the element's default value should be returned.
2380
 *
2381
 * @return
2382
 *   The data that will appear in the $element_state['values'] collection
2383
 *   for this element. Return nothing to use the default.
2384
 */
2385
function form_type_checkboxes_value($element, $input = FALSE) {
2386
  if ($input === FALSE) {
2387
    $value = array();
2388
    $element += array('#default_value' => array());
2389
    foreach ($element['#default_value'] as $key) {
2390
      $value[$key] = $key;
2391
    }
2392
    return $value;
2393
  }
2394
  elseif (is_array($input)) {
2395
    // Programmatic form submissions use NULL to indicate that a checkbox
2396
    // should be unchecked; see drupal_form_submit(). We therefore remove all
2397
    // NULL elements from the array before constructing the return value, to
2398
    // simulate the behavior of web browsers (which do not send unchecked
2399
    // checkboxes to the server at all). This will not affect non-programmatic
2400
    // form submissions, since all values in $_POST are strings.
2401
    foreach ($input as $key => $value) {
2402
      if (!isset($value)) {
2403
        unset($input[$key]);
2404
      }
2405
    }
2406
    return drupal_map_assoc($input);
2407
  }
2408
  else {
2409
    return array();
2410
  }
2411
}
2412

    
2413
/**
2414
 * Determines the value for a tableselect form element.
2415
 *
2416
 * @param $element
2417
 *   The form element whose value is being populated.
2418
 * @param $input
2419
 *   The incoming input to populate the form element. If this is FALSE,
2420
 *   the element's default value should be returned.
2421
 *
2422
 * @return
2423
 *   The data that will appear in the $element_state['values'] collection
2424
 *   for this element. Return nothing to use the default.
2425
 */
2426
function form_type_tableselect_value($element, $input = FALSE) {
2427
  // If $element['#multiple'] == FALSE, then radio buttons are displayed and
2428
  // the default value handling is used.
2429
  if (isset($element['#multiple']) && $element['#multiple']) {
2430
    // Checkboxes are being displayed with the default value coming from the
2431
    // keys of the #default_value property. This differs from the checkboxes
2432
    // element which uses the array values.
2433
    if ($input === FALSE) {
2434
      $value = array();
2435
      $element += array('#default_value' => array());
2436
      foreach ($element['#default_value'] as $key => $flag) {
2437
        if ($flag) {
2438
          $value[$key] = $key;
2439
        }
2440
      }
2441
      return $value;
2442
    }
2443
    else {
2444
      return is_array($input) ? drupal_map_assoc($input) : array();
2445
    }
2446
  }
2447
}
2448

    
2449
/**
2450
 * Form value callback: Determines the value for a #type radios form element.
2451
 *
2452
 * @param $element
2453
 *   The form element whose value is being populated.
2454
 * @param $input
2455
 *   (optional) The incoming input to populate the form element. If FALSE, the
2456
 *   element's default value is returned. Defaults to FALSE.
2457
 *
2458
 * @return
2459
 *   The data that will appear in the $element_state['values'] collection for
2460
 *   this element.
2461
 */
2462
function form_type_radios_value(&$element, $input = FALSE) {
2463
  if ($input !== FALSE) {
2464
    // When there's user input (including NULL), return it as the value.
2465
    // However, if NULL is submitted, _form_builder_handle_input_element() will
2466
    // apply the default value, and we want that validated against #options
2467
    // unless it's empty. (An empty #default_value, such as NULL or FALSE, can
2468
    // be used to indicate that no radio button is selected by default.)
2469
    if (!isset($input) && !empty($element['#default_value'])) {
2470
      $element['#needs_validation'] = TRUE;
2471
    }
2472
    return $input;
2473
  }
2474
  else {
2475
    // For default value handling, simply return #default_value. Additionally,
2476
    // for a NULL default value, set #has_garbage_value to prevent
2477
    // _form_builder_handle_input_element() converting the NULL to an empty
2478
    // string, so that code can distinguish between nothing selected and the
2479
    // selection of a radio button whose value is an empty string.
2480
    $value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
2481
    if (!isset($value)) {
2482
      $element['#has_garbage_value'] = TRUE;
2483
    }
2484
    return $value;
2485
  }
2486
}
2487

    
2488
/**
2489
 * Determines the value for a password_confirm form element.
2490
 *
2491
 * @param $element
2492
 *   The form element whose value is being populated.
2493
 * @param $input
2494
 *   The incoming input to populate the form element. If this is FALSE,
2495
 *   the element's default value should be returned.
2496
 *
2497
 * @return
2498
 *   The data that will appear in the $element_state['values'] collection
2499
 *   for this element. Return nothing to use the default.
2500
 */
2501
function form_type_password_confirm_value($element, $input = FALSE) {
2502
  if ($input === FALSE) {
2503
    $element += array('#default_value' => array());
2504
    return $element['#default_value'] + array('pass1' => '', 'pass2' => '');
2505
  }
2506
  $value = array('pass1' => '', 'pass2' => '');
2507
  // Throw out all invalid array keys; we only allow pass1 and pass2.
2508
  foreach ($value as $allowed_key => $default) {
2509
    // These should be strings, but allow other scalars since they might be
2510
    // valid input in programmatic form submissions. Any nested array values
2511
    // are ignored.
2512
    if (isset($input[$allowed_key]) && is_scalar($input[$allowed_key])) {
2513
      $value[$allowed_key] = (string) $input[$allowed_key];
2514
    }
2515
  }
2516
  return $value;
2517
}
2518

    
2519
/**
2520
 * Determines the value for a select form element.
2521
 *
2522
 * @param $element
2523
 *   The form element whose value is being populated.
2524
 * @param $input
2525
 *   The incoming input to populate the form element. If this is FALSE,
2526
 *   the element's default value should be returned.
2527
 *
2528
 * @return
2529
 *   The data that will appear in the $element_state['values'] collection
2530
 *   for this element. Return nothing to use the default.
2531
 */
2532
function form_type_select_value($element, $input = FALSE) {
2533
  if ($input !== FALSE) {
2534
    if (isset($element['#multiple']) && $element['#multiple']) {
2535
      // If an enabled multi-select submits NULL, it means all items are
2536
      // unselected. A disabled multi-select always submits NULL, and the
2537
      // default value should be used.
2538
      if (empty($element['#disabled'])) {
2539
        return (is_array($input)) ? drupal_map_assoc($input) : array();
2540
      }
2541
      else {
2542
        return (isset($element['#default_value']) && is_array($element['#default_value'])) ? $element['#default_value'] : array();
2543
      }
2544
    }
2545
    // Non-multiple select elements may have an empty option preprended to them
2546
    // (see form_process_select()). When this occurs, usually #empty_value is
2547
    // an empty string, but some forms set #empty_value to integer 0 or some
2548
    // other non-string constant. PHP receives all submitted form input as
2549
    // strings, but if the empty option is selected, set the value to match the
2550
    // empty value exactly.
2551
    elseif (isset($element['#empty_value']) && $input === (string) $element['#empty_value']) {
2552
      return $element['#empty_value'];
2553
    }
2554
    else {
2555
      return $input;
2556
    }
2557
  }
2558
}
2559

    
2560
/**
2561
 * Determines the value for a textarea form element.
2562
 *
2563
 * @param array $element
2564
 *   The form element whose value is being populated.
2565
 * @param mixed $input
2566
 *   The incoming input to populate the form element. If this is FALSE,
2567
 *   the element's default value should be returned.
2568
 *
2569
 * @return string
2570
 *   The data that will appear in the $element_state['values'] collection
2571
 *   for this element. Return nothing to use the default.
2572
 */
2573
function form_type_textarea_value($element, $input = FALSE) {
2574
  if ($input !== FALSE) {
2575
    // This should be a string, but allow other scalars since they might be
2576
    // valid input in programmatic form submissions.
2577
    return is_scalar($input) ? (string) $input : '';
2578
  }
2579
}
2580

    
2581
/**
2582
 * Determines the value for a textfield form element.
2583
 *
2584
 * @param $element
2585
 *   The form element whose value is being populated.
2586
 * @param $input
2587
 *   The incoming input to populate the form element. If this is FALSE,
2588
 *   the element's default value should be returned.
2589
 *
2590
 * @return
2591
 *   The data that will appear in the $element_state['values'] collection
2592
 *   for this element. Return nothing to use the default.
2593
 */
2594
function form_type_textfield_value($element, $input = FALSE) {
2595
  if ($input !== FALSE && $input !== NULL) {
2596
    // This should be a string, but allow other scalars since they might be
2597
    // valid input in programmatic form submissions.
2598
    if (!is_scalar($input)) {
2599
      $input = '';
2600
    }
2601
    return str_replace(array("\r", "\n"), '', (string) $input);
2602
  }
2603
}
2604

    
2605
/**
2606
 * Determines the value for form's token value.
2607
 *
2608
 * @param $element
2609
 *   The form element whose value is being populated.
2610
 * @param $input
2611
 *   The incoming input to populate the form element. If this is FALSE,
2612
 *   the element's default value should be returned.
2613
 *
2614
 * @return
2615
 *   The data that will appear in the $element_state['values'] collection
2616
 *   for this element. Return nothing to use the default.
2617
 */
2618
function form_type_token_value($element, $input = FALSE) {
2619
  if ($input !== FALSE) {
2620
    return (string) $input;
2621
  }
2622
}
2623

    
2624
/**
2625
 * Changes submitted form values during form validation.
2626
 *
2627
 * Use this function to change the submitted value of a form element in a form
2628
 * validation function, so that the changed value persists in $form_state
2629
 * through the remaining validation and submission handlers. It does not change
2630
 * the value in $element['#value'], only in $form_state['values'], which is
2631
 * where submitted values are always stored.
2632
 *
2633
 * Note that form validation functions are specified in the '#validate'
2634
 * component of the form array (the value of $form['#validate'] is an array of
2635
 * validation function names). If the form does not originate in your module,
2636
 * you can implement hook_form_FORM_ID_alter() to add a validation function
2637
 * to $form['#validate'].
2638
 *
2639
 * @param $element
2640
 *   The form element that should have its value updated; in most cases you can
2641
 *   just pass in the element from the $form array, although the only component
2642
 *   that is actually used is '#parents'. If constructing yourself, set
2643
 *   $element['#parents'] to be an array giving the path through the form
2644
 *   array's keys to the element whose value you want to update. For instance,
2645
 *   if you want to update the value of $form['elem1']['elem2'], which should be
2646
 *   stored in $form_state['values']['elem1']['elem2'], you would set
2647
 *   $element['#parents'] = array('elem1','elem2').
2648
 * @param $value
2649
 *   The new value for the form element.
2650
 * @param $form_state
2651
 *   Form state array where the value change should be recorded.
2652
 */
2653
function form_set_value($element, $value, &$form_state) {
2654
  drupal_array_set_nested_value($form_state['values'], $element['#parents'], $value, TRUE);
2655
}
2656

    
2657
/**
2658
 * Allows PHP array processing of multiple select options with the same value.
2659
 *
2660
 * Used for form select elements which need to validate HTML option groups
2661
 * and multiple options which may return the same value. Associative PHP arrays
2662
 * cannot handle these structures, since they share a common key.
2663
 *
2664
 * @param $array
2665
 *   The form options array to process.
2666
 *
2667
 * @return
2668
 *   An array with all hierarchical elements flattened to a single array.
2669
 */
2670
function form_options_flatten($array) {
2671
  // Always reset static var when first entering the recursion.
2672
  drupal_static_reset('_form_options_flatten');
2673
  return _form_options_flatten($array);
2674
}
2675

    
2676
/**
2677
 * Iterates over an array and returns a flat array with duplicate keys removed.
2678
 *
2679
 * This function also handles cases where objects are passed as array values.
2680
 */
2681
function _form_options_flatten($array) {
2682
  $return = &drupal_static(__FUNCTION__);
2683

    
2684
  foreach ($array as $key => $value) {
2685
    if (is_object($value)) {
2686
      _form_options_flatten($value->option);
2687
    }
2688
    elseif (is_array($value)) {
2689
      _form_options_flatten($value);
2690
    }
2691
    else {
2692
      $return[$key] = 1;
2693
    }
2694
  }
2695

    
2696
  return $return;
2697
}
2698

    
2699
/**
2700
 * Processes a select list form element.
2701
 *
2702
 * This process callback is mandatory for select fields, since all user agents
2703
 * automatically preselect the first available option of single (non-multiple)
2704
 * select lists.
2705
 *
2706
 * @param $element
2707
 *   The form element to process. Properties used:
2708
 *   - #multiple: (optional) Indicates whether one or more options can be
2709
 *     selected. Defaults to FALSE.
2710
 *   - #default_value: Must be NULL or not set in case there is no value for the
2711
 *     element yet, in which case a first default option is inserted by default.
2712
 *     Whether this first option is a valid option depends on whether the field
2713
 *     is #required or not.
2714
 *   - #required: (optional) Whether the user needs to select an option (TRUE)
2715
 *     or not (FALSE). Defaults to FALSE.
2716
 *   - #empty_option: (optional) The label to show for the first default option.
2717
 *     By default, the label is automatically set to "- Select -" for a required
2718
 *     field and "- None -" for an optional field.
2719
 *   - #empty_value: (optional) The value for the first default option, which is
2720
 *     used to determine whether the user submitted a value or not.
2721
 *     - If #required is TRUE, this defaults to '' (an empty string).
2722
 *     - If #required is not TRUE and this value isn't set, then no extra option
2723
 *       is added to the select control, leaving the control in a slightly
2724
 *       illogical state, because there's no way for the user to select nothing,
2725
 *       since all user agents automatically preselect the first available
2726
 *       option. But people are used to this being the behavior of select
2727
 *       controls.
2728
 *       @todo Address the above issue in Drupal 8.
2729
 *     - If #required is not TRUE and this value is set (most commonly to an
2730
 *       empty string), then an extra option (see #empty_option above)
2731
 *       representing a "non-selection" is added with this as its value.
2732
 *
2733
 * @see _form_validate()
2734
 */
2735
function form_process_select($element) {
2736
  // #multiple select fields need a special #name.
2737
  if ($element['#multiple']) {
2738
    $element['#attributes']['multiple'] = 'multiple';
2739
    $element['#attributes']['name'] = $element['#name'] . '[]';
2740
  }
2741
  // A non-#multiple select needs special handling to prevent user agents from
2742
  // preselecting the first option without intention. #multiple select lists do
2743
  // not get an empty option, as it would not make sense, user interface-wise.
2744
  else {
2745
    $required = $element['#required'];
2746
    // If the element is required and there is no #default_value, then add an
2747
    // empty option that will fail validation, so that the user is required to
2748
    // make a choice. Also, if there's a value for #empty_value or
2749
    // #empty_option, then add an option that represents emptiness.
2750
    if (($required && !isset($element['#default_value'])) || isset($element['#empty_value']) || isset($element['#empty_option'])) {
2751
      $element += array(
2752
        '#empty_value' => '',
2753
        '#empty_option' => $required ? t('- Select -') : t('- None -'),
2754
      );
2755
      // The empty option is prepended to #options and purposively not merged
2756
      // to prevent another option in #options mistakenly using the same value
2757
      // as #empty_value.
2758
      $empty_option = array($element['#empty_value'] => $element['#empty_option']);
2759
      $element['#options'] = $empty_option + $element['#options'];
2760
    }
2761
  }
2762
  return $element;
2763
}
2764

    
2765
/**
2766
 * Returns HTML for a select form element.
2767
 *
2768
 * It is possible to group options together; to do this, change the format of
2769
 * $options to an associative array in which the keys are group labels, and the
2770
 * values are associative arrays in the normal $options format.
2771
 *
2772
 * @param $variables
2773
 *   An associative array containing:
2774
 *   - element: An associative array containing the properties of the element.
2775
 *     Properties used: #title, #value, #options, #description, #extra,
2776
 *     #multiple, #required, #name, #attributes, #size.
2777
 *
2778
 * @ingroup themeable
2779
 */
2780
function theme_select($variables) {
2781
  $element = $variables['element'];
2782
  element_set_attributes($element, array('id', 'name', 'size'));
2783
  _form_set_class($element, array('form-select'));
2784

    
2785
  return '<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>';
2786
}
2787

    
2788
/**
2789
 * Converts an array of options into HTML, for use in select list form elements.
2790
 *
2791
 * This function calls itself recursively to obtain the values for each optgroup
2792
 * within the list of options and when the function encounters an object with
2793
 * an 'options' property inside $element['#options'].
2794
 *
2795
 * @param array $element
2796
 *   An associative array containing the following key-value pairs:
2797
 *   - #multiple: Optional Boolean indicating if the user may select more than
2798
 *     one item.
2799
 *   - #options: An associative array of options to render as HTML. Each array
2800
 *     value can be a string, an array, or an object with an 'option' property:
2801
 *     - A string or integer key whose value is a translated string is
2802
 *       interpreted as a single HTML option element. Do not use placeholders
2803
 *       that sanitize data: doing so will lead to double-escaping. Note that
2804
 *       the key will be visible in the HTML and could be modified by malicious
2805
 *       users, so don't put sensitive information in it.
2806
 *     - A translated string key whose value is an array indicates a group of
2807
 *       options. The translated string is used as the label attribute for the
2808
 *       optgroup. Do not use placeholders to sanitize data: doing so will lead
2809
 *       to double-escaping. The array should contain the options you wish to
2810
 *       group and should follow the syntax of $element['#options'].
2811
 *     - If the function encounters a string or integer key whose value is an
2812
 *       object with an 'option' property, the key is ignored, the contents of
2813
 *       the option property are interpreted as $element['#options'], and the
2814
 *       resulting HTML is added to the output.
2815
 *   - #value: Optional integer, string, or array representing which option(s)
2816
 *     to pre-select when the list is first displayed. The integer or string
2817
 *     must match the key of an option in the '#options' list. If '#multiple' is
2818
 *     TRUE, this can be an array of integers or strings.
2819
 * @param array|null $choices
2820
 *   (optional) Either an associative array of options in the same format as
2821
 *   $element['#options'] above, or NULL. This parameter is only used internally
2822
 *   and is not intended to be passed in to the initial function call.
2823
 *
2824
 * @return string
2825
 *   An HTML string of options and optgroups for use in a select form element.
2826
 */
2827
function form_select_options($element, $choices = NULL) {
2828
  if (!isset($choices)) {
2829
    $choices = $element['#options'];
2830
  }
2831
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
2832
  // isset() fails in this situation.
2833
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
2834
  $value_is_array = $value_valid && is_array($element['#value']);
2835
  $options = '';
2836
  foreach ($choices as $key => $choice) {
2837
    if (is_array($choice)) {
2838
      $options .= '<optgroup label="' . check_plain($key) . '">';
2839
      $options .= form_select_options($element, $choice);
2840
      $options .= '</optgroup>';
2841
    }
2842
    elseif (is_object($choice)) {
2843
      $options .= form_select_options($element, $choice->option);
2844
    }
2845
    else {
2846
      $key = (string) $key;
2847
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
2848
        $selected = ' selected="selected"';
2849
      }
2850
      else {
2851
        $selected = '';
2852
      }
2853
      $options .= '<option value="' . check_plain($key) . '"' . $selected . '>' . check_plain($choice) . '</option>';
2854
    }
2855
  }
2856
  return $options;
2857
}
2858

    
2859
/**
2860
 * Returns the indexes of a select element's options matching a given key.
2861
 *
2862
 * This function is useful if you need to modify the options that are
2863
 * already in a form element; for example, to remove choices which are
2864
 * not valid because of additional filters imposed by another module.
2865
 * One example might be altering the choices in a taxonomy selector.
2866
 * To correctly handle the case of a multiple hierarchy taxonomy,
2867
 * #options arrays can now hold an array of objects, instead of a
2868
 * direct mapping of keys to labels, so that multiple choices in the
2869
 * selector can have the same key (and label). This makes it difficult
2870
 * to manipulate directly, which is why this helper function exists.
2871
 *
2872
 * This function does not support optgroups (when the elements of the
2873
 * #options array are themselves arrays), and will return FALSE if
2874
 * arrays are found. The caller must either flatten/restore or
2875
 * manually do their manipulations in this case, since returning the
2876
 * index is not sufficient, and supporting this would make the
2877
 * "helper" too complicated and cumbersome to be of any help.
2878
 *
2879
 * As usual with functions that can return array() or FALSE, do not
2880
 * forget to use === and !== if needed.
2881
 *
2882
 * @param $element
2883
 *   The select element to search.
2884
 * @param $key
2885
 *   The key to look for.
2886
 *
2887
 * @return
2888
 *   An array of indexes that match the given $key. Array will be
2889
 *   empty if no elements were found. FALSE if optgroups were found.
2890
 */
2891
function form_get_options($element, $key) {
2892
  $keys = array();
2893
  foreach ($element['#options'] as $index => $choice) {
2894
    if (is_array($choice)) {
2895
      return FALSE;
2896
    }
2897
    elseif (is_object($choice)) {
2898
      if (isset($choice->option[$key])) {
2899
        $keys[] = $index;
2900
      }
2901
    }
2902
    elseif ($index == $key) {
2903
      $keys[] = $index;
2904
    }
2905
  }
2906
  return $keys;
2907
}
2908

    
2909
/**
2910
 * Returns HTML for a fieldset form element and its children.
2911
 *
2912
 * @param $variables
2913
 *   An associative array containing:
2914
 *   - element: An associative array containing the properties of the element.
2915
 *     Properties used: #attributes, #children, #collapsed, #collapsible,
2916
 *     #description, #id, #title, #value.
2917
 *
2918
 * @ingroup themeable
2919
 */
2920
function theme_fieldset($variables) {
2921
  $element = $variables['element'];
2922
  element_set_attributes($element, array('id'));
2923
  _form_set_class($element, array('form-wrapper'));
2924

    
2925
  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
2926
  if (!empty($element['#title'])) {
2927
    // Always wrap fieldset legends in a SPAN for CSS positioning.
2928
    $output .= '<legend><span class="fieldset-legend">' . $element['#title'] . '</span></legend>';
2929
  }
2930
  $output .= '<div class="fieldset-wrapper">';
2931
  if (!empty($element['#description'])) {
2932
    $output .= '<div class="fieldset-description">' . $element['#description'] . '</div>';
2933
  }
2934
  $output .= $element['#children'];
2935
  if (isset($element['#value'])) {
2936
    $output .= $element['#value'];
2937
  }
2938
  $output .= '</div>';
2939
  $output .= "</fieldset>\n";
2940
  return $output;
2941
}
2942

    
2943
/**
2944
 * Returns HTML for a radio button form element.
2945
 *
2946
 * Note: The input "name" attribute needs to be sanitized before output, which
2947
 *       is currently done by passing all attributes to drupal_attributes().
2948
 *
2949
 * @param $variables
2950
 *   An associative array containing:
2951
 *   - element: An associative array containing the properties of the element.
2952
 *     Properties used: #required, #return_value, #value, #attributes, #title,
2953
 *     #description
2954
 *
2955
 * @ingroup themeable
2956
 */
2957
function theme_radio($variables) {
2958
  $element = $variables['element'];
2959
  $element['#attributes']['type'] = 'radio';
2960
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
2961

    
2962
  if (isset($element['#return_value']) && $element['#value'] !== FALSE && $element['#value'] == $element['#return_value']) {
2963
    $element['#attributes']['checked'] = 'checked';
2964
  }
2965
  _form_set_class($element, array('form-radio'));
2966

    
2967
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
2968
}
2969

    
2970
/**
2971
 * Returns HTML for a set of radio button form elements.
2972
 *
2973
 * @param $variables
2974
 *   An associative array containing:
2975
 *   - element: An associative array containing the properties of the element.
2976
 *     Properties used: #title, #value, #options, #description, #required,
2977
 *     #attributes, #children.
2978
 *
2979
 * @ingroup themeable
2980
 */
2981
function theme_radios($variables) {
2982
  $element = $variables['element'];
2983
  $attributes = array();
2984
  if (isset($element['#id'])) {
2985
    $attributes['id'] = $element['#id'];
2986
  }
2987
  $attributes['class'] = 'form-radios';
2988
  if (!empty($element['#attributes']['class'])) {
2989
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
2990
  }
2991
  if (isset($element['#attributes']['title'])) {
2992
    $attributes['title'] = $element['#attributes']['title'];
2993
  }
2994
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
2995
}
2996

    
2997
/**
2998
 * Expand a password_confirm field into two text boxes.
2999
 */
3000
function form_process_password_confirm($element) {
3001
  $element['pass1'] =  array(
3002
    '#type' => 'password',
3003
    '#title' => t('Password'),
3004
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
3005
    '#required' => $element['#required'],
3006
    '#attributes' => array('class' => array('password-field')),
3007
  );
3008
  $element['pass2'] =  array(
3009
    '#type' => 'password',
3010
    '#title' => t('Confirm password'),
3011
    '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
3012
    '#required' => $element['#required'],
3013
    '#attributes' => array('class' => array('password-confirm')),
3014
  );
3015
  $element['#element_validate'] = array('password_confirm_validate');
3016
  $element['#tree'] = TRUE;
3017

    
3018
  if (isset($element['#size'])) {
3019
    $element['pass1']['#size'] = $element['pass2']['#size'] = $element['#size'];
3020
  }
3021

    
3022
  return $element;
3023
}
3024

    
3025
/**
3026
 * Validates a password_confirm element.
3027
 */
3028
function password_confirm_validate($element, &$element_state) {
3029
  $pass1 = trim($element['pass1']['#value']);
3030
  $pass2 = trim($element['pass2']['#value']);
3031
  if (!empty($pass1) || !empty($pass2)) {
3032
    if (strcmp($pass1, $pass2)) {
3033
      form_error($element, t('The specified passwords do not match.'));
3034
    }
3035
  }
3036
  elseif ($element['#required'] && !empty($element_state['input'])) {
3037
    form_error($element, t('Password field is required.'));
3038
  }
3039

    
3040
  // Password field must be converted from a two-element array into a single
3041
  // string regardless of validation results.
3042
  form_set_value($element['pass1'], NULL, $element_state);
3043
  form_set_value($element['pass2'], NULL, $element_state);
3044
  form_set_value($element, $pass1, $element_state);
3045

    
3046
  return $element;
3047

    
3048
}
3049

    
3050
/**
3051
 * Returns HTML for a date selection form element.
3052
 *
3053
 * @param $variables
3054
 *   An associative array containing:
3055
 *   - element: An associative array containing the properties of the element.
3056
 *     Properties used: #title, #value, #options, #description, #required,
3057
 *     #attributes.
3058
 *
3059
 * @ingroup themeable
3060
 */
3061
function theme_date($variables) {
3062
  $element = $variables['element'];
3063

    
3064
  $attributes = array();
3065
  if (isset($element['#id'])) {
3066
    $attributes['id'] = $element['#id'];
3067
  }
3068
  if (!empty($element['#attributes']['class'])) {
3069
    $attributes['class'] = (array) $element['#attributes']['class'];
3070
  }
3071
  $attributes['class'][] = 'container-inline';
3072

    
3073
  return '<div' . drupal_attributes($attributes) . '>' . drupal_render_children($element) . '</div>';
3074
}
3075

    
3076
/**
3077
 * Expands a date element into year, month, and day select elements.
3078
 */
3079
function form_process_date($element) {
3080
  // Default to current date
3081
  if (empty($element['#value'])) {
3082
    $element['#value'] = array(
3083
      'day' => format_date(REQUEST_TIME, 'custom', 'j'),
3084
      'month' => format_date(REQUEST_TIME, 'custom', 'n'),
3085
      'year' => format_date(REQUEST_TIME, 'custom', 'Y'),
3086
    );
3087
  }
3088

    
3089
  $element['#tree'] = TRUE;
3090

    
3091
  // Determine the order of day, month, year in the site's chosen date format.
3092
  $format = variable_get('date_format_short', 'm/d/Y - H:i');
3093
  $sort = array();
3094
  $sort['day'] = max(strpos($format, 'd'), strpos($format, 'j'));
3095
  $sort['month'] = max(strpos($format, 'm'), strpos($format, 'M'));
3096
  $sort['year'] = strpos($format, 'Y');
3097
  asort($sort);
3098
  $order = array_keys($sort);
3099

    
3100
  // Output multi-selector for date.
3101
  foreach ($order as $type) {
3102
    switch ($type) {
3103
      case 'day':
3104
        $options = drupal_map_assoc(range(1, 31));
3105
        $title = t('Day');
3106
        break;
3107

    
3108
      case 'month':
3109
        $options = drupal_map_assoc(range(1, 12), 'map_month');
3110
        $title = t('Month');
3111
        break;
3112

    
3113
      case 'year':
3114
        $options = drupal_map_assoc(range(1900, 2050));
3115
        $title = t('Year');
3116
        break;
3117
    }
3118

    
3119
    $element[$type] = array(
3120
      '#type' => 'select',
3121
      '#title' => $title,
3122
      '#title_display' => 'invisible',
3123
      '#value' => $element['#value'][$type],
3124
      '#attributes' => $element['#attributes'],
3125
      '#options' => $options,
3126
    );
3127
  }
3128

    
3129
  return $element;
3130
}
3131

    
3132
/**
3133
 * Validates the date type to prevent invalid dates (e.g., February 30, 2006).
3134
 */
3135
function date_validate($element) {
3136
  if (!checkdate($element['#value']['month'], $element['#value']['day'], $element['#value']['year'])) {
3137
    form_error($element, t('The specified date is invalid.'));
3138
  }
3139
}
3140

    
3141
/**
3142
 * Helper function for usage with drupal_map_assoc to display month names.
3143
 */
3144
function map_month($month) {
3145
  $months = &drupal_static(__FUNCTION__, array(
3146
    1 => 'Jan',
3147
    2 => 'Feb',
3148
    3 => 'Mar',
3149
    4 => 'Apr',
3150
    5 => 'May',
3151
    6 => 'Jun',
3152
    7 => 'Jul',
3153
    8 => 'Aug',
3154
    9 => 'Sep',
3155
    10 => 'Oct',
3156
    11 => 'Nov',
3157
    12 => 'Dec',
3158
  ));
3159
  return t($months[$month]);
3160
}
3161

    
3162
/**
3163
 * Sets the value for a weight element, with zero as a default.
3164
 */
3165
function weight_value(&$form) {
3166
  if (isset($form['#default_value'])) {
3167
    $form['#value'] = $form['#default_value'];
3168
  }
3169
  else {
3170
    $form['#value'] = 0;
3171
  }
3172
}
3173

    
3174
/**
3175
 * Expands a radios element into individual radio elements.
3176
 */
3177
function form_process_radios($element) {
3178
  if (count($element['#options']) > 0) {
3179
    $weight = 0;
3180
    foreach ($element['#options'] as $key => $choice) {
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
      // Generate the parents as the autogenerator does, so we will have a
3188
      // unique id for each radio button.
3189
      $parents_for_id = array_merge($element['#parents'], array($key));
3190
      $element[$key] += array(
3191
        '#type' => 'radio',
3192
        '#title' => $choice,
3193
        // The key is sanitized in drupal_attributes() during output from the
3194
        // theme function.
3195
        '#return_value' => $key,
3196
        // Use default or FALSE. A value of FALSE means that the radio button is
3197
        // not 'checked'.
3198
        '#default_value' => isset($element['#default_value']) ? $element['#default_value'] : FALSE,
3199
        '#attributes' => $element['#attributes'],
3200
        '#parents' => $element['#parents'],
3201
        '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
3202
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3203
        '#weight' => $weight,
3204
      );
3205
    }
3206
  }
3207
  return $element;
3208
}
3209

    
3210
/**
3211
 * Returns HTML for a checkbox form element.
3212
 *
3213
 * @param $variables
3214
 *   An associative array containing:
3215
 *   - element: An associative array containing the properties of the element.
3216
 *     Properties used: #id, #name, #attributes, #checked, #return_value.
3217
 *
3218
 * @ingroup themeable
3219
 */
3220
function theme_checkbox($variables) {
3221
  $element = $variables['element'];
3222
  $element['#attributes']['type'] = 'checkbox';
3223
  element_set_attributes($element, array('id', 'name', '#return_value' => 'value'));
3224

    
3225
  // Unchecked checkbox has #value of integer 0.
3226
  if (!empty($element['#checked'])) {
3227
    $element['#attributes']['checked'] = 'checked';
3228
  }
3229
  _form_set_class($element, array('form-checkbox'));
3230

    
3231
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3232
}
3233

    
3234
/**
3235
 * Returns HTML for a set of checkbox form elements.
3236
 *
3237
 * @param $variables
3238
 *   An associative array containing:
3239
 *   - element: An associative array containing the properties of the element.
3240
 *     Properties used: #children, #attributes.
3241
 *
3242
 * @ingroup themeable
3243
 */
3244
function theme_checkboxes($variables) {
3245
  $element = $variables['element'];
3246
  $attributes = array();
3247
  if (isset($element['#id'])) {
3248
    $attributes['id'] = $element['#id'];
3249
  }
3250
  $attributes['class'][] = 'form-checkboxes';
3251
  if (!empty($element['#attributes']['class'])) {
3252
    $attributes['class'] = array_merge($attributes['class'], $element['#attributes']['class']);
3253
  }
3254
  if (isset($element['#attributes']['title'])) {
3255
    $attributes['title'] = $element['#attributes']['title'];
3256
  }
3257
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';
3258
}
3259

    
3260
/**
3261
 * Adds form element theming to an element if its title or description is set.
3262
 *
3263
 * This is used as a pre render function for checkboxes and radios.
3264
 */
3265
function form_pre_render_conditional_form_element($element) {
3266
  $t = get_t();
3267
  // Set the element's title attribute to show #title as a tooltip, if needed.
3268
  if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
3269
    $element['#attributes']['title'] = $element['#title'];
3270
    if (!empty($element['#required'])) {
3271
      // Append an indication that this field is required.
3272
      $element['#attributes']['title'] .= ' (' . $t('Required') . ')';
3273
    }
3274
  }
3275

    
3276
  if (isset($element['#title']) || isset($element['#description'])) {
3277
    $element['#theme_wrappers'][] = 'form_element';
3278
  }
3279
  return $element;
3280
}
3281

    
3282
/**
3283
 * Sets the #checked property of a checkbox element.
3284
 */
3285
function form_process_checkbox($element, $form_state) {
3286
  $value = $element['#value'];
3287
  $return_value = $element['#return_value'];
3288
  // On form submission, the #value of an available and enabled checked
3289
  // checkbox is #return_value, and the #value of an available and enabled
3290
  // unchecked checkbox is integer 0. On not submitted forms, and for
3291
  // checkboxes with #access=FALSE or #disabled=TRUE, the #value is
3292
  // #default_value (integer 0 if #default_value is NULL). Most of the time,
3293
  // a string comparison of #value and #return_value is sufficient for
3294
  // determining the "checked" state, but a value of TRUE always means checked
3295
  // (even if #return_value is 'foo'), and a value of FALSE or integer 0 always
3296
  // means unchecked (even if #return_value is '' or '0').
3297
  if ($value === TRUE || $value === FALSE || $value === 0) {
3298
    $element['#checked'] = (bool) $value;
3299
  }
3300
  else {
3301
    // Compare as strings, so that 15 is not considered equal to '15foo', but 1
3302
    // is considered equal to '1'. This cast does not imply that either #value
3303
    // or #return_value is expected to be a string.
3304
    $element['#checked'] = ((string) $value === (string) $return_value);
3305
  }
3306
  return $element;
3307
}
3308

    
3309
/**
3310
 * Processes a checkboxes form element.
3311
 */
3312
function form_process_checkboxes($element) {
3313
  $value = is_array($element['#value']) ? $element['#value'] : array();
3314
  $element['#tree'] = TRUE;
3315
  if (count($element['#options']) > 0) {
3316
    if (!isset($element['#default_value']) || $element['#default_value'] == 0) {
3317
      $element['#default_value'] = array();
3318
    }
3319
    $weight = 0;
3320
    foreach ($element['#options'] as $key => $choice) {
3321
      // Integer 0 is not a valid #return_value, so use '0' instead.
3322
      // @see form_type_checkbox_value().
3323
      // @todo For Drupal 8, cast all integer keys to strings for consistency
3324
      //   with form_process_radios().
3325
      if ($key === 0) {
3326
        $key = '0';
3327
      }
3328
      // Maintain order of options as defined in #options, in case the element
3329
      // defines custom option sub-elements, but does not define all option
3330
      // sub-elements.
3331
      $weight += 0.001;
3332

    
3333
      $element += array($key => array());
3334
      $element[$key] += array(
3335
        '#type' => 'checkbox',
3336
        '#title' => $choice,
3337
        '#return_value' => $key,
3338
        '#default_value' => isset($value[$key]) ? $key : NULL,
3339
        '#attributes' => $element['#attributes'],
3340
        '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3341
        '#weight' => $weight,
3342
      );
3343
    }
3344
  }
3345
  return $element;
3346
}
3347

    
3348
/**
3349
 * Processes a form actions container element.
3350
 *
3351
 * @param $element
3352
 *   An associative array containing the properties and children of the
3353
 *   form actions container.
3354
 * @param $form_state
3355
 *   The $form_state array for the form this element belongs to.
3356
 *
3357
 * @return
3358
 *   The processed element.
3359
 */
3360
function form_process_actions($element, &$form_state) {
3361
  $element['#attributes']['class'][] = 'form-actions';
3362
  return $element;
3363
}
3364

    
3365
/**
3366
 * Processes a container element.
3367
 *
3368
 * @param $element
3369
 *   An associative array containing the properties and children of the
3370
 *   container.
3371
 * @param $form_state
3372
 *   The $form_state array for the form this element belongs to.
3373
 *
3374
 * @return
3375
 *   The processed element.
3376
 */
3377
function form_process_container($element, &$form_state) {
3378
  // Generate the ID of the element if it's not explicitly given.
3379
  if (!isset($element['#id'])) {
3380
    $element['#id'] = drupal_html_id(implode('-', $element['#parents']) . '-wrapper');
3381
  }
3382
  return $element;
3383
}
3384

    
3385
/**
3386
 * Returns HTML to wrap child elements in a container.
3387
 *
3388
 * Used for grouped form items. Can also be used as a theme wrapper for any
3389
 * renderable element, to surround it with a <div> and add attributes such as
3390
 * classes or an HTML ID.
3391
 *
3392
 * See the @link forms_api_reference.html Form API reference @endlink for more
3393
 * information on the #theme_wrappers render array property.
3394
 *
3395
 * @param $variables
3396
 *   An associative array containing:
3397
 *   - element: An associative array containing the properties of the element.
3398
 *     Properties used: #id, #attributes, #children.
3399
 *
3400
 * @ingroup themeable
3401
 */
3402
function theme_container($variables) {
3403
  $element = $variables['element'];
3404
  // Ensure #attributes is set.
3405
  $element += array('#attributes' => array());
3406

    
3407
  // Special handling for form elements.
3408
  if (isset($element['#array_parents'])) {
3409
    // Assign an html ID.
3410
    if (!isset($element['#attributes']['id'])) {
3411
      $element['#attributes']['id'] = $element['#id'];
3412
    }
3413
    // Add the 'form-wrapper' class.
3414
    $element['#attributes']['class'][] = 'form-wrapper';
3415
  }
3416

    
3417
  return '<div' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</div>';
3418
}
3419

    
3420
/**
3421
 * Returns HTML for a table with radio buttons or checkboxes.
3422
 *
3423
 * @param $variables
3424
 *   An associative array containing:
3425
 *   - element: An associative array containing the properties and children of
3426
 *     the tableselect element. Properties used: #header, #options, #empty,
3427
 *     and #js_select. The #options property is an array of selection options;
3428
 *     each array element of #options is an array of properties. These
3429
 *     properties can include #attributes, which is added to the
3430
 *     table row's HTML attributes; see theme_table(). An example of per-row
3431
 *     options:
3432
 *     @code
3433
 *     $options = array(
3434
 *       array(
3435
 *         'title' => 'How to Learn Drupal',
3436
 *         'content_type' => 'Article',
3437
 *         'status' => 'published',
3438
 *         '#attributes' => array('class' => array('article-row')),
3439
 *       ),
3440
 *       array(
3441
 *         'title' => 'Privacy Policy',
3442
 *         'content_type' => 'Page',
3443
 *         'status' => 'published',
3444
 *         '#attributes' => array('class' => array('page-row')),
3445
 *       ),
3446
 *     );
3447
 *     $header = array(
3448
 *       'title' => t('Title'),
3449
 *       'content_type' => t('Content type'),
3450
 *       'status' => t('Status'),
3451
 *     );
3452
 *     $form['table'] = array(
3453
 *       '#type' => 'tableselect',
3454
 *       '#header' => $header,
3455
 *       '#options' => $options,
3456
 *       '#empty' => t('No content available.'),
3457
 *     );
3458
 *     @endcode
3459
 *
3460
 * @ingroup themeable
3461
 */
3462
function theme_tableselect($variables) {
3463
  $element = $variables['element'];
3464
  $rows = array();
3465
  $header = $element['#header'];
3466
  if (!empty($element['#options'])) {
3467
    // Generate a table row for each selectable item in #options.
3468
    foreach (element_children($element) as $key) {
3469
      $row = array();
3470

    
3471
      $row['data'] = array();
3472
      if (isset($element['#options'][$key]['#attributes'])) {
3473
        $row += $element['#options'][$key]['#attributes'];
3474
      }
3475
      // Render the checkbox / radio element.
3476
      $row['data'][] = drupal_render($element[$key]);
3477

    
3478
      // As theme_table only maps header and row columns by order, create the
3479
      // correct order by iterating over the header fields.
3480
      foreach ($element['#header'] as $fieldname => $title) {
3481
        $row['data'][] = $element['#options'][$key][$fieldname];
3482
      }
3483
      $rows[] = $row;
3484
    }
3485
    // Add an empty header or a "Select all" checkbox to provide room for the
3486
    // checkboxes/radios in the first table column.
3487
    if ($element['#js_select']) {
3488
      // Add a "Select all" checkbox.
3489
      drupal_add_js('misc/tableselect.js');
3490
      array_unshift($header, array('class' => array('select-all')));
3491
    }
3492
    else {
3493
      // Add an empty header when radio buttons are displayed or a "Select all"
3494
      // checkbox is not desired.
3495
      array_unshift($header, '');
3496
    }
3497
  }
3498
  return theme('table', array('header' => $header, 'rows' => $rows, 'empty' => $element['#empty'], 'attributes' => $element['#attributes']));
3499
}
3500

    
3501
/**
3502
 * Creates checkbox or radio elements to populate a tableselect table.
3503
 *
3504
 * @param $element
3505
 *   An associative array containing the properties and children of the
3506
 *   tableselect element.
3507
 *
3508
 * @return
3509
 *   The processed element.
3510
 */
3511
function form_process_tableselect($element) {
3512

    
3513
  if ($element['#multiple']) {
3514
    $value = is_array($element['#value']) ? $element['#value'] : array();
3515
  }
3516
  else {
3517
    // Advanced selection behavior makes no sense for radios.
3518
    $element['#js_select'] = FALSE;
3519
  }
3520

    
3521
  $element['#tree'] = TRUE;
3522

    
3523
  if (count($element['#options']) > 0) {
3524
    if (!isset($element['#default_value']) || $element['#default_value'] === 0) {
3525
      $element['#default_value'] = array();
3526
    }
3527

    
3528
    // Create a checkbox or radio for each item in #options in such a way that
3529
    // the value of the tableselect element behaves as if it had been of type
3530
    // checkboxes or radios.
3531
    foreach ($element['#options'] as $key => $choice) {
3532
      // Do not overwrite manually created children.
3533
      if (!isset($element[$key])) {
3534
        if ($element['#multiple']) {
3535
          $title = '';
3536
          if (!empty($element['#options'][$key]['title']['data']['#title'])) {
3537
            $title = t('Update @title', array(
3538
              '@title' => $element['#options'][$key]['title']['data']['#title'],
3539
            ));
3540
          }
3541
          $element[$key] = array(
3542
            '#type' => 'checkbox',
3543
            '#title' => $title,
3544
            '#title_display' => 'invisible',
3545
            '#return_value' => $key,
3546
            '#default_value' => isset($value[$key]) ? $key : NULL,
3547
            '#attributes' => $element['#attributes'],
3548
          );
3549
        }
3550
        else {
3551
          // Generate the parents as the autogenerator does, so we will have a
3552
          // unique id for each radio button.
3553
          $parents_for_id = array_merge($element['#parents'], array($key));
3554
          $element[$key] = array(
3555
            '#type' => 'radio',
3556
            '#title' => '',
3557
            '#return_value' => $key,
3558
            '#default_value' => ($element['#default_value'] == $key) ? $key : NULL,
3559
            '#attributes' => $element['#attributes'],
3560
            '#parents' => $element['#parents'],
3561
            '#id' => drupal_html_id('edit-' . implode('-', $parents_for_id)),
3562
            '#ajax' => isset($element['#ajax']) ? $element['#ajax'] : NULL,
3563
          );
3564
        }
3565
        if (isset($element['#options'][$key]['#weight'])) {
3566
          $element[$key]['#weight'] = $element['#options'][$key]['#weight'];
3567
        }
3568
      }
3569
    }
3570
  }
3571
  else {
3572
    $element['#value'] = array();
3573
  }
3574
  return $element;
3575
}
3576

    
3577
/**
3578
 * Processes a machine-readable name form element.
3579
 *
3580
 * @param $element
3581
 *   The form element to process. Properties used:
3582
 *   - #machine_name: An associative array containing:
3583
 *     - exists: A function name to invoke for checking whether a submitted
3584
 *       machine name value already exists. The submitted value is passed as
3585
 *       argument. In most cases, an existing API or menu argument loader
3586
 *       function can be re-used. The callback is only invoked, if the submitted
3587
 *       value differs from the element's #default_value.
3588
 *     - source: (optional) The #array_parents of the form element containing
3589
 *       the human-readable name (i.e., as contained in the $form structure) to
3590
 *       use as source for the machine name. Defaults to array('name').
3591
 *     - label: (optional) A text to display as label for the machine name value
3592
 *       after the human-readable name form element. Defaults to "Machine name".
3593
 *     - replace_pattern: (optional) A regular expression (without delimiters)
3594
 *       matching disallowed characters in the machine name. Defaults to
3595
 *       '[^a-z0-9_]+'.
3596
 *     - replace: (optional) A character to replace disallowed characters in the
3597
 *       machine name via JavaScript. Defaults to '_' (underscore). When using a
3598
 *       different character, 'replace_pattern' needs to be set accordingly.
3599
 *     - error: (optional) A custom form error message string to show, if the
3600
 *       machine name contains disallowed characters.
3601
 *     - standalone: (optional) Whether the live preview should stay in its own
3602
 *       form element rather than in the suffix of the source element. Defaults
3603
 *       to FALSE.
3604
 *   - #maxlength: (optional) Should be set to the maximum allowed length of the
3605
 *     machine name. Defaults to 64.
3606
 *   - #disabled: (optional) Should be set to TRUE in case an existing machine
3607
 *     name must not be changed after initial creation.
3608
 */
3609
function form_process_machine_name($element, &$form_state) {
3610
  // Apply default form element properties.
3611
  $element += array(
3612
    '#title' => t('Machine-readable name'),
3613
    '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
3614
    '#machine_name' => array(),
3615
    '#field_prefix' => '',
3616
    '#field_suffix' => '',
3617
    '#suffix' => '',
3618
  );
3619
  // A form element that only wants to set one #machine_name property (usually
3620
  // 'source' only) would leave all other properties undefined, if the defaults
3621
  // were defined in hook_element_info(). Therefore, we apply the defaults here.
3622
  $element['#machine_name'] += array(
3623
    'source' => array('name'),
3624
    'target' => '#' . $element['#id'],
3625
    'label' => t('Machine name'),
3626
    'replace_pattern' => '[^a-z0-9_]+',
3627
    'replace' => '_',
3628
    'standalone' => FALSE,
3629
    'field_prefix' => $element['#field_prefix'],
3630
    'field_suffix' => $element['#field_suffix'],
3631
  );
3632

    
3633
  // By default, machine names are restricted to Latin alphanumeric characters.
3634
  // So, default to LTR directionality.
3635
  if (!isset($element['#attributes'])) {
3636
    $element['#attributes'] = array();
3637
  }
3638
  $element['#attributes'] += array('dir' => 'ltr');
3639

    
3640
  // The source element defaults to array('name'), but may have been overidden.
3641
  if (empty($element['#machine_name']['source'])) {
3642
    return $element;
3643
  }
3644

    
3645
  // Retrieve the form element containing the human-readable name from the
3646
  // complete form in $form_state. By reference, because we may need to append
3647
  // a #field_suffix that will hold the live preview.
3648
  $key_exists = NULL;
3649
  $source = drupal_array_get_nested_value($form_state['complete form'], $element['#machine_name']['source'], $key_exists);
3650
  if (!$key_exists) {
3651
    return $element;
3652
  }
3653

    
3654
  $suffix_id = $source['#id'] . '-machine-name-suffix';
3655
  $element['#machine_name']['suffix'] = '#' . $suffix_id;
3656

    
3657
  if ($element['#machine_name']['standalone']) {
3658
    $element['#suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3659
  }
3660
  else {
3661
    // Append a field suffix to the source form element, which will contain
3662
    // the live preview of the machine name.
3663
    $source += array('#field_suffix' => '');
3664
    $source['#field_suffix'] .= ' <small id="' . $suffix_id . '">&nbsp;</small>';
3665

    
3666
    $parents = array_merge($element['#machine_name']['source'], array('#field_suffix'));
3667
    drupal_array_set_nested_value($form_state['complete form'], $parents, $source['#field_suffix']);
3668
  }
3669

    
3670
  $js_settings = array(
3671
    'type' => 'setting',
3672
    'data' => array(
3673
      'machineName' => array(
3674
        '#' . $source['#id'] => $element['#machine_name'],
3675
      ),
3676
    ),
3677
  );
3678
  $element['#attached']['js'][] = 'misc/machine-name.js';
3679
  $element['#attached']['js'][] = $js_settings;
3680

    
3681
  return $element;
3682
}
3683

    
3684
/**
3685
 * Form element validation handler for machine_name elements.
3686
 *
3687
 * Note that #maxlength is validated by _form_validate() already.
3688
 */
3689
function form_validate_machine_name(&$element, &$form_state) {
3690
  // Verify that the machine name not only consists of replacement tokens.
3691
  if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
3692
    form_error($element, t('The machine-readable name must contain unique characters.'));
3693
  }
3694

    
3695
  // Verify that the machine name contains no disallowed characters.
3696
  if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
3697
    if (!isset($element['#machine_name']['error'])) {
3698
      // Since a hyphen is the most common alternative replacement character,
3699
      // a corresponding validation error message is supported here.
3700
      if ($element['#machine_name']['replace'] == '-') {
3701
        form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
3702
      }
3703
      // Otherwise, we assume the default (underscore).
3704
      else {
3705
        form_error($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
3706
      }
3707
    }
3708
    else {
3709
      form_error($element, $element['#machine_name']['error']);
3710
    }
3711
  }
3712

    
3713
  // Verify that the machine name is unique.
3714
  if ($element['#default_value'] !== $element['#value']) {
3715
    $function = $element['#machine_name']['exists'];
3716
    if ($function($element['#value'], $element, $form_state)) {
3717
      form_error($element, t('The machine-readable name is already in use. It must be unique.'));
3718
    }
3719
  }
3720
}
3721

    
3722
/**
3723
 * Arranges fieldsets into groups.
3724
 *
3725
 * @param $element
3726
 *   An associative array containing the properties and children of the
3727
 *   fieldset. Note that $element must be taken by reference here, so processed
3728
 *   child elements are taken over into $form_state.
3729
 * @param $form_state
3730
 *   The $form_state array for the form this fieldset belongs to.
3731
 *
3732
 * @return
3733
 *   The processed element.
3734
 */
3735
function form_process_fieldset(&$element, &$form_state) {
3736
  $parents = implode('][', $element['#parents']);
3737

    
3738
  // Each fieldset forms a new group. The #type 'vertical_tabs' basically only
3739
  // injects a new fieldset.
3740
  $form_state['groups'][$parents]['#group_exists'] = TRUE;
3741
  $element['#groups'] = &$form_state['groups'];
3742

    
3743
  // Process vertical tabs group member fieldsets.
3744
  if (isset($element['#group'])) {
3745
    // Add this fieldset to the defined group (by reference).
3746
    $group = $element['#group'];
3747
    $form_state['groups'][$group][] = &$element;
3748
  }
3749

    
3750
  // Contains form element summary functionalities.
3751
  $element['#attached']['library'][] = array('system', 'drupal.form');
3752

    
3753
  // The .form-wrapper class is required for #states to treat fieldsets like
3754
  // containers.
3755
  if (!isset($element['#attributes']['class'])) {
3756
    $element['#attributes']['class'] = array();
3757
  }
3758

    
3759
  // Collapsible fieldsets
3760
  if (!empty($element['#collapsible'])) {
3761
    $element['#attached']['library'][] = array('system', 'drupal.collapse');
3762
    $element['#attributes']['class'][] = 'collapsible';
3763
    if (!empty($element['#collapsed'])) {
3764
      $element['#attributes']['class'][] = 'collapsed';
3765
    }
3766
  }
3767

    
3768
  return $element;
3769
}
3770

    
3771
/**
3772
 * Adds members of this group as actual elements for rendering.
3773
 *
3774
 * @param $element
3775
 *   An associative array containing the properties and children of the
3776
 *   fieldset.
3777
 *
3778
 * @return
3779
 *   The modified element with all group members.
3780
 */
3781
function form_pre_render_fieldset($element) {
3782
  // Fieldsets may be rendered outside of a Form API context.
3783
  if (!isset($element['#parents']) || !isset($element['#groups'])) {
3784
    return $element;
3785
  }
3786
  // Inject group member elements belonging to this group.
3787
  $parents = implode('][', $element['#parents']);
3788
  $children = element_children($element['#groups'][$parents]);
3789
  if (!empty($children)) {
3790
    foreach ($children as $key) {
3791
      // Break references and indicate that the element should be rendered as
3792
      // group member.
3793
      $child = (array) $element['#groups'][$parents][$key];
3794
      $child['#group_fieldset'] = TRUE;
3795
      // Inject the element as new child element.
3796
      $element[] = $child;
3797

    
3798
      $sort = TRUE;
3799
    }
3800
    // Re-sort the element's children if we injected group member elements.
3801
    if (isset($sort)) {
3802
      $element['#sorted'] = FALSE;
3803
    }
3804
  }
3805

    
3806
  if (isset($element['#group'])) {
3807
    $group = $element['#group'];
3808
    // If this element belongs to a group, but the group-holding element does
3809
    // not exist, we need to render it (at its original location).
3810
    if (!isset($element['#groups'][$group]['#group_exists'])) {
3811
      // Intentionally empty to clarify the flow; we simply return $element.
3812
    }
3813
    // If we injected this element into the group, then we want to render it.
3814
    elseif (!empty($element['#group_fieldset'])) {
3815
      // Intentionally empty to clarify the flow; we simply return $element.
3816
    }
3817
    // Otherwise, this element belongs to a group and the group exists, so we do
3818
    // not render it.
3819
    elseif (element_children($element['#groups'][$group])) {
3820
      $element['#printed'] = TRUE;
3821
    }
3822
  }
3823

    
3824
  return $element;
3825
}
3826

    
3827
/**
3828
 * Creates a group formatted as vertical tabs.
3829
 *
3830
 * @param $element
3831
 *   An associative array containing the properties and children of the
3832
 *   fieldset.
3833
 * @param $form_state
3834
 *   The $form_state array for the form this vertical tab widget belongs to.
3835
 *
3836
 * @return
3837
 *   The processed element.
3838
 */
3839
function form_process_vertical_tabs($element, &$form_state) {
3840
  // Inject a new fieldset as child, so that form_process_fieldset() processes
3841
  // this fieldset like any other fieldset.
3842
  $element['group'] = array(
3843
    '#type' => 'fieldset',
3844
    '#theme_wrappers' => array(),
3845
    '#parents' => $element['#parents'],
3846
  );
3847

    
3848
  // The JavaScript stores the currently selected tab in this hidden
3849
  // field so that the active tab can be restored the next time the
3850
  // form is rendered, e.g. on preview pages or when form validation
3851
  // fails.
3852
  $name = implode('__', $element['#parents']);
3853
  if (isset($form_state['values'][$name . '__active_tab'])) {
3854
    $element['#default_tab'] = $form_state['values'][$name . '__active_tab'];
3855
  }
3856
  $element[$name . '__active_tab'] = array(
3857
    '#type' => 'hidden',
3858
    '#default_value' => $element['#default_tab'],
3859
    '#attributes' => array('class' => array('vertical-tabs-active-tab')),
3860
  );
3861

    
3862
  return $element;
3863
}
3864

    
3865
/**
3866
 * Returns HTML for an element's children fieldsets as vertical tabs.
3867
 *
3868
 * @param $variables
3869
 *   An associative array containing:
3870
 *   - element: An associative array containing the properties and children of
3871
 *     the fieldset. Properties used: #children.
3872
 *
3873
 * @ingroup themeable
3874
 */
3875
function theme_vertical_tabs($variables) {
3876
  $element = $variables['element'];
3877
  // Add required JavaScript and Stylesheet.
3878
  drupal_add_library('system', 'drupal.vertical-tabs');
3879

    
3880
  $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
3881
  $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
3882
  return $output;
3883
}
3884

    
3885
/**
3886
 * Returns HTML for a submit button form element.
3887
 *
3888
 * @param $variables
3889
 *   An associative array containing:
3890
 *   - element: An associative array containing the properties of the element.
3891
 *     Properties used: #attributes, #button_type, #name, #value.
3892
 *
3893
 * @ingroup themeable
3894
 */
3895
function theme_submit($variables) {
3896
  return theme('button', $variables['element']);
3897
}
3898

    
3899
/**
3900
 * Returns HTML for a button form element.
3901
 *
3902
 * @param $variables
3903
 *   An associative array containing:
3904
 *   - element: An associative array containing the properties of the element.
3905
 *     Properties used: #attributes, #button_type, #name, #value.
3906
 *
3907
 * @ingroup themeable
3908
 */
3909
function theme_button($variables) {
3910
  $element = $variables['element'];
3911
  $element['#attributes']['type'] = 'submit';
3912
  element_set_attributes($element, array('id', 'name', 'value'));
3913

    
3914
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3915
  if (!empty($element['#attributes']['disabled'])) {
3916
    $element['#attributes']['class'][] = 'form-button-disabled';
3917
  }
3918

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

    
3922
/**
3923
 * Returns HTML for an image button form element.
3924
 *
3925
 * @param $variables
3926
 *   An associative array containing:
3927
 *   - element: An associative array containing the properties of the element.
3928
 *     Properties used: #attributes, #button_type, #name, #value, #title, #src.
3929
 *
3930
 * @ingroup themeable
3931
 */
3932
function theme_image_button($variables) {
3933
  $element = $variables['element'];
3934
  $element['#attributes']['type'] = 'image';
3935
  element_set_attributes($element, array('id', 'name', 'value'));
3936

    
3937
  $element['#attributes']['src'] = file_create_url($element['#src']);
3938
  if (!empty($element['#title'])) {
3939
    $element['#attributes']['alt'] = $element['#title'];
3940
    $element['#attributes']['title'] = $element['#title'];
3941
  }
3942

    
3943
  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
3944
  if (!empty($element['#attributes']['disabled'])) {
3945
    $element['#attributes']['class'][] = 'form-button-disabled';
3946
  }
3947

    
3948
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
3949
}
3950

    
3951
/**
3952
 * Returns HTML for a hidden form element.
3953
 *
3954
 * @param $variables
3955
 *   An associative array containing:
3956
 *   - element: An associative array containing the properties of the element.
3957
 *     Properties used: #name, #value, #attributes.
3958
 *
3959
 * @ingroup themeable
3960
 */
3961
function theme_hidden($variables) {
3962
  $element = $variables['element'];
3963
  $element['#attributes']['type'] = 'hidden';
3964
  element_set_attributes($element, array('name', 'value'));
3965
  return '<input' . drupal_attributes($element['#attributes']) . " />\n";
3966
}
3967

    
3968
/**
3969
 * Process function to prepare autocomplete data.
3970
 *
3971
 * @param $element
3972
 *   A textfield or other element with a #autocomplete_path.
3973
 *
3974
 * @return array
3975
 *   The processed form element.
3976
 */
3977
function form_process_autocomplete($element) {
3978
  $element['#autocomplete_input'] = array();
3979
  if ($element['#autocomplete_path'] && drupal_valid_path($element['#autocomplete_path'])) {
3980
    $element['#autocomplete_input']['#id'] = $element['#id'] .'-autocomplete';
3981
    // Force autocomplete to use non-clean URLs since this protects against the
3982
    // browser interpreting the path plus search string as an actual file.
3983
    $current_clean_url = isset($GLOBALS['conf']['clean_url']) ? $GLOBALS['conf']['clean_url'] : NULL;
3984
    $GLOBALS['conf']['clean_url'] = 0;
3985
    // Force the script path to 'index.php', in case the server is not
3986
    // configured to find it automatically. Normally it is the responsibility
3987
    // of the site to do this themselves using hook_url_outbound_alter() (see
3988
    // url()) but since this code is forcing non-clean URLs on sites that don't
3989
    // normally use them, it is done here instead.
3990
    $element['#autocomplete_input']['#url_value'] = url($element['#autocomplete_path'], array('absolute' => TRUE, 'script' => 'index.php'));
3991
    $GLOBALS['conf']['clean_url'] = $current_clean_url;
3992
  }
3993
  return $element;
3994
}
3995

    
3996
/**
3997
 * Returns HTML for a textfield form element.
3998
 *
3999
 * @param $variables
4000
 *   An associative array containing:
4001
 *   - element: An associative array containing the properties of the element.
4002
 *     Properties used: #title, #value, #description, #size, #maxlength,
4003
 *     #required, #attributes, #autocomplete_path.
4004
 *
4005
 * @ingroup themeable
4006
 */
4007
function theme_textfield($variables) {
4008
  $element = $variables['element'];
4009
  $element['#attributes']['type'] = 'text';
4010
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
4011
  _form_set_class($element, array('form-text'));
4012

    
4013
  $extra = '';
4014
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input'])) {
4015
    drupal_add_library('system', 'drupal.autocomplete');
4016
    $element['#attributes']['class'][] = 'form-autocomplete';
4017

    
4018
    $attributes = array();
4019
    $attributes['type'] = 'hidden';
4020
    $attributes['id'] = $element['#autocomplete_input']['#id'];
4021
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
4022
    $attributes['disabled'] = 'disabled';
4023
    $attributes['class'][] = 'autocomplete';
4024
    $extra = '<input' . drupal_attributes($attributes) . ' />';
4025
  }
4026

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

    
4029
  return $output . $extra;
4030
}
4031

    
4032
/**
4033
 * Returns HTML for a form.
4034
 *
4035
 * @param $variables
4036
 *   An associative array containing:
4037
 *   - element: An associative array containing the properties of the element.
4038
 *     Properties used: #action, #method, #attributes, #children
4039
 *
4040
 * @ingroup themeable
4041
 */
4042
function theme_form($variables) {
4043
  $element = $variables['element'];
4044
  if (isset($element['#action'])) {
4045
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
4046
  }
4047
  element_set_attributes($element, array('method', 'id'));
4048
  if (empty($element['#attributes']['accept-charset'])) {
4049
    $element['#attributes']['accept-charset'] = "UTF-8";
4050
  }
4051
  // Anonymous DIV to satisfy XHTML compliance.
4052
  return '<form' . drupal_attributes($element['#attributes']) . '><div>' . $element['#children'] . '</div></form>';
4053
}
4054

    
4055
/**
4056
 * Returns HTML for a textarea form element.
4057
 *
4058
 * @param $variables
4059
 *   An associative array containing:
4060
 *   - element: An associative array containing the properties of the element.
4061
 *     Properties used: #title, #value, #description, #rows, #cols, #required,
4062
 *     #attributes
4063
 *
4064
 * @ingroup themeable
4065
 */
4066
function theme_textarea($variables) {
4067
  $element = $variables['element'];
4068
  element_set_attributes($element, array('id', 'name', 'cols', 'rows'));
4069
  _form_set_class($element, array('form-textarea'));
4070

    
4071
  $wrapper_attributes = array(
4072
    'class' => array('form-textarea-wrapper'),
4073
  );
4074

    
4075
  // Add resizable behavior.
4076
  if (!empty($element['#resizable'])) {
4077
    drupal_add_library('system', 'drupal.textarea');
4078
    $wrapper_attributes['class'][] = 'resizable';
4079
  }
4080

    
4081
  $output = '<div' . drupal_attributes($wrapper_attributes) . '>';
4082
  $output .= '<textarea' . drupal_attributes($element['#attributes']) . '>' . check_plain($element['#value']) . '</textarea>';
4083
  $output .= '</div>';
4084
  return $output;
4085
}
4086

    
4087
/**
4088
 * Returns HTML for a password form element.
4089
 *
4090
 * @param $variables
4091
 *   An associative array containing:
4092
 *   - element: An associative array containing the properties of the element.
4093
 *     Properties used: #title, #value, #description, #size, #maxlength,
4094
 *     #required, #attributes.
4095
 *
4096
 * @ingroup themeable
4097
 */
4098
function theme_password($variables) {
4099
  $element = $variables['element'];
4100
  $element['#attributes']['type'] = 'password';
4101
  element_set_attributes($element, array('id', 'name', 'size', 'maxlength'));
4102
  _form_set_class($element, array('form-text'));
4103

    
4104
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
4105
}
4106

    
4107
/**
4108
 * Expands a weight element into a select element.
4109
 */
4110
function form_process_weight($element) {
4111
  $element['#is_weight'] = TRUE;
4112

    
4113
  // If the number of options is small enough, use a select field.
4114
  $max_elements = variable_get('drupal_weight_select_max', DRUPAL_WEIGHT_SELECT_MAX);
4115
  if ($element['#delta'] <= $max_elements) {
4116
    $element['#type'] = 'select';
4117
    for ($n = (-1 * $element['#delta']); $n <= $element['#delta']; $n++) {
4118
      $weights[$n] = $n;
4119
    }
4120
    $element['#options'] = $weights;
4121
    $element += element_info('select');
4122
  }
4123
  // Otherwise, use a text field.
4124
  else {
4125
    $element['#type'] = 'textfield';
4126
    // Use a field big enough to fit most weights.
4127
    $element['#size'] = 10;
4128
    $element['#element_validate'] = array('element_validate_integer');
4129
    $element += element_info('textfield');
4130
  }
4131

    
4132
  return $element;
4133
}
4134

    
4135
/**
4136
 * Returns HTML for a file upload form element.
4137
 *
4138
 * For assistance with handling the uploaded file correctly, see the API
4139
 * provided by file.inc.
4140
 *
4141
 * @param $variables
4142
 *   An associative array containing:
4143
 *   - element: An associative array containing the properties of the element.
4144
 *     Properties used: #title, #name, #size, #description, #required,
4145
 *     #attributes.
4146
 *
4147
 * @ingroup themeable
4148
 */
4149
function theme_file($variables) {
4150
  $element = $variables['element'];
4151
  $element['#attributes']['type'] = 'file';
4152
  element_set_attributes($element, array('id', 'name', 'size'));
4153
  _form_set_class($element, array('form-file'));
4154

    
4155
  return '<input' . drupal_attributes($element['#attributes']) . ' />';
4156
}
4157

    
4158
/**
4159
 * Returns HTML for a form element.
4160
 *
4161
 * Each form element is wrapped in a DIV container having the following CSS
4162
 * classes:
4163
 * - form-item: Generic for all form elements.
4164
 * - form-type-#type: The internal element #type.
4165
 * - form-item-#name: The internal form element #name (usually derived from the
4166
 *   $form structure and set via form_builder()).
4167
 * - form-disabled: Only set if the form element is #disabled.
4168
 *
4169
 * In addition to the element itself, the DIV contains a label for the element
4170
 * based on the optional #title_display property, and an optional #description.
4171
 *
4172
 * The optional #title_display property can have these values:
4173
 * - before: The label is output before the element. This is the default.
4174
 *   The label includes the #title and the required marker, if #required.
4175
 * - after: The label is output after the element. For example, this is used
4176
 *   for radio and checkbox #type elements as set in system_element_info().
4177
 *   If the #title is empty but the field is #required, the label will
4178
 *   contain only the required marker.
4179
 * - invisible: Labels are critical for screen readers to enable them to
4180
 *   properly navigate through forms but can be visually distracting. This
4181
 *   property hides the label for everyone except screen readers.
4182
 * - attribute: Set the title attribute on the element to create a tooltip
4183
 *   but output no label element. This is supported only for checkboxes
4184
 *   and radios in form_pre_render_conditional_form_element(). It is used
4185
 *   where a visual label is not needed, such as a table of checkboxes where
4186
 *   the row and column provide the context. The tooltip will include the
4187
 *   title and required marker.
4188
 *
4189
 * If the #title property is not set, then the label and any required marker
4190
 * will not be output, regardless of the #title_display or #required values.
4191
 * This can be useful in cases such as the password_confirm element, which
4192
 * creates children elements that have their own labels and required markers,
4193
 * but the parent element should have neither. Use this carefully because a
4194
 * field without an associated label can cause accessibility challenges.
4195
 *
4196
 * @param $variables
4197
 *   An associative array containing:
4198
 *   - element: An associative array containing the properties of the element.
4199
 *     Properties used: #title, #title_display, #description, #id, #required,
4200
 *     #children, #type, #name.
4201
 *
4202
 * @ingroup themeable
4203
 */
4204
function theme_form_element($variables) {
4205
  $element = &$variables['element'];
4206

    
4207
  // This function is invoked as theme wrapper, but the rendered form element
4208
  // may not necessarily have been processed by form_builder().
4209
  $element += array(
4210
    '#title_display' => 'before',
4211
  );
4212

    
4213
  // Add element #id for #type 'item'.
4214
  if (isset($element['#markup']) && !empty($element['#id'])) {
4215
    $attributes['id'] = $element['#id'];
4216
  }
4217
  // Add element's #type and #name as class to aid with JS/CSS selectors.
4218
  $attributes['class'] = array('form-item');
4219
  if (!empty($element['#type'])) {
4220
    $attributes['class'][] = 'form-type-' . strtr($element['#type'], '_', '-');
4221
  }
4222
  if (!empty($element['#name'])) {
4223
    $attributes['class'][] = 'form-item-' . strtr($element['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
4224
  }
4225
  // Add a class for disabled elements to facilitate cross-browser styling.
4226
  if (!empty($element['#attributes']['disabled'])) {
4227
    $attributes['class'][] = 'form-disabled';
4228
  }
4229
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
4230

    
4231
  // If #title is not set, we don't display any label or required marker.
4232
  if (!isset($element['#title'])) {
4233
    $element['#title_display'] = 'none';
4234
  }
4235
  $prefix = isset($element['#field_prefix']) ? '<span class="field-prefix">' . $element['#field_prefix'] . '</span> ' : '';
4236
  $suffix = isset($element['#field_suffix']) ? ' <span class="field-suffix">' . $element['#field_suffix'] . '</span>' : '';
4237

    
4238
  switch ($element['#title_display']) {
4239
    case 'before':
4240
    case 'invisible':
4241
      $output .= ' ' . theme('form_element_label', $variables);
4242
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4243
      break;
4244

    
4245
    case 'after':
4246
      $output .= ' ' . $prefix . $element['#children'] . $suffix;
4247
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
4248
      break;
4249

    
4250
    case 'none':
4251
    case 'attribute':
4252
      // Output no label and no required marker, only the children.
4253
      $output .= ' ' . $prefix . $element['#children'] . $suffix . "\n";
4254
      break;
4255
  }
4256

    
4257
  if (!empty($element['#description'])) {
4258
    $output .= '<div class="description">' . $element['#description'] . "</div>\n";
4259
  }
4260

    
4261
  $output .= "</div>\n";
4262

    
4263
  return $output;
4264
}
4265

    
4266
/**
4267
 * Returns HTML for a marker for required form elements.
4268
 *
4269
 * @param $variables
4270
 *   An associative array containing:
4271
 *   - element: An associative array containing the properties of the element.
4272
 *
4273
 * @ingroup themeable
4274
 */
4275
function theme_form_required_marker($variables) {
4276
  // This is also used in the installer, pre-database setup.
4277
  $t = get_t();
4278
  $attributes = array(
4279
    'class' => 'form-required',
4280
    'title' => $t('This field is required.'),
4281
  );
4282
  return '<span' . drupal_attributes($attributes) . '>*</span>';
4283
}
4284

    
4285
/**
4286
 * Returns HTML for a form element label and required marker.
4287
 *
4288
 * Form element labels include the #title and a #required marker. The label is
4289
 * associated with the element itself by the element #id. Labels may appear
4290
 * before or after elements, depending on theme_form_element() and
4291
 * #title_display.
4292
 *
4293
 * This function will not be called for elements with no labels, depending on
4294
 * #title_display. For elements that have an empty #title and are not required,
4295
 * this function will output no label (''). For required elements that have an
4296
 * empty #title, this will output the required marker alone within the label.
4297
 * The label will use the #id to associate the marker with the field that is
4298
 * required. That is especially important for screenreader users to know
4299
 * which field is required.
4300
 *
4301
 * @param $variables
4302
 *   An associative array containing:
4303
 *   - element: An associative array containing the properties of the element.
4304
 *     Properties used: #required, #title, #id, #value, #description.
4305
 *
4306
 * @ingroup themeable
4307
 */
4308
function theme_form_element_label($variables) {
4309
  $element = $variables['element'];
4310
  // This is also used in the installer, pre-database setup.
4311
  $t = get_t();
4312

    
4313
  // If title and required marker are both empty, output no label.
4314
  if ((!isset($element['#title']) || $element['#title'] === '') && empty($element['#required'])) {
4315
    return '';
4316
  }
4317

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

    
4321
  $title = filter_xss_admin($element['#title']);
4322

    
4323
  $attributes = array();
4324
  // Style the label as class option to display inline with the element.
4325
  if ($element['#title_display'] == 'after') {
4326
    $attributes['class'] = 'option';
4327
  }
4328
  // Show label only to screen readers to avoid disruption in visual flows.
4329
  elseif ($element['#title_display'] == 'invisible') {
4330
    $attributes['class'] = 'element-invisible';
4331
  }
4332

    
4333
  if (!empty($element['#id'])) {
4334
    $attributes['for'] = $element['#id'];
4335
  }
4336

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

    
4341
/**
4342
 * Sets a form element's class attribute.
4343
 *
4344
 * Adds 'required' and 'error' classes as needed.
4345
 *
4346
 * @param $element
4347
 *   The form element.
4348
 * @param $name
4349
 *   Array of new class names to be added.
4350
 */
4351
function _form_set_class(&$element, $class = array()) {
4352
  if (!empty($class)) {
4353
    if (!isset($element['#attributes']['class'])) {
4354
      $element['#attributes']['class'] = array();
4355
    }
4356
    $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
4357
  }
4358
  // This function is invoked from form element theme functions, but the
4359
  // rendered form element may not necessarily have been processed by
4360
  // form_builder().
4361
  if (!empty($element['#required'])) {
4362
    $element['#attributes']['class'][] = 'required';
4363
  }
4364
  if (isset($element['#parents']) && form_get_error($element) !== NULL && !empty($element['#validated'])) {
4365
    $element['#attributes']['class'][] = 'error';
4366
  }
4367
}
4368

    
4369
/**
4370
 * Form element validation handler for integer elements.
4371
 */
4372
function element_validate_integer($element, &$form_state) {
4373
  $value = $element['#value'];
4374
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value)) {
4375
    form_error($element, t('%name must be an integer.', array('%name' => $element['#title'])));
4376
  }
4377
}
4378

    
4379
/**
4380
 * Form element validation handler for integer elements that must be positive.
4381
 */
4382
function element_validate_integer_positive($element, &$form_state) {
4383
  $value = $element['#value'];
4384
  if ($value !== '' && (!is_numeric($value) || intval($value) != $value || $value <= 0)) {
4385
    form_error($element, t('%name must be a positive integer.', array('%name' => $element['#title'])));
4386
  }
4387
}
4388

    
4389
/**
4390
 * Form element validation handler for number elements.
4391
 */
4392
function element_validate_number($element, &$form_state) {
4393
  $value = $element['#value'];
4394
  if ($value != '' && !is_numeric($value)) {
4395
    form_error($element, t('%name must be a number.', array('%name' => $element['#title'])));
4396
  }
4397
}
4398

    
4399
/**
4400
 * @} End of "defgroup form_api".
4401
 */
4402

    
4403
/**
4404
 * @defgroup batch Batch operations
4405
 * @{
4406
 * Creates and processes batch operations.
4407
 *
4408
 * Functions allowing forms processing to be spread out over several page
4409
 * requests, thus ensuring that the processing does not get interrupted
4410
 * because of a PHP timeout, while allowing the user to receive feedback
4411
 * on the progress of the ongoing operations.
4412
 *
4413
 * The API is primarily designed to integrate nicely with the Form API
4414
 * workflow, but can also be used by non-Form API scripts (like update.php)
4415
 * or even simple page callbacks (which should probably be used sparingly).
4416
 *
4417
 * Example:
4418
 * @code
4419
 * $batch = array(
4420
 *   'title' => t('Exporting'),
4421
 *   'operations' => array(
4422
 *     array('my_function_1', array($account->uid, 'story')),
4423
 *     array('my_function_2', array()),
4424
 *   ),
4425
 *   'finished' => 'my_finished_callback',
4426
 *   'file' => 'path_to_file_containing_myfunctions',
4427
 * );
4428
 * batch_set($batch);
4429
 * // Only needed if not inside a form _submit handler.
4430
 * // Setting redirect in batch_process.
4431
 * batch_process('node/1');
4432
 * @endcode
4433
 *
4434
 * Note: if the batch 'title', 'init_message', 'progress_message', or
4435
 * 'error_message' could contain any user input, it is the responsibility of
4436
 * the code calling batch_set() to sanitize them first with a function like
4437
 * check_plain() or filter_xss(). Furthermore, if the batch operation
4438
 * returns any user input in the 'results' or 'message' keys of $context,
4439
 * it must also sanitize them first.
4440
 *
4441
 * Sample callback_batch_operation():
4442
 * @code
4443
 * // Simple and artificial: load a node of a given type for a given user
4444
 * function my_function_1($uid, $type, &$context) {
4445
 *   // The $context array gathers batch context information about the execution (read),
4446
 *   // as well as 'return values' for the current operation (write)
4447
 *   // The following keys are provided :
4448
 *   // 'results' (read / write): The array of results gathered so far by
4449
 *   //   the batch processing, for the current operation to append its own.
4450
 *   // 'message' (write): A text message displayed in the progress page.
4451
 *   // The following keys allow for multi-step operations :
4452
 *   // 'sandbox' (read / write): An array that can be freely used to
4453
 *   //   store persistent data between iterations. It is recommended to
4454
 *   //   use this instead of $_SESSION, which is unsafe if the user
4455
 *   //   continues browsing in a separate window while the batch is processing.
4456
 *   // 'finished' (write): A float number between 0 and 1 informing
4457
 *   //   the processing engine of the completion level for the operation.
4458
 *   //   1 (or no value explicitly set) means the operation is finished
4459
 *   //   and the batch processing can continue to the next operation.
4460
 *
4461
 *   $node = node_load(array('uid' => $uid, 'type' => $type));
4462
 *   $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
4463
 *   $context['message'] = check_plain($node->title);
4464
 * }
4465
 *
4466
 * // More advanced example: multi-step operation - load all nodes, five by five
4467
 * function my_function_2(&$context) {
4468
 *   if (empty($context['sandbox'])) {
4469
 *     $context['sandbox']['progress'] = 0;
4470
 *     $context['sandbox']['current_node'] = 0;
4471
 *     $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
4472
 *   }
4473
 *   $limit = 5;
4474
 *   $result = db_select('node')
4475
 *     ->fields('node', array('nid'))
4476
 *     ->condition('nid', $context['sandbox']['current_node'], '>')
4477
 *     ->orderBy('nid')
4478
 *     ->range(0, $limit)
4479
 *     ->execute();
4480
 *   foreach ($result as $row) {
4481
 *     $node = node_load($row->nid, NULL, TRUE);
4482
 *     $context['results'][] = $node->nid . ' : ' . check_plain($node->title);
4483
 *     $context['sandbox']['progress']++;
4484
 *     $context['sandbox']['current_node'] = $node->nid;
4485
 *     $context['message'] = check_plain($node->title);
4486
 *   }
4487
 *   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
4488
 *     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
4489
 *   }
4490
 * }
4491
 * @endcode
4492
 *
4493
 * Sample callback_batch_finished():
4494
 * @code
4495
 * function my_finished_callback($success, $results, $operations) {
4496
 *   // The 'success' parameter means no fatal PHP errors were detected. All
4497
 *   // other error management should be handled using 'results'.
4498
 *   if ($success) {
4499
 *     $message = format_plural(count($results), 'One post processed.', '@count posts processed.');
4500
 *   }
4501
 *   else {
4502
 *     $message = t('Finished with an error.');
4503
 *   }
4504
 *   drupal_set_message($message);
4505
 *   // Providing data for the redirected page is done through $_SESSION.
4506
 *   foreach ($results as $result) {
4507
 *     $items[] = t('Loaded node %title.', array('%title' => $result));
4508
 *   }
4509
 *   $_SESSION['my_batch_results'] = $items;
4510
 * }
4511
 * @endcode
4512
 */
4513

    
4514
/**
4515
 * Adds a new batch.
4516
 *
4517
 * Batch operations are added as new batch sets. Batch sets are used to spread
4518
 * processing (primarily, but not exclusively, forms processing) over several
4519
 * page requests. This helps to ensure that the processing is not interrupted
4520
 * due to PHP timeouts, while users are still able to receive feedback on the
4521
 * progress of the ongoing operations. Combining related operations into
4522
 * distinct batch sets provides clean code independence for each batch set,
4523
 * ensuring that two or more batches, submitted independently, can be processed
4524
 * without mutual interference. Each batch set may specify its own set of
4525
 * operations and results, produce its own UI messages, and trigger its own
4526
 * 'finished' callback. Batch sets are processed sequentially, with the progress
4527
 * bar starting afresh for each new set.
4528
 *
4529
 * @param $batch_definition
4530
 *   An associative array defining the batch, with the following elements (all
4531
 *   are optional except as noted):
4532
 *   - operations: (required) Array of operations to be performed, where each
4533
 *     item is an array consisting of the name of an implementation of
4534
 *     callback_batch_operation() and an array of parameter.
4535
 *     Example:
4536
 *     @code
4537
 *     array(
4538
 *       array('callback_batch_operation_1', array($arg1)),
4539
 *       array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
4540
 *     )
4541
 *     @endcode
4542
 *   - title: A safe, translated string to use as the title for the progress
4543
 *     page. Defaults to t('Processing').
4544
 *   - init_message: Message displayed while the processing is initialized.
4545
 *     Defaults to t('Initializing.').
4546
 *   - progress_message: Message displayed while processing the batch. Available
4547
 *     placeholders are @current, @remaining, @total, @percentage, @estimate and
4548
 *     @elapsed. Defaults to t('Completed @current of @total.').
4549
 *   - error_message: Message displayed if an error occurred while processing
4550
 *     the batch. Defaults to t('An error has occurred.').
4551
 *   - finished: Name of an implementation of callback_batch_finished(). This is
4552
 *     executed after the batch has completed. This should be used to perform
4553
 *     any result massaging that may be needed, and possibly save data in
4554
 *     $_SESSION for display after final page redirection.
4555
 *   - file: Path to the file containing the definitions of the 'operations' and
4556
 *     'finished' functions, for instance if they don't reside in the main
4557
 *     .module file. The path should be relative to base_path(), and thus should
4558
 *     be built using drupal_get_path().
4559
 *   - css: Array of paths to CSS files to be used on the progress page.
4560
 *   - url_options: options passed to url() when constructing redirect URLs for
4561
 *     the batch.
4562
 */
4563
function batch_set($batch_definition) {
4564
  if ($batch_definition) {
4565
    $batch =& batch_get();
4566

    
4567
    // Initialize the batch if needed.
4568
    if (empty($batch)) {
4569
      $batch = array(
4570
        'sets' => array(),
4571
        'has_form_submits' => FALSE,
4572
      );
4573
    }
4574

    
4575
    // Base and default properties for the batch set.
4576
    // Use get_t() to allow batches during installation.
4577
    $t = get_t();
4578
    $init = array(
4579
      'sandbox' => array(),
4580
      'results' => array(),
4581
      'success' => FALSE,
4582
      'start' => 0,
4583
      'elapsed' => 0,
4584
    );
4585
    $defaults = array(
4586
      'title' => $t('Processing'),
4587
      'init_message' => $t('Initializing.'),
4588
      'progress_message' => $t('Completed @current of @total.'),
4589
      'error_message' => $t('An error has occurred.'),
4590
      'css' => array(),
4591
    );
4592
    $batch_set = $init + $batch_definition + $defaults;
4593

    
4594
    // Tweak init_message to avoid the bottom of the page flickering down after
4595
    // init phase.
4596
    $batch_set['init_message'] .= '<br/>&nbsp;';
4597

    
4598
    // The non-concurrent workflow of batch execution allows us to save
4599
    // numberOfItems() queries by handling our own counter.
4600
    $batch_set['total'] = count($batch_set['operations']);
4601
    $batch_set['count'] = $batch_set['total'];
4602

    
4603
    // Add the set to the batch.
4604
    if (empty($batch['id'])) {
4605
      // The batch is not running yet. Simply add the new set.
4606
      $batch['sets'][] = $batch_set;
4607
    }
4608
    else {
4609
      // The set is being added while the batch is running. Insert the new set
4610
      // right after the current one to ensure execution order, and store its
4611
      // operations in a queue.
4612
      $index = $batch['current_set'] + 1;
4613
      $slice1 = array_slice($batch['sets'], 0, $index);
4614
      $slice2 = array_slice($batch['sets'], $index);
4615
      $batch['sets'] = array_merge($slice1, array($batch_set), $slice2);
4616
      _batch_populate_queue($batch, $index);
4617
    }
4618
  }
4619
}
4620

    
4621
/**
4622
 * Processes the batch.
4623
 *
4624
 * Unless the batch has been marked with 'progressive' = FALSE, the function
4625
 * issues a drupal_goto and thus ends page execution.
4626
 *
4627
 * This function is generally not needed in form submit handlers;
4628
 * Form API takes care of batches that were set during form submission.
4629
 *
4630
 * @param $redirect
4631
 *   (optional) Path to redirect to when the batch has finished processing.
4632
 * @param $url
4633
 *   (optional - should only be used for separate scripts like update.php)
4634
 *   URL of the batch processing page.
4635
 * @param $redirect_callback
4636
 *   (optional) Specify a function to be called to redirect to the progressive
4637
 *   processing page. By default drupal_goto() will be used to redirect to a
4638
 *   page which will do the progressive page. Specifying another function will
4639
 *   allow the progressive processing to be processed differently.
4640
 */
4641
function batch_process($redirect = NULL, $url = 'batch', $redirect_callback = 'drupal_goto') {
4642
  $batch =& batch_get();
4643

    
4644
  drupal_theme_initialize();
4645

    
4646
  if (isset($batch)) {
4647
    // Add process information
4648
    $process_info = array(
4649
      'current_set' => 0,
4650
      'progressive' => TRUE,
4651
      'url' => $url,
4652
      'url_options' => array(),
4653
      'source_url' => $_GET['q'],
4654
      'redirect' => $redirect,
4655
      'theme' => $GLOBALS['theme_key'],
4656
      'redirect_callback' => $redirect_callback,
4657
    );
4658
    $batch += $process_info;
4659

    
4660
    // The batch is now completely built. Allow other modules to make changes
4661
    // to the batch so that it is easier to reuse batch processes in other
4662
    // environments.
4663
    drupal_alter('batch', $batch);
4664

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

    
4669
    // Move operations to a job queue. Non-progressive batches will use a
4670
    // memory-based queue.
4671
    foreach ($batch['sets'] as $key => $batch_set) {
4672
      _batch_populate_queue($batch, $key);
4673
    }
4674

    
4675
    // Initiate processing.
4676
    if ($batch['progressive']) {
4677
      // Now that we have a batch id, we can generate the redirection link in
4678
      // the generic error message.
4679
      $t = get_t();
4680
      $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')))));
4681

    
4682
      // Clear the way for the drupal_goto() redirection to the batch processing
4683
      // page, by saving and unsetting the 'destination', if there is any.
4684
      if (isset($_GET['destination'])) {
4685
        $batch['destination'] = $_GET['destination'];
4686
        unset($_GET['destination']);
4687
      }
4688

    
4689
      // Store the batch.
4690
      db_insert('batch')
4691
        ->fields(array(
4692
          'bid' => $batch['id'],
4693
          'timestamp' => REQUEST_TIME,
4694
          'token' => drupal_get_token($batch['id']),
4695
          'batch' => serialize($batch),
4696
        ))
4697
        ->execute();
4698

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

    
4702
      // Redirect for processing.
4703
      $function = $batch['redirect_callback'];
4704
      if (function_exists($function)) {
4705
        $function($batch['url'], array('query' => array('op' => 'start', 'id' => $batch['id'])));
4706
      }
4707
    }
4708
    else {
4709
      // Non-progressive execution: bypass the whole progressbar workflow
4710
      // and execute the batch in one pass.
4711
      require_once DRUPAL_ROOT . '/includes/batch.inc';
4712
      _batch_process();
4713
    }
4714
  }
4715
}
4716

    
4717
/**
4718
 * Retrieves the current batch.
4719
 */
4720
function &batch_get() {
4721
  // Not drupal_static(), because Batch API operates at a lower level than most
4722
  // use-cases for resetting static variables, and we specifically do not want a
4723
  // global drupal_static_reset() resetting the batch information. Functions
4724
  // that are part of the Batch API and need to reset the batch information may
4725
  // call batch_get() and manipulate the result by reference. Functions that are
4726
  // not part of the Batch API can also do this, but shouldn't.
4727
  static $batch = array();
4728
  return $batch;
4729
}
4730

    
4731
/**
4732
 * Populates a job queue with the operations of a batch set.
4733
 *
4734
 * Depending on whether the batch is progressive or not, the BatchQueue or
4735
 * BatchMemoryQueue handler classes will be used.
4736
 *
4737
 * @param $batch
4738
 *   The batch array.
4739
 * @param $set_id
4740
 *   The id of the set to process.
4741
 *
4742
 * @return
4743
 *   The name and class of the queue are added by reference to the batch set.
4744
 */
4745
function _batch_populate_queue(&$batch, $set_id) {
4746
  $batch_set = &$batch['sets'][$set_id];
4747

    
4748
  if (isset($batch_set['operations'])) {
4749
    $batch_set += array(
4750
      'queue' => array(
4751
        'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
4752
        'class' => $batch['progressive'] ? 'BatchQueue' : 'BatchMemoryQueue',
4753
      ),
4754
    );
4755

    
4756
    $queue = _batch_queue($batch_set);
4757
    $queue->createQueue();
4758
    foreach ($batch_set['operations'] as $operation) {
4759
      $queue->createItem($operation);
4760
    }
4761

    
4762
    unset($batch_set['operations']);
4763
  }
4764
}
4765

    
4766
/**
4767
 * Returns a queue object for a batch set.
4768
 *
4769
 * @param $batch_set
4770
 *   The batch set.
4771
 *
4772
 * @return
4773
 *   The queue object.
4774
 */
4775
function _batch_queue($batch_set) {
4776
  static $queues;
4777

    
4778
  // The class autoloader is not available when running update.php, so make
4779
  // sure the files are manually included.
4780
  if (!isset($queues)) {
4781
    $queues = array();
4782
    require_once DRUPAL_ROOT . '/modules/system/system.queue.inc';
4783
    require_once DRUPAL_ROOT . '/includes/batch.queue.inc';
4784
  }
4785

    
4786
  if (isset($batch_set['queue'])) {
4787
    $name = $batch_set['queue']['name'];
4788
    $class = $batch_set['queue']['class'];
4789

    
4790
    if (!isset($queues[$class][$name])) {
4791
      $queues[$class][$name] = new $class($name);
4792
    }
4793
    return $queues[$class][$name];
4794
  }
4795
}
4796

    
4797
/**
4798
 * @} End of "defgroup batch".
4799
 */