d99dca282a2177d47f1aac7c0826de2ccd312de8
[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, #maxlength,
374  *     #placeholder, #required, #attributes, #resizable.
375  */
376 function template_preprocess_textarea(&$variables) {
377   $element = $variables['element'];
378   $attributes = ['id', 'name', 'rows', 'cols', 'maxlength', 'placeholder'];
379   Element::setAttributes($element, $attributes);
380   RenderElement::setAttributes($element, ['form-textarea']);
381   $variables['wrapper_attributes'] = new Attribute();
382   $variables['attributes'] = new Attribute($element['#attributes']);
383   $variables['value'] = $element['#value'];
384   $variables['resizable'] = !empty($element['#resizable']) ? $element['#resizable'] : NULL;
385   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
386 }
387
388 /**
389  * Returns HTML for a form element.
390  * Prepares variables for form element templates.
391  *
392  * Default template: form-element.html.twig.
393  *
394  * In addition to the element itself, the DIV contains a label for the element
395  * based on the optional #title_display property, and an optional #description.
396  *
397  * The optional #title_display property can have these values:
398  * - before: The label is output before the element. This is the default.
399  *   The label includes the #title and the required marker, if #required.
400  * - after: The label is output after the element. For example, this is used
401  *   for radio and checkbox #type elements. If the #title is empty but the field
402  *   is #required, the label will contain only the required marker.
403  * - invisible: Labels are critical for screen readers to enable them to
404  *   properly navigate through forms but can be visually distracting. This
405  *   property hides the label for everyone except screen readers.
406  * - attribute: Set the title attribute on the element to create a tooltip
407  *   but output no label element. This is supported only for checkboxes
408  *   and radios in
409  *   \Drupal\Core\Render\Element\CompositeFormElementTrait::preRenderCompositeFormElement().
410  *   It is used where a visual label is not needed, such as a table of
411  *   checkboxes where the row and column provide the context. The tooltip will
412  *   include the title and required marker.
413  *
414  * If the #title property is not set, then the label and any required marker
415  * will not be output, regardless of the #title_display or #required values.
416  * This can be useful in cases such as the password_confirm element, which
417  * creates children elements that have their own labels and required markers,
418  * but the parent element should have neither. Use this carefully because a
419  * field without an associated label can cause accessibility challenges.
420  *
421  * @param array $variables
422  *   An associative array containing:
423  *   - element: An associative array containing the properties of the element.
424  *     Properties used: #title, #title_display, #description, #id, #required,
425  *     #children, #type, #name.
426  */
427 function template_preprocess_form_element(&$variables) {
428   $element = &$variables['element'];
429
430   // This function is invoked as theme wrapper, but the rendered form element
431   // may not necessarily have been processed by
432   // \Drupal::formBuilder()->doBuildForm().
433   $element += [
434     '#title_display' => 'before',
435     '#wrapper_attributes' => [],
436     '#label_attributes' => [],
437   ];
438   $variables['attributes'] = $element['#wrapper_attributes'];
439
440   // Add element #id for #type 'item'.
441   if (isset($element['#markup']) && !empty($element['#id'])) {
442     $variables['attributes']['id'] = $element['#id'];
443   }
444
445   // Pass elements #type and #name to template.
446   if (!empty($element['#type'])) {
447     $variables['type'] = $element['#type'];
448   }
449   if (!empty($element['#name'])) {
450     $variables['name'] = $element['#name'];
451   }
452
453   // Pass elements disabled status to template.
454   $variables['disabled'] = !empty($element['#attributes']['disabled']) ? $element['#attributes']['disabled'] : NULL;
455
456   // Suppress error messages.
457   $variables['errors'] = NULL;
458
459   // If #title is not set, we don't display any label.
460   if (!isset($element['#title'])) {
461     $element['#title_display'] = 'none';
462   }
463
464   $variables['title_display'] = $element['#title_display'];
465
466   $variables['prefix'] = isset($element['#field_prefix']) ? $element['#field_prefix'] : NULL;
467   $variables['suffix'] = isset($element['#field_suffix']) ? $element['#field_suffix'] : NULL;
468
469   $variables['description'] = NULL;
470   if (!empty($element['#description'])) {
471     $variables['description_display'] = $element['#description_display'];
472     $description_attributes = [];
473     if (!empty($element['#id'])) {
474       $description_attributes['id'] = $element['#id'] . '--description';
475     }
476     $variables['description']['attributes'] = new Attribute($description_attributes);
477     $variables['description']['content'] = $element['#description'];
478   }
479
480   // Add label_display and label variables to template.
481   $variables['label_display'] = $element['#title_display'];
482   $variables['label'] = ['#theme' => 'form_element_label'];
483   $variables['label'] += array_intersect_key($element, array_flip(['#id', '#required', '#title', '#title_display']));
484   $variables['label']['#attributes'] = $element['#label_attributes'];
485
486   $variables['children'] = $element['#children'];
487 }
488
489 /**
490  * Prepares variables for form label templates.
491  *
492  * Form element labels include the #title and a #required marker. The label is
493  * associated with the element itself by the element #id. Labels may appear
494  * before or after elements, depending on form-element.html.twig and
495  * #title_display.
496  *
497  * This function will not be called for elements with no labels, depending on
498  * #title_display. For elements that have an empty #title and are not required,
499  * this function will output no label (''). For required elements that have an
500  * empty #title, this will output the required marker alone within the label.
501  * The label will use the #id to associate the marker with the field that is
502  * required. That is especially important for screenreader users to know
503  * which field is required.
504  *
505  * @param array $variables
506  *   An associative array containing:
507  *   - element: An associative array containing the properties of the element.
508  *     Properties used: #required, #title, #id, #value, #description.
509  */
510 function template_preprocess_form_element_label(&$variables) {
511   $element = $variables['element'];
512   // If title and required marker are both empty, output no label.
513   if (isset($element['#title']) && $element['#title'] !== '') {
514     $variables['title'] = ['#markup' => $element['#title']];
515   }
516
517   // Pass elements title_display to template.
518   $variables['title_display'] = $element['#title_display'];
519
520   // A #for property of a dedicated #type 'label' element as precedence.
521   if (!empty($element['#for'])) {
522     $variables['attributes']['for'] = $element['#for'];
523     // A custom #id allows the referenced form input element to refer back to
524     // the label element; e.g., in the 'aria-labelledby' attribute.
525     if (!empty($element['#id'])) {
526       $variables['attributes']['id'] = $element['#id'];
527     }
528   }
529   // Otherwise, point to the #id of the form input element.
530   elseif (!empty($element['#id'])) {
531     $variables['attributes']['for'] = $element['#id'];
532   }
533
534   // Pass elements required to template.
535   $variables['required'] = !empty($element['#required']) ? $element['#required'] : NULL;
536 }
537
538 /**
539  * @defgroup batch Batch operations
540  * @{
541  * Creates and processes batch operations.
542  *
543  * Functions allowing forms processing to be spread out over several page
544  * requests, thus ensuring that the processing does not get interrupted
545  * because of a PHP timeout, while allowing the user to receive feedback
546  * on the progress of the ongoing operations.
547  *
548  * The API is primarily designed to integrate nicely with the Form API
549  * workflow, but can also be used by non-Form API scripts (like update.php)
550  * or even simple page callbacks (which should probably be used sparingly).
551  *
552  * Example:
553  * @code
554  * $batch = array(
555  *   'title' => t('Exporting'),
556  *   'operations' => array(
557  *     array('my_function_1', array($account->id(), 'story')),
558  *     array('my_function_2', array()),
559  *   ),
560  *   'finished' => 'my_finished_callback',
561  *   'file' => 'path_to_file_containing_myfunctions',
562  * );
563  * batch_set($batch);
564  * // Only needed if not inside a form _submit handler.
565  * // Setting redirect in batch_process.
566  * batch_process('node/1');
567  * @endcode
568  *
569  * Note: if the batch 'title', 'init_message', 'progress_message', or
570  * 'error_message' could contain any user input, it is the responsibility of
571  * the code calling batch_set() to sanitize them first with a function like
572  * \Drupal\Component\Utility\Html::escape() or
573  * \Drupal\Component\Utility\Xss::filter(). Furthermore, if the batch operation
574  * returns any user input in the 'results' or 'message' keys of $context, it
575  * must also sanitize them first.
576  *
577  * Sample callback_batch_operation():
578  * @code
579  * // Simple and artificial: load a node of a given type for a given user
580  * function my_function_1($uid, $type, &$context) {
581  *   // The $context array gathers batch context information about the execution (read),
582  *   // as well as 'return values' for the current operation (write)
583  *   // The following keys are provided :
584  *   // 'results' (read / write): The array of results gathered so far by
585  *   //   the batch processing, for the current operation to append its own.
586  *   // 'message' (write): A text message displayed in the progress page.
587  *   // The following keys allow for multi-step operations :
588  *   // 'sandbox' (read / write): An array that can be freely used to
589  *   //   store persistent data between iterations. It is recommended to
590  *   //   use this instead of $_SESSION, which is unsafe if the user
591  *   //   continues browsing in a separate window while the batch is processing.
592  *   // 'finished' (write): A float number between 0 and 1 informing
593  *   //   the processing engine of the completion level for the operation.
594  *   //   1 (or no value explicitly set) means the operation is finished
595  *   //   and the batch processing can continue to the next operation.
596  *
597  *   $nodes = \Drupal::entityTypeManager()->getStorage('node')
598  *     ->loadByProperties(['uid' => $uid, 'type' => $type]);
599  *   $node = reset($nodes);
600  *   $context['results'][] = $node->id() . ' : ' . Html::escape($node->label());
601  *   $context['message'] = Html::escape($node->label());
602  * }
603  *
604  * // A more advanced example is a multi-step operation that loads all rows,
605  * // five by five.
606  * function my_function_2(&$context) {
607  *   if (empty($context['sandbox'])) {
608  *     $context['sandbox']['progress'] = 0;
609  *     $context['sandbox']['current_id'] = 0;
610  *     $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT id) FROM {example}')->fetchField();
611  *   }
612  *   $limit = 5;
613  *   $result = db_select('example')
614  *     ->fields('example', array('id'))
615  *     ->condition('id', $context['sandbox']['current_id'], '>')
616  *     ->orderBy('id')
617  *     ->range(0, $limit)
618  *     ->execute();
619  *   foreach ($result as $row) {
620  *     $context['results'][] = $row->id . ' : ' . Html::escape($row->title);
621  *     $context['sandbox']['progress']++;
622  *     $context['sandbox']['current_id'] = $row->id;
623  *     $context['message'] = Html::escape($row->title);
624  *   }
625  *   if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
626  *     $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
627  *   }
628  * }
629  * @endcode
630  *
631  * Sample callback_batch_finished():
632  * @code
633  * function my_finished_callback($success, $results, $operations) {
634  *   // The 'success' parameter means no fatal PHP errors were detected. All
635  *   // other error management should be handled using 'results'.
636  *   if ($success) {
637  *     $message = \Drupal::translation()->formatPlural(count($results), 'One post processed.', '@count posts processed.');
638  *   }
639  *   else {
640  *     $message = t('Finished with an error.');
641  *   }
642  *   drupal_set_message($message);
643  *   // Providing data for the redirected page is done through $_SESSION.
644  *   foreach ($results as $result) {
645  *     $items[] = t('Loaded node %title.', array('%title' => $result));
646  *   }
647  *   $_SESSION['my_batch_results'] = $items;
648  * }
649  * @endcode
650  */
651
652 /**
653  * Adds a new batch.
654  *
655  * Batch operations are added as new batch sets. Batch sets are used to spread
656  * processing (primarily, but not exclusively, forms processing) over several
657  * page requests. This helps to ensure that the processing is not interrupted
658  * due to PHP timeouts, while users are still able to receive feedback on the
659  * progress of the ongoing operations. Combining related operations into
660  * distinct batch sets provides clean code independence for each batch set,
661  * ensuring that two or more batches, submitted independently, can be processed
662  * without mutual interference. Each batch set may specify its own set of
663  * operations and results, produce its own UI messages, and trigger its own
664  * 'finished' callback. Batch sets are processed sequentially, with the progress
665  * bar starting afresh for each new set.
666  *
667  * @param $batch_definition
668  *   An associative array defining the batch, with the following elements (all
669  *   are optional except as noted):
670  *   - operations: (required) Array of operations to be performed, where each
671  *     item is an array consisting of the name of an implementation of
672  *     callback_batch_operation() and an array of parameter.
673  *     Example:
674  *     @code
675  *     array(
676  *       array('callback_batch_operation_1', array($arg1)),
677  *       array('callback_batch_operation_2', array($arg2_1, $arg2_2)),
678  *     )
679  *     @endcode
680  *   - title: A safe, translated string to use as the title for the progress
681  *     page. Defaults to t('Processing').
682  *   - init_message: Message displayed while the processing is initialized.
683  *     Defaults to t('Initializing.').
684  *   - progress_message: Message displayed while processing the batch. Available
685  *     placeholders are @current, @remaining, @total, @percentage, @estimate and
686  *     @elapsed. Defaults to t('Completed @current of @total.').
687  *   - error_message: Message displayed if an error occurred while processing
688  *     the batch. Defaults to t('An error has occurred.').
689  *   - finished: Name of an implementation of callback_batch_finished(). This is
690  *     executed after the batch has completed. This should be used to perform
691  *     any result massaging that may be needed, and possibly save data in
692  *     $_SESSION for display after final page redirection.
693  *   - file: Path to the file containing the definitions of the 'operations' and
694  *     'finished' functions, for instance if they don't reside in the main
695  *     .module file. The path should be relative to base_path(), and thus should
696  *     be built using drupal_get_path().
697  *   - library: An array of batch-specific CSS and JS libraries.
698  *   - url_options: options passed to the \Drupal\Core\Url object when
699  *     constructing redirect URLs for the batch.
700  *   - progressive: A Boolean that indicates whether or not the batch needs to
701  *     run progressively. TRUE indicates that the batch will run in more than
702  *     one run. FALSE (default) indicates that the batch will finish in a single
703  *     run.
704  *   - queue: An override of the default queue (with name and class fields
705  *     optional). An array containing two elements:
706  *     - name: Unique identifier for the queue.
707  *     - class: The name of a class that implements
708  *       \Drupal\Core\Queue\QueueInterface, including the full namespace but not
709  *       starting with a backslash. It must have a constructor with two
710  *       arguments: $name and a \Drupal\Core\Database\Connection object.
711  *       Typically, the class will either be \Drupal\Core\Queue\Batch or
712  *       \Drupal\Core\Queue\BatchMemory. Defaults to Batch if progressive is
713  *       TRUE, or to BatchMemory if progressive is FALSE.
714  */
715 function batch_set($batch_definition) {
716   if ($batch_definition) {
717     $batch =& batch_get();
718
719     // Initialize the batch if needed.
720     if (empty($batch)) {
721       $batch = [
722         'sets' => [],
723         'has_form_submits' => FALSE,
724       ];
725     }
726
727     // Base and default properties for the batch set.
728     $init = [
729       'sandbox' => [],
730       'results' => [],
731       'success' => FALSE,
732       'start' => 0,
733       'elapsed' => 0,
734     ];
735     $defaults = [
736       'title' => t('Processing'),
737       'init_message' => t('Initializing.'),
738       'progress_message' => t('Completed @current of @total.'),
739       'error_message' => t('An error has occurred.'),
740     ];
741     $batch_set = $init + $batch_definition + $defaults;
742
743     // Tweak init_message to avoid the bottom of the page flickering down after
744     // init phase.
745     $batch_set['init_message'] .= '<br/>&nbsp;';
746
747     // The non-concurrent workflow of batch execution allows us to save
748     // numberOfItems() queries by handling our own counter.
749     $batch_set['total'] = count($batch_set['operations']);
750     $batch_set['count'] = $batch_set['total'];
751
752     // Add the set to the batch.
753     if (empty($batch['id'])) {
754       // The batch is not running yet. Simply add the new set.
755       $batch['sets'][] = $batch_set;
756     }
757     else {
758       // The set is being added while the batch is running. Insert the new set
759       // right after the current one to ensure execution order, and store its
760       // operations in a queue.
761       $index = $batch['current_set'] + 1;
762       $slice1 = array_slice($batch['sets'], 0, $index);
763       $slice2 = array_slice($batch['sets'], $index);
764       $batch['sets'] = array_merge($slice1, [$batch_set], $slice2);
765       _batch_populate_queue($batch, $index);
766     }
767   }
768 }
769
770 /**
771  * Processes the batch.
772  *
773  * This function is generally not needed in form submit handlers;
774  * Form API takes care of batches that were set during form submission.
775  *
776  * @param \Drupal\Core\Url|string $redirect
777  *   (optional) Either path or Url object to redirect to when the batch has
778  *   finished processing. Note that to simply force a batch to (conditionally)
779  *   redirect to a custom location after it is finished processing but to
780  *   otherwise allow the standard form API batch handling to occur, it is not
781  *   necessary to call batch_process() and use this parameter. Instead, make
782  *   the batch 'finished' callback return an instance of
783  *   \Symfony\Component\HttpFoundation\RedirectResponse, which will be used
784  *   automatically by the standard batch processing pipeline (and which takes
785  *   precedence over this parameter).
786  *   User will be redirected to the page that started the batch if this argument
787  *   is omitted and no redirect response was returned by the 'finished'
788  *   callback. Any query arguments will be automatically persisted.
789  * @param \Drupal\Core\Url $url
790  *   (optional) URL of the batch processing page. Should only be used for
791  *   separate scripts like update.php.
792  * @param $redirect_callback
793  *   (optional) Specify a function to be called to redirect to the progressive
794  *   processing page.
795  *
796  * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
797  *   A redirect response if the batch is progressive. No return value otherwise.
798  */
799 function batch_process($redirect = NULL, Url $url = NULL, $redirect_callback = NULL) {
800   $batch =& batch_get();
801
802   if (isset($batch)) {
803     // Add process information
804     $process_info = [
805       'current_set' => 0,
806       'progressive' => TRUE,
807       'url' => isset($url) ? $url : Url::fromRoute('system.batch_page.html'),
808       'source_url' => Url::fromRouteMatch(\Drupal::routeMatch())->mergeOptions(['query' => \Drupal::request()->query->all()]),
809       'batch_redirect' => $redirect,
810       'theme' => \Drupal::theme()->getActiveTheme()->getName(),
811       'redirect_callback' => $redirect_callback,
812     ];
813     $batch += $process_info;
814
815     // The batch is now completely built. Allow other modules to make changes
816     // to the batch so that it is easier to reuse batch processes in other
817     // environments.
818     \Drupal::moduleHandler()->alter('batch', $batch);
819
820     // Assign an arbitrary id: don't rely on a serial column in the 'batch'
821     // table, since non-progressive batches skip database storage completely.
822     $batch['id'] = db_next_id();
823
824     // Move operations to a job queue. Non-progressive batches will use a
825     // memory-based queue.
826     foreach ($batch['sets'] as $key => $batch_set) {
827       _batch_populate_queue($batch, $key);
828     }
829
830     // Initiate processing.
831     if ($batch['progressive']) {
832       // Now that we have a batch id, we can generate the redirection link in
833       // the generic error message.
834       /** @var \Drupal\Core\Url $batch_url */
835       $batch_url = $batch['url'];
836       /** @var \Drupal\Core\Url $error_url */
837       $error_url = clone $batch_url;
838       $query_options = $error_url->getOption('query');
839       $query_options['id'] = $batch['id'];
840       $query_options['op'] = 'finished';
841       $error_url->setOption('query', $query_options);
842
843       $batch['error_message'] = t('Please continue to <a href=":error_url">the error page</a>', [':error_url' => $error_url->toString(TRUE)->getGeneratedUrl()]);
844
845       // Clear the way for the redirection to the batch processing page, by
846       // saving and unsetting the 'destination', if there is any.
847       $request = \Drupal::request();
848       if ($request->query->has('destination')) {
849         $batch['destination'] = $request->query->get('destination');
850         $request->query->remove('destination');
851       }
852
853       // Store the batch.
854       \Drupal::service('batch.storage')->create($batch);
855
856       // Set the batch number in the session to guarantee that it will stay alive.
857       $_SESSION['batches'][$batch['id']] = TRUE;
858
859       // Redirect for processing.
860       $query_options = $error_url->getOption('query');
861       $query_options['op'] = 'start';
862       $query_options['id'] = $batch['id'];
863       $batch_url->setOption('query', $query_options);
864       if (($function = $batch['redirect_callback']) && function_exists($function)) {
865         $function($batch_url->toString(), ['query' => $query_options]);
866       }
867       else {
868         return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
869       }
870     }
871     else {
872       // Non-progressive execution: bypass the whole progressbar workflow
873       // and execute the batch in one pass.
874       require_once __DIR__ . '/batch.inc';
875       _batch_process();
876     }
877   }
878 }
879
880 /**
881  * Retrieves the current batch.
882  */
883 function &batch_get() {
884   // Not drupal_static(), because Batch API operates at a lower level than most
885   // use-cases for resetting static variables, and we specifically do not want a
886   // global drupal_static_reset() resetting the batch information. Functions
887   // that are part of the Batch API and need to reset the batch information may
888   // call batch_get() and manipulate the result by reference. Functions that are
889   // not part of the Batch API can also do this, but shouldn't.
890   static $batch = [];
891   return $batch;
892 }
893
894 /**
895  * Populates a job queue with the operations of a batch set.
896  *
897  * Depending on whether the batch is progressive or not, the
898  * Drupal\Core\Queue\Batch or Drupal\Core\Queue\BatchMemory handler classes will
899  * be used. The name and class of the queue are added by reference to the
900  * batch set.
901  *
902  * @param $batch
903  *   The batch array.
904  * @param $set_id
905  *   The id of the set to process.
906  */
907 function _batch_populate_queue(&$batch, $set_id) {
908   $batch_set = &$batch['sets'][$set_id];
909
910   if (isset($batch_set['operations'])) {
911     $batch_set += [
912       'queue' => [
913         'name' => 'drupal_batch:' . $batch['id'] . ':' . $set_id,
914         'class' => $batch['progressive'] ? 'Drupal\Core\Queue\Batch' : 'Drupal\Core\Queue\BatchMemory',
915       ],
916     ];
917
918     $queue = _batch_queue($batch_set);
919     $queue->createQueue();
920     foreach ($batch_set['operations'] as $operation) {
921       $queue->createItem($operation);
922     }
923
924     unset($batch_set['operations']);
925   }
926 }
927
928 /**
929  * Returns a queue object for a batch set.
930  *
931  * @param $batch_set
932  *   The batch set.
933  *
934  * @return
935  *   The queue object.
936  */
937 function _batch_queue($batch_set) {
938   static $queues;
939
940   if (!isset($queues)) {
941     $queues = [];
942   }
943
944   if (isset($batch_set['queue'])) {
945     $name = $batch_set['queue']['name'];
946     $class = $batch_set['queue']['class'];
947
948     if (!isset($queues[$class][$name])) {
949       $queues[$class][$name] = new $class($name, \Drupal::database());
950     }
951     return $queues[$class][$name];
952   }
953 }
954
955 /**
956  * @} End of "defgroup batch".
957  */