38 abstract class UploadBase {
40 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
41 protected $mTitle =
false, $mTitleError = 0;
42 protected $mFilteredName, $mFinalExtension;
43 protected $mLocalFile, $mFileSize, $mFileProps;
44 protected $mBlackListedExtensions;
45 protected $mJavaDetected, $mSVGNSError;
47 protected static $safeXmlEncodings =
array(
'UTF-8',
'ISO-8859-1',
'ISO-8859-2',
'UTF-16',
'UTF-32' );
52 const MIN_LENGTH_PARTNAME = 4;
53 const ILLEGAL_FILENAME = 5;
54 const OVERWRITE_EXISTING_FILE = 7; # Not
used anymore; handled by verifyTitlePermissions()
55 const FILETYPE_MISSING = 8;
56 const FILETYPE_BADTYPE = 9;
57 const VERIFICATION_ERROR = 10;
59 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60 const UPLOAD_VERIFICATION_ERROR = 11;
61 const HOOK_ABORTED = 11;
62 const FILE_TOO_LARGE = 12;
63 const WINDOWS_NONASCII_FILENAME = 13;
64 const FILENAME_TOO_LONG = 14;
66 const SESSION_STATUS_KEY =
'wsUploadStatusData';
72 public function getVerificationErrorCode(
$error ) {
73 $code_to_status =
array(
74 self::EMPTY_FILE =>
'empty-file',
75 self::FILE_TOO_LARGE =>
'file-too-large',
76 self::FILETYPE_MISSING =>
'filetype-missing',
77 self::FILETYPE_BADTYPE =>
'filetype-banned',
78 self::MIN_LENGTH_PARTNAME =>
'filename-tooshort',
79 self::ILLEGAL_FILENAME =>
'illegal-filename',
80 self::OVERWRITE_EXISTING_FILE =>
'overwrite',
81 self::VERIFICATION_ERROR =>
'verification-error',
82 self::HOOK_ABORTED =>
'hookaborted',
83 self::WINDOWS_NONASCII_FILENAME =>
'windows-nonascii-filename',
84 self::FILENAME_TOO_LONG =>
'filename-toolong',
86 if ( isset( $code_to_status[
$error] ) ) {
87 return $code_to_status[
$error];
90 return 'unknown-error';
98 public static function isEnabled() {
101 if ( !$wgEnableUploads ) {
105 # Check php's file_uploads setting
117 public static function isAllowed(
$user ) {
118 foreach (
array(
'upload',
'edit' )
as $permission ) {
119 if ( !
$user->isAllowed( $permission ) ) {
132 public static function isThrottled(
$user ) {
133 return $user->pingLimiter(
'upload' );
137 static $uploadHandlers =
array(
'Stash',
'File',
'Url' );
146 public static function createFromRequest( &
$request,
$type =
null ) {
159 if ( is_null( $className ) ) {
160 $className =
'UploadFrom' .
$type;
161 wfDebug( __METHOD__ .
": class name: $className\n" );
162 if ( !in_array(
$type, self::$uploadHandlers ) ) {
168 if ( !call_user_func(
array( $className,
'isEnabled' ) ) ) {
173 if ( !call_user_func(
array( $className,
'isValidRequest' ),
$request ) ) {
177 $handler =
new $className;
179 $handler->initializeFromRequest(
$request );
188 public static function isValidRequest(
$request ) {
192 public function __construct() {}
200 public function getSourceType() {
212 public function initializePathInfo(
$name, $tempPath, $fileSize, $removeTempFile =
false ) {
213 $this->mDesiredDestName =
$name;
215 throw new MWException( __METHOD__ .
" given storage path `$tempPath`." );
217 $this->mTempPath = $tempPath;
218 $this->mFileSize = $fileSize;
219 $this->mRemoveTempFile = $removeTempFile;
225 abstract public function initializeFromRequest( &
$request );
231 public function fetchFile() {
239 public function isEmptyFile() {
240 return empty( $this->mFileSize );
247 public function getFileSize() {
248 return $this->mFileSize;
255 public function getTempFileSha1Base36() {
263 function getRealPath( $srcPath ) {
266 if ( $repo->isVirtualUrl( $srcPath ) ) {
269 $tmpFile = $repo->getLocalCopy( $srcPath );
271 $tmpFile->bind( $this );
273 $path = $tmpFile ? $tmpFile->getPath() :
false;
285 public function verifyUpload() {
291 if ( $this->isEmptyFile() ) {
293 return array(
'status' => self::EMPTY_FILE );
299 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
300 if ( $this->mFileSize > $maxSize ) {
303 'status' => self::FILE_TOO_LARGE,
313 $verification = $this->verifyFile();
314 if ( $verification !==
true ) {
317 'status' => self::VERIFICATION_ERROR,
318 'details' => $verification
325 $result = $this->validateName();
333 array( $this->mDestName, $this->mTempPath, &
$error ) )
336 return array(
'status' => self::HOOK_ABORTED,
'error' =>
$error );
340 return array(
'status' => self::OK );
349 public function validateName() {
350 $nt = $this->getTitle();
351 if ( is_null( $nt ) ) {
353 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
354 $result[
'filtered'] = $this->mFilteredName;
356 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
357 $result[
'finalExt'] = $this->mFinalExtension;
358 if ( count( $this->mBlackListedExtensions ) ) {
359 $result[
'blacklistedExt'] = $this->mBlackListedExtensions;
364 $this->mDestName = $this->getLocalFile()->
getName();
377 protected function verifyMimeType(
$mime ) {
380 if ( $wgVerifyMimeType ) {
381 wfDebug(
"\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
382 global $wgMimeTypeBlacklist;
383 if ( $this->checkFileExtension(
$mime, $wgMimeTypeBlacklist ) ) {
389 $fp = fopen( $this->mTempPath,
'rb' );
390 $chunk = fread( $fp, 256 );
393 $magic = MimeMagic::singleton();
394 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
395 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
396 foreach ( $ieTypes
as $ieType ) {
397 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
399 return array(
'filetype-bad-ie-mime', $ieType );
413 protected function verifyFile() {
417 $status = $this->verifyPartialFile();
418 if ( $status !==
true ) {
424 $mime = $this->mFileProps[
'file-mime'];
426 if ( $wgVerifyMimeType ) {
427 # XXX: Missing extension will be caught by validateName() via getTitle()
428 if ( $this->mFinalExtension !=
'' && !$this->verifyExtension(
$mime, $this->mFinalExtension ) ) {
430 return array(
'filetype-mime-mismatch', $this->mFinalExtension,
$mime );
436 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
437 if ( !$handlerStatus->isOK() ) {
438 $errors = $handlerStatus->getErrorsArray();
440 return reset( $errors );
445 if ( $status !==
true ) {
450 wfDebug( __METHOD__ .
": all clear; passing.\n" );
463 protected function verifyPartialFile() {
464 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
467 # getTitle() sets some internal parameters like $this->mFinalExtension
472 # check mime type, if desired
473 $mime = $this->mFileProps[
'file-mime'];
474 $status = $this->verifyMimeType(
$mime );
475 if ( $status !==
true ) {
480 # check for htmlish code and javascript
481 if ( !$wgDisableUploadScriptChecks ) {
482 if ( self::detectScript( $this->mTempPath,
$mime, $this->mFinalExtension ) ) {
484 return array(
'uploadscripted' );
486 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
487 $svgStatus = $this->detectScriptInSvg( $this->mTempPath );
488 if ( $svgStatus !==
false ) {
495 # Check for Java applets, which if uploaded can bypass cross-site
497 if ( !$wgAllowJavaUploads ) {
498 $this->mJavaDetected =
false;
500 array( $this,
'zipEntryCallback' ) );
501 if ( !$zipStatus->isOK() ) {
502 $errors = $zipStatus->getErrorsArray();
503 $error = reset( $errors );
504 if (
$error[0] !==
'zip-wrong-format' ) {
509 if ( $this->mJavaDetected ) {
511 return array(
'uploadjava' );
515 # Scan the uploaded file for viruses
516 $virus = $this->detectVirus( $this->mTempPath );
519 return array(
'uploadvirus', $virus );
529 function zipEntryCallback( $entry ) {
530 $names =
array( $entry[
'name'] );
537 $nullPos = strpos( $entry[
'name'],
"\000" );
538 if ( $nullPos !==
false ) {
539 $names[] = substr( $entry[
'name'], 0, $nullPos );
544 if ( preg_grep(
'!\.class/?$!', $names ) ) {
545 $this->mJavaDetected =
true;
556 public function verifyPermissions(
$user ) {
557 return $this->verifyTitlePermissions(
$user );
571 public function verifyTitlePermissions(
$user ) {
576 $nt = $this->getTitle();
577 if ( is_null( $nt ) ) {
580 $permErrors = $nt->getUserPermissionsErrors(
'edit',
$user );
581 $permErrorsUpload = $nt->getUserPermissionsErrors(
'upload',
$user );
582 if ( !$nt->exists() ) {
583 $permErrorsCreate = $nt->getUserPermissionsErrors(
'create',
$user );
585 $permErrorsCreate =
array();
587 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
588 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsUpload, $permErrors ) );
589 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsCreate, $permErrors ) );
593 $overwriteError = $this->checkOverwrite(
$user );
594 if ( $overwriteError !==
true ) {
595 return array( $overwriteError );
608 public function checkWarnings() {
614 $localFile = $this->getLocalFile();
615 $filename = $localFile->getName();
621 $comparableName = str_replace(
' ',
'_', $this->mDesiredDestName );
624 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
625 $warnings[
'badfilename'] = $filename;
627 wfDebugLog(
'upload',
"Filename: '$filename', mDesiredDestName: '$this->mDesiredDestName', comparableName: '$comparableName'" );
632 if ( $wgCheckFileExtensions ) {
634 if ( !$this->checkFileExtension( $this->mFinalExtension,
$extensions ) ) {
635 $warnings[
'filetype-unwanted-type'] =
array( $this->mFinalExtension,
640 global $wgUploadSizeWarning;
641 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
642 $warnings[
'large-file'] =
array( $wgUploadSizeWarning, $this->mFileSize );
645 if ( $this->mFileSize == 0 ) {
646 $warnings[
'emptyfile'] =
true;
649 $exists = self::getExistsWarning( $localFile );
650 if ( $exists !==
false ) {
651 $warnings[
'exists'] = $exists;
655 $hash = $this->getTempFileSha1Base36();
657 $title = $this->getTitle();
659 foreach ( $dupes
as $key => $dupe ) {
660 if (
$title->equals( $dupe->getTitle() ) ) {
661 unset( $dupes[$key] );
665 $warnings[
'duplicate'] = $dupes;
669 $archivedImage =
new ArchivedFile(
null, 0,
"{$hash}.{$this->mFinalExtension}" );
670 if ( $archivedImage->getID() > 0 ) {
672 $warnings[
'duplicate-archive'] = $archivedImage->getName();
674 $warnings[
'duplicate-archive'] =
'';
693 public function performUpload(
$comment, $pageText, $watch,
$user ) {
696 $status = $this->getLocalFile()->upload(
706 if ( $status->isGood() ) {
723 public function getTitle() {
724 if ( $this->mTitle !==
false ) {
725 return $this->mTitle;
732 $this->mFilteredName =
$title->getDBkey();
734 $this->mFilteredName = $this->mDesiredDestName;
737 # oi_archive_name is max 255 bytes, which include a timestamp and an
738 # exclamation mark, so restrict file name to 240 bytes.
739 if ( strlen( $this->mFilteredName ) > 240 ) {
740 $this->mTitleError = self::FILENAME_TOO_LONG;
741 $this->mTitle =
null;
742 return $this->mTitle;
753 if ( is_null( $nt ) ) {
754 $this->mTitleError = self::ILLEGAL_FILENAME;
755 $this->mTitle =
null;
756 return $this->mTitle;
758 $this->mFilteredName = $nt->getDBkey();
764 list( $partname,
$ext ) = $this->splitExtensions( $this->mFilteredName );
766 if ( count(
$ext ) ) {
767 $this->mFinalExtension = trim(
$ext[count(
$ext ) - 1] );
769 $this->mFinalExtension =
'';
771 # No extension, try guessing one
772 $magic = MimeMagic::singleton();
773 $mime = $magic->guessMimeType( $this->mTempPath );
774 if (
$mime !==
'unknown/unknown' ) {
775 # Get a space separated list of extensions
776 $extList = $magic->getExtensionsForType(
$mime );
778 # Set the extension to the canonical extension
779 $this->mFinalExtension = strtok( $extList,
' ' );
781 # Fix up the other variables
782 $this->mFilteredName .=
".{$this->mFinalExtension}";
790 global $wgCheckFileExtensions, $wgStrictFileExtensions;
793 $blackListedExtensions = $this->checkFileExtensionList(
$ext, $wgFileBlacklist );
795 if ( $this->mFinalExtension ==
'' ) {
796 $this->mTitleError = self::FILETYPE_MISSING;
797 $this->mTitle =
null;
798 return $this->mTitle;
799 } elseif ( $blackListedExtensions ||
800 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
802 $this->mBlackListedExtensions = $blackListedExtensions;
803 $this->mTitleError = self::FILETYPE_BADTYPE;
804 $this->mTitle =
null;
805 return $this->mTitle;
809 if (
wfIsWindows() && !preg_match(
'/^[\x0-\x7f]*$/', $nt->getText() ) ) {
810 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
811 $this->mTitle =
null;
812 return $this->mTitle;
815 # If there was more than one "extension", reassemble the base
816 # filename to prevent bogus complaints about length
817 if ( count(
$ext ) > 1 ) {
818 for ( $i = 0; $i < count(
$ext ) - 1; $i++ ) {
819 $partname .=
'.' .
$ext[$i];
823 if ( strlen( $partname ) < 1 ) {
824 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
825 $this->mTitle =
null;
826 return $this->mTitle;
830 return $this->mTitle;
838 public function getLocalFile() {
839 if ( is_null( $this->mLocalFile ) ) {
840 $nt = $this->getTitle();
841 $this->mLocalFile = is_null( $nt ) ? null :
wfLocalFile( $nt );
843 return $this->mLocalFile;
858 public function stashFile(
User $user =
null ) {
863 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
864 $this->mLocalFile =
$file;
875 public function stashFileGetKey() {
876 return $this->stashFile()->getFileKey();
884 public function stashSession() {
885 return $this->stashFileGetKey();
892 public function cleanupTempFile() {
893 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
894 wfDebug( __METHOD__ .
": Removing temporary file {$this->mTempPath}\n" );
895 unlink( $this->mTempPath );
899 public function getTempPath() {
900 return $this->mTempPath;
912 public static function splitExtensions( $filename ) {
913 $bits = explode(
'.', $filename );
914 $basename = array_shift( $bits );
915 return array( $basename, $bits );
926 public static function checkFileExtension(
$ext, $list ) {
927 return in_array( strtolower(
$ext ), $list );
938 public static function checkFileExtensionList(
$ext, $list ) {
939 return array_intersect( array_map(
'strtolower',
$ext ), $list );
949 public static function verifyExtension(
$mime, $extension ) {
950 $magic = MimeMagic::singleton();
953 if ( !$magic->isRecognizableExtension( $extension ) ) {
954 wfDebug( __METHOD__ .
": passing file with unknown detected mime type; " .
955 "unrecognized extension '$extension', can't verify\n" );
958 wfDebug( __METHOD__ .
": rejecting file with unknown detected mime type; " .
959 "recognized extension '$extension', so probably invalid file\n" );
964 $match = $magic->isMatchingExtension( $extension,
$mime );
966 if ( $match ===
null ) {
967 if ( $magic->getTypesForExtension( $extension ) !== null ) {
968 wfDebug( __METHOD__ .
": No extension known for $mime, but we know a mime for $extension\n" );
971 wfDebug( __METHOD__ .
": no file extension known for mime type $mime, passing file\n" );
974 } elseif ( $match ===
true ) {
975 wfDebug( __METHOD__ .
": mime type $mime matches extension $extension, passing file\n" );
977 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
981 wfDebug( __METHOD__ .
": mime type $mime mismatches file extension $extension, rejecting file\n" );
997 public static function detectScript(
$file,
$mime, $extension ) {
998 global $wgAllowTitlesInSVG;
1001 # ugly hack: for text files, always look at the entire file.
1002 # For binary field, just check the first K.
1004 if ( strpos(
$mime,
'text/' ) === 0 ) {
1005 $chunk = file_get_contents(
$file );
1007 $fp = fopen(
$file,
'rb' );
1008 $chunk = fread( $fp, 1024 );
1012 $chunk = strtolower( $chunk );
1019 # decode from UTF-16 if needed (could be used for obfuscation).
1020 if ( substr( $chunk, 0, 2 ) ==
"\xfe\xff" ) {
1022 } elseif ( substr( $chunk, 0, 2 ) ==
"\xff\xfe" ) {
1029 $chunk = iconv( $enc,
"ASCII//IGNORE", $chunk );
1032 $chunk = trim( $chunk );
1034 # @todo FIXME: Convert from UTF-16 if necessary!
1035 wfDebug( __METHOD__ .
": checking for embedded scripts and HTML stuff\n" );
1037 # check for HTML doctype
1038 if ( preg_match(
"/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1045 if ( $extension ==
'svg' || strpos(
$mime,
'image/svg' ) === 0 ) {
1046 if ( self::checkXMLEncodingMissmatch(
$file ) ) {
1071 '<html', #also
in safari
1074 '<script', #also
in safari
1078 if ( !$wgAllowTitlesInSVG && $extension !==
'svg' &&
$mime !==
'image/svg' ) {
1082 foreach ( $tags
as $tag ) {
1083 if (
false !== strpos( $chunk, $tag ) ) {
1084 wfDebug( __METHOD__ .
": found something that may make it be mistaken for html: $tag\n" );
1094 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1097 # look for script-types
1098 if ( preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1099 wfDebug( __METHOD__ .
": found script types\n" );
1104 # look for html-style script-urls
1105 if ( preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1106 wfDebug( __METHOD__ .
": found html-style script urls\n" );
1111 # look for css-style script-urls
1112 if ( preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1113 wfDebug( __METHOD__ .
": found css-style script urls\n" );
1118 wfDebug( __METHOD__ .
": no scripts found\n" );
1130 public static function checkXMLEncodingMissmatch(
$file ) {
1131 global $wgSVGMetadataCutoff;
1132 $contents = file_get_contents(
$file,
false,
null, -1, $wgSVGMetadataCutoff );
1133 $encodingRegex =
'!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1135 if ( preg_match(
"!<\?xml\b(.*?)\?>!si", $contents,
$matches ) ) {
1136 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1137 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1139 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1142 } elseif ( preg_match(
"!<\?xml\b!si", $contents ) ) {
1145 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1147 } elseif ( substr( $contents, 0, 4 ) ==
"\x4C\x6F\xA7\x94" ) {
1149 wfDebug( __METHOD__ .
": EBCDIC Encoded XML\n" );
1155 $attemptEncodings =
array(
'UTF-16',
'UTF-16BE',
'UTF-32',
'UTF-32BE' );
1156 foreach ( $attemptEncodings
as $encoding ) {
1158 $str = iconv( $encoding,
'UTF-8', $contents );
1160 if ( $str !=
'' && preg_match(
"!<\?xml\b(.*?)\?>!si", $str,
$matches ) ) {
1161 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1162 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1164 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1167 } elseif ( $str !=
'' && preg_match(
"!<\?xml\b!si", $str ) ) {
1170 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1182 protected function detectScriptInSvg( $filename ) {
1183 $this->mSVGNSError =
false;
1186 array( $this,
'checkSvgScriptCallback' ),
1188 array(
'processing_instruction_handler' =>
'UploadBase::checkSvgPICallback' )
1190 if ( $check->wellFormed !==
true ) {
1192 return array(
'uploadinvalidxml' );
1193 } elseif ( $check->filterMatch ) {
1194 if ( $this->mSVGNSError ) {
1195 return array(
'uploadscriptednamespace', $this->mSVGNSError );
1197 return array(
'uploadscripted' );
1208 public static function checkSvgPICallback( $target, $data ) {
1210 if ( preg_match(
'/xml-stylesheet/i', $target ) ) {
1222 public function checkSvgScriptCallback( $element,
$attribs, $data =
null ) {
1224 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1226 static $validNamespaces =
array(
1229 'http://creativecommons.org/ns#',
1230 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1231 'http://ns.adobe.com/adobeillustrator/10.0/',
1232 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1233 'http://ns.adobe.com/extensibility/1.0/',
1234 'http://ns.adobe.com/flows/1.0/',
1235 'http://ns.adobe.com/illustrator/1.0/',
1236 'http://ns.adobe.com/imagereplacement/1.0/',
1237 'http://ns.adobe.com/pdf/1.3/',
1238 'http://ns.adobe.com/photoshop/1.0/',
1239 'http://ns.adobe.com/saveforweb/1.0/',
1240 'http://ns.adobe.com/variables/1.0/',
1241 'http://ns.adobe.com/xap/1.0/',
1242 'http://ns.adobe.com/xap/1.0/g/',
1243 'http://ns.adobe.com/xap/1.0/g/img/',
1244 'http://ns.adobe.com/xap/1.0/mm/',
1245 'http://ns.adobe.com/xap/1.0/rights/',
1246 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1247 'http://ns.adobe.com/xap/1.0/stype/font#',
1248 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1249 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1250 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1251 'http://ns.adobe.com/xap/1.0/t/pg/',
1252 'http://purl.org/dc/elements/1.1/',
1253 'http://purl.org/dc/elements/1.1',
1254 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1255 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1256 'http://web.resource.org/cc/',
1257 'http://www.freesoftware.fsf.org/bkchem/cdml',
1258 'http://www.inkscape.org/namespaces/inkscape',
1259 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1260 'http://www.w3.org/2000/svg',
1263 if ( !in_array( $namespace, $validNamespaces ) ) {
1264 wfDebug( __METHOD__ .
": Non-svg namespace '$namespace' in uploaded file.\n" );
1266 $this->mSVGNSError = $namespace;
1273 if ( $strippedElement ==
'script' ) {
1274 wfDebug( __METHOD__ .
": Found script element '$element' in uploaded file.\n" );
1278 # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1279 if ( $strippedElement ==
'handler' ) {
1280 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1284 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1285 if ( $strippedElement ==
'stylesheet' ) {
1286 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1290 # Block iframes, in case they pass the namespace check
1291 if ( $strippedElement ==
'iframe' ) {
1292 wfDebug( __METHOD__ .
": iframe in uploaded file.\n" );
1297 if ( $strippedElement ==
'style'
1300 wfDebug( __METHOD__ .
": hostile css in style element.\n" );
1305 $stripped = $this->stripXmlNamespace( $attrib );
1308 if ( substr( $stripped, 0, 2 ) ==
'on' ) {
1309 wfDebug( __METHOD__ .
": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1313 # href with non-local target (don't allow http://, javascript:, etc)
1314 if ( $stripped ==
'href'
1315 && strpos(
$value,
'data:' ) !== 0
1316 && strpos(
$value,
'#' ) !== 0
1318 if ( !( $strippedElement ===
'a'
1319 && preg_match(
'!^https?://!i',
$value ) )
1321 wfDebug( __METHOD__ .
": Found href attribute <$strippedElement "
1322 .
"'$attrib'='$value' in uploaded file.\n" );
1328 # only allow data: targets that should be safe. This prevents vectors like,
1329 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1330 if ( $stripped ==
'href' && strncasecmp(
'data:',
$value, 5 ) === 0 ) {
1332 $parameters =
'(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1333 if ( !preg_match(
"!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i",
$value ) ) {
1334 wfDebug( __METHOD__ .
": Found href to unwhitelisted data: uri "
1335 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1340 # Change href with animate from (http://html5sec.org/#137).
1341 if ( $stripped ===
'attributename'
1342 && $strippedElement ===
'animate'
1343 && $this->stripXmlNamespace(
$value ) ==
'href'
1345 wfDebug( __METHOD__ .
": Found animate that might be changing href using from "
1346 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1351 # use set/animate to add event-handler attribute to parent
1352 if ( ( $strippedElement ==
'set' || $strippedElement ==
'animate' ) && $stripped ==
'attributename' && substr(
$value, 0, 2 ) ==
'on' ) {
1353 wfDebug( __METHOD__ .
": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1357 # use set to add href attribute to parent element
1358 if ( $strippedElement ==
'set' && $stripped ==
'attributename' && strpos(
$value,
'href' ) !==
false ) {
1359 wfDebug( __METHOD__ .
": Found svg setting href attribute '$value' in uploaded file.\n" );
1363 # use set to add a remote / data / script target to an element
1364 if ( $strippedElement ==
'set' && $stripped ==
'to' && preg_match(
'!(http|https|data|script):!sim',
$value ) ) {
1365 wfDebug( __METHOD__ .
": Found svg setting attribute to '$value' in uploaded file.\n" );
1369 # use handler attribute with remote / data / script
1370 if ( $stripped ==
'handler' && preg_match(
'!(http|https|data|script):!sim',
$value ) ) {
1371 wfDebug( __METHOD__ .
": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1375 # use CSS styles to bring in remote code
1376 if ( $stripped ==
'style'
1379 wfDebug( __METHOD__ .
": Found svg setting a style with "
1380 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1384 # Several attributes can include css, css character escaping isn't allowed
1385 $cssAttrs =
array(
'font',
'clip-path',
'fill',
'filter',
'marker',
1386 'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke' );
1387 if ( in_array( $stripped, $cssAttrs )
1388 && self::checkCssFragment(
$value )
1390 wfDebug( __METHOD__ .
": Found svg setting a style with "
1391 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1395 # image filters can pull in url, which could be svg that executes scripts
1396 if ( $strippedElement ==
'image' && $stripped ==
'filter' && preg_match(
'!url\s*\(!sim',
$value ) ) {
1397 wfDebug( __METHOD__ .
": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1413 private static function checkCssFragment(
$value ) {
1415 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1416 if ( stripos(
$value,
'@import' ) !==
false ) {
1420 # We allow @font-face to embed fonts with data: urls, so we snip the string
1421 # 'url' out so this case won't match when we check for urls below
1422 $pattern =
'!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1425 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1426 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1427 # Expression and -o-link don't seem to work either, but filtering them here in case.
1428 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1429 # but not local ones such as url("#..., url('#..., url(#....
1430 if ( preg_match(
'!expression
1432 | -o-link-source\s*:
1433 | -o-replace\s*:!imx',
$value ) ) {
1437 if ( preg_match_all(
1438 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1443 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1445 if ( !preg_match(
"!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1451 if ( preg_match(
'/[\000-\010\013\016-\037\177]/',
$value ) ) {
1463 private static function splitXmlNamespace( $element ) {
1465 $parts = explode(
':', strtolower( $element ) );
1466 $name = array_pop( $parts );
1467 $ns = implode(
':', $parts );
1475 private function stripXmlNamespace(
$name ) {
1477 $parts = explode(
':', strtolower(
$name ) );
1478 return array_pop( $parts );
1491 public static function detectVirus(
$file ) {
1492 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired,
$wgOut;
1495 if ( !$wgAntivirus ) {
1496 wfDebug( __METHOD__ .
": virus scanner disabled\n" );
1501 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1502 wfDebug( __METHOD__ .
": unknown virus scanner: $wgAntivirus\n" );
1503 $wgOut->wrapWikiMsg(
"<div class=\"error\">\n$1\n</div>",
1504 array(
'virus-badscanner', $wgAntivirus ) );
1506 return wfMessage(
'virus-unknownscanner' )->text() .
" $wgAntivirus";
1509 # look up scanner configuration
1510 $command = $wgAntivirusSetup[$wgAntivirus][
'command'];
1511 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus][
'codemap'];
1512 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus][
'messagepattern'] ) ?
1513 $wgAntivirusSetup[$wgAntivirus][
'messagepattern'] :
null;
1515 if ( strpos(
$command,
"%f" ) ===
false ) {
1516 # simple pattern: append file to scan
1519 # complex pattern: replace "%f" with file to scan
1523 wfDebug( __METHOD__ .
": running virus scan: $command \n" );
1525 # execute virus scanner
1528 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1529 # that does not seem to be worth the pain.
1530 # Ask me (Duesentrieb) about it if it's ever needed.
1533 # map exit code to AV_xxx constants.
1534 $mappedCode = $exitCode;
1535 if ( $exitCodeMap ) {
1536 if ( isset( $exitCodeMap[$exitCode] ) ) {
1537 $mappedCode = $exitCodeMap[$exitCode];
1538 } elseif ( isset( $exitCodeMap[
"*"] ) ) {
1539 $mappedCode = $exitCodeMap[
"*"];
1547 # scan failed (code was mapped to false by $exitCodeMap)
1548 wfDebug( __METHOD__ .
": failed to scan $file (code $exitCode).\n" );
1550 $output = $wgAntivirusRequired ?
wfMessage(
'virus-scanfailed',
array( $exitCode ) )->text() :
null;
1552 # scan failed because filetype is unknown (probably imune)
1553 wfDebug( __METHOD__ .
": unsupported file type $file (code $exitCode).\n" );
1557 wfDebug( __METHOD__ .
": file passed virus scan.\n" );
1564 } elseif ( $msgPattern ) {
1566 if ( preg_match( $msgPattern, $output, $groups ) ) {
1568 $output = $groups[1];
1573 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1576 wfProfileOut( __METHOD__ );
1588 private function checkOverwrite( $user ) {
1589 // First check whether the local file can be overwritten
1590 $file = $this->getLocalFile();
1591 if ( $file->exists() ) {
1592 if ( !self::userCanReUpload( $user, $file ) ) {
1593 return array( 'fileexists-forbidden
', $file->getName() );
1599 /* Check shared conflicts: if the local file does not exist, but
1600 * wfFindFile finds a file, it exists in a shared repository.
1602 $file = wfFindFile( $this->getTitle() );
1603 if ( $file && !$user->isAllowed( 'reupload-shared
' ) ) {
1604 return array( 'fileexists-shared-forbidden
', $file->getName() );
1617 public static function userCanReUpload( User $user, $img ) {
1618 if ( $user->isAllowed( 'reupload
' ) ) {
1619 return true; // non-conditional
1621 if ( !$user->isAllowed( 'reupload-own
' ) ) {
1624 if ( is_string( $img ) ) {
1625 $img = wfLocalFile( $img );
1627 if ( !( $img instanceof LocalFile ) ) {
1631 return $user->getId() == $img->getUser( 'id' );
1645 public static function getExistsWarning( $file ) {
1646 if ( $file->exists() ) {
1647 return array( 'warning
' => 'exists
', 'file' => $file );
1650 if ( $file->getTitle()->getArticleID() ) {
1651 return array( 'warning
' => 'page-exists
', 'file' => $file );
1654 if ( $file->wasDeleted() && !$file->exists() ) {
1655 return array( 'warning
' => 'was-deleted
', 'file' => $file );
1658 if ( strpos( $file->getName(), '.
' ) == false ) {
1659 $partname = $file->getName();
1662 $n = strrpos( $file->getName(), '.
' );
1663 $extension = substr( $file->getName(), $n + 1 );
1664 $partname = substr( $file->getName(), 0, $n );
1666 $normalizedExtension = File::normalizeExtension( $extension );
1668 if ( $normalizedExtension != $extension ) {
1669 // We're not
using the normalized
form of the extension.
1677 if ( $file_lc->exists() ) {
1679 'warning' =>
'exists-normalized',
1681 'normalizedFile' => $file_lc
1688 "{$partname}.", 1 );
1689 if ( count( $similarFiles ) ) {
1691 'warning' =>
'exists-normalized',
1693 'normalizedFile' => $similarFiles[0],
1697 if ( self::isThumbName(
$file->getName() ) ) {
1698 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1701 if ( $file_thb->exists() ) {
1703 'warning' =>
'thumb',
1705 'thumbFile' => $file_thb
1710 'warning' =>
'thumb-name',
1712 'thumbFile' => $file_thb
1717 foreach ( self::getFilenamePrefixBlacklist()
as $prefix ) {
1718 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1720 'warning' =>
'bad-prefix',
1735 public static function isThumbName( $filename ) {
1736 $n = strrpos( $filename,
'.' );
1737 $partname =
$n ? substr( $filename, 0,
$n ) : $filename;
1739 substr( $partname, 3, 3 ) ==
'px-' ||
1740 substr( $partname, 2, 3 ) ==
'px-'
1742 preg_match(
"/[0-9]{2}/", substr( $partname, 0, 2 ) );
1750 public static function getFilenamePrefixBlacklist() {
1751 $blacklist =
array();
1752 $message =
wfMessage(
'filename-prefix-blacklist' )->inContentLanguage();
1753 if ( !$message->isDisabled() ) {
1754 $lines = explode(
"\n", $message->plain() );
1766 $blacklist[] = trim(
$line );
1782 public function getImageInfo(
$result ) {
1783 $file = $this->getLocalFile();
1800 public function convertVerifyErrorToStatus(
$error ) {
1801 $code =
$error[
'status'];
1802 unset( $code[
'status'] );
1810 public static function getMaxUploadSize( $forType =
null ) {
1813 if ( is_array( $wgMaxUploadSize ) ) {
1814 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1815 return $wgMaxUploadSize[$forType];
1817 return $wgMaxUploadSize[
'*'];
1820 return intval( $wgMaxUploadSize );
1830 public static function getSessionStatus( $statusKey ) {
1831 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1832 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1843 public static function setSessionStatus( $statusKey,
$value ) {
1844 if (
$value ===
false ) {
1845 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1847 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] =
$value;