FormValidator.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. $url = $this->requestStack->getCurrentRequest()->getRequestUri();
  111. // Setting this error will cause the form to fail validation.
  112. $form_state->setErrorByName('form_token', $this->t('The form has become outdated. Copy any unsaved work in the form below and then <a href=":link">reload this page</a>.', [':link' => $url]));
  113. }
  114. /**
  115. * Handles validation errors for forms with limited validation.
  116. *
  117. * If validation errors are limited then remove any non validated form values,
  118. * so that only values that passed validation are left for submit callbacks.
  119. *
  120. * @param array $form
  121. * An associative array containing the structure of the form.
  122. * @param \Drupal\Core\Form\FormStateInterface $form_state
  123. * The current state of the form.
  124. * @param string $form_id
  125. * The unique string identifying the form.
  126. */
  127. protected function handleErrorsWithLimitedValidation(&$form, FormStateInterface &$form_state, $form_id) {
  128. // If validation errors are limited then remove any non validated form values,
  129. // so that only values that passed validation are left for submit callbacks.
  130. $triggering_element = $form_state->getTriggeringElement();
  131. if (isset($triggering_element['#limit_validation_errors']) && $triggering_element['#limit_validation_errors'] !== FALSE) {
  132. $values = [];
  133. foreach ($triggering_element['#limit_validation_errors'] as $section) {
  134. // If the section exists within $form_state->getValues(), even if the
  135. // value is NULL, copy it to $values.
  136. $section_exists = NULL;
  137. $value = NestedArray::getValue($form_state->getValues(), $section, $section_exists);
  138. if ($section_exists) {
  139. NestedArray::setValue($values, $section, $value);
  140. }
  141. }
  142. // A button's #value does not require validation, so for convenience we
  143. // allow the value of the clicked button to be retained in its normal
  144. // $form_state->getValues() locations, even if these locations are not
  145. // included in #limit_validation_errors.
  146. if (!empty($triggering_element['#is_button'])) {
  147. $button_value = $triggering_element['#value'];
  148. // Like all input controls, the button value may be in the location
  149. // dictated by #parents. If it is, copy it to $values, but do not
  150. // override what may already be in $values.
  151. $parents = $triggering_element['#parents'];
  152. if (!NestedArray::keyExists($values, $parents) && NestedArray::getValue($form_state->getValues(), $parents) === $button_value) {
  153. NestedArray::setValue($values, $parents, $button_value);
  154. }
  155. // Additionally, self::doBuildForm() places the button value in
  156. // $form_state->getValue(BUTTON_NAME). If it's still there, after
  157. // validation handlers have run, copy it to $values, but do not override
  158. // what may already be in $values.
  159. $name = $triggering_element['#name'];
  160. if (!isset($values[$name]) && $form_state->getValue($name) === $button_value) {
  161. $values[$name] = $button_value;
  162. }
  163. }
  164. $form_state->setValues($values);
  165. }
  166. }
  167. /**
  168. * Finalizes validation.
  169. *
  170. * @param array $form
  171. * An associative array containing the structure of the form.
  172. * @param \Drupal\Core\Form\FormStateInterface $form_state
  173. * The current state of the form.
  174. * @param string $form_id
  175. * The unique string identifying the form.
  176. */
  177. protected function finalizeValidation(&$form, FormStateInterface &$form_state, $form_id) {
  178. // Delegate handling of form errors to a service.
  179. $this->formErrorHandler->handleFormErrors($form, $form_state);
  180. // Mark this form as validated.
  181. $form_state->setValidationComplete();
  182. }
  183. /**
  184. * Performs validation on form elements.
  185. *
  186. * First ensures required fields are completed, #maxlength is not exceeded,
  187. * and selected options were in the list of options given to the user. Then
  188. * calls user-defined validators.
  189. *
  190. * @param $elements
  191. * An associative array containing the structure of the form.
  192. * @param \Drupal\Core\Form\FormStateInterface $form_state
  193. * The current state of the form. The current user-submitted data is stored
  194. * in $form_state->getValues(), though form validation functions are passed
  195. * an explicit copy of the values for the sake of simplicity. Validation
  196. * handlers can also $form_state to pass information on to submit handlers.
  197. * For example:
  198. * $form_state->set('data_for_submission', $data);
  199. * This technique is useful when validation requires file parsing,
  200. * web service requests, or other expensive requests that should
  201. * not be repeated in the submission step.
  202. * @param $form_id
  203. * A unique string identifying the form for validation, submission,
  204. * theming, and hook_form_alter functions.
  205. */
  206. protected function doValidateForm(&$elements, FormStateInterface &$form_state, $form_id = NULL) {
  207. // Recurse through all children, sorting the elements so that the order of
  208. // error messages displayed to the user matches the order of elements in
  209. // the form. Use a copy of $elements so that it is not modified by the
  210. // sorting itself.
  211. $elements_sorted = $elements;
  212. foreach (Element::children($elements_sorted, TRUE) as $key) {
  213. if (isset($elements[$key]) && $elements[$key]) {
  214. $this->doValidateForm($elements[$key], $form_state);
  215. }
  216. }
  217. // Validate the current input.
  218. if (!isset($elements['#validated']) || !$elements['#validated']) {
  219. // The following errors are always shown.
  220. if (isset($elements['#needs_validation'])) {
  221. $this->performRequiredValidation($elements, $form_state);
  222. }
  223. // Set up the limited validation for errors.
  224. $form_state->setLimitValidationErrors($this->determineLimitValidationErrors($form_state));
  225. // Make sure a value is passed when the field is required.
  226. if (isset($elements['#needs_validation']) && $elements['#required']) {
  227. // A simple call to empty() will not cut it here as some fields, like
  228. // checkboxes, can return a valid value of '0'. Instead, check the
  229. // length if it's a string, and the item count if it's an array.
  230. // An unchecked checkbox has a #value of integer 0, different than
  231. // string '0', which could be a valid value.
  232. $is_countable = is_array($elements['#value']) || $elements['#value'] instanceof \Countable;
  233. $is_empty_multiple = $is_countable && count($elements['#value']) == 0;
  234. $is_empty_string = (is_string($elements['#value']) && mb_strlen(trim($elements['#value'])) == 0);
  235. $is_empty_value = ($elements['#value'] === 0);
  236. $is_empty_null = is_null($elements['#value']);
  237. if ($is_empty_multiple || $is_empty_string || $is_empty_value || $is_empty_null) {
  238. // Flag this element as #required_but_empty to allow #element_validate
  239. // handlers to set a custom required error message, but without having
  240. // to re-implement the complex logic to figure out whether the field
  241. // value is empty.
  242. $elements['#required_but_empty'] = TRUE;
  243. }
  244. }
  245. // Call user-defined form level validators.
  246. if (isset($form_id)) {
  247. $this->executeValidateHandlers($elements, $form_state);
  248. }
  249. // Call any element-specific validators. These must act on the element
  250. // #value data.
  251. elseif (isset($elements['#element_validate'])) {
  252. foreach ($elements['#element_validate'] as $callback) {
  253. $complete_form = &$form_state->getCompleteForm();
  254. call_user_func_array($form_state->prepareCallback($callback), [&$elements, &$form_state, &$complete_form]);
  255. }
  256. }
  257. // Ensure that a #required form error is thrown, regardless of whether
  258. // #element_validate handlers changed any properties. If $is_empty_value
  259. // is defined, then above #required validation code ran, so the other
  260. // variables are also known to be defined and we can test them again.
  261. if (isset($is_empty_value) && ($is_empty_multiple || $is_empty_string || $is_empty_value || $is_empty_null)) {
  262. if (isset($elements['#required_error'])) {
  263. $form_state->setError($elements, $elements['#required_error']);
  264. }
  265. // A #title is not mandatory for form elements, but without it we cannot
  266. // set a form error message. So when a visible title is undesirable,
  267. // form constructors are encouraged to set #title anyway, and then set
  268. // #title_display to 'invisible'. This improves accessibility.
  269. elseif (isset($elements['#title'])) {
  270. $form_state->setError($elements, $this->t('@name field is required.', ['@name' => $elements['#title']]));
  271. }
  272. else {
  273. $form_state->setError($elements);
  274. }
  275. }
  276. $elements['#validated'] = TRUE;
  277. }
  278. // Done validating this element, so turn off error suppression.
  279. // self::doValidateForm() turns it on again when starting on the next
  280. // element, if it's still appropriate to do so.
  281. $form_state->setLimitValidationErrors(NULL);
  282. }
  283. /**
  284. * Performs validation of elements that are not subject to limited validation.
  285. *
  286. * @param array $elements
  287. * An associative array containing the structure of the form.
  288. * @param \Drupal\Core\Form\FormStateInterface $form_state
  289. * The current state of the form. The current user-submitted data is stored
  290. * in $form_state->getValues(), though form validation functions are passed
  291. * an explicit copy of the values for the sake of simplicity. Validation
  292. * handlers can also $form_state to pass information on to submit handlers.
  293. * For example:
  294. * $form_state->set('data_for_submission', $data);
  295. * This technique is useful when validation requires file parsing,
  296. * web service requests, or other expensive requests that should
  297. * not be repeated in the submission step.
  298. */
  299. protected function performRequiredValidation(&$elements, FormStateInterface &$form_state) {
  300. // Verify that the value is not longer than #maxlength.
  301. if (isset($elements['#maxlength']) && mb_strlen($elements['#value']) > $elements['#maxlength']) {
  302. $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'])]));
  303. }
  304. if (isset($elements['#options']) && isset($elements['#value'])) {
  305. if ($elements['#type'] == 'select') {
  306. $options = OptGroup::flattenOptions($elements['#options']);
  307. }
  308. else {
  309. $options = $elements['#options'];
  310. }
  311. if (is_array($elements['#value'])) {
  312. $value = in_array($elements['#type'], ['checkboxes', 'tableselect']) ? array_keys($elements['#value']) : $elements['#value'];
  313. foreach ($value as $v) {
  314. if (!isset($options[$v])) {
  315. $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
  316. $this->logger->error('Illegal choice %choice in %name element.', ['%choice' => $v, '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']]);
  317. }
  318. }
  319. }
  320. // Non-multiple select fields always have a value in HTML. If the user
  321. // does not change the form, it will be the value of the first option.
  322. // Because of this, form validation for the field will almost always
  323. // pass, even if the user did not select anything. To work around this
  324. // browser behavior, required select fields without a #default_value
  325. // get an additional, first empty option. In case the submitted value
  326. // is identical to the empty option's value, we reset the element's
  327. // value to NULL to trigger the regular #required handling below.
  328. // @see \Drupal\Core\Render\Element\Select::processSelect()
  329. elseif ($elements['#type'] == 'select' && !$elements['#multiple'] && $elements['#required'] && !isset($elements['#default_value']) && $elements['#value'] === $elements['#empty_value']) {
  330. $elements['#value'] = NULL;
  331. $form_state->setValueForElement($elements, NULL);
  332. }
  333. elseif (!isset($options[$elements['#value']])) {
  334. $form_state->setError($elements, $this->t('An illegal choice has been detected. Please contact the site administrator.'));
  335. $this->logger->error('Illegal choice %choice in %name element.', ['%choice' => $elements['#value'], '%name' => empty($elements['#title']) ? $elements['#parents'][0] : $elements['#title']]);
  336. }
  337. }
  338. }
  339. /**
  340. * Determines if validation errors should be limited.
  341. *
  342. * @param \Drupal\Core\Form\FormStateInterface $form_state
  343. * The current state of the form.
  344. *
  345. * @return array|null
  346. */
  347. protected function determineLimitValidationErrors(FormStateInterface &$form_state) {
  348. // While this element is being validated, it may be desired that some
  349. // calls to \Drupal\Core\Form\FormStateInterface::setErrorByName() be
  350. // suppressed and not result in a form error, so that a button that
  351. // implements low-risk functionality (such as "Previous" or "Add more") that
  352. // doesn't require all user input to be valid can still have its submit
  353. // handlers triggered. The triggering element's #limit_validation_errors
  354. // property contains the information for which errors are needed, and all
  355. // other errors are to be suppressed. The #limit_validation_errors property
  356. // is ignored if submit handlers will run, but the element doesn't have a
  357. // #submit property, because it's too large a security risk to have any
  358. // invalid user input when executing form-level submit handlers.
  359. $triggering_element = $form_state->getTriggeringElement();
  360. if (isset($triggering_element['#limit_validation_errors']) && ($triggering_element['#limit_validation_errors'] !== FALSE) && !($form_state->isSubmitted() && !isset($triggering_element['#submit']))) {
  361. return $triggering_element['#limit_validation_errors'];
  362. }
  363. // If submit handlers won't run (due to the submission having been
  364. // triggered by an element whose #executes_submit_callback property isn't
  365. // TRUE), then it's safe to suppress all validation errors, and we do so
  366. // by default, which is particularly useful during an Ajax submission
  367. // triggered by a non-button. An element can override this default by
  368. // setting the #limit_validation_errors property. For button element
  369. // types, #limit_validation_errors defaults to FALSE, so that full
  370. // validation is their default behavior.
  371. elseif ($triggering_element && !isset($triggering_element['#limit_validation_errors']) && !$form_state->isSubmitted()) {
  372. return [];
  373. }
  374. // As an extra security measure, explicitly turn off error suppression if
  375. // one of the above conditions wasn't met. Since this is also done at the
  376. // end of this function, doing it here is only to handle the rare edge
  377. // case where a validate handler invokes form processing of another form.
  378. else {
  379. return NULL;
  380. }
  381. }
  382. }