FormValidator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Access\CsrfTokenGenerator;
  5. use Drupal\Core\Render\Element;
  6. use Drupal\Core\StringTranslation\StringTranslationTrait;
  7. use Drupal\Core\StringTranslation\TranslationInterface;
  8. use Psr\Log\LoggerInterface;
  9. use Symfony\Component\HttpFoundation\RequestStack;
  10. /**
  11. * Provides validation of form submissions.
  12. */
  13. class FormValidator implements FormValidatorInterface {
  14. use StringTranslationTrait;
  15. /**
  16. * The CSRF token generator to validate the form token.
  17. *
  18. * @var \Drupal\Core\Access\CsrfTokenGenerator
  19. */
  20. protected $csrfToken;
  21. /**
  22. * The request stack.
  23. *
  24. * @var \Symfony\Component\HttpFoundation\RequestStack
  25. */
  26. protected $requestStack;
  27. /**
  28. * A logger instance.
  29. *
  30. * @var \Psr\Log\LoggerInterface
  31. */
  32. protected $logger;
  33. /**
  34. * The form error handler.
  35. *
  36. * @var \Drupal\Core\Form\FormErrorHandlerInterface
  37. */
  38. protected $formErrorHandler;
  39. /**
  40. * Constructs a new FormValidator.
  41. *
  42. * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
  43. * The request stack.
  44. * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
  45. * The string translation service.
  46. * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
  47. * The CSRF token generator.
  48. * @param \Psr\Log\LoggerInterface $logger
  49. * A logger instance.
  50. * @param \Drupal\Core\Form\FormErrorHandlerInterface $form_error_handler
  51. * The form error handler.
  52. */
  53. public function __construct(RequestStack $request_stack, TranslationInterface $string_translation, CsrfTokenGenerator $csrf_token, LoggerInterface $logger, FormErrorHandlerInterface $form_error_handler) {
  54. $this->requestStack = $request_stack;
  55. $this->stringTranslation = $string_translation;
  56. $this->csrfToken = $csrf_token;
  57. $this->logger = $logger;
  58. $this->formErrorHandler = $form_error_handler;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function executeValidateHandlers(&$form, FormStateInterface &$form_state) {
  64. // If there was a button pressed, use its handlers.
  65. $handlers = $form_state->getValidateHandlers();
  66. // Otherwise, check for a form-level handler.
  67. if (!$handlers && isset($form['#validate'])) {
  68. $handlers = $form['#validate'];
  69. }
  70. foreach ($handlers as $callback) {
  71. call_user_func_array($form_state->prepareCallback($callback), [&$form, &$form_state]);
  72. }
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function validateForm($form_id, &$form, FormStateInterface &$form_state) {
  78. // If this form is flagged to always validate, ensure that previous runs of
  79. // validation are ignored.
  80. if ($form_state->isValidationEnforced()) {
  81. $form_state->setValidationComplete(FALSE);
  82. }
  83. // If this form has completed validation, do not validate again.
  84. if ($form_state->isValidationComplete()) {
  85. return;
  86. }
  87. // If the session token was set by self::prepareForm(), ensure that it
  88. // matches the current user's session. This is duplicate to code in
  89. // FormBuilder::doBuildForm() but left to protect any custom form handling
  90. // code.
  91. if (isset($form['#token'])) {
  92. if (!$this->csrfToken->validate($form_state->getValue('form_token'), $form['#token']) || $form_state->hasInvalidToken()) {
  93. $this->setInvalidTokenError($form_state);
  94. // Stop here and don't run any further validation handlers, because they
  95. // could invoke non-safe operations which opens the door for CSRF
  96. // vulnerabilities.
  97. $this->finalizeValidation($form, $form_state, $form_id);
  98. return;
  99. }
  100. }
  101. // Recursively validate each form element.
  102. $this->doValidateForm($form, $form_state, $form_id);
  103. $this->finalizeValidation($form, $form_state, $form_id);
  104. $this->handleErrorsWithLimitedValidation($form, $form_state, $form_id);
  105. }
  106. /**
  107. * {@inheritdoc}
  108. */
  109. public function setInvalidTokenError(FormStateInterface $form_state) {
  110. // Setting this error will cause the form to fail validation.
  111. $form_state->setErrorByName('form_token', $this->t('The form has become outdated. Press the back button, copy any unsaved work in the form, and then reload the page.'));
  112. }
  113. /**
  114. * Handles validation errors for forms with limited validation.
  115. *
  116. * If validation errors are limited then remove any non validated form values,
  117. * so that only values that passed validation are left for submit callbacks.
  118. *
  119. * @param array $form
  120. * An associative array containing the structure of the form.
  121. * @param \Drupal\Core\Form\FormStateInterface $form_state
  122. * The current state of the form.
  123. * @param string $form_id
  124. * The unique string identifying the form.
  125. */
  126. protected function handleErrorsWithLimitedValidation(&$form, FormStateInterface &$form_state, $form_id) {
  127. // If validation errors are limited then remove any non validated form values,
  128. // so that only values that passed validation are left for submit callbacks.
  129. $triggering_element = $form_state->getTriggeringElement();
  130. if (isset($triggering_element['#limit_validation_errors']) && $triggering_element['#limit_validation_errors'] !== FALSE) {
  131. $values = [];
  132. foreach ($triggering_element['#limit_validation_errors'] as $section) {
  133. // If the section exists within $form_state->getValues(), even if the
  134. // value is NULL, copy it to $values.
  135. $section_exists = NULL;
  136. $value = NestedArray::getValue($form_state->getValues(), $section, $section_exists);
  137. if ($section_exists) {
  138. NestedArray::setValue($values, $section, $value);
  139. }
  140. }
  141. // A button's #value does not require validation, so for convenience we
  142. // allow the value of the clicked button to be retained in its normal
  143. // $form_state->getValues() locations, even if these locations are not
  144. // included in #limit_validation_errors.
  145. if (!empty($triggering_element['#is_button'])) {
  146. $button_value = $triggering_element['#value'];
  147. // Like all input controls, the button value may be in the location
  148. // dictated by #parents. If it is, copy it to $values, but do not
  149. // override what may already be in $values.
  150. $parents = $triggering_element['#parents'];
  151. if (!NestedArray::keyExists($values, $parents) && NestedArray::getValue($form_state->getValues(), $parents) === $button_value) {
  152. NestedArray::setValue($values, $parents, $button_value);
  153. }
  154. // Additionally, self::doBuildForm() places the button value in
  155. // $form_state->getValue(BUTTON_NAME). If it's still there, after
  156. // validation handlers have run, copy it to $values, but do not override
  157. // what may already be in $values.
  158. $name = $triggering_element['#name'];
  159. if (!isset($values[$name]) && $form_state->getValue($name) === $button_value) {
  160. $values[$name] = $button_value;
  161. }
  162. }
  163. $form_state->setValues($values);
  164. }
  165. }
  166. /**
  167. * Finalizes validation.
  168. *
  169. * @param array $form
  170. * An associative array containing the structure of the form.
  171. * @param \Drupal\Core\Form\FormStateInterface $form_state
  172. * The current state of the form.
  173. * @param string $form_id
  174. * The unique string identifying the form.
  175. */
  176. protected function finalizeValidation(&$form, FormStateInterface &$form_state, $form_id) {
  177. // Delegate handling of form errors to a service.
  178. $this->formErrorHandler->handleFormErrors($form, $form_state);
  179. // Mark this form as validated.
  180. $form_state->setValidationComplete();
  181. }
  182. /**
  183. * Performs validation on form elements.
  184. *
  185. * First ensures required fields are completed, #maxlength is not exceeded,
  186. * and selected options were in the list of options given to the user. Then
  187. * calls user-defined validators.
  188. *
  189. * @param $elements
  190. * An associative array containing the structure of the form.
  191. * @param \Drupal\Core\Form\FormStateInterface $form_state
  192. * The current state of the form. The current user-submitted data is stored
  193. * in $form_state->getValues(), though form validation functions are passed
  194. * an explicit copy of the values for the sake of simplicity. Validation
  195. * handlers can also $form_state to pass information on to submit handlers.
  196. * For example:
  197. * $form_state->set('data_for_submission', $data);
  198. * This technique is useful when validation requires file parsing,
  199. * web service requests, or other expensive requests that should
  200. * not be repeated in the submission step.
  201. * @param $form_id
  202. * A unique string identifying the form for validation, submission,
  203. * theming, and hook_form_alter functions.
  204. */
  205. protected function doValidateForm(&$elements, FormStateInterface &$form_state, $form_id = NULL) {
  206. // Recurse through all children, sorting the elements so that the order of
  207. // error messages displayed to the user matches the order of elements in
  208. // the form. Use a copy of $elements so that it is not modified by the
  209. // sorting itself.
  210. $elements_sorted = $elements;
  211. foreach (Element::children($elements_sorted, TRUE) as $key) {
  212. if (isset($elements[$key]) && $elements[$key]) {
  213. $this->doValidateForm($elements[$key], $form_state);
  214. }
  215. }
  216. // Validate the current input.
  217. if (!isset($elements['#validated']) || !$elements['#validated']) {
  218. // The following errors are always shown.
  219. if (isset($elements['#needs_validation'])) {
  220. $this->performRequiredValidation($elements, $form_state);
  221. }
  222. // Set up the limited validation for errors.
  223. $form_state->setLimitValidationErrors($this->determineLimitValidationErrors($form_state));
  224. // Make sure a value is passed when the field is required.
  225. if (isset($elements['#needs_validation']) && $elements['#required']) {
  226. // A simple call to empty() will not cut it here as some fields, like
  227. // checkboxes, can return a valid value of '0'. Instead, check the
  228. // length if it's a string, and the item count if it's an array.
  229. // An unchecked checkbox has a #value of integer 0, different than
  230. // string '0', which could be a valid value.
  231. $is_countable = is_array($elements['#value']) || $elements['#value'] instanceof \Countable;
  232. $is_empty_multiple = $is_countable && count($elements['#value']) == 0;
  233. $is_empty_string = (is_string($elements['#value']) && mb_strlen(trim($elements['#value'])) == 0);
  234. $is_empty_value = ($elements['#value'] === 0);
  235. $is_empty_null = is_null($elements['#value']);
  236. if ($is_empty_multiple || $is_empty_string || $is_empty_value || $is_empty_null) {
  237. // Flag this element as #required_but_empty to allow #element_validate
  238. // handlers to set a custom required error message, but without having
  239. // to re-implement the complex logic to figure out whether the field
  240. // value is empty.
  241. $elements['#required_but_empty'] = TRUE;
  242. }
  243. }
  244. // Call user-defined form level validators.
  245. if (isset($form_id)) {
  246. $this->executeValidateHandlers($elements, $form_state);
  247. }
  248. // Call any element-specific validators. These must act on the element
  249. // #value data.
  250. elseif (isset($elements['#element_validate'])) {
  251. foreach ($elements['#element_validate'] as $callback) {
  252. $complete_form = &$form_state->getCompleteForm();
  253. call_user_func_array($form_state->prepareCallback($callback), [&$elements, &$form_state, &$complete_form]);
  254. }
  255. }
  256. // Ensure that a #required form error is thrown, regardless of whether
  257. // #element_validate handlers changed any properties. If $is_empty_value
  258. // is defined, then above #required validation code ran, so the other
  259. // variables are also known to be defined and we can test them again.
  260. if (isset($is_empty_value) && ($is_empty_multiple || $is_empty_string || $is_empty_value || $is_empty_null)) {
  261. if (isset($elements['#required_error'])) {
  262. $form_state->setError($elements, $elements['#required_error']);
  263. }
  264. // A #title is not mandatory for form elements, but without it we cannot
  265. // set a form error message. So when a visible title is undesirable,
  266. // form constructors are encouraged to set #title anyway, and then set
  267. // #title_display to 'invisible'. This improves accessibility.
  268. elseif (isset($elements['#title'])) {
  269. $form_state->setError($elements, $this->t('@name field is required.', ['@name' => $elements['#title']]));
  270. }
  271. else {
  272. $form_state->setError($elements);
  273. }
  274. }
  275. $elements['#validated'] = TRUE;
  276. }
  277. // Done validating this element, so turn off error suppression.
  278. // self::doValidateForm() turns it on again when starting on the next
  279. // element, if it's still appropriate to do so.
  280. $form_state->setLimitValidationErrors(NULL);
  281. }
  282. /**
  283. * Performs validation of elements that are not subject to limited validation.
  284. *
  285. * @param array $elements
  286. * An associative array containing the structure of the form.
  287. * @param \Drupal\Core\Form\FormStateInterface $form_state
  288. * The current state of the form. The current user-submitted data is stored
  289. * in $form_state->getValues(), though form validation functions are passed
  290. * an explicit copy of the values for the sake of simplicity. Validation
  291. * handlers can also $form_state to pass information on to submit handlers.
  292. * For example:
  293. * $form_state->set('data_for_submission', $data);
  294. * This technique is useful when validation requires file parsing,
  295. * web service requests, or other expensive requests that should
  296. * not be repeated in the submission step.
  297. */
  298. protected function performRequiredValidation(&$elements, FormStateInterface &$form_state) {
  299. // Verify that the value is not longer than #maxlength.
  300. if (isset($elements['#maxlength']) && mb_strlen($elements['#value']) > $elements['#maxlength']) {
  301. $form_state->setError($elements, $this->t('@name cannot be longer than %max characters but is currently %length characters long.', ['@name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title'], '%max' => $elements['#maxlength'], '%length' => mb_strlen($elements['#value'])]));
  302. }
  303. if (isset($elements['#options']) && isset($elements['#value'])) {
  304. if ($elements['#type'] == 'select') {
  305. $options = OptGroup::flattenOptions($elements['#options']);
  306. }
  307. else {
  308. $options = $elements['#options'];
  309. }
  310. if (is_array($elements['#value'])) {
  311. $value = in_array($elements['#type'], ['checkboxes', 'tableselect']) ? array_keys($elements['#value']) : $elements['#value'];
  312. foreach ($value as $v) {
  313. if (!isset($options[$v])) {
  314. $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
  315. $this->logger->error('Illegal choice %choice in %name element.', ['%choice' => $v, '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']]);
  316. }
  317. }
  318. }
  319. // Non-multiple select fields always have a value in HTML. If the user
  320. // does not change the form, it will be the value of the first option.
  321. // Because of this, form validation for the field will almost always
  322. // pass, even if the user did not select anything. To work around this
  323. // browser behavior, required select fields without a #default_value
  324. // get an additional, first empty option. In case the submitted value
  325. // is identical to the empty option's value, we reset the element's
  326. // value to NULL to trigger the regular #required handling below.
  327. // @see \Drupal\Core\Render\Element\Select::processSelect()
  328. elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
  329. $elements['#value'] = NULL;
  330. $form_state->setValueForElement($elements, NULL);
  331. }
  332. elseif (!isset($options[$elements['#value']])) {
  333. $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
  334. $this->logger->error('Illegal choice %choice in %name element.', ['%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']]);
  335. }
  336. }
  337. }
  338. /**
  339. * Determines if validation errors should be limited.
  340. *
  341. * @param \Drupal\Core\Form\FormStateInterface $form_state
  342. * The current state of the form.
  343. *
  344. * @return array|null
  345. */
  346. protected function determineLimitValidationErrors(FormStateInterface &$form_state) {
  347. // While this element is being validated, it may be desired that some
  348. // calls to \Drupal\Core\Form\FormStateInterface::setErrorByName() be
  349. // suppressed and not result in a form error, so that a button that
  350. // implements low-risk functionality (such as "Previous" or "Add more") that
  351. // doesn't require all user input to be valid can still have its submit
  352. // handlers triggered. The triggering element's #limit_validation_errors
  353. // property contains the information for which errors are needed, and all
  354. // other errors are to be suppressed. The #limit_validation_errors property
  355. // is ignored if submit handlers will run, but the element doesn't have a
  356. // #submit property, because it's too large a security risk to have any
  357. // invalid user input when executing form-level submit handlers.
  358. $triggering_element = $form_state->getTriggeringElement();
  359. if (isset($triggering_element['#limit_validation_errors']) && ($triggering_element['#limit_validation_errors'] !== FALSE) && !($form_state->isSubmitted() && !isset($triggering_element['#submit']))) {
  360. return $triggering_element['#limit_validation_errors'];
  361. }
  362. // If submit handlers won't run (due to the submission having been
  363. // triggered by an element whose #executes_submit_callback property isn't
  364. // TRUE), then it's safe to suppress all validation errors, and we do so
  365. // by default, which is particularly useful during an Ajax submission
  366. // triggered by a non-button. An element can override this default by
  367. // setting the #limit_validation_errors property. For button element
  368. // types, #limit_validation_errors defaults to FALSE, so that full
  369. // validation is their default behavior.
  370. elseif ($triggering_element && !isset($triggering_element['#limit_validation_errors']) && !$form_state->isSubmitted()) {
  371. return [];
  372. }
  373. // As an extra security measure, explicitly turn off error suppression if
  374. // one of the above conditions wasn't met. Since this is also done at the
  375. // end of this function, doing it here is only to handle the rare edge
  376. // case where a validate handler invokes form processing of another form.
  377. else {
  378. return NULL;
  379. }
  380. }
  381. }