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
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\User\User
;
41 use MediaWiki\User\UserIdentity
;
42 use Wikimedia\AtEase\AtEase
;
43 use Wikimedia\FileBackend\FileBackend
;
44 use Wikimedia\FileBackend\FSFile\FSFile
;
45 use Wikimedia\FileBackend\FSFile\TempFSFile
;
46 use Wikimedia\Mime\XmlTypeCheck
;
47 use Wikimedia\ObjectCache\BagOStuff
;
48 use Wikimedia\Rdbms\IDBAccessObject
;
51 * @defgroup Upload Upload related
57 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
58 * The frontends are formed by ApiUpload and SpecialUpload.
62 * @author Brooke Vibber
63 * @author Bryan Tong Minh
64 * @author Michael Dale
66 abstract class UploadBase
{
67 use ProtectedHookAccessorTrait
;
69 /** @var string|null Local file system path to the file to upload (or a local copy) */
71 /** @var TempFSFile|null Wrapper to handle deleting the temp file */
72 protected $tempFileObj;
73 /** @var string|null */
74 protected $mDesiredDestName;
75 /** @var string|null */
78 protected $mRemoveTempFile;
79 /** @var string|null */
80 protected $mSourceType;
81 /** @var Title|false|null */
82 protected $mTitle = false;
84 protected $mTitleError = 0;
85 /** @var string|null */
86 protected $mFilteredName;
87 /** @var string|null */
88 protected $mFinalExtension;
89 /** @var LocalFile|null */
90 protected $mLocalFile;
91 /** @var UploadStashFile|null */
92 protected $mStashFile;
95 /** @var array|null */
96 protected $mFileProps;
98 protected $mBlackListedExtensions;
100 protected $mJavaDetected;
101 /** @var string|false */
102 protected $mSVGNSError;
104 private const SAFE_XML_ENCONDINGS
= [
122 public const SUCCESS
= 0;
124 public const EMPTY_FILE
= 3;
125 public const MIN_LENGTH_PARTNAME
= 4;
126 public const ILLEGAL_FILENAME
= 5;
127 public const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
128 public const FILETYPE_MISSING
= 8;
129 public const FILETYPE_BADTYPE
= 9;
130 public const VERIFICATION_ERROR
= 10;
131 public const HOOK_ABORTED
= 11;
132 public const FILE_TOO_LARGE
= 12;
133 public const WINDOWS_NONASCII_FILENAME
= 13;
134 public const FILENAME_TOO_LONG
= 14;
136 private const CODE_TO_STATUS
= [
137 self
::EMPTY_FILE
=> 'empty-file',
138 self
::FILE_TOO_LARGE
=> 'file-too-large',
139 self
::FILETYPE_MISSING
=> 'filetype-missing',
140 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
141 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
142 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
143 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
144 self
::VERIFICATION_ERROR
=> 'verification-error',
145 self
::HOOK_ABORTED
=> 'hookaborted',
146 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
147 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
154 public function getVerificationErrorCode( $error ) {
155 return self
::CODE_TO_STATUS
[$error] ??
'unknown-error';
159 * Returns true if uploads are enabled.
160 * Can be override by subclasses.
161 * @stable to override
164 public static function isEnabled() {
165 $enableUploads = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::EnableUploads
);
167 return $enableUploads && wfIniGetBool( 'file_uploads' );
171 * Returns true if the user can use this upload module or else a string
172 * identifying the missing permission.
173 * Can be overridden by subclasses.
175 * @param Authority $performer
176 * @return bool|string
178 public static function isAllowed( Authority
$performer ) {
179 foreach ( [ 'upload', 'edit' ] as $permission ) {
180 if ( !$performer->isAllowed( $permission ) ) {
189 * Returns true if the user has surpassed the upload rate limit, false otherwise.
191 * @deprecated since 1.41, use verifyTitlePermissions() instead.
192 * Rate limit checks are now implicit in permission checks.
197 public static function isThrottled( $user ) {
198 wfDeprecated( __METHOD__
, '1.41' );
199 return $user->pingLimiter( 'upload' );
202 /** @var string[] Upload handlers. Should probably just be a configuration variable. */
203 private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
206 * Create a form of UploadBase depending on wpSourceType and initializes it.
208 * @param WebRequest &$request
209 * @param string|null $type
212 public static function createFromRequest( &$request, $type = null ) {
213 $type = $type ?
: $request->getVal( 'wpSourceType', 'File' );
219 // Get the upload class
220 $type = ucfirst( $type );
222 // Give hooks the chance to handle this request
223 /** @var self|null $className */
225 ( new HookRunner( MediaWikiServices
::getInstance()->getHookContainer() ) )
226 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
227 ->onUploadCreateFromRequest( $type, $className );
228 if ( $className === null ) {
229 $className = 'UploadFrom' . $type;
230 wfDebug( __METHOD__
. ": class name: $className" );
231 if ( !in_array( $type, self
::$uploadHandlers ) ) {
236 if ( !$className::isEnabled() ||
!$className::isValidRequest( $request ) ) {
240 /** @var self $handler */
241 $handler = new $className;
243 $handler->initializeFromRequest( $request );
249 * Check whether a request if valid for this handler.
250 * @param WebRequest $request
253 public static function isValidRequest( $request ) {
258 * Get the desired destination name.
259 * @return string|null
261 public function getDesiredDestName() {
262 return $this->mDesiredDestName
;
268 public function __construct() {
272 * Returns the upload type. Should be overridden by child classes.
275 * @stable to override
276 * @return string|null
278 public function getSourceType() {
283 * @param string $name The desired destination name
284 * @param string|null $tempPath Callers should make sure this is not a storage path
285 * @param int|null $fileSize
286 * @param bool $removeTempFile (false) remove the temporary file?
288 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
289 $this->mDesiredDestName
= $name;
290 if ( FileBackend
::isStoragePath( $tempPath ) ) {
291 throw new InvalidArgumentException( __METHOD__
. " given storage path `$tempPath`." );
294 $this->setTempFile( $tempPath, $fileSize );
295 $this->mRemoveTempFile
= $removeTempFile;
299 * Initialize from a WebRequest. Override this in a subclass.
301 * @param WebRequest &$request
303 abstract public function initializeFromRequest( &$request );
306 * @param string|null $tempPath File system path to temporary file containing the upload
307 * @param int|null $fileSize
309 protected function setTempFile( $tempPath, $fileSize = null ) {
310 $this->mTempPath
= $tempPath ??
'';
311 $this->mFileSize
= $fileSize ?
: null;
312 $this->mFileProps
= null;
313 if ( strlen( $this->mTempPath
) && file_exists( $this->mTempPath
) ) {
314 $this->tempFileObj
= new TempFSFile( $this->mTempPath
);
316 $this->mFileSize
= filesize( $this->mTempPath
);
319 $this->tempFileObj
= null;
324 * Fetch the file. Usually a no-op.
325 * @stable to override
328 public function fetchFile() {
329 return Status
::newGood();
333 * Perform checks to see if the file can be fetched. Usually a no-op.
334 * @stable to override
337 public function canFetchFile() {
338 return Status
::newGood();
342 * Return true if the file is empty.
345 public function isEmptyFile() {
346 return !$this->mFileSize
;
350 * Return the file size.
353 public function getFileSize() {
354 return $this->mFileSize
;
358 * Get the base 36 SHA1 of the file.
359 * @stable to override
360 * @return string|false
362 public function getTempFileSha1Base36() {
363 // Use cached version if we already have it.
364 if ( $this->mFileProps
&& is_string( $this->mFileProps
['sha1'] ) ) {
365 return $this->mFileProps
['sha1'];
367 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
371 * @param string $srcPath The source path
372 * @return string|false The real path if it was a virtual URL Returns false on failure
374 public function getRealPath( $srcPath ) {
375 $repo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
376 if ( FileRepo
::isVirtualUrl( $srcPath ) ) {
377 /** @todo Just make uploads work with storage paths UploadFromStash
378 * loads files via virtual URLs.
380 $tmpFile = $repo->getLocalCopy( $srcPath );
382 $tmpFile->bind( $this ); // keep alive with $this
384 $path = $tmpFile ?
$tmpFile->getPath() : false;
393 * Verify whether the upload is sensible.
395 * Return a status array representing the outcome of the verification.
397 * - 'status': set to self::OK in case of success, or to one of the error constants defined in
398 * this class in case of failure
399 * - 'max': set to the maximum allowed file size ($wgMaxUploadSize) if the upload is too large
400 * - 'details': set to error details if the file type is valid but contents are corrupt
401 * - 'filtered': set to the sanitized file name if the requested file name is invalid
402 * - 'finalExt': set to the file's file extension if it is not an allowed file extension
403 * - 'blacklistedExt': set to the list of disallowed file extensions if the current file extension
404 * is not allowed for uploads and the list is not empty
406 * @stable to override
407 * @return mixed[] array representing the result of the verification
409 public function verifyUpload() {
411 * If there was no filename or a zero size given, give up quick.
413 if ( $this->isEmptyFile() ) {
414 return [ 'status' => self
::EMPTY_FILE
];
418 * Honor $wgMaxUploadSize
420 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
421 if ( $this->mFileSize
> $maxSize ) {
423 'status' => self
::FILE_TOO_LARGE
,
429 * Look at the contents of the file; if we can recognize the
430 * type, but it's corrupt or data of the wrong type, we should
431 * probably not accept it.
433 $verification = $this->verifyFile();
434 if ( $verification !== true ) {
436 'status' => self
::VERIFICATION_ERROR
,
437 'details' => $verification
442 * Make sure this file can be created
444 $result = $this->validateName();
445 if ( $result !== true ) {
449 return [ 'status' => self
::OK
];
453 * Verify that the name is valid and, if necessary, that we can overwrite
455 * @return array|bool True if valid, otherwise an array with 'status'
458 public function validateName() {
459 $nt = $this->getTitle();
460 if ( $nt === null ) {
461 $result = [ 'status' => $this->mTitleError
];
462 if ( $this->mTitleError
=== self
::ILLEGAL_FILENAME
) {
463 $result['filtered'] = $this->mFilteredName
;
465 if ( $this->mTitleError
=== self
::FILETYPE_BADTYPE
) {
466 $result['finalExt'] = $this->mFinalExtension
;
467 if ( count( $this->mBlackListedExtensions
) ) {
468 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
474 $this->mDestName
= $this->getLocalFile()->getName();
480 * Verify the MIME type.
482 * @note Only checks that it is not an evil MIME.
483 * The "does it have the correct file extension given its MIME type?" check is in verifyFile.
484 * @param string $mime Representing the MIME
485 * @return array|bool True if the file is verified, an array otherwise
487 protected function verifyMimeType( $mime ) {
488 $verifyMimeType = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::VerifyMimeType
);
489 if ( $verifyMimeType ) {
490 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
491 $mimeTypeExclusions = MediaWikiServices
::getInstance()->getMainConfig()
492 ->get( MainConfigNames
::MimeTypeExclusions
);
493 if ( self
::checkFileExtension( $mime, $mimeTypeExclusions ) ) {
494 return [ 'filetype-badmime', $mime ];
502 * Verifies that it's ok to include the uploaded file
504 * @return array|true True of the file is verified, array otherwise.
506 protected function verifyFile() {
507 $config = MediaWikiServices
::getInstance()->getMainConfig();
508 $verifyMimeType = $config->get( MainConfigNames
::VerifyMimeType
);
509 $disableUploadScriptChecks = $config->get( MainConfigNames
::DisableUploadScriptChecks
);
510 $status = $this->verifyPartialFile();
511 if ( $status !== true ) {
515 // Calculating props calculates the sha1 which is expensive.
516 // reuse props if we already have them
517 if ( !is_array( $this->mFileProps
) ) {
518 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
519 $this->mFileProps
= $mwProps->getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
521 $mime = $this->mFileProps
['mime'];
523 if ( $verifyMimeType ) {
524 # XXX: Missing extension will be caught by validateName() via getTitle()
525 if ( (string)$this->mFinalExtension
!== '' &&
526 !self
::verifyExtension( $mime, $this->mFinalExtension
)
528 return [ 'filetype-mime-mismatch', $this->mFinalExtension
, $mime ];
532 # check for htmlish code and javascript
533 if ( !$disableUploadScriptChecks ) {
534 if ( $this->mFinalExtension
=== 'svg' ||
$mime === 'image/svg+xml' ) {
535 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, false );
536 if ( $svgStatus !== false ) {
542 $handler = MediaHandler
::getHandler( $mime );
544 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
545 if ( !$handlerStatus->isOK() ) {
546 $errors = $handlerStatus->getErrorsArray();
548 return reset( $errors );
553 $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
554 if ( $error !== true ) {
555 if ( !is_array( $error ) ) {
561 wfDebug( __METHOD__
. ": all clear; passing." );
567 * A verification routine suitable for partial files
569 * Runs the deny list checks, but not any checks that may
570 * assume the entire file is present.
572 * @return array|true True, if the file is valid, else an array with error message key.
573 * @phan-return non-empty-array|true
575 protected function verifyPartialFile() {
576 $config = MediaWikiServices
::getInstance()->getMainConfig();
577 $disableUploadScriptChecks = $config->get( MainConfigNames
::DisableUploadScriptChecks
);
578 # getTitle() sets some internal parameters like $this->mFinalExtension
581 // Calculating props calculates the sha1 which is expensive.
582 // reuse props if we already have them (e.g. During stashed upload)
583 if ( !is_array( $this->mFileProps
) ) {
584 $mwProps = new MWFileProps( MediaWikiServices
::getInstance()->getMimeAnalyzer() );
585 $this->mFileProps
= $mwProps->getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
588 # check MIME type, if desired
589 $mime = $this->mFileProps
['file-mime'];
590 $status = $this->verifyMimeType( $mime );
591 if ( $status !== true ) {
595 # check for htmlish code and javascript
596 if ( !$disableUploadScriptChecks ) {
597 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
598 return [ 'uploadscripted' ];
600 if ( $this->mFinalExtension
=== 'svg' ||
$mime === 'image/svg+xml' ) {
601 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, true );
602 if ( $svgStatus !== false ) {
608 # Scan the uploaded file for viruses
609 $virus = self
::detectVirus( $this->mTempPath
);
611 return [ 'uploadvirus', $virus ];
618 * Callback for ZipDirectoryReader to detect Java class files.
620 * @param array $entry
622 public function zipEntryCallback( $entry ) {
623 $names = [ $entry['name'] ];
625 // If there is a null character, cut off the name at it, because JDK's
626 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
627 // were constructed which had ".class\0" followed by a string chosen to
628 // make the hash collide with the truncated name, that file could be
629 // returned in response to a request for the .class file.
630 $nullPos = strpos( $entry['name'], "\000" );
631 if ( $nullPos !== false ) {
632 $names[] = substr( $entry['name'], 0, $nullPos );
635 // If there is a trailing slash in the file name, we have to strip it,
636 // because that's what ZIP_GetEntry() does.
637 if ( preg_grep( '!\.class/?$!', $names ) ) {
638 $this->mJavaDetected
= true;
643 * Alias for verifyTitlePermissions. The function was originally
644 * 'verifyPermissions', but that suggests it's checking the user, when it's
645 * really checking the title + user combination.
647 * @param Authority $performer to verify the permissions against
648 * @return array|bool An array as returned by getPermissionErrors or true
649 * in case the user has proper permissions.
651 public function verifyPermissions( Authority
$performer ) {
652 return $this->verifyTitlePermissions( $performer );
656 * Check whether the user can edit, upload and create the image. This
657 * checks only against the current title; if it returns errors, it may
658 * very well be that another title will not give errors. Therefore
659 * isAllowed() should be called as well for generic is-user-blocked or
660 * can-user-upload checking.
662 * @param Authority $performer to verify the permissions against
663 * @return array|bool An array as returned by getPermissionErrors or true
664 * in case the user has proper permissions.
666 public function verifyTitlePermissions( Authority
$performer ) {
668 * If the image is protected, non-sysop users won't be able
669 * to modify it by uploading a new revision.
671 $nt = $this->getTitle();
672 if ( $nt === null ) {
676 $status = PermissionStatus
::newEmpty();
677 $performer->authorizeWrite( 'edit', $nt, $status );
678 $performer->authorizeWrite( 'upload', $nt, $status );
679 if ( !$status->isGood() ) {
680 return $status->toLegacyErrorArray();
683 $overwriteError = $this->checkOverwrite( $performer );
684 if ( $overwriteError !== true ) {
685 return [ $overwriteError ];
692 * Check for non fatal problems with the file.
694 * This should not assume that mTempPath is set.
696 * @param User|null $user Accepted since 1.35
698 * @return mixed[] Array of warnings
700 public function checkWarnings( $user = null ) {
701 if ( $user === null ) {
702 // TODO check uses and hard deprecate
703 $user = RequestContext
::getMain()->getUser();
708 $localFile = $this->getLocalFile();
709 $localFile->load( IDBAccessObject
::READ_LATEST
);
710 $filename = $localFile->getName();
711 $hash = $this->getTempFileSha1Base36();
713 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName
);
714 if ( $badFileName !== null ) {
715 $warnings['badfilename'] = $badFileName;
718 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension
);
719 if ( $unwantedFileExtensionDetails !== null ) {
720 $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
723 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize
);
724 if ( $fileSizeWarnings ) {
725 $warnings = array_merge( $warnings, $fileSizeWarnings );
728 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
729 if ( $localFileExistsWarnings ) {
730 $warnings = array_merge( $warnings, $localFileExistsWarnings );
733 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
734 $warnings['was-deleted'] = $filename;
737 // If a file with the same name exists locally then the local file has already been tested
738 // for duplication of content
739 $ignoreLocalDupes = isset( $warnings['exists'] );
740 $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
742 $warnings['duplicate'] = $dupes;
745 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
746 if ( $archivedDupes !== null ) {
747 $warnings['duplicate-archive'] = $archivedDupes;
754 * Convert the warnings array returned by checkWarnings() to something that
755 * can be serialized. File objects will be converted to an associative array
756 * with the following keys:
758 * - fileName: The name of the file
759 * - timestamp: The upload timestamp
761 * @param mixed[] $warnings
764 public static function makeWarningsSerializable( $warnings ) {
765 array_walk_recursive( $warnings, static function ( &$param, $key ) {
766 if ( $param instanceof File
) {
768 'fileName' => $param->getName(),
769 'timestamp' => $param->getTimestamp()
771 } elseif ( is_object( $param ) ) {
772 throw new InvalidArgumentException(
773 'UploadBase::makeWarningsSerializable: ' .
774 'Unexpected object of class ' . get_class( $param ) );
781 * Convert the serialized warnings array created by makeWarningsSerializable()
782 * back to the output of checkWarnings().
784 * @param mixed[] $warnings
787 public static function unserializeWarnings( $warnings ) {
788 foreach ( $warnings as $key => $value ) {
789 if ( is_array( $value ) ) {
790 if ( isset( $value['fileName'] ) && isset( $value['timestamp'] ) ) {
791 $warnings[$key] = MediaWikiServices
::getInstance()->getRepoGroup()->findFile(
793 [ 'time' => $value['timestamp'] ]
796 $warnings[$key] = self
::unserializeWarnings( $value );
804 * Check whether the resulting filename is different from the desired one,
805 * but ignore things like ucfirst() and spaces/underscore things
807 * @param string $filename
808 * @param string $desiredFileName
810 * @return string|null String that was determined to be bad or null if the filename is okay
812 private function checkBadFileName( $filename, $desiredFileName ) {
813 $comparableName = str_replace( ' ', '_', $desiredFileName );
814 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
816 if ( $desiredFileName != $filename && $comparableName != $filename ) {
824 * @param string $fileExtension The file extension to check
826 * @return array|null array with the following keys:
827 * 0 => string The final extension being used
828 * 1 => string[] The extensions that are allowed
829 * 2 => int The number of extensions that are allowed.
831 private function checkUnwantedFileExtensions( $fileExtension ) {
832 $checkFileExtensions = MediaWikiServices
::getInstance()->getMainConfig()
833 ->get( MainConfigNames
::CheckFileExtensions
);
834 $fileExtensions = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::FileExtensions
);
835 if ( $checkFileExtensions ) {
836 $extensions = array_unique( $fileExtensions );
837 if ( !self
::checkFileExtension( $fileExtension, $extensions ) ) {
840 Message
::listParam( $extensions, 'comma' ),
850 * @param int $fileSize
852 * @return array warnings
854 private function checkFileSize( $fileSize ) {
855 $uploadSizeWarning = MediaWikiServices
::getInstance()->getMainConfig()
856 ->get( MainConfigNames
::UploadSizeWarning
);
860 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
861 $warnings['large-file'] = [
862 Message
::sizeParam( $uploadSizeWarning ),
863 Message
::sizeParam( $fileSize ),
867 if ( $fileSize == 0 ) {
868 $warnings['empty-file'] = true;
875 * @param LocalFile $localFile
876 * @param string|false $hash sha1 hash of the file to check
878 * @return array warnings
880 private function checkLocalFileExists( LocalFile
$localFile, $hash ) {
883 $exists = self
::getExistsWarning( $localFile );
884 if ( $exists !== false ) {
885 $warnings['exists'] = $exists;
887 // check if file is an exact duplicate of current file version
888 if ( $hash !== false && $hash === $localFile->getSha1() ) {
889 $warnings['no-change'] = $localFile;
892 // check if file is an exact duplicate of older versions of this file
893 $history = $localFile->getHistory();
894 foreach ( $history as $oldFile ) {
895 if ( $hash === $oldFile->getSha1() ) {
896 $warnings['duplicate-version'][] = $oldFile;
904 private function checkLocalFileWasDeleted( LocalFile
$localFile ) {
905 return $localFile->wasDeleted() && !$localFile->exists();
909 * @param string|false $hash sha1 hash of the file to check
910 * @param bool $ignoreLocalDupes True to ignore local duplicates
912 * @return File[] Duplicate files, if found.
914 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
915 if ( $hash === false ) {
918 $dupes = MediaWikiServices
::getInstance()->getRepoGroup()->findBySha1( $hash );
919 $title = $this->getTitle();
920 foreach ( $dupes as $key => $dupe ) {
922 ( $dupe instanceof LocalFile
) &&
924 $title->equals( $dupe->getTitle() )
926 unset( $dupes[$key] );
934 * @param string|false $hash sha1 hash of the file to check
935 * @param Authority $performer
937 * @return string|null Name of the dupe or empty string if discovered (depending on visibility)
938 * null if the check discovered no dupes.
940 private function checkAgainstArchiveDupes( $hash, Authority
$performer ) {
941 if ( $hash === false ) {
944 $archivedFile = new ArchivedFile( null, 0, '', $hash );
945 if ( $archivedFile->getID() > 0 ) {
946 if ( $archivedFile->userCan( File
::DELETED_FILE
, $performer ) ) {
947 return $archivedFile->getName();
956 * Really perform the upload. Stores the file in the local repo, watches
957 * if necessary and runs the UploadComplete hook.
959 * @param string $comment
960 * @param string|false $pageText
961 * @param bool $watch Whether the file page should be added to user's watchlist.
962 * (This doesn't check $user's permissions.)
964 * @param string[] $tags Change tags to add to the log entry and page revision.
965 * (This doesn't check $user's permissions.)
966 * @param string|null $watchlistExpiry Optional watchlist expiry timestamp in any format
967 * acceptable to wfTimestamp().
968 * @return Status Indicating the whether the upload succeeded.
970 * @since 1.35 Accepts $watchlistExpiry parameter.
972 public function performUpload(
973 $comment, $pageText, $watch, $user, $tags = [], ?
string $watchlistExpiry = null
975 $this->getLocalFile()->load( IDBAccessObject
::READ_LATEST
);
976 $props = $this->mFileProps
;
979 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
981 if ( !is_array( $error ) ) {
984 return Status
::newFatal( ...$error );
987 $status = $this->getLocalFile()->upload(
990 $pageText !== false ?
$pageText : '',
998 if ( $status->isGood() ) {
1000 MediaWikiServices
::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
1002 $this->getLocalFile()->getTitle(),
1006 $this->getHookRunner()->onUploadComplete( $this );
1008 $this->postProcessUpload();
1015 * Perform extra steps after a successful upload.
1017 * @stable to override
1020 public function postProcessUpload() {
1024 * Returns the title of the file to be uploaded. Sets mTitleError in case
1025 * the name was illegal.
1027 * @return Title|null The title of the file or null in case the name was illegal
1029 public function getTitle() {
1030 if ( $this->mTitle
!== false ) {
1031 return $this->mTitle
;
1033 if ( !is_string( $this->mDesiredDestName
) ) {
1034 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
1035 $this->mTitle
= null;
1037 return $this->mTitle
;
1039 /* Assume that if a user specified File:Something.jpg, this is an error
1040 * and that the namespace prefix needs to be stripped of.
1042 $title = Title
::newFromText( $this->mDesiredDestName
);
1043 if ( $title && $title->getNamespace() === NS_FILE
) {
1044 $this->mFilteredName
= $title->getDBkey();
1046 $this->mFilteredName
= $this->mDesiredDestName
;
1049 # oi_archive_name is max 255 bytes, which include a timestamp and an
1050 # exclamation mark, so restrict file name to 240 bytes.
1051 if ( strlen( $this->mFilteredName
) > 240 ) {
1052 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
1053 $this->mTitle
= null;
1055 return $this->mTitle
;
1059 * Chop off any directories in the given filename. Then
1060 * filter out illegal characters, and try to make a legible name
1061 * out of it. We'll strip some silently that Title would die on.
1063 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
1064 /* Normalize to title form before we do any further processing */
1065 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
1066 if ( $nt === null ) {
1067 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
1068 $this->mTitle
= null;
1070 return $this->mTitle
;
1072 $this->mFilteredName
= $nt->getDBkey();
1075 * We'll want to prevent against *any* 'extension', and use
1076 * only the final one for the allow list.
1078 [ $partname, $ext ] = self
::splitExtensions( $this->mFilteredName
);
1080 if ( $ext !== [] ) {
1081 $this->mFinalExtension
= trim( end( $ext ) );
1083 $this->mFinalExtension
= '';
1085 // No extension, try guessing one from the temporary file
1086 // FIXME: Sometimes we mTempPath isn't set yet here, possibly due to an unrealistic
1087 // or incomplete test case in UploadBaseTest (T272328)
1088 if ( $this->mTempPath
!== null ) {
1089 $magic = MediaWikiServices
::getInstance()->getMimeAnalyzer();
1090 $mime = $magic->guessMimeType( $this->mTempPath
);
1091 if ( $mime !== 'unknown/unknown' ) {
1092 # Get a space separated list of extensions
1093 $mimeExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
1094 if ( $mimeExt !== null ) {
1095 # Set the extension to the canonical extension
1096 $this->mFinalExtension
= $mimeExt;
1098 # Fix up the other variables
1099 $this->mFilteredName
.= ".{$this->mFinalExtension}";
1100 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
1101 $ext = [ $this->mFinalExtension
];
1107 // Don't allow users to override the list of prohibited file extensions (check file extension)
1108 $config = MediaWikiServices
::getInstance()->getMainConfig();
1109 $checkFileExtensions = $config->get( MainConfigNames
::CheckFileExtensions
);
1110 $strictFileExtensions = $config->get( MainConfigNames
::StrictFileExtensions
);
1111 $fileExtensions = $config->get( MainConfigNames
::FileExtensions
);
1112 $prohibitedFileExtensions = $config->get( MainConfigNames
::ProhibitedFileExtensions
);
1114 $badList = self
::checkFileExtensionList( $ext, $prohibitedFileExtensions );
1116 if ( $this->mFinalExtension
== '' ) {
1117 $this->mTitleError
= self
::FILETYPE_MISSING
;
1118 $this->mTitle
= null;
1120 return $this->mTitle
;
1124 ( $checkFileExtensions && $strictFileExtensions &&
1125 !self
::checkFileExtension( $this->mFinalExtension
, $fileExtensions ) )
1127 $this->mBlackListedExtensions
= $badList;
1128 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
1129 $this->mTitle
= null;
1131 return $this->mTitle
;
1134 // Windows may be broken with special characters, see T3780
1135 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1136 && !MediaWikiServices
::getInstance()->getRepoGroup()
1137 ->getLocalRepo()->backendSupportsUnicodePaths()
1139 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
1140 $this->mTitle
= null;
1142 return $this->mTitle
;
1145 # If there was more than one file "extension", reassemble the base
1146 # filename to prevent bogus complaints about length
1147 if ( count( $ext ) > 1 ) {
1148 $iterations = count( $ext ) - 1;
1149 for ( $i = 0; $i < $iterations; $i++
) {
1150 $partname .= '.' . $ext[$i];
1154 if ( strlen( $partname ) < 1 ) {
1155 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
1156 $this->mTitle
= null;
1158 return $this->mTitle
;
1161 $this->mTitle
= $nt;
1163 return $this->mTitle
;
1167 * Return the local file and initializes if necessary.
1169 * @stable to override
1170 * @return LocalFile|null
1172 public function getLocalFile() {
1173 if ( $this->mLocalFile
=== null ) {
1174 $nt = $this->getTitle();
1175 $this->mLocalFile
= $nt === null
1177 : MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1180 return $this->mLocalFile
;
1184 * @return UploadStashFile|null
1186 public function getStashFile() {
1187 return $this->mStashFile
;
1191 * Like stashFile(), but respects extensions' wishes to prevent the stashing. verifyUpload() must
1192 * be called before calling this method (unless $isPartial is true).
1194 * Upload stash exceptions are also caught and converted to an error status.
1197 * @stable to override
1199 * @param bool $isPartial Pass `true` if this is a part of a chunked upload (not a complete file).
1200 * @return Status If successful, value is an UploadStashFile instance
1202 public function tryStashFile( User
$user, $isPartial = false ) {
1203 if ( !$isPartial ) {
1204 $error = $this->runUploadStashFileHook( $user );
1206 return Status
::newFatal( ...$error );
1210 $file = $this->doStashFile( $user );
1211 return Status
::newGood( $file );
1212 } catch ( UploadStashException
$e ) {
1213 return Status
::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1219 * @return array|null Error message and parameters, null if there's no error
1221 protected function runUploadStashFileHook( User
$user ) {
1222 $props = $this->mFileProps
;
1224 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1225 if ( $error && !is_array( $error ) ) {
1226 $error = [ $error ];
1232 * Implementation for stashFile() and tryStashFile().
1234 * @stable to override
1235 * @param User|null $user
1236 * @return UploadStashFile Stashed file
1238 protected function doStashFile( ?User
$user = null ) {
1239 $stash = MediaWikiServices
::getInstance()->getRepoGroup()
1240 ->getLocalRepo()->getUploadStash( $user );
1241 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType(), $this->mFileProps
);
1242 $this->mStashFile
= $file;
1248 * If we've modified the upload file, then we need to manually remove it
1249 * on exit to clean up.
1251 public function cleanupTempFile() {
1252 if ( $this->mRemoveTempFile
&& $this->tempFileObj
) {
1253 // Delete when all relevant TempFSFile handles go out of scope
1254 wfDebug( __METHOD__
. ": Marked temporary file '{$this->mTempPath}' for removal" );
1255 $this->tempFileObj
->autocollect();
1260 * @return string|null
1262 public function getTempPath() {
1263 return $this->mTempPath
;
1267 * Split a file into a base name and all dot-delimited 'extensions'
1268 * on the end. Some web server configurations will fall back to
1269 * earlier pseudo-'extensions' to determine type and execute
1270 * scripts, so we need to check them all.
1272 * @param string $filename
1273 * @return array [ string, string[] ]
1275 public static function splitExtensions( $filename ) {
1276 $bits = explode( '.', $filename );
1277 $basename = array_shift( $bits );
1279 return [ $basename, $bits ];
1283 * Perform case-insensitive match against a list of file extensions.
1285 * @param string $ext File extension
1286 * @param array $list
1287 * @return bool Returns true if the extension is in the list.
1289 public static function checkFileExtension( $ext, $list ) {
1290 return in_array( strtolower( $ext ??
'' ), $list, true );
1294 * Perform case-insensitive match against a list of file extensions.
1295 * Returns an array of matching extensions.
1297 * @param string[] $ext File extensions
1298 * @param string[] $list
1301 public static function checkFileExtensionList( $ext, $list ) {
1302 return array_intersect( array_map( 'strtolower', $ext ), $list );
1306 * Checks if the MIME type of the uploaded file matches the file extension.
1308 * @param string $mime The MIME type of the uploaded file
1309 * @param string $extension The filename extension that the file is to be served with
1312 public static function verifyExtension( $mime, $extension ) {
1313 $magic = MediaWikiServices
::getInstance()->getMimeAnalyzer();
1315 if ( !$mime ||
$mime === 'unknown' ||
$mime === 'unknown/unknown' ) {
1316 if ( !$magic->isRecognizableExtension( $extension ) ) {
1317 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
1318 "unrecognized extension '$extension', can't verify" );
1323 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
1324 "recognized extension '$extension', so probably invalid file" );
1328 $match = $magic->isMatchingExtension( $extension, $mime );
1330 if ( $match === null ) {
1331 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1332 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension" );
1337 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file" );
1342 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file" );
1344 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1349 . ": mime type $mime mismatches file extension $extension, rejecting file" );
1355 * Heuristic for detecting files that *could* contain JavaScript instructions or
1356 * things that may look like HTML to a browser and are thus
1357 * potentially harmful. The present implementation will produce false
1358 * positives in some situations.
1360 * @param string|null $file Pathname to the temporary upload file
1361 * @param string $mime The MIME type of the file
1362 * @param string|null $extension The extension of the file
1363 * @return bool True if the file contains something looking like embedded scripts
1365 public static function detectScript( $file, $mime, $extension ) {
1366 # ugly hack: for text files, always look at the entire file.
1367 # For binary field, just check the first K.
1369 if ( str_starts_with( $mime ??
'', 'text/' ) ) {
1370 $chunk = file_get_contents( $file );
1372 $fp = fopen( $file, 'rb' );
1376 $chunk = fread( $fp, 1024 );
1380 $chunk = strtolower( $chunk );
1386 # decode from UTF-16 if needed (could be used for obfuscation).
1387 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
1389 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
1395 if ( $enc !== null ) {
1396 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1399 $chunk = trim( $chunk );
1401 /** @todo FIXME: Convert from UTF-16 if necessary! */
1402 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff" );
1404 # check for HTML doctype
1405 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1409 // Some browsers will interpret obscure xml encodings as UTF-8, while
1410 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1411 if ( $extension === 'svg' ||
str_starts_with( $mime ??
'', 'image/svg' ) ) {
1412 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1417 // Quick check for HTML heuristics in old IE and Safari.
1419 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1420 // don't need them all here as it can cause many false positives.
1422 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1426 '<html', # also in safari
1427 '<script', # also in safari
1430 foreach ( $tags as $tag ) {
1431 if ( strpos( $chunk, $tag ) !== false ) {
1432 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag" );
1439 * look for JavaScript
1442 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1443 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1445 # look for script-types
1446 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1447 wfDebug( __METHOD__
. ": found script types" );
1452 # look for html-style script-urls
1453 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1454 wfDebug( __METHOD__
. ": found html-style script urls" );
1459 # look for css-style script-urls
1460 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1461 wfDebug( __METHOD__
. ": found css-style script urls" );
1466 wfDebug( __METHOD__
. ": no scripts found" );
1472 * Check an allowed list of xml encodings that are known not to be interpreted differently
1473 * by the server's xml parser (expat) and some common browsers.
1475 * @param string $file Pathname to the temporary upload file
1476 * @return bool True if the file contains an encoding that could be misinterpreted
1478 public static function checkXMLEncodingMissmatch( $file ) {
1479 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
1480 // should read the first 1445 bytes. Do 4096 bytes for good measure.
1481 // XML Spec says XML declaration if present must be first thing in file
1483 $contents = file_get_contents( $file, false, null, 0, 4096 );
1484 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1486 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1487 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1488 && !in_array( strtoupper( $encMatch[1] ), self
::SAFE_XML_ENCONDINGS
)
1490 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'" );
1494 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1495 // Start of XML declaration without an end in the first 4096 bytes
1496 // bytes. There shouldn't be a legitimate reason for this to happen.
1497 wfDebug( __METHOD__
. ": Unmatched XML declaration start" );
1500 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1501 // EBCDIC encoded XML
1502 wfDebug( __METHOD__
. ": EBCDIC Encoded XML" );
1507 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1508 // detect the encoding in case it specifies an encoding not allowed in self::SAFE_XML_ENCONDINGS
1509 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1510 foreach ( $attemptEncodings as $encoding ) {
1511 AtEase
::suppressWarnings();
1512 $str = iconv( $encoding, 'UTF-8', $contents );
1513 AtEase
::restoreWarnings();
1514 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1515 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1516 && !in_array( strtoupper( $encMatch[1] ), self
::SAFE_XML_ENCONDINGS
)
1518 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'" );
1522 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1523 // Start of XML declaration without an end in the first 4096 bytes
1524 // bytes. There shouldn't be a legitimate reason for this to happen.
1525 wfDebug( __METHOD__
. ": Unmatched XML declaration start" );
1535 * @param string $filename
1536 * @param bool $partial
1537 * @return bool|array
1539 protected function detectScriptInSvg( $filename, $partial ) {
1540 $this->mSVGNSError
= false;
1541 $check = new XmlTypeCheck(
1543 [ $this, 'checkSvgScriptCallback' ],
1546 'processing_instruction_handler' => [ __CLASS__
, 'checkSvgPICallback' ],
1547 'external_dtd_handler' => [ __CLASS__
, 'checkSvgExternalDTD' ],
1550 if ( $check->wellFormed
!== true ) {
1551 // Invalid xml (T60553)
1552 // But only when non-partial (T67724)
1553 return $partial ?
false : [ 'uploadinvalidxml' ];
1556 if ( $check->filterMatch
) {
1557 if ( $this->mSVGNSError
) {
1558 return [ 'uploadscriptednamespace', $this->mSVGNSError
];
1560 return $check->filterMatchType
;
1567 * Callback to filter SVG Processing Instructions.
1569 * @param string $target Processing instruction name
1570 * @param string $data Processing instruction attribute and value
1571 * @return bool|array
1573 public static function checkSvgPICallback( $target, $data ) {
1574 // Don't allow external stylesheets (T59550)
1575 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1576 return [ 'upload-scripted-pi-callback' ];
1583 * Verify that DTD URLs referenced are only the standard DTDs.
1585 * Browsers seem to ignore external DTDs.
1587 * However, just to be on the safe side, only allow DTDs from the SVG standard.
1589 * @param string $type PUBLIC or SYSTEM
1590 * @param string $publicId The well-known public identifier for the dtd
1591 * @param string $systemId The url for the external dtd
1592 * @return bool|array
1594 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1595 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1596 // allow XHTML anyway.
1597 static $allowedDTDs = [
1598 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1599 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1600 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1601 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1602 // https://phabricator.wikimedia.org/T168856
1603 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1605 if ( $type !== 'PUBLIC'
1606 ||
!in_array( $systemId, $allowedDTDs )
1607 ||
!str_starts_with( $publicId, "-//W3C//" )
1609 return [ 'upload-scripted-dtd' ];
1615 * @todo Replace this with a allow list filter!
1616 * @param string $element
1617 * @param array $attribs
1618 * @param string|null $data
1619 * @return bool|array
1621 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1622 [ $namespace, $strippedElement ] = self
::splitXmlNamespace( $element );
1624 // We specifically don't include:
1625 // http://www.w3.org/1999/xhtml (T62771)
1626 static $validNamespaces = [
1629 'http://creativecommons.org/ns#',
1630 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1631 'http://ns.adobe.com/adobeillustrator/10.0/',
1632 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1633 'http://ns.adobe.com/extensibility/1.0/',
1634 'http://ns.adobe.com/flows/1.0/',
1635 'http://ns.adobe.com/illustrator/1.0/',
1636 'http://ns.adobe.com/imagereplacement/1.0/',
1637 'http://ns.adobe.com/pdf/1.3/',
1638 'http://ns.adobe.com/photoshop/1.0/',
1639 'http://ns.adobe.com/saveforweb/1.0/',
1640 'http://ns.adobe.com/variables/1.0/',
1641 'http://ns.adobe.com/xap/1.0/',
1642 'http://ns.adobe.com/xap/1.0/g/',
1643 'http://ns.adobe.com/xap/1.0/g/img/',
1644 'http://ns.adobe.com/xap/1.0/mm/',
1645 'http://ns.adobe.com/xap/1.0/rights/',
1646 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1647 'http://ns.adobe.com/xap/1.0/stype/font#',
1648 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1649 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1650 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1651 'http://ns.adobe.com/xap/1.0/t/pg/',
1652 'http://purl.org/dc/elements/1.1/',
1653 'http://purl.org/dc/elements/1.1',
1654 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1655 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1656 'http://taptrix.com/inkpad/svg_extensions',
1657 'http://web.resource.org/cc/',
1658 'http://www.freesoftware.fsf.org/bkchem/cdml',
1659 'http://www.inkscape.org/namespaces/inkscape',
1660 'http://www.opengis.net/gml',
1661 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1662 'http://www.w3.org/2000/svg',
1663 'http://www.w3.org/tr/rec-rdf-syntax/',
1664 'http://www.w3.org/2000/01/rdf-schema#',
1665 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1668 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1669 // This is nasty but harmless. (T144827)
1670 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1672 if ( !( $isBuggyInkscape ||
in_array( $namespace, $validNamespaces ) ) ) {
1673 wfDebug( __METHOD__
. ": Non-svg namespace '$namespace' in uploaded file." );
1674 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1675 $this->mSVGNSError
= $namespace;
1680 // check for elements that can contain javascript
1681 if ( $strippedElement === 'script' ) {
1682 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file." );
1684 return [ 'uploaded-script-svg', $strippedElement ];
1687 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1688 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1689 if ( $strippedElement === 'handler' ) {
1690 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file." );
1692 return [ 'uploaded-script-svg', $strippedElement ];
1695 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1696 if ( $strippedElement === 'stylesheet' ) {
1697 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file." );
1699 return [ 'uploaded-script-svg', $strippedElement ];
1702 // Block iframes, in case they pass the namespace check
1703 if ( $strippedElement === 'iframe' ) {
1704 wfDebug( __METHOD__
. ": iframe in uploaded file." );
1706 return [ 'uploaded-script-svg', $strippedElement ];
1709 // Check <style> css
1710 if ( $strippedElement === 'style'
1711 && self
::checkCssFragment( Sanitizer
::normalizeCss( $data ) )
1713 wfDebug( __METHOD__
. ": hostile css in style element." );
1715 return [ 'uploaded-hostile-svg' ];
1718 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1719 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1721 foreach ( $attribs as $attrib => $value ) {
1722 // If attributeNamespace is '', it is relative to its element's namespace
1723 [ $attributeNamespace, $stripped ] = self
::splitXmlNamespace( $attrib );
1724 $value = strtolower( $value );
1727 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1728 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1729 $attributeNamespace === ''
1730 ) && str_starts_with( $stripped, 'on' )
1733 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1735 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1738 // Do not allow relative links, or unsafe url schemas.
1739 // For <a> tags, only data:, http: and https: and same-document
1740 // fragment links are allowed.
1741 // For all other tags, only 'data:' and fragments (#) are allowed.
1743 $stripped === 'href'
1745 && !str_starts_with( $value, 'data:' )
1746 && !str_starts_with( $value, '#' )
1747 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1749 wfDebug( __METHOD__
. ": Found href attribute <$strippedElement "
1750 . "'$attrib'='$value' in uploaded file." );
1752 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1755 // Only allow 'data:\' targets that should be safe.
1756 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1757 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1758 // RFC2397 parameters.
1759 // This is only slightly slower than (;[\w;]+)*.
1760 // phpcs:ignore Generic.Files.LineLength
1761 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1763 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1764 wfDebug( __METHOD__
. ": Found href to allow listed data: uri "
1765 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1766 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1770 // Change href with animate from (http://html5sec.org/#137).
1771 if ( $stripped === 'attributename'
1772 && $strippedElement === 'animate'
1773 && $this->stripXmlNamespace( $value ) === 'href'
1775 wfDebug( __METHOD__
. ": Found animate that might be changing href using from "
1776 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1778 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1781 // Use set/animate to add event-handler attribute to parent.
1782 if ( ( $strippedElement === 'set' ||
$strippedElement === 'animate' )
1783 && $stripped === 'attributename'
1784 && str_starts_with( $value, 'on' )
1786 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with "
1787 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1789 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1792 // use set to add href attribute to parent element.
1793 if ( $strippedElement === 'set'
1794 && $stripped === 'attributename'
1795 && str_contains( $value, 'href' )
1797 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file." );
1799 return [ 'uploaded-setting-href-svg' ];
1802 // use set to add a remote / data / script target to an element.
1803 if ( $strippedElement === 'set'
1804 && $stripped === 'to'
1805 && preg_match( '!(http|https|data|script):!im', $value )
1807 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file." );
1809 return [ 'uploaded-wrong-setting-svg', $value ];
1812 // use handler attribute with remote / data / script.
1813 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1814 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script "
1815 . "'$attrib'='$value' in uploaded file." );
1817 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1820 // use CSS styles to bring in remote code.
1821 if ( $stripped === 'style'
1822 && self
::checkCssFragment( Sanitizer
::normalizeCss( $value ) )
1824 wfDebug( __METHOD__
. ": Found svg setting a style with "
1825 . "remote url '$attrib'='$value' in uploaded file." );
1826 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1829 // Several attributes can include css, css character escaping isn't allowed.
1830 if ( in_array( $stripped, $cssAttrs, true )
1831 && self
::checkCssFragment( $value )
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 ];
1838 // image filters can pull in url, which could be svg that executes scripts.
1839 // Only allow url( "#foo" ).
1840 // Do not allow url( http://example.com )
1841 if ( $strippedElement === 'image'
1842 && $stripped === 'filter'
1843 && preg_match( '!url\s*\(\s*["\']?[^#]!im', $value )
1845 wfDebug( __METHOD__
. ": Found image filter with url: "
1846 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1848 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1852 return false; // No scripts detected
1856 * Check a block of CSS or CSS fragment for anything that looks like
1857 * it is bringing in remote code.
1858 * @param string $value a string of CSS
1859 * @return bool true if the CSS contains an illegal string, false if otherwise
1861 private static function checkCssFragment( $value ) {
1862 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1863 if ( stripos( $value, '@import' ) !== false ) {
1867 # We allow @font-face to embed fonts with data: urls, so we snip the string
1868 # 'url' out so that this case won't match when we check for urls below
1869 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1870 $value = preg_replace( $pattern, '$1$2', $value );
1872 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1873 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1874 # Expression and -o-link don't seem to work either, but filtering them here in case.
1875 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1876 # but not local ones such as url("#..., url('#..., url(#....
1877 if ( preg_match( '!expression
1879 | -o-link-source\s*:
1880 | -o-replace\s*:!imx', $value ) ) {
1884 if ( preg_match_all(
1885 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1890 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1891 foreach ( $matches[1] as $match ) {
1892 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1898 return (bool)preg_match( '/[\000-\010\013\016-\037\177]/', $value );
1902 * Divide the element name passed by the XML parser to the callback into URI and prefix.
1903 * @param string $element
1904 * @return array Containing the namespace URI and prefix
1906 private static function splitXmlNamespace( $element ) {
1907 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1908 $parts = explode( ':', strtolower( $element ) );
1909 $name = array_pop( $parts );
1910 $ns = implode( ':', $parts );
1912 return [ $ns, $name ];
1916 * @param string $element
1919 private function stripXmlNamespace( $element ) {
1920 // 'http://www.w3.org/2000/svg:script' -> 'script'
1921 return self
::splitXmlNamespace( $element )[1];
1925 * Generic wrapper function for a virus scanner program.
1926 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1927 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1929 * @param string $file Pathname to the temporary upload file
1930 * @return bool|null|string False if not virus is found, null if the scan fails or is disabled,
1931 * or a string containing feedback from the virus scanner if a virus was found.
1932 * If textual feedback is missing but a virus was found, this function returns true.
1934 public static function detectVirus( $file ) {
1936 $mainConfig = MediaWikiServices
::getInstance()->getMainConfig();
1937 $antivirus = $mainConfig->get( MainConfigNames
::Antivirus
);
1938 $antivirusSetup = $mainConfig->get( MainConfigNames
::AntivirusSetup
);
1939 $antivirusRequired = $mainConfig->get( MainConfigNames
::AntivirusRequired
);
1940 if ( !$antivirus ) {
1941 wfDebug( __METHOD__
. ": virus scanner disabled" );
1946 if ( !$antivirusSetup[$antivirus] ) {
1947 wfDebug( __METHOD__
. ": unknown virus scanner: {$antivirus}" );
1948 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1949 [ 'virus-badscanner', $antivirus ] );
1951 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1954 # look up scanner configuration
1955 $command = $antivirusSetup[$antivirus]['command'];
1956 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1957 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ??
null;
1959 if ( !str_contains( $command, "%f" ) ) {
1960 # simple pattern: append file to scan
1961 $command .= " " . Shell
::escape( $file );
1963 # complex pattern: replace "%f" with file to scan
1964 $command = str_replace( "%f", Shell
::escape( $file ), $command );
1967 wfDebug( __METHOD__
. ": running virus scan: $command " );
1969 # execute virus scanner
1972 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1973 # that does not seem to be worth the pain.
1974 # Ask me (Duesentrieb) about it if it's ever needed.
1975 $output = wfShellExecWithStderr( $command, $exitCode );
1977 # map exit code to AV_xxx constants.
1978 $mappedCode = $exitCode;
1979 if ( $exitCodeMap ) {
1980 if ( isset( $exitCodeMap[$exitCode] ) ) {
1981 $mappedCode = $exitCodeMap[$exitCode];
1982 } elseif ( isset( $exitCodeMap["*"] ) ) {
1983 $mappedCode = $exitCodeMap["*"];
1987 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1988 # so we need the strict equalities === and thus can't use a switch here
1989 if ( $mappedCode === AV_SCAN_FAILED
) {
1990 # scan failed (code was mapped to false by $exitCodeMap)
1991 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode)." );
1993 $output = $antivirusRequired
1994 ?
wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1996 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1997 # scan failed because filetype is unknown (probably immune)
1998 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode)." );
2000 } elseif ( $mappedCode === AV_NO_VIRUS
) {
2002 wfDebug( __METHOD__
. ": file passed virus scan." );
2005 $output = trim( $output );
2008 $output = true; # if there's no output, return true
2009 } elseif ( $msgPattern ) {
2011 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
2012 $output = $groups[1];
2016 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output" );
2023 * Check if there's a file overwrite conflict and, if so, if restrictions
2024 * forbid this user from performing the upload.
2026 * @param Authority $performer
2028 * @return bool|array
2030 private function checkOverwrite( Authority
$performer ) {
2031 // First check whether the local file can be overwritten
2032 $file = $this->getLocalFile();
2033 $file->load( IDBAccessObject
::READ_LATEST
);
2034 if ( $file->exists() ) {
2035 if ( !self
::userCanReUpload( $performer, $file ) ) {
2036 return [ 'fileexists-forbidden', $file->getName() ];
2042 $services = MediaWikiServices
::getInstance();
2044 /* Check shared conflicts: if the local file does not exist, but
2045 * RepoGroup::findFile finds a file, it exists in a shared repository.
2047 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2048 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
2049 return [ 'fileexists-shared-forbidden', $file->getName() ];
2056 * Check if a user is the last uploader
2058 * @param Authority $performer
2062 public static function userCanReUpload( Authority
$performer, File
$img ) {
2063 if ( $performer->isAllowed( 'reupload' ) ) {
2064 return true; // non-conditional
2067 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2071 if ( !( $img instanceof LocalFile
) ) {
2075 return $performer->getUser()->equals( $img->getUploader( File
::RAW
) );
2079 * Helper function that does various existence checks for a file.
2080 * The following checks are performed:
2081 * - If the file exists
2082 * - If an article with the same name as the file exists
2083 * - If a file exists with normalized extension
2084 * - If the file looks like a thumbnail and the original exists
2086 * @param File $file The File object to check
2087 * @return array|false False if the file does not exist, else an array
2089 public static function getExistsWarning( $file ) {
2090 if ( $file->exists() ) {
2091 return [ 'warning' => 'exists', 'file' => $file ];
2094 if ( $file->getTitle()->getArticleID() ) {
2095 return [ 'warning' => 'page-exists', 'file' => $file ];
2098 $n = strrpos( $file->getName(), '.' );
2100 $partname = substr( $file->getName(), 0, $n );
2101 $extension = substr( $file->getName(), $n +
1 );
2103 $partname = $file->getName();
2106 $normalizedExtension = File
::normalizeExtension( $extension );
2107 $localRepo = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo();
2109 if ( $normalizedExtension != $extension ) {
2110 // We're not using the normalized form of the extension.
2111 // Normal form is lowercase, using most common of alternate
2112 // extensions (e.g. 'jpg' rather than 'JPEG').
2114 // Check for another file using the normalized form...
2115 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
2116 $file_lc = $localRepo->newFile( $nt_lc );
2118 if ( $file_lc->exists() ) {
2120 'warning' => 'exists-normalized',
2122 'normalizedFile' => $file_lc
2127 // Check for files with the same name but a different extension
2128 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2129 if ( count( $similarFiles ) ) {
2131 'warning' => 'exists-normalized',
2133 'normalizedFile' => $similarFiles[0],
2137 if ( self
::isThumbName( $file->getName() ) ) {
2138 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2139 $nt_thb = Title
::newFromText(
2140 substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension,
2143 $file_thb = $localRepo->newFile( $nt_thb );
2144 if ( $file_thb->exists() ) {
2146 'warning' => 'thumb',
2148 'thumbFile' => $file_thb
2152 // The file does not exist, but we just don't like the name
2154 'warning' => 'thumb-name',
2156 'thumbFile' => $file_thb
2160 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
2161 if ( str_starts_with( $partname, $prefix ) ) {
2163 'warning' => 'bad-prefix',
2174 * Helper function that checks whether the filename looks like a thumbnail
2175 * @param string $filename
2178 public static function isThumbName( $filename ) {
2179 $n = strrpos( $filename, '.' );
2180 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
2183 substr( $partname, 3, 3 ) === 'px-' ||
2184 substr( $partname, 2, 3 ) === 'px-'
2185 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2189 * Get a list of disallowed filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
2191 * @return string[] List of prefixes
2193 public static function getFilenamePrefixBlacklist() {
2195 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2196 if ( !$message->isDisabled() ) {
2197 $lines = explode( "\n", $message->plain() );
2198 foreach ( $lines as $line ) {
2199 // Remove comment lines
2200 $comment = substr( trim( $line ), 0, 1 );
2201 if ( $comment === '#' ||
$comment == '' ) {
2204 // Remove additional comments after a prefix
2205 $comment = strpos( $line, '#' );
2206 if ( $comment > 0 ) {
2207 $line = substr( $line, 0, $comment - 1 );
2209 $list[] = trim( $line );
2217 * Gets image info about the file just uploaded.
2219 * @deprecated since 1.42, subclasses of ApiUpload can use
2220 * ApiUpload::getUploadImageInfo() instead.
2222 * @param ?ApiResult $result unused since 1.42
2223 * @return array Image info
2225 public function getImageInfo( $result = null ) {
2226 $apiUpload = ApiUpload
::getDummyInstance();
2227 return $apiUpload->getUploadImageInfo( $this );
2231 * @param array $error
2234 public function convertVerifyErrorToStatus( $error ) {
2235 $code = $error['status'];
2236 unset( $code['status'] );
2238 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
2242 * Get MediaWiki's maximum uploaded file size for a given type of upload, based on
2245 * @param null|string $forType
2248 public static function getMaxUploadSize( $forType = null ) {
2249 $maxUploadSize = MediaWikiServices
::getInstance()->getMainConfig()->get( MainConfigNames
::MaxUploadSize
);
2251 if ( is_array( $maxUploadSize ) ) {
2252 return $maxUploadSize[$forType] ??
$maxUploadSize['*'];
2254 return intval( $maxUploadSize );
2258 * Get the PHP maximum uploaded file size, based on ini settings. If there is no limit or the
2259 * limit can't be guessed, return a very large number (PHP_INT_MAX) instead.
2264 public static function getMaxPhpUploadSize() {
2265 $phpMaxFileSize = wfShorthandToInteger(
2266 ini_get( 'upload_max_filesize' ),
2269 $phpMaxPostSize = wfShorthandToInteger(
2270 ini_get( 'post_max_size' ),
2273 return min( $phpMaxFileSize, $phpMaxPostSize );
2277 * Get the current status of a chunked upload (used for polling).
2279 * This should only be called during POST requests since we
2280 * fetch from dc-local MainStash, and from a GET request we can't
2281 * know that the value is available or up-to-date.
2283 * @param UserIdentity $user
2284 * @param string $statusKey
2285 * @return mixed[]|false
2287 public static function getSessionStatus( UserIdentity
$user, $statusKey ) {
2288 $store = self
::getUploadSessionStore();
2289 $key = self
::getUploadSessionKey( $store, $user, $statusKey );
2291 return $store->get( $key );
2295 * Set the current status of a chunked upload (used for polling).
2297 * The value will be set in cache for 1 day.
2299 * This should only be called during POST requests.
2301 * @param UserIdentity $user
2302 * @param string $statusKey
2303 * @param array|false $value
2306 public static function setSessionStatus( UserIdentity
$user, $statusKey, $value ) {
2307 $store = self
::getUploadSessionStore();
2308 $key = self
::getUploadSessionKey( $store, $user, $statusKey );
2309 $logger = LoggerFactory
::getInstance( 'upload' );
2311 if ( is_array( $value ) && ( $value['result'] ??
'' ) === 'Failure' ) {
2312 $logger->info( 'Upload session {key} for {user} set to failure {status} at {stage}',
2314 'result' => $value['result'] ??
'',
2315 'stage' => $value['stage'] ??
'unknown',
2316 'user' => $user->getName(),
2317 'status' => (string)( $value['status'] ??
'-' ),
2318 'filekey' => $value['filekey'] ??
'',
2322 } elseif ( is_array( $value ) ) {
2323 $logger->debug( 'Upload session {key} for {user} changed {status} at {stage}',
2325 'result' => $value['result'] ??
'',
2326 'stage' => $value['stage'] ??
'unknown',
2327 'user' => $user->getName(),
2328 'status' => (string)( $value['status'] ??
'-' ),
2329 'filekey' => $value['filekey'] ??
'',
2334 $logger->debug( "Upload session {key} deleted for {user}",
2337 'key' => $statusKey,
2338 'user' => $user->getName()
2343 if ( $value === false ) {
2344 $store->delete( $key );
2346 $store->set( $key, $value, $store::TTL_DAY
);
2351 * @param BagOStuff $store
2352 * @param UserIdentity $user
2353 * @param string $statusKey
2356 private static function getUploadSessionKey( BagOStuff
$store, UserIdentity
$user, $statusKey ) {
2357 return $store->makeKey(
2359 $user->isRegistered() ?
$user->getId() : md5( $user->getName() ),
2367 private static function getUploadSessionStore() {
2368 return MediaWikiServices
::getInstance()->getMainObjectStash();