Projet

Général

Profil

Paste
Télécharger (49,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / ajax.inc @ c7768a53

1
<?php
2

    
3
/**
4
 * @file
5
 * Functions for use with Drupal's Ajax framework.
6
 */
7

    
8
/**
9
 * @defgroup ajax Ajax framework
10
 * @{
11
 * Functions for Drupal's Ajax framework.
12
 *
13
 * Drupal's Ajax framework is used to dynamically update parts of a page's HTML
14
 * based on data from the server. Upon a specified event, such as a button
15
 * click, a callback function is triggered which performs server-side logic and
16
 * may return updated markup, which is then replaced on-the-fly with no page
17
 * refresh necessary.
18
 *
19
 * This framework creates a PHP macro language that allows the server to
20
 * instruct JavaScript to perform actions on the client browser. When using
21
 * forms, it can be used with the #ajax property.
22
 * The #ajax property can be used to bind events to the Ajax framework. By
23
 * default, #ajax uses 'system/ajax' as its path for submission and thus calls
24
 * ajax_form_callback() and a defined #ajax['callback'] function.
25
 * However, you may optionally specify a different path to request or a
26
 * different callback function to invoke, which can return updated HTML or can
27
 * also return a richer set of
28
 * @link ajax_commands Ajax framework commands @endlink.
29
 *
30
 * Standard form handling is as follows:
31
 *   - A form element has a #ajax property that includes #ajax['callback'] and
32
 *     omits #ajax['path']. See below about using #ajax['path'] to implement
33
 *     advanced use-cases that require something other than standard form
34
 *     handling.
35
 *   - On the specified element, Ajax processing is triggered by a change to
36
 *     that element.
37
 *   - The browser submits an HTTP POST request to the 'system/ajax' Drupal
38
 *     path.
39
 *   - The menu page callback for 'system/ajax', ajax_form_callback(), calls
40
 *     drupal_process_form() to process the form submission and rebuild the
41
 *     form if necessary. The form is processed in much the same way as if it
42
 *     were submitted without Ajax, with the same #process functions and
43
 *     validation and submission handlers called in either case, making it easy
44
 *     to create Ajax-enabled forms that degrade gracefully when JavaScript is
45
 *     disabled.
46
 *   - After form processing is complete, ajax_form_callback() calls the
47
 *     function named by #ajax['callback'], which returns the form element that
48
 *     has been updated and needs to be returned to the browser, or
49
 *     alternatively, an array of custom Ajax commands.
50
 *   - The page delivery callback for 'system/ajax', ajax_deliver(), renders the
51
 *     element returned by #ajax['callback'], and returns the JSON string
52
 *     created by ajax_render() to the browser.
53
 *   - The browser unserializes the returned JSON string into an array of
54
 *     command objects and executes each command, resulting in the old page
55
 *     content within and including the HTML element specified by
56
 *     #ajax['wrapper'] being replaced by the new content returned by
57
 *     #ajax['callback'], using a JavaScript animation effect specified by
58
 *     #ajax['effect'].
59
 *
60
 * A simple example of basic Ajax use from the
61
 * @link http://drupal.org/project/examples Examples module @endlink follows:
62
 * @code
63
 * function main_page() {
64
 *   return drupal_get_form('ajax_example_simplest');
65
 * }
66
 *
67
 * function ajax_example_simplest($form, &$form_state) {
68
 *   $form = array();
69
 *   $form['changethis'] = array(
70
 *     '#type' => 'select',
71
 *     '#options' => array(
72
 *       'one' => 'one',
73
 *       'two' => 'two',
74
 *       'three' => 'three',
75
 *     ),
76
 *     '#ajax' => array(
77
 *       'callback' => 'ajax_example_simplest_callback',
78
 *       'wrapper' => 'replace_textfield_div',
79
 *      ),
80
 *   );
81

    
82
 *   // This entire form element will be replaced with an updated value.
83
 *   $form['replace_textfield'] = array(
84
 *     '#type' => 'textfield',
85
 *     '#title' => t("The default value will be changed"),
86
 *     '#description' => t("Say something about why you chose") . "'" .
87
 *       (!empty($form_state['values']['changethis'])
88
 *       ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
89
 *     '#prefix' => '<div id="replace_textfield_div">',
90
 *     '#suffix' => '</div>',
91
 *   );
92
 *   return $form;
93
 * }
94
 *
95
 * function ajax_example_simplest_callback($form, $form_state) {
96
 *   // The form has already been submitted and updated. We can return the replaced
97
 *   // item as it is.
98
 *   return $form['replace_textfield'];
99
 * }
100
 * @endcode
101
 *
102
 * In the above example, the 'changethis' element is Ajax-enabled. The default
103
 * #ajax['event'] is 'change', so when the 'changethis' element changes,
104
 * an Ajax call is made. The form is submitted and reprocessed, and then the
105
 * callback is called. In this case, the form has been automatically
106
 * built changing $form['replace_textfield']['#description'], so the callback
107
 * just returns that part of the form.
108
 *
109
 * To implement Ajax handling in a form, add '#ajax' to the form
110
 * definition of a field. That field will trigger an Ajax event when it is
111
 * clicked (or changed, depending on the kind of field). #ajax supports
112
 * the following parameters (either 'path' or 'callback' is required at least):
113
 * - #ajax['callback']: The callback to invoke to handle the server side of the
114
 *   Ajax event, which will receive a $form and $form_state as arguments, and
115
 *   returns a renderable array (most often a form or form fragment), an HTML
116
 *   string, or an array of Ajax commands. If returning a renderable array or
117
 *   a string, the value will replace the original element named in
118
 *   #ajax['wrapper'], and
119
 *   theme_status_messages()
120
 *   will be prepended to that
121
 *   element. (If the status messages are not wanted, return an array
122
 *   of Ajax commands instead.)
123
 *   #ajax['wrapper']. If an array of Ajax commands is returned, it will be
124
 *   executed by the calling code.
125
 * - #ajax['path']: The menu path to use for the request. This is often omitted
126
 *   and the default is used. This path should map
127
 *   to a menu page callback that returns data using ajax_render(). Defaults to
128
 *   'system/ajax', which invokes ajax_form_callback(), eventually calling
129
 *   the function named in #ajax['callback']. If you use a custom
130
 *   path, you must set up the menu entry and handle the entire callback in your
131
 *   own code.
132
 * - #ajax['wrapper']: The CSS ID of the area to be replaced by the content
133
 *   returned by the #ajax['callback'] function. The content returned from
134
 *   the callback will replace the entire element named by #ajax['wrapper'].
135
 *   The wrapper is usually created using #prefix and #suffix properties in the
136
 *   form. Note that this is the wrapper ID, not a CSS selector. So to replace
137
 *   the element referred to by the CSS selector #some-selector on the page,
138
 *   use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
139
 * - #ajax['effect']: The jQuery effect to use when placing the new HTML.
140
 *   Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
141
 * - #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be
142
 *   'slow', 'fast' or a number in milliseconds which represents the length
143
 *   of time the effect should run.
144
 * - #ajax['event']: The JavaScript event to respond to. This is normally
145
 *   selected automatically for the type of form widget being used, and
146
 *   is only needed if you need to override the default behavior.
147
 * - #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered.
148
 *   Defaults to 'click' for #ajax on #type 'submit', 'button', and
149
 *   'image_button'. Multiple events may be specified separated by spaces.
150
 *   For example, when binding #ajax behaviors to form buttons, pressing the
151
 *   ENTER key within a textfield triggers the 'click' event of the form's first
152
 *   submit button. Triggering Ajax in this situation leads to problems, like
153
 *   breaking autocomplete textfields. Because of that, Ajax behaviors are bound
154
 *   to the 'mousedown' event on form buttons by default. However, binding to
155
 *   'mousedown' rather than 'click' means that it is possible to trigger a
156
 *   click by pressing the mouse, holding the mouse button down until the Ajax
157
 *   request is complete and the button is re-enabled, and then releasing the
158
 *   mouse button. For this case, 'prevent' can be set to 'click', so an
159
 *   additional event handler is bound to prevent such a click from triggering a
160
 *   non-Ajax form submission. This also prevents a textfield's ENTER press
161
 *   triggering a button's non-Ajax form submission behavior.
162
 * - #ajax['method']: The jQuery method to use to place the new HTML.
163
 *   Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend',
164
 *   'before', 'after', or 'html'. See the
165
 *   @link http://api.jquery.com/category/manipulation/ jQuery manipulators documentation @endlink
166
 *   for more information on these methods.
167
 * - #ajax['progress']: Choose either a throbber or progress bar that is
168
 *   displayed while awaiting a response from the callback, and add an optional
169
 *   message. Possible keys: 'type', 'message', 'url', 'interval'.
170
 *   More information is available in the
171
 *   @link forms_api_reference.html Form API Reference @endlink
172
 *
173
 * In addition to using Form API for doing in-form modification, Ajax may be
174
 * enabled by adding classes to buttons and links. By adding the 'use-ajax'
175
 * class to a link, the link will be loaded via an Ajax call. When using this
176
 * method, the href of the link can contain '/nojs/' as part of the path. When
177
 * the Ajax framework makes the request, it will convert this to '/ajax/'.
178
 * The server is then able to easily tell if this request was made through an
179
 * actual Ajax request or in a degraded state, and respond appropriately.
180
 *
181
 * Similarly, submit buttons can be given the class 'use-ajax-submit'. The
182
 * form will then be submitted via Ajax to the path specified in the #action.
183
 * Like the ajax-submit class above, this path will have '/nojs/' replaced with
184
 * '/ajax/' so that the submit handler can tell if the form was submitted
185
 * in a degraded state or not.
186
 *
187
 * When responding to Ajax requests, the server should do what it needs to do
188
 * for that request, then create a commands array. This commands array will
189
 * be converted to a JSON object and returned to the client, which will then
190
 * iterate over the array and process it like a macro language.
191
 *
192
 * Each command item is an associative array which will be converted to a
193
 * command object on the JavaScript side. $command_item['command'] is the type
194
 * of command, e.g. 'alert' or 'replace', and will correspond to a method in the
195
 * Drupal.ajax[command] space. The command array may contain any other data that
196
 * the command needs to process, e.g. 'method', 'selector', 'settings', etc.
197
 *
198
 * Commands are usually created with a couple of helper functions, so they
199
 * look like this:
200
 * @code
201
 *   $commands = array();
202
 *   // Replace the content of '#object-1' on the page with 'some html here'.
203
 *   $commands[] = ajax_command_replace('#object-1', 'some html here');
204
 *   // Add a visual "changed" marker to the '#object-1' element.
205
 *   $commands[] = ajax_command_changed('#object-1');
206
 *   // Menu 'page callback' and #ajax['callback'] functions are supposed to
207
 *   // return render arrays. If returning an Ajax commands array, it must be
208
 *   // encapsulated in a render array structure.
209
 *   return array('#type' => 'ajax', '#commands' => $commands);
210
 * @endcode
211
 *
212
 * When returning an Ajax command array, it is often useful to have
213
 * status messages rendered along with other tasks in the command array.
214
 * In that case the Ajax commands array may be constructed like this:
215
 * @code
216
 *   $commands = array();
217
 *   $commands[] = ajax_command_replace(NULL, $output);
218
 *   $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
219
 *   return array('#type' => 'ajax', '#commands' => $commands);
220
 * @endcode
221
 *
222
 * See @link ajax_commands Ajax framework commands @endlink
223
 */
224

    
225
/**
226
 * Renders a commands array into JSON.
227
 *
228
 * @param $commands
229
 *   A list of macro commands generated by the use of ajax_command_*()
230
 *   functions.
231
 */
232
function ajax_render($commands = array()) {
233
  // Although ajax_deliver() does this, some contributed and custom modules
234
  // render Ajax responses without using that delivery callback.
235
  ajax_set_verification_header();
236

    
237
  // Ajax responses aren't rendered with html.tpl.php, so we have to call
238
  // drupal_get_css() and drupal_get_js() here, in order to have new files added
239
  // during this request to be loaded by the page. We only want to send back
240
  // files that the page hasn't already loaded, so we implement simple diffing
241
  // logic using array_diff_key().
242
  foreach (array('css', 'js') as $type) {
243
    // It is highly suspicious if $_POST['ajax_page_state'][$type] is empty,
244
    // since the base page ought to have at least one JS file and one CSS file
245
    // loaded. It probably indicates an error, and rather than making the page
246
    // reload all of the files, instead we return no new files.
247
    if (empty($_POST['ajax_page_state'][$type])) {
248
      $items[$type] = array();
249
    }
250
    else {
251
      $function = 'drupal_add_' . $type;
252
      $items[$type] = $function();
253
      drupal_alter($type, $items[$type]);
254
      // @todo Inline CSS and JS items are indexed numerically. These can't be
255
      //   reliably diffed with array_diff_key(), since the number can change
256
      //   due to factors unrelated to the inline content, so for now, we strip
257
      //   the inline items from Ajax responses, and can add support for them
258
      //   when drupal_add_css() and drupal_add_js() are changed to use a hash
259
      //   of the inline content as the array key.
260
      foreach ($items[$type] as $key => $item) {
261
        if (is_numeric($key)) {
262
          unset($items[$type][$key]);
263
        }
264
      }
265
      // Ensure that the page doesn't reload what it already has.
266
      $items[$type] = array_diff_key($items[$type], $_POST['ajax_page_state'][$type]);
267
    }
268
  }
269

    
270
  // Render the HTML to load these files, and add AJAX commands to insert this
271
  // HTML in the page. We pass TRUE as the $skip_alter argument to prevent the
272
  // data from being altered again, as we already altered it above. Settings are
273
  // handled separately, afterwards.
274
  if (isset($items['js']['settings'])) {
275
    unset($items['js']['settings']);
276
  }
277
  $styles = drupal_get_css($items['css'], TRUE);
278
  $scripts_footer = drupal_get_js('footer', $items['js'], TRUE);
279
  $scripts_header = drupal_get_js('header', $items['js'], TRUE);
280

    
281
  $extra_commands = array();
282
  if (!empty($styles)) {
283
    $extra_commands[] = ajax_command_add_css($styles);
284
  }
285
  if (!empty($scripts_header)) {
286
    $extra_commands[] = ajax_command_prepend('head', $scripts_header);
287
  }
288
  if (!empty($scripts_footer)) {
289
    $extra_commands[] = ajax_command_append('body', $scripts_footer);
290
  }
291
  if (!empty($extra_commands)) {
292
    $commands = array_merge($extra_commands, $commands);
293
  }
294

    
295
  // Now add a command to merge changes and additions to Drupal.settings.
296
  $scripts = drupal_add_js();
297
  drupal_alter('js', $scripts);
298
  if (!empty($scripts['settings'])) {
299
    $settings = $scripts['settings'];
300
    array_unshift($commands, ajax_command_settings(drupal_array_merge_deep_array($settings['data']), TRUE));
301
  }
302

    
303
  // Allow modules to alter any Ajax response.
304
  drupal_alter('ajax_render', $commands);
305

    
306
  return drupal_json_encode($commands);
307
}
308

    
309
/**
310
 * Gets a form submitted via #ajax during an Ajax callback.
311
 *
312
 * This will load a form from the form cache used during Ajax operations. It
313
 * pulls the form info from $_POST.
314
 *
315
 * @return
316
 *   An array containing the $form, $form_state, $form_id, $form_build_id and an
317
 *   initial list of Ajax $commands. Use the list() function to break these
318
 *   apart:
319
 *   @code
320
 *     list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
321
 *   @endcode
322
 */
323
function ajax_get_form() {
324
  $form_state = form_state_defaults();
325

    
326
  $form_build_id = $_POST['form_build_id'];
327

    
328
  // Get the form from the cache.
329
  $form = form_get_cache($form_build_id, $form_state);
330
  if (!$form) {
331
    // If $form cannot be loaded from the cache, the form_build_id in $_POST
332
    // must be invalid, which means that someone performed a POST request onto
333
    // system/ajax without actually viewing the concerned form in the browser.
334
    // This is likely a hacking attempt as it never happens under normal
335
    // circumstances, so we just do nothing.
336
    watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
337
    drupal_exit();
338
  }
339

    
340
  // When a page level cache is enabled, the form-build id might have been
341
  // replaced from within form_get_cache. If this is the case, it is also
342
  // necessary to update it in the browser by issuing an appropriate Ajax
343
  // command.
344
  $commands = array();
345
  if (isset($form['#build_id_old']) && $form['#build_id_old'] != $form['#build_id']) {
346
    // If the form build ID has changed, issue an Ajax command to update it.
347
    $commands[] = ajax_command_update_build_id($form);
348
    $form_build_id = $form['#build_id'];
349
  }
350

    
351
  // Since some of the submit handlers are run, redirects need to be disabled.
352
  $form_state['no_redirect'] = TRUE;
353

    
354
  // When a form is rebuilt after Ajax processing, its #build_id and #action
355
  // should not change.
356
  // @see drupal_rebuild_form()
357
  $form_state['rebuild_info']['copy']['#build_id'] = TRUE;
358
  $form_state['rebuild_info']['copy']['#action'] = TRUE;
359

    
360
  // The form needs to be processed; prepare for that by setting a few internal
361
  // variables.
362
  $form_state['input'] = $_POST;
363
  $form_id = $form['#form_id'];
364

    
365
  return array($form, $form_state, $form_id, $form_build_id, $commands);
366
}
367

    
368
/**
369
 * Menu callback; handles Ajax requests for the #ajax Form API property.
370
 *
371
 * This rebuilds the form from cache and invokes the defined #ajax['callback']
372
 * to return an Ajax command structure for JavaScript. In case no 'callback' has
373
 * been defined, nothing will happen.
374
 *
375
 * The Form API #ajax property can be set both for buttons and other input
376
 * elements.
377
 *
378
 * This function is also the canonical example of how to implement
379
 * #ajax['path']. If processing is required that cannot be accomplished with
380
 * a callback, re-implement this function and set #ajax['path'] to the
381
 * enhanced function.
382
 *
383
 * @see system_menu()
384
 */
385
function ajax_form_callback() {
386
  list($form, $form_state, $form_id, $form_build_id, $commands) = ajax_get_form();
387
  drupal_process_form($form['#form_id'], $form, $form_state);
388

    
389
  // We need to return the part of the form (or some other content) that needs
390
  // to be re-rendered so the browser can update the page with changed content.
391
  // Since this is the generic menu callback used by many Ajax elements, it is
392
  // up to the #ajax['callback'] function of the element (may or may not be a
393
  // button) that triggered the Ajax request to determine what needs to be
394
  // rendered.
395
  if (!empty($form_state['triggering_element'])) {
396
    $callback = $form_state['triggering_element']['#ajax']['callback'];
397
  }
398
  if (!empty($callback) && is_callable($callback)) {
399
    $result = $callback($form, $form_state);
400

    
401
    if (!(is_array($result) && isset($result['#type']) && $result['#type'] == 'ajax')) {
402
      // Turn the response into a #type=ajax array if it isn't one already.
403
      $result = array(
404
        '#type' => 'ajax',
405
        '#commands' => ajax_prepare_response($result),
406
      );
407
    }
408

    
409
    $result['#commands'] = array_merge($commands, $result['#commands']);
410

    
411
    return $result;
412
  }
413
}
414

    
415
/**
416
 * Theme callback for Ajax requests.
417
 *
418
 * Many different pages can invoke an Ajax request to system/ajax or another
419
 * generic Ajax path. It is almost always desired for an Ajax response to be
420
 * rendered using the same theme as the base page, because most themes are built
421
 * with the assumption that they control the entire page, so if the CSS for two
422
 * themes are both loaded for a given page, they may conflict with each other.
423
 * For example, Bartik is Drupal's default theme, and Seven is Drupal's default
424
 * administration theme. Depending on whether the "Use the administration theme
425
 * when editing or creating content" checkbox is checked, the node edit form may
426
 * be displayed in either theme, but the Ajax response to the Field module's
427
 * "Add another item" button should be rendered using the same theme as the rest
428
 * of the page. Therefore, system_menu() sets the 'theme callback' for
429
 * 'system/ajax' to this function, and it is recommended that modules
430
 * implementing other generic Ajax paths do the same.
431
 *
432
 * @see system_menu()
433
 * @see file_menu()
434
 */
435
function ajax_base_page_theme() {
436
  if (!empty($_POST['ajax_page_state']['theme']) && !empty($_POST['ajax_page_state']['theme_token'])) {
437
    $theme = $_POST['ajax_page_state']['theme'];
438
    $token = $_POST['ajax_page_state']['theme_token'];
439

    
440
    // Prevent a request forgery from giving a person access to a theme they
441
    // shouldn't be otherwise allowed to see. However, since everyone is allowed
442
    // to see the default theme, token validation isn't required for that, and
443
    // bypassing it allows most use-cases to work even when accessed from the
444
    // page cache.
445
    if ($theme === variable_get('theme_default', 'bartik') || drupal_valid_token($token, $theme)) {
446
      return $theme;
447
    }
448
  }
449
}
450

    
451
/**
452
 * Packages and sends the result of a page callback as an Ajax response.
453
 *
454
 * This function is the equivalent of drupal_deliver_html_page(), but for Ajax
455
 * requests. Like that function, it:
456
 * - Adds needed HTTP headers.
457
 * - Prints rendered output.
458
 * - Performs end-of-request tasks.
459
 *
460
 * @param $page_callback_result
461
 *   The result of a page callback. Can be one of:
462
 *   - NULL: to indicate no content.
463
 *   - An integer menu status constant: to indicate an error condition.
464
 *   - A string of HTML content.
465
 *   - A renderable array of content.
466
 *
467
 * @see drupal_deliver_html_page()
468
 */
469
function ajax_deliver($page_callback_result) {
470
  // Browsers do not allow JavaScript to read the contents of a user's local
471
  // files. To work around that, the jQuery Form plugin submits forms containing
472
  // a file input element to an IFRAME, instead of using XHR. Browsers do not
473
  // normally expect JSON strings as content within an IFRAME, so the response
474
  // must be customized accordingly.
475
  // @see http://malsup.com/jquery/form/#file-upload
476
  // @see Drupal.ajax.prototype.beforeSend()
477
  $iframe_upload = !empty($_POST['ajax_iframe_upload']);
478

    
479
  // Emit a Content-Type HTTP header if none has been added by the page callback
480
  // or by a wrapping delivery callback.
481
  if (is_null(drupal_get_http_header('Content-Type'))) {
482
    if (!$iframe_upload) {
483
      // Standard JSON can be returned to a browser's XHR object, and to
484
      // non-browser user agents.
485
      // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
486
      drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
487
    }
488
    else {
489
      // Browser IFRAMEs expect HTML. With most other content types, Internet
490
      // Explorer presents the user with a download prompt.
491
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
492
    }
493
  }
494

    
495
  // Let ajax.js know that this response is safe to process.
496
  ajax_set_verification_header();
497

    
498
  // Print the response.
499
  $commands = ajax_prepare_response($page_callback_result);
500
  $json = ajax_render($commands);
501
  if (!$iframe_upload) {
502
    // Standard JSON can be returned to a browser's XHR object, and to
503
    // non-browser user agents.
504
    print $json;
505
  }
506
  else {
507
    // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
508
    // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
509
    // links. This corrupts the JSON response. Protect the integrity of the
510
    // JSON data by making it the value of a textarea.
511
    // @see http://malsup.com/jquery/form/#file-upload
512
    // @see http://drupal.org/node/1009382
513
    print '<textarea>' . $json . '</textarea>';
514
  }
515

    
516
  // Perform end-of-request tasks.
517
  ajax_footer();
518
}
519

    
520
/**
521
 * Converts the return value of a page callback into an Ajax commands array.
522
 *
523
 * @param $page_callback_result
524
 *   The result of a page callback. Can be one of:
525
 *   - NULL: to indicate no content.
526
 *   - An integer menu status constant: to indicate an error condition.
527
 *   - A string of HTML content.
528
 *   - A renderable array of content.
529
 *
530
 * @return
531
 *   An Ajax commands array that can be passed to ajax_render().
532
 */
533
function ajax_prepare_response($page_callback_result) {
534
  $commands = array();
535
  if (!isset($page_callback_result)) {
536
    // Simply delivering an empty commands array is sufficient. This results
537
    // in the Ajax request being completed, but nothing being done to the page.
538
  }
539
  elseif (is_int($page_callback_result)) {
540
    switch ($page_callback_result) {
541
      case MENU_NOT_FOUND:
542
        $commands[] = ajax_command_alert(t('The requested page could not be found.'));
543
        break;
544

    
545
      case MENU_ACCESS_DENIED:
546
        $commands[] = ajax_command_alert(t('You are not authorized to access this page.'));
547
        break;
548

    
549
      case MENU_SITE_OFFLINE:
550
        $commands[] = ajax_command_alert(filter_xss_admin(variable_get('maintenance_mode_message',
551
          t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
552
        break;
553
    }
554
  }
555
  elseif (is_array($page_callback_result) && isset($page_callback_result['#type']) && ($page_callback_result['#type'] == 'ajax')) {
556
    // Complex Ajax callbacks can return a result that contains an error message
557
    // or a specific set of commands to send to the browser.
558
    $page_callback_result += element_info('ajax');
559
    $error = $page_callback_result['#error'];
560
    if (isset($error) && $error !== FALSE) {
561
      if ((empty($error) || $error === TRUE)) {
562
        $error = t('An error occurred while handling the request: The server received invalid input.');
563
      }
564
      $commands[] = ajax_command_alert($error);
565
    }
566
    else {
567
      $commands = $page_callback_result['#commands'];
568
    }
569
  }
570
  else {
571
    // Like normal page callbacks, simple Ajax callbacks can return HTML
572
    // content, as a string or render array. This HTML is inserted in some
573
    // relationship to #ajax['wrapper'], as determined by which jQuery DOM
574
    // manipulation method is used. The method used is specified by
575
    // #ajax['method']. The default method is 'replaceWith', which completely
576
    // replaces the old wrapper element and its content with the new HTML.
577
    $html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
578
    $commands[] = ajax_command_insert(NULL, $html);
579
    // Add the status messages inside the new content's wrapper element, so that
580
    // on subsequent Ajax requests, it is treated as old content.
581
    $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
582
  }
583

    
584
  return $commands;
585
}
586

    
587
/**
588
 * Sets a response header for ajax.js to trust the response body.
589
 *
590
 * It is not safe to invoke Ajax commands within user-uploaded files, so this
591
 * header protects against those being invoked.
592
 *
593
 * @see Drupal.ajax.options.success()
594
 */
595
function ajax_set_verification_header() {
596
  $added = &drupal_static(__FUNCTION__);
597

    
598
  // User-uploaded files cannot set any response headers, so a custom header is
599
  // used to indicate to ajax.js that this response is safe. Note that most
600
  // Ajax requests bound using the Form API will be protected by having the URL
601
  // flagged as trusted in Drupal.settings, so this header is used only for
602
  // things like custom markup that gets Ajax behaviors attached.
603
  if (empty($added)) {
604
    drupal_add_http_header('X-Drupal-Ajax-Token', '1');
605
    // Avoid sending the header twice.
606
    $added = TRUE;
607
  }
608
}
609

    
610
/**
611
 * Performs end-of-Ajax-request tasks.
612
 *
613
 * This function is the equivalent of drupal_page_footer(), but for Ajax
614
 * requests.
615
 *
616
 * @see drupal_page_footer()
617
 */
618
function ajax_footer() {
619
  // Even for Ajax requests, invoke hook_exit() implementations. There may be
620
  // modules that need very fast Ajax responses, and therefore, run Ajax
621
  // requests with an early bootstrap.
622
  if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update')) {
623
    module_invoke_all('exit');
624
  }
625

    
626
  // Commit the user session. See above comment about the possibility of this
627
  // function running without session.inc loaded.
628
  if (function_exists('drupal_session_commit')) {
629
    drupal_session_commit();
630
  }
631
}
632

    
633
/**
634
 * Form element processing handler for the #ajax form property.
635
 *
636
 * @param $element
637
 *   An associative array containing the properties of the element.
638
 *
639
 * @return
640
 *   The processed element.
641
 *
642
 * @see ajax_pre_render_element()
643
 */
644
function ajax_process_form($element, &$form_state) {
645
  $element = ajax_pre_render_element($element);
646
  if (!empty($element['#ajax_processed'])) {
647
    $form_state['cache'] = TRUE;
648
  }
649
  return $element;
650
}
651

    
652
/**
653
 * Adds Ajax information about an element to communicate with JavaScript.
654
 *
655
 * If #ajax['path'] is set on an element, this additional JavaScript is added
656
 * to the page header to attach the Ajax behaviors. See ajax.js for more
657
 * information.
658
 *
659
 * @param $element
660
 *   An associative array containing the properties of the element.
661
 *   Properties used:
662
 *   - #ajax['event']
663
 *   - #ajax['prevent']
664
 *   - #ajax['path']
665
 *   - #ajax['options']
666
 *   - #ajax['wrapper']
667
 *   - #ajax['parameters']
668
 *   - #ajax['effect']
669
 *
670
 * @return
671
 *   The processed element with the necessary JavaScript attached to it.
672
 */
673
function ajax_pre_render_element($element) {
674
  // Skip already processed elements.
675
  if (isset($element['#ajax_processed'])) {
676
    return $element;
677
  }
678
  // Initialize #ajax_processed, so we do not process this element again.
679
  $element['#ajax_processed'] = FALSE;
680

    
681
  // Nothing to do if there is neither a callback nor a path.
682
  if (!(isset($element['#ajax']['callback']) || isset($element['#ajax']['path']))) {
683
    return $element;
684
  }
685

    
686
  // Add a reasonable default event handler if none was specified.
687
  if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
688
    switch ($element['#type']) {
689
      case 'submit':
690
      case 'button':
691
      case 'image_button':
692
        // Pressing the ENTER key within a textfield triggers the click event of
693
        // the form's first submit button. Triggering Ajax in this situation
694
        // leads to problems, like breaking autocomplete textfields, so we bind
695
        // to mousedown instead of click.
696
        // @see http://drupal.org/node/216059
697
        $element['#ajax']['event'] = 'mousedown';
698
        // Retain keyboard accessibility by setting 'keypress'. This causes
699
        // ajax.js to trigger 'event' when SPACE or ENTER are pressed while the
700
        // button has focus.
701
        $element['#ajax']['keypress'] = TRUE;
702
        // Binding to mousedown rather than click means that it is possible to
703
        // trigger a click by pressing the mouse, holding the mouse button down
704
        // until the Ajax request is complete and the button is re-enabled, and
705
        // then releasing the mouse button. Set 'prevent' so that ajax.js binds
706
        // an additional handler to prevent such a click from triggering a
707
        // non-Ajax form submission. This also prevents a textfield's ENTER
708
        // press triggering this button's non-Ajax form submission behavior.
709
        if (!isset($element['#ajax']['prevent'])) {
710
          $element['#ajax']['prevent'] = 'click';
711
        }
712
        break;
713

    
714
      case 'password':
715
      case 'textfield':
716
      case 'textarea':
717
        $element['#ajax']['event'] = 'blur';
718
        break;
719

    
720
      case 'radio':
721
      case 'checkbox':
722
      case 'select':
723
        $element['#ajax']['event'] = 'change';
724
        break;
725

    
726
      case 'link':
727
        $element['#ajax']['event'] = 'click';
728
        break;
729

    
730
      default:
731
        return $element;
732
    }
733
  }
734

    
735
  // Attach JavaScript settings to the element.
736
  if (isset($element['#ajax']['event'])) {
737
    $element['#attached']['library'][] = array('system', 'jquery.form');
738
    $element['#attached']['library'][] = array('system', 'drupal.ajax');
739

    
740
    $settings = $element['#ajax'];
741

    
742
    // Assign default settings.
743
    $settings += array(
744
      'path' => 'system/ajax',
745
      'options' => array(),
746
    );
747

    
748
    // @todo Legacy support. Remove in Drupal 8.
749
    if (isset($settings['method']) && $settings['method'] == 'replace') {
750
      $settings['method'] = 'replaceWith';
751
    }
752

    
753
    // Change path to URL.
754
    $settings['url'] = url($settings['path'], $settings['options']);
755
    unset($settings['path'], $settings['options']);
756

    
757
    // Add special data to $settings['submit'] so that when this element
758
    // triggers an Ajax submission, Drupal's form processing can determine which
759
    // element triggered it.
760
    // @see _form_element_triggered_scripted_submission()
761
    if (isset($settings['trigger_as'])) {
762
      // An element can add a 'trigger_as' key within #ajax to make the element
763
      // submit as though another one (for example, a non-button can use this
764
      // to submit the form as though a button were clicked). When using this,
765
      // the 'name' key is always required to identify the element to trigger
766
      // as. The 'value' key is optional, and only needed when multiple elements
767
      // share the same name, which is commonly the case for buttons.
768
      $settings['submit']['_triggering_element_name'] = $settings['trigger_as']['name'];
769
      if (isset($settings['trigger_as']['value'])) {
770
        $settings['submit']['_triggering_element_value'] = $settings['trigger_as']['value'];
771
      }
772
      unset($settings['trigger_as']);
773
    }
774
    elseif (isset($element['#name'])) {
775
      // Most of the time, elements can submit as themselves, in which case the
776
      // 'trigger_as' key isn't needed, and the element's name is used.
777
      $settings['submit']['_triggering_element_name'] = $element['#name'];
778
      // If the element is a (non-image) button, its name may not identify it
779
      // uniquely, in which case a match on value is also needed.
780
      // @see _form_button_was_clicked()
781
      if (isset($element['#button_type']) && empty($element['#has_garbage_value'])) {
782
        $settings['submit']['_triggering_element_value'] = $element['#value'];
783
      }
784
    }
785

    
786
    // Convert a simple #ajax['progress'] string into an array.
787
    if (isset($settings['progress']) && is_string($settings['progress'])) {
788
      $settings['progress'] = array('type' => $settings['progress']);
789
    }
790
    // Change progress path to a full URL.
791
    if (isset($settings['progress']['path'])) {
792
      $settings['progress']['url'] = url($settings['progress']['path']);
793
      unset($settings['progress']['path']);
794
    }
795

    
796
    $element['#attached']['js'][] = array(
797
      'type' => 'setting',
798
      'data' => array(
799
        'ajax' => array($element['#id'] => $settings),
800
        'urlIsAjaxTrusted' => array(
801
          $settings['url'] => TRUE,
802
        ),
803
      ),
804
    );
805

    
806
    // Indicate that Ajax processing was successful.
807
    $element['#ajax_processed'] = TRUE;
808
  }
809
  return $element;
810
}
811

    
812
/**
813
 * @} End of "defgroup ajax".
814
 */
815

    
816
/**
817
 * @defgroup ajax_commands Ajax framework commands
818
 * @{
819
 * Functions to create various Ajax commands.
820
 *
821
 * These functions can be used to create arrays for use with the
822
 * ajax_render() function.
823
 */
824

    
825
/**
826
 * Creates a Drupal Ajax 'alert' command.
827
 *
828
 * The 'alert' command instructs the client to display a JavaScript alert
829
 * dialog box.
830
 *
831
 * This command is implemented by Drupal.ajax.prototype.commands.alert()
832
 * defined in misc/ajax.js.
833
 *
834
 * @param $text
835
 *   The message string to display to the user.
836
 *
837
 * @return
838
 *   An array suitable for use with the ajax_render() function.
839
 */
840
function ajax_command_alert($text) {
841
  return array(
842
    'command' => 'alert',
843
    'text' => $text,
844
  );
845
}
846

    
847
/**
848
 * Creates a Drupal Ajax 'insert' command using the method in #ajax['method'].
849
 *
850
 * This command instructs the client to insert the given HTML using whichever
851
 * jQuery DOM manipulation method has been specified in the #ajax['method']
852
 * variable of the element that triggered the request.
853
 *
854
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
855
 * defined in misc/ajax.js.
856
 *
857
 * @param $selector
858
 *   A jQuery selector string. If the command is a response to a request from
859
 *   an #ajax form element then this value can be NULL.
860
 * @param $html
861
 *   The data to use with the jQuery method.
862
 * @param $settings
863
 *   An optional array of settings that will be used for this command only.
864
 *
865
 * @return
866
 *   An array suitable for use with the ajax_render() function.
867
 */
868
function ajax_command_insert($selector, $html, $settings = NULL) {
869
  return array(
870
    'command' => 'insert',
871
    'method' => NULL,
872
    'selector' => $selector,
873
    'data' => $html,
874
    'settings' => $settings,
875
  );
876
}
877

    
878
/**
879
 * Creates a Drupal Ajax 'insert/replaceWith' command.
880
 *
881
 * The 'insert/replaceWith' command instructs the client to use jQuery's
882
 * replaceWith() method to replace each element matched matched by the given
883
 * selector with the given HTML.
884
 *
885
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
886
 * defined in misc/ajax.js.
887
 *
888
 * @param $selector
889
 *   A jQuery selector string. If the command is a response to a request from
890
 *   an #ajax form element then this value can be NULL.
891
 * @param $html
892
 *   The data to use with the jQuery replaceWith() method.
893
 * @param $settings
894
 *   An optional array of settings that will be used for this command only.
895
 *
896
 * @return
897
 *   An array suitable for use with the ajax_render() function.
898
 *
899
 * See
900
 * @link http://docs.jquery.com/Manipulation/replaceWith#content jQuery replaceWith command @endlink
901
 */
902
function ajax_command_replace($selector, $html, $settings = NULL) {
903
  return array(
904
    'command' => 'insert',
905
    'method' => 'replaceWith',
906
    'selector' => $selector,
907
    'data' => $html,
908
    'settings' => $settings,
909
  );
910
}
911

    
912
/**
913
 * Creates a Drupal Ajax 'insert/html' command.
914
 *
915
 * The 'insert/html' command instructs the client to use jQuery's html()
916
 * method to set the HTML content of each element matched by the given
917
 * selector while leaving the outer tags intact.
918
 *
919
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
920
 * defined in misc/ajax.js.
921
 *
922
 * @param $selector
923
 *   A jQuery selector string. If the command is a response to a request from
924
 *   an #ajax form element then this value can be NULL.
925
 * @param $html
926
 *   The data to use with the jQuery html() method.
927
 * @param $settings
928
 *   An optional array of settings that will be used for this command only.
929
 *
930
 * @return
931
 *   An array suitable for use with the ajax_render() function.
932
 *
933
 * @see http://docs.jquery.com/Attributes/html#val
934
 */
935
function ajax_command_html($selector, $html, $settings = NULL) {
936
  return array(
937
    'command' => 'insert',
938
    'method' => 'html',
939
    'selector' => $selector,
940
    'data' => $html,
941
    'settings' => $settings,
942
  );
943
}
944

    
945
/**
946
 * Creates a Drupal Ajax 'insert/prepend' command.
947
 *
948
 * The 'insert/prepend' command instructs the client to use jQuery's prepend()
949
 * method to prepend the given HTML content to the inside each element matched
950
 * by the given selector.
951
 *
952
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
953
 * defined in misc/ajax.js.
954
 *
955
 * @param $selector
956
 *   A jQuery selector string. If the command is a response to a request from
957
 *   an #ajax form element then this value can be NULL.
958
 * @param $html
959
 *   The data to use with the jQuery prepend() method.
960
 * @param $settings
961
 *   An optional array of settings that will be used for this command only.
962
 *
963
 * @return
964
 *   An array suitable for use with the ajax_render() function.
965
 *
966
 * @see http://docs.jquery.com/Manipulation/prepend#content
967
 */
968
function ajax_command_prepend($selector, $html, $settings = NULL) {
969
  return array(
970
    'command' => 'insert',
971
    'method' => 'prepend',
972
    'selector' => $selector,
973
    'data' => $html,
974
    'settings' => $settings,
975
  );
976
}
977

    
978
/**
979
 * Creates a Drupal Ajax 'insert/append' command.
980
 *
981
 * The 'insert/append' command instructs the client to use jQuery's append()
982
 * method to append the given HTML content to the inside of each element matched
983
 * by the given selector.
984
 *
985
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
986
 * defined in misc/ajax.js.
987
 *
988
 * @param $selector
989
 *   A jQuery selector string. If the command is a response to a request from
990
 *   an #ajax form element then this value can be NULL.
991
 * @param $html
992
 *   The data to use with the jQuery append() method.
993
 * @param $settings
994
 *   An optional array of settings that will be used for this command only.
995
 *
996
 * @return
997
 *   An array suitable for use with the ajax_render() function.
998
 *
999
 * @see http://docs.jquery.com/Manipulation/append#content
1000
 */
1001
function ajax_command_append($selector, $html, $settings = NULL) {
1002
  return array(
1003
    'command' => 'insert',
1004
    'method' => 'append',
1005
    'selector' => $selector,
1006
    'data' => $html,
1007
    'settings' => $settings,
1008
  );
1009
}
1010

    
1011
/**
1012
 * Creates a Drupal Ajax 'insert/after' command.
1013
 *
1014
 * The 'insert/after' command instructs the client to use jQuery's after()
1015
 * method to insert the given HTML content after each element matched by
1016
 * the given selector.
1017
 *
1018
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
1019
 * defined in misc/ajax.js.
1020
 *
1021
 * @param $selector
1022
 *   A jQuery selector string. If the command is a response to a request from
1023
 *   an #ajax form element then this value can be NULL.
1024
 * @param $html
1025
 *   The data to use with the jQuery after() method.
1026
 * @param $settings
1027
 *   An optional array of settings that will be used for this command only.
1028
 *
1029
 * @return
1030
 *   An array suitable for use with the ajax_render() function.
1031
 *
1032
 * @see http://docs.jquery.com/Manipulation/after#content
1033
 */
1034
function ajax_command_after($selector, $html, $settings = NULL) {
1035
  return array(
1036
    'command' => 'insert',
1037
    'method' => 'after',
1038
    'selector' => $selector,
1039
    'data' => $html,
1040
    'settings' => $settings,
1041
  );
1042
}
1043

    
1044
/**
1045
 * Creates a Drupal Ajax 'insert/before' command.
1046
 *
1047
 * The 'insert/before' command instructs the client to use jQuery's before()
1048
 * method to insert the given HTML content before each of elements matched by
1049
 * the given selector.
1050
 *
1051
 * This command is implemented by Drupal.ajax.prototype.commands.insert()
1052
 * defined in misc/ajax.js.
1053
 *
1054
 * @param $selector
1055
 *   A jQuery selector string. If the command is a response to a request from
1056
 *   an #ajax form element then this value can be NULL.
1057
 * @param $html
1058
 *   The data to use with the jQuery before() method.
1059
 * @param $settings
1060
 *   An optional array of settings that will be used for this command only.
1061
 *
1062
 * @return
1063
 *   An array suitable for use with the ajax_render() function.
1064
 *
1065
 * @see http://docs.jquery.com/Manipulation/before#content
1066
 */
1067
function ajax_command_before($selector, $html, $settings = NULL) {
1068
  return array(
1069
    'command' => 'insert',
1070
    'method' => 'before',
1071
    'selector' => $selector,
1072
    'data' => $html,
1073
    'settings' => $settings,
1074
  );
1075
}
1076

    
1077
/**
1078
 * Creates a Drupal Ajax 'remove' command.
1079
 *
1080
 * The 'remove' command instructs the client to use jQuery's remove() method
1081
 * to remove each of elements matched by the given selector, and everything
1082
 * within them.
1083
 *
1084
 * This command is implemented by Drupal.ajax.prototype.commands.remove()
1085
 * defined in misc/ajax.js.
1086
 *
1087
 * @param $selector
1088
 *   A jQuery selector string. If the command is a response to a request from
1089
 *   an #ajax form element then this value can be NULL.
1090
 *
1091
 * @return
1092
 *   An array suitable for use with the ajax_render() function.
1093
 *
1094
 * @see http://docs.jquery.com/Manipulation/remove#expr
1095
 */
1096
function ajax_command_remove($selector) {
1097
  return array(
1098
    'command' => 'remove',
1099
    'selector' => $selector,
1100
  );
1101
}
1102

    
1103
/**
1104
 * Creates a Drupal Ajax 'changed' command.
1105
 *
1106
 * This command instructs the client to mark each of the elements matched by the
1107
 * given selector as 'ajax-changed'.
1108
 *
1109
 * This command is implemented by Drupal.ajax.prototype.commands.changed()
1110
 * defined in misc/ajax.js.
1111
 *
1112
 * @param $selector
1113
 *   A jQuery selector string. If the command is a response to a request from
1114
 *   an #ajax form element then this value can be NULL.
1115
 * @param $asterisk
1116
 *   An optional CSS selector which must be inside $selector. If specified,
1117
 *   an asterisk will be appended to the HTML inside the $asterisk selector.
1118
 *
1119
 * @return
1120
 *   An array suitable for use with the ajax_render() function.
1121
 */
1122
function ajax_command_changed($selector, $asterisk = '') {
1123
  return array(
1124
    'command' => 'changed',
1125
    'selector' => $selector,
1126
    'asterisk' => $asterisk,
1127
  );
1128
}
1129

    
1130
/**
1131
 * Creates a Drupal Ajax 'css' command.
1132
 *
1133
 * The 'css' command will instruct the client to use the jQuery css() method
1134
 * to apply the CSS arguments to elements matched by the given selector.
1135
 *
1136
 * This command is implemented by Drupal.ajax.prototype.commands.css()
1137
 * defined in misc/ajax.js.
1138
 *
1139
 * @param $selector
1140
 *   A jQuery selector string. If the command is a response to a request from
1141
 *   an #ajax form element then this value can be NULL.
1142
 * @param $argument
1143
 *   An array of key/value pairs to set in the CSS for the selector.
1144
 *
1145
 * @return
1146
 *   An array suitable for use with the ajax_render() function.
1147
 *
1148
 * @see http://docs.jquery.com/CSS/css#properties
1149
 */
1150
function ajax_command_css($selector, $argument) {
1151
  return array(
1152
    'command' => 'css',
1153
    'selector' => $selector,
1154
    'argument' => $argument,
1155
  );
1156
}
1157

    
1158
/**
1159
 * Creates a Drupal Ajax 'settings' command.
1160
 *
1161
 * The 'settings' command instructs the client either to use the given array as
1162
 * the settings for ajax-loaded content or to extend Drupal.settings with the
1163
 * given array, depending on the value of the $merge parameter.
1164
 *
1165
 * This command is implemented by Drupal.ajax.prototype.commands.settings()
1166
 * defined in misc/ajax.js.
1167
 *
1168
 * @param $argument
1169
 *   An array of key/value pairs to add to the settings. This will be utilized
1170
 *   for all commands after this if they do not include their own settings
1171
 *   array.
1172
 * @param $merge
1173
 *   Whether or not the passed settings in $argument should be merged into the
1174
 *   global Drupal.settings on the page. By default (FALSE), the settings that
1175
 *   are passed to Drupal.attachBehaviors will not include the global
1176
 *   Drupal.settings.
1177
 *
1178
 * @return
1179
 *   An array suitable for use with the ajax_render() function.
1180
 */
1181
function ajax_command_settings($argument, $merge = FALSE) {
1182
  return array(
1183
    'command' => 'settings',
1184
    'settings' => $argument,
1185
    'merge' => $merge,
1186
  );
1187
}
1188

    
1189
/**
1190
 * Creates a Drupal Ajax 'data' command.
1191
 *
1192
 * The 'data' command instructs the client to attach the name=value pair of
1193
 * data to the selector via jQuery's data cache.
1194
 *
1195
 * This command is implemented by Drupal.ajax.prototype.commands.data()
1196
 * defined in misc/ajax.js.
1197
 *
1198
 * @param $selector
1199
 *   A jQuery selector string. If the command is a response to a request from
1200
 *   an #ajax form element then this value can be NULL.
1201
 * @param $name
1202
 *   The name or key (in the key value pair) of the data attached to this
1203
 *   selector.
1204
 * @param $value
1205
 *   The value of the data. Not just limited to strings can be any format.
1206
 *
1207
 * @return
1208
 *   An array suitable for use with the ajax_render() function.
1209
 *
1210
 * @see http://docs.jquery.com/Core/data#namevalue
1211
 */
1212
function ajax_command_data($selector, $name, $value) {
1213
  return array(
1214
    'command' => 'data',
1215
    'selector' => $selector,
1216
    'name' => $name,
1217
    'value' => $value,
1218
  );
1219
}
1220

    
1221
/**
1222
 * Creates a Drupal Ajax 'invoke' command.
1223
 *
1224
 * The 'invoke' command will instruct the client to invoke the given jQuery
1225
 * method with the supplied arguments on the elements matched by the given
1226
 * selector. Intended for simple jQuery commands, such as attr(), addClass(),
1227
 * removeClass(), toggleClass(), etc.
1228
 *
1229
 * This command is implemented by Drupal.ajax.prototype.commands.invoke()
1230
 * defined in misc/ajax.js.
1231
 *
1232
 * @param $selector
1233
 *   A jQuery selector string. If the command is a response to a request from
1234
 *   an #ajax form element then this value can be NULL.
1235
 * @param $method
1236
 *   The jQuery method to invoke.
1237
 * @param $arguments
1238
 *   (optional) A list of arguments to the jQuery $method, if any.
1239
 *
1240
 * @return
1241
 *   An array suitable for use with the ajax_render() function.
1242
 */
1243
function ajax_command_invoke($selector, $method, array $arguments = array()) {
1244
  return array(
1245
    'command' => 'invoke',
1246
    'selector' => $selector,
1247
    'method' => $method,
1248
    'arguments' => $arguments,
1249
  );
1250
}
1251

    
1252
/**
1253
 * Creates a Drupal Ajax 'restripe' command.
1254
 *
1255
 * The 'restripe' command instructs the client to restripe a table. This is
1256
 * usually used after a table has been modified by a replace or append command.
1257
 *
1258
 * This command is implemented by Drupal.ajax.prototype.commands.restripe()
1259
 * defined in misc/ajax.js.
1260
 *
1261
 * @param $selector
1262
 *   A jQuery selector string.
1263
 *
1264
 * @return
1265
 *   An array suitable for use with the ajax_render() function.
1266
 */
1267
function ajax_command_restripe($selector) {
1268
  return array(
1269
    'command' => 'restripe',
1270
    'selector' => $selector,
1271
  );
1272
}
1273

    
1274
/**
1275
 * Creates a Drupal Ajax 'update_build_id' command.
1276
 *
1277
 * This command updates the value of a hidden form_build_id input element on a
1278
 * form. It requires the form passed in to have keys for both the old build ID
1279
 * in #build_id_old and the new build ID in #build_id.
1280
 *
1281
 * The primary use case for this Ajax command is to serve a new build ID to a
1282
 * form served from the cache to an anonymous user, preventing one anonymous
1283
 * user from accessing the form state of another anonymous users on Ajax enabled
1284
 * forms.
1285
 *
1286
 * @param $form
1287
 *   The form array representing the form whose build ID should be updated.
1288
 */
1289
function ajax_command_update_build_id($form) {
1290
  return array(
1291
    'command' => 'updateBuildId',
1292
    'old' => $form['#build_id_old'],
1293
    'new' => $form['#build_id'],
1294
  );
1295
}
1296

    
1297
/**
1298
 * Creates a Drupal Ajax 'add_css' command.
1299
 *
1300
 * This method will add css via ajax in a cross-browser compatible way.
1301
 *
1302
 * This command is implemented by Drupal.ajax.prototype.commands.add_css()
1303
 * defined in misc/ajax.js.
1304
 *
1305
 * @param $styles
1306
 *   A string that contains the styles to be added.
1307
 *
1308
 * @return
1309
 *   An array suitable for use with the ajax_render() function.
1310
 *
1311
 * @see misc/ajax.js
1312
 */
1313
function ajax_command_add_css($styles) {
1314
  return array(
1315
    'command' => 'add_css',
1316
    'data' => $styles,
1317
  );
1318
}