Drupal investigation

form.inc 38KB

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