24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
31 use Wikimedia\AtEase\AtEase;
50 use ProtectedHookAccessorTrait;
125 self::EMPTY_FILE =>
'empty-file',
126 self::FILE_TOO_LARGE =>
'file-too-large',
127 self::FILETYPE_MISSING =>
'filetype-missing',
128 self::FILETYPE_BADTYPE =>
'filetype-banned',
129 self::MIN_LENGTH_PARTNAME =>
'filename-tooshort',
130 self::ILLEGAL_FILENAME =>
'illegal-filename',
131 self::OVERWRITE_EXISTING_FILE =>
'overwrite',
132 self::VERIFICATION_ERROR =>
'verification-error',
133 self::HOOK_ABORTED =>
'hookaborted',
134 self::WINDOWS_NONASCII_FILENAME =>
'windows-nonascii-filename',
135 self::FILENAME_TOO_LONG =>
'filename-toolong',
137 return $code_to_status[$error] ??
'unknown-error';
147 $enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
149 return $enableUploads &&
wfIniGetBool(
'file_uploads' );
161 foreach ( [
'upload',
'edit' ] as $permission ) {
162 if ( !$performer->
isAllowed( $permission ) ) {
177 return $user->pingLimiter(
'upload' );
181 private static $uploadHandlers = [
'Stash',
'File',
'Url' ];
191 $type =
$type ?: $request->getVal(
'wpSourceType',
'File' );
205 if ( $className ===
null ) {
206 $className =
'UploadFrom' .
$type;
207 wfDebug( __METHOD__ .
": class name: $className" );
208 if ( !in_array(
$type, self::$uploadHandlers ) ) {
214 if ( !$className::isEnabled() ) {
219 if ( !$className::isValidRequest( $request ) ) {
224 $handler =
new $className;
226 $handler->initializeFromRequest( $request );
265 $this->mDesiredDestName = $name;
267 throw new MWException( __METHOD__ .
" given storage path `$tempPath`." );
271 $this->mRemoveTempFile = $removeTempFile;
286 $this->mTempPath = $tempPath ??
'';
287 $this->mFileSize = $fileSize ?:
null;
288 if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
289 $this->tempFileObj =
new TempFSFile( $this->mTempPath );
291 $this->mFileSize = filesize( $this->mTempPath );
294 $this->tempFileObj =
null;
312 return empty( $this->mFileSize );
337 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
342 $tmpFile = $repo->getLocalCopy( $srcPath );
344 $tmpFile->bind( $this );
346 $path = $tmpFile ? $tmpFile->getPath() :
false;
383 if ( $this->mFileSize > $maxSize ) {
396 if ( $verification !==
true ) {
399 'details' => $verification
407 if ( $result !==
true ) {
422 if ( $nt ===
null ) {
424 if ( $this->mTitleError === self::ILLEGAL_FILENAME ) {
427 if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
429 if ( count( $this->mBlackListedExtensions ) ) {
451 $verifyMimeType = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeType );
452 $verifyMimeTypeIE = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeTypeIE );
453 if ( $verifyMimeType ) {
454 wfDebug(
"mime: <$mime> extension: <{$this->mFinalExtension}>" );
455 $mimeTypeExclusions = MediaWikiServices::getInstance()->getMainConfig()
456 ->get( MainConfigNames::MimeTypeExclusions );
457 if ( self::checkFileExtension(
$mime, $mimeTypeExclusions ) ) {
458 return [
'filetype-badmime',
$mime ];
461 if ( $verifyMimeTypeIE ) {
462 # Check what Internet Explorer would detect
463 $fp = fopen( $this->mTempPath,
'rb' );
465 $chunk = fread( $fp, 256 );
468 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
469 $extMime = $magic->getMimeTypeFromExtensionOrNull( (
string)$this->mFinalExtension ) ??
'';
470 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
471 foreach ( $ieTypes as $ieType ) {
472 if ( self::checkFileExtension( $ieType, $mimeTypeExclusions ) ) {
473 return [
'filetype-bad-ie-mime', $ieType ];
489 $config = MediaWikiServices::getInstance()->getMainConfig();
490 $verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
491 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
493 if ( $status !==
true ) {
497 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
498 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
499 $mime = $this->mFileProps[
'mime'];
501 if ( $verifyMimeType ) {
502 # XXX: Missing extension will be caught by validateName() via getTitle()
503 if ( (
string)$this->mFinalExtension !==
'' &&
504 !self::verifyExtension(
$mime, $this->mFinalExtension )
510 # check for htmlish code and javascript
511 if ( !$disableUploadScriptChecks ) {
512 if ( $this->mFinalExtension ===
'svg' ||
$mime ===
'image/svg+xml' ) {
514 if ( $svgStatus !==
false ) {
522 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
523 if ( !$handlerStatus->isOK() ) {
524 $errors = $handlerStatus->getErrorsArray();
526 return reset( $errors );
531 $this->getHookRunner()->onUploadVerifyFile( $this,
$mime, $error );
532 if ( $error !==
true ) {
533 if ( !is_array( $error ) ) {
539 wfDebug( __METHOD__ .
": all clear; passing." );
554 $config = MediaWikiServices::getInstance()->getMainConfig();
555 $disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
556 # getTitle() sets some internal parameters like $this->mFinalExtension
559 $mwProps =
new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
560 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
562 # check MIME type, if desired
563 $mime = $this->mFileProps[
'file-mime'];
565 if ( $status !==
true ) {
569 # check for htmlish code and javascript
570 if ( !$disableUploadScriptChecks ) {
571 if ( self::detectScript( $this->mTempPath,
$mime, $this->mFinalExtension ) ) {
572 return [
'uploadscripted' ];
574 if ( $this->mFinalExtension ===
'svg' ||
$mime ===
'image/svg+xml' ) {
576 if ( $svgStatus !==
false ) {
582 # Scan the uploaded file for viruses
585 return [
'uploadvirus', $virus ];
597 $names = [ $entry[
'name'] ];
604 $nullPos = strpos( $entry[
'name'],
"\000" );
605 if ( $nullPos !==
false ) {
606 $names[] = substr( $entry[
'name'], 0, $nullPos );
611 if ( preg_grep(
'!\.class/?$!', $names ) ) {
612 $this->mJavaDetected =
true;
646 if ( $nt ===
null ) {
650 $status = PermissionStatus::newEmpty();
653 if ( !$status->isGood() ) {
654 return $status->toLegacyErrorArray();
657 $overwriteError = $this->checkOverwrite( $performer );
658 if ( $overwriteError !==
true ) {
659 return [ $overwriteError ];
675 if ( $user ===
null ) {
683 $localFile->
load( File::READ_LATEST );
684 $filename = $localFile->
getName();
687 $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
688 if ( $badFileName !==
null ) {
689 $warnings[
'badfilename'] = $badFileName;
692 $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (
string)$this->mFinalExtension );
693 if ( $unwantedFileExtensionDetails !==
null ) {
694 $warnings[
'filetype-unwanted-type'] = $unwantedFileExtensionDetails;
697 $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
698 if ( $fileSizeWarnings ) {
699 $warnings = array_merge( $warnings, $fileSizeWarnings );
702 $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
703 if ( $localFileExistsWarnings ) {
704 $warnings = array_merge( $warnings, $localFileExistsWarnings );
707 if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
708 $warnings[
'was-deleted'] = $filename;
713 $ignoreLocalDupes = isset( $warnings[
'exists'] );
714 $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
716 $warnings[
'duplicate'] = $dupes;
719 $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
720 if ( $archivedDupes !==
null ) {
721 $warnings[
'duplicate-archive'] = $archivedDupes;
739 array_walk_recursive( $warnings,
static function ( &$param, $key ) {
740 if ( $param instanceof
File ) {
742 'fileName' => $param->getName(),
743 'timestamp' => $param->getTimestamp()
745 } elseif ( is_object( $param ) ) {
746 throw new InvalidArgumentException(
747 'UploadBase::makeWarningsSerializable: ' .
748 'Unexpected object of class ' . get_class( $param ) );
763 private function checkBadFileName( $filename, $desiredFileName ) {
764 $comparableName = str_replace(
' ',
'_', $desiredFileName );
767 if ( $desiredFileName != $filename && $comparableName != $filename ) {
782 private function checkUnwantedFileExtensions( $fileExtension ) {
783 $checkFileExtensions = MediaWikiServices::getInstance()->getMainConfig()
784 ->get( MainConfigNames::CheckFileExtensions );
785 $fileExtensions = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::FileExtensions );
786 if ( $checkFileExtensions ) {
787 $extensions = array_unique( $fileExtensions );
788 if ( !self::checkFileExtension( $fileExtension, $extensions ) ) {
805 private function checkFileSize( $fileSize ) {
806 $uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
807 ->get( MainConfigNames::UploadSizeWarning );
811 if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
812 $warnings[
'large-file'] = [
818 if ( $fileSize == 0 ) {
819 $warnings[
'empty-file'] =
true;
831 private function checkLocalFileExists(
LocalFile $localFile, $hash ) {
835 if ( $exists !==
false ) {
836 $warnings[
'exists'] = $exists;
839 if ( $hash !==
false && $hash === $localFile->
getSha1() ) {
840 $warnings[
'no-change'] = $localFile;
845 foreach ( $history as $oldFile ) {
846 if ( $hash === $oldFile->getSha1() ) {
847 $warnings[
'duplicate-version'][] = $oldFile;
855 private function checkLocalFileWasDeleted(
LocalFile $localFile ) {
865 private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
866 if ( $hash ===
false ) {
869 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
871 foreach ( $dupes as $key => $dupe ) {
875 $title->equals( $dupe->getTitle() )
877 unset( $dupes[$key] );
891 private function checkAgainstArchiveDupes( $hash,
Authority $performer ) {
892 if ( $hash ===
false ) {
896 if ( $archivedFile->getID() > 0 ) {
898 return $archivedFile->getName();
924 $comment, $pageText, $watch, $user, $tags = [], ?
string $watchlistExpiry =
null
931 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
933 if ( !is_array( $error ) ) {
950 if ( $status->isGood() ) {
952 MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(
958 $this->getHookRunner()->onUploadComplete( $this );
982 if ( $this->mTitle !==
false ) {
985 if ( !is_string( $this->mDesiredDestName ) ) {
987 $this->mTitle =
null;
996 $this->mFilteredName =
$title->getDBkey();
1001 # oi_archive_name is max 255 bytes, which include a timestamp and an
1002 # exclamation mark, so restrict file name to 240 bytes.
1003 if ( strlen( $this->mFilteredName ) > 240 ) {
1005 $this->mTitle =
null;
1018 if ( $nt ===
null ) {
1020 $this->mTitle =
null;
1024 $this->mFilteredName = $nt->
getDBkey();
1032 if (
$ext !== [] ) {
1033 $this->mFinalExtension = trim( end(
$ext ) );
1035 $this->mFinalExtension =
'';
1040 if ( $this->mTempPath !==
null ) {
1041 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1042 $mime = $magic->guessMimeType( $this->mTempPath );
1043 if (
$mime !==
'unknown/unknown' ) {
1044 # Get a space separated list of extensions
1045 $mimeExt = $magic->getExtensionFromMimeTypeOrNull(
$mime );
1046 if ( $mimeExt !==
null ) {
1047 # Set the extension to the canonical extension
1048 $this->mFinalExtension = $mimeExt;
1050 # Fix up the other variables
1051 $this->mFilteredName .=
".{$this->mFinalExtension}";
1060 $config = MediaWikiServices::getInstance()->getMainConfig();
1061 $checkFileExtensions = $config->get( MainConfigNames::CheckFileExtensions );
1062 $strictFileExtensions = $config->get( MainConfigNames::StrictFileExtensions );
1063 $fileExtensions = $config->get( MainConfigNames::FileExtensions );
1064 $prohibitedFileExtensions = $config->get( MainConfigNames::ProhibitedFileExtensions );
1068 if ( $this->mFinalExtension ==
'' ) {
1070 $this->mTitle =
null;
1075 if ( $blackListedExtensions ||
1076 ( $checkFileExtensions && $strictFileExtensions &&
1077 !self::checkFileExtension( $this->mFinalExtension, $fileExtensions ) ) ) {
1078 $this->mBlackListedExtensions = $blackListedExtensions;
1080 $this->mTitle =
null;
1086 if ( !preg_match(
'/^[\x0-\x7f]*$/', $nt->getText() )
1087 && !MediaWikiServices::getInstance()->getRepoGroup()
1088 ->getLocalRepo()->backendSupportsUnicodePaths()
1091 $this->mTitle =
null;
1096 # If there was more than one "extension", reassemble the base
1097 # filename to prevent bogus complaints about length
1098 if ( count(
$ext ) > 1 ) {
1099 $iterations = count(
$ext ) - 1;
1100 for ( $i = 0; $i < $iterations; $i++ ) {
1101 $partname .=
'.' .
$ext[$i];
1105 if ( strlen( $partname ) < 1 ) {
1107 $this->mTitle =
null;
1112 $this->mTitle = $nt;
1124 if ( $this->mLocalFile ===
null ) {
1126 $this->mLocalFile = $nt ===
null
1128 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1154 if ( !$isPartial ) {
1164 return Status::newFatal(
'uploadstash-exception', get_class( $e ), $e->getMessage() );
1175 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1176 if ( $error && !is_array( $error ) ) {
1177 $error = [ $error ];
1190 $stash = MediaWikiServices::getInstance()->getRepoGroup()
1191 ->getLocalRepo()->getUploadStash( $user );
1193 $this->mStashFile =
$file;
1203 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1205 wfDebug( __METHOD__ .
": Marked temporary file '{$this->mTempPath}' for removal" );
1206 $this->tempFileObj->autocollect();
1224 $bits = explode(
'.', $filename );
1225 $basename = array_shift( $bits );
1227 return [ $basename, $bits ];
1239 return in_array( strtolower(
$ext ), $list,
true );
1251 return array_intersect( array_map(
'strtolower',
$ext ), $list );
1262 $magic = MediaWikiServices::getInstance()->getMimeAnalyzer();
1265 if ( !$magic->isRecognizableExtension( $extension ) ) {
1266 wfDebug( __METHOD__ .
": passing file with unknown detected mime type; " .
1267 "unrecognized extension '$extension', can't verify" );
1272 wfDebug( __METHOD__ .
": rejecting file with unknown detected mime type; " .
1273 "recognized extension '$extension', so probably invalid file" );
1277 $match = $magic->isMatchingExtension( $extension,
$mime );
1279 if ( $match ===
null ) {
1280 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1281 wfDebug( __METHOD__ .
": No extension known for $mime, but we know a mime for $extension" );
1286 wfDebug( __METHOD__ .
": no file extension known for mime type $mime, passing file" );
1291 wfDebug( __METHOD__ .
": mime type $mime matches extension $extension, passing file" );
1298 .
": mime type $mime mismatches file extension $extension, rejecting file" );
1315 # ugly hack: for text files, always look at the entire file.
1316 # For binary field, just check the first K.
1318 if ( str_starts_with(
$mime,
'text/' ) ) {
1319 $chunk = file_get_contents(
$file );
1321 $fp = fopen(
$file,
'rb' );
1325 $chunk = fread( $fp, 1024 );
1329 $chunk = strtolower( $chunk );
1335 # decode from UTF-16 if needed (could be used for obfuscation).
1336 if ( str_starts_with( $chunk,
"\xfe\xff" ) ) {
1338 } elseif ( str_starts_with( $chunk,
"\xff\xfe" ) ) {
1344 if ( $enc !==
null ) {
1345 $chunk = iconv( $enc,
"ASCII//IGNORE", $chunk );
1348 $chunk = trim( $chunk );
1351 wfDebug( __METHOD__ .
": checking for embedded scripts and HTML stuff" );
1353 # check for HTML doctype
1354 if ( preg_match(
"/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1360 if ( $extension ===
'svg' || str_starts_with(
$mime,
'image/svg' ) ) {
1361 if ( self::checkXMLEncodingMissmatch(
$file ) ) {
1375 '<html', # also in safari
1376 '<script', # also in safari
1379 foreach ( $tags as $tag ) {
1380 if ( strpos( $chunk, $tag ) !==
false ) {
1381 wfDebug( __METHOD__ .
": found something that may make it be mistaken for html: $tag" );
1391 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1394 # look for script-types
1395 if ( preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1396 wfDebug( __METHOD__ .
": found script types" );
1401 # look for html-style script-urls
1402 if ( preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1403 wfDebug( __METHOD__ .
": found html-style script urls" );
1408 # look for css-style script-urls
1409 if ( preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1410 wfDebug( __METHOD__ .
": found css-style script urls" );
1415 wfDebug( __METHOD__ .
": no scripts found" );
1428 $svgMetadataCutoff = MediaWikiServices::getInstance()->getMainConfig()
1429 ->get( MainConfigNames::SVGMetadataCutoff );
1430 $contents = file_get_contents(
$file,
false,
null, 0, $svgMetadataCutoff );
1431 $encodingRegex =
'!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1433 if ( preg_match(
"!<\?xml\b(.*?)\?>!si", $contents,
$matches ) ) {
1434 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1435 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1437 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'" );
1441 } elseif ( preg_match(
"!<\?xml\b!si", $contents ) ) {
1444 wfDebug( __METHOD__ .
": Unmatched XML declaration start" );
1447 } elseif ( str_starts_with( $contents,
"\x4C\x6F\xA7\x94" ) ) {
1449 wfDebug( __METHOD__ .
": EBCDIC Encoded XML" );
1456 $attemptEncodings = [
'UTF-16',
'UTF-16BE',
'UTF-32',
'UTF-32BE' ];
1457 foreach ( $attemptEncodings as $encoding ) {
1458 AtEase::suppressWarnings();
1459 $str = iconv( $encoding,
'UTF-8', $contents );
1460 AtEase::restoreWarnings();
1461 if ( $str !=
'' && preg_match(
"!<\?xml\b(.*?)\?>!si", $str,
$matches ) ) {
1462 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1463 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1465 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'" );
1469 } elseif ( $str !=
'' && preg_match(
"!<\?xml\b!si", $str ) ) {
1472 wfDebug( __METHOD__ .
": Unmatched XML declaration start" );
1487 $this->mSVGNSError =
false;
1490 [ $this,
'checkSvgScriptCallback' ],
1493 'processing_instruction_handler' => [ __CLASS__,
'checkSvgPICallback' ],
1494 'external_dtd_handler' => [ __CLASS__,
'checkSvgExternalDTD' ],
1497 if ( $check->wellFormed !==
true ) {
1500 return $partial ? false : [
'uploadinvalidxml' ];
1503 if ( $check->filterMatch ) {
1504 if ( $this->mSVGNSError ) {
1507 return $check->filterMatchType;
1521 if ( preg_match(
'/xml-stylesheet/i', $target ) ) {
1522 return [
'upload-scripted-pi-callback' ];
1543 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1544 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1545 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1546 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1548 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1550 if (
$type !==
'PUBLIC'
1551 || !in_array( $systemId, $allowedDTDs )
1552 || !str_starts_with( $publicId,
"-//W3C//" )
1554 return [
'upload-scripted-dtd' ];
1567 [ $namespace, $strippedElement ] = self::splitXmlNamespace( $element );
1571 static $validNamespaces = [
1574 'http://creativecommons.org/ns#',
1575 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1576 'http://ns.adobe.com/adobeillustrator/10.0/',
1577 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1578 'http://ns.adobe.com/extensibility/1.0/',
1579 'http://ns.adobe.com/flows/1.0/',
1580 'http://ns.adobe.com/illustrator/1.0/',
1581 'http://ns.adobe.com/imagereplacement/1.0/',
1582 'http://ns.adobe.com/pdf/1.3/',
1583 'http://ns.adobe.com/photoshop/1.0/',
1584 'http://ns.adobe.com/saveforweb/1.0/',
1585 'http://ns.adobe.com/variables/1.0/',
1586 'http://ns.adobe.com/xap/1.0/',
1587 'http://ns.adobe.com/xap/1.0/g/',
1588 'http://ns.adobe.com/xap/1.0/g/img/',
1589 'http://ns.adobe.com/xap/1.0/mm/',
1590 'http://ns.adobe.com/xap/1.0/rights/',
1591 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1592 'http://ns.adobe.com/xap/1.0/stype/font#',
1593 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1594 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1595 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1596 'http://ns.adobe.com/xap/1.0/t/pg/',
1597 'http://purl.org/dc/elements/1.1/',
1598 'http://purl.org/dc/elements/1.1',
1599 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1600 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1601 'http://taptrix.com/inkpad/svg_extensions',
1602 'http://web.resource.org/cc/',
1603 'http://www.freesoftware.fsf.org/bkchem/cdml',
1604 'http://www.inkscape.org/namespaces/inkscape',
1605 'http://www.opengis.net/gml',
1606 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1607 'http://www.w3.org/2000/svg',
1608 'http://www.w3.org/tr/rec-rdf-syntax/',
1609 'http://www.w3.org/2000/01/rdf-schema#',
1610 'http://www.w3.org/2000/02/svg/testsuite/description/',
1615 $isBuggyInkscape = preg_match(
'/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1617 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1618 wfDebug( __METHOD__ .
": Non-svg namespace '$namespace' in uploaded file." );
1620 $this->mSVGNSError = $namespace;
1628 if ( $strippedElement ===
'script' ) {
1629 wfDebug( __METHOD__ .
": Found script element '$element' in uploaded file." );
1631 return [
'uploaded-script-svg', $strippedElement ];
1634 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1635 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1636 if ( $strippedElement ===
'handler' ) {
1637 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file." );
1639 return [
'uploaded-script-svg', $strippedElement ];
1642 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1643 if ( $strippedElement ===
'stylesheet' ) {
1644 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file." );
1646 return [
'uploaded-script-svg', $strippedElement ];
1649 # Block iframes, in case they pass the namespace check
1650 if ( $strippedElement ===
'iframe' ) {
1651 wfDebug( __METHOD__ .
": iframe in uploaded file." );
1653 return [
'uploaded-script-svg', $strippedElement ];
1657 if ( $strippedElement ===
'style'
1660 wfDebug( __METHOD__ .
": hostile css in style element." );
1662 return [
'uploaded-hostile-svg' ];
1665 foreach ( $attribs as $attrib => $value ) {
1666 $stripped = $this->stripXmlNamespace( $attrib );
1667 $value = strtolower( $value );
1669 if ( str_starts_with( $stripped,
'on' ) ) {
1671 .
": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1673 return [
'uploaded-event-handler-on-svg', $attrib, $value ];
1676 # Do not allow relative links, or unsafe url schemas.
1677 # For <a> tags, only data:, http: and https: and same-document
1678 # fragment links are allowed. For all other tags, only data:
1679 # and fragment are allowed.
1680 if ( $stripped ===
'href'
1682 && !str_starts_with( $value,
'data:' )
1683 && !str_starts_with( $value,
'#' )
1685 if ( !( $strippedElement ===
'a'
1686 && preg_match(
'!^https?://!i', $value ) )
1688 wfDebug( __METHOD__ .
": Found href attribute <$strippedElement "
1689 .
"'$attrib'='$value' in uploaded file." );
1691 return [
'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1695 # only allow data: targets that should be safe. This prevents vectors like,
1696 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1697 if ( $stripped ===
'href' && strncasecmp(
'data:', $value, 5 ) === 0 ) {
1700 $parameters =
'(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1702 if ( !preg_match(
"!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1703 wfDebug( __METHOD__ .
": Found href to unwhitelisted data: uri "
1704 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1705 return [
'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1709 # Change href with animate from (http:
1710 if ( $stripped ===
'attributename'
1711 && $strippedElement ===
'animate'
1712 && $this->stripXmlNamespace( $value ) ===
'href'
1714 wfDebug( __METHOD__ .
": Found animate that might be changing href using from "
1715 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1717 return [
'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1720 # use set/animate to add event-handler attribute to parent
1721 if ( ( $strippedElement ===
'set' || $strippedElement ===
'animate' )
1722 && $stripped ===
'attributename'
1723 && substr( $value, 0, 2 ) ===
'on'
1725 wfDebug( __METHOD__ .
": Found svg setting event-handler attribute with "
1726 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1728 return [
'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1731 # use set to add href attribute to parent element
1732 if ( $strippedElement ===
'set'
1733 && $stripped ===
'attributename'
1734 && str_contains( $value,
'href' )
1736 wfDebug( __METHOD__ .
": Found svg setting href attribute '$value' in uploaded file." );
1738 return [
'uploaded-setting-href-svg' ];
1741 # use set to add a remote / data / script target to an element
1742 if ( $strippedElement ===
'set'
1743 && $stripped ===
'to'
1744 && preg_match(
'!(http|https|data|script):!sim', $value )
1746 wfDebug( __METHOD__ .
": Found svg setting attribute to '$value' in uploaded file." );
1748 return [
'uploaded-wrong-setting-svg', $value ];
1751 # use handler attribute with remote / data / script
1752 if ( $stripped ===
'handler' && preg_match(
'!(http|https|data|script):!sim', $value ) ) {
1753 wfDebug( __METHOD__ .
": Found svg setting handler with remote/data/script "
1754 .
"'$attrib'='$value' in uploaded file." );
1756 return [
'uploaded-setting-handler-svg', $attrib, $value ];
1759 # use CSS styles to bring in remote code
1760 if ( $stripped ===
'style'
1763 wfDebug( __METHOD__ .
": Found svg setting a style with "
1764 .
"remote url '$attrib'='$value' in uploaded file." );
1765 return [
'uploaded-remote-url-svg', $attrib, $value ];
1768 # Several attributes can include css, css character escaping isn't allowed
1769 $cssAttrs = [
'font',
'clip-path',
'fill',
'filter',
'marker',
1770 'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke' ];
1771 if ( in_array( $stripped, $cssAttrs,
true )
1772 && self::checkCssFragment( $value )
1774 wfDebug( __METHOD__ .
": Found svg setting a style with "
1775 .
"remote url '$attrib'='$value' in uploaded file." );
1776 return [
'uploaded-remote-url-svg', $attrib, $value ];
1779 # image filters can pull in url, which could be svg that executes scripts
1780 # Only allow url( "#foo" ). Do not allow url( http:
1781 if ( $strippedElement ===
'image'
1782 && $stripped ===
'filter'
1783 && preg_match(
'!url\s*\(\s*["\']?[^#]!sim', $value )
1785 wfDebug( __METHOD__ .
": Found image filter with url: "
1786 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1788 return [
'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1801 private static function checkCssFragment( $value ) {
1802 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1803 if ( stripos( $value,
'@import' ) !==
false ) {
1807 # We allow @font-face to embed fonts with data: urls, so we snip the string
1808 # 'url' out so this case won't match when we check for urls below
1809 $pattern =
'!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1810 $value = preg_replace( $pattern,
'$1$2', $value );
1812 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1813 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1814 # Expression and -o-link don't seem to work either, but filtering them here in case.
1815 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1816 # but not local ones such as url("#..., url('#..., url(#....
1817 if ( preg_match(
'!expression
1819 | -o-link-source\s*:
1820 | -o-replace\s*:!imx', $value ) ) {
1824 if ( preg_match_all(
1825 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1830 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1831 foreach (
$matches[1] as $match ) {
1832 if ( !preg_match(
"!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1838 if ( preg_match(
'/[\000-\010\013\016-\037\177]/', $value ) ) {
1850 private static function splitXmlNamespace( $element ) {
1852 $parts = explode(
':', strtolower( $element ) );
1853 $name = array_pop( $parts );
1854 $ns = implode(
':', $parts );
1856 return [ $ns, $name ];
1863 private function stripXmlNamespace( $name ) {
1865 $parts = explode(
':', strtolower( $name ) );
1867 return array_pop( $parts );
1882 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
1883 $antivirus = $mainConfig->get( MainConfigNames::Antivirus );
1884 $antivirusSetup = $mainConfig->get( MainConfigNames::AntivirusSetup );
1885 $antivirusRequired = $mainConfig->get( MainConfigNames::AntivirusRequired );
1886 if ( !$antivirus ) {
1887 wfDebug( __METHOD__ .
": virus scanner disabled" );
1892 if ( !$antivirusSetup[$antivirus] ) {
1893 wfDebug( __METHOD__ .
": unknown virus scanner: {$antivirus}" );
1894 $wgOut->wrapWikiMsg(
"<div class=\"error\">\n$1\n</div>",
1895 [
'virus-badscanner', $antivirus ] );
1897 return wfMessage(
'virus-unknownscanner' )->text() .
" {$antivirus}";
1900 # look up scanner configuration
1901 $command = $antivirusSetup[$antivirus][
'command'];
1902 $exitCodeMap = $antivirusSetup[$antivirus][
'codemap'];
1903 $msgPattern = $antivirusSetup[$antivirus][
'messagepattern'] ??
null;
1905 if ( !str_contains( $command,
"%f" ) ) {
1906 # simple pattern: append file to scan
1907 $command .=
" " . Shell::escape(
$file );
1909 # complex pattern: replace "%f" with file to scan
1910 $command = str_replace(
"%f", Shell::escape(
$file ), $command );
1913 wfDebug( __METHOD__ .
": running virus scan: $command " );
1915 # execute virus scanner
1918 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1919 # that does not seem to be worth the pain.
1920 # Ask me (Duesentrieb) about it if it's ever needed.
1923 # map exit code to AV_xxx constants.
1924 $mappedCode = $exitCode;
1925 if ( $exitCodeMap ) {
1926 if ( isset( $exitCodeMap[$exitCode] ) ) {
1927 $mappedCode = $exitCodeMap[$exitCode];
1928 } elseif ( isset( $exitCodeMap[
"*"] ) ) {
1929 $mappedCode = $exitCodeMap[
"*"];
1937 # scan failed (code was mapped to false by $exitCodeMap)
1938 wfDebug( __METHOD__ .
": failed to scan $file (code $exitCode)." );
1940 $output = $antivirusRequired
1941 ?
wfMessage(
'virus-scanfailed', [ $exitCode ] )->text()
1944 # scan failed because filetype is unknown (probably immune)
1945 wfDebug( __METHOD__ .
": unsupported file type $file (code $exitCode)." );
1949 wfDebug( __METHOD__ .
": file passed virus scan." );
1952 $output = trim( $output );
1955 $output =
true; #
if there
's no output, return true
1956 } elseif ( $msgPattern ) {
1958 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1959 $output = $groups[1];
1963 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
1977 private function checkOverwrite( Authority $performer ) {
1978 // First check whether the local file can be overwritten
1979 $file = $this->getLocalFile();
1980 $file->load( File::READ_LATEST );
1981 if ( $file->exists() ) {
1982 if ( !self::userCanReUpload( $performer, $file ) ) {
1983 return [ 'fileexists-forbidden
', $file->getName() ];
1989 $services = MediaWikiServices::getInstance();
1991 /* Check shared conflicts: if the local file does not exist, but
1992 * RepoGroup::findFile finds a file, it exists in a shared repository.
1994 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest
' => true ] );
1995 if ( $file && !$performer->isAllowed( 'reupload-shared
' )
1997 return [ 'fileexists-shared-forbidden
', $file->getName() ];
2010 public static function userCanReUpload( Authority $performer, File $img ) {
2011 if ( $performer->isAllowed( 'reupload
' ) ) {
2012 return true; // non-conditional
2015 if ( !$performer->isAllowed( 'reupload-own
' ) ) {
2019 if ( !( $img instanceof LocalFile ) ) {
2023 return $performer->getUser()->equals( $img->getUploader( File::RAW ) );
2037 public static function getExistsWarning( $file ) {
2038 if ( $file->exists() ) {
2039 return [ 'warning
' => 'exists
', 'file
' => $file ];
2042 if ( $file->getTitle()->getArticleID() ) {
2043 return [ 'warning
' => 'page-exists
', 'file
' => $file ];
2046 if ( !strpos( $file->getName(), '.
' ) ) {
2047 $partname = $file->getName();
2050 $n = strrpos( $file->getName(), '.
' );
2051 $extension = substr( $file->getName(), $n + 1 );
2052 $partname = substr( $file->getName(), 0, $n );
2054 $normalizedExtension = File::normalizeExtension( $extension );
2055 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2057 if ( $normalizedExtension != $extension ) {
2058 // We're not
using the normalized form of the extension.
2064 $file_lc = $localRepo->newFile( $nt_lc );
2066 if ( $file_lc->exists() ) {
2068 'warning' =>
'exists-normalized',
2070 'normalizedFile' => $file_lc
2076 $similarFiles = $localRepo->findFilesByPrefix(
"{$partname}.", 1 );
2077 if ( count( $similarFiles ) ) {
2079 'warning' =>
'exists-normalized',
2081 'normalizedFile' => $similarFiles[0],
2085 if ( self::isThumbName(
$file->getName() ) ) {
2086 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
2088 substr( $partname, strpos( $partname,
'-' ) + 1 ) .
'.' . $extension,
2091 $file_thb = $localRepo->newFile( $nt_thb );
2092 if ( $file_thb->exists() ) {
2094 'warning' =>
'thumb',
2096 'thumbFile' => $file_thb
2102 'warning' =>
'thumb-name',
2104 'thumbFile' => $file_thb
2108 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2109 if ( str_starts_with( $partname, $prefix ) ) {
2111 'warning' =>
'bad-prefix',
2127 $n = strrpos( $filename,
'.' );
2128 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2131 substr( $partname, 3, 3 ) ===
'px-' ||
2132 substr( $partname, 2, 3 ) ===
'px-'
2134 preg_match(
"/[0-9]{2}/", substr( $partname, 0, 2 ) );
2144 $message =
wfMessage(
'filename-prefix-blacklist' )->inContentLanguage();
2145 if ( !$message->isDisabled() ) {
2146 $lines = explode(
"\n", $message->plain() );
2147 foreach (
$lines as $line ) {
2149 $comment = substr( trim( $line ), 0, 1 );
2150 if ( $comment ===
'#' || $comment ==
'' ) {
2154 $comment = strpos( $line,
'#' );
2155 if ( $comment > 0 ) {
2156 $line = substr( $line, 0, $comment - 1 );
2158 $list[] = trim( $line );
2197 $code = $error[
'status'];
2198 unset( $code[
'status'] );
2211 $maxUploadSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::MaxUploadSize );
2213 if ( is_array( $maxUploadSize ) ) {
2214 if ( $forType !==
null && isset( $maxUploadSize[$forType] ) ) {
2215 return $maxUploadSize[$forType];
2217 return $maxUploadSize[
'*'];
2219 return intval( $maxUploadSize );
2231 ini_get(
'upload_max_filesize' ),
2235 ini_get(
'post_max_size' ),
2238 return min( $phpMaxFileSize, $phpMaxPostSize );
2253 $store = self::getUploadSessionStore();
2254 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2256 return $store->
get( $key );
2272 $store = self::getUploadSessionStore();
2273 $key = self::getUploadSessionKey( $store, $user, $statusKey );
2275 if ( $value ===
false ) {
2278 $store->
set( $key, $value, $store::TTL_DAY );
2299 private static function getUploadSessionStore() {
2300 return MediaWikiServices::getInstance()->getMainObjectStash();
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.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgOut
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
static getPropertyNames( $filter=null)
Returns all possible parameters to siiprop.
Deleted file in the 'filearchive' table.
Class representing a cache/ephemeral data store.
get( $key, $flags=0)
Get an item.
delete( $key, $flags=0)
Delete an item if it exists.
makeKey( $collection,... $components)
Make a cache key for the global keyspace and given components.
set( $key, $value, $exptime=0, $flags=0)
Set an item.
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Implements some public methods and some protected utility functions which are required by multiple ch...
getName()
Return the name of this file.
wasDeleted()
Was this file ever deleted from the wiki?
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Local file in the wiki's own database.
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.
A class containing constants representing the names of configuration variables.
static listParam(array $list, $type='text')
static getMain()
Get the RequestContext object associated with the main request.
static decodeCharReferences( $text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
static normalizeCss( $value)
Normalize CSS into a format we can easily search for hostile input.
static newFatal( $message,... $parameters)
Factory function for fatal errors.
static newGood( $value=null)
Factory function for good results.
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
static capitalize( $text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
getDBkey()
Get the main part with underscores.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
UploadBase and subclasses are the backend of MediaWiki's file uploads.
getSourceType()
Returns the upload type.
static makeWarningsSerializable( $warnings)
Convert the warnings array returned by checkWarnings() to something that can be serialized.
static setSessionStatus(UserIdentity $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
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.
string null $mFilteredName
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.
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 blacklisted 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 a whitelist of xml encodings that are known not to be interpreted differently by the server's x...
doStashFile(User $user=null)
Implementation for stashFile() and tryStashFile().
string[] $mBlackListedExtensions
static isAllowed(Authority $performer)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
const WINDOWS_NONASCII_FILENAME
cleanupTempFile()
If we've modified the upload file we need to manually remove it on exit to clean up.
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
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 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.
getImageInfo( $result)
Gets image info about the file just uploaded.
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 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
static getExistsWarning( $file)
Helper function that does various existence checks for a file.
static getMaxPhpUploadSize()
Get the PHP maximum uploaded file size, based on ini settings.
verifyMimeType( $mime)
Verify the MIME type.
initializeFromRequest(&$request)
Initialize from a WebRequest.
string false $mSVGNSError
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext
if(!file_exists( $CREDITS)) $lines