NativeRequestHandler.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form;
  11. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  12. use Symfony\Component\Form\Util\ServerParams;
  13. /**
  14. * A request handler using PHP super globals $_GET, $_POST and $_SERVER.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class NativeRequestHandler implements RequestHandlerInterface
  19. {
  20. private $serverParams;
  21. /**
  22. * The allowed keys of the $_FILES array.
  23. */
  24. private const FILE_KEYS = [
  25. 'error',
  26. 'name',
  27. 'size',
  28. 'tmp_name',
  29. 'type',
  30. ];
  31. public function __construct(ServerParams $params = null)
  32. {
  33. $this->serverParams = $params ?: new ServerParams();
  34. }
  35. /**
  36. * {@inheritdoc}
  37. *
  38. * @throws Exception\UnexpectedTypeException If the $request is not null
  39. */
  40. public function handleRequest(FormInterface $form, $request = null)
  41. {
  42. if (null !== $request) {
  43. throw new UnexpectedTypeException($request, 'null');
  44. }
  45. $name = $form->getName();
  46. $method = $form->getConfig()->getMethod();
  47. if ($method !== self::getRequestMethod()) {
  48. return;
  49. }
  50. // For request methods that must not have a request body we fetch data
  51. // from the query string. Otherwise we look for data in the request body.
  52. if ('GET' === $method || 'HEAD' === $method || 'TRACE' === $method) {
  53. if ('' === $name) {
  54. $data = $_GET;
  55. } else {
  56. // Don't submit GET requests if the form's name does not exist
  57. // in the request
  58. if (!isset($_GET[$name])) {
  59. return;
  60. }
  61. $data = $_GET[$name];
  62. }
  63. } else {
  64. // Mark the form with an error if the uploaded size was too large
  65. // This is done here and not in FormValidator because $_POST is
  66. // empty when that error occurs. Hence the form is never submitted.
  67. if ($this->serverParams->hasPostMaxSizeBeenExceeded()) {
  68. // Submit the form, but don't clear the default values
  69. $form->submit(null, false);
  70. $form->addError(new FormError(
  71. $form->getConfig()->getOption('upload_max_size_message')(),
  72. null,
  73. ['{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()]
  74. ));
  75. return;
  76. }
  77. $fixedFiles = [];
  78. foreach ($_FILES as $fileKey => $file) {
  79. $fixedFiles[$fileKey] = self::stripEmptyFiles(self::fixPhpFilesArray($file));
  80. }
  81. if ('' === $name) {
  82. $params = $_POST;
  83. $files = $fixedFiles;
  84. } elseif (\array_key_exists($name, $_POST) || \array_key_exists($name, $fixedFiles)) {
  85. $default = $form->getConfig()->getCompound() ? [] : null;
  86. $params = \array_key_exists($name, $_POST) ? $_POST[$name] : $default;
  87. $files = \array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default;
  88. } else {
  89. // Don't submit the form if it is not present in the request
  90. return;
  91. }
  92. if (\is_array($params) && \is_array($files)) {
  93. $data = array_replace_recursive($params, $files);
  94. } else {
  95. $data = $params ?: $files;
  96. }
  97. }
  98. // Don't auto-submit the form unless at least one field is present.
  99. if ('' === $name && \count(array_intersect_key($data, $form->all())) <= 0) {
  100. return;
  101. }
  102. if (\is_array($data) && \array_key_exists('_method', $data) && $method === $data['_method'] && !$form->has('_method')) {
  103. unset($data['_method']);
  104. }
  105. $form->submit($data, 'PATCH' !== $method);
  106. }
  107. /**
  108. * {@inheritdoc}
  109. */
  110. public function isFileUpload($data)
  111. {
  112. // POST data will always be strings or arrays of strings. Thus, we can be sure
  113. // that the submitted data is a file upload if the "error" value is an integer
  114. // (this value must have been injected by PHP itself).
  115. return \is_array($data) && isset($data['error']) && \is_int($data['error']);
  116. }
  117. /**
  118. * @return int|null
  119. */
  120. public function getUploadFileError($data)
  121. {
  122. if (!\is_array($data)) {
  123. return null;
  124. }
  125. if (!isset($data['error'])) {
  126. return null;
  127. }
  128. if (!\is_int($data['error'])) {
  129. return null;
  130. }
  131. if (\UPLOAD_ERR_OK === $data['error']) {
  132. return null;
  133. }
  134. return $data['error'];
  135. }
  136. /**
  137. * Returns the method used to submit the request to the server.
  138. */
  139. private static function getRequestMethod(): string
  140. {
  141. $method = isset($_SERVER['REQUEST_METHOD'])
  142. ? strtoupper($_SERVER['REQUEST_METHOD'])
  143. : 'GET';
  144. if ('POST' === $method && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
  145. $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  146. }
  147. return $method;
  148. }
  149. /**
  150. * Fixes a malformed PHP $_FILES array.
  151. *
  152. * PHP has a bug that the format of the $_FILES array differs, depending on
  153. * whether the uploaded file fields had normal field names or array-like
  154. * field names ("normal" vs. "parent[child]").
  155. *
  156. * This method fixes the array to look like the "normal" $_FILES array.
  157. *
  158. * It's safe to pass an already converted array, in which case this method
  159. * just returns the original array unmodified.
  160. *
  161. * This method is identical to {@link \Symfony\Component\HttpFoundation\FileBag::fixPhpFilesArray}
  162. * and should be kept as such in order to port fixes quickly and easily.
  163. *
  164. * @return mixed
  165. */
  166. private static function fixPhpFilesArray($data)
  167. {
  168. if (!\is_array($data)) {
  169. return $data;
  170. }
  171. $keys = array_keys($data);
  172. sort($keys);
  173. if (self::FILE_KEYS !== $keys || !isset($data['name']) || !\is_array($data['name'])) {
  174. return $data;
  175. }
  176. $files = $data;
  177. foreach (self::FILE_KEYS as $k) {
  178. unset($files[$k]);
  179. }
  180. foreach ($data['name'] as $key => $name) {
  181. $files[$key] = self::fixPhpFilesArray([
  182. 'error' => $data['error'][$key],
  183. 'name' => $name,
  184. 'type' => $data['type'][$key],
  185. 'tmp_name' => $data['tmp_name'][$key],
  186. 'size' => $data['size'][$key],
  187. ]);
  188. }
  189. return $files;
  190. }
  191. /**
  192. * Sets empty uploaded files to NULL in the given uploaded files array.
  193. *
  194. * @return mixed Returns the stripped upload data
  195. */
  196. private static function stripEmptyFiles($data)
  197. {
  198. if (!\is_array($data)) {
  199. return $data;
  200. }
  201. $keys = array_keys($data);
  202. sort($keys);
  203. if (self::FILE_KEYS === $keys) {
  204. if (\UPLOAD_ERR_NO_FILE === $data['error']) {
  205. return null;
  206. }
  207. return $data;
  208. }
  209. foreach ($data as $key => $value) {
  210. $data[$key] = self::stripEmptyFiles($value);
  211. }
  212. return $data;
  213. }
  214. }