Version 1
[yaffs-website] / web / core / includes / form.inc
1 <?php
2
3 /**
4  * @file
5  * Functions for form and batch generation and processing.
6  */
7
8 use Drupal\Component\Utility\UrlHelper;
9 use Drupal\Core\Render\Element;
10 use Drupal\Core\Render\Element\RenderElement;
11 use Drupal\Core\Template\Attribute;
12 use Drupal\Core\Url;
13 use Symfony\Component\HttpFoundation\RedirectResponse;
14
15 /**
16  * Prepares variables for select element templates.
17  *
18  * Default template: select.html.twig.
19  *
20  * It is possible to group options together; to do this, change the format of
21  * $options to an associative array in which the keys are group labels, and the
22  * values are associative arrays in the normal $options format.
23  *
24  * @param $variables
25  *   An associative array containing:
26  *   - element: An associative array containing the properties of the element.
27  *     Properties used: #title, #value, #options, #description, #extra,
28  *     #multiple, #required, #name, #attributes, #size.
29  */
30 function template_preprocess_select(&$variables) {
31   $element = $variables['element'];
32   Element::setAttributes($element, ['id', 'name', 'size']);
33   RenderElement::setAttributes($element, ['form-select']);
34
35   $variables['attributes'] = $element['#attributes'];
36   $variables['options'] = form_select_options($element);
37 }
38
39 /**
40  * Converts an options form element into a structured array for output.
41  *
42  * This function calls itself recursively to obtain the values for each optgroup
43  * within the list of options and when the function encounters an object with
44  * an 'options' property inside $element['#options'].
45  *
46  * @param array $element
47  *   An associative array containing the following key-value pairs:
48  *   - #multiple: Optional Boolean indicating if the user may select more than
49  *     one item.
50  *   - #options: An associative array of options to render as HTML. Each array
51  *     value can be a string, an array, or an object with an 'option' property:
52  *     - A string or integer key whose value is a translated string is
53  *       interpreted as a single HTML option element. Do not use placeholders
54  *       that sanitize data: doing so will lead to double-escaping. Note that
55  *       the key will be visible in the HTML and could be modified by malicious
56  *       users, so don't put sensitive information in it.
57  *     - A translated string key whose value is an array indicates a group of
58  *       options. The translated string is used as the label attribute for the
59  *       optgroup. Do not use placeholders to sanitize data: doing so will lead
60  *       to double-escaping. The array should contain the options you wish to
61  *       group and should follow the syntax of $element['#options'].
62  *     - If the function encounters a string or integer key whose value is an
63  *       object with an 'option' property, the key is ignored, the contents of
64  *       the option property are interpreted as $element['#options'], and the
65  *       resulting HTML is added to the output.
66  *   - #value: Optional integer, string, or array representing which option(s)
67  *     to pre-select when the list is first displayed. The integer or string
68  *     must match the key of an option in the '#options' list. If '#multiple' is
69  *     TRUE, this can be an array of integers or strings.
70  * @param array|null $choices
71  *   (optional) Either an associative array of options in the same format as
72  *   $element['#options'] above, or NULL. This parameter is only used internally
73  *   and is not intended to be passed in to the initial function call.
74  *
75  * @return mixed[]
76  *   A structured, possibly nested, array of options and optgroups for use in a
77  *   select form element.
78  *   - label: A translated string whose value is the text of a single HTML
79  *     option element, or the label attribute for an optgroup.
80  *   - options: Optional, array of options for an optgroup.
81  *   - selected: A boolean that indicates whether the option is selected when
82  *     rendered.
83  *   - type: A string that defines the element type. The value can be 'option'
84  *     or 'optgroup'.
85  *   - value: A string that contains the value attribute for the option.
86  */
87 function form_select_options($element, $choices = NULL) {
88   if (!isset($choices)) {
89     if (empty($element['#options'])) {
90       return [];
91     }
92     $choices = $element['#options'];
93   }
94   // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
95   // isset() fails in this situation.
96   $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
97   $value_is_array = $value_valid && is_array($element['#value']);
98   // Check if the element is multiple select and no value has been selected.
99   $empty_value = (empty($element['#value']) && !empty($element['#multiple']));
100   $options = [];
101   foreach ($choices as $key => $choice) {
102     if (is_array($choice)) {
103       $options[] = [
104         'type' => 'optgroup',
105         'label' => $key,
106         'options' => form_select_options($element, $choice),
107       ];
108     }
109     elseif (is_object($choice) && isset($choice->option)) {
110       $options = array_merge($options, form_select_options($element, $choice->option));
111     }
112     else {
113       $option = [];
114       $key = (string) $key;
115       $empty_choice = $empty_value && $key == '_none';
116       if ($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice)) {
117         $option['selected'] = TRUE;
118       }
119       else {
120         $option['selected'] = FALSE;
121       }
122       $option['type'] = 'option';
123       $option['value'] = $key;
124       $option['label'] = $choice;
125       $options[] = $option;
126     }
127   }
128   return $options;
129 }
130
131 /**
132  * Returns the indexes of a select element's options matching a given key.
133  *
134  * This function is useful if you need to modify the options that are
135  * already in a form element; for example, to remove choices which are
136  * not valid because of additional filters imposed by another module.
137  * One example might be altering the choices in a taxonomy selector.
138  * To correctly handle the case of a multiple hierarchy taxonomy,
139  * #options arrays can now hold an array of objects, instead of a
140  * direct mapping of keys to labels, so that multiple choices in the
141  * selector can have the same key (and label). This makes it difficult
142  * to manipulate directly, which is why this helper function exists.
143  *
144  * This function does not support optgroups (when the elements of the
145  * #options array are themselves arrays), and will return FALSE if
146  * arrays are found. The caller must either flatten/restore or
147  * manually do their manipulations in this case, since returning the
148  * index is not sufficient, and supporting this would make the
149  * "helper" too complicated and cumbersome to be of any help.
150  *
151  * As usual with functions that can return array() or FALSE, do not
152  * forget to use === and !== if needed.
153  *
154  * @param $element
155  *   The select element to search.
156  * @param $key
157  *   The key to look for.
158  *
159  * @return
160  *   An array of indexes that match the given $key. Array will be
161  *   empty if no elements were found. FALSE if optgroups were found.
162  */
163 function form_get_options($element, $key) {
164   $keys = [];
165   foreach ($element['#options'] as $index => $choice) {
166     if (is_array($choice)) {
167       return FALSE;
168     }
169     elseif (is_object($choice)) {
170       if (isset($choice->option[$key])) {
171         $keys[] = $index;
172       }
173     }
174     elseif ($index == $key) {
175       $keys[] = $index;
176     }
177   }
178   return $keys;
179 }
180
181 /**
182  * Prepares variables for fieldset element templates.
183  *
184  * Default template: fieldset.html.twig.
185  *
186  * @param array $variables
187  *   An associative array containing:
188  *   - element: An associative array containing the properties of the element.
189  *     Properties used: #attributes, #children, #description, #id, #title,
190  *     #value.
191  */
192 function template_preprocess_fieldset(&$variables) {
193   $element = $variables['element'];
194   Element::setAttributes($element, ['id']);
195   RenderElement::setAttributes($element);
196   $variables['attributes'] = isset($element['#attributes']) ? $element['#attributes'] : [];
197   $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
198   $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
199   $variables['title_display'] = isset($element['#title_display']) ? $element['#title_display'] : NULL;
200   $variables['children'] = $element['#children'];
201   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
202
203   if (isset($element['#title']) && $element['#title'] !== '') {
204     $variables['legend']['title'] = ['#markup' => $element['#title']];
205   }
206
207   $variables['legend']['attributes'] = new Attribute();
208   // Add 'visually-hidden' class to legend span.
209   if ($variables['title_display'] == 'invisible') {
210     $variables['legend_span']['attributes'] = new Attribute(['class' => ['visually-hidden']]);
211   }
212   else {
213     $variables['legend_span']['attributes'] = new Attribute();
214   }
215
216   if (!empty($element['#description'])) {
217     $description_id = $element['#attributes']['id'] . '--description';
218     $description_attributes['id'] = $description_id;
219     $variables['description']['attributes'] = new Attribute($description_attributes);
220     $variables['description']['content'] = $element['#description'];
221
222     // Add the description's id to the fieldset aria attributes.
223     $variables['attributes']['aria-describedby'] = $description_id;
224   }
225
226   // Suppress error messages.
227   $variables['errors'] = NULL;
228 }
229
230 /**
231  * Prepares variables for details element templates.
232  *
233  * Default template: details.html.twig.
234  *
235  * @param array $variables
236  *   An associative array containing:
237  *   - element: An associative array containing the properties of the element.
238  *     Properties used: #attributes, #children, #open,
239  *     #description, #id, #title, #value, #optional.
240  */
241 function template_preprocess_details(&$variables) {
242   $element = $variables['element'];
243   $variables['attributes'] = $element['#attributes'];
244   $variables['summary_attributes'] = new Attribute();
245   if (!empty($element['#title'])) {
246     $variables['summary_attributes']['role'] = 'button';
247     if (!empty($element['#attributes']['id'])) {
248       $variables['summary_attributes']['aria-controls'] = $element['#attributes']['id'];
249     }
250     $variables['summary_attributes']['aria-expanded'] = !empty($element['#attributes']['open']) ? 'true' : 'false';
251     $variables['summary_attributes']['aria-pressed'] = $variables['summary_attributes']['aria-expanded'];
252   }
253   $variables['title'] = (!empty($element['#title'])) ? $element['#title'] : '';
254   $variables['description'] = (!empty($element['#description'])) ? $element['#description'] : '';
255   $variables['children'] = (isset($element['#children'])) ? $element['#children'] : '';
256   $variables['value'] = (isset($element['#value'])) ? $element['#value'] : '';
257   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
258
259   // Suppress error messages.
260   $variables['errors'] = NULL;
261 }
262
263 /**
264  * Prepares variables for radios templates.
265  *
266  * Default template: radios.html.twig.
267  *
268  * @param array $variables
269  *   An associative array containing:
270  *   - element: An associative array containing the properties of the element.
271  *     Properties used: #title, #value, #options, #description, #required,
272  *     #attributes, #children.
273  */
274 function template_preprocess_radios(&$variables) {
275   $element = $variables['element'];
276   $variables['attributes'] = [];
277   if (isset($element['#id'])) {
278     $variables['attributes']['id'] = $element['#id'];
279   }
280   if (isset($element['#attributes']['title'])) {
281     $variables['attributes']['title'] = $element['#attributes']['title'];
282   }
283   $variables['children'] = $element['#children'];
284 }
285
286 /**
287  * Prepares variables for checkboxes templates.
288  *
289  * Default template: checkboxes.html.twig.
290  *
291  * @param array $variables
292  *   An associative array containing:
293  *   - element: An associative array containing the properties of the element.
294  *     Properties used: #children, #attributes.
295  */
296 function template_preprocess_checkboxes(&$variables) {
297   $element = $variables['element'];
298   $variables['attributes'] = [];
299   if (isset($element['#id'])) {
300     $variables['attributes']['id'] = $element['#id'];
301   }
302   if (isset($element['#attributes']['title'])) {
303     $variables['attributes']['title'] = $element['#attributes']['title'];
304   }
305   $variables['children'] = $element['#children'];
306 }
307
308 /**
309  * Prepares variables for vertical tabs templates.
310  *
311  * Default template: vertical-tabs.html.twig.
312  *
313  * @param array $variables
314  *   An associative array containing:
315  *   - element: An associative array containing the properties and children of
316  *     the details element. Properties used: #children.
317  */
318 function template_preprocess_vertical_tabs(&$variables) {
319   $element = $variables['element'];
320   $variables['children'] = (!empty($element['#children'])) ? $element['#children'] : '';
321 }
322
323 /**
324  * Prepares variables for input templates.
325  *
326  * Default template: input.html.twig.
327  *
328  * @param array $variables
329  *   An associative array containing:
330  *   - element: An associative array containing the properties of the element.
331  *     Properties used: #attributes.
332  */
333 function template_preprocess_input(&$variables) {
334   $element = $variables['element'];
335   // Remove name attribute if empty, for W3C compliance.
336   if (isset($variables['attributes']['name']) && empty((string) $variables['attributes']['name'])) {
337     unset($variables['attributes']['name']);
338   }
339   $variables['children'] = $element['#children'];
340 }
341
342 /**
343  * Prepares variables for form templates.
344  *
345  * Default template: form.html.twig.
346  *
347  * @param $variables
348  *   An associative array containing:
349  *   - element: An associative array containing the properties of the element.
350  *     Properties used: #action, #method, #attributes, #children
351  */
352 function template_preprocess_form(&$variables) {
353   $element = $variables['element'];
354   if (isset($element['#action'])) {
355     $element['#attributes']['action'] = UrlHelper::stripDangerousProtocols($element['#action']);
356   }
357   Element::setAttributes($element, ['method', 'id']);
358   if (empty($element['#attributes']['accept-charset'])) {
359     $element['#attributes']['accept-charset'] = "UTF-8";
360   }
361   $variables['attributes'] = $element['#attributes'];
362   $variables['children'] = $element['#children'];
363 }
364
365 /**
366  * Prepares variables for textarea templates.
367  *
368  * Default template: textarea.html.twig.
369  *
370  * @param array $variables
371  *   An associative array containing:
372  *   - element: An associative array containing the properties of the element.
373  *     Properties used: #title, #value, #description, #rows, #cols,
374  *     #placeholder, #required, #attributes, #resizable
375  */
376 function template_preprocess_textarea(&$variables) {
377   $element = $variables['element'];
378   Element::setAttributes($element, ['id', 'name', 'rows', 'cols', 'placeholder']);
379   RenderElement::setAttributes($element, ['form-textarea']);
380   $variables['wrapper_attributes'] = new Attribute();
381   $variables['attributes'] = new Attribute($element['#attributes']);
382   $variables['value'] = $element['#value'];
383   $variables['resizable'] = !empty($element['#resizable']) ? $element['#resizable'] : NULL;
384   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
385 }
386
387 /**
388  * Returns HTML for a form element.
389  * Prepares variables for form element templates.
390  *
391  * Default template: form-element.html.twig.
392  *
393  * In addition to the element itself, the DIV contains a label for the element
394  * based on the optional #title_display property, and an optional #description.
395  *
396  * The optional #title_display property can have these values:
397  * - before: The label is output before the element. This is the default.
398  *   The label includes the #title and the required marker, if #required.
399  * - after: The label is output after the element. For example, this is used
400  *   for radio and checkbox #type elements. If the #title is empty but the field
401  *   is #required, the label will contain only the required marker.
402  * - invisible: Labels are critical for screen readers to enable them to
403  *   properly navigate through forms but can be visually distracting. This
404  *   property hides the label for everyone except screen readers.
405  * - attribute: Set the title attribute on the element to create a tooltip
406  *   but output no label element. This is supported only for checkboxes
407  *   and radios in
408  *   \Drupal\Core\Render\Element\CompositeFormElementTrait::preRenderCompositeFormElement().
409  *   It is used where a visual label is not needed, such as a table of
410  *   checkboxes where the row and column provide the context. The tooltip will
411  *   include the title and required marker.
412  *
413  * If the #title property is not set, then the label and any required marker
414  * will not be output, regardless of the #title_display or #required values.
415  * This can be useful in cases such as the password_confirm element, which
416  * creates children elements that have their own labels and required markers,
417  * but the parent element should have neither. Use this carefully because a
418  * field without an associated label can cause accessibility challenges.
419  *
420  * @param array $variables
421  *   An associative array containing:
422  *   - element: An associative array containing the properties of the element.
423  *     Properties used: #title, #title_display, #description, #id, #required,
424  *     #children, #type, #name.
425  */
426 function template_preprocess_form_element(&$variables) {
427   $element = &$variables['element'];
428
429   // This function is invoked as theme wrapper, but the rendered form element
430   // may not necessarily have been processed by
431   // \Drupal::formBuilder()->doBuildForm().
432   $element += [
433     '#title_display' => 'before',
434     '#wrapper_attributes' => [],
435     '#label_attributes' => [],
436   ];
437   $variables['attributes'] = $element['#wrapper_attributes'];
438
439   // Add element #id for #type 'item'.
440   if (isset($element['#markup']) && !empty($element['#id'])) {
441     $variables['attributes']['id'] = $element['#id'];
442   }
443
444   // Pass elements #type and #name to template.
445   if (!empty($element['#type'])) {
446     $variables['type'] = $element['#type'];
447   }
448   if (!empty($element['#name'])) {
449     $variables['name'] = $element['#name'];
450   }
451
452   // Pass elements disabled status to template.
453   $variables['disabled'] = !empty($element['#attributes']['disabled']) ? $element['#attributes']['disabled'] : NULL;
454
455   // Suppress error messages.
456   $variables['errors'] = NULL;
457
458   // If #title is not set, we don't display any label.
459   if (!isset($element['#title'])) {
460     $element['#title_display'] = 'none';
461   }
462
463   $variables['title_display'] = $element['#title_display'];
464
465   $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
466   $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
467
468   $variables['description'] = NULL;
469   if (!empty($element['#description'])) {
470     $variables['description_display'] = $element['#description_display'];
471     $description_attributes = [];
472     if (!empty($element['#id'])) {
473       $description_attributes['id'] = $element['#id'] . '--description';
474     }
475     $variables['description']['attributes'] = new Attribute($description_attributes);
476     $variables['description']['content'] = $element['#description'];
477   }
478
479   // Add label_display and label variables to template.
480   $variables['label_display'] = $element['#title_display'];
481   $variables['label'] = ['#theme' => 'form_element_label'];
482   $variables['label'] += array_intersect_key($element, array_flip(['#id', '#required', '#title', '#title_display']));
483   $variables['label']['#attributes'] = $element['#label_attributes'];
484
485   $variables['children'] = $element['#children'];
486 }
487
488 /**
489  * Prepares variables for form label templates.
490  *
491  * Form element labels include the #title and a #required marker. The label is
492  * associated with the element itself by the element #id. Labels may appear
493  * before or after elements, depending on form-element.html.twig and
494  * #title_display.
495  *
496  * This function will not be called for elements with no labels, depending on
497  * #title_display. For elements that have an empty #title and are not required,
498  * this function will output no label (''). For required elements that have an
499  * empty #title, this will output the required marker alone within the label.
500  * The label will use the #id to associate the marker with the field that is
501  * required. That is especially important for screenreader users to know
502  * which field is required.
503  *
504  * @param array $variables
505  *   An associative array containing:
506  *   - element: An associative array containing the properties of the element.
507  *     Properties used: #required, #title, #id, #value, #description.
508  */
509 function template_preprocess_form_element_label(&$variables) {
510   $element = $variables['element'];
511   // If title and required marker are both empty, output no label.
512   if (isset($element['#title']) && $element['#title'] !== '') {
513     $variables['title'] = ['#markup' => $element['#title']];
514   }
515
516   // Pass elements title_display to template.
517   $variables['title_display'] = $element['#title_display'];
518
519   // A #for property of a dedicated #type 'label' element as precedence.
520   if (!empty($element['#for'])) {
521     $variables['attributes']['for'] = $element['#for'];
522     // A custom #id allows the referenced form input element to refer back to
523     // the label element; e.g., in the 'aria-labelledby' attribute.
524     if (!empty($element['#id'])) {
525       $variables['attributes']['id'] = $element['#id'];
526     }
527   }
528   // Otherwise, point to the #id of the form input element.
529   elseif (!empty($element['#id'])) {
530     $variables['attributes']['for'] = $element['#id'];
531   }
532
533   // Pass elements required to template.
534   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
535 }
536
537 /**
538  * @defgroup batch Batch operations
539  * @{
540  * Creates and processes batch operations.
541  *
542  * Functions allowing forms processing to be spread out over several page
543  * requests, thus ensuring that the processing does not get interrupted
544  * because of a PHP timeout, while allowing the user to receive feedback
545  * on the progress of the ongoing operations.
546  *
547  * The API is primarily designed to integrate nicely with the Form API
548  * workflow, but can also be used by non-Form API scripts (like update.php)
549  * or even simple page callbacks (which should probably be used sparingly).
550  *
551  * Example:
552  * @code
553  * $batch = array(
554  *   'title' => t('Exporting'),
555  *   'operations' => array(
556  *     array('my_function_1', array($account->id(), 'story')),
557  *     array('my_function_2', array()),
558  *   ),
559  *   'finished' => 'my_finished_callback',
560  *   'file' => 'path_to_file_containing_myfunctions',
561  * );
562  * batch_set($batch);
563  * // Only needed if not inside a form _submit handler.
564  * // Setting redirect in batch_process.
565  * batch_process('node/1');
566  * @endcode
567  *
568  * Note: if the batch 'title', 'init_message', 'progress_message', or
569  * 'error_message' could contain any user input, it is the responsibility of
570  * the code calling batch_set() to sanitize them first with a function like
571  * \Drupal\Component\Utility\Html::escape() or
572  * \Drupal\Component\Utility\Xss::filter(). Furthermore, if the batch operation
573  * returns any user input in the 'results' or 'message' keys of $context, it
574  * must also sanitize them first.
575  *
576  * Sample callback_batch_operation():
577  * @code
578  * // Simple and artificial: load a node of a given type for a given user
579  * function my_function_1($uid, $type, &$context) {
580  *   // The $context array gathers batch context information about the execution (read),
581  *   // as well as 'return values' for the current operation (write)
582  *   // The following keys are provided :
583  *   // 'results' (read / write): The array of results gathered so far by
584  *   //   the batch processing, for the current operation to append its own.
585  *   // 'message' (write): A text message displayed in the progress page.
586  *   // The following keys allow for multi-step operations :
587  *   // 'sandbox' (read / write): An array that can be freely used to
588  *   //   store persistent data between iterations. It is recommended to
589  *   //   use this instead of $_SESSION, which is unsafe if the user
590  *   //   continues browsing in a separate window while the batch is processing.
591  *   // 'finished' (write): A float number between 0 and 1 informing
592  *   //   the processing engine of the completion level for the operation.
593  *   //   1 (or no value explicitly set) means the operation is finished
594  *   //   and the batch processing can continue to the next operation.
595  *
596  *   $nodes = \Drupal::entityTypeManager()->getStorage('node')
597  *     ->loadByProperties(['uid' => $uid, 'type' => $type]);
598  *   $node = reset($nodes);
599  *   $context['results'][] = $node->id() . ' : ' . Html::escape($node->label());
600  *   $context['message'] = Html::escape($node->label());
601  * }
602  *
603  * // A more advanced example is a multi-step operation that loads all rows,
604  * // five by five.
605  * function my_function_2(&$context) {
606  *   if (empty($context['sandbox'])) {
607  *     $context['sandbox']['progress'] = 0;
608  *     $context['sandbox']['current_id'] = 0;
609  *     $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT id) FROM {example}')->fetchField();
610  *   }
611  *   $limit = 5;
612  *   $result = db_select('example')
613  *     ->fields('example', array('id'))
614  *     ->condition('id', $context['sandbox']['current_id'], '>')
615  *     ->orderBy('id')
616  *     ->range(0, $limit)
617  *     ->execute();
618  *   foreach ($result as $row) {
619  *     $context['results'][] = $row->id . ' : ' . Html::escape($row->title);
620  *     $context['sandbox']['progress']++;
621  *     $context['sandbox']['current_id'] = $row->id;
622  *     $context['message'] = Html::escape($row->title);
623  *   }
624  *   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
625  *     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
626  *   }
627  * }
628  * @endcode
629  *
630  * Sample callback_batch_finished():
631  * @code
632  * function my_finished_callback($success, $results, $operations) {
633  *   // The 'success' parameter means no fatal PHP errors were detected. All
634  *   // other error management should be handled using 'results'.
635  *   if ($success) {
636  *     $message = \Drupal::translation()->formatPlural(count($results), 'One post processed.', '@count posts processed.');
637  *   }
638  *   else {
639  *     $message = t('Finished with an error.');
640  *   }
641  *   drupal_set_message($message);
642  *   // Providing data for the redirected page is done through $_SESSION.
643  *   foreach ($results as $result) {
644  *     $items[] = t('Loaded node %title.', array('%title' => $result));
645  *   }
646  *   $_SESSION['my_batch_results'] = $items;
647  * }
648  * @endcode
649  */
650
651 /**
652  * Adds a new batch.
653  *
654  * Batch operations are added as new batch sets. Batch sets are used to spread
655  * processing (primarily, but not exclusively, forms processing) over several
656  * page requests. This helps to ensure that the processing is not interrupted
657  * due to PHP timeouts, while users are still able to receive feedback on the
658  * progress of the ongoing operations. Combining related operations into
659  * distinct batch sets provides clean code independence for each batch set,
660  * ensuring that two or more batches, submitted independently, can be processed
661  * without mutual interference. Each batch set may specify its own set of
662  * operations and results, produce its own UI messages, and trigger its own
663  * 'finished' callback. Batch sets are processed sequentially, with the progress
664  * bar starting afresh for each new set.
665  *
666  * @param $batch_definition
667  *   An associative array defining the batch, with the following elements (all
668  *   are optional except as noted):
669  *   - operations: (required) Array of operations to be performed, where each
670  *     item is an array consisting of the name of an implementation of
671  *     callback_batch_operation() and an array of parameter.
672  *     Example:
673  *     @code
674  *     array(
675  *       array('callback_batch_operation_1', array($arg1)),
676  *       array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
677  *     )
678  *     @endcode
679  *   - title: A safe, translated string to use as the title for the progress
680  *     page. Defaults to t('Processing').
681  *   - init_message: Message displayed while the processing is initialized.
682  *     Defaults to t('Initializing.').
683  *   - progress_message: Message displayed while processing the batch. Available
684  *     placeholders are @current, @remaining, @total, @percentage, @estimate and
685  *     @elapsed. Defaults to t('Completed @current of @total.').
686  *   - error_message: Message displayed if an error occurred while processing
687  *     the batch. Defaults to t('An error has occurred.').
688  *   - finished: Name of an implementation of callback_batch_finished(). This is
689  *     executed after the batch has completed. This should be used to perform
690  *     any result massaging that may be needed, and possibly save data in
691  *     $_SESSION for display after final page redirection.
692  *   - file: Path to the file containing the definitions of the 'operations' and
693  *     'finished' functions, for instance if they don't reside in the main
694  *     .module file. The path should be relative to base_path(), and thus should
695  *     be built using drupal_get_path().
696  *   - library: An array of batch-specific CSS and JS libraries.
697  *   - url_options: options passed to the \Drupal\Core\Url object when
698  *     constructing redirect URLs for the batch.
699  *   - progressive: A Boolean that indicates whether or not the batch needs to
700  *     run progressively. TRUE indicates that the batch will run in more than
701  *     one run. FALSE (default) indicates that the batch will finish in a single
702  *     run.
703  *   - queue: An override of the default queue (with name and class fields
704  *     optional). An array containing two elements:
705  *     - name: Unique identifier for the queue.
706  *     - class: The name of a class that implements
707  *       \Drupal\Core\Queue\QueueInterface, including the full namespace but not
708  *       starting with a backslash. It must have a constructor with two
709  *       arguments: $name and a \Drupal\Core\Database\Connection object.
710  *       Typically, the class will either be \Drupal\Core\Queue\Batch or
711  *       \Drupal\Core\Queue\BatchMemory. Defaults to Batch if progressive is
712  *       TRUE, or to BatchMemory if progressive is FALSE.
713  */
714 function batch_set($batch_definition) {
715   if ($batch_definition) {
716     $batch =& batch_get();
717
718     // Initialize the batch if needed.
719     if (empty($batch)) {
720       $batch = [
721         'sets' => [],
722         'has_form_submits' => FALSE,
723       ];
724     }
725
726     // Base and default properties for the batch set.
727     $init = [
728       'sandbox' => [],
729       'results' => [],
730       'success' => FALSE,
731       'start' => 0,
732       'elapsed' => 0,
733     ];
734     $defaults = [
735       'title' => t('Processing'),
736       'init_message' => t('Initializing.'),
737       'progress_message' => t('Completed @current of @total.'),
738       'error_message' => t('An error has occurred.'),
739     ];
740     $batch_set = $init + $batch_definition + $defaults;
741
742     // Tweak init_message to avoid the bottom of the page flickering down after
743     // init phase.
744     $batch_set['init_message'] .= '<br/>&nbsp;';
745
746     // The non-concurrent workflow of batch execution allows us to save
747     // numberOfItems() queries by handling our own counter.
748     $batch_set['total'] = count($batch_set['operations']);
749     $batch_set['count'] = $batch_set['total'];
750
751     // Add the set to the batch.
752     if (empty($batch['id'])) {
753       // The batch is not running yet. Simply add the new set.
754       $batch['sets'][] = $batch_set;
755     }
756     else {
757       // The set is being added while the batch is running. Insert the new set
758       // right after the current one to ensure execution order, and store its
759       // operations in a queue.
760       $index = $batch['current_set'] + 1;
761       $slice1 = array_slice($batch['sets'], 0, $index);
762       $slice2 = array_slice($batch['sets'], $index);
763       $batch['sets'] = array_merge($slice1, [$batch_set], $slice2);
764       _batch_populate_queue($batch, $index);
765     }
766   }
767 }
768
769 /**
770  * Processes the batch.
771  *
772  * This function is generally not needed in form submit handlers;
773  * Form API takes care of batches that were set during form submission.
774  *
775  * @param \Drupal\Core\Url|string $redirect
776  *   (optional) Either path or Url object to redirect to when the batch has
777  *   finished processing. Note that to simply force a batch to (conditionally)
778  *   redirect to a custom location after it is finished processing but to
779  *   otherwise allow the standard form API batch handling to occur, it is not
780  *   necessary to call batch_process() and use this parameter. Instead, make
781  *   the batch 'finished' callback return an instance of
782  *   \Symfony\Component\HttpFoundation\RedirectResponse, which will be used
783  *   automatically by the standard batch processing pipeline (and which takes
784  *   precedence over this parameter).
785  *   User will be redirected to the page that started the batch if this argument
786  *   is omitted and no redirect response was returned by the 'finished'
787  *   callback. Any query arguments will be automatically persisted.
788  * @param \Drupal\Core\Url $url
789  *   (optional - should only be used for separate scripts like update.php)
790  *   URL of the batch processing page.
791  * @param $redirect_callback
792  *   (optional) Specify a function to be called to redirect to the progressive
793  *   processing page.
794  *
795  * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
796  *   A redirect response if the batch is progressive. No return value otherwise.
797  */
798 function batch_process($redirect = NULL, Url $url = NULL, $redirect_callback = NULL) {
799   $batch =& batch_get();
800
801   if (isset($batch)) {
802     // Add process information
803     $process_info = [
804       'current_set' => 0,
805       'progressive' => TRUE,
806       'url' => isset($url) ? $url : Url::fromRoute('system.batch_page.html'),
807       'source_url' => Url::fromRouteMatch(\Drupal::routeMatch())->mergeOptions(['query' => \Drupal::request()->query->all()]),
808       'batch_redirect' => $redirect,
809       'theme' => \Drupal::theme()->getActiveTheme()->getName(),
810       'redirect_callback' => $redirect_callback,
811     ];
812     $batch += $process_info;
813
814     // The batch is now completely built. Allow other modules to make changes
815     // to the batch so that it is easier to reuse batch processes in other
816     // environments.
817     \Drupal::moduleHandler()->alter('batch', $batch);
818
819     // Assign an arbitrary id: don't rely on a serial column in the 'batch'
820     // table, since non-progressive batches skip database storage completely.
821     $batch['id'] = db_next_id();
822
823     // Move operations to a job queue. Non-progressive batches will use a
824     // memory-based queue.
825     foreach ($batch['sets'] as $key => $batch_set) {
826       _batch_populate_queue($batch, $key);
827     }
828
829     // Initiate processing.
830     if ($batch['progressive']) {
831       // Now that we have a batch id, we can generate the redirection link in
832       // the generic error message.
833       /** @var \Drupal\Core\Url $batch_url */
834       $batch_url = $batch['url'];
835       /** @var \Drupal\Core\Url $error_url */
836       $error_url = clone $batch_url;
837       $query_options = $error_url->getOption('query');
838       $query_options['id'] = $batch['id'];
839       $query_options['op'] = 'finished';
840       $error_url->setOption('query', $query_options);
841
842       $batch['error_message'] = t('Please continue to <a href=":error_url">the error page</a>', [':error_url' => $error_url->toString(TRUE)->getGeneratedUrl()]);
843
844       // Clear the way for the redirection to the batch processing page, by
845       // saving and unsetting the 'destination', if there is any.
846       $request = \Drupal::request();
847       if ($request->query->has('destination')) {
848         $batch['destination'] = $request->query->get('destination');
849         $request->query->remove('destination');
850       }
851
852       // Store the batch.
853       \Drupal::service('batch.storage')->create($batch);
854
855       // Set the batch number in the session to guarantee that it will stay alive.
856       $_SESSION['batches'][$batch['id']] = TRUE;
857
858       // Redirect for processing.
859       $query_options = $error_url->getOption('query');
860       $query_options['op'] = 'start';
861       $query_options['id'] = $batch['id'];
862       $batch_url->setOption('query', $query_options);
863       if (($function = $batch['redirect_callback']) && function_exists($function)) {
864         $function($batch_url->toString(), ['query' => $query_options]);
865       }
866       else {
867         return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
868       }
869     }
870     else {
871       // Non-progressive execution: bypass the whole progressbar workflow
872       // and execute the batch in one pass.
873       require_once __DIR__ . '/batch.inc';
874       _batch_process();
875     }
876   }
877 }
878
879 /**
880  * Retrieves the current batch.
881  */
882 function &batch_get() {
883   // Not drupal_static(), because Batch API operates at a lower level than most
884   // use-cases for resetting static variables, and we specifically do not want a
885   // global drupal_static_reset() resetting the batch information. Functions
886   // that are part of the Batch API and need to reset the batch information may
887   // call batch_get() and manipulate the result by reference. Functions that are
888   // not part of the Batch API can also do this, but shouldn't.
889   static $batch = [];
890   return $batch;
891 }
892
893 /**
894  * Populates a job queue with the operations of a batch set.
895  *
896  * Depending on whether the batch is progressive or not, the
897  * Drupal\Core\Queue\Batch or Drupal\Core\Queue\BatchMemory handler classes will
898  * be used. The name and class of the queue are added by reference to the
899  * batch set.
900  *
901  * @param $batch
902  *   The batch array.
903  * @param $set_id
904  *   The id of the set to process.
905  */
906 function _batch_populate_queue(&$batch, $set_id) {
907   $batch_set = &$batch['sets'][$set_id];
908
909   if (isset($batch_set['operations'])) {
910     $batch_set += [
911       'queue' => [
912         'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
913         'class' => $batch['progressive'] ? 'Drupal\Core\Queue\Batch' : 'Drupal\Core\Queue\BatchMemory',
914       ],
915     ];
916
917     $queue = _batch_queue($batch_set);
918     $queue->createQueue();
919     foreach ($batch_set['operations'] as $operation) {
920       $queue->createItem($operation);
921     }
922
923     unset($batch_set['operations']);
924   }
925 }
926
927 /**
928  * Returns a queue object for a batch set.
929  *
930  * @param $batch_set
931  *   The batch set.
932  *
933  * @return
934  *   The queue object.
935  */
936 function _batch_queue($batch_set) {
937   static $queues;
938
939   if (!isset($queues)) {
940     $queues = [];
941   }
942
943   if (isset($batch_set['queue'])) {
944     $name = $batch_set['queue']['name'];
945     $class = $batch_set['queue']['class'];
946
947     if (!isset($queues[$class][$name])) {
948       $queues[$class][$name] = new $class($name, \Drupal::database());
949     }
950     return $queues[$class][$name];
951   }
952 }
953
954 /**
955  * @} End of "defgroup batch".
956  */