Debian Codegraph @

includes/upload/UploadBase.php

raw symbols SCIP
1 <?php
2 /**
3 * Base class for the backend of file upload.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Upload
22 */
23
24 use MediaWiki\Api\ApiResult;
25 use MediaWiki\Api\ApiUpload;
26 use MediaWiki\Context\RequestContext;
27 use MediaWiki\HookContainer\HookRunner;
28 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
29 use MediaWiki\Logger\LoggerFactory;
30 use MediaWiki\MainConfigNames;
31 use MediaWiki\MediaWikiServices;
32 use MediaWiki\Message\Message;
33 use MediaWiki\Parser\Sanitizer;
34 use MediaWiki\Permissions\Authority;
35 use MediaWiki\Permissions\PermissionStatus;
36 use MediaWiki\Request\WebRequest;
37 use MediaWiki\Shell\Shell;
38 use MediaWiki\Status\Status;
39 use MediaWiki\Title\Title;
40 use MediaWiki\Upload\SVGCSSChecker;
41 use MediaWiki\User\User;
42 use MediaWiki\User\UserIdentity;
43 use Wikimedia\AtEase\AtEase;
44 use Wikimedia\FileBackend\FileBackend;
45 use Wikimedia\FileBackend\FSFile\FSFile;
46 use Wikimedia\FileBackend\FSFile\TempFSFile;
47 use Wikimedia\Message\MessageParam;
48 use Wikimedia\Mime\XmlTypeCheck;
49 use Wikimedia\ObjectCache\BagOStuff;
50 use Wikimedia\Rdbms\IDBAccessObject;
51
52 /**
53 * @defgroup Upload Upload related
54 */
55
56 /**
57 * @ingroup Upload
58 *
59 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
60 * The frontends are formed by ApiUpload and SpecialUpload.
61 *
62 * @stable to extend
63 *
64 * @author Brooke Vibber
65 * @author Bryan Tong Minh
66 * @author Michael Dale
67 */
68 abstract class UploadBase {
69 use ProtectedHookAccessorTrait;
70
71 /** @var string|null Local file system path to the file to upload (or a local copy) */
72 protected $mTempPath;
73 /** @var TempFSFile|null Wrapper to handle deleting the temp file */
74 protected $tempFileObj;
75 /** @var string|null */
76 protected $mDesiredDestName;
77 /** @var string|null */
78 protected $mDestName;
79 /** @var bool|null */
80 protected $mRemoveTempFile;
81 /** @var string|null */
82 protected $mSourceType;
83 /** @var Title|false|null */
84 protected $mTitle = false;
85 /** @var int */
86 protected $mTitleError = 0;
87 /** @var string|null */
88 protected $mFilteredName;
89 /** @var string|null */
90 protected $mFinalExtension;
91 /** @var LocalFile|null */
92 protected $mLocalFile;
93 /** @var UploadStashFile|null */
94 protected $mStashFile;
95 /** @var int|null */
96 protected $mFileSize;
97 /** @var array|null */
98 protected $mFileProps;
99 /** @var string[] */
100 protected $mBlackListedExtensions;
101 /** @var bool|null */
102 protected $mJavaDetected;
103 /** @var string|false */
104 protected $mSVGNSError;
105
106 private const SAFE_XML_ENCONDINGS = [
107 'UTF-8',
108 'US-ASCII',
109 'ISO-8859-1',
110 'ISO-8859-2',
111 'UTF-16',
112 'UTF-32',
113 'WINDOWS-1250',
114 'WINDOWS-1251',
115 'WINDOWS-1252',
116 'WINDOWS-1253',
117 'WINDOWS-1254',
118 'WINDOWS-1255',
119 'WINDOWS-1256',
120 'WINDOWS-1257',
121 'WINDOWS-1258',
122 ];
123
124 public const SUCCESS = 0;
125 public const OK = 0;
126 public const EMPTY_FILE = 3;
127 public const MIN_LENGTH_PARTNAME = 4;
128 public const ILLEGAL_FILENAME = 5;
129 public const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
130 public const FILETYPE_MISSING = 8;
131 public const FILETYPE_BADTYPE = 9;
132 public const VERIFICATION_ERROR = 10;
133 public const HOOK_ABORTED = 11;
134 public const FILE_TOO_LARGE = 12;
135 public const WINDOWS_NONASCII_FILENAME = 13;
136 public const FILENAME_TOO_LONG = 14;
137
138 private const CODE_TO_STATUS = [
139 self::EMPTY_FILE => 'empty-file',
140 self::FILE_TOO_LARGE => 'file-too-large',
141 self::FILETYPE_MISSING => 'filetype-missing',
142 self::FILETYPE_BADTYPE => 'filetype-banned',
143 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
144 self::ILLEGAL_FILENAME => 'illegal-filename',
145 self::OVERWRITE_EXISTING_FILE => 'overwrite',
146 self::VERIFICATION_ERROR => 'verification-error',
147 self::HOOK_ABORTED => 'hookaborted',
148 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
149 self::FILENAME_TOO_LONG => 'filename-toolong',
150 ];
151
152 /**
153 * @param int $error
154 * @return string
155 */
156 public function getVerificationErrorCode( $error ) {
157 return self::CODE_TO_STATUS[$error] ?? 'unknown-error';
158 }
159
160 /**
161 * Returns true if uploads are enabled.
162 * Can be override by subclasses.
163 * @stable to override
164 * @return bool
165 */
166 public static function isEnabled() {
167 $enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
168
169 return $enableUploads && wfIniGetBool( 'file_uploads' );
170 }
171
172 /**
173 * Returns true if the user can use this upload module or else a string
174 * identifying the missing permission.
175 * Can be overridden by subclasses.
176 *
177 * @param Authority $performer
178 * @return bool|string
179 */
180 public static function isAllowed( Authority $performer ) {
181 foreach ( [ 'upload', 'edit' ] as $permission ) {
182 if ( !$performer->isAllowed( $permission ) ) {
183 return $permission;
184 }
185 }
186
187 return true;
188 }
189
190 /**
191 * Returns true if the user has surpassed the upload rate limit, false otherwise.
192 *
193 * @deprecated since 1.41, use verifyTitlePermissions() instead.
194 * Rate limit checks are now implicit in permission checks.
195 *
196 * @param User $user
197 * @return bool
198 */
199 public static function isThrottled( $user ) {
200 wfDeprecated( __METHOD__, '1.41' );
201 return $user->pingLimiter( 'upload' );
202 }
203
204 /** @var string[] Upload handlers. Should probably just be a configuration variable. */
205 private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
206
207 /**
208 * Create a form of UploadBase depending on wpSourceType and initializes it.
209 *
210 * @param WebRequest &$request
211 * @param string|null $type
212 * @return null|self
213 */
214 public static function createFromRequest( &$request, $type = null ) {
215 $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
216
217 if ( !$type ) {
218 return null;
219 }
220
221 // Get the upload class
222 $type = ucfirst( $type );
223
224 // Give hooks the chance to handle this request
225 /** @var self|null $className */
226 $className = null;
227 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
228 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
229 ->onUploadCreateFromRequest( $type, $className );
230 if ( $className === null ) {
231 $className = 'UploadFrom' . $type;
232 wfDebug( __METHOD__ . ": class name: $className" );
233 if ( !in_array( $type, self::$uploadHandlers ) ) {
234 return null;
235 }
236 }
237
238 if ( !$className::isEnabled() || !$className::isValidRequest( $request ) ) {
239 return null;
240 }
241
242 /** @var self $handler */
243 $handler = new $className;
244
245 $handler->initializeFromRequest( $request );
246
247 return $handler;
248 }
249
250 /**
251 * Check whether a request if valid for this handler.
252 * @param WebRequest $request
253 * @return bool
254 */
255 public static function isValidRequest( $request ) {
256 return false;
257 }
258
259 /**
260 * Get the desired destination name.
261 * @return string|null
262 */
263 public function getDesiredDestName() {
264 return $this->mDesiredDestName;
265 }
266
267 /**
268 * @stable to call
269 */
270 public function __construct() {
271 }
272
273 /**
274 * Returns the upload type. Should be overridden by child classes.
275 *
276 * @since 1.18
277 * @stable to override
278 * @return string|null
279 */
280 public function getSourceType() {
281 return null;
282 }
283
284 /**
285 * @param string $name The desired destination name
286 * @param string|null $tempPath Callers should make sure this is not a storage path
287 * @param int|null $fileSize
288 * @param bool $removeTempFile (false) remove the temporary file?
289 */
290 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
291 $this->mDesiredDestName = $name;
292 if ( FileBackend::isStoragePath( $tempPath ) ) {
293 throw new InvalidArgumentException( __METHOD__ . " given storage path `$tempPath`." );
294 }
295
296 $this->setTempFile( $tempPath, $fileSize );
297 $this->mRemoveTempFile = $removeTempFile;
298 }
299
300 /**
301 * Initialize from a WebRequest. Override this in a subclass.
302 *
303 * @param WebRequest &$request
304 */
305 abstract public function initializeFromRequest( &$request );
306
307 /**
308 * @param string|null $tempPath File system path to temporary file containing the upload
309 * @param int|null $fileSize
310 */
311 protected function setTempFile( $tempPath, $fileSize = null ) {
312 $this->mTempPath = $tempPath ?? '';
313 $this->mFileSize = $fileSize ?: null;
314 $this->mFileProps = null;
315 if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
316 $this->tempFileObj = new TempFSFile( $this->mTempPath );
317 if ( !$fileSize ) {
318 $this->mFileSize = filesize( $this->mTempPath );
319 }
320 } else {
321 $this->tempFileObj = null;
322 }
323 }
324
325 /**
326 * Fetch the file. Usually a no-op.
327 * @stable to override
328 * @return Status
329 */
330 public function fetchFile() {
331 return Status::newGood();
332 }
333
334 /**
335 * Perform checks to see if the file can be fetched. Usually a no-op.
336 * @stable to override
337 * @return Status
338 */
339 public function canFetchFile() {
340 return Status::newGood();
341 }
342
343 /**
344 * Return true if the file is empty.
345 * @return bool
346 */
347 public function isEmptyFile() {
348 return !$this->mFileSize;
349 }
350
351 /**
352 * Return the file size.
353 * @return int
354 */
355 public function getFileSize() {
356 return $this->mFileSize;
357 }
358
359 /**
360 * Get the base 36 SHA1 of the file.
361 * @stable to override
362 * @return string|false
363 */
364 public function getTempFileSha1Base36() {
365 // Use cached version if we already have it.
366 if ( $this->mFileProps && is_string( $this->mFileProps['sha1'] ) ) {
367 return $this->mFileProps['sha1'];
368 }
369 return FSFile::getSha1Base36FromPath( $this->mTempPath );
370 }
371
372 /**
373 * @param string $srcPath The source path
374 * @return string|false The real path if it was a virtual URL Returns false on failure
375 */
376 public function getRealPath( $srcPath ) {
377 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
378 if ( FileRepo::isVirtualUrl( $srcPath ) ) {
379 /** @todo Just make uploads work with storage paths UploadFromStash
380 * loads files via virtual URLs.
381 */
382 $tmpFile = $repo->getLocalCopy( $srcPath );
383 if ( $tmpFile ) {
384 $tmpFile->bind( $this ); // keep alive with $this
385 }
386 $path = $tmpFile ? $tmpFile->getPath() : false;
387 } else {
388 $path = $srcPath;
389 }
390
391 return $path;
392 }
393
394 /**
395 * Verify whether the upload is sensible.
396 *
397 * Return a status array representing the outcome of the verification.
398 * Possible keys are:
399 * - 'status': set to self::OK in case of success, or to one of the error constants defined in
400 * this class in case of failure
401 * - 'max': set to the maximum allowed file size ($wgMaxUploadSize) if the upload is too large
402 * - 'details': set to error details if the file type is valid but contents are corrupt
403 * - 'filtered': set to the sanitized file name if the requested file name is invalid
404 * - 'finalExt': set to the file's file extension if it is not an allowed file extension
405 * - 'blacklistedExt': set to the list of disallowed file extensions if the current file extension
406 * is not allowed for uploads and the list is not empty
407 *
408 * @stable to override
409 * @return mixed[] array representing the result of the verification
410 */
411 public function verifyUpload() {
412 /**
413 * If there was no filename or a zero size given, give up quick.
414 */
415 if ( $this->isEmptyFile() ) {
416 return [ 'status' => self::EMPTY_FILE ];
417 }
418
419 /**
420 * Honor $wgMaxUploadSize
421 */
422 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
423 if ( $this->mFileSize > $maxSize ) {
424 return [
425 'status' => self::FILE_TOO_LARGE,
426 'max' => $maxSize,
427 ];
428 }
429
430 /**
431 * Look at the contents of the file; if we can recognize the
432 * type, but it's corrupt or data of the wrong type, we should
433 * probably not accept it.
434 */
435 $verification = $this->verifyFile();
436 if ( $verification !== true ) {
437 return [
438 'status' => self::VERIFICATION_ERROR,
439 'details' => $verification
440 ];
441 }
442
443 /**
444 * Make sure this file can be created
445 */
446 $result = $this->validateName();
447 if ( $result !== true ) {
448 return $result;
449 }
450
451 return [ 'status' => self::OK ];
452 }
453
454 /**
455 * Verify that the name is valid and, if necessary, that we can overwrite
456 *
457 * @return array|bool True if valid, otherwise an array with 'status'
458 * and other keys
459 */
460 public function validateName() {
461 $nt = $this->getTitle();
462 if ( $nt === null ) {
463 $result = [ 'status' => $this->mTitleError ];
464 if ( $this->mTitleError === self::ILLEGAL_FILENAME ) {
465 $result['filtered'] = $this->mFilteredName;
466 }
467 if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
468 $result['finalExt'] = $this->mFinalExtension;
469 if ( count( $this->mBlackListedExtensions ) ) {
470 $result['blacklistedExt'] = $this->mBlackListedExtensions;
471 }
472 }
473
474 return $result;
475 }
476 $this->mDestName = $this->getLocalFile()->getName();
477
478 return true;
479 }
480
481 /**
482 * Verify the MIME type.
483 *
484 * @note Only checks that it is not an evil MIME.
485 * The "does it have the correct file extension given its MIME type?" check is in verifyFile.
486 * @param string $mime Representing the MIME
487 * @return array|bool True if the file is verified, an array otherwise
488 */
489 protected function verifyMimeType( $mime ) {
490 $verifyMimeType = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeType );
491 if ( $verifyMimeType ) {
492 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
493 $mimeTypeExclusions = MediaWikiServices::getInstance()->getMainConfig()
494 ->get( MainConfigNames::MimeTypeExclusions );
495 if ( self::checkFileExtension( $mime, $mimeTypeExclusions ) ) {
496 return [ 'filetype-badmime', $mime ];
497 }
498 }
499
500 return true;
501 }
502
503 /**
504 * Verifies that it's ok to include the uploaded file
505 *
506 * @return array|true True of the file is verified, array otherwise.
507 */
508 protected function verifyFile() {
509 $config = MediaWikiServices::getInstance()->getMainConfig();
510 $verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
511 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
512 $status = $this->verifyPartialFile();
513 if ( $status !== true ) {
514 return $status;
515 }
516
517 // Calculating props calculates the sha1 which is expensive.
518 // reuse props if we already have them
519 if ( !is_array( $this->mFileProps ) ) {
520 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
521 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
522 }
523 $mime = $this->mFileProps['mime'];
524
525 if ( $verifyMimeType ) {
526 # XXX: Missing extension will be caught by validateName() via getTitle()
527 if ( (string)$this->mFinalExtension !== '' &&
528 !self::verifyExtension( $mime, $this->mFinalExtension )
529 ) {
530 return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
531 }
532 }
533
534 # check for htmlish code and javascript
535 if ( !$disableUploadScriptChecks ) {
536 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
537 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
538 if ( $svgStatus !== false ) {
539 return $svgStatus;
540 }
541 }
542 }
543
544 $handler = $mime !== null ? MediaHandler::getHandler( $mime ) : null;
545 if ( $handler ) {
546 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
547 if ( !$handlerStatus->isOK() ) {
548 $errors = $handlerStatus->getErrorsArray();
549
550 return reset( $errors );
551 }
552 }
553
554 $error = true;
555 $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
556 if ( $error !== true ) {
557 if ( !is_array( $error ) ) {
558 $error = [ $error ];
559 }
560 return $error;
561 }
562
563 wfDebug( __METHOD__ . ": all clear; passing." );
564
565 return true;
566 }
567
568 /**
569 * A verification routine suitable for partial files
570 *
571 * Runs the deny list checks, but not any checks that may
572 * assume the entire file is present.
573 *
574 * @return array|true True, if the file is valid, else an array with error message key.
575 * @phan-return non-empty-array|true
576 */
577 protected function verifyPartialFile() {
578 $config = MediaWikiServices::getInstance()->getMainConfig();
579 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
580 # getTitle() sets some internal parameters like $this->mFinalExtension
581 $this->getTitle();
582
583 // Calculating props calculates the sha1 which is expensive.
584 // reuse props if we already have them (e.g. During stashed upload)
585 if ( !is_array( $this->mFileProps ) ) {
586 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
587 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
588 }
589
590 # check MIME type, if desired
591 $mime = $this->mFileProps['file-mime'];
592 $status = $this->verifyMimeType( $mime );
593 if ( $status !== true ) {
594 return $status;
595 }
596
597 # check for htmlish code and javascript
598 if ( !$disableUploadScriptChecks ) {
599 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
600 return [ 'uploadscripted' ];
601 }
602 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
603 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
604 if ( $svgStatus !== false ) {
605 return $svgStatus;
606 }
607 }
608 }
609
610 # Scan the uploaded file for viruses
611 $virus = self::detectVirus( $this->mTempPath );
612 if ( $virus ) {
613 return [ 'uploadvirus', $virus ];
614 }
615
616 return true;
617 }
618
619 /**
620 * Callback for ZipDirectoryReader to detect Java class files.
621 *
622 * @param array $entry
623 */
624 public function zipEntryCallback( $entry ) {
625 $names = [ $entry['name'] ];
626
627 // If there is a null character, cut off the name at it, because JDK's
628 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
629 // were constructed which had ".class\0" followed by a string chosen to
630 // make the hash collide with the truncated name, that file could be
631 // returned in response to a request for the .class file.
632 $nullPos = strpos( $entry['name'], "\000" );
633 if ( $nullPos !== false ) {
634 $names[] = substr( $entry['name'], 0, $nullPos );
635 }
636
637 // If there is a trailing slash in the file name, we have to strip it,
638 // because that's what ZIP_GetEntry() does.
639 if ( preg_grep( '!\.class/?$!', $names ) ) {
640 $this->mJavaDetected = true;
641 }
642 }
643
644 /**
645 * Alias for verifyTitlePermissions. The function was originally
646 * 'verifyPermissions', but that suggests it's checking the user, when it's
647 * really checking the title + user combination.
648 *
649 * @param Authority $performer to verify the permissions against
650 * @return array|bool An array as returned by getPermissionErrors or true
651 * in case the user has proper permissions.
652 */
653 public function verifyPermissions( Authority $performer ) {
654 return $this->verifyTitlePermissions( $performer );
655 }
656
657 /**
658 * Check whether the user can edit, upload and create the image. This
659 * checks only against the current title; if it returns errors, it may
660 * very well be that another title will not give errors. Therefore
661 * isAllowed() should be called as well for generic is-user-blocked or
662 * can-user-upload checking.
663 *
664 * @param Authority $performer to verify the permissions against
665 * @return array|bool An array as returned by getPermissionErrors or true
666 * in case the user has proper permissions.
667 */
668 public function verifyTitlePermissions( Authority $performer ) {
669 /**
670 * If the image is protected, non-sysop users won't be able
671 * to modify it by uploading a new revision.
672 */
673 $nt = $this->getTitle();
674 if ( $nt === null ) {
675 return true;
676 }
677
678 $status = PermissionStatus::newEmpty();
679 $performer->authorizeWrite( 'edit', $nt, $status );
680 $performer->authorizeWrite( 'upload', $nt, $status );
681 if ( !$status->isGood() ) {
682 return $status->toLegacyErrorArray();
683 }
684
685 $overwriteError = $this->checkOverwrite( $performer );
686 if ( $overwriteError !== true ) {
687 return [ $overwriteError ];
688 }
689
690 return true;
691 }
692
693 /**
694 * Check for non fatal problems with the file.
695 *
696 * This should not assume that mTempPath is set.
697 *
698 * @param User|null $user Accepted since 1.35
699 *
700 * @return mixed[] Array of warnings
701 */
702 public function checkWarnings( $user = null ) {
703 if ( $user === null ) {
704 // TODO check uses and hard deprecate
705 $user = RequestContext::getMain()->getUser();
706 }
707
708 $warnings = [];
709
710 $localFile = $this->getLocalFile();
711 $localFile->load( IDBAccessObject::READ_LATEST );
712 $filename = $localFile->getName();
713 $hash = $this->getTempFileSha1Base36();
714
715 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
716 if ( $badFileName !== null ) {
717 $warnings['badfilename'] = $badFileName;
718 }
719
720 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension );
721 if ( $unwantedFileExtensionDetails !== null ) {
722 $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
723 }
724
725 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
726 if ( $fileSizeWarnings ) {
727 $warnings = array_merge( $warnings, $fileSizeWarnings );
728 }
729
730 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
731 if ( $localFileExistsWarnings ) {
732 $warnings = array_merge( $warnings, $localFileExistsWarnings );
733 }
734
735 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
736 $warnings['was-deleted'] = $filename;
737 }
738
739 // If a file with the same name exists locally then the local file has already been tested
740 // for duplication of content
741 $ignoreLocalDupes = isset( $warnings['exists'] );
742 $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
743 if ( $dupes ) {
744 $warnings['duplicate'] = $dupes;
745 }
746
747 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
748 if ( $archivedDupes !== null ) {
749 $warnings['duplicate-archive'] = $archivedDupes;
750 }
751
752 return $warnings;
753 }
754
755 /**
756 * Convert the warnings array returned by checkWarnings() to something that
757 * can be serialized, and that is suitable for inclusion directly in action API results.
758 *
759 * File objects will be converted to an associative array with the following keys:
760 *
761 * - fileName: The name of the file
762 * - timestamp: The upload timestamp
763 *
764 * @param mixed[] $warnings
765 * @return mixed[]
766 */
767 public static function makeWarningsSerializable( $warnings ) {
768 array_walk_recursive( $warnings, static function ( &$param, $key ) {
769 if ( $param instanceof File ) {
770 $param = [
771 'fileName' => $param->getName(),
772 'timestamp' => $param->getTimestamp()
773 ];
774 } elseif ( $param instanceof MessageParam ) {
775 // Do nothing (T390001)
776 } elseif ( is_object( $param ) ) {
777 throw new InvalidArgumentException(
778 'UploadBase::makeWarningsSerializable: ' .
779 'Unexpected object of class ' . get_class( $param ) );
780 }
781 } );
782 return $warnings;
783 }
784
785 /**
786 * Convert the serialized warnings array created by makeWarningsSerializable()
787 * back to the output of checkWarnings().
788 *
789 * @param mixed[] $warnings
790 * @return mixed[]
791 */
792 public static function unserializeWarnings( $warnings ) {
793 foreach ( $warnings as $key => $value ) {
794 if ( is_array( $value ) ) {
795 if ( isset( $value['fileName'] ) && isset( $value['timestamp'] ) ) {
796 $warnings[$key] = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
797 $value['fileName'],
798 [ 'time' => $value['timestamp'] ]
799 );
800 } else {
801 $warnings[$key] = self::unserializeWarnings( $value );
802 }
803 }
804 }
805 return $warnings;
806 }
807
808 /**
809 * Check whether the resulting filename is different from the desired one,
810 * but ignore things like ucfirst() and spaces/underscore things
811 *
812 * @param string $filename
813 * @param string $desiredFileName
814 *
815 * @return string|null String that was determined to be bad or null if the filename is okay
816 */
817 private function checkBadFileName( $filename, $desiredFileName ) {
818 $comparableName = str_replace( ' ', '_', $desiredFileName );
819 $comparableName = Title::capitalize( $comparableName, NS_FILE );
820
821 if ( $desiredFileName != $filename && $comparableName != $filename ) {
822 return $filename;
823 }
824
825 return null;
826 }
827
828 /**
829 * @param string $fileExtension The file extension to check
830 *
831 * @return array|null array with the following keys:
832 * 0 => string The final extension being used
833 * 1 => string[] The extensions that are allowed
834 * 2 => int The number of extensions that are allowed.
835 */
836 private function checkUnwantedFileExtensions( $fileExtension ) {
837 $checkFileExtensions = MediaWikiServices::getInstance()->getMainConfig()
838 ->get( MainConfigNames::CheckFileExtensions );
839 $fileExtensions = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::FileExtensions );
840 if ( $checkFileExtensions ) {
841 $extensions = array_unique( $fileExtensions );
842 if ( !self::checkFileExtension( $fileExtension, $extensions ) ) {
843 return [
844 $fileExtension,
845 Message::listParam( $extensions, 'comma' ),
846 count( $extensions )
847 ];
848 }
849 }
850
851 return null;
852 }
853
854 /**
855 * @param int $fileSize
856 *
857 * @return array warnings
858 */
859 private function checkFileSize( $fileSize ) {
860 $uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
861 ->get( MainConfigNames::UploadSizeWarning );
862
863 $warnings = [];
864
865 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
866 $warnings['large-file'] = [
867 Message::sizeParam( $uploadSizeWarning ),
868 Message::sizeParam( $fileSize ),
869 ];
870 }
871
872 if ( $fileSize == 0 ) {
873 $warnings['empty-file'] = true;
874 }
875
876 return $warnings;
877 }
878
879 /**
880 * @param LocalFile $localFile
881 * @param string|false $hash sha1 hash of the file to check
882 *
883 * @return array warnings
884 */
885 private function checkLocalFileExists( LocalFile $localFile, $hash ) {
886 $warnings = [];
887
888 $exists = self::getExistsWarning( $localFile );
889 if ( $exists !== false ) {
890 $warnings['exists'] = $exists;
891
892 // check if file is an exact duplicate of current file version
893 if ( $hash !== false && $hash === $localFile->getSha1() ) {
894 $warnings['no-change'] = $localFile;
895 }
896
897 // check if file is an exact duplicate of older versions of this file
898 $history = $localFile->getHistory();
899 foreach ( $history as $oldFile ) {
900 if ( $hash === $oldFile->getSha1() ) {
901 $warnings['duplicate-version'][] = $oldFile;
902 }
903 }
904 }
905
906 return $warnings;
907 }
908
909 private function checkLocalFileWasDeleted( LocalFile $localFile ) {
910 return $localFile->wasDeleted() && !$localFile->exists();
911 }
912
913 /**
914 * @param string|false $hash sha1 hash of the file to check
915 * @param bool $ignoreLocalDupes True to ignore local duplicates
916 *
917 * @return File[] Duplicate files, if found.
918 */
919 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
920 if ( $hash === false ) {
921 return [];
922 }
923 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
924 $title = $this->getTitle();
925 foreach ( $dupes as $key => $dupe ) {
926 if (
927 ( $dupe instanceof LocalFile ) &&
928 $ignoreLocalDupes &&
929 $title->equals( $dupe->getTitle() )
930 ) {
931 unset( $dupes[$key] );
932 }
933 }
934
935 return $dupes;
936 }
937
938 /**
939 * @param string|false $hash sha1 hash of the file to check
940 * @param Authority $performer
941 *
942 * @return string|null Name of the dupe or empty string if discovered (depending on visibility)
943 * null if the check discovered no dupes.
944 */
945 private function checkAgainstArchiveDupes( $hash, Authority $performer ) {
946 if ( $hash === false ) {
947 return null;
948 }
949 $archivedFile = new ArchivedFile( null, 0, '', $hash );
950 if ( $archivedFile->getID() > 0 ) {
951 if ( $archivedFile->userCan( File::DELETED_FILE, $performer ) ) {
952 return $archivedFile->getName();
953 }
954 return '';
955 }
956
957 return null;
958 }
959
960 /**
961 * Really perform the upload. Stores the file in the local repo, watches
962 * if necessary and runs the UploadComplete hook.
963 *
964 * @param string $comment
965 * @param string|false $pageText
966 * @param bool $watch Whether the file page should be added to user's watchlist.
967 * (This doesn't check $user's permissions.)
968 * @param User $user
969 * @param string[] $tags Change tags to add to the log entry and page revision.
970 * (This doesn't check $user's permissions.)
971 * @param string|null $watchlistExpiry Optional watchlist expiry timestamp in any format
972 * acceptable to wfTimestamp().
973 * @return Status Indicating the whether the upload succeeded.
974 *
975 * @since 1.35 Accepts $watchlistExpiry parameter.
976 */
977 public function performUpload(
978 $comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
979 ) {
980 $this->getLocalFile()->load( IDBAccessObject::READ_LATEST );
981 $props = $this->mFileProps;
982
983 $error = null;
984 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
985 if ( $error ) {
986 if ( !is_array( $error ) ) {
987 $error = [ $error ];
988 }
989 return Status::newFatal( ...$error );
990 }
991
992 $status = $this->getLocalFile()->upload(
993 $this->mTempPath,
994 $comment,
995 $pageText !== false ? $pageText : '',
996 File::DELETE_SOURCE,
997 $props,
998 false,
999 $user,
1000 $tags
1001 );
1002
1003 if ( $status->isGood() ) {
1004 if ( $watch ) {
1005 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
1006 $user,
1007 $this->getLocalFile()->getTitle(),
1008 $watchlistExpiry
1009 );
1010 }
1011 $this->getHookRunner()->onUploadComplete( $this );
1012
1013 $this->postProcessUpload();
1014 }
1015
1016 return $status;
1017 }
1018
1019 /**
1020 * Perform extra steps after a successful upload.
1021 *
1022 * @stable to override
1023 * @since 1.25
1024 */
1025 public function postProcessUpload() {
1026 }
1027
1028 /**
1029 * Returns the title of the file to be uploaded. Sets mTitleError in case
1030 * the name was illegal.
1031 *
1032 * @return Title|null The title of the file or null in case the name was illegal
1033 */
1034 public function getTitle() {
1035 if ( $this->mTitle !== false ) {
1036 return $this->mTitle;
1037 }
1038 if ( !is_string( $this->mDesiredDestName ) ) {
1039 $this->mTitleError = self::ILLEGAL_FILENAME;
1040 $this->mTitle = null;
1041
1042 return $this->mTitle;
1043 }
1044 /* Assume that if a user specified File:Something.jpg, this is an error
1045 * and that the namespace prefix needs to be stripped of.
1046 */
1047 $title = Title::newFromText( $this->mDesiredDestName );
1048 if ( $title && $title->getNamespace() === NS_FILE ) {
1049 $this->mFilteredName = $title->getDBkey();
1050 } else {
1051 $this->mFilteredName = $this->mDesiredDestName;
1052 }
1053
1054 # oi_archive_name is max 255 bytes, which include a timestamp and an
1055 # exclamation mark, so restrict file name to 240 bytes.
1056 if ( strlen( $this->mFilteredName ) > 240 ) {
1057 $this->mTitleError = self::FILENAME_TOO_LONG;
1058 $this->mTitle = null;
1059
1060 return $this->mTitle;
1061 }
1062
1063 /**
1064 * Chop off any directories in the given filename. Then
1065 * filter out illegal characters, and try to make a legible name
1066 * out of it. We'll strip some silently that Title would die on.
1067 */
1068 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
1069 /* Normalize to title form before we do any further processing */
1070 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1071 if ( $nt === null ) {
1072 $this->mTitleError = self::ILLEGAL_FILENAME;
1073 $this->mTitle = null;
1074
1075 return $this->mTitle;
1076 }
1077 $this->mFilteredName = $nt->getDBkey();
1078
1079 /**
1080 * We'll want to prevent against *any* 'extension', and use
1081 * only the final one for the allow list.
1082 */
1083 [ $partname, $ext ] = self::splitExtensions( $this->mFilteredName );
1084
1085 if ( $ext !== [] ) {
1086 $this->mFinalExtension = trim( end( $ext ) );
1087 } else {
1088 $this->mFinalExtension = '';
1089
1090 // No extension, try guessing one from the temporary file
1091 // FIXME: Sometimes we mTempPath isn't set yet here, possibly due to an unrealistic
1092 // or incomplete test case in UploadBaseTest (T272328)
1093 if ( $this->mTempPath !== null ) {
1094 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1095 $mime = $magic->guessMimeType( $this->mTempPath );
1096 if ( $mime !== 'unknown/unknown' ) {
1097 # Get a space separated list of extensions
1098 $mimeExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
1099 if ( $mimeExt !== null ) {
1100 # Set the extension to the canonical extension
1101 $this->mFinalExtension = $mimeExt;
1102
1103 # Fix up the other variables
1104 $this->mFilteredName .= ".{$this->mFinalExtension}";
1105 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1106 $ext = [ $this->mFinalExtension ];
1107 }
1108 }
1109 }
1110 }
1111
1112 // Don't allow users to override the list of prohibited file extensions (check file extension)
1113 $config = MediaWikiServices::getInstance()->getMainConfig();
1114 $checkFileExtensions = $config->get( MainConfigNames::CheckFileExtensions );
1115 $strictFileExtensions = $config->get( MainConfigNames::StrictFileExtensions );
1116 $fileExtensions = $config->get( MainConfigNames::FileExtensions );
1117 $prohibitedFileExtensions = $config->get( MainConfigNames::ProhibitedFileExtensions );
1118
1119 $badList = self::checkFileExtensionList( $ext, $prohibitedFileExtensions );
1120
1121 if ( $this->mFinalExtension == '' ) {
1122 $this->mTitleError = self::FILETYPE_MISSING;
1123 $this->mTitle = null;
1124
1125 return $this->mTitle;
1126 }
1127
1128 if ( $badList ||
1129 ( $checkFileExtensions && $strictFileExtensions &&
1130 !self::checkFileExtension( $this->mFinalExtension, $fileExtensions ) )
1131 ) {
1132 $this->mBlackListedExtensions = $badList;
1133 $this->mTitleError = self::FILETYPE_BADTYPE;
1134 $this->mTitle = null;
1135
1136 return $this->mTitle;
1137 }
1138
1139 // Windows may be broken with special characters, see T3780
1140 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1141 && !MediaWikiServices::getInstance()->getRepoGroup()
1142 ->getLocalRepo()->backendSupportsUnicodePaths()
1143 ) {
1144 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1145 $this->mTitle = null;
1146
1147 return $this->mTitle;
1148 }
1149
1150 # If there was more than one file "extension", reassemble the base
1151 # filename to prevent bogus complaints about length
1152 if ( count( $ext ) > 1 ) {
1153 $iterations = count( $ext ) - 1;
1154 for ( $i = 0; $i < $iterations; $i++ ) {
1155 $partname .= '.' . $ext[$i];
1156 }
1157 }
1158
1159 if ( strlen( $partname ) < 1 ) {
1160 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1161 $this->mTitle = null;
1162
1163 return $this->mTitle;
1164 }
1165
1166 $this->mTitle = $nt;
1167
1168 return $this->mTitle;
1169 }
1170
1171 /**
1172 * Return the local file and initializes if necessary.
1173 *
1174 * @stable to override
1175 * @return LocalFile|null
1176 */
1177 public function getLocalFile() {
1178 if ( $this->mLocalFile === null ) {
1179 $nt = $this->getTitle();
1180 $this->mLocalFile = $nt === null
1181 ? null
1182 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1183 }
1184
1185 return $this->mLocalFile;
1186 }
1187
1188 /**
1189 * @return UploadStashFile|null
1190 */
1191 public function getStashFile() {
1192 return $this->mStashFile;
1193 }
1194
1195 /**
1196 * Like stashFile(), but respects extensions' wishes to prevent the stashing. verifyUpload() must
1197 * be called before calling this method (unless $isPartial is true).
1198 *
1199 * Upload stash exceptions are also caught and converted to an error status.
1200 *
1201 * @since 1.28
1202 * @stable to override
1203 * @param User $user
1204 * @param bool $isPartial Pass `true` if this is a part of a chunked upload (not a complete file).
1205 * @return Status If successful, value is an UploadStashFile instance
1206 */
1207 public function tryStashFile( User $user, $isPartial = false ) {
1208 if ( !$isPartial ) {
1209 $error = $this->runUploadStashFileHook( $user );
1210 if ( $error ) {
1211 return Status::newFatal( ...$error );
1212 }
1213 }
1214 try {
1215 $file = $this->doStashFile( $user );
1216 return Status::newGood( $file );
1217 } catch ( UploadStashException $e ) {
1218 return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1219 }
1220 }
1221
1222 /**
1223 * @param User $user
1224 * @return array|null Error message and parameters, null if there's no error
1225 */
1226 protected function runUploadStashFileHook( User $user ) {
1227 $props = $this->mFileProps;
1228 $error = null;
1229 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1230 if ( $error && !is_array( $error ) ) {
1231 $error = [ $error ];
1232 }
1233 return $error;
1234 }
1235
1236 /**
1237 * Implementation for stashFile() and tryStashFile().
1238 *
1239 * @stable to override
1240 * @param User|null $user
1241 * @return UploadStashFile Stashed file
1242 */
1243 protected function doStashFile( ?User $user = null ) {
1244 $stash = MediaWikiServices::getInstance()->getRepoGroup()
1245 ->getLocalRepo()->getUploadStash( $user );
1246 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType(), $this->mFileProps );
1247 $this->mStashFile = $file;
1248
1249 return $file;
1250 }
1251
1252 /**
1253 * If we've modified the upload file, then we need to manually remove it
1254 * on exit to clean up.
1255 */
1256 public function cleanupTempFile() {
1257 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1258 // Delete when all relevant TempFSFile handles go out of scope
1259 wfDebug( __METHOD__ . ": Marked temporary file '{$this->mTempPath}' for removal" );
1260 $this->tempFileObj->autocollect();
1261 }
1262 }
1263
1264 /**
1265 * @return string|null
1266 */
1267 public function getTempPath() {
1268 return $this->mTempPath;
1269 }
1270
1271 /**
1272 * Split a file into a base name and all dot-delimited 'extensions'
1273 * on the end. Some web server configurations will fall back to
1274 * earlier pseudo-'extensions' to determine type and execute
1275 * scripts, so we need to check them all.
1276 *
1277 * @param string $filename
1278 * @return array [ string, string[] ]
1279 */
1280 public static function splitExtensions( $filename ) {
1281 $bits = explode( '.', $filename );
1282 $basename = array_shift( $bits );
1283
1284 return [ $basename, $bits ];
1285 }
1286
1287 /**
1288 * Perform case-insensitive match against a list of file extensions.
1289 *
1290 * @param string $ext File extension
1291 * @param array $list
1292 * @return bool Returns true if the extension is in the list.
1293 */
1294 public static function checkFileExtension( $ext, $list ) {
1295 return in_array( strtolower( $ext ?? '' ), $list, true );
1296 }
1297
1298 /**
1299 * Perform case-insensitive match against a list of file extensions.
1300 * Returns an array of matching extensions.
1301 *
1302 * @param string[] $ext File extensions
1303 * @param string[] $list
1304 * @return string[]
1305 */
1306 public static function checkFileExtensionList( $ext, $list ) {
1307 return array_intersect( array_map( 'strtolower', $ext ), $list );
1308 }
1309
1310 /**
1311 * Checks if the MIME type of the uploaded file matches the file extension.
1312 *
1313 * @param string $mime The MIME type of the uploaded file
1314 * @param string $extension The filename extension that the file is to be served with
1315 * @return bool
1316 */
1317 public static function verifyExtension( $mime, $extension ) {
1318 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1319
1320 if ( !$mime || $mime === 'unknown' || $mime === 'unknown/unknown' ) {
1321 if ( !$magic->isRecognizableExtension( $extension ) ) {
1322 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1323 "unrecognized extension '$extension', can't verify" );
1324
1325 return true;
1326 }
1327
1328 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1329 "recognized extension '$extension', so probably invalid file" );
1330 return false;
1331 }
1332
1333 $match = $magic->isMatchingExtension( $extension, $mime );
1334
1335 if ( $match === null ) {
1336 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1337 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension" );
1338
1339 return false;
1340 }
1341
1342 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file" );
1343 return true;
1344 }
1345
1346 if ( $match ) {
1347 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file" );
1348
1349 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1350 return true;
1351 }
1352
1353 wfDebug( __METHOD__
1354 . ": mime type $mime mismatches file extension $extension, rejecting file" );
1355
1356 return false;
1357 }
1358
1359 /**
1360 * Heuristic for detecting files that *could* contain JavaScript instructions or
1361 * things that may look like HTML to a browser and are thus
1362 * potentially harmful. The present implementation will produce false
1363 * positives in some situations.
1364 *
1365 * @param string|null $file Pathname to the temporary upload file
1366 * @param string $mime The MIME type of the file
1367 * @param string|null $extension The extension of the file
1368 * @return bool True if the file contains something looking like embedded scripts
1369 */
1370 public static function detectScript( $file, $mime, $extension ) {
1371 # ugly hack: for text files, always look at the entire file.
1372 # For binary field, just check the first K.
1373
1374 if ( str_starts_with( $mime ?? '', 'text/' ) ) {
1375 $chunk = file_get_contents( $file );
1376 } else {
1377 $fp = fopen( $file, 'rb' );
1378 if ( !$fp ) {
1379 return false;
1380 }
1381 $chunk = fread( $fp, 1024 );
1382 fclose( $fp );
1383 }
1384
1385 $chunk = strtolower( $chunk );
1386
1387 if ( !$chunk ) {
1388 return false;
1389 }
1390
1391 # decode from UTF-16 if needed (could be used for obfuscation).
1392 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
1393 $enc = 'UTF-16BE';
1394 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
1395 $enc = 'UTF-16LE';
1396 } else {
1397 $enc = null;
1398 }
1399
1400 if ( $enc !== null ) {
1401 AtEase::suppressWarnings();
1402 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1403 AtEase::restoreWarnings();
1404 }
1405
1406 $chunk = trim( $chunk );
1407
1408 /** @todo FIXME: Convert from UTF-16 if necessary! */
1409 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1410
1411 # check for HTML doctype
1412 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1413 return true;
1414 }
1415
1416 // Some browsers will interpret obscure xml encodings as UTF-8, while
1417 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1418 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
1419 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1420 return true;
1421 }
1422 }
1423
1424 // Quick check for HTML heuristics in old IE and Safari.
1425 //
1426 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1427 // don't need them all here as it can cause many false positives.
1428 //
1429 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1430 $tags = [
1431 '<body',
1432 '<head',
1433 '<html', # also in safari
1434 '<script', # also in safari
1435 ];
1436
1437 foreach ( $tags as $tag ) {
1438 if ( strpos( $chunk, $tag ) !== false ) {
1439 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1440
1441 return true;
1442 }
1443 }
1444
1445 /*
1446 * look for JavaScript
1447 */
1448
1449 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1450 $chunk = Sanitizer::decodeCharReferences( $chunk );
1451
1452 # look for script-types
1453 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1454 wfDebug( __METHOD__ . ": found script types" );
1455
1456 return true;
1457 }
1458
1459 # look for html-style script-urls
1460 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1461 wfDebug( __METHOD__ . ": found html-style script urls" );
1462
1463 return true;
1464 }
1465
1466 # look for css-style script-urls
1467 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1468 wfDebug( __METHOD__ . ": found css-style script urls" );
1469
1470 return true;
1471 }
1472
1473 wfDebug( __METHOD__ . ": no scripts found" );
1474
1475 return false;
1476 }
1477
1478 /**
1479 * Check an allowed list of xml encodings that are known not to be interpreted differently
1480 * by the server's xml parser (expat) and some common browsers.
1481 *
1482 * @param string $file Pathname to the temporary upload file
1483 * @return bool True if the file contains an encoding that could be misinterpreted
1484 */
1485 public static function checkXMLEncodingMissmatch( $file ) {
1486 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
1487 // should read the first 1445 bytes. Do 4096 bytes for good measure.
1488 // XML Spec says XML declaration if present must be first thing in file
1489 // other than BOM
1490 $contents = file_get_contents( $file, false, null, 0, 4096 );
1491 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1492
1493 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1494 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1495 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1496 ) {
1497 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1498
1499 return true;
1500 }
1501 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1502 // Start of XML declaration without an end in the first 4096 bytes
1503 // bytes. There shouldn't be a legitimate reason for this to happen.
1504 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1505
1506 return true;
1507 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1508 // EBCDIC encoded XML
1509 wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1510
1511 return true;
1512 }
1513
1514 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1515 // detect the encoding in case it specifies an encoding not allowed in self::SAFE_XML_ENCONDINGS
1516 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1517 foreach ( $attemptEncodings as $encoding ) {
1518 AtEase::suppressWarnings();
1519 $str = iconv( $encoding, 'UTF-8', $contents );
1520 AtEase::restoreWarnings();
1521 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1522 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1523 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1524 ) {
1525 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1526
1527 return true;
1528 }
1529 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1530 // Start of XML declaration without an end in the first 4096 bytes
1531 // bytes. There shouldn't be a legitimate reason for this to happen.
1532 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1533
1534 return true;
1535 }
1536 }
1537
1538 return false;
1539 }
1540
1541 /**
1542 * @param string $filename
1543 * @param bool $partial
1544 * @return bool|array
1545 */
1546 protected function detectScriptInSvg( $filename, $partial ) {
1547 $this->mSVGNSError = false;
1548 $check = new XmlTypeCheck(
1549 $filename,
1550 [ $this, 'checkSvgScriptCallback' ],
1551 true,
1552 [
1553 'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1554 'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1555 ]
1556 );
1557 if ( $check->wellFormed !== true ) {
1558 // Invalid xml (T60553)
1559 // But only when non-partial (T67724)
1560 return $partial ? false : [ 'uploadinvalidxml' ];
1561 }
1562
1563 if ( $check->filterMatch ) {
1564 if ( $this->mSVGNSError ) {
1565 return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1566 }
1567 return $check->filterMatchType;
1568 }
1569
1570 return false;
1571 }
1572
1573 /**
1574 * Callback to filter SVG Processing Instructions.
1575 *
1576 * @param string $target Processing instruction name
1577 * @param string $data Processing instruction attribute and value
1578 * @return bool|array
1579 */
1580 public static function checkSvgPICallback( $target, $data ) {
1581 // Don't allow external stylesheets (T59550)
1582 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1583 return [ 'upload-scripted-pi-callback' ];
1584 }
1585
1586 return false;
1587 }
1588
1589 /**
1590 * Verify that DTD URLs referenced are only the standard DTDs.
1591 *
1592 * Browsers seem to ignore external DTDs.
1593 *
1594 * However, just to be on the safe side, only allow DTDs from the SVG standard.
1595 *
1596 * @param string $type PUBLIC or SYSTEM
1597 * @param string $publicId The well-known public identifier for the dtd
1598 * @param string $systemId The url for the external dtd
1599 * @return bool|array
1600 */
1601 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1602 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1603 // allow XHTML anyway.
1604 static $allowedDTDs = [
1605 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1606 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1607 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1608 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1609 // https://phabricator.wikimedia.org/T168856
1610 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1611 ];
1612 if ( $type !== 'PUBLIC'
1613 || !in_array( $systemId, $allowedDTDs )
1614 || !str_starts_with( $publicId, "-//W3C//" )
1615 ) {
1616 return [ 'upload-scripted-dtd' ];
1617 }
1618 return false;
1619 }
1620
1621 /**
1622 * @todo Replace this with a allow list filter!
1623 * @param string $element
1624 * @param array $attribs
1625 * @param string|null $data
1626 * @return bool|array
1627 */
1628 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1629 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1630
1631 // We specifically don't include:
1632 // http://www.w3.org/1999/xhtml (T62771)
1633 static $validNamespaces = [
1634 '',
1635 'adobe:ns:meta/',
1636 'http://creativecommons.org/ns#',
1637 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1638 'http://ns.adobe.com/adobeillustrator/10.0/',
1639 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1640 'http://ns.adobe.com/extensibility/1.0/',
1641 'http://ns.adobe.com/flows/1.0/',
1642 'http://ns.adobe.com/illustrator/1.0/',
1643 'http://ns.adobe.com/imagereplacement/1.0/',
1644 'http://ns.adobe.com/pdf/1.3/',
1645 'http://ns.adobe.com/photoshop/1.0/',
1646 'http://ns.adobe.com/saveforweb/1.0/',
1647 'http://ns.adobe.com/variables/1.0/',
1648 'http://ns.adobe.com/xap/1.0/',
1649 'http://ns.adobe.com/xap/1.0/g/',
1650 'http://ns.adobe.com/xap/1.0/g/img/',
1651 'http://ns.adobe.com/xap/1.0/mm/',
1652 'http://ns.adobe.com/xap/1.0/rights/',
1653 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1654 'http://ns.adobe.com/xap/1.0/stype/font#',
1655 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1656 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1657 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1658 'http://ns.adobe.com/xap/1.0/t/pg/',
1659 'http://purl.org/dc/elements/1.1/',
1660 'http://purl.org/dc/elements/1.1',
1661 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1662 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1663 'http://taptrix.com/inkpad/svg_extensions',
1664 'http://web.resource.org/cc/',
1665 'http://www.freesoftware.fsf.org/bkchem/cdml',
1666 'http://www.inkscape.org/namespaces/inkscape',
1667 'http://www.opengis.net/gml',
1668 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1669 'http://www.w3.org/2000/svg',
1670 'http://www.w3.org/tr/rec-rdf-syntax/',
1671 'http://www.w3.org/2000/01/rdf-schema#',
1672 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1673 ];
1674
1675 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1676 // This is nasty but harmless. (T144827)
1677 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1678
1679 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1680 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1681 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1682 $this->mSVGNSError = $namespace;
1683
1684 return true;
1685 }
1686
1687 // check for elements that can contain javascript
1688 if ( $strippedElement === 'script' ) {
1689 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1690
1691 return [ 'uploaded-script-svg', $strippedElement ];
1692 }
1693
1694 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1695 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1696 if ( $strippedElement === 'handler' ) {
1697 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1698
1699 return [ 'uploaded-script-svg', $strippedElement ];
1700 }
1701
1702 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1703 if ( $strippedElement === 'stylesheet' ) {
1704 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1705
1706 return [ 'uploaded-script-svg', $strippedElement ];
1707 }
1708
1709 // Block iframes, in case they pass the namespace check
1710 if ( $strippedElement === 'iframe' ) {
1711 wfDebug( __METHOD__ . ": iframe in uploaded file." );
1712
1713 return [ 'uploaded-script-svg', $strippedElement ];
1714 }
1715
1716 // Check <style> css
1717 if ( $strippedElement === 'style'
1718 ) {
1719 $cssCheck = ( new SVGCSSChecker )->checkStyleTag( $data );
1720 if ( $cssCheck !== true ) {
1721 wfDebug( __METHOD__ . ": hostile css in style element." );
1722
1723 return [ 'uploaded-hostile-svg', $cssCheck[0], $cssCheck[1], $cssCheck[2] ];
1724 }
1725 }
1726
1727 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1728 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke', 'cursor' ];
1729
1730 foreach ( $attribs as $attrib => $value ) {
1731 // If attributeNamespace is '', it is relative to its element's namespace
1732 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
1733 $value = strtolower( $value );
1734
1735 if ( !(
1736 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1737 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1738 $attributeNamespace === ''
1739 ) && str_starts_with( $stripped, 'on' )
1740 ) {
1741 wfDebug( __METHOD__
1742 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1743
1744 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1745 }
1746
1747 // Do not allow relative links, or unsafe url schemas.
1748 // For <a> tags, only data:, http: and https: and same-document
1749 // fragment links are allowed.
1750 // For all other tags, only 'data:' and fragments (#) are allowed.
1751 if (
1752 $stripped === 'href'
1753 && $value !== ''
1754 && !str_starts_with( $value, 'data:' )
1755 && !str_starts_with( $value, '#' )
1756 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1757 ) {
1758 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1759 . "'$attrib'='$value' in uploaded file." );
1760
1761 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1762 }
1763
1764 // Only allow 'data:\' targets that should be safe.
1765 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1766 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1767 // RFC2397 parameters.
1768 // This is only slightly slower than (;[\w;]+)*.
1769 // phpcs:ignore Generic.Files.LineLength
1770 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1771
1772 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1773 wfDebug( __METHOD__ . ": Found href to allow listed data: uri "
1774 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1775 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1776 }
1777 }
1778
1779 // Change href with animate from (http://html5sec.org/#137).
1780 if ( $stripped === 'attributename'
1781 && $strippedElement === 'animate'
1782 && $this->stripXmlNamespace( $value ) === 'href'
1783 ) {
1784 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1785 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1786
1787 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1788 }
1789
1790 // Use set/animate to add event-handler attribute to parent.
1791 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
1792 && $stripped === 'attributename'
1793 && str_starts_with( $value, 'on' )
1794 ) {
1795 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1796 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1797
1798 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1799 }
1800
1801 // use set to add href attribute to parent element.
1802 if ( $strippedElement === 'set'
1803 && $stripped === 'attributename'
1804 && str_contains( $value, 'href' )
1805 ) {
1806 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1807
1808 return [ 'uploaded-setting-href-svg' ];
1809 }
1810
1811 // use set to add a remote / data / script target to an element.
1812 if ( $strippedElement === 'set'
1813 && $stripped === 'to'
1814 && preg_match( '!(http|https|data|script):!im', $value )
1815 ) {
1816 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1817
1818 return [ 'uploaded-wrong-setting-svg', $value ];
1819 }
1820
1821 // use handler attribute with remote / data / script.
1822 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1823 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1824 . "'$attrib'='$value' in uploaded file." );
1825
1826 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1827 }
1828
1829 // use CSS styles to bring in remote code.
1830 if ( $stripped === 'style'
1831 && ( new SVGCSSChecker )->checkStyleAttribute( $value ) !== true
1832 ) {
1833 wfDebug( __METHOD__ . ": Found svg setting a style with "
1834 . "remote url '$attrib'='$value' in uploaded file." );
1835 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1836 }
1837
1838 // Several attributes can include css, css character escaping isn't allowed.
1839 if ( in_array( $stripped, $cssAttrs, true )
1840 && ( new SVGCSSChecker )->checkPresentationalAttribute( $value ) !== true
1841 ) {
1842 wfDebug( __METHOD__ . ": Found svg setting a style with "
1843 . "remote url '$attrib'='$value' in uploaded file." );
1844 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1845 }
1846
1847 // image filters can pull in url, which could be svg that executes scripts.
1848 // Only allow url( "#foo" ).
1849 // Do not allow url( http://example.com )
1850 if ( $strippedElement === 'image'
1851 && $stripped === 'filter'
1852 && preg_match( '!url\s*\(\s*["\']?[^#]!im', $value )
1853 ) {
1854 wfDebug( __METHOD__ . ": Found image filter with url: "
1855 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1856
1857 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1858 }
1859 }
1860
1861 return false; // No scripts detected
1862 }
1863
1864 /**
1865 * Divide the element name passed by the XML parser to the callback into URI and prefix.
1866 * @param string $element
1867 * @return array Containing the namespace URI and prefix
1868 */
1869 private static function splitXmlNamespace( $element ) {
1870 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1871 $parts = explode( ':', strtolower( $element ) );
1872 $name = array_pop( $parts );
1873 $ns = implode( ':', $parts );
1874
1875 return [ $ns, $name ];
1876 }
1877
1878 /**
1879 * @param string $element
1880 * @return string
1881 */
1882 private function stripXmlNamespace( $element ) {
1883 // 'http://www.w3.org/2000/svg:script' -> 'script'
1884 return self::splitXmlNamespace( $element )[1];
1885 }
1886
1887 /**
1888 * Generic wrapper function for a virus scanner program.
1889 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1890 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1891 *
1892 * @param string $file Pathname to the temporary upload file
1893 * @return bool|null|string False if not virus is found, null if the scan fails or is disabled,
1894 * or a string containing feedback from the virus scanner if a virus was found.
1895 * If textual feedback is missing but a virus was found, this function returns true.
1896 */
1897 public static function detectVirus( $file ) {
1898 global $wgOut;
1899 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1900 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1901 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1902 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1903 if ( !$antivirus ) {
1904 wfDebug( __METHOD__ . ": virus scanner disabled" );
1905
1906 return null;
1907 }
1908
1909 if ( !$antivirusSetup[$antivirus] ) {
1910 wfDebug( __METHOD__ . ": unknown virus scanner: {$antivirus}" );
1911 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1912 [ 'virus-badscanner', $antivirus ] );
1913
1914 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1915 }
1916
1917 # look up scanner configuration
1918 $command = $antivirusSetup[$antivirus]['command'];
1919 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1920 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
1921
1922 if ( !str_contains( $command, "%f" ) ) {
1923 # simple pattern: append file to scan
1924 $command .= " " . Shell::escape( $file );
1925 } else {
1926 # complex pattern: replace "%f" with file to scan
1927 $command = str_replace( "%f", Shell::escape( $file ), $command );
1928 }
1929
1930 wfDebug( __METHOD__ . ": running virus scan: $command " );
1931
1932 # execute virus scanner
1933 $exitCode = false;
1934
1935 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1936 # that does not seem to be worth the pain.
1937 # Ask me (Duesentrieb) about it if it's ever needed.
1938 $output = wfShellExecWithStderr( $command, $exitCode );
1939
1940 # map exit code to AV_xxx constants.
1941 $mappedCode = $exitCode;
1942 if ( $exitCodeMap ) {
1943 if ( isset( $exitCodeMap[$exitCode] ) ) {
1944 $mappedCode = $exitCodeMap[$exitCode];
1945 } elseif ( isset( $exitCodeMap["*"] ) ) {
1946 $mappedCode = $exitCodeMap["*"];
1947 }
1948 }
1949
1950 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1951 # so we need the strict equalities === and thus can't use a switch here
1952 if ( $mappedCode === AV_SCAN_FAILED ) {
1953 # scan failed (code was mapped to false by $exitCodeMap)
1954 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1955
1956 $output = $antivirusRequired
1957 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1958 : null;
1959 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1960 # scan failed because filetype is unknown (probably immune)
1961 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
1962 $output = null;
1963 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1964 # no virus found
1965 wfDebug( __METHOD__ . ": file passed virus scan." );
1966 $output = false;
1967 } else {
1968 $output = trim( $output );
1969
1970 if ( !$output ) {
1971 $output = true; # if there's no output, return true
1972 } elseif ( $msgPattern ) {
1973 $groups = [];
1974 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1975 $output = $groups[1];
1976 }
1977 }
1978
1979 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
1980 }
1981
1982 return $output;
1983 }
1984
1985 /**
1986 * Check if there's a file overwrite conflict and, if so, if restrictions
1987 * forbid this user from performing the upload.
1988 *
1989 * @param Authority $performer
1990 *
1991 * @return bool|array
1992 */
1993 private function checkOverwrite( Authority $performer ) {
1994 // First check whether the local file can be overwritten
1995 $file = $this->getLocalFile();
1996 $file->load( IDBAccessObject::READ_LATEST );
1997 if ( $file->exists() ) {
1998 if ( !self::userCanReUpload( $performer, $file ) ) {
1999 return [ 'fileexists-forbidden', $file->getName() ];
2000 }
2001
2002 return true;
2003 }
2004
2005 $services = MediaWikiServices::getInstance();
2006
2007 /* Check shared conflicts: if the local file does not exist, but
2008 * RepoGroup::findFile finds a file, it exists in a shared repository.
2009 */
2010 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2011 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
2012 return [ 'fileexists-shared-forbidden', $file->getName() ];
2013 }
2014
2015 return true;
2016 }
2017
2018 /**
2019 * Check if a user is the last uploader
2020 *
2021 * @param Authority $performer
2022 * @param File $img
2023 * @return bool
2024 */
2025 public static function userCanReUpload( Authority $performer, File $img ) {
2026 if ( $performer->isAllowed( 'reupload' ) ) {
2027 return true; // non-conditional
2028 }
2029
2030 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2031 return false;
2032 }
2033
2034 if ( !( $img instanceof LocalFile ) ) {
2035 return false;
2036 }
2037
2038 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2039 }
2040
2041 /**
2042 * Helper function that does various existence checks for a file.
2043 * The following checks are performed:
2044 * - If the file exists
2045 * - If an article with the same name as the file exists
2046 * - If a file exists with normalized extension
2047 * - If the file looks like a thumbnail and the original exists
2048 *
2049 * @param File $file The File object to check
2050 * @return array|false False if the file does not exist, else an array
2051 */
2052 public static function getExistsWarning( $file ) {
2053 if ( $file->exists() ) {
2054 return [ 'warning' => 'exists', 'file' => $file ];
2055 }
2056
2057 if ( $file->getTitle()->getArticleID() ) {
2058 return [ 'warning' => 'page-exists', 'file' => $file ];
2059 }
2060
2061 $n = strrpos( $file->getName(), '.' );
2062 if ( $n > 0 ) {
2063 $partname = substr( $file->getName(), 0, $n );
2064 $extension = substr( $file->getName(), $n + 1 );
2065 } else {
2066 $partname = $file->getName();
2067 $extension = '';
2068 }
2069 $normalizedExtension = File::normalizeExtension( $extension );
2070 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2071
2072 if ( $normalizedExtension != $extension ) {
2073 // We're not using the normalized form of the extension.
2074 // Normal form is lowercase, using most common of alternate
2075 // extensions (e.g. 'jpg' rather than 'JPEG').
2076
2077 // Check for another file using the normalized form...
2078 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2079 $file_lc = $localRepo->newFile( $nt_lc );
2080
2081 if ( $file_lc->exists() ) {
2082 return [
2083 'warning' => 'exists-normalized',
2084 'file' => $file,
2085 'normalizedFile' => $file_lc
2086 ];
2087 }
2088 }
2089
2090 // Check for files with the same name but a different extension
2091 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2092 if ( count( $similarFiles ) ) {
2093 return [
2094 'warning' => 'exists-normalized',
2095 'file' => $file,
2096 'normalizedFile' => $similarFiles[0],
2097 ];
2098 }
2099
2100 if ( self::isThumbName( $file->getName() ) ) {
2101 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2102 $nt_thb = Title::newFromText(
2103 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2104 NS_FILE
2105 );
2106 $file_thb = $localRepo->newFile( $nt_thb );
2107 if ( $file_thb->exists() ) {
2108 return [
2109 'warning' => 'thumb',
2110 'file' => $file,
2111 'thumbFile' => $file_thb
2112 ];
2113 }
2114
2115 // The file does not exist, but we just don't like the name
2116 return [
2117 'warning' => 'thumb-name',
2118 'file' => $file,
2119 'thumbFile' => $file_thb
2120 ];
2121 }
2122
2123 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2124 if ( str_starts_with( $partname, $prefix ) ) {
2125 return [
2126 'warning' => 'bad-prefix',
2127 'file' => $file,
2128 'prefix' => $prefix
2129 ];
2130 }
2131 }
2132
2133 return false;
2134 }
2135
2136 /**
2137 * Helper function that checks whether the filename looks like a thumbnail
2138 * @param string $filename
2139 * @return bool
2140 */
2141 public static function isThumbName( $filename ) {
2142 $n = strrpos( $filename, '.' );
2143 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2144
2145 return (
2146 substr( $partname, 3, 3 ) === 'px-' ||
2147 substr( $partname, 2, 3 ) === 'px-'
2148 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2149 }
2150
2151 /**
2152 * Get a list of disallowed filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
2153 *
2154 * @return string[] List of prefixes
2155 */
2156 public static function getFilenamePrefixBlacklist() {
2157 $list = [];
2158 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2159 if ( !$message->isDisabled() ) {
2160 $lines = explode( "\n", $message->plain() );
2161 foreach ( $lines as $line ) {
2162 // Remove comment lines
2163 $comment = substr( trim( $line ), 0, 1 );
2164 if ( $comment === '#' || $comment == '' ) {
2165 continue;
2166 }
2167 // Remove additional comments after a prefix
2168 $comment = strpos( $line, '#' );
2169 if ( $comment > 0 ) {
2170 $line = substr( $line, 0, $comment - 1 );
2171 }
2172 $list[] = trim( $line );
2173 }
2174 }
2175
2176 return $list;
2177 }
2178
2179 /**
2180 * Gets image info about the file just uploaded.
2181 *
2182 * @deprecated since 1.42, subclasses of ApiUpload can use
2183 * ApiUpload::getUploadImageInfo() instead.
2184 *
2185 * @param ?ApiResult $result unused since 1.42
2186 * @return array Image info
2187 */
2188 public function getImageInfo( $result = null ) {
2189 $apiUpload = ApiUpload::getDummyInstance();
2190 return $apiUpload->getUploadImageInfo( $this );
2191 }
2192
2193 /**
2194 * @param array $error
2195 * @return Status
2196 */
2197 public function convertVerifyErrorToStatus( $error ) {
2198 $code = $error['status'];
2199 unset( $code['status'] );
2200
2201 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2202 }
2203
2204 /**
2205 * Get MediaWiki's maximum uploaded file size for a given type of upload, based on
2206 * $wgMaxUploadSize.
2207 *
2208 * @param null|string $forType
2209 * @return int
2210 */
2211 public static function getMaxUploadSize( $forType = null ) {
2212 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2213
2214 if ( is_array( $maxUploadSize ) ) {
2215 if ( $forType !== null && isset( $maxUploadSize[$forType] ) ) {
2216 return $maxUploadSize[$forType];
2217 }
2218 return $maxUploadSize['*'];
2219 }
2220 return intval( $maxUploadSize );
2221 }
2222
2223 /**
2224 * Get the PHP maximum uploaded file size, based on ini settings. If there is no limit or the
2225 * limit can't be guessed, return a very large number (PHP_INT_MAX) instead.
2226 *
2227 * @since 1.27
2228 * @return int
2229 */
2230 public static function getMaxPhpUploadSize() {
2231 $phpMaxFileSize = wfShorthandToInteger(
2232 ini_get( 'upload_max_filesize' ),
2233 PHP_INT_MAX
2234 );
2235 $phpMaxPostSize = wfShorthandToInteger(
2236 ini_get( 'post_max_size' ),
2237 PHP_INT_MAX
2238 ) ?: PHP_INT_MAX;
2239 return min( $phpMaxFileSize, $phpMaxPostSize );
2240 }
2241
2242 /**
2243 * Get the current status of a chunked upload (used for polling).
2244 *
2245 * This should only be called during POST requests since we
2246 * fetch from dc-local MainStash, and from a GET request we can't
2247 * know that the value is available or up-to-date.
2248 *
2249 * @param UserIdentity $user
2250 * @param string $statusKey
2251 * @return mixed[]|false
2252 */
2253 public static function getSessionStatus( UserIdentity $user, $statusKey ) {
2254 $store = self::getUploadSessionStore();
2255 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2256
2257 return $store->get( $key );
2258 }
2259
2260 /**
2261 * Set the current status of a chunked upload (used for polling).
2262 *
2263 * The value will be set in cache for 1 day.
2264 *
2265 * This should only be called during POST requests.
2266 *
2267 * @param UserIdentity $user
2268 * @param string $statusKey
2269 * @param array|false $value
2270 * @return void
2271 */
2272 public static function setSessionStatus( UserIdentity $user, $statusKey, $value ) {
2273 $store = self::getUploadSessionStore();
2274 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2275 $logger = LoggerFactory::getInstance( 'upload' );
2276
2277 if ( is_array( $value ) && ( $value['result'] ?? '' ) === 'Failure' ) {
2278 $logger->info( 'Upload session {key} for {user} set to failure {status} at {stage}',
2279 [
2280 'result' => $value['result'] ?? '',
2281 'stage' => $value['stage'] ?? 'unknown',
2282 'user' => $user->getName(),
2283 'status' => (string)( $value['status'] ?? '-' ),
2284 'filekey' => $value['filekey'] ?? '',
2285 'key' => $statusKey
2286 ]
2287 );
2288 } elseif ( is_array( $value ) ) {
2289 $logger->debug( 'Upload session {key} for {user} changed {status} at {stage}',
2290 [
2291 'result' => $value['result'] ?? '',
2292 'stage' => $value['stage'] ?? 'unknown',
2293 'user' => $user->getName(),
2294 'status' => (string)( $value['status'] ?? '-' ),
2295 'filekey' => $value['filekey'] ?? '',
2296 'key' => $statusKey
2297 ]
2298 );
2299 } else {
2300 $logger->debug( "Upload session {key} deleted for {user}",
2301 [
2302 'value' => $value,
2303 'key' => $statusKey,
2304 'user' => $user->getName()
2305 ]
2306 );
2307 }
2308
2309 if ( $value === false ) {
2310 $store->delete( $key );
2311 } else {
2312 $store->set( $key, $value, $store::TTL_DAY );
2313 }
2314 }
2315
2316 /**
2317 * @param BagOStuff $store
2318 * @param UserIdentity $user
2319 * @param string $statusKey
2320 * @return string
2321 */
2322 private static function getUploadSessionKey( BagOStuff $store, UserIdentity $user, $statusKey ) {
2323 return $store->makeKey(
2324 'uploadstatus',
2325 $user->isRegistered() ? $user->getId() : md5( $user->getName() ),
2326 $statusKey
2327 );
2328 }
2329
2330 /**
2331 * @return BagOStuff
2332 */
2333 private static function getUploadSessionStore() {
2334 return MediaWikiServices::getInstance()->getMainObjectStash();
2335 }
2336 }