form.inc 38 KB

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