Merge "upload: Fix doc on UploadVerifyUploadHook"
[mediawiki.git] / includes / upload / UploadBase.php
blob67563571ac3e488e93a0c61e435497cf4bd8c5b1
1 <?php
2 /**
3 * Base class for the backend of file upload.
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.
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.
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
20 * @file
21 * @ingroup Upload
24 use MediaWiki\HookContainer\HookRunner;
25 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
26 use MediaWiki\MainConfigNames;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Permissions\Authority;
29 use MediaWiki\Permissions\PermissionStatus;
30 use MediaWiki\Request\WebRequest;
31 use MediaWiki\Shell\Shell;
32 use MediaWiki\Status\Status;
33 use MediaWiki\Title\Title;
34 use MediaWiki\User\UserIdentity;
35 use Wikimedia\AtEase\AtEase;
37 /**
38 * @defgroup Upload Upload related
41 /**
42 * @ingroup Upload
44 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
45 * The frontends are formed by ApiUpload and SpecialUpload.
47 * @stable to extend
49 * @author Brion Vibber
50 * @author Bryan Tong Minh
51 * @author Michael Dale
53 abstract class UploadBase {
54 use ProtectedHookAccessorTrait;
56 /** @var string|null Local file system path to the file to upload (or a local copy) */
57 protected $mTempPath;
58 /** @var TempFSFile|null Wrapper to handle deleting the temp file */
59 protected $tempFileObj;
60 /** @var string|null */
61 protected $mDesiredDestName;
62 /** @var string|null */
63 protected $mDestName;
64 /** @var bool|null */
65 protected $mRemoveTempFile;
66 /** @var string|null */
67 protected $mSourceType;
68 /** @var Title|false|null */
69 protected $mTitle = false;
70 /** @var int */
71 protected $mTitleError = 0;
72 /** @var string|null */
73 protected $mFilteredName;
74 /** @var string|null */
75 protected $mFinalExtension;
76 /** @var LocalFile|null */
77 protected $mLocalFile;
78 /** @var UploadStashFile|null */
79 protected $mStashFile;
80 /** @var int|null */
81 protected $mFileSize;
82 /** @var array|null */
83 protected $mFileProps;
84 /** @var string[] */
85 protected $mBlackListedExtensions;
86 /** @var bool|null */
87 protected $mJavaDetected;
88 /** @var string|false */
89 protected $mSVGNSError;
91 protected static $safeXmlEncodings = [
92 'UTF-8',
93 'US-ASCII',
94 'ISO-8859-1',
95 'ISO-8859-2',
96 'UTF-16',
97 'UTF-32',
98 'WINDOWS-1250',
99 'WINDOWS-1251',
100 'WINDOWS-1252',
101 'WINDOWS-1253',
102 'WINDOWS-1254',
103 'WINDOWS-1255',
104 'WINDOWS-1256',
105 'WINDOWS-1257',
106 'WINDOWS-1258',
109 public const SUCCESS = 0;
110 public const OK = 0;
111 public const EMPTY_FILE = 3;
112 public const MIN_LENGTH_PARTNAME = 4;
113 public const ILLEGAL_FILENAME = 5;
114 public const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
115 public const FILETYPE_MISSING = 8;
116 public const FILETYPE_BADTYPE = 9;
117 public const VERIFICATION_ERROR = 10;
118 public const HOOK_ABORTED = 11;
119 public const FILE_TOO_LARGE = 12;
120 public const WINDOWS_NONASCII_FILENAME = 13;
121 public const FILENAME_TOO_LONG = 14;
123 private const CODE_TO_STATUS = [
124 self::EMPTY_FILE => 'empty-file',
125 self::FILE_TOO_LARGE => 'file-too-large',
126 self::FILETYPE_MISSING => 'filetype-missing',
127 self::FILETYPE_BADTYPE => 'filetype-banned',
128 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
129 self::ILLEGAL_FILENAME => 'illegal-filename',
130 self::OVERWRITE_EXISTING_FILE => 'overwrite',
131 self::VERIFICATION_ERROR => 'verification-error',
132 self::HOOK_ABORTED => 'hookaborted',
133 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
134 self::FILENAME_TOO_LONG => 'filename-toolong',
138 * @param int $error
139 * @return string
141 public function getVerificationErrorCode( $error ) {
142 return self::CODE_TO_STATUS[$error] ?? 'unknown-error';
146 * Returns true if uploads are enabled.
147 * Can be override by subclasses.
148 * @stable to override
149 * @return bool
151 public static function isEnabled() {
152 $enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
154 return $enableUploads && wfIniGetBool( 'file_uploads' );
158 * Returns true if the user can use this upload module or else a string
159 * identifying the missing permission.
160 * Can be overridden by subclasses.
162 * @param Authority $performer
163 * @return bool|string
165 public static function isAllowed( Authority $performer ) {
166 foreach ( [ 'upload', 'edit' ] as $permission ) {
167 if ( !$performer->isAllowed( $permission ) ) {
168 return $permission;
172 return true;
176 * Returns true if the user has surpassed the upload rate limit, false otherwise.
178 * @param User $user
179 * @return bool
181 public static function isThrottled( $user ) {
182 return $user->pingLimiter( 'upload' );
185 /** @var string[] Upload handlers. Should probably just be a configuration variable. */
186 private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
189 * Create a form of UploadBase depending on wpSourceType and initializes it.
191 * @param WebRequest &$request
192 * @param string|null $type
193 * @return null|self
195 public static function createFromRequest( &$request, $type = null ) {
196 $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
198 if ( !$type ) {
199 return null;
202 // Get the upload class
203 $type = ucfirst( $type );
205 // Give hooks the chance to handle this request
206 /** @var self|null $className */
207 $className = null;
208 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
209 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
210 ->onUploadCreateFromRequest( $type, $className );
211 if ( $className === null ) {
212 $className = 'UploadFrom' . $type;
213 wfDebug( __METHOD__ . ": class name: $className" );
214 if ( !in_array( $type, self::$uploadHandlers ) ) {
215 return null;
219 if ( !$className::isEnabled() || !$className::isValidRequest( $request ) ) {
220 return null;
223 /** @var self $handler */
224 $handler = new $className;
226 $handler->initializeFromRequest( $request );
228 return $handler;
232 * Check whether a request if valid for this handler.
233 * @param WebRequest $request
234 * @return bool
236 public static function isValidRequest( $request ) {
237 return false;
241 * @stable to call
243 public function __construct() {
247 * Returns the upload type. Should be overridden by child classes.
249 * @since 1.18
250 * @stable to override
251 * @return string|null
253 public function getSourceType() {
254 return null;
258 * @param string $name The desired destination name
259 * @param string|null $tempPath
260 * @param int|null $fileSize
261 * @param bool $removeTempFile (false) remove the temporary file?
262 * @throws MWException
264 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
265 $this->mDesiredDestName = $name;
266 if ( FileBackend::isStoragePath( $tempPath ) ) {
267 throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
270 $this->setTempFile( $tempPath, $fileSize );
271 $this->mRemoveTempFile = $removeTempFile;
275 * Initialize from a WebRequest. Override this in a subclass.
277 * @param WebRequest &$request
279 abstract public function initializeFromRequest( &$request );
282 * @param string|null $tempPath File system path to temporary file containing the upload
283 * @param int|null $fileSize
285 protected function setTempFile( $tempPath, $fileSize = null ) {
286 $this->mTempPath = $tempPath ?? '';
287 $this->mFileSize = $fileSize ?: null;
288 if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
289 $this->tempFileObj = new TempFSFile( $this->mTempPath );
290 if ( !$fileSize ) {
291 $this->mFileSize = filesize( $this->mTempPath );
293 } else {
294 $this->tempFileObj = null;
299 * Fetch the file. Usually a no-op.
300 * @stable to override
301 * @return Status
303 public function fetchFile() {
304 return Status::newGood();
308 * Return true if the file is empty.
309 * @return bool
311 public function isEmptyFile() {
312 return !$this->mFileSize;
316 * Return the file size.
317 * @return int
319 public function getFileSize() {
320 return $this->mFileSize;
324 * Get the base 36 SHA1 of the file.
325 * @stable to override
326 * @return string|false
328 public function getTempFileSha1Base36() {
329 return FSFile::getSha1Base36FromPath( $this->mTempPath );
333 * @param string $srcPath The source path
334 * @return string|false The real path if it was a virtual URL Returns false on failure
336 public function getRealPath( $srcPath ) {
337 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
338 if ( FileRepo::isVirtualUrl( $srcPath ) ) {
339 /** @todo Just make uploads work with storage paths UploadFromStash
340 * loads files via virtual URLs.
342 $tmpFile = $repo->getLocalCopy( $srcPath );
343 if ( $tmpFile ) {
344 $tmpFile->bind( $this ); // keep alive with $this
346 $path = $tmpFile ? $tmpFile->getPath() : false;
347 } else {
348 $path = $srcPath;
351 return $path;
355 * Verify whether the upload is sensible.
357 * Return a status array representing the outcome of the verification.
358 * Possible keys are:
359 * - 'status': set to self::OK in case of success, or to one of the error constants defined in
360 * this class in case of failure
361 * - 'max': set to the maximum allowed file size ($wgMaxUploadSize) if the upload is too large
362 * - 'details': set to error details if the file type is valid but contents are corrupt
363 * - 'filtered': set to the sanitized file name if the requested file name is invalid
364 * - 'finalExt': set to the file's file extension if it is not an allowed file extension
365 * - 'blacklistedExt': set to the list of disallowed file extensions if the current file extension
366 * is not allowed for uploads and the list is not empty
368 * @stable to override
369 * @return mixed[] array representing the result of the verification
371 public function verifyUpload() {
373 * If there was no filename or a zero size given, give up quick.
375 if ( $this->isEmptyFile() ) {
376 return [ 'status' => self::EMPTY_FILE ];
380 * Honor $wgMaxUploadSize
382 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
383 if ( $this->mFileSize > $maxSize ) {
384 return [
385 'status' => self::FILE_TOO_LARGE,
386 'max' => $maxSize,
391 * Look at the contents of the file; if we can recognize the
392 * type, but it's corrupt or data of the wrong type, we should
393 * probably not accept it.
395 $verification = $this->verifyFile();
396 if ( $verification !== true ) {
397 return [
398 'status' => self::VERIFICATION_ERROR,
399 'details' => $verification
404 * Make sure this file can be created
406 $result = $this->validateName();
407 if ( $result !== true ) {
408 return $result;
411 return [ 'status' => self::OK ];
415 * Verify that the name is valid and, if necessary, that we can overwrite
417 * @return array|bool True if valid, otherwise an array with 'status'
418 * and other keys
420 public function validateName() {
421 $nt = $this->getTitle();
422 if ( $nt === null ) {
423 $result = [ 'status' => $this->mTitleError ];
424 if ( $this->mTitleError === self::ILLEGAL_FILENAME ) {
425 $result['filtered'] = $this->mFilteredName;
427 if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
428 $result['finalExt'] = $this->mFinalExtension;
429 if ( count( $this->mBlackListedExtensions ) ) {
430 $result['blacklistedExt'] = $this->mBlackListedExtensions;
434 return $result;
436 $this->mDestName = $this->getLocalFile()->getName();
438 return true;
442 * Verify the MIME type.
444 * @note Only checks that it is not an evil MIME.
445 * The "does it have the correct file extension given its MIME type?" check is in verifyFile.
446 * @param string $mime Representing the MIME
447 * @return array|bool True if the file is verified, an array otherwise
449 protected function verifyMimeType( $mime ) {
450 $verifyMimeType = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeType );
451 if ( $verifyMimeType ) {
452 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
453 $mimeTypeExclusions = MediaWikiServices::getInstance()->getMainConfig()
454 ->get( MainConfigNames::MimeTypeExclusions );
455 if ( self::checkFileExtension( $mime, $mimeTypeExclusions ) ) {
456 return [ 'filetype-badmime', $mime ];
460 return true;
464 * Verifies that it's ok to include the uploaded file
466 * @return array|true True of the file is verified, array otherwise.
468 protected function verifyFile() {
469 $config = MediaWikiServices::getInstance()->getMainConfig();
470 $verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
471 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
472 $status = $this->verifyPartialFile();
473 if ( $status !== true ) {
474 return $status;
477 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
478 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
479 $mime = $this->mFileProps['mime'];
481 if ( $verifyMimeType ) {
482 # XXX: Missing extension will be caught by validateName() via getTitle()
483 if ( (string)$this->mFinalExtension !== '' &&
484 !self::verifyExtension( $mime, $this->mFinalExtension )
486 return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
490 # check for htmlish code and javascript
491 if ( !$disableUploadScriptChecks ) {
492 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
493 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
494 if ( $svgStatus !== false ) {
495 return $svgStatus;
500 $handler = MediaHandler::getHandler( $mime );
501 if ( $handler ) {
502 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
503 if ( !$handlerStatus->isOK() ) {
504 $errors = $handlerStatus->getErrorsArray();
506 return reset( $errors );
510 $error = true;
511 $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
512 if ( $error !== true ) {
513 if ( !is_array( $error ) ) {
514 $error = [ $error ];
516 return $error;
519 wfDebug( __METHOD__ . ": all clear; passing." );
521 return true;
525 * A verification routine suitable for partial files
527 * Runs the deny list checks, but not any checks that may
528 * assume the entire file is present.
530 * @return array|true True, if the file is valid, else an array with error message key.
531 * @phan-return non-empty-array|true
533 protected function verifyPartialFile() {
534 $config = MediaWikiServices::getInstance()->getMainConfig();
535 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
536 # getTitle() sets some internal parameters like $this->mFinalExtension
537 $this->getTitle();
539 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
540 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
542 # check MIME type, if desired
543 $mime = $this->mFileProps['file-mime'];
544 $status = $this->verifyMimeType( $mime );
545 if ( $status !== true ) {
546 return $status;
549 # check for htmlish code and javascript
550 if ( !$disableUploadScriptChecks ) {
551 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
552 return [ 'uploadscripted' ];
554 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
555 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
556 if ( $svgStatus !== false ) {
557 return $svgStatus;
562 # Scan the uploaded file for viruses
563 $virus = self::detectVirus( $this->mTempPath );
564 if ( $virus ) {
565 return [ 'uploadvirus', $virus ];
568 return true;
572 * Callback for ZipDirectoryReader to detect Java class files.
574 * @param array $entry
576 public function zipEntryCallback( $entry ) {
577 $names = [ $entry['name'] ];
579 // If there is a null character, cut off the name at it, because JDK's
580 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
581 // were constructed which had ".class\0" followed by a string chosen to
582 // make the hash collide with the truncated name, that file could be
583 // returned in response to a request for the .class file.
584 $nullPos = strpos( $entry['name'], "\000" );
585 if ( $nullPos !== false ) {
586 $names[] = substr( $entry['name'], 0, $nullPos );
589 // If there is a trailing slash in the file name, we have to strip it,
590 // because that's what ZIP_GetEntry() does.
591 if ( preg_grep( '!\.class/?$!', $names ) ) {
592 $this->mJavaDetected = true;
597 * Alias for verifyTitlePermissions. The function was originally
598 * 'verifyPermissions', but that suggests it's checking the user, when it's
599 * really checking the title + user combination.
601 * @param Authority $performer to verify the permissions against
602 * @return array|bool An array as returned by getPermissionErrors or true
603 * in case the user has proper permissions.
605 public function verifyPermissions( Authority $performer ) {
606 return $this->verifyTitlePermissions( $performer );
610 * Check whether the user can edit, upload and create the image. This
611 * checks only against the current title; if it returns errors, it may
612 * very well be that another title will not give errors. Therefore
613 * isAllowed() should be called as well for generic is-user-blocked or
614 * can-user-upload checking.
616 * @param Authority $performer to verify the permissions against
617 * @return array|bool An array as returned by getPermissionErrors or true
618 * in case the user has proper permissions.
620 public function verifyTitlePermissions( Authority $performer ) {
622 * If the image is protected, non-sysop users won't be able
623 * to modify it by uploading a new revision.
625 $nt = $this->getTitle();
626 if ( $nt === null ) {
627 return true;
630 $status = PermissionStatus::newEmpty();
631 $performer->authorizeWrite( 'edit', $nt, $status );
632 $performer->authorizeWrite( 'upload', $nt, $status );
633 if ( !$status->isGood() ) {
634 return $status->toLegacyErrorArray();
637 $overwriteError = $this->checkOverwrite( $performer );
638 if ( $overwriteError !== true ) {
639 return [ $overwriteError ];
642 return true;
646 * Check for non fatal problems with the file.
648 * This should not assume that mTempPath is set.
650 * @param User|null $user Accepted since 1.35
652 * @return mixed[] Array of warnings
654 public function checkWarnings( $user = null ) {
655 if ( $user === null ) {
656 // TODO check uses and hard deprecate
657 $user = RequestContext::getMain()->getUser();
660 $warnings = [];
662 $localFile = $this->getLocalFile();
663 $localFile->load( File::READ_LATEST );
664 $filename = $localFile->getName();
665 $hash = $this->getTempFileSha1Base36();
667 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
668 if ( $badFileName !== null ) {
669 $warnings['badfilename'] = $badFileName;
672 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension );
673 if ( $unwantedFileExtensionDetails !== null ) {
674 $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
677 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
678 if ( $fileSizeWarnings ) {
679 $warnings = array_merge( $warnings, $fileSizeWarnings );
682 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
683 if ( $localFileExistsWarnings ) {
684 $warnings = array_merge( $warnings, $localFileExistsWarnings );
687 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
688 $warnings['was-deleted'] = $filename;
691 // If a file with the same name exists locally then the local file has already been tested
692 // for duplication of content
693 $ignoreLocalDupes = isset( $warnings['exists'] );
694 $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
695 if ( $dupes ) {
696 $warnings['duplicate'] = $dupes;
699 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
700 if ( $archivedDupes !== null ) {
701 $warnings['duplicate-archive'] = $archivedDupes;
704 return $warnings;
708 * Convert the warnings array returned by checkWarnings() to something that
709 * can be serialized. File objects will be converted to an associative array
710 * with the following keys:
712 * - fileName: The name of the file
713 * - timestamp: The upload timestamp
715 * @param mixed[] $warnings
716 * @return mixed[]
718 public static function makeWarningsSerializable( $warnings ) {
719 array_walk_recursive( $warnings, static function ( &$param, $key ) {
720 if ( $param instanceof File ) {
721 $param = [
722 'fileName' => $param->getName(),
723 'timestamp' => $param->getTimestamp()
725 } elseif ( is_object( $param ) ) {
726 throw new InvalidArgumentException(
727 'UploadBase::makeWarningsSerializable: ' .
728 'Unexpected object of class ' . get_class( $param ) );
730 } );
731 return $warnings;
735 * Check whether the resulting filename is different from the desired one,
736 * but ignore things like ucfirst() and spaces/underscore things
738 * @param string $filename
739 * @param string $desiredFileName
741 * @return string|null String that was determined to be bad or null if the filename is okay
743 private function checkBadFileName( $filename, $desiredFileName ) {
744 $comparableName = str_replace( ' ', '_', $desiredFileName );
745 $comparableName = Title::capitalize( $comparableName, NS_FILE );
747 if ( $desiredFileName != $filename && $comparableName != $filename ) {
748 return $filename;
751 return null;
755 * @param string $fileExtension The file extension to check
757 * @return array|null array with the following keys:
758 * 0 => string The final extension being used
759 * 1 => string[] The extensions that are allowed
760 * 2 => int The number of extensions that are allowed.
762 private function checkUnwantedFileExtensions( $fileExtension ) {
763 $checkFileExtensions = MediaWikiServices::getInstance()->getMainConfig()
764 ->get( MainConfigNames::CheckFileExtensions );
765 $fileExtensions = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::FileExtensions );
766 if ( $checkFileExtensions ) {
767 $extensions = array_unique( $fileExtensions );
768 if ( !self::checkFileExtension( $fileExtension, $extensions ) ) {
769 return [
770 $fileExtension,
771 Message::listParam( $extensions, 'comma' ),
772 count( $extensions )
777 return null;
781 * @param int $fileSize
783 * @return array warnings
785 private function checkFileSize( $fileSize ) {
786 $uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
787 ->get( MainConfigNames::UploadSizeWarning );
789 $warnings = [];
791 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
792 $warnings['large-file'] = [
793 Message::sizeParam( $uploadSizeWarning ),
794 Message::sizeParam( $fileSize ),
798 if ( $fileSize == 0 ) {
799 $warnings['empty-file'] = true;
802 return $warnings;
806 * @param LocalFile $localFile
807 * @param string|false $hash sha1 hash of the file to check
809 * @return array warnings
811 private function checkLocalFileExists( LocalFile $localFile, $hash ) {
812 $warnings = [];
814 $exists = self::getExistsWarning( $localFile );
815 if ( $exists !== false ) {
816 $warnings['exists'] = $exists;
818 // check if file is an exact duplicate of current file version
819 if ( $hash !== false && $hash === $localFile->getSha1() ) {
820 $warnings['no-change'] = $localFile;
823 // check if file is an exact duplicate of older versions of this file
824 $history = $localFile->getHistory();
825 foreach ( $history as $oldFile ) {
826 if ( $hash === $oldFile->getSha1() ) {
827 $warnings['duplicate-version'][] = $oldFile;
832 return $warnings;
835 private function checkLocalFileWasDeleted( LocalFile $localFile ) {
836 return $localFile->wasDeleted() && !$localFile->exists();
840 * @param string|false $hash sha1 hash of the file to check
841 * @param bool $ignoreLocalDupes True to ignore local duplicates
843 * @return File[] Duplicate files, if found.
845 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
846 if ( $hash === false ) {
847 return [];
849 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
850 $title = $this->getTitle();
851 foreach ( $dupes as $key => $dupe ) {
852 if (
853 ( $dupe instanceof LocalFile ) &&
854 $ignoreLocalDupes &&
855 $title->equals( $dupe->getTitle() )
857 unset( $dupes[$key] );
861 return $dupes;
865 * @param string|false $hash sha1 hash of the file to check
866 * @param Authority $performer
868 * @return string|null Name of the dupe or empty string if discovered (depending on visibility)
869 * null if the check discovered no dupes.
871 private function checkAgainstArchiveDupes( $hash, Authority $performer ) {
872 if ( $hash === false ) {
873 return null;
875 $archivedFile = new ArchivedFile( null, 0, '', $hash );
876 if ( $archivedFile->getID() > 0 ) {
877 if ( $archivedFile->userCan( File::DELETED_FILE, $performer ) ) {
878 return $archivedFile->getName();
880 return '';
883 return null;
887 * Really perform the upload. Stores the file in the local repo, watches
888 * if necessary and runs the UploadComplete hook.
890 * @param string $comment
891 * @param string|false $pageText
892 * @param bool $watch Whether the file page should be added to user's watchlist.
893 * (This doesn't check $user's permissions.)
894 * @param User $user
895 * @param string[] $tags Change tags to add to the log entry and page revision.
896 * (This doesn't check $user's permissions.)
897 * @param string|null $watchlistExpiry Optional watchlist expiry timestamp in any format
898 * acceptable to wfTimestamp().
899 * @return Status Indicating the whether the upload succeeded.
901 * @since 1.35 Accepts $watchlistExpiry parameter.
903 public function performUpload(
904 $comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
906 $this->getLocalFile()->load( File::READ_LATEST );
907 $props = $this->mFileProps;
909 $error = null;
910 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
911 if ( $error ) {
912 if ( !is_array( $error ) ) {
913 $error = [ $error ];
915 return Status::newFatal( ...$error );
918 $status = $this->getLocalFile()->upload(
919 $this->mTempPath,
920 $comment,
921 $pageText !== false ? $pageText : '',
922 File::DELETE_SOURCE,
923 $props,
924 false,
925 $user,
926 $tags
929 if ( $status->isGood() ) {
930 if ( $watch ) {
931 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
932 $user,
933 $this->getLocalFile()->getTitle(),
934 $watchlistExpiry
937 $this->getHookRunner()->onUploadComplete( $this );
939 $this->postProcessUpload();
942 return $status;
946 * Perform extra steps after a successful upload.
948 * @stable to override
949 * @since 1.25
951 public function postProcessUpload() {
955 * Returns the title of the file to be uploaded. Sets mTitleError in case
956 * the name was illegal.
958 * @return Title|null The title of the file or null in case the name was illegal
960 public function getTitle() {
961 if ( $this->mTitle !== false ) {
962 return $this->mTitle;
964 if ( !is_string( $this->mDesiredDestName ) ) {
965 $this->mTitleError = self::ILLEGAL_FILENAME;
966 $this->mTitle = null;
968 return $this->mTitle;
970 /* Assume that if a user specified File:Something.jpg, this is an error
971 * and that the namespace prefix needs to be stripped of.
973 $title = Title::newFromText( $this->mDesiredDestName );
974 if ( $title && $title->getNamespace() === NS_FILE ) {
975 $this->mFilteredName = $title->getDBkey();
976 } else {
977 $this->mFilteredName = $this->mDesiredDestName;
980 # oi_archive_name is max 255 bytes, which include a timestamp and an
981 # exclamation mark, so restrict file name to 240 bytes.
982 if ( strlen( $this->mFilteredName ) > 240 ) {
983 $this->mTitleError = self::FILENAME_TOO_LONG;
984 $this->mTitle = null;
986 return $this->mTitle;
990 * Chop off any directories in the given filename. Then
991 * filter out illegal characters, and try to make a legible name
992 * out of it. We'll strip some silently that Title would die on.
994 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
995 /* Normalize to title form before we do any further processing */
996 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
997 if ( $nt === null ) {
998 $this->mTitleError = self::ILLEGAL_FILENAME;
999 $this->mTitle = null;
1001 return $this->mTitle;
1003 $this->mFilteredName = $nt->getDBkey();
1006 * We'll want to prevent against *any* 'extension', and use
1007 * only the final one for the allow list.
1009 [ $partname, $ext ] = self::splitExtensions( $this->mFilteredName );
1011 if ( $ext !== [] ) {
1012 $this->mFinalExtension = trim( end( $ext ) );
1013 } else {
1014 $this->mFinalExtension = '';
1016 // No extension, try guessing one from the temporary file
1017 // FIXME: Sometimes we mTempPath isn't set yet here, possibly due to an unrealistic
1018 // or incomplete test case in UploadBaseTest (T272328)
1019 if ( $this->mTempPath !== null ) {
1020 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1021 $mime = $magic->guessMimeType( $this->mTempPath );
1022 if ( $mime !== 'unknown/unknown' ) {
1023 # Get a space separated list of extensions
1024 $mimeExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
1025 if ( $mimeExt !== null ) {
1026 # Set the extension to the canonical extension
1027 $this->mFinalExtension = $mimeExt;
1029 # Fix up the other variables
1030 $this->mFilteredName .= ".{$this->mFinalExtension}";
1031 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1032 $ext = [ $this->mFinalExtension ];
1038 // Don't allow users to override the list of prohibited file extensions (check file extension)
1039 $config = MediaWikiServices::getInstance()->getMainConfig();
1040 $checkFileExtensions = $config->get( MainConfigNames::CheckFileExtensions );
1041 $strictFileExtensions = $config->get( MainConfigNames::StrictFileExtensions );
1042 $fileExtensions = $config->get( MainConfigNames::FileExtensions );
1043 $prohibitedFileExtensions = $config->get( MainConfigNames::ProhibitedFileExtensions );
1045 $badList = self::checkFileExtensionList( $ext, $prohibitedFileExtensions );
1047 if ( $this->mFinalExtension == '' ) {
1048 $this->mTitleError = self::FILETYPE_MISSING;
1049 $this->mTitle = null;
1051 return $this->mTitle;
1054 if ( $badList ||
1055 ( $checkFileExtensions && $strictFileExtensions &&
1056 !self::checkFileExtension( $this->mFinalExtension, $fileExtensions ) )
1058 $this->mBlackListedExtensions = $badList;
1059 $this->mTitleError = self::FILETYPE_BADTYPE;
1060 $this->mTitle = null;
1062 return $this->mTitle;
1065 // Windows may be broken with special characters, see T3780
1066 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1067 && !MediaWikiServices::getInstance()->getRepoGroup()
1068 ->getLocalRepo()->backendSupportsUnicodePaths()
1070 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1071 $this->mTitle = null;
1073 return $this->mTitle;
1076 # If there was more than one file "extension", reassemble the base
1077 # filename to prevent bogus complaints about length
1078 if ( count( $ext ) > 1 ) {
1079 $iterations = count( $ext ) - 1;
1080 for ( $i = 0; $i < $iterations; $i++ ) {
1081 $partname .= '.' . $ext[$i];
1085 if ( strlen( $partname ) < 1 ) {
1086 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1087 $this->mTitle = null;
1089 return $this->mTitle;
1092 $this->mTitle = $nt;
1094 return $this->mTitle;
1098 * Return the local file and initializes if necessary.
1100 * @stable to override
1101 * @return LocalFile|null
1103 public function getLocalFile() {
1104 if ( $this->mLocalFile === null ) {
1105 $nt = $this->getTitle();
1106 $this->mLocalFile = $nt === null
1107 ? null
1108 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1111 return $this->mLocalFile;
1115 * @return UploadStashFile|null
1117 public function getStashFile() {
1118 return $this->mStashFile;
1122 * Like stashFile(), but respects extensions' wishes to prevent the stashing. verifyUpload() must
1123 * be called before calling this method (unless $isPartial is true).
1125 * Upload stash exceptions are also caught and converted to an error status.
1127 * @since 1.28
1128 * @stable to override
1129 * @param User $user
1130 * @param bool $isPartial Pass `true` if this is a part of a chunked upload (not a complete file).
1131 * @return Status If successful, value is an UploadStashFile instance
1133 public function tryStashFile( User $user, $isPartial = false ) {
1134 if ( !$isPartial ) {
1135 $error = $this->runUploadStashFileHook( $user );
1136 if ( $error ) {
1137 return Status::newFatal( ...$error );
1140 try {
1141 $file = $this->doStashFile( $user );
1142 return Status::newGood( $file );
1143 } catch ( UploadStashException $e ) {
1144 return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1149 * @param User $user
1150 * @return array|null Error message and parameters, null if there's no error
1152 protected function runUploadStashFileHook( User $user ) {
1153 $props = $this->mFileProps;
1154 $error = null;
1155 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1156 if ( $error && !is_array( $error ) ) {
1157 $error = [ $error ];
1159 return $error;
1163 * Implementation for stashFile() and tryStashFile().
1165 * @stable to override
1166 * @param User|null $user
1167 * @return UploadStashFile Stashed file
1169 protected function doStashFile( User $user = null ) {
1170 $stash = MediaWikiServices::getInstance()->getRepoGroup()
1171 ->getLocalRepo()->getUploadStash( $user );
1172 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
1173 $this->mStashFile = $file;
1175 return $file;
1179 * If we've modified the upload file, then we need to manually remove it
1180 * on exit to clean up.
1182 public function cleanupTempFile() {
1183 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1184 // Delete when all relevant TempFSFile handles go out of scope
1185 wfDebug( __METHOD__ . ": Marked temporary file '{$this->mTempPath}' for removal" );
1186 $this->tempFileObj->autocollect();
1191 * @return string|null
1193 public function getTempPath() {
1194 return $this->mTempPath;
1198 * Split a file into a base name and all dot-delimited 'extensions'
1199 * on the end. Some web server configurations will fall back to
1200 * earlier pseudo-'extensions' to determine type and execute
1201 * scripts, so we need to check them all.
1203 * @param string $filename
1204 * @return array [ string, string[] ]
1206 public static function splitExtensions( $filename ) {
1207 $bits = explode( '.', $filename );
1208 $basename = array_shift( $bits );
1210 return [ $basename, $bits ];
1214 * Perform case-insensitive match against a list of file extensions.
1216 * @param string $ext File extension
1217 * @param array $list
1218 * @return bool Returns true if the extension is in the list.
1220 public static function checkFileExtension( $ext, $list ) {
1221 return in_array( strtolower( $ext ?? '' ), $list, true );
1225 * Perform case-insensitive match against a list of file extensions.
1226 * Returns an array of matching extensions.
1228 * @param string[] $ext File extensions
1229 * @param string[] $list
1230 * @return string[]
1232 public static function checkFileExtensionList( $ext, $list ) {
1233 return array_intersect( array_map( 'strtolower', $ext ), $list );
1237 * Checks if the MIME type of the uploaded file matches the file extension.
1239 * @param string $mime The MIME type of the uploaded file
1240 * @param string $extension The filename extension that the file is to be served with
1241 * @return bool
1243 public static function verifyExtension( $mime, $extension ) {
1244 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1246 if ( !$mime || $mime === 'unknown' || $mime === 'unknown/unknown' ) {
1247 if ( !$magic->isRecognizableExtension( $extension ) ) {
1248 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1249 "unrecognized extension '$extension', can't verify" );
1251 return true;
1254 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1255 "recognized extension '$extension', so probably invalid file" );
1256 return false;
1259 $match = $magic->isMatchingExtension( $extension, $mime );
1261 if ( $match === null ) {
1262 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1263 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension" );
1265 return false;
1268 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file" );
1269 return true;
1272 if ( $match ) {
1273 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file" );
1275 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1276 return true;
1279 wfDebug( __METHOD__
1280 . ": mime type $mime mismatches file extension $extension, rejecting file" );
1282 return false;
1286 * Heuristic for detecting files that *could* contain JavaScript instructions or
1287 * things that may look like HTML to a browser and are thus
1288 * potentially harmful. The present implementation will produce false
1289 * positives in some situations.
1291 * @param string|null $file Pathname to the temporary upload file
1292 * @param string $mime The MIME type of the file
1293 * @param string|null $extension The extension of the file
1294 * @return bool True if the file contains something looking like embedded scripts
1296 public static function detectScript( $file, $mime, $extension ) {
1297 # ugly hack: for text files, always look at the entire file.
1298 # For binary field, just check the first K.
1300 if ( str_starts_with( $mime ?? '', 'text/' ) ) {
1301 $chunk = file_get_contents( $file );
1302 } else {
1303 $fp = fopen( $file, 'rb' );
1304 if ( !$fp ) {
1305 return false;
1307 $chunk = fread( $fp, 1024 );
1308 fclose( $fp );
1311 $chunk = strtolower( $chunk );
1313 if ( !$chunk ) {
1314 return false;
1317 # decode from UTF-16 if needed (could be used for obfuscation).
1318 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
1319 $enc = 'UTF-16BE';
1320 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
1321 $enc = 'UTF-16LE';
1322 } else {
1323 $enc = null;
1326 if ( $enc !== null ) {
1327 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1330 $chunk = trim( $chunk );
1332 /** @todo FIXME: Convert from UTF-16 if necessary! */
1333 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1335 # check for HTML doctype
1336 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1337 return true;
1340 // Some browsers will interpret obscure xml encodings as UTF-8, while
1341 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1342 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
1343 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1344 return true;
1348 // Quick check for HTML heuristics in old IE and Safari.
1350 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1351 // don't need them all here as it can cause many false positives.
1353 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1354 $tags = [
1355 '<body',
1356 '<head',
1357 '<html', # also in safari
1358 '<script', # also in safari
1361 foreach ( $tags as $tag ) {
1362 if ( strpos( $chunk, $tag ) !== false ) {
1363 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1365 return true;
1370 * look for JavaScript
1373 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1374 $chunk = Sanitizer::decodeCharReferences( $chunk );
1376 # look for script-types
1377 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1378 wfDebug( __METHOD__ . ": found script types" );
1380 return true;
1383 # look for html-style script-urls
1384 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1385 wfDebug( __METHOD__ . ": found html-style script urls" );
1387 return true;
1390 # look for css-style script-urls
1391 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1392 wfDebug( __METHOD__ . ": found css-style script urls" );
1394 return true;
1397 wfDebug( __METHOD__ . ": no scripts found" );
1399 return false;
1403 * Check an allowed list of xml encodings that are known not to be interpreted differently
1404 * by the server's xml parser (expat) and some common browsers.
1406 * @param string $file Pathname to the temporary upload file
1407 * @return bool True if the file contains an encoding that could be misinterpreted
1409 public static function checkXMLEncodingMissmatch( $file ) {
1410 $svgMetadataCutoff = MediaWikiServices::getInstance()->getMainConfig()
1411 ->get( MainConfigNames::SVGMetadataCutoff );
1412 $contents = file_get_contents( $file, false, null, 0, $svgMetadataCutoff );
1413 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1415 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1416 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1417 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1419 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1421 return true;
1423 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1424 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1425 // bytes. There shouldn't be a legitimate reason for this to happen.
1426 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1428 return true;
1429 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1430 // EBCDIC encoded XML
1431 wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1433 return true;
1436 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1437 // detect the encoding in case it specifies an encoding not allowed in self::$safeXmlEncodings
1438 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1439 foreach ( $attemptEncodings as $encoding ) {
1440 AtEase::suppressWarnings();
1441 $str = iconv( $encoding, 'UTF-8', $contents );
1442 AtEase::restoreWarnings();
1443 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1444 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1445 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1447 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1449 return true;
1451 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1452 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1453 // bytes. There shouldn't be a legitimate reason for this to happen.
1454 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1456 return true;
1460 return false;
1464 * @param string $filename
1465 * @param bool $partial
1466 * @return bool|array
1468 protected function detectScriptInSvg( $filename, $partial ) {
1469 $this->mSVGNSError = false;
1470 $check = new XmlTypeCheck(
1471 $filename,
1472 [ $this, 'checkSvgScriptCallback' ],
1473 true,
1475 'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1476 'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1479 if ( $check->wellFormed !== true ) {
1480 // Invalid xml (T60553)
1481 // But only when non-partial (T67724)
1482 return $partial ? false : [ 'uploadinvalidxml' ];
1485 if ( $check->filterMatch ) {
1486 if ( $this->mSVGNSError ) {
1487 return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1489 return $check->filterMatchType;
1492 return false;
1496 * Callback to filter SVG Processing Instructions.
1498 * @param string $target Processing instruction name
1499 * @param string $data Processing instruction attribute and value
1500 * @return bool|array
1502 public static function checkSvgPICallback( $target, $data ) {
1503 // Don't allow external stylesheets (T59550)
1504 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1505 return [ 'upload-scripted-pi-callback' ];
1508 return false;
1512 * Verify that DTD URLs referenced are only the standard DTDs.
1514 * Browsers seem to ignore external DTDs.
1516 * However, just to be on the safe side, only allow DTDs from the SVG standard.
1518 * @param string $type PUBLIC or SYSTEM
1519 * @param string $publicId The well-known public identifier for the dtd
1520 * @param string $systemId The url for the external dtd
1521 * @return bool|array
1523 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1524 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1525 // allow XHTML anyway.
1526 static $allowedDTDs = [
1527 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1528 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1529 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1530 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1531 // https://phabricator.wikimedia.org/T168856
1532 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1534 if ( $type !== 'PUBLIC'
1535 || !in_array( $systemId, $allowedDTDs )
1536 || !str_starts_with( $publicId, "-//W3C//" )
1538 return [ 'upload-scripted-dtd' ];
1540 return false;
1544 * @todo Replace this with a allow list filter!
1545 * @param string $element
1546 * @param array $attribs
1547 * @param string|null $data
1548 * @return bool|array
1550 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1551 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1553 // We specifically don't include:
1554 // http://www.w3.org/1999/xhtml (T62771)
1555 static $validNamespaces = [
1557 'adobe:ns:meta/',
1558 'http://creativecommons.org/ns#',
1559 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1560 'http://ns.adobe.com/adobeillustrator/10.0/',
1561 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1562 'http://ns.adobe.com/extensibility/1.0/',
1563 'http://ns.adobe.com/flows/1.0/',
1564 'http://ns.adobe.com/illustrator/1.0/',
1565 'http://ns.adobe.com/imagereplacement/1.0/',
1566 'http://ns.adobe.com/pdf/1.3/',
1567 'http://ns.adobe.com/photoshop/1.0/',
1568 'http://ns.adobe.com/saveforweb/1.0/',
1569 'http://ns.adobe.com/variables/1.0/',
1570 'http://ns.adobe.com/xap/1.0/',
1571 'http://ns.adobe.com/xap/1.0/g/',
1572 'http://ns.adobe.com/xap/1.0/g/img/',
1573 'http://ns.adobe.com/xap/1.0/mm/',
1574 'http://ns.adobe.com/xap/1.0/rights/',
1575 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1576 'http://ns.adobe.com/xap/1.0/stype/font#',
1577 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1578 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1579 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1580 'http://ns.adobe.com/xap/1.0/t/pg/',
1581 'http://purl.org/dc/elements/1.1/',
1582 'http://purl.org/dc/elements/1.1',
1583 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1584 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1585 'http://taptrix.com/inkpad/svg_extensions',
1586 'http://web.resource.org/cc/',
1587 'http://www.freesoftware.fsf.org/bkchem/cdml',
1588 'http://www.inkscape.org/namespaces/inkscape',
1589 'http://www.opengis.net/gml',
1590 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1591 'http://www.w3.org/2000/svg',
1592 'http://www.w3.org/tr/rec-rdf-syntax/',
1593 'http://www.w3.org/2000/01/rdf-schema#',
1594 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1597 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1598 // This is nasty but harmless. (T144827)
1599 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1601 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1602 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1603 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1604 $this->mSVGNSError = $namespace;
1606 return true;
1609 // check for elements that can contain javascript
1610 if ( $strippedElement === 'script' ) {
1611 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1613 return [ 'uploaded-script-svg', $strippedElement ];
1616 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1617 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1618 if ( $strippedElement === 'handler' ) {
1619 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1621 return [ 'uploaded-script-svg', $strippedElement ];
1624 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1625 if ( $strippedElement === 'stylesheet' ) {
1626 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1628 return [ 'uploaded-script-svg', $strippedElement ];
1631 // Block iframes, in case they pass the namespace check
1632 if ( $strippedElement === 'iframe' ) {
1633 wfDebug( __METHOD__ . ": iframe in uploaded file." );
1635 return [ 'uploaded-script-svg', $strippedElement ];
1638 // Check <style> css
1639 if ( $strippedElement === 'style'
1640 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1642 wfDebug( __METHOD__ . ": hostile css in style element." );
1644 return [ 'uploaded-hostile-svg' ];
1647 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1648 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1650 foreach ( $attribs as $attrib => $value ) {
1651 // If attributeNamespace is '', it is relative to its element's namespace
1652 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
1653 $value = strtolower( $value );
1655 if ( !(
1656 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1657 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1658 $attributeNamespace === ''
1659 ) && str_starts_with( $stripped, 'on' )
1661 wfDebug( __METHOD__
1662 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1664 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1667 // Do not allow relative links, or unsafe url schemas.
1668 // For <a> tags, only data:, http: and https: and same-document
1669 // fragment links are allowed.
1670 // For all other tags, only 'data:' and fragments (#) are allowed.
1671 if (
1672 $stripped === 'href'
1673 && $value !== ''
1674 && !str_starts_with( $value, 'data:' )
1675 && !str_starts_with( $value, '#' )
1676 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1678 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1679 . "'$attrib'='$value' in uploaded file." );
1681 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1684 // Only allow 'data:\' targets that should be safe.
1685 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1686 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1687 // RFC2397 parameters.
1688 // This is only slightly slower than (;[\w;]+)*.
1689 // phpcs:ignore Generic.Files.LineLength
1690 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1692 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1693 wfDebug( __METHOD__ . ": Found href to allow listed data: uri "
1694 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1695 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1699 // Change href with animate from (http://html5sec.org/#137).
1700 if ( $stripped === 'attributename'
1701 && $strippedElement === 'animate'
1702 && $this->stripXmlNamespace( $value ) === 'href'
1704 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1705 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1707 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1710 // Use set/animate to add event-handler attribute to parent.
1711 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
1712 && $stripped === 'attributename'
1713 && str_starts_with( $value, 'on' )
1715 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1716 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1718 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1721 // use set to add href attribute to parent element.
1722 if ( $strippedElement === 'set'
1723 && $stripped === 'attributename'
1724 && str_contains( $value, 'href' )
1726 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1728 return [ 'uploaded-setting-href-svg' ];
1731 // use set to add a remote / data / script target to an element.
1732 if ( $strippedElement === 'set'
1733 && $stripped === 'to'
1734 && preg_match( '!(http|https|data|script):!im', $value )
1736 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1738 return [ 'uploaded-wrong-setting-svg', $value ];
1741 // use handler attribute with remote / data / script.
1742 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1743 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1744 . "'$attrib'='$value' in uploaded file." );
1746 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1749 // use CSS styles to bring in remote code.
1750 if ( $stripped === 'style'
1751 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1753 wfDebug( __METHOD__ . ": Found svg setting a style with "
1754 . "remote url '$attrib'='$value' in uploaded file." );
1755 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1758 // Several attributes can include css, css character escaping isn't allowed.
1759 if ( in_array( $stripped, $cssAttrs, true )
1760 && self::checkCssFragment( $value )
1762 wfDebug( __METHOD__ . ": Found svg setting a style with "
1763 . "remote url '$attrib'='$value' in uploaded file." );
1764 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1767 // image filters can pull in url, which could be svg that executes scripts.
1768 // Only allow url( "#foo" ).
1769 // Do not allow url( http://example.com )
1770 if ( $strippedElement === 'image'
1771 && $stripped === 'filter'
1772 && preg_match( '!url\s*\(\s*["\']?[^#]!im', $value )
1774 wfDebug( __METHOD__ . ": Found image filter with url: "
1775 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1777 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1781 return false; // No scripts detected
1785 * Check a block of CSS or CSS fragment for anything that looks like
1786 * it is bringing in remote code.
1787 * @param string $value a string of CSS
1788 * @return bool true if the CSS contains an illegal string, false if otherwise
1790 private static function checkCssFragment( $value ) {
1791 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1792 if ( stripos( $value, '@import' ) !== false ) {
1793 return true;
1796 # We allow @font-face to embed fonts with data: urls, so we snip the string
1797 # 'url' out so that this case won't match when we check for urls below
1798 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1799 $value = preg_replace( $pattern, '$1$2', $value );
1801 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1802 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1803 # Expression and -o-link don't seem to work either, but filtering them here in case.
1804 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1805 # but not local ones such as url("#..., url('#..., url(#....
1806 if ( preg_match( '!expression
1807 | -o-link\s*:
1808 | -o-link-source\s*:
1809 | -o-replace\s*:!imx', $value ) ) {
1810 return true;
1813 if ( preg_match_all(
1814 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1815 $value,
1816 $matches
1817 ) !== 0
1819 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1820 foreach ( $matches[1] as $match ) {
1821 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1822 return true;
1827 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1828 return true;
1831 return false;
1835 * Divide the element name passed by the XML parser to the callback into URI and prefix.
1836 * @param string $element
1837 * @return array Containing the namespace URI and prefix
1839 private static function splitXmlNamespace( $element ) {
1840 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1841 $parts = explode( ':', strtolower( $element ) );
1842 $name = array_pop( $parts );
1843 $ns = implode( ':', $parts );
1845 return [ $ns, $name ];
1849 * @param string $element
1850 * @return string
1852 private function stripXmlNamespace( $element ) {
1853 // 'http://www.w3.org/2000/svg:script' -> 'script'
1854 return self::splitXmlNamespace( $element )[1];
1858 * Generic wrapper function for a virus scanner program.
1859 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1860 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1862 * @param string $file Pathname to the temporary upload file
1863 * @return bool|null|string False if not virus is found, null if the scan fails or is disabled,
1864 * or a string containing feedback from the virus scanner if a virus was found.
1865 * If textual feedback is missing but a virus was found, this function returns true.
1867 public static function detectVirus( $file ) {
1868 global $wgOut;
1869 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1870 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1871 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1872 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1873 if ( !$antivirus ) {
1874 wfDebug( __METHOD__ . ": virus scanner disabled" );
1876 return null;
1879 if ( !$antivirusSetup[$antivirus] ) {
1880 wfDebug( __METHOD__ . ": unknown virus scanner: {$antivirus}" );
1881 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1882 [ 'virus-badscanner', $antivirus ] );
1884 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1887 # look up scanner configuration
1888 $command = $antivirusSetup[$antivirus]['command'];
1889 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1890 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
1892 if ( !str_contains( $command, "%f" ) ) {
1893 # simple pattern: append file to scan
1894 $command .= " " . Shell::escape( $file );
1895 } else {
1896 # complex pattern: replace "%f" with file to scan
1897 $command = str_replace( "%f", Shell::escape( $file ), $command );
1900 wfDebug( __METHOD__ . ": running virus scan: $command " );
1902 # execute virus scanner
1903 $exitCode = false;
1905 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1906 # that does not seem to be worth the pain.
1907 # Ask me (Duesentrieb) about it if it's ever needed.
1908 $output = wfShellExecWithStderr( $command, $exitCode );
1910 # map exit code to AV_xxx constants.
1911 $mappedCode = $exitCode;
1912 if ( $exitCodeMap ) {
1913 if ( isset( $exitCodeMap[$exitCode] ) ) {
1914 $mappedCode = $exitCodeMap[$exitCode];
1915 } elseif ( isset( $exitCodeMap["*"] ) ) {
1916 $mappedCode = $exitCodeMap["*"];
1920 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1921 # so we need the strict equalities === and thus can't use a switch here
1922 if ( $mappedCode === AV_SCAN_FAILED ) {
1923 # scan failed (code was mapped to false by $exitCodeMap)
1924 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1926 $output = $antivirusRequired
1927 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1928 : null;
1929 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1930 # scan failed because filetype is unknown (probably immune)
1931 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
1932 $output = null;
1933 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1934 # no virus found
1935 wfDebug( __METHOD__ . ": file passed virus scan." );
1936 $output = false;
1937 } else {
1938 $output = trim( $output );
1940 if ( !$output ) {
1941 $output = true; # if there's no output, return true
1942 } elseif ( $msgPattern ) {
1943 $groups = [];
1944 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1945 $output = $groups[1];
1949 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
1952 return $output;
1956 * Check if there's a file overwrite conflict and, if so, if restrictions
1957 * forbid this user from performing the upload.
1959 * @param Authority $performer
1961 * @return bool|array
1963 private function checkOverwrite( Authority $performer ) {
1964 // First check whether the local file can be overwritten
1965 $file = $this->getLocalFile();
1966 $file->load( File::READ_LATEST );
1967 if ( $file->exists() ) {
1968 if ( !self::userCanReUpload( $performer, $file ) ) {
1969 return [ 'fileexists-forbidden', $file->getName() ];
1972 return true;
1975 $services = MediaWikiServices::getInstance();
1977 /* Check shared conflicts: if the local file does not exist, but
1978 * RepoGroup::findFile finds a file, it exists in a shared repository.
1980 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
1981 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
1982 return [ 'fileexists-shared-forbidden', $file->getName() ];
1985 return true;
1989 * Check if a user is the last uploader
1991 * @param Authority $performer
1992 * @param File $img
1993 * @return bool
1995 public static function userCanReUpload( Authority $performer, File $img ) {
1996 if ( $performer->isAllowed( 'reupload' ) ) {
1997 return true; // non-conditional
2000 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2001 return false;
2004 if ( !( $img instanceof LocalFile ) ) {
2005 return false;
2008 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2012 * Helper function that does various existence checks for a file.
2013 * The following checks are performed:
2014 * - If the file exists
2015 * - If an article with the same name as the file exists
2016 * - If a file exists with normalized extension
2017 * - If the file looks like a thumbnail and the original exists
2019 * @param File $file The File object to check
2020 * @return array|false False if the file does not exist, else an array
2022 public static function getExistsWarning( $file ) {
2023 if ( $file->exists() ) {
2024 return [ 'warning' => 'exists', 'file' => $file ];
2027 if ( $file->getTitle()->getArticleID() ) {
2028 return [ 'warning' => 'page-exists', 'file' => $file ];
2031 if ( !strpos( $file->getName(), '.' ) ) {
2032 $partname = $file->getName();
2033 $extension = '';
2034 } else {
2035 $n = strrpos( $file->getName(), '.' );
2036 $extension = substr( $file->getName(), $n + 1 );
2037 $partname = substr( $file->getName(), 0, $n );
2039 $normalizedExtension = File::normalizeExtension( $extension );
2040 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2042 if ( $normalizedExtension != $extension ) {
2043 // We're not using the normalized form of the extension.
2044 // Normal form is lowercase, using most common of alternate
2045 // extensions (e.g. 'jpg' rather than 'JPEG').
2047 // Check for another file using the normalized form...
2048 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2049 $file_lc = $localRepo->newFile( $nt_lc );
2051 if ( $file_lc->exists() ) {
2052 return [
2053 'warning' => 'exists-normalized',
2054 'file' => $file,
2055 'normalizedFile' => $file_lc
2060 // Check for files with the same name but a different extension
2061 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2062 if ( count( $similarFiles ) ) {
2063 return [
2064 'warning' => 'exists-normalized',
2065 'file' => $file,
2066 'normalizedFile' => $similarFiles[0],
2070 if ( self::isThumbName( $file->getName() ) ) {
2071 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2072 $nt_thb = Title::newFromText(
2073 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2074 NS_FILE
2076 $file_thb = $localRepo->newFile( $nt_thb );
2077 if ( $file_thb->exists() ) {
2078 return [
2079 'warning' => 'thumb',
2080 'file' => $file,
2081 'thumbFile' => $file_thb
2085 // The file does not exist, but we just don't like the name
2086 return [
2087 'warning' => 'thumb-name',
2088 'file' => $file,
2089 'thumbFile' => $file_thb
2093 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2094 if ( str_starts_with( $partname, $prefix ) ) {
2095 return [
2096 'warning' => 'bad-prefix',
2097 'file' => $file,
2098 'prefix' => $prefix
2103 return false;
2107 * Helper function that checks whether the filename looks like a thumbnail
2108 * @param string $filename
2109 * @return bool
2111 public static function isThumbName( $filename ) {
2112 $n = strrpos( $filename, '.' );
2113 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2115 return (
2116 substr( $partname, 3, 3 ) === 'px-' ||
2117 substr( $partname, 2, 3 ) === 'px-'
2118 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2122 * Get a list of disallowed filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
2124 * @return string[] List of prefixes
2126 public static function getFilenamePrefixBlacklist() {
2127 $list = [];
2128 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2129 if ( !$message->isDisabled() ) {
2130 $lines = explode( "\n", $message->plain() );
2131 foreach ( $lines as $line ) {
2132 // Remove comment lines
2133 $comment = substr( trim( $line ), 0, 1 );
2134 if ( $comment === '#' || $comment == '' ) {
2135 continue;
2137 // Remove additional comments after a prefix
2138 $comment = strpos( $line, '#' );
2139 if ( $comment > 0 ) {
2140 $line = substr( $line, 0, $comment - 1 );
2142 $list[] = trim( $line );
2146 return $list;
2150 * Gets image info about the file just uploaded.
2152 * Also has the effect of setting metadata to be an 'indexed tag name' in
2153 * returned API result if 'metadata' was requested. Oddly, we have to pass
2154 * the "result" object down just so it can do that with the appropriate
2155 * format, presumably.
2157 * @param ApiResult $result
2158 * @return array Image info
2160 public function getImageInfo( $result ) {
2161 $stashFile = $this->getStashFile();
2162 // Calling a different API module depending on whether the file was stashed is less than optimal.
2163 // In fact, calling API modules here at all is less than optimal. Maybe it should be refactored.
2164 if ( $stashFile ) {
2165 $imParam = ApiQueryStashImageInfo::getPropertyNames();
2166 $info = ApiQueryStashImageInfo::getInfo( $stashFile, array_fill_keys( $imParam, true ), $result );
2167 } else {
2168 $localFile = $this->getLocalFile();
2169 $imParam = ApiQueryImageInfo::getPropertyNames();
2170 $info = ApiQueryImageInfo::getInfo( $localFile, array_fill_keys( $imParam, true ), $result );
2173 return $info;
2177 * @param array $error
2178 * @return Status
2180 public function convertVerifyErrorToStatus( $error ) {
2181 $code = $error['status'];
2182 unset( $code['status'] );
2184 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2188 * Get MediaWiki's maximum uploaded file size for a given type of upload, based on
2189 * $wgMaxUploadSize.
2191 * @param null|string $forType
2192 * @return int
2194 public static function getMaxUploadSize( $forType = null ) {
2195 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2197 if ( is_array( $maxUploadSize ) ) {
2198 if ( $forType !== null && isset( $maxUploadSize[$forType] ) ) {
2199 return $maxUploadSize[$forType];
2201 return $maxUploadSize['*'];
2203 return intval( $maxUploadSize );
2207 * Get the PHP maximum uploaded file size, based on ini settings. If there is no limit or the
2208 * limit can't be guessed, return a very large number (PHP_INT_MAX) instead.
2210 * @since 1.27
2211 * @return int
2213 public static function getMaxPhpUploadSize() {
2214 $phpMaxFileSize = wfShorthandToInteger(
2215 ini_get( 'upload_max_filesize' ),
2216 PHP_INT_MAX
2218 $phpMaxPostSize = wfShorthandToInteger(
2219 ini_get( 'post_max_size' ),
2220 PHP_INT_MAX
2221 ) ?: PHP_INT_MAX;
2222 return min( $phpMaxFileSize, $phpMaxPostSize );
2226 * Get the current status of a chunked upload (used for polling).
2228 * This should only be called during POST requests since we
2229 * fetch from dc-local MainStash, and from a GET request we can't
2230 * know that the value is available or up-to-date.
2232 * @param UserIdentity $user
2233 * @param string $statusKey
2234 * @return Status[]|false
2236 public static function getSessionStatus( UserIdentity $user, $statusKey ) {
2237 $store = self::getUploadSessionStore();
2238 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2240 return $store->get( $key );
2244 * Set the current status of a chunked upload (used for polling).
2246 * The value will be set in cache for 1 day.
2248 * This should only be called during POST requests.
2250 * @param UserIdentity $user
2251 * @param string $statusKey
2252 * @param array|false $value
2253 * @return void
2255 public static function setSessionStatus( UserIdentity $user, $statusKey, $value ) {
2256 $store = self::getUploadSessionStore();
2257 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2259 if ( $value === false ) {
2260 $store->delete( $key );
2261 } else {
2262 $store->set( $key, $value, $store::TTL_DAY );
2267 * @param BagOStuff $store
2268 * @param UserIdentity $user
2269 * @param string $statusKey
2270 * @return string
2272 private static function getUploadSessionKey( BagOStuff $store, UserIdentity $user, $statusKey ) {
2273 return $store->makeKey(
2274 'uploadstatus',
2275 $user->isRegistered() ? $user->getId() : md5( $user->getName() ),
2276 $statusKey
2281 * @return BagOStuff
2283 private static function getUploadSessionStore() {
2284 return MediaWikiServices::getInstance()->getMainObjectStash();