form.inc 38 KB

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