MediaWiki master
UploadBase.php
Go to the documentation of this file.
1<?php
32use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
46use Wikimedia\AtEase\AtEase;
53
70abstract class UploadBase {
71 use ProtectedHookAccessorTrait;
72
74 protected $mTempPath;
76 protected $tempFileObj;
80 protected $mDestName;
84 protected $mSourceType;
86 protected $mTitle = false;
88 protected $mTitleError = 0;
90 protected $mFilteredName;
94 protected $mLocalFile;
96 protected $mStashFile;
98 protected $mFileSize;
100 protected $mFileProps;
104 protected $mJavaDetected;
106 protected $mSVGNSError;
107
108 private const SAFE_XML_ENCODINGS = [
109 'UTF-8',
110 'US-ASCII',
111 'ISO-8859-1',
112 'ISO-8859-2',
113 'UTF-16',
114 'UTF-32',
115 'WINDOWS-1250',
116 'WINDOWS-1251',
117 'WINDOWS-1252',
118 'WINDOWS-1253',
119 'WINDOWS-1254',
120 'WINDOWS-1255',
121 'WINDOWS-1256',
122 'WINDOWS-1257',
123 'WINDOWS-1258',
124 ];
125
126 public const SUCCESS = 0;
127 public const OK = 0;
128 public const EMPTY_FILE = 3;
129 public const MIN_LENGTH_PARTNAME = 4;
130 public const ILLEGAL_FILENAME = 5;
131 public const FILETYPE_MISSING = 8;
132 public const FILETYPE_BADTYPE = 9;
133 public const VERIFICATION_ERROR = 10;
134 public const HOOK_ABORTED = 11;
135 public const FILE_TOO_LARGE = 12;
136 public const WINDOWS_NONASCII_FILENAME = 13;
137 public const FILENAME_TOO_LONG = 14;
138
139 private const CODE_TO_STATUS = [
140 self::EMPTY_FILE => 'empty-file',
141 self::FILE_TOO_LARGE => 'file-too-large',
142 self::FILETYPE_MISSING => 'filetype-missing',
143 self::FILETYPE_BADTYPE => 'filetype-banned',
144 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
145 self::ILLEGAL_FILENAME => 'illegal-filename',
146 self::VERIFICATION_ERROR => 'verification-error',
147 self::HOOK_ABORTED => 'hookaborted',
148 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
149 self::FILENAME_TOO_LONG => 'filename-toolong',
150 ];
151
156 public function getVerificationErrorCode( $error ) {
157 return self::CODE_TO_STATUS[$error] ?? 'unknown-error';
158 }
159
166 public static function isEnabled() {
167 $enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
168
169 return $enableUploads && wfIniGetBool( 'file_uploads' );
170 }
171
180 public static function isAllowed( Authority $performer ) {
181 foreach ( [ 'upload', 'edit' ] as $permission ) {
182 if ( !$performer->isAllowed( $permission ) ) {
183 return $permission;
184 }
185 }
186
187 return true;
188 }
189
199 public static function isThrottled( $user ) {
200 wfDeprecated( __METHOD__, '1.41' );
201 return $user->pingLimiter( 'upload' );
202 }
203
205 private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
206
214 public static function createFromRequest( &$request, $type = null ) {
215 $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
216
217 if ( !$type ) {
218 return null;
219 }
220
221 // Get the upload class
222 $type = ucfirst( $type );
223
224 // Give hooks the chance to handle this request
226 $className = null;
227 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
228 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
229 ->onUploadCreateFromRequest( $type, $className );
230 if ( $className === null ) {
231 $className = 'UploadFrom' . $type;
232 wfDebug( __METHOD__ . ": class name: $className" );
233 if ( !in_array( $type, self::$uploadHandlers ) ) {
234 return null;
235 }
236 }
237
238 if ( !$className::isEnabled() || !$className::isValidRequest( $request ) ) {
239 return null;
240 }
241
243 $handler = new $className;
244
245 $handler->initializeFromRequest( $request );
246
247 return $handler;
248 }
249
255 public static function isValidRequest( $request ) {
256 return false;
257 }
258
263 public function getDesiredDestName() {
264 return $this->mDesiredDestName;
265 }
266
270 public function __construct() {
271 }
272
280 public function getSourceType() {
281 return null;
282 }
283
290 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
291 $this->mDesiredDestName = $name;
292 if ( FileBackend::isStoragePath( $tempPath ) ) {
293 throw new InvalidArgumentException( __METHOD__ . " given storage path `$tempPath`." );
294 }
295
296 $this->setTempFile( $tempPath, $fileSize );
297 $this->mRemoveTempFile = $removeTempFile;
298 }
299
305 abstract public function initializeFromRequest( &$request );
306
311 protected function setTempFile( $tempPath, $fileSize = null ) {
312 $this->mTempPath = $tempPath ?? '';
313 $this->mFileSize = $fileSize ?: null;
314 $this->mFileProps = null;
315 if ( $this->mTempPath !== '' && file_exists( $this->mTempPath ) ) {
316 $this->tempFileObj = new TempFSFile( $this->mTempPath );
317 if ( !$fileSize ) {
318 $this->mFileSize = filesize( $this->mTempPath );
319 }
320 } else {
321 $this->tempFileObj = null;
322 }
323 }
324
330 public function fetchFile() {
331 return Status::newGood();
332 }
333
339 public function canFetchFile() {
340 return Status::newGood();
341 }
342
347 public function isEmptyFile() {
348 return !$this->mFileSize;
349 }
350
355 public function getFileSize() {
356 return $this->mFileSize;
357 }
358
364 public function getTempFileSha1Base36() {
365 // Use cached version if we already have it.
366 if ( $this->mFileProps && is_string( $this->mFileProps['sha1'] ) ) {
367 return $this->mFileProps['sha1'];
368 }
369 return FSFile::getSha1Base36FromPath( $this->mTempPath );
370 }
371
376 public function getRealPath( $srcPath ) {
377 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
378 if ( FileRepo::isVirtualUrl( $srcPath ) ) {
382 $tmpFile = $repo->getLocalCopy( $srcPath );
383 if ( $tmpFile ) {
384 $tmpFile->bind( $this ); // keep alive with $this
385 }
386 $path = $tmpFile ? $tmpFile->getPath() : false;
387 } else {
388 $path = $srcPath;
389 }
390
391 return $path;
392 }
393
411 public function verifyUpload() {
415 if ( $this->isEmptyFile() ) {
416 return [ 'status' => self::EMPTY_FILE ];
417 }
418
422 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
423 if ( $this->mFileSize > $maxSize ) {
424 return [
425 'status' => self::FILE_TOO_LARGE,
426 'max' => $maxSize,
427 ];
428 }
429
435 $verification = $this->verifyFile();
436 if ( $verification !== true ) {
437 return [
438 'status' => self::VERIFICATION_ERROR,
439 'details' => $verification
440 ];
441 }
442
446 $result = $this->validateName();
447 if ( $result !== true ) {
448 return $result;
449 }
450
451 return [ 'status' => self::OK ];
452 }
453
460 public function validateName() {
461 $nt = $this->getTitle();
462 if ( $nt === null ) {
463 $result = [ 'status' => $this->mTitleError ];
464 if ( $this->mTitleError === self::ILLEGAL_FILENAME ) {
465 $result['filtered'] = $this->mFilteredName;
466 }
467 if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
468 $result['finalExt'] = $this->mFinalExtension;
469 if ( count( $this->mBlackListedExtensions ) ) {
470 $result['blacklistedExt'] = $this->mBlackListedExtensions;
471 }
472 }
473
474 return $result;
475 }
476 $this->mDestName = $this->getLocalFile()->getName();
477
478 return true;
479 }
480
489 protected function verifyMimeType( $mime ) {
490 $verifyMimeType = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeType );
491 if ( $verifyMimeType ) {
492 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
493 $mimeTypeExclusions = MediaWikiServices::getInstance()->getMainConfig()
494 ->get( MainConfigNames::MimeTypeExclusions );
495 if ( self::checkFileExtension( $mime, $mimeTypeExclusions ) ) {
496 return [ 'filetype-badmime', $mime ];
497 }
498 }
499
500 return true;
501 }
502
508 protected function verifyFile() {
509 $config = MediaWikiServices::getInstance()->getMainConfig();
510 $verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
511 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
512 $status = $this->verifyPartialFile();
513 if ( $status !== true ) {
514 return $status;
515 }
516
517 // Calculating props calculates the sha1 which is expensive.
518 // reuse props if we already have them
519 if ( !is_array( $this->mFileProps ) ) {
520 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
521 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
522 }
523 $mime = $this->mFileProps['mime'];
524
525 if ( $verifyMimeType ) {
526 # XXX: Missing extension will be caught by validateName() via getTitle()
527 if ( (string)$this->mFinalExtension !== '' &&
528 !self::verifyExtension( $mime, $this->mFinalExtension )
529 ) {
530 return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
531 }
532 }
533
534 # check for htmlish code and javascript
535 if ( !$disableUploadScriptChecks ) {
536 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
537 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
538 if ( $svgStatus !== false ) {
539 return $svgStatus;
540 }
541 }
542 }
543
544 $handler = MediaHandler::getHandler( $mime );
545 if ( $handler ) {
546 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
547 if ( !$handlerStatus->isOK() ) {
548 $errors = $handlerStatus->getErrorsArray();
549
550 return reset( $errors );
551 }
552 }
553
554 $error = true;
555 $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
556 if ( $error !== true ) {
557 if ( !is_array( $error ) ) {
558 $error = [ $error ];
559 }
560 return $error;
561 }
562
563 wfDebug( __METHOD__ . ": all clear; passing." );
564
565 return true;
566 }
567
577 protected function verifyPartialFile() {
578 $config = MediaWikiServices::getInstance()->getMainConfig();
579 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
580 # getTitle() sets some internal parameters like $this->mFinalExtension
581 $this->getTitle();
582
583 // Calculating props calculates the sha1 which is expensive.
584 // reuse props if we already have them (e.g. During stashed upload)
585 if ( !is_array( $this->mFileProps ) ) {
586 $mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
587 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
588 }
589
590 # check MIME type, if desired
591 $mime = $this->mFileProps['file-mime'];
592 $status = $this->verifyMimeType( $mime );
593 if ( $status !== true ) {
594 return $status;
595 }
596
597 # check for htmlish code and javascript
598 if ( !$disableUploadScriptChecks ) {
599 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
600 return [ 'uploadscripted' ];
601 }
602 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
603 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
604 if ( $svgStatus !== false ) {
605 return $svgStatus;
606 }
607 }
608 }
609
610 # Scan the uploaded file for viruses
611 $virus = self::detectVirus( $this->mTempPath );
612 if ( $virus ) {
613 return [ 'uploadvirus', $virus ];
614 }
615
616 return true;
617 }
618
624 public function zipEntryCallback( $entry ) {
625 $names = [ $entry['name'] ];
626
627 // If there is a null character, cut off the name at it, because JDK's
628 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
629 // were constructed which had ".class\0" followed by a string chosen to
630 // make the hash collide with the truncated name, that file could be
631 // returned in response to a request for the .class file.
632 $nullPos = strpos( $entry['name'], "\000" );
633 if ( $nullPos !== false ) {
634 $names[] = substr( $entry['name'], 0, $nullPos );
635 }
636
637 // If there is a trailing slash in the file name, we have to strip it,
638 // because that's what ZIP_GetEntry() does.
639 if ( preg_grep( '!\.class/?$!', $names ) ) {
640 $this->mJavaDetected = true;
641 }
642 }
643
653 public function verifyPermissions( Authority $performer ) {
654 return $this->verifyTitlePermissions( $performer );
655 }
656
668 public function verifyTitlePermissions( Authority $performer ) {
673 $nt = $this->getTitle();
674 if ( $nt === null ) {
675 return true;
676 }
677
678 $status = PermissionStatus::newEmpty();
679 $performer->authorizeWrite( 'edit', $nt, $status );
680 $performer->authorizeWrite( 'upload', $nt, $status );
681 if ( !$status->isGood() ) {
682 return $status->toLegacyErrorArray();
683 }
684
685 $overwriteError = $this->checkOverwrite( $performer );
686 if ( $overwriteError !== true ) {
687 return [ $overwriteError ];
688 }
689
690 return true;
691 }
692
702 public function checkWarnings( $user = null ) {
703 if ( $user === null ) {
704 // TODO check uses and hard deprecate
705 $user = RequestContext::getMain()->getUser();
706 }
707
708 $warnings = [];
709
710 $localFile = $this->getLocalFile();
711 $localFile->load( IDBAccessObject::READ_LATEST );
712 $filename = $localFile->getName();
713 $hash = $this->getTempFileSha1Base36();
714
715 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
716 if ( $badFileName !== null ) {
717 $warnings['badfilename'] = $badFileName;
718 }
719
720 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension );
721 if ( $unwantedFileExtensionDetails !== null ) {
722 $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
723 }
724
725 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
726 if ( $fileSizeWarnings ) {
727 $warnings = array_merge( $warnings, $fileSizeWarnings );
728 }
729
730 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
731 if ( $localFileExistsWarnings ) {
732 $warnings = array_merge( $warnings, $localFileExistsWarnings );
733 }
734
735 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
736 $warnings['was-deleted'] = $filename;
737 }
738
739 // If a file with the same name exists locally then the local file has already been tested
740 // for duplication of content
741 $ignoreLocalDupes = isset( $warnings['exists'] );
742 $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
743 if ( $dupes ) {
744 $warnings['duplicate'] = $dupes;
745 }
746
747 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
748 if ( $archivedDupes !== null ) {
749 $warnings['duplicate-archive'] = $archivedDupes;
750 }
751
752 return $warnings;
753 }
754
766 public static function makeWarningsSerializable( $warnings ) {
767 array_walk_recursive( $warnings, static function ( &$param, $key ) {
768 if ( $param instanceof File ) {
769 $param = [
770 'fileName' => $param->getName(),
771 'timestamp' => $param->getTimestamp()
772 ];
773 } elseif ( is_object( $param ) ) {
774 throw new InvalidArgumentException(
775 'UploadBase::makeWarningsSerializable: ' .
776 'Unexpected object of class ' . get_class( $param ) );
777 }
778 } );
779 return $warnings;
780 }
781
789 public static function unserializeWarnings( $warnings ) {
790 foreach ( $warnings as $key => $value ) {
791 if ( is_array( $value ) ) {
792 if ( isset( $value['fileName'] ) && isset( $value['timestamp'] ) ) {
793 $warnings[$key] = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
794 $value['fileName'],
795 [ 'time' => $value['timestamp'] ]
796 );
797 } else {
798 $warnings[$key] = self::unserializeWarnings( $value );
799 }
800 }
801 }
802 return $warnings;
803 }
804
814 private function checkBadFileName( $filename, $desiredFileName ) {
815 $comparableName = str_replace( ' ', '_', $desiredFileName );
816 $comparableName = Title::capitalize( $comparableName, NS_FILE );
817
818 if ( $desiredFileName != $filename && $comparableName != $filename ) {
819 return $filename;
820 }
821
822 return null;
823 }
824
833 private function checkUnwantedFileExtensions( $fileExtension ) {
834 $checkFileExtensions = MediaWikiServices::getInstance()->getMainConfig()
835 ->get( MainConfigNames::CheckFileExtensions );
836 $fileExtensions = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::FileExtensions );
837 if ( $checkFileExtensions ) {
838 $extensions = array_unique( $fileExtensions );
839 if ( !self::checkFileExtension( $fileExtension, $extensions ) ) {
840 return [
841 $fileExtension,
842 Message::listParam( $extensions, 'comma' ),
843 count( $extensions )
844 ];
845 }
846 }
847
848 return null;
849 }
850
856 private function checkFileSize( $fileSize ) {
857 $uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
858 ->get( MainConfigNames::UploadSizeWarning );
859
860 $warnings = [];
861
862 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
863 $warnings['large-file'] = [
864 Message::sizeParam( $uploadSizeWarning ),
865 Message::sizeParam( $fileSize ),
866 ];
867 }
868
869 if ( $fileSize == 0 ) {
870 $warnings['empty-file'] = true;
871 }
872
873 return $warnings;
874 }
875
882 private function checkLocalFileExists( LocalFile $localFile, $hash ) {
883 $warnings = [];
884
885 $exists = self::getExistsWarning( $localFile );
886 if ( $exists !== false ) {
887 $warnings['exists'] = $exists;
888
889 // check if file is an exact duplicate of current file version
890 if ( $hash !== false && $hash === $localFile->getSha1() ) {
891 $warnings['no-change'] = $localFile;
892 }
893
894 // check if file is an exact duplicate of older versions of this file
895 $history = $localFile->getHistory();
896 foreach ( $history as $oldFile ) {
897 if ( $hash === $oldFile->getSha1() ) {
898 $warnings['duplicate-version'][] = $oldFile;
899 }
900 }
901 }
902
903 return $warnings;
904 }
905
906 private function checkLocalFileWasDeleted( LocalFile $localFile ) {
907 return $localFile->wasDeleted() && !$localFile->exists();
908 }
909
916 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
917 if ( $hash === false ) {
918 return [];
919 }
920 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
921 $title = $this->getTitle();
922 foreach ( $dupes as $key => $dupe ) {
923 if (
924 ( $dupe instanceof LocalFile ) &&
925 $ignoreLocalDupes &&
926 $title->equals( $dupe->getTitle() )
927 ) {
928 unset( $dupes[$key] );
929 }
930 }
931
932 return $dupes;
933 }
934
942 private function checkAgainstArchiveDupes( $hash, Authority $performer ) {
943 if ( $hash === false ) {
944 return null;
945 }
946 $archivedFile = new ArchivedFile( null, 0, '', $hash );
947 if ( $archivedFile->getID() > 0 ) {
948 if ( $archivedFile->userCan( File::DELETED_FILE, $performer ) ) {
949 return $archivedFile->getName();
950 }
951 return '';
952 }
953
954 return null;
955 }
956
974 public function performUpload(
975 $comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
976 ) {
977 $this->getLocalFile()->load( IDBAccessObject::READ_LATEST );
978 $props = $this->mFileProps;
979
980 $error = null;
981 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
982 if ( $error ) {
983 if ( !is_array( $error ) ) {
984 $error = [ $error ];
985 }
986 return Status::newFatal( ...$error );
987 }
988
989 $status = $this->getLocalFile()->upload(
990 $this->mTempPath,
991 $comment,
992 $pageText !== false ? $pageText : '',
993 File::DELETE_SOURCE,
994 $props,
995 false,
996 $user,
997 $tags
998 );
999
1000 if ( $status->isGood() ) {
1001 if ( $watch ) {
1002 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
1003 $user,
1004 $this->getLocalFile()->getTitle(),
1005 $watchlistExpiry
1006 );
1007 }
1008 $this->getHookRunner()->onUploadComplete( $this );
1009
1010 $this->postProcessUpload();
1011 }
1012
1013 return $status;
1014 }
1015
1022 public function postProcessUpload() {
1023 }
1024
1031 public function getTitle() {
1032 if ( $this->mTitle !== false ) {
1033 return $this->mTitle;
1034 }
1035 if ( !is_string( $this->mDesiredDestName ) ) {
1036 $this->mTitleError = self::ILLEGAL_FILENAME;
1037 $this->mTitle = null;
1038
1039 return $this->mTitle;
1040 }
1041 /* Assume that if a user specified File:Something.jpg, this is an error
1042 * and that the namespace prefix needs to be stripped of.
1043 */
1044 $title = Title::newFromText( $this->mDesiredDestName );
1045 if ( $title && $title->getNamespace() === NS_FILE ) {
1046 $this->mFilteredName = $title->getDBkey();
1047 } else {
1048 $this->mFilteredName = $this->mDesiredDestName;
1049 }
1050
1051 # oi_archive_name is max 255 bytes, which include a timestamp and an
1052 # exclamation mark, so restrict file name to 240 bytes.
1053 if ( strlen( $this->mFilteredName ) > 240 ) {
1054 $this->mTitleError = self::FILENAME_TOO_LONG;
1055 $this->mTitle = null;
1056
1057 return $this->mTitle;
1058 }
1059
1065 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
1066 /* Normalize to title form before we do any further processing */
1067 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1068 if ( $nt === null ) {
1069 $this->mTitleError = self::ILLEGAL_FILENAME;
1070 $this->mTitle = null;
1071
1072 return $this->mTitle;
1073 }
1074 $this->mFilteredName = $nt->getDBkey();
1075
1080 [ $partname, $ext ] = self::splitExtensions( $this->mFilteredName );
1081
1082 if ( $ext !== [] ) {
1083 $this->mFinalExtension = trim( end( $ext ) );
1084 } else {
1085 $this->mFinalExtension = '';
1086
1087 // No extension, try guessing one from the temporary file
1088 // FIXME: Sometimes we mTempPath isn't set yet here, possibly due to an unrealistic
1089 // or incomplete test case in UploadBaseTest (T272328)
1090 if ( $this->mTempPath !== null ) {
1091 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1092 $mime = $magic->guessMimeType( $this->mTempPath );
1093 if ( $mime !== 'unknown/unknown' ) {
1094 # Get a space separated list of extensions
1095 $mimeExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
1096 if ( $mimeExt !== null ) {
1097 # Set the extension to the canonical extension
1098 $this->mFinalExtension = $mimeExt;
1099
1100 # Fix up the other variables
1101 $this->mFilteredName .= ".{$this->mFinalExtension}";
1102 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1103 $ext = [ $this->mFinalExtension ];
1104 }
1105 }
1106 }
1107 }
1108
1109 // Don't allow users to override the list of prohibited file extensions (check file extension)
1110 $config = MediaWikiServices::getInstance()->getMainConfig();
1111 $checkFileExtensions = $config->get( MainConfigNames::CheckFileExtensions );
1112 $strictFileExtensions = $config->get( MainConfigNames::StrictFileExtensions );
1113 $fileExtensions = $config->get( MainConfigNames::FileExtensions );
1114 $prohibitedFileExtensions = $config->get( MainConfigNames::ProhibitedFileExtensions );
1115
1116 $badList = self::checkFileExtensionList( $ext, $prohibitedFileExtensions );
1117
1118 if ( $this->mFinalExtension == '' ) {
1119 $this->mTitleError = self::FILETYPE_MISSING;
1120 $this->mTitle = null;
1121
1122 return $this->mTitle;
1123 }
1124
1125 if ( $badList ||
1126 ( $checkFileExtensions && $strictFileExtensions &&
1127 !self::checkFileExtension( $this->mFinalExtension, $fileExtensions ) )
1128 ) {
1129 $this->mBlackListedExtensions = $badList;
1130 $this->mTitleError = self::FILETYPE_BADTYPE;
1131 $this->mTitle = null;
1132
1133 return $this->mTitle;
1134 }
1135
1136 // Windows may be broken with special characters, see T3780
1137 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1138 && !MediaWikiServices::getInstance()->getRepoGroup()
1139 ->getLocalRepo()->backendSupportsUnicodePaths()
1140 ) {
1141 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1142 $this->mTitle = null;
1143
1144 return $this->mTitle;
1145 }
1146
1147 # If there was more than one file "extension", reassemble the base
1148 # filename to prevent bogus complaints about length
1149 if ( count( $ext ) > 1 ) {
1150 $iterations = count( $ext ) - 1;
1151 for ( $i = 0; $i < $iterations; $i++ ) {
1152 $partname .= '.' . $ext[$i];
1153 }
1154 }
1155
1156 if ( strlen( $partname ) < 1 ) {
1157 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1158 $this->mTitle = null;
1159
1160 return $this->mTitle;
1161 }
1162
1163 $this->mTitle = $nt;
1164
1165 return $this->mTitle;
1166 }
1167
1174 public function getLocalFile() {
1175 if ( $this->mLocalFile === null ) {
1176 $nt = $this->getTitle();
1177 $this->mLocalFile = $nt === null
1178 ? null
1179 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1180 }
1181
1182 return $this->mLocalFile;
1183 }
1184
1188 public function getStashFile() {
1189 return $this->mStashFile;
1190 }
1191
1204 public function tryStashFile( User $user, $isPartial = false ) {
1205 if ( !$isPartial ) {
1206 $error = $this->runUploadStashFileHook( $user );
1207 if ( $error ) {
1208 return Status::newFatal( ...$error );
1209 }
1210 }
1211 try {
1212 $file = $this->doStashFile( $user );
1213 return Status::newGood( $file );
1214 } catch ( UploadStashException $e ) {
1215 return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1216 }
1217 }
1218
1223 protected function runUploadStashFileHook( User $user ) {
1224 $props = $this->mFileProps;
1225 $error = null;
1226 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1227 if ( $error && !is_array( $error ) ) {
1228 $error = [ $error ];
1229 }
1230 return $error;
1231 }
1232
1240 protected function doStashFile( ?User $user = null ) {
1241 $stash = MediaWikiServices::getInstance()->getRepoGroup()
1242 ->getLocalRepo()->getUploadStash( $user );
1243 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType(), $this->mFileProps );
1244 $this->mStashFile = $file;
1245
1246 return $file;
1247 }
1248
1253 public function cleanupTempFile() {
1254 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1255 // Delete when all relevant TempFSFile handles go out of scope
1256 wfDebug( __METHOD__ . ": Marked temporary file '{$this->mTempPath}' for removal" );
1257 $this->tempFileObj->autocollect();
1258 }
1259 }
1260
1264 public function getTempPath() {
1265 return $this->mTempPath;
1266 }
1267
1277 public static function splitExtensions( $filename ) {
1278 $bits = explode( '.', $filename );
1279 $basename = array_shift( $bits );
1280
1281 return [ $basename, $bits ];
1282 }
1283
1291 public static function checkFileExtension( $ext, $list ) {
1292 return in_array( strtolower( $ext ?? '' ), $list, true );
1293 }
1294
1303 public static function checkFileExtensionList( $ext, $list ) {
1304 return array_intersect( array_map( 'strtolower', $ext ), $list );
1305 }
1306
1314 public static function verifyExtension( $mime, $extension ) {
1315 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1316
1317 if ( !$mime || $mime === 'unknown' || $mime === 'unknown/unknown' ) {
1318 if ( !$magic->isRecognizableExtension( $extension ) ) {
1319 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1320 "unrecognized extension '$extension', can't verify" );
1321
1322 return true;
1323 }
1324
1325 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1326 "recognized extension '$extension', so probably invalid file" );
1327 return false;
1328 }
1329
1330 $match = $magic->isMatchingExtension( $extension, $mime );
1331
1332 if ( $match === null ) {
1333 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1334 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension" );
1335
1336 return false;
1337 }
1338
1339 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file" );
1340 return true;
1341 }
1342
1343 if ( $match ) {
1344 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file" );
1345
1347 return true;
1348 }
1349
1350 wfDebug( __METHOD__
1351 . ": mime type $mime mismatches file extension $extension, rejecting file" );
1352
1353 return false;
1354 }
1355
1367 public static function detectScript( $file, $mime, $extension ) {
1368 # ugly hack: for text files, always look at the entire file.
1369 # For binary field, just check the first K.
1370
1371 if ( str_starts_with( $mime ?? '', 'text/' ) ) {
1372 $chunk = file_get_contents( $file );
1373 } else {
1374 $fp = fopen( $file, 'rb' );
1375 if ( !$fp ) {
1376 return false;
1377 }
1378 $chunk = fread( $fp, 1024 );
1379 fclose( $fp );
1380 }
1381
1382 $chunk = strtolower( $chunk );
1383
1384 if ( !$chunk ) {
1385 return false;
1386 }
1387
1388 # decode from UTF-16 if needed (could be used for obfuscation).
1389 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
1390 $enc = 'UTF-16BE';
1391 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
1392 $enc = 'UTF-16LE';
1393 } else {
1394 $enc = null;
1395 }
1396
1397 if ( $enc !== null ) {
1398 AtEase::suppressWarnings();
1399 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1400 AtEase::restoreWarnings();
1401 }
1402
1403 $chunk = trim( $chunk );
1404
1406 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1407
1408 # check for HTML doctype
1409 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1410 return true;
1411 }
1412
1413 // Some browsers will interpret obscure xml encodings as UTF-8, while
1414 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1415 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
1416 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1417 return true;
1418 }
1419 }
1420
1421 // Quick check for HTML heuristics in old IE and Safari.
1422 //
1423 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1424 // don't need them all here as it can cause many false positives.
1425 //
1426 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1427 $tags = [
1428 '<body',
1429 '<head',
1430 '<html', # also in safari
1431 '<script', # also in safari
1432 ];
1433
1434 foreach ( $tags as $tag ) {
1435 if ( strpos( $chunk, $tag ) !== false ) {
1436 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1437
1438 return true;
1439 }
1440 }
1441
1442 /*
1443 * look for JavaScript
1444 */
1445
1446 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1447 $chunk = Sanitizer::decodeCharReferences( $chunk );
1448
1449 # look for script-types
1450 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1451 wfDebug( __METHOD__ . ": found script types" );
1452
1453 return true;
1454 }
1455
1456 # look for html-style script-urls
1457 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1458 wfDebug( __METHOD__ . ": found html-style script urls" );
1459
1460 return true;
1461 }
1462
1463 # look for css-style script-urls
1464 if ( preg_match( '!url\s*\‍(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1465 wfDebug( __METHOD__ . ": found css-style script urls" );
1466
1467 return true;
1468 }
1469
1470 wfDebug( __METHOD__ . ": no scripts found" );
1471
1472 return false;
1473 }
1474
1482 public static function checkXMLEncodingMissmatch( $file ) {
1483 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
1484 // should read the first 1445 bytes. Do 4096 bytes for good measure.
1485 // XML Spec says XML declaration if present must be first thing in file
1486 // other than BOM
1487 $contents = file_get_contents( $file, false, null, 0, 4096 );
1488 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1489
1490 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1491 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1492 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCODINGS )
1493 ) {
1494 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1495
1496 return true;
1497 }
1498 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1499 // Start of XML declaration without an end in the first 4096 bytes
1500 // bytes. There shouldn't be a legitimate reason for this to happen.
1501 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1502
1503 return true;
1504 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1505 // EBCDIC encoded XML
1506 wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1507
1508 return true;
1509 }
1510
1511 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1512 // detect the encoding in case it specifies an encoding not allowed in self::SAFE_XML_ENCODINGS
1513 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1514 foreach ( $attemptEncodings as $encoding ) {
1515 AtEase::suppressWarnings();
1516 $str = iconv( $encoding, 'UTF-8', $contents );
1517 AtEase::restoreWarnings();
1518 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1519 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1520 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCODINGS )
1521 ) {
1522 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1523
1524 return true;
1525 }
1526 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1527 // Start of XML declaration without an end in the first 4096 bytes
1528 // bytes. There shouldn't be a legitimate reason for this to happen.
1529 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1530
1531 return true;
1532 }
1533 }
1534
1535 return false;
1536 }
1537
1543 protected function detectScriptInSvg( $filename, $partial ) {
1544 $this->mSVGNSError = false;
1545 $check = new XmlTypeCheck(
1546 $filename,
1547 [ $this, 'checkSvgScriptCallback' ],
1548 true,
1549 [
1550 'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1551 'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1552 ]
1553 );
1554 if ( $check->wellFormed !== true ) {
1555 // Invalid xml (T60553)
1556 // But only when non-partial (T67724)
1557 return $partial ? false : [ 'uploadinvalidxml' ];
1558 }
1559
1560 if ( $check->filterMatch ) {
1561 if ( $this->mSVGNSError ) {
1562 return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1563 }
1564 return $check->filterMatchType;
1565 }
1566
1567 return false;
1568 }
1569
1577 public static function checkSvgPICallback( $target, $data ) {
1578 // Don't allow external stylesheets (T59550)
1579 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1580 return [ 'upload-scripted-pi-callback' ];
1581 }
1582
1583 return false;
1584 }
1585
1598 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1599 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1600 // allow XHTML anyway.
1601 static $allowedDTDs = [
1602 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1603 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1604 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1605 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1606 // https://phabricator.wikimedia.org/T168856
1607 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1608 ];
1609 if ( $type !== 'PUBLIC'
1610 || !in_array( $systemId, $allowedDTDs )
1611 || !str_starts_with( $publicId, "-//W3C//" )
1612 ) {
1613 return [ 'upload-scripted-dtd' ];
1614 }
1615 return false;
1616 }
1617
1625 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1626 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1627
1628 // We specifically don't include:
1629 // http://www.w3.org/1999/xhtml (T62771)
1630 static $validNamespaces = [
1631 '',
1632 'adobe:ns:meta/',
1633 'http://creativecommons.org/ns#',
1634 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1635 'http://ns.adobe.com/adobeillustrator/10.0/',
1636 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1637 'http://ns.adobe.com/extensibility/1.0/',
1638 'http://ns.adobe.com/flows/1.0/',
1639 'http://ns.adobe.com/illustrator/1.0/',
1640 'http://ns.adobe.com/imagereplacement/1.0/',
1641 'http://ns.adobe.com/pdf/1.3/',
1642 'http://ns.adobe.com/photoshop/1.0/',
1643 'http://ns.adobe.com/saveforweb/1.0/',
1644 'http://ns.adobe.com/variables/1.0/',
1645 'http://ns.adobe.com/xap/1.0/',
1646 'http://ns.adobe.com/xap/1.0/g/',
1647 'http://ns.adobe.com/xap/1.0/g/img/',
1648 'http://ns.adobe.com/xap/1.0/mm/',
1649 'http://ns.adobe.com/xap/1.0/rights/',
1650 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1651 'http://ns.adobe.com/xap/1.0/stype/font#',
1652 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1653 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1654 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1655 'http://ns.adobe.com/xap/1.0/t/pg/',
1656 'http://purl.org/dc/elements/1.1/',
1657 'http://purl.org/dc/elements/1.1',
1658 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1659 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1660 'http://taptrix.com/inkpad/svg_extensions',
1661 'http://web.resource.org/cc/',
1662 'http://www.freesoftware.fsf.org/bkchem/cdml',
1663 'http://www.inkscape.org/namespaces/inkscape',
1664 'http://www.opengis.net/gml',
1665 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1666 'http://www.w3.org/2000/svg',
1667 'http://www.w3.org/tr/rec-rdf-syntax/',
1668 'http://www.w3.org/2000/01/rdf-schema#',
1669 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1670 ];
1671
1672 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1673 // This is nasty but harmless. (T144827)
1674 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1675
1676 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1677 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1679 $this->mSVGNSError = $namespace;
1680
1681 return true;
1682 }
1683
1684 // check for elements that can contain javascript
1685 if ( $strippedElement === 'script' ) {
1686 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1687
1688 return [ 'uploaded-script-svg', $strippedElement ];
1689 }
1690
1691 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1692 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1693 if ( $strippedElement === 'handler' ) {
1694 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1695
1696 return [ 'uploaded-script-svg', $strippedElement ];
1697 }
1698
1699 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1700 if ( $strippedElement === 'stylesheet' ) {
1701 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1702
1703 return [ 'uploaded-script-svg', $strippedElement ];
1704 }
1705
1706 // Block iframes, in case they pass the namespace check
1707 if ( $strippedElement === 'iframe' ) {
1708 wfDebug( __METHOD__ . ": iframe in uploaded file." );
1709
1710 return [ 'uploaded-script-svg', $strippedElement ];
1711 }
1712
1713 // Check <style> css
1714 if ( $strippedElement === 'style'
1715 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1716 ) {
1717 wfDebug( __METHOD__ . ": hostile css in style element." );
1718
1719 return [ 'uploaded-hostile-svg' ];
1720 }
1721
1722 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1723 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1724
1725 foreach ( $attribs as $attrib => $value ) {
1726 // If attributeNamespace is '', it is relative to its element's namespace
1727 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
1728 $value = strtolower( $value );
1729
1730 if ( !(
1731 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1732 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1733 $attributeNamespace === ''
1734 ) && str_starts_with( $stripped, 'on' )
1735 ) {
1736 wfDebug( __METHOD__
1737 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1738
1739 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1740 }
1741
1742 // Do not allow relative links, or unsafe url schemas.
1743 // For <a> tags, only data:, http: and https: and same-document
1744 // fragment links are allowed.
1745 // For all other tags, only 'data:' and fragments (#) are allowed.
1746 if (
1747 $stripped === 'href'
1748 && $value !== ''
1749 && !str_starts_with( $value, 'data:' )
1750 && !str_starts_with( $value, '#' )
1751 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1752 ) {
1753 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1754 . "'$attrib'='$value' in uploaded file." );
1755
1756 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1757 }
1758
1759 // Only allow 'data:\' targets that should be safe.
1760 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1761 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1762 // RFC2397 parameters.
1763 // This is only slightly slower than (;[\w;]+)*.
1764 // phpcs:ignore Generic.Files.LineLength
1765 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1766
1767 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1768 wfDebug( __METHOD__ . ": Found href to allow listed data: uri "
1769 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1770 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1771 }
1772 }
1773
1774 // Change href with animate from (http://html5sec.org/#137).
1775 if ( $stripped === 'attributename'
1776 && $strippedElement === 'animate'
1777 && $this->stripXmlNamespace( $value ) === 'href'
1778 ) {
1779 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1780 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1781
1782 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1783 }
1784
1785 // Use set/animate to add event-handler attribute to parent.
1786 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
1787 && $stripped === 'attributename'
1788 && str_starts_with( $value, 'on' )
1789 ) {
1790 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1791 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1792
1793 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1794 }
1795
1796 // use set to add href attribute to parent element.
1797 if ( $strippedElement === 'set'
1798 && $stripped === 'attributename'
1799 && str_contains( $value, 'href' )
1800 ) {
1801 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1802
1803 return [ 'uploaded-setting-href-svg' ];
1804 }
1805
1806 // use set to add a remote / data / script target to an element.
1807 if ( $strippedElement === 'set'
1808 && $stripped === 'to'
1809 && preg_match( '!(http|https|data|script):!im', $value )
1810 ) {
1811 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1812
1813 return [ 'uploaded-wrong-setting-svg', $value ];
1814 }
1815
1816 // use handler attribute with remote / data / script.
1817 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1818 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1819 . "'$attrib'='$value' in uploaded file." );
1820
1821 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1822 }
1823
1824 // use CSS styles to bring in remote code.
1825 if ( $stripped === 'style'
1826 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1827 ) {
1828 wfDebug( __METHOD__ . ": Found svg setting a style with "
1829 . "remote url '$attrib'='$value' in uploaded file." );
1830 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1831 }
1832
1833 // Several attributes can include css, css character escaping isn't allowed.
1834 if ( in_array( $stripped, $cssAttrs, true )
1835 && self::checkCssFragment( $value )
1836 ) {
1837 wfDebug( __METHOD__ . ": Found svg setting a style with "
1838 . "remote url '$attrib'='$value' in uploaded file." );
1839 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1840 }
1841
1842 // image filters can pull in url, which could be svg that executes scripts.
1843 // Only allow url( "#foo" ).
1844 // Do not allow url( http://example.com )
1845 if ( $strippedElement === 'image'
1846 && $stripped === 'filter'
1847 && preg_match( '!url\s*\‍(\s*["\']?[^#]!im', $value )
1848 ) {
1849 wfDebug( __METHOD__ . ": Found image filter with url: "
1850 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1851
1852 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1853 }
1854 }
1855
1856 return false; // No scripts detected
1857 }
1858
1865 private static function checkCssFragment( $value ) {
1866 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1867 if ( stripos( $value, '@import' ) !== false ) {
1868 return true;
1869 }
1870
1871 # We allow @font-face to embed fonts with data: urls, so we snip the string
1872 # 'url' out so that this case won't match when we check for urls below
1873 $pattern = '!(@font-face\s*{[^}]*src:)url(\‍("data:;base64,)!im';
1874 $value = preg_replace( $pattern, '$1$2', $value );
1875
1876 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1877 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1878 # Expression and -o-link don't seem to work either, but filtering them here in case.
1879 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1880 # but not local ones such as url("#..., url('#..., url(#....
1881 if ( preg_match( '!expression
1882 | -o-link\s*:
1883 | -o-link-source\s*:
1884 | -o-replace\s*:!imx', $value ) ) {
1885 return true;
1886 }
1887
1888 if ( preg_match_all(
1889 "!(\s*(url|image|image-set)\s*\‍(\s*[\"']?\s*[^#]+.*?\‍))!sim",
1890 $value,
1891 $matches
1892 ) !== 0
1893 ) {
1894 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1895 foreach ( $matches[1] as $match ) {
1896 if ( !preg_match( "!\s*(url|image|image-set)\s*\‍(\s*(#|'#|\"#)!im", $match ) ) {
1897 return true;
1898 }
1899 }
1900 }
1901
1902 return (bool)preg_match( '/[\000-\010\013\016-\037\177]/', $value );
1903 }
1904
1910 private static function splitXmlNamespace( $element ) {
1911 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1912 $parts = explode( ':', strtolower( $element ) );
1913 $name = array_pop( $parts );
1914 $ns = implode( ':', $parts );
1915
1916 return [ $ns, $name ];
1917 }
1918
1923 private function stripXmlNamespace( $element ) {
1924 // 'http://www.w3.org/2000/svg:script' -> 'script'
1925 return self::splitXmlNamespace( $element )[1];
1926 }
1927
1938 public static function detectVirus( $file ) {
1939 global $wgOut;
1940 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1941 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1942 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1943 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1944 if ( !$antivirus ) {
1945 wfDebug( __METHOD__ . ": virus scanner disabled" );
1946
1947 return null;
1948 }
1949
1950 if ( !$antivirusSetup[$antivirus] ) {
1951 wfDebug( __METHOD__ . ": unknown virus scanner: {$antivirus}" );
1952 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1953 [ 'virus-badscanner', $antivirus ] );
1954
1955 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1956 }
1957
1958 # look up scanner configuration
1959 $command = $antivirusSetup[$antivirus]['command'];
1960 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1961 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
1962
1963 if ( !str_contains( $command, "%f" ) ) {
1964 # simple pattern: append file to scan
1965 $command .= " " . Shell::escape( $file );
1966 } else {
1967 # complex pattern: replace "%f" with file to scan
1968 $command = str_replace( "%f", Shell::escape( $file ), $command );
1969 }
1970
1971 wfDebug( __METHOD__ . ": running virus scan: $command " );
1972
1973 # execute virus scanner
1974 $exitCode = false;
1975
1976 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1977 # that does not seem to be worth the pain.
1978 # Ask me (Duesentrieb) about it if it's ever needed.
1979 $output = wfShellExecWithStderr( $command, $exitCode );
1980
1981 # map exit code to AV_xxx constants.
1982 $mappedCode = $exitCode;
1983 if ( $exitCodeMap ) {
1984 if ( isset( $exitCodeMap[$exitCode] ) ) {
1985 $mappedCode = $exitCodeMap[$exitCode];
1986 } elseif ( isset( $exitCodeMap["*"] ) ) {
1987 $mappedCode = $exitCodeMap["*"];
1988 }
1989 }
1990
1991 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1992 # so we need the strict equalities === and thus can't use a switch here
1993 if ( $mappedCode === AV_SCAN_FAILED ) {
1994 # scan failed (code was mapped to false by $exitCodeMap)
1995 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1996
1997 $output = $antivirusRequired
1998 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1999 : null;
2000 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
2001 # scan failed because filetype is unknown (probably immune)
2002 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
2003 $output = null;
2004 } elseif ( $mappedCode === AV_NO_VIRUS ) {
2005 # no virus found
2006 wfDebug( __METHOD__ . ": file passed virus scan." );
2007 $output = false;
2008 } else {
2009 $output = trim( $output );
2010
2011 if ( !$output ) {
2012 $output = true; # if there's no output, return true
2013 } elseif ( $msgPattern ) {
2014 $groups = [];
2015 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
2016 $output = $groups[1];
2017 }
2018 }
2019
2020 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
2021 }
2022
2023 return $output;
2024 }
2025
2034 private function checkOverwrite( Authority $performer ) {
2035 // First check whether the local file can be overwritten
2036 $file = $this->getLocalFile();
2037 $file->load( IDBAccessObject::READ_LATEST );
2038 if ( $file->exists() ) {
2039 if ( !self::userCanReUpload( $performer, $file ) ) {
2040 return [ 'fileexists-forbidden', $file->getName() ];
2041 }
2042
2043 return true;
2044 }
2045
2046 $services = MediaWikiServices::getInstance();
2047
2048 /* Check shared conflicts: if the local file does not exist, but
2049 * RepoGroup::findFile finds a file, it exists in a shared repository.
2050 */
2051 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2052 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
2053 return [ 'fileexists-shared-forbidden', $file->getName() ];
2054 }
2055
2056 return true;
2057 }
2058
2066 public static function userCanReUpload( Authority $performer, File $img ) {
2067 if ( $performer->isAllowed( 'reupload' ) ) {
2068 return true; // non-conditional
2069 }
2070
2071 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2072 return false;
2073 }
2074
2075 if ( !( $img instanceof LocalFile ) ) {
2076 return false;
2077 }
2078
2079 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2080 }
2081
2093 public static function getExistsWarning( $file ) {
2094 if ( $file->exists() ) {
2095 return [ 'warning' => 'exists', 'file' => $file ];
2096 }
2097
2098 if ( $file->getTitle()->getArticleID() ) {
2099 return [ 'warning' => 'page-exists', 'file' => $file ];
2100 }
2101
2102 $n = strrpos( $file->getName(), '.' );
2103 if ( $n > 0 ) {
2104 $partname = substr( $file->getName(), 0, $n );
2105 $extension = substr( $file->getName(), $n + 1 );
2106 } else {
2107 $partname = $file->getName();
2108 $extension = '';
2109 }
2110 $normalizedExtension = File::normalizeExtension( $extension );
2111 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2112
2113 if ( $normalizedExtension != $extension ) {
2114 // We're not using the normalized form of the extension.
2115 // Normal form is lowercase, using most common of alternate
2116 // extensions (e.g. 'jpg' rather than 'JPEG').
2117
2118 // Check for another file using the normalized form...
2119 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2120 $file_lc = $localRepo->newFile( $nt_lc );
2121
2122 if ( $file_lc->exists() ) {
2123 return [
2124 'warning' => 'exists-normalized',
2125 'file' => $file,
2126 'normalizedFile' => $file_lc
2127 ];
2128 }
2129 }
2130
2131 // Check for files with the same name but a different extension
2132 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2133 if ( count( $similarFiles ) ) {
2134 return [
2135 'warning' => 'exists-normalized',
2136 'file' => $file,
2137 'normalizedFile' => $similarFiles[0],
2138 ];
2139 }
2140
2141 if ( self::isThumbName( $file->getName() ) ) {
2142 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2143 $nt_thb = Title::newFromText(
2144 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2145 NS_FILE
2146 );
2147 $file_thb = $localRepo->newFile( $nt_thb );
2148 if ( $file_thb->exists() ) {
2149 return [
2150 'warning' => 'thumb',
2151 'file' => $file,
2152 'thumbFile' => $file_thb
2153 ];
2154 }
2155
2156 // The file does not exist, but we just don't like the name
2157 return [
2158 'warning' => 'thumb-name',
2159 'file' => $file,
2160 'thumbFile' => $file_thb
2161 ];
2162 }
2163
2164 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2165 if ( str_starts_with( $partname, $prefix ) ) {
2166 return [
2167 'warning' => 'bad-prefix',
2168 'file' => $file,
2169 'prefix' => $prefix
2170 ];
2171 }
2172 }
2173
2174 return false;
2175 }
2176
2182 public static function isThumbName( $filename ) {
2183 $n = strrpos( $filename, '.' );
2184 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2185
2186 return (
2187 substr( $partname, 3, 3 ) === 'px-' ||
2188 substr( $partname, 2, 3 ) === 'px-'
2189 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2190 }
2191
2197 public static function getFilenamePrefixBlacklist() {
2198 $list = [];
2199 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2200 if ( !$message->isDisabled() ) {
2201 $lines = explode( "\n", $message->plain() );
2202 foreach ( $lines as $line ) {
2203 // Remove comment lines
2204 $comment = substr( trim( $line ), 0, 1 );
2205 if ( $comment === '#' || $comment == '' ) {
2206 continue;
2207 }
2208 // Remove additional comments after a prefix
2209 $comment = strpos( $line, '#' );
2210 if ( $comment > 0 ) {
2211 $line = substr( $line, 0, $comment - 1 );
2212 }
2213 $list[] = trim( $line );
2214 }
2215 }
2216
2217 return $list;
2218 }
2219
2229 public function getImageInfo( $result = null ) {
2230 $apiUpload = ApiUpload::getDummyInstance();
2231 return $apiUpload->getUploadImageInfo( $this );
2232 }
2233
2238 public function convertVerifyErrorToStatus( $error ) {
2239 $code = $error['status'];
2240 unset( $code['status'] );
2241
2242 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2243 }
2244
2252 public static function getMaxUploadSize( $forType = null ) {
2253 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2254
2255 if ( is_array( $maxUploadSize ) ) {
2256 return $maxUploadSize[$forType] ?? $maxUploadSize['*'];
2257 }
2258 return intval( $maxUploadSize );
2259 }
2260
2268 public static function getMaxPhpUploadSize() {
2269 $phpMaxFileSize = wfShorthandToInteger(
2270 ini_get( 'upload_max_filesize' ),
2271 PHP_INT_MAX
2272 );
2273 $phpMaxPostSize = wfShorthandToInteger(
2274 ini_get( 'post_max_size' ),
2275 PHP_INT_MAX
2276 ) ?: PHP_INT_MAX;
2277 return min( $phpMaxFileSize, $phpMaxPostSize );
2278 }
2279
2291 public static function getSessionStatus( UserIdentity $user, $statusKey ) {
2292 $store = self::getUploadSessionStore();
2293 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2294
2295 return $store->get( $key );
2296 }
2297
2310 public static function setSessionStatus( UserIdentity $user, $statusKey, $value ) {
2311 $store = self::getUploadSessionStore();
2312 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2313 $logger = LoggerFactory::getInstance( 'upload' );
2314
2315 if ( is_array( $value ) && ( $value['result'] ?? '' ) === 'Failure' ) {
2316 $logger->info( 'Upload session {key} for {user} set to failure {status} at {stage}',
2317 [
2318 'result' => $value['result'] ?? '',
2319 'stage' => $value['stage'] ?? 'unknown',
2320 'user' => $user->getName(),
2321 'status' => (string)( $value['status'] ?? '-' ),
2322 'filekey' => $value['filekey'] ?? '',
2323 'key' => $statusKey
2324 ]
2325 );
2326 } elseif ( is_array( $value ) ) {
2327 $logger->debug( 'Upload session {key} for {user} changed {status} at {stage}',
2328 [
2329 'result' => $value['result'] ?? '',
2330 'stage' => $value['stage'] ?? 'unknown',
2331 'user' => $user->getName(),
2332 'status' => (string)( $value['status'] ?? '-' ),
2333 'filekey' => $value['filekey'] ?? '',
2334 'key' => $statusKey
2335 ]
2336 );
2337 } else {
2338 $logger->debug( "Upload session {key} deleted for {user}",
2339 [
2340 'value' => $value,
2341 'key' => $statusKey,
2342 'user' => $user->getName()
2343 ]
2344 );
2345 }
2346
2347 if ( $value === false ) {
2348 $store->delete( $key );
2349 } else {
2350 $store->set( $key, $value, $store::TTL_DAY );
2351 }
2352 }
2353
2360 private static function getUploadSessionKey( BagOStuff $store, UserIdentity $user, $statusKey ) {
2361 return $store->makeKey(
2362 'uploadstatus',
2363 $user->isRegistered() ? $user->getId() : md5( $user->getName() ),
2364 $statusKey
2365 );
2366 }
2367
2371 private static function getUploadSessionStore() {
2372 return MediaWikiServices::getInstance()->getMainObjectStash();
2373 }
2374}
const AV_SCAN_FAILED
Definition Defines.php:100
const NS_FILE
Definition Defines.php:71
const AV_SCAN_ABORTED
Definition Defines.php:99
const AV_NO_VIRUS
Definition Defines.php:97
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Title null $mTitle
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgOut
Definition Setup.php:558
MimeMagic helper wrapper.
This class represents the result of the API operations.
Definition ApiResult.php:43
Group all the pieces relevant to the context of a request into one instance.
Base class for file repositories.
Definition FileRepo.php:68
Deleted file in the 'filearchive' table.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:93
wasDeleted()
Was this file ever deleted from the wiki?
Definition File.php:2180
getName()
Return the name of this file.
Definition File.php:361
Local file in the wiki's own database.
Definition LocalFile.php:93
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:155
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:46
A StatusValue for permission errors.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Executes shell commands.
Definition Shell.php:46
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
Represents a title within MediaWiki.
Definition Title.php:78
getDBkey()
Get the main part with underscores.
Definition Title.php:1031
User class for the MediaWiki software.
Definition User.php:120
UploadBase and subclasses are the backend of MediaWiki's file uploads.
getSourceType()
Returns the upload type.
getDesiredDestName()
Get the desired destination name.
static makeWarningsSerializable( $warnings)
Convert the warnings array returned by checkWarnings() to something that can be serialized.
int $mTitleError
static setSessionStatus(UserIdentity $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling).
const EMPTY_FILE
UploadStashFile null $mStashFile
static verifyExtension( $mime, $extension)
Checks if the MIME type of the uploaded file matches the file extension.
postProcessUpload()
Perform extra steps after a successful upload.
checkSvgScriptCallback( $element, $attribs, $data=null)
verifyPermissions(Authority $performer)
Alias for verifyTitlePermissions.
getLocalFile()
Return the local file and initializes if necessary.
const SUCCESS
bool null $mJavaDetected
string null $mFilteredName
doStashFile(?User $user=null)
Implementation for stashFile() and tryStashFile().
getRealPath( $srcPath)
static createFromRequest(&$request, $type=null)
Create a form of UploadBase depending on wpSourceType and initializes it.
runUploadStashFileHook(User $user)
zipEntryCallback( $entry)
Callback for ZipDirectoryReader to detect Java class files.
static checkSvgPICallback( $target, $data)
Callback to filter SVG Processing Instructions.
static isValidRequest( $request)
Check whether a request if valid for this handler.
const FILETYPE_MISSING
convertVerifyErrorToStatus( $error)
string null $mFinalExtension
verifyPartialFile()
A verification routine suitable for partial files.
static detectScript( $file, $mime, $extension)
Heuristic for detecting files that could contain JavaScript instructions or things that may look like...
verifyFile()
Verifies that it's ok to include the uploaded file.
array null $mFileProps
static isEnabled()
Returns true if uploads are enabled.
static isThumbName( $filename)
Helper function that checks whether the filename looks like a thumbnail.
getVerificationErrorCode( $error)
performUpload( $comment, $pageText, $watch, $user, $tags=[], ?string $watchlistExpiry=null)
Really perform the upload.
string null $mDesiredDestName
verifyTitlePermissions(Authority $performer)
Check whether the user can edit, upload and create the image.
static getFilenamePrefixBlacklist()
Get a list of disallowed filename prefixes from [[MediaWiki:Filename-prefix-blacklist]].
setTempFile( $tempPath, $fileSize=null)
static getSessionStatus(UserIdentity $user, $statusKey)
Get the current status of a chunked upload (used for polling).
static checkXMLEncodingMissmatch( $file)
Check an allowed list of xml encodings that are known not to be interpreted differently by the server...
const HOOK_ABORTED
string null $mDestName
const VERIFICATION_ERROR
string[] $mBlackListedExtensions
static isAllowed(Authority $performer)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
const WINDOWS_NONASCII_FILENAME
cleanupTempFile()
If we've modified the upload file, then we need to manually remove it on exit to clean up.
getImageInfo( $result=null)
Gets image info about the file just uploaded.
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
string null $mSourceType
int null $mFileSize
isEmptyFile()
Return true if the file is empty.
static checkFileExtension( $ext, $list)
Perform case-insensitive match against a list of file extensions.
const FILETYPE_BADTYPE
tryStashFile(User $user, $isPartial=false)
Like stashFile(), but respects extensions' wishes to prevent the stashing.
getTitle()
Returns the title of the file to be uploaded.
initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile=false)
static getMaxUploadSize( $forType=null)
Get MediaWiki's maximum uploaded file size for a given type of upload, based on $wgMaxUploadSize.
bool null $mRemoveTempFile
static checkSvgExternalDTD( $type, $publicId, $systemId)
Verify that DTD URLs referenced are only the standard DTDs.
getTempFileSha1Base36()
Get the base 36 SHA1 of the file.
detectScriptInSvg( $filename, $partial)
static splitExtensions( $filename)
Split a file into a base name and all dot-delimited 'extensions' on the end.
fetchFile()
Fetch the file.
checkWarnings( $user=null)
Check for non fatal problems with the file.
const FILE_TOO_LARGE
static isThrottled( $user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
getFileSize()
Return the file size.
verifyUpload()
Verify whether the upload is sensible.
const ILLEGAL_FILENAME
const MIN_LENGTH_PARTNAME
static checkFileExtensionList( $ext, $list)
Perform case-insensitive match against a list of file extensions.
static detectVirus( $file)
Generic wrapper function for a virus scanner program.
string null $mTempPath
Local file system path to the file to upload (or a local copy)
TempFSFile null $tempFileObj
Wrapper to handle deleting the temp file.
LocalFile null $mLocalFile
canFetchFile()
Perform checks to see if the file can be fetched.
const FILENAME_TOO_LONG
static getMaxPhpUploadSize()
Get the PHP maximum uploaded file size, based on ini settings.
verifyMimeType( $mime)
Verify the MIME type.
static unserializeWarnings( $warnings)
Convert the serialized warnings array created by makeWarningsSerializable() back to the output of che...
initializeFromRequest(&$request)
Initialize from a WebRequest.
string false $mSVGNSError
Class representing a non-directory file on the file system.
Definition FSFile.php:34
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Base class for all file backend classes (including multi-write backends).
XML syntax and type checker.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:88
delete( $key, $flags=0)
Delete an item if it exists.
set( $key, $value, $exptime=0, $flags=0)
Set an item.
get( $key, $flags=0)
Get an item.
makeKey( $keygroup,... $components)
Make a cache key from the given components, in the default keyspace.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:37
isAllowed(string $permission, ?PermissionStatus $status=null)
Checks whether this authority has the given permission in general.
authorizeWrite(string $action, PageIdentity $target, ?PermissionStatus $status=null)
Authorize write access.
Interface for objects representing user identity.
isRegistered()
This must be equivalent to getId() != 0 and is provided for code readability.
getId( $wikiId=self::LOCAL)
Interface for database access objects.
if(!file_exists( $CREDITS)) $lines