MediaWiki master
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 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1397 }
1398
1399 $chunk = trim( $chunk );
1400
1402 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1403
1404 # check for HTML doctype
1405 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1406 return true;
1407 }
1408
1409 // Some browsers will interpret obscure xml encodings as UTF-8, while
1410 // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1411 if ( $extension === 'svg' || str_starts_with( $mime ?? '', 'image/svg' ) ) {
1412 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1413 return true;
1414 }
1415 }
1416
1417 // Quick check for HTML heuristics in old IE and Safari.
1418 //
1419 // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1420 // don't need them all here as it can cause many false positives.
1421 //
1422 // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1423 $tags = [
1424 '<body',
1425 '<head',
1426 '<html', # also in safari
1427 '<script', # also in safari
1428 ];
1429
1430 foreach ( $tags as $tag ) {
1431 if ( strpos( $chunk, $tag ) !== false ) {
1432 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1433
1434 return true;
1435 }
1436 }
1437
1438 /*
1439 * look for JavaScript
1440 */
1441
1442 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1443 $chunk = Sanitizer::decodeCharReferences( $chunk );
1444
1445 # look for script-types
1446 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!im', $chunk ) ) {
1447 wfDebug( __METHOD__ . ": found script types" );
1448
1449 return true;
1450 }
1451
1452 # look for html-style script-urls
1453 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1454 wfDebug( __METHOD__ . ": found html-style script urls" );
1455
1456 return true;
1457 }
1458
1459 # look for css-style script-urls
1460 if ( preg_match( '!url\s*\‍(\s*[\'"]?\s*(?:ecma|java)script:!im', $chunk ) ) {
1461 wfDebug( __METHOD__ . ": found css-style script urls" );
1462
1463 return true;
1464 }
1465
1466 wfDebug( __METHOD__ . ": no scripts found" );
1467
1468 return false;
1469 }
1470
1478 public static function checkXMLEncodingMissmatch( $file ) {
1479 // https://mimesniff.spec.whatwg.org/#resource-header says browsers
1480 // should read the first 1445 bytes. Do 4096 bytes for good measure.
1481 // XML Spec says XML declaration if present must be first thing in file
1482 // other than BOM
1483 $contents = file_get_contents( $file, false, null, 0, 4096 );
1484 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1485
1486 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1487 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1488 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1489 ) {
1490 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1491
1492 return true;
1493 }
1494 } elseif ( preg_match( "!<\?xml\b!i", $contents ) ) {
1495 // Start of XML declaration without an end in the first 4096 bytes
1496 // bytes. There shouldn't be a legitimate reason for this to happen.
1497 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1498
1499 return true;
1500 } elseif ( str_starts_with( $contents, "\x4C\x6F\xA7\x94" ) ) {
1501 // EBCDIC encoded XML
1502 wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1503
1504 return true;
1505 }
1506
1507 // It's possible the file is encoded with multibyte encoding, so re-encode attempt to
1508 // detect the encoding in case it specifies an encoding not allowed in self::SAFE_XML_ENCONDINGS
1509 $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1510 foreach ( $attemptEncodings as $encoding ) {
1511 AtEase::suppressWarnings();
1512 $str = iconv( $encoding, 'UTF-8', $contents );
1513 AtEase::restoreWarnings();
1514 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1515 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1516 && !in_array( strtoupper( $encMatch[1] ), self::SAFE_XML_ENCONDINGS )
1517 ) {
1518 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1519
1520 return true;
1521 }
1522 } elseif ( $str != '' && preg_match( "!<\?xml\b!i", $str ) ) {
1523 // Start of XML declaration without an end in the first 4096 bytes
1524 // bytes. There shouldn't be a legitimate reason for this to happen.
1525 wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1526
1527 return true;
1528 }
1529 }
1530
1531 return false;
1532 }
1533
1539 protected function detectScriptInSvg( $filename, $partial ) {
1540 $this->mSVGNSError = false;
1541 $check = new XmlTypeCheck(
1542 $filename,
1543 [ $this, 'checkSvgScriptCallback' ],
1544 true,
1545 [
1546 'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1547 'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1548 ]
1549 );
1550 if ( $check->wellFormed !== true ) {
1551 // Invalid xml (T60553)
1552 // But only when non-partial (T67724)
1553 return $partial ? false : [ 'uploadinvalidxml' ];
1554 }
1555
1556 if ( $check->filterMatch ) {
1557 if ( $this->mSVGNSError ) {
1558 return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1559 }
1560 return $check->filterMatchType;
1561 }
1562
1563 return false;
1564 }
1565
1573 public static function checkSvgPICallback( $target, $data ) {
1574 // Don't allow external stylesheets (T59550)
1575 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1576 return [ 'upload-scripted-pi-callback' ];
1577 }
1578
1579 return false;
1580 }
1581
1594 public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1595 // This doesn't include the XHTML+MathML+SVG doctype since we don't
1596 // allow XHTML anyway.
1597 static $allowedDTDs = [
1598 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1599 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1600 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1601 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1602 // https://phabricator.wikimedia.org/T168856
1603 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1604 ];
1605 if ( $type !== 'PUBLIC'
1606 || !in_array( $systemId, $allowedDTDs )
1607 || !str_starts_with( $publicId, "-//W3C//" )
1608 ) {
1609 return [ 'upload-scripted-dtd' ];
1610 }
1611 return false;
1612 }
1613
1621 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1622 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1623
1624 // We specifically don't include:
1625 // http://www.w3.org/1999/xhtml (T62771)
1626 static $validNamespaces = [
1627 '',
1628 'adobe:ns:meta/',
1629 'http://creativecommons.org/ns#',
1630 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1631 'http://ns.adobe.com/adobeillustrator/10.0/',
1632 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1633 'http://ns.adobe.com/extensibility/1.0/',
1634 'http://ns.adobe.com/flows/1.0/',
1635 'http://ns.adobe.com/illustrator/1.0/',
1636 'http://ns.adobe.com/imagereplacement/1.0/',
1637 'http://ns.adobe.com/pdf/1.3/',
1638 'http://ns.adobe.com/photoshop/1.0/',
1639 'http://ns.adobe.com/saveforweb/1.0/',
1640 'http://ns.adobe.com/variables/1.0/',
1641 'http://ns.adobe.com/xap/1.0/',
1642 'http://ns.adobe.com/xap/1.0/g/',
1643 'http://ns.adobe.com/xap/1.0/g/img/',
1644 'http://ns.adobe.com/xap/1.0/mm/',
1645 'http://ns.adobe.com/xap/1.0/rights/',
1646 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1647 'http://ns.adobe.com/xap/1.0/stype/font#',
1648 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1649 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1650 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1651 'http://ns.adobe.com/xap/1.0/t/pg/',
1652 'http://purl.org/dc/elements/1.1/',
1653 'http://purl.org/dc/elements/1.1',
1654 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1655 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1656 'http://taptrix.com/inkpad/svg_extensions',
1657 'http://web.resource.org/cc/',
1658 'http://www.freesoftware.fsf.org/bkchem/cdml',
1659 'http://www.inkscape.org/namespaces/inkscape',
1660 'http://www.opengis.net/gml',
1661 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1662 'http://www.w3.org/2000/svg',
1663 'http://www.w3.org/tr/rec-rdf-syntax/',
1664 'http://www.w3.org/2000/01/rdf-schema#',
1665 'http://www.w3.org/2000/02/svg/testsuite/description/', // https://phabricator.wikimedia.org/T278044
1666 ];
1667
1668 // Inkscape mangles namespace definitions created by Adobe Illustrator.
1669 // This is nasty but harmless. (T144827)
1670 $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1671
1672 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1673 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1675 $this->mSVGNSError = $namespace;
1676
1677 return true;
1678 }
1679
1680 // check for elements that can contain javascript
1681 if ( $strippedElement === 'script' ) {
1682 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1683
1684 return [ 'uploaded-script-svg', $strippedElement ];
1685 }
1686
1687 // e.g., <svg xmlns="http://www.w3.org/2000/svg">
1688 // <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1689 if ( $strippedElement === 'handler' ) {
1690 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1691
1692 return [ 'uploaded-script-svg', $strippedElement ];
1693 }
1694
1695 // SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1696 if ( $strippedElement === 'stylesheet' ) {
1697 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1698
1699 return [ 'uploaded-script-svg', $strippedElement ];
1700 }
1701
1702 // Block iframes, in case they pass the namespace check
1703 if ( $strippedElement === 'iframe' ) {
1704 wfDebug( __METHOD__ . ": iframe in uploaded file." );
1705
1706 return [ 'uploaded-script-svg', $strippedElement ];
1707 }
1708
1709 // Check <style> css
1710 if ( $strippedElement === 'style'
1711 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1712 ) {
1713 wfDebug( __METHOD__ . ": hostile css in style element." );
1714
1715 return [ 'uploaded-hostile-svg' ];
1716 }
1717
1718 static $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1719 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1720
1721 foreach ( $attribs as $attrib => $value ) {
1722 // If attributeNamespace is '', it is relative to its element's namespace
1723 [ $attributeNamespace, $stripped ] = self::splitXmlNamespace( $attrib );
1724 $value = strtolower( $value );
1725
1726 if ( !(
1727 // Inkscape element's have valid attribs that start with on and are safe, fail all others
1728 $namespace === 'http://www.inkscape.org/namespaces/inkscape' &&
1729 $attributeNamespace === ''
1730 ) && str_starts_with( $stripped, 'on' )
1731 ) {
1732 wfDebug( __METHOD__
1733 . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1734
1735 return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1736 }
1737
1738 // Do not allow relative links, or unsafe url schemas.
1739 // For <a> tags, only data:, http: and https: and same-document
1740 // fragment links are allowed.
1741 // For all other tags, only 'data:' and fragments (#) are allowed.
1742 if (
1743 $stripped === 'href'
1744 && $value !== ''
1745 && !str_starts_with( $value, 'data:' )
1746 && !str_starts_with( $value, '#' )
1747 && !( $strippedElement === 'a' && preg_match( '!^https?://!i', $value ) )
1748 ) {
1749 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1750 . "'$attrib'='$value' in uploaded file." );
1751
1752 return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1753 }
1754
1755 // Only allow 'data:\' targets that should be safe.
1756 // This prevents vectors like image/svg, text/xml, application/xml, and text/html, which can contain scripts
1757 if ( $stripped === 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1758 // RFC2397 parameters.
1759 // This is only slightly slower than (;[\w;]+)*.
1760 // phpcs:ignore Generic.Files.LineLength
1761 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1762
1763 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1764 wfDebug( __METHOD__ . ": Found href to allow listed data: uri "
1765 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1766 return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1767 }
1768 }
1769
1770 // Change href with animate from (http://html5sec.org/#137).
1771 if ( $stripped === 'attributename'
1772 && $strippedElement === 'animate'
1773 && $this->stripXmlNamespace( $value ) === 'href'
1774 ) {
1775 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1776 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1777
1778 return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1779 }
1780
1781 // Use set/animate to add event-handler attribute to parent.
1782 if ( ( $strippedElement === 'set' || $strippedElement === 'animate' )
1783 && $stripped === 'attributename'
1784 && str_starts_with( $value, 'on' )
1785 ) {
1786 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1787 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1788
1789 return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1790 }
1791
1792 // use set to add href attribute to parent element.
1793 if ( $strippedElement === 'set'
1794 && $stripped === 'attributename'
1795 && str_contains( $value, 'href' )
1796 ) {
1797 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1798
1799 return [ 'uploaded-setting-href-svg' ];
1800 }
1801
1802 // use set to add a remote / data / script target to an element.
1803 if ( $strippedElement === 'set'
1804 && $stripped === 'to'
1805 && preg_match( '!(http|https|data|script):!im', $value )
1806 ) {
1807 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1808
1809 return [ 'uploaded-wrong-setting-svg', $value ];
1810 }
1811
1812 // use handler attribute with remote / data / script.
1813 if ( $stripped === 'handler' && preg_match( '!(http|https|data|script):!im', $value ) ) {
1814 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1815 . "'$attrib'='$value' in uploaded file." );
1816
1817 return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1818 }
1819
1820 // use CSS styles to bring in remote code.
1821 if ( $stripped === 'style'
1822 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1823 ) {
1824 wfDebug( __METHOD__ . ": Found svg setting a style with "
1825 . "remote url '$attrib'='$value' in uploaded file." );
1826 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1827 }
1828
1829 // Several attributes can include css, css character escaping isn't allowed.
1830 if ( in_array( $stripped, $cssAttrs, true )
1831 && self::checkCssFragment( $value )
1832 ) {
1833 wfDebug( __METHOD__ . ": Found svg setting a style with "
1834 . "remote url '$attrib'='$value' in uploaded file." );
1835 return [ 'uploaded-remote-url-svg', $attrib, $value ];
1836 }
1837
1838 // image filters can pull in url, which could be svg that executes scripts.
1839 // Only allow url( "#foo" ).
1840 // Do not allow url( http://example.com )
1841 if ( $strippedElement === 'image'
1842 && $stripped === 'filter'
1843 && preg_match( '!url\s*\‍(\s*["\']?[^#]!im', $value )
1844 ) {
1845 wfDebug( __METHOD__ . ": Found image filter with url: "
1846 . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1847
1848 return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1849 }
1850 }
1851
1852 return false; // No scripts detected
1853 }
1854
1861 private static function checkCssFragment( $value ) {
1862 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1863 if ( stripos( $value, '@import' ) !== false ) {
1864 return true;
1865 }
1866
1867 # We allow @font-face to embed fonts with data: urls, so we snip the string
1868 # 'url' out so that this case won't match when we check for urls below
1869 $pattern = '!(@font-face\s*{[^}]*src:)url(\‍("data:;base64,)!im';
1870 $value = preg_replace( $pattern, '$1$2', $value );
1871
1872 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1873 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1874 # Expression and -o-link don't seem to work either, but filtering them here in case.
1875 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1876 # but not local ones such as url("#..., url('#..., url(#....
1877 if ( preg_match( '!expression
1878 | -o-link\s*:
1879 | -o-link-source\s*:
1880 | -o-replace\s*:!imx', $value ) ) {
1881 return true;
1882 }
1883
1884 if ( preg_match_all(
1885 "!(\s*(url|image|image-set)\s*\‍(\s*[\"']?\s*[^#]+.*?\‍))!sim",
1886 $value,
1887 $matches
1888 ) !== 0
1889 ) {
1890 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1891 foreach ( $matches[1] as $match ) {
1892 if ( !preg_match( "!\s*(url|image|image-set)\s*\‍(\s*(#|'#|\"#)!im", $match ) ) {
1893 return true;
1894 }
1895 }
1896 }
1897
1898 return (bool)preg_match( '/[\000-\010\013\016-\037\177]/', $value );
1899 }
1900
1906 private static function splitXmlNamespace( $element ) {
1907 // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1908 $parts = explode( ':', strtolower( $element ) );
1909 $name = array_pop( $parts );
1910 $ns = implode( ':', $parts );
1911
1912 return [ $ns, $name ];
1913 }
1914
1919 private function stripXmlNamespace( $element ) {
1920 // 'http://www.w3.org/2000/svg:script' -> 'script'
1921 return self::splitXmlNamespace( $element )[1];
1922 }
1923
1934 public static function detectVirus( $file ) {
1935 global $wgOut;
1936 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1937 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1938 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1939 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1940 if ( !$antivirus ) {
1941 wfDebug( __METHOD__ . ": virus scanner disabled" );
1942
1943 return null;
1944 }
1945
1946 if ( !$antivirusSetup[$antivirus] ) {
1947 wfDebug( __METHOD__ . ": unknown virus scanner: {$antivirus}" );
1948 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1949 [ 'virus-badscanner', $antivirus ] );
1950
1951 return wfMessage( 'virus-unknownscanner' )->text() . " {$antivirus}";
1952 }
1953
1954 # look up scanner configuration
1955 $command = $antivirusSetup[$antivirus]['command'];
1956 $exitCodeMap = $antivirusSetup[$antivirus]['codemap'];
1957 $msgPattern = $antivirusSetup[$antivirus]['messagepattern'] ?? null;
1958
1959 if ( !str_contains( $command, "%f" ) ) {
1960 # simple pattern: append file to scan
1961 $command .= " " . Shell::escape( $file );
1962 } else {
1963 # complex pattern: replace "%f" with file to scan
1964 $command = str_replace( "%f", Shell::escape( $file ), $command );
1965 }
1966
1967 wfDebug( __METHOD__ . ": running virus scan: $command " );
1968
1969 # execute virus scanner
1970 $exitCode = false;
1971
1972 # NOTE: there's a 50-line workaround to make stderr redirection work on windows, too.
1973 # that does not seem to be worth the pain.
1974 # Ask me (Duesentrieb) about it if it's ever needed.
1975 $output = wfShellExecWithStderr( $command, $exitCode );
1976
1977 # map exit code to AV_xxx constants.
1978 $mappedCode = $exitCode;
1979 if ( $exitCodeMap ) {
1980 if ( isset( $exitCodeMap[$exitCode] ) ) {
1981 $mappedCode = $exitCodeMap[$exitCode];
1982 } elseif ( isset( $exitCodeMap["*"] ) ) {
1983 $mappedCode = $exitCodeMap["*"];
1984 }
1985 }
1986
1987 # NB: AV_NO_VIRUS is 0, but AV_SCAN_FAILED is false,
1988 # so we need the strict equalities === and thus can't use a switch here
1989 if ( $mappedCode === AV_SCAN_FAILED ) {
1990 # scan failed (code was mapped to false by $exitCodeMap)
1991 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1992
1993 $output = $antivirusRequired
1994 ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1995 : null;
1996 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1997 # scan failed because filetype is unknown (probably immune)
1998 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
1999 $output = null;
2000 } elseif ( $mappedCode === AV_NO_VIRUS ) {
2001 # no virus found
2002 wfDebug( __METHOD__ . ": file passed virus scan." );
2003 $output = false;
2004 } else {
2005 $output = trim( $output );
2006
2007 if ( !$output ) {
2008 $output = true; # if there's no output, return true
2009 } elseif ( $msgPattern ) {
2010 $groups = [];
2011 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
2012 $output = $groups[1];
2013 }
2014 }
2015
2016 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
2017 }
2018
2019 return $output;
2020 }
2021
2030 private function checkOverwrite( Authority $performer ) {
2031 // First check whether the local file can be overwritten
2032 $file = $this->getLocalFile();
2033 $file->load( IDBAccessObject::READ_LATEST );
2034 if ( $file->exists() ) {
2035 if ( !self::userCanReUpload( $performer, $file ) ) {
2036 return [ 'fileexists-forbidden', $file->getName() ];
2037 }
2038
2039 return true;
2040 }
2041
2042 $services = MediaWikiServices::getInstance();
2043
2044 /* Check shared conflicts: if the local file does not exist, but
2045 * RepoGroup::findFile finds a file, it exists in a shared repository.
2046 */
2047 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2048 if ( $file && !$performer->isAllowed( 'reupload-shared' ) ) {
2049 return [ 'fileexists-shared-forbidden', $file->getName() ];
2050 }
2051
2052 return true;
2053 }
2054
2062 public static function userCanReUpload( Authority $performer, File $img ) {
2063 if ( $performer->isAllowed( 'reupload' ) ) {
2064 return true; // non-conditional
2065 }
2066
2067 if ( !$performer->isAllowed( 'reupload-own' ) ) {
2068 return false;
2069 }
2070
2071 if ( !( $img instanceof LocalFile ) ) {
2072 return false;
2073 }
2074
2075 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2076 }
2077
2089 public static function getExistsWarning( $file ) {
2090 if ( $file->exists() ) {
2091 return [ 'warning' => 'exists', 'file' => $file ];
2092 }
2093
2094 if ( $file->getTitle()->getArticleID() ) {
2095 return [ 'warning' => 'page-exists', 'file' => $file ];
2096 }
2097
2098 $n = strrpos( $file->getName(), '.' );
2099 if ( $n > 0 ) {
2100 $partname = substr( $file->getName(), 0, $n );
2101 $extension = substr( $file->getName(), $n + 1 );
2102 } else {
2103 $partname = $file->getName();
2104 $extension = '';
2105 }
2106 $normalizedExtension = File::normalizeExtension( $extension );
2107 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2108
2109 if ( $normalizedExtension != $extension ) {
2110 // We're not using the normalized form of the extension.
2111 // Normal form is lowercase, using most common of alternate
2112 // extensions (e.g. 'jpg' rather than 'JPEG').
2113
2114 // Check for another file using the normalized form...
2115 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2116 $file_lc = $localRepo->newFile( $nt_lc );
2117
2118 if ( $file_lc->exists() ) {
2119 return [
2120 'warning' => 'exists-normalized',
2121 'file' => $file,
2122 'normalizedFile' => $file_lc
2123 ];
2124 }
2125 }
2126
2127 // Check for files with the same name but a different extension
2128 $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2129 if ( count( $similarFiles ) ) {
2130 return [
2131 'warning' => 'exists-normalized',
2132 'file' => $file,
2133 'normalizedFile' => $similarFiles[0],
2134 ];
2135 }
2136
2137 if ( self::isThumbName( $file->getName() ) ) {
2138 // Check for filenames like 50px- or 180px-, these are mostly thumbnails
2139 $nt_thb = Title::newFromText(
2140 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2141 NS_FILE
2142 );
2143 $file_thb = $localRepo->newFile( $nt_thb );
2144 if ( $file_thb->exists() ) {
2145 return [
2146 'warning' => 'thumb',
2147 'file' => $file,
2148 'thumbFile' => $file_thb
2149 ];
2150 }
2151
2152 // The file does not exist, but we just don't like the name
2153 return [
2154 'warning' => 'thumb-name',
2155 'file' => $file,
2156 'thumbFile' => $file_thb
2157 ];
2158 }
2159
2160 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2161 if ( str_starts_with( $partname, $prefix ) ) {
2162 return [
2163 'warning' => 'bad-prefix',
2164 'file' => $file,
2165 'prefix' => $prefix
2166 ];
2167 }
2168 }
2169
2170 return false;
2171 }
2172
2178 public static function isThumbName( $filename ) {
2179 $n = strrpos( $filename, '.' );
2180 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2181
2182 return (
2183 substr( $partname, 3, 3 ) === 'px-' ||
2184 substr( $partname, 2, 3 ) === 'px-'
2185 ) && preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2186 }
2187
2193 public static function getFilenamePrefixBlacklist() {
2194 $list = [];
2195 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2196 if ( !$message->isDisabled() ) {
2197 $lines = explode( "\n", $message->plain() );
2198 foreach ( $lines as $line ) {
2199 // Remove comment lines
2200 $comment = substr( trim( $line ), 0, 1 );
2201 if ( $comment === '#' || $comment == '' ) {
2202 continue;
2203 }
2204 // Remove additional comments after a prefix
2205 $comment = strpos( $line, '#' );
2206 if ( $comment > 0 ) {
2207 $line = substr( $line, 0, $comment - 1 );
2208 }
2209 $list[] = trim( $line );
2210 }
2211 }
2212
2213 return $list;
2214 }
2215
2225 public function getImageInfo( $result = null ) {
2226 $apiUpload = ApiUpload::getDummyInstance();
2227 return $apiUpload->getUploadImageInfo( $this );
2228 }
2229
2234 public function convertVerifyErrorToStatus( $error ) {
2235 $code = $error['status'];
2236 unset( $code['status'] );
2237
2238 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2239 }
2240
2248 public static function getMaxUploadSize( $forType = null ) {
2249 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2250
2251 if ( is_array( $maxUploadSize ) ) {
2252 return $maxUploadSize[$forType] ?? $maxUploadSize['*'];
2253 }
2254 return intval( $maxUploadSize );
2255 }
2256
2264 public static function getMaxPhpUploadSize() {
2265 $phpMaxFileSize = wfShorthandToInteger(
2266 ini_get( 'upload_max_filesize' ),
2267 PHP_INT_MAX
2268 );
2269 $phpMaxPostSize = wfShorthandToInteger(
2270 ini_get( 'post_max_size' ),
2271 PHP_INT_MAX
2272 ) ?: PHP_INT_MAX;
2273 return min( $phpMaxFileSize, $phpMaxPostSize );
2274 }
2275
2287 public static function getSessionStatus( UserIdentity $user, $statusKey ) {
2288 $store = self::getUploadSessionStore();
2289 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2290
2291 return $store->get( $key );
2292 }
2293
2306 public static function setSessionStatus( UserIdentity $user, $statusKey, $value ) {
2307 $store = self::getUploadSessionStore();
2308 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2309 $logger = LoggerFactory::getInstance( 'upload' );
2310
2311 if ( is_array( $value ) && ( $value['result'] ?? '' ) === 'Failure' ) {
2312 $logger->info( 'Upload session {key} for {user} set to failure {status} at {stage}',
2313 [
2314 'result' => $value['result'] ?? '',
2315 'stage' => $value['stage'] ?? 'unknown',
2316 'user' => $user->getName(),
2317 'status' => (string)( $value['status'] ?? '-' ),
2318 'filekey' => $value['filekey'] ?? '',
2319 'key' => $statusKey
2320 ]
2321 );
2322 } elseif ( is_array( $value ) ) {
2323 $logger->debug( 'Upload session {key} for {user} changed {status} at {stage}',
2324 [
2325 'result' => $value['result'] ?? '',
2326 'stage' => $value['stage'] ?? 'unknown',
2327 'user' => $user->getName(),
2328 'status' => (string)( $value['status'] ?? '-' ),
2329 'filekey' => $value['filekey'] ?? '',
2330 'key' => $statusKey
2331 ]
2332 );
2333 } else {
2334 $logger->debug( "Upload session {key} deleted for {user}",
2335 [
2336 'value' => $value,
2337 'key' => $statusKey,
2338 'user' => $user->getName()
2339 ]
2340 );
2341 }
2342
2343 if ( $value === false ) {
2344 $store->delete( $key );
2345 } else {
2346 $store->set( $key, $value, $store::TTL_DAY );
2347 }
2348 }
2349
2356 private static function getUploadSessionKey( BagOStuff $store, UserIdentity $user, $statusKey ) {
2357 return $store->makeKey(
2358 'uploadstatus',
2359 $user->isRegistered() ? $user->getId() : md5( $user->getName() ),
2360 $statusKey
2361 );
2362 }
2363
2367 private static function getUploadSessionStore() {
2368 return MediaWikiServices::getInstance()->getMainObjectStash();
2369 }
2370}
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:572
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:2113
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: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:1034
internal since 1.36
Definition User.php:93
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