NativeRequestHandler.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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 static $fileKeys = array(
  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. public function handleRequest(FormInterface $form, $request = null)
  39. {
  40. if (null !== $request) {
  41. throw new UnexpectedTypeException($request, 'null');
  42. }
  43. $name = $form->getName();
  44. $method = $form->getConfig()->getMethod();
  45. if ($method !== self::getRequestMethod()) {
  46. return;
  47. }
  48. // For request methods that must not have a request body we fetch data
  49. // from the query string. Otherwise we look for data in the request body.
  50. if ('GET' === $method || 'HEAD' === $method || 'TRACE' === $method) {
  51. if ('' === $name) {
  52. $data = $_GET;
  53. } else {
  54. // Don't submit GET requests if the form's name does not exist
  55. // in the request
  56. if (!isset($_GET[$name])) {
  57. return;
  58. }
  59. $data = $_GET[$name];
  60. }
  61. } else {
  62. // Mark the form with an error if the uploaded size was too large
  63. // This is done here and not in FormValidator because $_POST is
  64. // empty when that error occurs. Hence the form is never submitted.
  65. if ($this->serverParams->hasPostMaxSizeBeenExceeded()) {
  66. // Submit the form, but don't clear the default values
  67. $form->submit(null, false);
  68. $form->addError(new FormError(
  69. \call_user_func($form->getConfig()->getOption('upload_max_size_message')),
  70. null,
  71. array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize())
  72. ));
  73. return;
  74. }
  75. $fixedFiles = array();
  76. foreach ($_FILES as $fileKey => $file) {
  77. $fixedFiles[$fileKey] = self::stripEmptyFiles(self::fixPhpFilesArray($file));
  78. }
  79. if ('' === $name) {
  80. $params = $_POST;
  81. $files = $fixedFiles;
  82. } elseif (array_key_exists($name, $_POST) || array_key_exists($name, $fixedFiles)) {
  83. $default = $form->getConfig()->getCompound() ? array() : null;
  84. $params = array_key_exists($name, $_POST) ? $_POST[$name] : $default;
  85. $files = array_key_exists($name, $fixedFiles) ? $fixedFiles[$name] : $default;
  86. } else {
  87. // Don't submit the form if it is not present in the request
  88. return;
  89. }
  90. if (\is_array($params) && \is_array($files)) {
  91. $data = array_replace_recursive($params, $files);
  92. } else {
  93. $data = $params ?: $files;
  94. }
  95. }
  96. // Don't auto-submit the form unless at least one field is present.
  97. if ('' === $name && \count(array_intersect_key($data, $form->all())) <= 0) {
  98. return;
  99. }
  100. $form->submit($data, 'PATCH' !== $method);
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function isFileUpload($data)
  106. {
  107. // POST data will always be strings or arrays of strings. Thus, we can be sure
  108. // that the submitted data is a file upload if the "error" value is an integer
  109. // (this value must have been injected by PHP itself).
  110. return \is_array($data) && isset($data['error']) && \is_int($data['error']);
  111. }
  112. /**
  113. * Returns the method used to submit the request to the server.
  114. *
  115. * @return string The request method
  116. */
  117. private static function getRequestMethod()
  118. {
  119. $method = isset($_SERVER['REQUEST_METHOD'])
  120. ? strtoupper($_SERVER['REQUEST_METHOD'])
  121. : 'GET';
  122. if ('POST' === $method && isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'])) {
  123. $method = strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  124. }
  125. return $method;
  126. }
  127. /**
  128. * Fixes a malformed PHP $_FILES array.
  129. *
  130. * PHP has a bug that the format of the $_FILES array differs, depending on
  131. * whether the uploaded file fields had normal field names or array-like
  132. * field names ("normal" vs. "parent[child]").
  133. *
  134. * This method fixes the array to look like the "normal" $_FILES array.
  135. *
  136. * It's safe to pass an already converted array, in which case this method
  137. * just returns the original array unmodified.
  138. *
  139. * This method is identical to {@link \Symfony\Component\HttpFoundation\FileBag::fixPhpFilesArray}
  140. * and should be kept as such in order to port fixes quickly and easily.
  141. *
  142. * @return array
  143. */
  144. private static function fixPhpFilesArray($data)
  145. {
  146. if (!\is_array($data)) {
  147. return $data;
  148. }
  149. $keys = array_keys($data);
  150. sort($keys);
  151. if (self::$fileKeys !== $keys || !isset($data['name']) || !\is_array($data['name'])) {
  152. return $data;
  153. }
  154. $files = $data;
  155. foreach (self::$fileKeys as $k) {
  156. unset($files[$k]);
  157. }
  158. foreach ($data['name'] as $key => $name) {
  159. $files[$key] = self::fixPhpFilesArray(array(
  160. 'error' => $data['error'][$key],
  161. 'name' => $name,
  162. 'type' => $data['type'][$key],
  163. 'tmp_name' => $data['tmp_name'][$key],
  164. 'size' => $data['size'][$key],
  165. ));
  166. }
  167. return $files;
  168. }
  169. /**
  170. * Sets empty uploaded files to NULL in the given uploaded files array.
  171. *
  172. * @param mixed $data The file upload data
  173. *
  174. * @return array|null Returns the stripped upload data
  175. */
  176. private static function stripEmptyFiles($data)
  177. {
  178. if (!\is_array($data)) {
  179. return $data;
  180. }
  181. $keys = array_keys($data);
  182. sort($keys);
  183. if (self::$fileKeys === $keys) {
  184. if (UPLOAD_ERR_NO_FILE === $data['error']) {
  185. return null;
  186. }
  187. return $data;
  188. }
  189. foreach ($data as $key => $value) {
  190. $data[$key] = self::stripEmptyFiles($value);
  191. }
  192. return $data;
  193. }
  194. }