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