MediaWiki 1.43.1
UploadBase.php
Go to the documentation of this file.
1<?php
28use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
42use Wikimedia\AtEase\AtEase;
49
66abstract class UploadBase {
67 use ProtectedHookAccessorTrait;
68
70 protected $mTempPath;
72 protected $tempFileObj;
76 protected $mDestName;
80 protected $mSourceType;
82 protected $mTitle = false;
84 protected $mTitleError = 0;
86 protected $mFilteredName;
90 protected $mLocalFile;
92 protected $mStashFile;
94 protected $mFileSize;
96 protected $mFileProps;
100 protected $mJavaDetected;
102 protected $mSVGNSError;
103
104 private const SAFE_XML_ENCONDINGS = [
105 'UTF-8',
106 'US-ASCII',
107 'ISO-8859-1',
108 'ISO-8859-2',
109 'UTF-16',
110 'UTF-32',
111 'WINDOWS-1250',
112 'WINDOWS-1251',
113 'WINDOWS-1252',
114 'WINDOWS-1253',
115 'WINDOWS-1254',
116 'WINDOWS-1255',
117 'WINDOWS-1256',
118 'WINDOWS-1257',
119 'WINDOWS-1258',
120 ];
121
122 public const SUCCESS = 0;
123 public const OK = 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;
135
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',
148 ];
149
154 public function getVerificationErrorCode( $error ) {
155 return self::CODE_TO_STATUS[$error] ?? 'unknown-error';
156 }
157
164 public static function isEnabled() {
165 $enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
166
167 return $enableUploads && wfIniGetBool( 'file_uploads' );
168 }
169
178 public static function isAllowed( Authority $performer ) {
179 foreach ( [ 'upload', 'edit' ] as $permission ) {
180 if ( !$performer->isAllowed( $permission ) ) {
181 return $permission;
182 }
183 }
184
185 return true;
186 }
187
197 public static function isThrottled( $user ) {
198 wfDeprecated( __METHOD__, '1.41' );
199 return $user->pingLimiter( 'upload' );
200 }
201
203 private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
204
212 public static function createFromRequest( &$request, $type = null ) {
213 $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
214
215 if ( !$type ) {
216 return null;
217 }
218
219 // Get the upload class
220 $type = ucfirst( $type );
221
222 // Give hooks the chance to handle this request
224 $className = null;
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 ) ) {
232 return null;
233 }
234 }
235
236 if ( !$className::isEnabled() || !$className::isValidRequest( $request ) ) {
237 return null;
238 }
239
241 $handler = new $className;
242
243 $handler->initializeFromRequest( $request );
244
245 return $handler;
246 }
247
253 public static function isValidRequest( $request ) {
254 return false;
255 }
256
261 public function getDesiredDestName() {
262 return $this->mDesiredDestName;
263 }
264
268 public function __construct() {
269 }
270
278 public function getSourceType() {
279 return null;
280 }
281
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`." );
292 }
293
294 $this->setTempFile( $tempPath, $fileSize );
295 $this->mRemoveTempFile = $removeTempFile;
296 }
297
303 abstract public function initializeFromRequest( &$request );
304
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 );
315 if ( !$fileSize ) {
316 $this->mFileSize = filesize( $this->mTempPath );
317 }
318 } else {
319 $this->tempFileObj = null;
320 }
321 }
322
328 public function fetchFile() {
329 return Status::newGood();
330 }
331
337 public function canFetchFile() {
338 return Status::newGood();
339 }
340
345 public function isEmptyFile() {
346 return !$this->mFileSize;
347 }
348
353 public function getFileSize() {
354 return $this->mFileSize;
355 }
356
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'];
366 }
367 return FSFile::getSha1Base36FromPath( $this->mTempPath );
368 }
369
374 public function getRealPath( $srcPath ) {
375 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
376 if ( FileRepo::isVirtualUrl( $srcPath ) ) {
380 $tmpFile = $repo->getLocalCopy( $srcPath );
381 if ( $tmpFile ) {
382 $tmpFile->bind( $this ); // keep alive with $this
383 }
384 $path = $tmpFile ? $tmpFile->getPath() : false;
385 } else {
386 $path = $srcPath;
387 }
388
389 return $path;
390 }
391
409 public function verifyUpload() {
413 if ( $this->isEmptyFile() ) {
414 return [ 'status' => self::EMPTY_FILE ];
415 }
416
420 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
421 if ( $this->mFileSize > $maxSize ) {
422 return [
423 'status' => self::FILE_TOO_LARGE,
424 'max' => $maxSize,
425 ];
426 }
427
433 $verification = $this->verifyFile();
434 if ( $verification !== true ) {
435 return [
436 'status' => self::VERIFICATION_ERROR,
437 'details' => $verification
438 ];
439 }
440
444 $result = $this->validateName();
445 if ( $result !== true ) {
446 return $result;
447 }
448
449 return [ 'status' => self::OK ];
450 }
451
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;
464 }
465 if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
466 $result['finalExt'] = $this->mFinalExtension;
467 if ( count( $this->mBlackListedExtensions ) ) {
468 $result['blacklistedExt'] = $this->mBlackListedExtensions;
469 }
470 }
471
472 return $result;
473 }
474 $this->mDestName = $this->getLocalFile()->getName();
475
476 return true;
477 }
478
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 ];
495 }
496 }
497
498 return true;
499 }
500
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 ) {
512 return $status;
513 }
514
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 );
520 }
521 $mime = $this->mFileProps['mime'];
522
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 )
527 ) {
528 return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
529 }
530 }
531
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 ) {
537 return $svgStatus;
538 }
539 }
540 }
541
542 $handler = MediaHandler::getHandler( $mime );
543 if ( $handler ) {
544 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
545 if ( !$handlerStatus->isOK() ) {
546 $errors = $handlerStatus->getErrorsArray();
547
548 return reset( $errors );
549 }
550 }
551
552 $error = true;
553 $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
554 if ( $error !== true ) {
555 if ( !is_array( $error ) ) {
556 $error = [ $error ];
557 }
558 return $error;
559 }
560
561 wfDebug( __METHOD__ . ": all clear; passing." );
562
563 return true;
564 }
565
575 protected function verifyPartialFile() {
576 $config = MediaWikiServices::getInstance()->getMainConfig();
577 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
578 # getTitle() sets some internal parameters like $this->mFinalExtension
579 $this->getTitle();
580
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 );
586 }
587
588 # check MIME type, if desired
589 $mime = $this->mFileProps['file-mime'];
590 $status = $this->verifyMimeType( $mime );
591 if ( $status !== true ) {
592 return $status;
593 }
594
595 # check for htmlish code and javascript
596 if ( !$disableUploadScriptChecks ) {
597 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
598 return [ 'uploadscripted' ];
599 }
600 if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
601 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
602 if ( $svgStatus !== false ) {
603 return $svgStatus;
604 }
605 }
606 }
607
608 # Scan the uploaded file for viruses
609 $virus = self::detectVirus( $this->mTempPath );
610 if ( $virus ) {
611 return [ 'uploadvirus', $virus ];
612 }
613
614 return true;
615 }
616
622 public function zipEntryCallback( $entry ) {
623 $names = [ $entry['name'] ];
624
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 );
633 }
634
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;
639 }
640 }
641
651 public function verifyPermissions( Authority $performer ) {
652 return $this->verifyTitlePermissions( $performer );
653 }
654
666 public function verifyTitlePermissions( Authority $performer ) {
671 $nt = $this->getTitle();
672 if ( $nt === null ) {
673 return true;
674 }
675
676 $status = PermissionStatus::newEmpty();
677 $performer->authorizeWrite( 'edit', $nt, $status );
678 $performer->authorizeWrite( 'upload', $nt, $status );
679 if ( !$status->isGood() ) {
680 return $status->toLegacyErrorArray();
681 }
682
683 $overwriteError = $this->checkOverwrite( $performer );
684 if ( $overwriteError !== true ) {
685 return [ $overwriteError ];
686 }
687
688 return true;
689 }
690
700 public function checkWarnings( $user = null ) {
701 if ( $user === null ) {
702 // TODO check uses and hard deprecate
703 $user = RequestContext::getMain()->getUser();
704 }
705
706 $warnings = [];
707
708 $localFile = $this->getLocalFile();
709 $localFile->load( IDBAccessObject::READ_LATEST );
710 $filename = $localFile->getName();
711 $hash = $this->getTempFileSha1Base36();
712
713 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
714 if ( $badFileName !== null ) {
715 $warnings['badfilename'] = $badFileName;
716 }
717
718 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension );
719 if ( $unwantedFileExtensionDetails !== null ) {
720 $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
721 }
722
723 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
724 if ( $fileSizeWarnings ) {
725 $warnings = array_merge( $warnings, $fileSizeWarnings );
726 }
727
728 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
729 if ( $localFileExistsWarnings ) {
730 $warnings = array_merge( $warnings, $localFileExistsWarnings );
731 }
732
733 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
734 $warnings['was-deleted'] = $filename;
735 }
736
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 );
741 if ( $dupes ) {
742 $warnings['duplicate'] = $dupes;
743 }
744
745 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
746 if ( $archivedDupes !== null ) {
747 $warnings['duplicate-archive'] = $archivedDupes;
748 }
749
750 return $warnings;
751 }
752
764 public static function makeWarningsSerializable( $warnings ) {
765 array_walk_recursive( $warnings, static function ( &$param, $key ) {
766 if ( $param instanceof File ) {
767 $param = [
768 'fileName' => $param->getName(),
769 'timestamp' => $param->getTimestamp()
770 ];
771 } elseif ( is_object( $param ) ) {
772 throw new InvalidArgumentException(
773 'UploadBase::makeWarningsSerializable: ' .
774 'Unexpected object of class ' . get_class( $param ) );
775 }
776 } );
777 return $warnings;
778 }
779
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(
792 $value['fileName'],
793 [ 'time' => $value['timestamp'] ]
794 );
795 } else {
796 $warnings[$key] = self::unserializeWarnings( $value );
797 }
798 }
799 }
800 return $warnings;
801 }
802
812 private function checkBadFileName( $filename, $desiredFileName ) {
813 $comparableName = str_replace( ' ', '_', $desiredFileName );
814 $comparableName = Title::capitalize( $comparableName, NS_FILE );
815
816 if ( $desiredFileName != $filename && $comparableName != $filename ) {
817 return $filename;
818 }
819
820 return null;
821 }
822
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 ) ) {
838 return [
839 $fileExtension,
840 Message::listParam( $extensions, 'comma' ),
841 count( $extensions )
842 ];
843 }
844 }
845
846 return null;
847 }
848
854 private function checkFileSize( $fileSize ) {
855 $uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
856 ->get( MainConfigNames::UploadSizeWarning );
857
858 $warnings = [];
859
860 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
861 $warnings['large-file'] = [
862 Message::sizeParam( $uploadSizeWarning ),
863 Message::sizeParam( $fileSize ),
864 ];
865 }
866
867 if ( $fileSize == 0 ) {
868 $warnings['empty-file'] = true;
869 }
870
871 return $warnings;
872 }
873
880 private function checkLocalFileExists( LocalFile $localFile, $hash ) {
881 $warnings = [];
882
883 $exists = self::getExistsWarning( $localFile );
884 if ( $exists !== false ) {
885 $warnings['exists'] = $exists;
886
887 // check if file is an exact duplicate of current file version
888 if ( $hash !== false && $hash === $localFile->getSha1() ) {
889 $warnings['no-change'] = $localFile;
890 }
891
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;
897 }
898 }
899 }
900
901 return $warnings;
902 }
903
904 private function checkLocalFileWasDeleted( LocalFile $localFile ) {
905 return $localFile->wasDeleted() && !$localFile->exists();
906 }
907
914 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
915 if ( $hash === false ) {
916 return [];
917 }
918 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
919 $title = $this->getTitle();
920 foreach ( $dupes as $key => $dupe ) {
921 if (
922 ( $dupe instanceof LocalFile ) &&
923 $ignoreLocalDupes &&
924 $title->equals( $dupe->getTitle() )
925 ) {
926 unset( $dupes[$key] );
927 }
928 }
929
930 return $dupes;
931 }
932
940 private function checkAgainstArchiveDupes( $hash, Authority $performer ) {
941 if ( $hash === false ) {
942 return null;
943 }
944 $archivedFile = new ArchivedFile( null, 0, '', $hash );
945 if ( $archivedFile->getID() > 0 ) {
946 if ( $archivedFile->userCan( File::DELETED_FILE, $performer ) ) {
947 return $archivedFile->getName();
948 }
949 return '';
950 }
951
952 return null;
953 }
954
972 public function performUpload(
973 $comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
974 ) {
975 $this->getLocalFile()->load( IDBAccessObject::READ_LATEST );
976 $props = $this->mFileProps;
977
978 $error = null;
979 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
980 if ( $error ) {
981 if ( !is_array( $error ) ) {
982 $error = [ $error ];
983 }
984 return Status::newFatal( ...$error );
985 }
986
987 $status = $this->getLocalFile()->upload(
988 $this->mTempPath,
989 $comment,
990 $pageText !== false ? $pageText : '',
991 File::DELETE_SOURCE,
992 $props,
993 false,
994 $user,
995 $tags
996 );
997
998 if ( $status->isGood() ) {
999 if ( $watch ) {
1000 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
1001 $user,
1002 $this->getLocalFile()->getTitle(),
1003 $watchlistExpiry
1004 );
1005 }
1006 $this->getHookRunner()->onUploadComplete( $this );
1007
1008 $this->postProcessUpload();
1009 }
1010
1011 return $status;
1012 }
1013
1020 public function postProcessUpload() {
1021 }
1022
1029 public function getTitle() {
1030 if ( $this->mTitle !== false ) {
1031 return $this->mTitle;
1032 }
1033 if ( !is_string( $this->mDesiredDestName ) ) {
1034 $this->mTitleError = self::ILLEGAL_FILENAME;
1035 $this->mTitle = null;
1036
1037 return $this->mTitle;
1038 }
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.
1041 */
1042 $title = Title::newFromText( $this->mDesiredDestName );
1043 if ( $title && $title->getNamespace() === NS_FILE ) {
1044 $this->mFilteredName = $title->getDBkey();
1045 } else {
1046 $this->mFilteredName = $this->mDesiredDestName;
1047 }
1048
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;
1054
1055 return $this->mTitle;
1056 }
1057
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;
1069
1070 return $this->mTitle;
1071 }
1072 $this->mFilteredName = $nt->getDBkey();
1073
1078 [ $partname, $ext ] = self::splitExtensions( $this->mFilteredName );
1079
1080 if ( $ext !== [] ) {
1081 $this->mFinalExtension = trim( end( $ext ) );
1082 } else {
1083 $this->mFinalExtension = '';
1084
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;
1097
1098 # Fix up the other variables
1099 $this->mFilteredName .= ".{$this->mFinalExtension}";
1100 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1101 $ext = [ $this->mFinalExtension ];
1102 }
1103 }
1104 }
1105 }
1106
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 );
1113
1114 $badList = self::checkFileExtensionList( $ext, $prohibitedFileExtensions );
1115
1116 if ( $this->mFinalExtension == '' ) {
1117 $this->mTitleError = self::FILETYPE_MISSING;
1118 $this->mTitle = null;
1119
1120 return $this->mTitle;
1121 }
1122
1123 if ( $badList ||
1124 ( $checkFileExtensions && $strictFileExtensions &&
1125 !self::checkFileExtension( $this->mFinalExtension, $fileExtensions ) )
1126 ) {
1127 $this->mBlackListedExtensions = $badList;
1128 $this->mTitleError = self::FILETYPE_BADTYPE;
1129 $this->mTitle = null;
1130
1131 return $this->mTitle;
1132 }
1133
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()
1138 ) {
1139 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1140 $this->mTitle = null;
1141
1142 return $this->mTitle;
1143 }
1144
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];
1151 }
1152 }
1153
1154 if ( strlen( $partname ) < 1 ) {
1155 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1156 $this->mTitle = null;
1157
1158 return $this->mTitle;
1159 }
1160
1161 $this->mTitle = $nt;
1162
1163 return $this->mTitle;
1164 }
1165
1172 public function getLocalFile() {
1173 if ( $this->mLocalFile === null ) {
1174 $nt = $this->getTitle();
1175 $this->mLocalFile = $nt === null
1176 ? null
1177 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1178 }
1179
1180 return $this->mLocalFile;
1181 }
1182
1186 public function getStashFile() {
1187 return $this->mStashFile;
1188 }
1189
1202 public function tryStashFile( User $user, $isPartial = false ) {
1203 if ( !$isPartial ) {
1204 $error = $this->runUploadStashFileHook( $user );
1205 if ( $error ) {
1206 return Status::newFatal( ...$error );
1207 }
1208 }
1209 try {
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() );
1214 }
1215 }
1216
1221 protected function runUploadStashFileHook( User $user ) {
1222 $props = $this->mFileProps;
1223 $error = null;
1224 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1225 if ( $error && !is_array( $error ) ) {
1226 $error = [ $error ];
1227 }
1228 return $error;
1229 }
1230
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;
1243
1244 return $file;
1245 }
1246
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();
1256 }
1257 }
1258
1262 public function getTempPath() {
1263 return $this->mTempPath;
1264 }
1265
1275 public static function splitExtensions( $filename ) {
1276 $bits = explode( '.', $filename );
1277 $basename = array_shift( $bits );
1278
1279 return [ $basename, $bits ];
1280 }
1281
1289 public static function checkFileExtension( $ext, $list ) {
1290 return in_array( strtolower( $ext ?? '' ), $list, true );
1291 }
1292
1301 public static function checkFileExtensionList( $ext, $list ) {
1302 return array_intersect( array_map( 'strtolower', $ext ), $list );
1303 }
1304
1312 public static function verifyExtension( $mime, $extension ) {
1313 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1314
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" );
1319
1320 return true;
1321 }
1322
1323 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1324 "recognized extension '$extension', so probably invalid file" );
1325 return false;
1326 }
1327
1328 $match = $magic->isMatchingExtension( $extension, $mime );
1329
1330 if ( $match === null ) {
1331 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1332 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension" );
1333
1334 return false;
1335 }
1336
1337 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file" );
1338 return true;
1339 }
1340
1341 if ( $match ) {
1342 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file" );
1343
1345 return true;
1346 }
1347
1348 wfDebug( __METHOD__
1349 . ": mime type $mime mismatches file extension $extension, rejecting file" );
1350
1351 return false;
1352 }
1353
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.
1368
1369 if ( str_starts_with( $mime ?? '', 'text/' ) ) {
1370 $chunk = file_get_contents( $file );
1371 } else {
1372 $fp = fopen( $file, 'rb' );
1373 if ( !$fp ) {
1374 return false;
1375 }
1376 $chunk = fread( $fp, 1024 );
1377 fclose( $fp );
1378 }
1379
1380 $chunk = strtolower( $chunk );
1381
1382 if ( !$chunk ) {
1383 return false;
1384 }
1385
1386 # decode from UTF-16 if needed (could be used for obfuscation).
1387 if ( str_starts_with( $chunk, "\xfe\xff" ) ) {
1388 $enc = 'UTF-16BE';
1389 } elseif ( str_starts_with( $chunk, "\xff\xfe" ) ) {
1390 $enc = 'UTF-16LE';
1391 } else {
1392 $enc = null;
1393 }
1394
1395 if ( $enc !== null ) {
1396 AtEase::suppressWarnings();
1397 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1398 AtEase::restoreWarnings();
1399 }
1400
1401 $chunk = trim( $chunk );
1402
1404 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1405
1406 # check for HTML doctype
1407 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1408 return true;
1409 }
1410
1411 // Some browsers will interpret obscure xml encodings as UTF-8, while
1412 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1413 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
1414 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1415 return true;
1416 }
1417 }
1418
1419 // Quick check for HTML heuristics in old IE and Safari.
1420 //
1421 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1422 // don't need them all here as it can cause many false positives.
1423 //
1424 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1425 $tags = [
1426 '<body',
1427 '<head',
1428 '<html', # also in safari
1429 '<script', # also in safari
1430 ];
1431
1432 foreach ( $tags as $tag ) {
1433 if ( strpos( $chunk, $tag ) !== false ) {
1434 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1435
1436 return true;
1437 }
1438 }
1439
1440 /*
1441 * look for JavaScript
1442 */
1443
1444 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1445 $chunk = Sanitizer::decodeCharReferences( $chunk );
1446
1447 # look for script-types
1448 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1449 wfDebug( __METHOD__ . ": found script types" );
1450
1451 return true;
1452 }
1453
1454 # look for html-style script-urls
1455 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1456 wfDebug( __METHOD__ . ": found html-style script urls" );
1457
1458 return true;
1459 }
1460
1461 # look for css-style script-urls
1462 if ( preg_match( '!url\s*\‍(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1463 wfDebug( __METHOD__ . ": found css-style script urls" );
1464
1465 return true;
1466 }
1467
1468 wfDebug( __METHOD__ . ": no scripts found" );
1469
1470 return false;
1471 }
1472
1480 public static function checkXMLEncodingMissmatch( $file ) {
1481 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
1482 // should read the first 1445 bytes. Do 4096 bytes for good measure.
1483 // XML Spec says XML declaration if present must be first thing in file
1484 // other than BOM
1485 $contents = file_get_contents( $file, false, null, 0, 4096 );
1486 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1487
1488 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1489 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1490 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1491 ) {
1492 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1493
1494 return true;
1495 }
1496 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1497 // Start of XML declaration without an end in the first 4096 bytes
1498 // bytes. There shouldn't be a legitimate reason for this to happen.
1499 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1500
1501 return true;
1502 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1503 // EBCDIC encoded XML
1504 wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1505
1506 return true;
1507 }
1508
1509 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1510 // detect the encoding in case it specifies an encoding not allowed in self::SAFE_XML_ENCONDINGS
1511 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1512 foreach ( $attemptEncodings as $encoding ) {
1513 AtEase::suppressWarnings();
1514 $str = iconv( $encoding, 'UTF-8', $contents );
1515 AtEase::restoreWarnings();
1516 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1517 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1518 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1519 ) {
1520 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1521
1522 return true;
1523 }
1524 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1525 // Start of XML declaration without an end in the first 4096 bytes
1526 // bytes. There shouldn't be a legitimate reason for this to happen.
1527 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1528
1529 return true;
1530 }
1531 }
1532
1533 return false;
1534 }
1535
1541 protected function detectScriptInSvg( $filename, $partial ) {
1542 $this->mSVGNSError = false;
1543 $check = new XmlTypeCheck(
1544 $filename,
1545 [ $this, 'checkSvgScriptCallback' ],
1546 true,
1547 [
1548 'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1549 'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1550 ]
1551 );
1552 if ( $check->wellFormed !== true ) {
1553 // Invalid xml (T60553)
1554 // But only when non-partial (T67724)
1555 return $partial ? false : [ 'uploadinvalidxml' ];
1556 }
1557
1558 if ( $check->filterMatch ) {
1559 if ( $this->mSVGNSError ) {
1560 return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1561 }
1562 return $check->filterMatchType;
1563 }
1564
1565 return false;
1566 }
1567
1575 public static function checkSvgPICallback( $target, $data ) {
1576 // Don't allow external stylesheets (T59550)
1577 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1578 return [ 'upload-scripted-pi-callback' ];
1579 }
1580
1581 return false;
1582 }
1583
1596 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1597 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1598 // allow XHTML anyway.
1599 static $allowedDTDs = [
1600 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1601 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1602 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1603 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1604 // https://phabricator.wikimedia.org/T168856
1605 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1606 ];
1607 if ( $type !== 'PUBLIC'
1608 || !in_array( $systemId, $allowedDTDs )
1609 || !str_starts_with( $publicId, "-//W3C//" )
1610 ) {
1611 return [ 'upload-scripted-dtd' ];
1612 }
1613 return false;
1614 }
1615
1623 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1624 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1625
1626 // We specifically don't include:
1627 // http://www.w3.org/1999/xhtml (T62771)
1628 static $validNamespaces = [
1629 '',
1630 'adobe:ns:meta/',
1631 'http://creativecommons.org/ns#',
1632 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1633 'http://ns.adobe.com/adobeillustrator/10.0/',
1634 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1635 'http://ns.adobe.com/extensibility/1.0/',
1636 'http://ns.adobe.com/flows/1.0/',
1637 'http://ns.adobe.com/illustrator/1.0/',
1638 'http://ns.adobe.com/imagereplacement/1.0/',
1639 'http://ns.adobe.com/pdf/1.3/',
1640 'http://ns.adobe.com/photoshop/1.0/',
1641 'http://ns.adobe.com/saveforweb/1.0/',
1642 'http://ns.adobe.com/variables/1.0/',
1643 'http://ns.adobe.com/xap/1.0/',
1644 'http://ns.adobe.com/xap/1.0/g/',
1645 'http://ns.adobe.com/xap/1.0/g/img/',
1646 'http://ns.adobe.com/xap/1.0/mm/',
1647 'http://ns.adobe.com/xap/1.0/rights/',
1648 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1649 'http://ns.adobe.com/xap/1.0/stype/font#',
1650 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1651 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1652 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1653 'http://ns.adobe.com/xap/1.0/t/pg/',
1654 'http://purl.org/dc/elements/1.1/',
1655 'http://purl.org/dc/elements/1.1',
1656 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1657 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1658 'http://taptrix.com/inkpad/svg_extensions',
1659 'http://web.resource.org/cc/',
1660 'http://www.freesoftware.fsf.org/bkchem/cdml',
1661 'http://www.inkscape.org/namespaces/inkscape',
1662 'http://www.opengis.net/gml',
1663 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1664 'http://www.w3.org/2000/svg',
1665 'http://www.w3.org/tr/rec-rdf-syntax/',
1666 'http://www.w3.org/2000/01/rdf-schema#',
1667 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1668 ];
1669
1670 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1671 // This is nasty but harmless. (T144827)
1672 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1673
1674 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1675 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1677 $this->mSVGNSError = $namespace;
1678
1679 return true;
1680 }
1681
1682 // check for elements that can contain javascript
1683 if ( $strippedElement === 'script' ) {
1684 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1685
1686 return [ 'uploaded-script-svg', $strippedElement ];
1687 }
1688
1689 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1690 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1691 if ( $strippedElement === 'handler' ) {
1692 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1693
1694 return [ 'uploaded-script-svg', $strippedElement ];
1695 }
1696
1697 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1698 if ( $strippedElement === 'stylesheet' ) {
1699 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1700
1701 return [ 'uploaded-script-svg', $strippedElement ];
1702 }
1703
1704 // Block iframes, in case they pass the namespace check
1705 if ( $strippedElement === 'iframe' ) {
1706 wfDebug( __METHOD__ . ": iframe in uploaded file." );
1707
1708 return [ 'uploaded-script-svg', $strippedElement ];
1709 }
1710
1711 // Check <style> css
1712 if ( $strippedElement === 'style'
1713 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1714 ) {
1715 wfDebug( __METHOD__ . ": hostile css in style element." );
1716
1717 return [ 'uploaded-hostile-svg' ];
1718 }
1719
1720 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1721 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1722
1723 foreach ( $attribs as $attrib => $value ) {
1724 // If attributeNamespace is '', it is relative to its element's namespace
1725 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
1726 $value = strtolower( $value );
1727
1728 if ( !(
1729 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1730 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1731 $attributeNamespace === ''
1732 ) && str_starts_with( $stripped, 'on' )
1733 ) {
1734 wfDebug( __METHOD__
1735 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1736
1737 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1738 }
1739
1740 // Do not allow relative links, or unsafe url schemas.
1741 // For <a> tags, only data:, http: and https: and same-document
1742 // fragment links are allowed.
1743 // For all other tags, only 'data:' and fragments (#) are allowed.
1744 if (
1745 $stripped === 'href'
1746 && $value !== ''
1747 && !str_starts_with( $value, 'data:' )
1748 && !str_starts_with( $value, '#' )
1749 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1750 ) {
1751 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1752 . "'$attrib'='$value' in uploaded file." );
1753
1754 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1755 }
1756
1757 // Only allow 'data:\' targets that should be safe.
1758 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1759 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1760 // RFC2397 parameters.
1761 // This is only slightly slower than (;[\w;]+)*.
1762 // phpcs:ignore Generic.Files.LineLength
1763 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1764
1765 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1766 wfDebug( __METHOD__ . ": Found href to allow listed data: uri "
1767 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1768 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1769 }
1770 }
1771
1772 // Change href with animate from (http://html5sec.org/#137).
1773 if ( $stripped === 'attributename'
1774 && $strippedElement === 'animate'
1775 && $this->stripXmlNamespace( $value ) === 'href'
1776 ) {
1777 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1778 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1779
1780 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1781 }
1782
1783 // Use set/animate to add event-handler attribute to parent.
1784 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
1785 && $stripped === 'attributename'
1786 && str_starts_with( $value, 'on' )
1787 ) {
1788 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1789 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1790
1791 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1792 }
1793
1794 // use set to add href attribute to parent element.
1795 if ( $strippedElement === 'set'
1796 && $stripped === 'attributename'
1797 && str_contains( $value, 'href' )
1798 ) {
1799 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1800
1801 return [ 'uploaded-setting-href-svg' ];
1802 }
1803
1804 // use set to add a remote / data / script target to an element.
1805 if ( $strippedElement === 'set'
1806 && $stripped === 'to'
1807 && preg_match( '!(http|https|data|script):!im', $value )
1808 ) {
1809 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1810
1811 return [ 'uploaded-wrong-setting-svg', $value ];
1812 }
1813
1814 // use handler attribute with remote / data / script.
1815 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1816 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1817 . "'$attrib'='$value' in uploaded file." );
1818
1819 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1820 }
1821
1822 // use CSS styles to bring in remote code.
1823 if ( $stripped === 'style'
1824 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1825 ) {
1826 wfDebug( __METHOD__ . ": Found svg setting a style with "
1827 . "remote url '$attrib'='$value' in uploaded file." );
1828 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1829 }
1830
1831 // Several attributes can include css, css character escaping isn't allowed.
1832 if ( in_array( $stripped, $cssAttrs, true )
1833 && self::checkCssFragment( $value )
1834 ) {
1835 wfDebug( __METHOD__ . ": Found svg setting a style with "
1836 . "remote url '$attrib'='$value' in uploaded file." );
1837 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1838 }
1839
1840 // image filters can pull in url, which could be svg that executes scripts.
1841 // Only allow url( "#foo" ).
1842 // Do not allow url( http://example.com )
1843 if ( $strippedElement === 'image'
1844 && $stripped === 'filter'
1845 && preg_match( '!url\s*\‍(\s*["\']?[^#]!im', $value )
1846 ) {
1847 wfDebug( __METHOD__ . ": Found image filter with url: "
1848 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1849
1850 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1851 }
1852 }
1853
1854 return false; // No scripts detected
1855 }
1856
1863 private static function checkCssFragment( $value ) {
1864 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1865 if ( stripos( $value, '@import' ) !== false ) {
1866 return true;
1867 }
1868
1869 # We allow @font-face to embed fonts with data: urls, so we snip the string
1870 # 'url' out so that this case won't match when we check for urls below
1871 $pattern = '!(@font-face\s*{[^}]*src:)url(\‍("data:;base64,)!im';
1872 $value = preg_replace( $pattern, '$1$2', $value );
1873
1874 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1875 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1876 # Expression and -o-link don't seem to work either, but filtering them here in case.
1877 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1878 # but not local ones such as url("#..., url('#..., url(#....
1879 if ( preg_match( '!expression
1880 | -o-link\s*:
1881 | -o-link-source\s*:
1882 | -o-replace\s*:!imx', $value ) ) {
1883 return true;
1884 }
1885
1886 if ( preg_match_all(
1887 "!(\s*(url|image|image-set)\s*\‍(\s*[\"']?\s*[^#]+.*?\‍))!sim",
1888 $value,
1889 $matches
1890 ) !== 0
1891 ) {
1892 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1893 foreach ( $matches[1] as $match ) {
1894 if ( !preg_match( "!\s*(url|image|image-set)\s*\‍(\s*(#|'#|\"#)!im", $match ) ) {
1895 return true;
1896 }
1897 }
1898 }
1899
1900 return (bool)preg_match( '/[\000-\010\013\016-\037\177]/', $value );
1901 }
1902
1908 private static function splitXmlNamespace( $element ) {
1909 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1910 $parts = explode( ':', strtolower( $element ) );
1911 $name = array_pop( $parts );
1912 $ns = implode( ':', $parts );
1913
1914 return [ $ns, $name ];
1915 }
1916
1921 private function stripXmlNamespace( $element ) {
1922 // 'http://www.w3.org/2000/svg:script' -> 'script'
1923 return self::splitXmlNamespace( $element )[1];
1924 }
1925
1936 public static function detectVirus( $file ) {
1937 global $wgOut;
1938 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1939 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1940 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1941 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1942 if ( !$antivirus ) {
1943 wfDebug( __METHOD__ . ": virus scanner disabled" );
1944
1945 return null;
1946 }
1947
1948 if ( !$antivirusSetup[$antivirus] ) {
1949 wfDebug( __METHOD__ . ": unknown virus scanner: {$antivirus}" );
1950 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1951 [ 'virus-badscanner', $antivirus ] );
1952
1953 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1954 }
1955
1956 # look up scanner configuration
1957 $command = $antivirusSetup[$antivirus]['command'];
1958 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1959 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
1960
1961 if ( !str_contains( $command, "%f" ) ) {
1962 # simple pattern: append file to scan
1963 $command .= " " . Shell::escape( $file );
1964 } else {
1965 # complex pattern: replace "%f" with file to scan
1966 $command = str_replace( "%f", Shell::escape( $file ), $command );
1967 }
1968
1969 wfDebug( __METHOD__ . ": running virus scan: $command " );
1970
1971 # execute virus scanner
1972 $exitCode = false;
1973
1974 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1975 # that does not seem to be worth the pain.
1976 # Ask me (Duesentrieb) about it if it's ever needed.
1977 $output = wfShellExecWithStderr( $command, $exitCode );
1978
1979 # map exit code to AV_xxx constants.
1980 $mappedCode = $exitCode;
1981 if ( $exitCodeMap ) {
1982 if ( isset( $exitCodeMap[$exitCode] ) ) {
1983 $mappedCode = $exitCodeMap[$exitCode];
1984 } elseif ( isset( $exitCodeMap["*"] ) ) {
1985 $mappedCode = $exitCodeMap["*"];
1986 }
1987 }
1988
1989 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1990 # so we need the strict equalities === and thus can't use a switch here
1991 if ( $mappedCode === AV_SCAN_FAILED ) {
1992 # scan failed (code was mapped to false by $exitCodeMap)
1993 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1994
1995 $output = $antivirusRequired
1996 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1997 : null;
1998 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1999 # scan failed because filetype is unknown (probably immune)
2000 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
2001 $output = null;
2002 } elseif ( $mappedCode === AV_NO_VIRUS ) {
2003 # no virus found
2004 wfDebug( __METHOD__ . ": file passed virus scan." );
2005 $output = false;
2006 } else {
2007 $output = trim( $output );
2008
2009 if ( !$output ) {
2010 $output = true; # if there's no output, return true
2011 } elseif ( $msgPattern ) {
2012 $groups = [];
2013 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
2014 $output = $groups[1];
2015 }
2016 }
2017
2018 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
2019 }
2020
2021 return $output;
2022 }
2023
2032 private function checkOverwrite( Authority $performer ) {
2033 // First check whether the local file can be overwritten
2034 $file = $this->getLocalFile();
2035 $file->load( IDBAccessObject::READ_LATEST );
2036 if ( $file->exists() ) {
2037 if ( !self::userCanReUpload( $performer, $file ) ) {
2038 return [ 'fileexists-forbidden', $file->getName() ];
2039 }
2040
2041 return true;
2042 }
2043
2044 $services = MediaWikiServices::getInstance();
2045
2046 /* Check shared conflicts: if the local file does not exist, but
2047 * RepoGroup::findFile finds a file, it exists in a shared repository.
2048 */
2049 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2050 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
2051 return [ 'fileexists-shared-forbidden', $file->getName() ];
2052 }
2053
2054 return true;
2055 }
2056
2064 public static function userCanReUpload( Authority $performer, File $img ) {
2065 if ( $performer->isAllowed( 'reupload' ) ) {
2066 return true; // non-conditional
2067 }
2068
2069 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2070 return false;
2071 }
2072
2073 if ( !( $img instanceof LocalFile ) ) {
2074 return false;
2075 }
2076
2077 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2078 }
2079
2091 public static function getExistsWarning( $file ) {
2092 if ( $file->exists() ) {
2093 return [ 'warning' => 'exists', 'file' => $file ];
2094 }
2095
2096 if ( $file->getTitle()->getArticleID() ) {
2097 return [ 'warning' => 'page-exists', 'file' => $file ];
2098 }
2099
2100 $n = strrpos( $file->getName(), '.' );
2101 if ( $n > 0 ) {
2102 $partname = substr( $file->getName(), 0, $n );
2103 $extension = substr( $file->getName(), $n + 1 );
2104 } else {
2105 $partname = $file->getName();
2106 $extension = '';
2107 }
2108 $normalizedExtension = File::normalizeExtension( $extension );
2109 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2110
2111 if ( $normalizedExtension != $extension ) {
2112 // We're not using the normalized form of the extension.
2113 // Normal form is lowercase, using most common of alternate
2114 // extensions (e.g. 'jpg' rather than 'JPEG').
2115
2116 // Check for another file using the normalized form...
2117 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2118 $file_lc = $localRepo->newFile( $nt_lc );
2119
2120 if ( $file_lc->exists() ) {
2121 return [
2122 'warning' => 'exists-normalized',
2123 'file' => $file,
2124 'normalizedFile' => $file_lc
2125 ];
2126 }
2127 }
2128
2129 // Check for files with the same name but a different extension
2130 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2131 if ( count( $similarFiles ) ) {
2132 return [
2133 'warning' => 'exists-normalized',
2134 'file' => $file,
2135 'normalizedFile' => $similarFiles[0],
2136 ];
2137 }
2138
2139 if ( self::isThumbName( $file->getName() ) ) {
2140 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2141 $nt_thb = Title::newFromText(
2142 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2143 NS_FILE
2144 );
2145 $file_thb = $localRepo->newFile( $nt_thb );
2146 if ( $file_thb->exists() ) {
2147 return [
2148 'warning' => 'thumb',
2149 'file' => $file,
2150 'thumbFile' => $file_thb
2151 ];
2152 }
2153
2154 // The file does not exist, but we just don't like the name
2155 return [
2156 'warning' => 'thumb-name',
2157 'file' => $file,
2158 'thumbFile' => $file_thb
2159 ];
2160 }
2161
2162 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2163 if ( str_starts_with( $partname, $prefix ) ) {
2164 return [
2165 'warning' => 'bad-prefix',
2166 'file' => $file,
2167 'prefix' => $prefix
2168 ];
2169 }
2170 }
2171
2172 return false;
2173 }
2174
2180 public static function isThumbName( $filename ) {
2181 $n = strrpos( $filename, '.' );
2182 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2183
2184 return (
2185 substr( $partname, 3, 3 ) === 'px-' ||
2186 substr( $partname, 2, 3 ) === 'px-'
2187 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2188 }
2189
2195 public static function getFilenamePrefixBlacklist() {
2196 $list = [];
2197 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2198 if ( !$message->isDisabled() ) {
2199 $lines = explode( "\n", $message->plain() );
2200 foreach ( $lines as $line ) {
2201 // Remove comment lines
2202 $comment = substr( trim( $line ), 0, 1 );
2203 if ( $comment === '#' || $comment == '' ) {
2204 continue;
2205 }
2206 // Remove additional comments after a prefix
2207 $comment = strpos( $line, '#' );
2208 if ( $comment > 0 ) {
2209 $line = substr( $line, 0, $comment - 1 );
2210 }
2211 $list[] = trim( $line );
2212 }
2213 }
2214
2215 return $list;
2216 }
2217
2227 public function getImageInfo( $result = null ) {
2228 $apiUpload = ApiUpload::getDummyInstance();
2229 return $apiUpload->getUploadImageInfo( $this );
2230 }
2231
2236 public function convertVerifyErrorToStatus( $error ) {
2237 $code = $error['status'];
2238 unset( $code['status'] );
2239
2240 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2241 }
2242
2250 public static function getMaxUploadSize( $forType = null ) {
2251 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2252
2253 if ( is_array( $maxUploadSize ) ) {
2254 return $maxUploadSize[$forType] ?? $maxUploadSize['*'];
2255 }
2256 return intval( $maxUploadSize );
2257 }
2258
2266 public static function getMaxPhpUploadSize() {
2267 $phpMaxFileSize = wfShorthandToInteger(
2268 ini_get( 'upload_max_filesize' ),
2269 PHP_INT_MAX
2270 );
2271 $phpMaxPostSize = wfShorthandToInteger(
2272 ini_get( 'post_max_size' ),
2273 PHP_INT_MAX
2274 ) ?: PHP_INT_MAX;
2275 return min( $phpMaxFileSize, $phpMaxPostSize );
2276 }
2277
2289 public static function getSessionStatus( UserIdentity $user, $statusKey ) {
2290 $store = self::getUploadSessionStore();
2291 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2292
2293 return $store->get( $key );
2294 }
2295
2308 public static function setSessionStatus( UserIdentity $user, $statusKey, $value ) {
2309 $store = self::getUploadSessionStore();
2310 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2311 $logger = LoggerFactory::getInstance( 'upload' );
2312
2313 if ( is_array( $value ) && ( $value['result'] ?? '' ) === 'Failure' ) {
2314 $logger->info( 'Upload session {key} for {user} set to failure {status} at {stage}',
2315 [
2316 'result' => $value['result'] ?? '',
2317 'stage' => $value['stage'] ?? 'unknown',
2318 'user' => $user->getName(),
2319 'status' => (string)( $value['status'] ?? '-' ),
2320 'filekey' => $value['filekey'] ?? '',
2321 'key' => $statusKey
2322 ]
2323 );
2324 } elseif ( is_array( $value ) ) {
2325 $logger->debug( 'Upload session {key} for {user} changed {status} at {stage}',
2326 [
2327 'result' => $value['result'] ?? '',
2328 'stage' => $value['stage'] ?? 'unknown',
2329 'user' => $user->getName(),
2330 'status' => (string)( $value['status'] ?? '-' ),
2331 'filekey' => $value['filekey'] ?? '',
2332 'key' => $statusKey
2333 ]
2334 );
2335 } else {
2336 $logger->debug( "Upload session {key} deleted for {user}",
2337 [
2338 'value' => $value,
2339 'key' => $statusKey,
2340 'user' => $user->getName()
2341 ]
2342 );
2343 }
2344
2345 if ( $value === false ) {
2346 $store->delete( $key );
2347 } else {
2348 $store->set( $key, $value, $store::TTL_DAY );
2349 }
2350 }
2351
2358 private static function getUploadSessionKey( BagOStuff $store, UserIdentity $user, $statusKey ) {
2359 return $store->makeKey(
2360 'uploadstatus',
2361 $user->isRegistered() ? $user->getId() : md5( $user->getName() ),
2362 $statusKey
2363 );
2364 }
2365
2369 private static function getUploadSessionStore() {
2370 return MediaWikiServices::getInstance()->getMainObjectStash();
2371 }
2372}
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:541
Deleted file in the 'filearchive' table.
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition FileRepo.php:293
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
getName()
Return the name of this file.
Definition File.php:347
wasDeleted()
Was this file ever deleted from the wiki?
Definition File.php:2112
Local file in the wiki's own database.
Definition LocalFile.php:75
exists()
canRender inherited
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
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.
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:156
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:1034
internal since 1.36
Definition User.php:94
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.
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]].
const OVERWRITE_EXISTING_FILE
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...
string null $mDestName
string[] $mBlackListedExtensions
static isAllowed(Authority $performer)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
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.
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.
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.
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:89
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