39 abstract class UploadBase {
43 protected $tempFileObj;
45 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
46 protected $mTitle =
false, $mTitleError = 0;
47 protected $mFilteredName, $mFinalExtension;
48 protected $mLocalFile, $mStashFile, $mFileSize, $mFileProps;
49 protected $mBlackListedExtensions;
50 protected $mJavaDetected, $mSVGNSError;
52 protected static $safeXmlEncodings = [
72 const MIN_LENGTH_PARTNAME = 4;
73 const ILLEGAL_FILENAME = 5;
74 const OVERWRITE_EXISTING_FILE = 7; # Not
used anymore; handled
by verifyTitlePermissions()
75 const FILETYPE_MISSING = 8;
76 const FILETYPE_BADTYPE = 9;
77 const VERIFICATION_ERROR = 10;
78 const HOOK_ABORTED = 11;
79 const FILE_TOO_LARGE = 12;
80 const WINDOWS_NONASCII_FILENAME = 13;
81 const FILENAME_TOO_LONG = 14;
89 self::EMPTY_FILE =>
'empty-file',
90 self::FILE_TOO_LARGE =>
'file-too-large',
91 self::FILETYPE_MISSING =>
'filetype-missing',
92 self::FILETYPE_BADTYPE =>
'filetype-banned',
93 self::MIN_LENGTH_PARTNAME =>
'filename-tooshort',
94 self::ILLEGAL_FILENAME =>
'illegal-filename',
95 self::OVERWRITE_EXISTING_FILE =>
'overwrite',
96 self::VERIFICATION_ERROR =>
'verification-error',
97 self::HOOK_ABORTED =>
'hookaborted',
98 self::WINDOWS_NONASCII_FILENAME =>
'windows-nonascii-filename',
99 self::FILENAME_TOO_LONG =>
'filename-toolong',
101 if ( isset( $code_to_status[$error] ) ) {
102 return $code_to_status[$error];
105 return 'unknown-error';
113 public static function isEnabled() {
120 # Check php's file_uploads setting
132 public static function isAllowed(
$user ) {
133 foreach ( [
'upload',
'edit' ]
as $permission ) {
134 if ( !
$user->isAllowed( $permission ) ) {
148 public static function isThrottled(
$user ) {
149 return $user->pingLimiter(
'upload' );
153 private static $uploadHandlers = [
'Stash',
'File',
'Url' ];
162 public static function createFromRequest( &
$request,
$type =
null ) {
175 if ( is_null( $className ) ) {
176 $className =
'UploadFrom' .
$type;
177 wfDebug( __METHOD__ .
": class name: $className\n" );
178 if ( !in_array(
$type, self::$uploadHandlers ) ) {
184 if ( !call_user_func( [ $className,
'isEnabled' ] ) ) {
189 if ( !call_user_func( [ $className,
'isValidRequest' ],
$request ) ) {
206 public static function isValidRequest(
$request ) {
210 public function __construct() {
219 public function getSourceType() {
231 public function initializePathInfo(
$name, $tempPath, $fileSize, $removeTempFile =
false ) {
232 $this->mDesiredDestName =
$name;
234 throw new MWException( __METHOD__ .
" given storage path `$tempPath`." );
237 $this->setTempFile( $tempPath, $fileSize );
238 $this->mRemoveTempFile = $removeTempFile;
246 abstract public function initializeFromRequest( &
$request );
252 protected function setTempFile( $tempPath, $fileSize =
null ) {
253 $this->mTempPath = $tempPath;
254 $this->mFileSize = $fileSize ?:
null;
255 if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
256 $this->tempFileObj =
new TempFSFile( $this->mTempPath );
258 $this->mFileSize = filesize( $this->mTempPath );
261 $this->tempFileObj =
null;
269 public function fetchFile() {
277 public function isEmptyFile() {
278 return empty( $this->mFileSize );
285 public function getFileSize() {
286 return $this->mFileSize;
293 public function getTempFileSha1Base36() {
301 public function getRealPath( $srcPath ) {
303 if ( $repo->isVirtualUrl( $srcPath ) ) {
307 $tmpFile = $repo->getLocalCopy( $srcPath );
309 $tmpFile->bind( $this );
311 $path = $tmpFile ? $tmpFile->getPath() :
false;
323 public function verifyUpload() {
328 if ( $this->isEmptyFile() ) {
329 return [
'status' => self::EMPTY_FILE ];
335 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
336 if ( $this->mFileSize > $maxSize ) {
338 'status' => self::FILE_TOO_LARGE,
348 $verification = $this->verifyFile();
349 if ( $verification !==
true ) {
351 'status' => self::VERIFICATION_ERROR,
352 'details' => $verification
359 $result = $this->validateName();
366 [ $this->mDestName, $this->mTempPath, &$error ],
'1.28' )
368 return [
'status' => self::HOOK_ABORTED,
'error' => $error ];
371 return [
'status' => self::OK ];
380 public function validateName() {
381 $nt = $this->getTitle();
382 if ( is_null( $nt ) ) {
383 $result = [
'status' => $this->mTitleError ];
384 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
385 $result[
'filtered'] = $this->mFilteredName;
387 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
388 $result[
'finalExt'] = $this->mFinalExtension;
389 if (
count( $this->mBlackListedExtensions ) ) {
390 $result[
'blacklistedExt'] = $this->mBlackListedExtensions;
396 $this->mDestName = $this->getLocalFile()->
getName();
410 protected function verifyMimeType(
$mime ) {
413 wfDebug(
"mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
416 return [
'filetype-badmime',
$mime ];
419 # Check what Internet Explorer would detect
420 $fp = fopen( $this->mTempPath,
'rb' );
421 $chunk = fread( $fp, 256 );
425 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
426 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
427 foreach ( $ieTypes
as $ieType ) {
429 return [
'filetype-bad-ie-mime', $ieType ];
442 protected function verifyFile() {
445 $status = $this->verifyPartialFile();
451 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
452 $mime = $this->mFileProps[
'mime'];
455 # XXX: Missing extension will be caught by validateName() via getTitle()
456 if ( $this->mFinalExtension !=
'' && !$this->verifyExtension(
$mime, $this->mFinalExtension ) ) {
457 return [
'filetype-mime-mismatch', $this->mFinalExtension,
$mime ];
461 # check for htmlish code and javascript
463 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
464 $svgStatus = $this->detectScriptInSvg( $this->mTempPath,
false );
465 if ( $svgStatus !==
false ) {
473 $handlerStatus =
$handler->verifyUpload( $this->mTempPath );
474 if ( !$handlerStatus->isOK() ) {
475 $errors = $handlerStatus->getErrorsArray();
477 return reset( $errors );
483 if ( $error !==
true ) {
484 if ( !is_array( $error ) ) {
490 wfDebug( __METHOD__ .
": all clear; passing.\n" );
503 protected function verifyPartialFile() {
506 # getTitle() sets some internal parameters like $this->mFinalExtension
510 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
512 # check MIME type, if desired
513 $mime = $this->mFileProps[
'file-mime'];
519 # check for htmlish code and javascript
521 if ( self::detectScript( $this->mTempPath,
$mime, $this->mFinalExtension ) ) {
522 return [
'uploadscripted' ];
524 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
525 $svgStatus = $this->detectScriptInSvg( $this->mTempPath,
true );
526 if ( $svgStatus !==
false ) {
532 # Check for Java applets, which if uploaded can bypass cross-site
535 $this->mJavaDetected =
false;
537 [ $this,
'zipEntryCallback' ] );
538 if ( !$zipStatus->isOK() ) {
539 $errors = $zipStatus->getErrorsArray();
540 $error = reset( $errors );
541 if ( $error[0] !==
'zip-wrong-format' ) {
545 if ( $this->mJavaDetected ) {
546 return [
'uploadjava' ];
550 # Scan the uploaded file for viruses
551 $virus = $this->detectVirus( $this->mTempPath );
553 return [
'uploadvirus', $virus ];
564 public function zipEntryCallback( $entry ) {
565 $names = [ $entry[
'name'] ];
572 $nullPos = strpos( $entry[
'name'],
"\000" );
573 if ( $nullPos !==
false ) {
574 $names[] = substr( $entry[
'name'], 0, $nullPos );
579 if ( preg_grep(
'!\.class/?$!', $names ) ) {
580 $this->mJavaDetected =
true;
593 public function verifyPermissions(
$user ) {
594 return $this->verifyTitlePermissions(
$user );
608 public function verifyTitlePermissions(
$user ) {
613 $nt = $this->getTitle();
614 if ( is_null( $nt ) ) {
617 $permErrors = $nt->getUserPermissionsErrors(
'edit',
$user );
618 $permErrorsUpload = $nt->getUserPermissionsErrors(
'upload',
$user );
619 if ( !$nt->exists() ) {
620 $permErrorsCreate = $nt->getUserPermissionsErrors(
'create',
$user );
622 $permErrorsCreate = [];
624 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
625 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsUpload, $permErrors ) );
626 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsCreate, $permErrors ) );
631 $overwriteError = $this->checkOverwrite(
$user );
632 if ( $overwriteError !==
true ) {
633 return [ $overwriteError ];
646 public function checkWarnings() {
651 $localFile = $this->getLocalFile();
652 $localFile->load( File::READ_LATEST );
653 $filename = $localFile->getName();
659 $comparableName = str_replace(
' ',
'_', $this->mDesiredDestName );
662 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
663 $warnings[
'badfilename'] = $filename;
670 if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
671 $warnings[
'filetype-unwanted-type'] = [ $this->mFinalExtension,
672 $wgLang->commaList( $extensions ),
count( $extensions ) ];
681 if ( $this->mFileSize == 0 ) {
682 $warnings[
'empty-file'] =
true;
685 $hash = $this->getTempFileSha1Base36();
686 $exists = self::getExistsWarning( $localFile );
687 if ( $exists !==
false ) {
688 $warnings[
'exists'] = $exists;
691 if ( $hash === $localFile->getSha1() ) {
692 $warnings[
'no-change'] = $localFile;
696 $history = $localFile->getHistory();
697 foreach ( $history
as $oldFile ) {
698 if ( $hash === $oldFile->getSha1() ) {
699 $warnings[
'duplicate-version'][] = $oldFile;
704 if ( $localFile->wasDeleted() && !$localFile->exists() ) {
705 $warnings[
'was-deleted'] = $filename;
710 $title = $this->getTitle();
712 foreach ( $dupes
as $key => $dupe ) {
713 if (
$title->equals( $dupe->getTitle() ) ) {
714 unset( $dupes[$key] );
718 $warnings[
'duplicate'] = $dupes;
723 if ( $archivedFile->getID() > 0 ) {
725 $warnings[
'duplicate-archive'] = $archivedFile->getName();
727 $warnings[
'duplicate-archive'] =
'';
747 public function performUpload( $comment, $pageText, $watch,
$user, $tags = [] ) {
748 $this->getLocalFile()->load( File::READ_LATEST );
749 $props = $this->mFileProps;
752 Hooks::run(
'UploadVerifyUpload', [ $this,
$user, $props, $comment, $pageText, &$error ] );
754 if ( !is_array( $error ) ) {
757 return call_user_func_array(
'Status::newFatal', $error );
760 $status = $this->getLocalFile()->upload(
774 $this->getLocalFile()->getTitle(),
781 Hooks::run(
'UploadComplete', [ &$uploadBase ] );
783 $this->postProcessUpload();
794 public function postProcessUpload() {
803 public function getTitle() {
804 if ( $this->mTitle !==
false ) {
805 return $this->mTitle;
807 if ( !is_string( $this->mDesiredDestName ) ) {
808 $this->mTitleError = self::ILLEGAL_FILENAME;
809 $this->mTitle =
null;
811 return $this->mTitle;
818 $this->mFilteredName =
$title->getDBkey();
820 $this->mFilteredName = $this->mDesiredDestName;
823 # oi_archive_name is max 255 bytes, which include a timestamp and an
824 # exclamation mark, so restrict file name to 240 bytes.
825 if ( strlen( $this->mFilteredName ) > 240 ) {
826 $this->mTitleError = self::FILENAME_TOO_LONG;
827 $this->mTitle =
null;
829 return $this->mTitle;
840 if ( is_null( $nt ) ) {
841 $this->mTitleError = self::ILLEGAL_FILENAME;
842 $this->mTitle =
null;
844 return $this->mTitle;
846 $this->mFilteredName = $nt->getDBkey();
852 list( $partname,
$ext ) = $this->splitExtensions( $this->mFilteredName );
857 $this->mFinalExtension =
'';
859 # No extension, try guessing one
861 $mime = $magic->guessMimeType( $this->mTempPath );
862 if (
$mime !==
'unknown/unknown' ) {
863 # Get a space separated list of extensions
864 $extList = $magic->getExtensionsForType(
$mime );
866 # Set the extension to the canonical extension
867 $this->mFinalExtension = strtok( $extList,
' ' );
869 # Fix up the other variables
870 $this->mFilteredName .=
".{$this->mFinalExtension}";
872 $ext = [ $this->mFinalExtension ];
883 if ( $this->mFinalExtension ==
'' ) {
884 $this->mTitleError = self::FILETYPE_MISSING;
885 $this->mTitle =
null;
887 return $this->mTitle;
888 } elseif ( $blackListedExtensions ||
892 $this->mBlackListedExtensions = $blackListedExtensions;
893 $this->mTitleError = self::FILETYPE_BADTYPE;
894 $this->mTitle =
null;
896 return $this->mTitle;
900 if ( !preg_match(
'/^[\x0-\x7f]*$/', $nt->getText() )
903 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
904 $this->mTitle =
null;
906 return $this->mTitle;
909 # If there was more than one "extension", reassemble the base
910 # filename to prevent bogus complaints about length
913 for ( $i = 0; $i < $iterations; $i++ ) {
914 $partname .=
'.' .
$ext[$i];
918 if ( strlen( $partname ) < 1 ) {
919 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
920 $this->mTitle =
null;
922 return $this->mTitle;
927 return $this->mTitle;
935 public function getLocalFile() {
936 if ( is_null( $this->mLocalFile ) ) {
937 $nt = $this->getTitle();
938 $this->mLocalFile = is_null( $nt ) ? null :
wfLocalFile( $nt );
941 return $this->mLocalFile;
947 public function getStashFile() {
948 return $this->mStashFile;
962 public function tryStashFile(
User $user, $isPartial =
false ) {
964 $error = $this->runUploadStashFileHook(
$user );
966 return call_user_func_array(
'Status::newFatal', $error );
970 $file = $this->doStashFile(
$user );
981 protected function runUploadStashFileHook(
User $user ) {
982 $props = $this->mFileProps;
986 if ( !is_array( $error ) ) {
1012 public function stashFile(
User $user =
null ) {
1013 return $this->doStashFile(
$user );
1022 protected function doStashFile(
User $user =
null ) {
1024 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
1025 $this->mStashFile = $file;
1037 public function stashFileGetKey() {
1039 return $this->doStashFile()->getFileKey();
1048 public function stashSession() {
1050 return $this->doStashFile()->getFileKey();
1057 public function cleanupTempFile() {
1058 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1060 wfDebug( __METHOD__ .
": Marked temporary file '{$this->mTempPath}' for removal\n" );
1061 $this->tempFileObj->autocollect();
1065 public function getTempPath() {
1066 return $this->mTempPath;
1078 public static function splitExtensions( $filename ) {
1079 $bits = explode(
'.', $filename );
1080 $basename = array_shift( $bits );
1082 return [ $basename, $bits ];
1093 public static function checkFileExtension(
$ext, $list ) {
1094 return in_array( strtolower(
$ext ), $list );
1105 public static function checkFileExtensionList(
$ext, $list ) {
1106 return array_intersect( array_map(
'strtolower',
$ext ), $list );
1116 public static function verifyExtension(
$mime, $extension ) {
1120 if ( !$magic->isRecognizableExtension( $extension ) ) {
1121 wfDebug( __METHOD__ .
": passing file with unknown detected mime type; " .
1122 "unrecognized extension '$extension', can't verify\n" );
1126 wfDebug( __METHOD__ .
": rejecting file with unknown detected mime type; " .
1127 "recognized extension '$extension', so probably invalid file\n" );
1133 $match = $magic->isMatchingExtension( $extension,
$mime );
1135 if ( $match ===
null ) {
1136 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1137 wfDebug( __METHOD__ .
": No extension known for $mime, but we know a mime for $extension\n" );
1141 wfDebug( __METHOD__ .
": no file extension known for mime type $mime, passing file\n" );
1145 } elseif ( $match ===
true ) {
1146 wfDebug( __METHOD__ .
": mime type $mime matches extension $extension, passing file\n" );
1152 .
": mime type $mime mismatches file extension $extension, rejecting file\n" );
1169 public static function detectScript( $file,
$mime, $extension ) {
1172 # ugly hack: for text files, always look at the entire file.
1173 # For binary field, just check the first K.
1175 if ( strpos(
$mime,
'text/' ) === 0 ) {
1176 $chunk = file_get_contents( $file );
1178 $fp = fopen( $file,
'rb' );
1179 $chunk = fread( $fp, 1024 );
1183 $chunk = strtolower( $chunk );
1189 # decode from UTF-16 if needed (could be used for obfuscation).
1190 if ( substr( $chunk, 0, 2 ) ==
"\xfe\xff" ) {
1192 } elseif ( substr( $chunk, 0, 2 ) ==
"\xff\xfe" ) {
1199 $chunk = iconv( $enc,
"ASCII//IGNORE", $chunk );
1202 $chunk = trim( $chunk );
1205 wfDebug( __METHOD__ .
": checking for embedded scripts and HTML stuff\n" );
1207 # check for HTML doctype
1208 if ( preg_match(
"/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1214 if ( $extension ==
'svg' || strpos(
$mime,
'image/svg' ) === 0 ) {
1215 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1239 '<html', # also
in safari
1242 '<script', # also
in safari
1250 foreach ( $tags
as $tag ) {
1251 if (
false !== strpos( $chunk,
$tag ) ) {
1252 wfDebug( __METHOD__ .
": found something that may make it be mistaken for html: $tag\n" );
1262 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1263 $chunk = Sanitizer::decodeCharReferences( $chunk );
1265 # look for script-types
1266 if ( preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1267 wfDebug( __METHOD__ .
": found script types\n" );
1272 # look for html-style script-urls
1273 if ( preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1274 wfDebug( __METHOD__ .
": found html-style script urls\n" );
1279 # look for css-style script-urls
1280 if ( preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1281 wfDebug( __METHOD__ .
": found css-style script urls\n" );
1286 wfDebug( __METHOD__ .
": no scripts found\n" );
1298 public static function checkXMLEncodingMissmatch( $file ) {
1301 $encodingRegex =
'!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1303 if ( preg_match(
"!<\?xml\b(.*?)\?>!si", $contents,
$matches ) ) {
1304 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1305 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1307 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1311 } elseif ( preg_match(
"!<\?xml\b!si", $contents ) ) {
1314 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1317 } elseif ( substr( $contents, 0, 4 ) ==
"\x4C\x6F\xA7\x94" ) {
1319 wfDebug( __METHOD__ .
": EBCDIC Encoded XML\n" );
1326 $attemptEncodings = [
'UTF-16',
'UTF-16BE',
'UTF-32',
'UTF-32BE' ];
1327 foreach ( $attemptEncodings
as $encoding ) {
1328 MediaWiki\suppressWarnings();
1329 $str = iconv( $encoding,
'UTF-8', $contents );
1330 MediaWiki\restoreWarnings();
1331 if ( $str !=
'' && preg_match(
"!<\?xml\b(.*?)\?>!si", $str,
$matches ) ) {
1332 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1333 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1335 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1339 } elseif ( $str !=
'' && preg_match(
"!<\?xml\b!si", $str ) ) {
1342 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1356 protected function detectScriptInSvg( $filename, $partial ) {
1357 $this->mSVGNSError =
false;
1360 [ $this,
'checkSvgScriptCallback' ],
1363 'processing_instruction_handler' =>
'UploadBase::checkSvgPICallback',
1364 'external_dtd_handler' =>
'UploadBase::checkSvgExternalDTD',
1367 if ( $check->wellFormed !==
true ) {
1370 return $partial ?
false : [
'uploadinvalidxml' ];
1371 } elseif ( $check->filterMatch ) {
1372 if ( $this->mSVGNSError ) {
1373 return [
'uploadscriptednamespace', $this->mSVGNSError ];
1376 return $check->filterMatchType;
1388 public static function checkSvgPICallback( $target, $data ) {
1390 if ( preg_match(
'/xml-stylesheet/i', $target ) ) {
1391 return [
'upload-scripted-pi-callback' ];
1407 public static function checkSvgExternalDTD(
$type, $publicId, $systemId ) {
1411 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1412 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1413 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1414 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1416 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1418 if (
$type !==
'PUBLIC'
1419 || !in_array( $systemId, $allowedDTDs )
1420 || strpos( $publicId,
"-//W3C//" ) !== 0
1422 return [
'upload-scripted-dtd' ];
1433 public function checkSvgScriptCallback( $element,
$attribs, $data =
null ) {
1435 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1439 static $validNamespaces = [
1442 'http://creativecommons.org/ns#',
1443 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1444 'http://ns.adobe.com/adobeillustrator/10.0/',
1445 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1446 'http://ns.adobe.com/extensibility/1.0/',
1447 'http://ns.adobe.com/flows/1.0/',
1448 'http://ns.adobe.com/illustrator/1.0/',
1449 'http://ns.adobe.com/imagereplacement/1.0/',
1450 'http://ns.adobe.com/pdf/1.3/',
1451 'http://ns.adobe.com/photoshop/1.0/',
1452 'http://ns.adobe.com/saveforweb/1.0/',
1453 'http://ns.adobe.com/variables/1.0/',
1454 'http://ns.adobe.com/xap/1.0/',
1455 'http://ns.adobe.com/xap/1.0/g/',
1456 'http://ns.adobe.com/xap/1.0/g/img/',
1457 'http://ns.adobe.com/xap/1.0/mm/',
1458 'http://ns.adobe.com/xap/1.0/rights/',
1459 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1460 'http://ns.adobe.com/xap/1.0/stype/font#',
1461 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1462 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1463 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1464 'http://ns.adobe.com/xap/1.0/t/pg/',
1465 'http://purl.org/dc/elements/1.1/',
1466 'http://purl.org/dc/elements/1.1',
1467 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1468 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1469 'http://taptrix.com/inkpad/svg_extensions',
1470 'http://web.resource.org/cc/',
1471 'http://www.freesoftware.fsf.org/bkchem/cdml',
1472 'http://www.inkscape.org/namespaces/inkscape',
1473 'http://www.opengis.net/gml',
1474 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1475 'http://www.w3.org/2000/svg',
1476 'http://www.w3.org/tr/rec-rdf-syntax/',
1477 'http://www.w3.org/2000/01/rdf-schema#',
1482 $isBuggyInkscape = preg_match(
'/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1484 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1485 wfDebug( __METHOD__ .
": Non-svg namespace '$namespace' in uploaded file.\n" );
1487 $this->mSVGNSError = $namespace;
1495 if ( $strippedElement ==
'script' ) {
1496 wfDebug( __METHOD__ .
": Found script element '$element' in uploaded file.\n" );
1498 return [
'uploaded-script-svg', $strippedElement ];
1501 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1502 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1503 if ( $strippedElement ==
'handler' ) {
1504 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1506 return [
'uploaded-script-svg', $strippedElement ];
1509 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1510 if ( $strippedElement ==
'stylesheet' ) {
1511 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1513 return [
'uploaded-script-svg', $strippedElement ];
1516 # Block iframes, in case they pass the namespace check
1517 if ( $strippedElement ==
'iframe' ) {
1518 wfDebug( __METHOD__ .
": iframe in uploaded file.\n" );
1520 return [
'uploaded-script-svg', $strippedElement ];
1524 if ( $strippedElement ==
'style'
1525 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1527 wfDebug( __METHOD__ .
": hostile css in style element.\n" );
1528 return [
'uploaded-hostile-svg' ];
1532 $stripped = $this->stripXmlNamespace( $attrib );
1535 if ( substr( $stripped, 0, 2 ) ==
'on' ) {
1537 .
": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1539 return [
'uploaded-event-handler-on-svg', $attrib,
$value ];
1542 # Do not allow relative links, or unsafe url schemas.
1543 # For <a> tags, only data:, http: and https: and same-document
1544 # fragment links are allowed. For all other tags, only data:
1545 # and fragment are allowed.
1546 if ( $stripped ==
'href'
1548 && strpos(
$value,
'data:' ) !== 0
1549 && strpos(
$value,
'#' ) !== 0
1551 if ( !( $strippedElement ===
'a'
1552 && preg_match(
'!^https?://!i',
$value ) )
1554 wfDebug( __METHOD__ .
": Found href attribute <$strippedElement "
1555 .
"'$attrib'='$value' in uploaded file.\n" );
1557 return [
'uploaded-href-attribute-svg', $strippedElement, $attrib,
$value ];
1561 # only allow data: targets that should be safe. This prevents vectors like,
1562 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1563 if ( $stripped ==
'href' && strncasecmp(
'data:',
$value, 5 ) === 0 ) {
1566 $parameters =
'(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1569 if ( !preg_match(
"!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i",
$value ) ) {
1570 wfDebug( __METHOD__ .
": Found href to unwhitelisted data: uri "
1571 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1572 return [
'uploaded-href-unsafe-target-svg', $strippedElement, $attrib,
$value ];
1576 # Change href with animate from (http://html5sec.org/#137).
1577 if ( $stripped ===
'attributename'
1578 && $strippedElement ===
'animate'
1579 && $this->stripXmlNamespace(
$value ) ==
'href'
1581 wfDebug( __METHOD__ .
": Found animate that might be changing href using from "
1582 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1584 return [
'uploaded-animate-svg', $strippedElement, $attrib,
$value ];
1587 # use set/animate to add event-handler attribute to parent
1588 if ( ( $strippedElement ==
'set' || $strippedElement ==
'animate' )
1589 && $stripped ==
'attributename'
1590 && substr(
$value, 0, 2 ) ==
'on'
1592 wfDebug( __METHOD__ .
": Found svg setting event-handler attribute with "
1593 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1595 return [
'uploaded-setting-event-handler-svg', $strippedElement, $stripped,
$value ];
1598 # use set to add href attribute to parent element
1599 if ( $strippedElement ==
'set'
1600 && $stripped ==
'attributename'
1601 && strpos(
$value,
'href' ) !==
false
1603 wfDebug( __METHOD__ .
": Found svg setting href attribute '$value' in uploaded file.\n" );
1605 return [
'uploaded-setting-href-svg' ];
1608 # use set to add a remote / data / script target to an element
1609 if ( $strippedElement ==
'set'
1610 && $stripped ==
'to'
1611 && preg_match(
'!(http|https|data|script):!sim',
$value )
1613 wfDebug( __METHOD__ .
": Found svg setting attribute to '$value' in uploaded file.\n" );
1615 return [
'uploaded-wrong-setting-svg',
$value ];
1618 # use handler attribute with remote / data / script
1619 if ( $stripped ==
'handler' && preg_match(
'!(http|https|data|script):!sim',
$value ) ) {
1620 wfDebug( __METHOD__ .
": Found svg setting handler with remote/data/script "
1621 .
"'$attrib'='$value' in uploaded file.\n" );
1623 return [
'uploaded-setting-handler-svg', $attrib,
$value ];
1626 # use CSS styles to bring in remote code
1627 if ( $stripped ==
'style'
1628 && self::checkCssFragment( Sanitizer::normalizeCss(
$value ) )
1630 wfDebug( __METHOD__ .
": Found svg setting a style with "
1631 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1632 return [
'uploaded-remote-url-svg', $attrib,
$value ];
1635 # Several attributes can include css, css character escaping isn't allowed
1636 $cssAttrs = [
'font',
'clip-path',
'fill',
'filter',
'marker',
1637 'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke' ];
1638 if ( in_array( $stripped, $cssAttrs )
1639 && self::checkCssFragment(
$value )
1641 wfDebug( __METHOD__ .
": Found svg setting a style with "
1642 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1643 return [
'uploaded-remote-url-svg', $attrib,
$value ];
1646 # image filters can pull in url, which could be svg that executes scripts
1647 if ( $strippedElement ==
'image'
1648 && $stripped ==
'filter'
1649 && preg_match(
'!url\s*\(!sim',
$value )
1651 wfDebug( __METHOD__ .
": Found image filter with url: "
1652 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1654 return [
'uploaded-image-filter-svg', $strippedElement, $stripped,
$value ];
1668 private static function checkCssFragment(
$value ) {
1670 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1671 if ( stripos(
$value,
'@import' ) !==
false ) {
1675 # We allow @font-face to embed fonts with data: urls, so we snip the string
1676 # 'url' out so this case won't match when we check for urls below
1677 $pattern =
'!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1680 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1681 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1682 # Expression and -o-link don't seem to work either, but filtering them here in case.
1683 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1684 # but not local ones such as url("#..., url('#..., url(#....
1685 if ( preg_match(
'!expression
1687 | -o-link-source\s*:
1688 | -o-replace\s*:!imx',
$value ) ) {
1692 if ( preg_match_all(
1693 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1698 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1700 if ( !preg_match(
"!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1706 if ( preg_match(
'/[\000-\010\013\016-\037\177]/',
$value ) ) {
1718 private static function splitXmlNamespace( $element ) {
1720 $parts = explode(
':', strtolower( $element ) );
1721 $name = array_pop( $parts );
1722 $ns = implode(
':', $parts );
1724 return [ $ns,
$name ];
1731 private function stripXmlNamespace(
$name ) {
1733 $parts = explode(
':', strtolower(
$name ) );
1735 return array_pop( $parts );
1748 public static function detectVirus( $file ) {
1752 wfDebug( __METHOD__ .
": virus scanner disabled\n" );
1758 wfDebug( __METHOD__ .
": unknown virus scanner: $wgAntivirus\n" );
1759 $wgOut->wrapWikiMsg(
"<div class=\"error\">\n$1\n</div>",
1762 return wfMessage(
'virus-unknownscanner' )->text() .
" $wgAntivirus";
1765 # look up scanner configuration
1771 if ( strpos(
$command,
"%f" ) ===
false ) {
1772 # simple pattern: append file to scan
1775 # complex pattern: replace "%f" with file to scan
1779 wfDebug( __METHOD__ .
": running virus scan: $command \n" );
1781 # execute virus scanner
1784 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1785 # that does not seem to be worth the pain.
1786 # Ask me (Duesentrieb) about it if it's ever needed.
1789 # map exit code to AV_xxx constants.
1790 $mappedCode = $exitCode;
1791 if ( $exitCodeMap ) {
1792 if ( isset( $exitCodeMap[$exitCode] ) ) {
1793 $mappedCode = $exitCodeMap[$exitCode];
1794 } elseif ( isset( $exitCodeMap[
"*"] ) ) {
1795 $mappedCode = $exitCodeMap[
"*"];
1803 # scan failed (code was mapped to false by $exitCodeMap)
1804 wfDebug( __METHOD__ .
": failed to scan $file (code $exitCode).\n" );
1807 ?
wfMessage(
'virus-scanfailed', [ $exitCode ] )->text()
1810 # scan failed because filetype is unknown (probably imune)
1811 wfDebug( __METHOD__ .
": unsupported file type $file (code $exitCode).\n" );
1815 wfDebug( __METHOD__ .
": file passed virus scan.\n" );
1822 } elseif ( $msgPattern ) {
1824 if ( preg_match( $msgPattern, $output, $groups ) ) {
1826 $output = $groups[1];
1831 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1845 private function checkOverwrite( $user ) {
1846 // First check whether the local file can be overwritten
1847 $file = $this->getLocalFile();
1848 $file->load( File::READ_LATEST );
1849 if ( $file->exists() ) {
1850 if ( !self::userCanReUpload( $user, $file ) ) {
1851 return [ 'fileexists-forbidden
', $file->getName() ];
1857 /* Check shared conflicts: if the local file does not exist, but
1858 * wfFindFile finds a file, it exists in a shared repository.
1860 $file = wfFindFile( $this->getTitle(), [ 'latest
' => true ] );
1861 if ( $file && !$user->isAllowed( 'reupload-shared
' ) ) {
1862 return [ 'fileexists-shared-forbidden
', $file->getName() ];
1875 public static function userCanReUpload( User $user, File $img ) {
1876 if ( $user->isAllowed( 'reupload
' ) ) {
1877 return true; // non-conditional
1878 } elseif ( !$user->isAllowed( 'reupload-
own' ) ) {
1882 if ( !( $img instanceof LocalFile ) ) {
1888 return $user->getId() == $img->getUser( 'id' );
1902 public static function getExistsWarning( $file ) {
1903 if ( $file->exists() ) {
1904 return [ 'warning
' => 'exists
', 'file' => $file ];
1907 if ( $file->getTitle()->getArticleID() ) {
1908 return [ 'warning
' => 'page-exists
', 'file' => $file ];
1911 if ( strpos( $file->getName(), '.
' ) == false ) {
1912 $partname = $file->getName();
1915 $n = strrpos( $file->getName(), '.
' );
1916 $extension = substr( $file->getName(), $n + 1 );
1917 $partname = substr( $file->getName(), 0, $n );
1919 $normalizedExtension = File::normalizeExtension( $extension );
1921 if ( $normalizedExtension != $extension ) {
1922 // We're
not using the normalized
form of the extension.
1930 if ( $file_lc->exists() ) {
1932 'warning' =>
'exists-normalized',
1934 'normalizedFile' => $file_lc
1941 "{$partname}.", 1 );
1942 if (
count( $similarFiles ) ) {
1944 'warning' =>
'exists-normalized',
1946 'normalizedFile' => $similarFiles[0],
1950 if ( self::isThumbName( $file->getName() ) ) {
1951 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1953 substr( $partname, strpos( $partname,
'-' ) + 1 ) .
'.' . $extension,
1957 if ( $file_thb->exists() ) {
1959 'warning' =>
'thumb',
1961 'thumbFile' => $file_thb
1966 'warning' =>
'thumb-name',
1968 'thumbFile' => $file_thb
1973 foreach ( self::getFilenamePrefixBlacklist()
as $prefix ) {
1974 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1976 'warning' =>
'bad-prefix',
1991 public static function isThumbName( $filename ) {
1992 $n = strrpos( $filename,
'.' );
1993 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1996 substr( $partname, 3, 3 ) ==
'px-' ||
1997 substr( $partname, 2, 3 ) ==
'px-'
1999 preg_match(
"/[0-9]{2}/", substr( $partname, 0, 2 ) );
2007 public static function getFilenamePrefixBlacklist() {
2009 $message =
wfMessage(
'filename-prefix-blacklist' )->inContentLanguage();
2010 if ( !$message->isDisabled() ) {
2011 $lines = explode(
"\n", $message->plain() );
2014 $comment = substr( trim(
$line ), 0, 1 );
2015 if ( $comment ==
'#' || $comment ==
'' ) {
2019 $comment = strpos(
$line,
'#' );
2020 if ( $comment > 0 ) {
2023 $blacklist[] = trim(
$line );
2041 public function getImageInfo(
$result ) {
2042 $localFile = $this->getLocalFile();
2043 $stashFile = $this->getStashFile();
2061 public function convertVerifyErrorToStatus( $error ) {
2062 $code = $error[
'status'];
2063 unset(
$code[
'status'] );
2075 public static function getMaxUploadSize( $forType =
null ) {
2096 public static function getMaxPhpUploadSize() {
2098 ini_get(
'upload_max_filesize' ) ?: ini_get(
'hhvm.server.upload.upload_max_file_size' ),
2102 ini_get(
'post_max_size' ) ?: ini_get(
'hhvm.server.max_post_size' ),
2105 return min( $phpMaxFileSize, $phpMaxPostSize );
2117 public static function getSessionStatus(
User $user, $statusKey ) {
2118 $key =
wfMemcKey(
'uploadstatus',
$user->getId() ?: md5(
$user->getName() ), $statusKey );
2120 return MediaWikiServices::getInstance()->getMainObjectStash()->get( $key );
2133 public static function setSessionStatus(
User $user, $statusKey,
$value ) {
2134 $key =
wfMemcKey(
'uploadstatus',
$user->getId() ?: md5(
$user->getName() ), $statusKey );
2136 $cache = MediaWikiServices::getInstance()->getMainObjectStash();
2137 if (
$value ===
false ) {