Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/File/UploadedFile.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation\File;
13
14 use Symfony\Component\HttpFoundation\File\Exception\CannotWriteFileException;
15 use Symfony\Component\HttpFoundation\File\Exception\ExtensionFileException;
16 use Symfony\Component\HttpFoundation\File\Exception\FileException;
17 use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
18 use Symfony\Component\HttpFoundation\File\Exception\FormSizeFileException;
19 use Symfony\Component\HttpFoundation\File\Exception\IniSizeFileException;
20 use Symfony\Component\HttpFoundation\File\Exception\NoFileException;
21 use Symfony\Component\HttpFoundation\File\Exception\NoTmpDirFileException;
22 use Symfony\Component\HttpFoundation\File\Exception\PartialFileException;
23 use Symfony\Component\Mime\MimeTypes;
24
25 /**
26 * A file uploaded through a form.
27 *
28 * @author Bernhard Schussek <[email protected]>
29 * @author Florian Eckerstorfer <[email protected]>
30 * @author Fabien Potencier <[email protected]>
31 */
32 class UploadedFile extends File
33 {
34 private string $originalName;
35 private string $mimeType;
36 private int $error;
37 private string $originalPath;
38
39 /**
40 * Accepts the information of the uploaded file as provided by the PHP global $_FILES.
41 *
42 * The file object is only created when the uploaded file is valid (i.e. when the
43 * isValid() method returns true). Otherwise the only methods that could be called
44 * on an UploadedFile instance are:
45 *
46 * * getClientOriginalName,
47 * * getClientMimeType,
48 * * isValid,
49 * * getError.
50 *
51 * Calling any other method on an non-valid instance will cause an unpredictable result.
52 *
53 * @param string $path The full temporary path to the file
54 * @param string $originalName The original file name of the uploaded file
55 * @param string|null $mimeType The type of the file as provided by PHP; null defaults to application/octet-stream
56 * @param int|null $error The error constant of the upload (one of PHP's UPLOAD_ERR_XXX constants); null defaults to UPLOAD_ERR_OK
57 * @param bool $test Whether the test mode is active
58 * Local files are used in test mode hence the code should not enforce HTTP uploads
59 *
60 * @throws FileException If file_uploads is disabled
61 * @throws FileNotFoundException If the file does not exist
62 */
63 public function __construct(
64 string $path,
65 string $originalName,
66 ?string $mimeType = null,
67 ?int $error = null,
68 private bool $test = false,
69 ) {
70 $this->originalName = $this->getName($originalName);
71 $this->originalPath = strtr($originalName, '\\', '/');
72 $this->mimeType = $mimeType ?: 'application/octet-stream';
73 $this->error = $error ?: \UPLOAD_ERR_OK;
74
75 parent::__construct($path, \UPLOAD_ERR_OK === $this->error);
76 }
77
78 /**
79 * Returns the original file name.
80 *
81 * It is extracted from the request from which the file has been uploaded.
82 * This should not be considered as a safe value to use for a file name on your servers.
83 */
84 public function getClientOriginalName(): string
85 {
86 return $this->originalName;
87 }
88
89 /**
90 * Returns the original file extension.
91 *
92 * It is extracted from the original file name that was uploaded.
93 * This should not be considered as a safe value to use for a file name on your servers.
94 */
95 public function getClientOriginalExtension(): string
96 {
97 return pathinfo($this->originalName, \PATHINFO_EXTENSION);
98 }
99
100 /**
101 * Returns the original file full path.
102 *
103 * It is extracted from the request from which the file has been uploaded.
104 * This should not be considered as a safe value to use for a file name/path on your servers.
105 *
106 * If this file was uploaded with the "webkitdirectory" upload directive, this will contain
107 * the path of the file relative to the uploaded root directory. Otherwise this will be identical
108 * to getClientOriginalName().
109 */
110 public function getClientOriginalPath(): string
111 {
112 return $this->originalPath;
113 }
114
115 /**
116 * Returns the file mime type.
117 *
118 * The client mime type is extracted from the request from which the file
119 * was uploaded, so it should not be considered as a safe value.
120 *
121 * For a trusted mime type, use getMimeType() instead (which guesses the mime
122 * type based on the file content).
123 *
124 * @see getMimeType()
125 */
126 public function getClientMimeType(): string
127 {
128 return $this->mimeType;
129 }
130
131 /**
132 * Returns the extension based on the client mime type.
133 *
134 * If the mime type is unknown, returns null.
135 *
136 * This method uses the mime type as guessed by getClientMimeType()
137 * to guess the file extension. As such, the extension returned
138 * by this method cannot be trusted.
139 *
140 * For a trusted extension, use guessExtension() instead (which guesses
141 * the extension based on the guessed mime type for the file).
142 *
143 * @see guessExtension()
144 * @see getClientMimeType()
145 */
146 public function guessClientExtension(): ?string
147 {
148 if (!class_exists(MimeTypes::class)) {
149 throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
150 }
151
152 return MimeTypes::getDefault()->getExtensions($this->getClientMimeType())[0] ?? null;
153 }
154
155 /**
156 * Returns the upload error.
157 *
158 * If the upload was successful, the constant UPLOAD_ERR_OK is returned.
159 * Otherwise one of the other UPLOAD_ERR_XXX constants is returned.
160 */
161 public function getError(): int
162 {
163 return $this->error;
164 }
165
166 /**
167 * Returns whether the file has been uploaded with HTTP and no error occurred.
168 */
169 public function isValid(): bool
170 {
171 $isOk = \UPLOAD_ERR_OK === $this->error;
172
173 return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
174 }
175
176 /**
177 * Moves the file to a new location.
178 *
179 * @throws FileException if, for any reason, the file could not have been moved
180 */
181 public function move(string $directory, ?string $name = null): File
182 {
183 if ($this->isValid()) {
184 if ($this->test) {
185 return parent::move($directory, $name);
186 }
187
188 $target = $this->getTargetFile($directory, $name);
189
190 set_error_handler(static function ($type, $msg) use (&$error) { $error = $msg; });
191 try {
192 $moved = move_uploaded_file($this->getPathname(), $target);
193 } finally {
194 restore_error_handler();
195 }
196 if (!$moved) {
197 throw new FileException(\sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname(), $target, strip_tags($error)));
198 }
199
200 @chmod($target, 0o666 & ~umask());
201
202 return $target;
203 }
204
205 switch ($this->error) {
206 case \UPLOAD_ERR_INI_SIZE:
207 throw new IniSizeFileException($this->getExceptionMessage());
208 case \UPLOAD_ERR_FORM_SIZE:
209 throw new FormSizeFileException($this->getExceptionMessage());
210 case \UPLOAD_ERR_PARTIAL:
211 throw new PartialFileException($this->getExceptionMessage());
212 case \UPLOAD_ERR_NO_FILE:
213 throw new NoFileException($this->getExceptionMessage());
214 case \UPLOAD_ERR_CANT_WRITE:
215 throw new CannotWriteFileException($this->getExceptionMessage());
216 case \UPLOAD_ERR_NO_TMP_DIR:
217 throw new NoTmpDirFileException($this->getExceptionMessage());
218 case \UPLOAD_ERR_EXTENSION:
219 throw new ExtensionFileException($this->getExceptionMessage());
220 }
221
222 throw new FileException($this->getExceptionMessage());
223 }
224
225 /**
226 * Retrieves a user-friendly error message for file upload issues, if any.
227 */
228 public function getErrorMessage(): string
229 {
230 return \UPLOAD_ERR_OK !== $this->error ? $this->getExceptionMessage() : '';
231 }
232
233 /**
234 * Returns the maximum size of an uploaded file as configured in php.ini.
235 *
236 * @return int|float The maximum size of an uploaded file in bytes (returns float if size > PHP_INT_MAX)
237 */
238 public static function getMaxFilesize(): int|float
239 {
240 $sizePostMax = self::parseFilesize(\ini_get('post_max_size'));
241 $sizeUploadMax = self::parseFilesize(\ini_get('upload_max_filesize'));
242
243 return min($sizePostMax ?: \PHP_INT_MAX, $sizeUploadMax ?: \PHP_INT_MAX);
244 }
245
246 private static function parseFilesize(string $size): int|float
247 {
248 if ('' === $size) {
249 return 0;
250 }
251
252 $size = strtolower($size);
253
254 $max = ltrim($size, '+');
255 if (str_starts_with($max, '0x')) {
256 $max = \intval($max, 16);
257 } elseif (str_starts_with($max, '0')) {
258 $max = \intval($max, 8);
259 } else {
260 $max = (int) $max;
261 }
262
263 switch (substr($size, -1)) {
264 case 't': $max *= 1024;
265 // no break
266 case 'g': $max *= 1024;
267 // no break
268 case 'm': $max *= 1024;
269 // no break
270 case 'k': $max *= 1024;
271 }
272
273 return $max;
274 }
275
276 /**
277 * Returns an informative upload error message.
278 */
279 private function getExceptionMessage(): string
280 {
281 static $errors = [
282 \UPLOAD_ERR_INI_SIZE => 'The file "%s" exceeds your upload_max_filesize ini directive (limit is %d KiB).',
283 \UPLOAD_ERR_FORM_SIZE => 'The file "%s" exceeds the upload limit defined in your form.',
284 \UPLOAD_ERR_PARTIAL => 'The file "%s" was only partially uploaded.',
285 \UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
286 \UPLOAD_ERR_CANT_WRITE => 'The file "%s" could not be written on disk.',
287 \UPLOAD_ERR_NO_TMP_DIR => 'File could not be uploaded: missing temporary directory.',
288 \UPLOAD_ERR_EXTENSION => 'File upload was stopped by a PHP extension.',
289 ];
290
291 $errorCode = $this->error;
292 $maxFilesize = \UPLOAD_ERR_INI_SIZE === $errorCode ? self::getMaxFilesize() / 1024 : 0;
293 $message = $errors[$errorCode] ?? 'The file "%s" was not uploaded due to an unknown error.';
294
295 return \sprintf($message, $this->getClientOriginalName(), $maxFilesize);
296 }
297 }