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 ) ) {
127 static $uploadHandlers =
array(
'Stash',
'File',
'Url' );
136 public static function createFromRequest( &$request,
$type =
null ) {
149 if ( is_null( $className ) ) {
150 $className =
'UploadFrom' .
$type;
151 wfDebug( __METHOD__ .
": class name: $className\n" );
152 if ( !in_array(
$type, self::$uploadHandlers ) ) {
158 if ( !call_user_func(
array( $className,
'isEnabled' ) ) ) {
163 if ( !call_user_func(
array( $className,
'isValidRequest' ), $request ) ) {
167 $handler =
new $className;
169 $handler->initializeFromRequest( $request );
178 public static function isValidRequest( $request ) {
182 public function __construct() {}
190 public function getSourceType() {
202 public function initializePathInfo(
$name, $tempPath, $fileSize, $removeTempFile =
false ) {
203 $this->mDesiredDestName =
$name;
205 throw new MWException( __METHOD__ .
" given storage path `$tempPath`." );
207 $this->mTempPath = $tempPath;
208 $this->mFileSize = $fileSize;
209 $this->mRemoveTempFile = $removeTempFile;
215 abstract public function initializeFromRequest( &$request );
221 public function fetchFile() {
229 public function isEmptyFile() {
230 return empty( $this->mFileSize );
237 public function getFileSize() {
238 return $this->mFileSize;
245 public function getTempFileSha1Base36() {
253 function getRealPath( $srcPath ) {
256 if ( $repo->isVirtualUrl( $srcPath ) ) {
259 $tmpFile = $repo->getLocalCopy( $srcPath );
261 $tmpFile->bind( $this );
263 $path = $tmpFile ? $tmpFile->getPath() :
false;
275 public function verifyUpload() {
281 if ( $this->isEmptyFile() ) {
283 return array(
'status' => self::EMPTY_FILE );
289 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
290 if ( $this->mFileSize > $maxSize ) {
293 'status' => self::FILE_TOO_LARGE,
303 $verification = $this->verifyFile();
304 if ( $verification !==
true ) {
307 'status' => self::VERIFICATION_ERROR,
308 'details' => $verification
315 $result = $this->validateName();
323 array( $this->mDestName, $this->mTempPath, &
$error ) )
326 return array(
'status' => self::HOOK_ABORTED,
'error' =>
$error );
330 return array(
'status' => self::OK );
339 public function validateName() {
340 $nt = $this->getTitle();
341 if ( is_null( $nt ) ) {
343 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
344 $result[
'filtered'] = $this->mFilteredName;
346 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
347 $result[
'finalExt'] = $this->mFinalExtension;
348 if ( count( $this->mBlackListedExtensions ) ) {
349 $result[
'blacklistedExt'] = $this->mBlackListedExtensions;
354 $this->mDestName = $this->getLocalFile()->
getName();
367 protected function verifyMimeType(
$mime ) {
370 if ( $wgVerifyMimeType ) {
371 wfDebug(
"\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
372 global $wgMimeTypeBlacklist;
373 if ( $this->checkFileExtension(
$mime, $wgMimeTypeBlacklist ) ) {
379 $fp = fopen( $this->mTempPath,
'rb' );
380 $chunk = fread( $fp, 256 );
383 $magic = MimeMagic::singleton();
384 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
385 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
386 foreach ( $ieTypes
as $ieType ) {
387 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
389 return array(
'filetype-bad-ie-mime', $ieType );
403 protected function verifyFile() {
407 $status = $this->verifyPartialFile();
408 if ( $status !==
true ) {
414 $mime = $this->mFileProps[
'file-mime'];
416 if ( $wgVerifyMimeType ) {
417 # XXX: Missing extension will be caught by validateName() via getTitle()
418 if ( $this->mFinalExtension !=
'' && !$this->verifyExtension(
$mime, $this->mFinalExtension ) ) {
420 return array(
'filetype-mime-mismatch', $this->mFinalExtension,
$mime );
426 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
427 if ( !$handlerStatus->isOK() ) {
428 $errors = $handlerStatus->getErrorsArray();
430 return reset( $errors );
435 if ( $status !==
true ) {
440 wfDebug( __METHOD__ .
": all clear; passing.\n" );
453 protected function verifyPartialFile() {
454 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
457 # getTitle() sets some internal parameters like $this->mFinalExtension
462 # check mime type, if desired
463 $mime = $this->mFileProps[
'file-mime'];
464 $status = $this->verifyMimeType(
$mime );
465 if ( $status !==
true ) {
470 # check for htmlish code and javascript
471 if ( !$wgDisableUploadScriptChecks ) {
472 if ( self::detectScript( $this->mTempPath,
$mime, $this->mFinalExtension ) ) {
474 return array(
'uploadscripted' );
476 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
477 $svgStatus = $this->detectScriptInSvg( $this->mTempPath );
478 if ( $svgStatus !==
false ) {
485 # Check for Java applets, which if uploaded can bypass cross-site
487 if ( !$wgAllowJavaUploads ) {
488 $this->mJavaDetected =
false;
490 array( $this,
'zipEntryCallback' ) );
491 if ( !$zipStatus->isOK() ) {
492 $errors = $zipStatus->getErrorsArray();
493 $error = reset( $errors );
494 if (
$error[0] !==
'zip-wrong-format' ) {
499 if ( $this->mJavaDetected ) {
501 return array(
'uploadjava' );
505 # Scan the uploaded file for viruses
506 $virus = $this->detectVirus( $this->mTempPath );
509 return array(
'uploadvirus', $virus );
519 function zipEntryCallback( $entry ) {
520 $names =
array( $entry[
'name'] );
527 $nullPos = strpos( $entry[
'name'],
"\000" );
528 if ( $nullPos !==
false ) {
529 $names[] = substr( $entry[
'name'], 0, $nullPos );
534 if ( preg_grep(
'!\.class/?$!', $names ) ) {
535 $this->mJavaDetected =
true;
546 public function verifyPermissions(
$user ) {
547 return $this->verifyTitlePermissions(
$user );
561 public function verifyTitlePermissions(
$user ) {
566 $nt = $this->getTitle();
567 if ( is_null( $nt ) ) {
570 $permErrors = $nt->getUserPermissionsErrors(
'edit',
$user );
571 $permErrorsUpload = $nt->getUserPermissionsErrors(
'upload',
$user );
572 if ( !$nt->exists() ) {
573 $permErrorsCreate = $nt->getUserPermissionsErrors(
'create',
$user );
575 $permErrorsCreate =
array();
577 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
578 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsUpload, $permErrors ) );
579 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsCreate, $permErrors ) );
583 $overwriteError = $this->checkOverwrite(
$user );
584 if ( $overwriteError !==
true ) {
585 return array( $overwriteError );
598 public function checkWarnings() {
604 $localFile = $this->getLocalFile();
605 $filename = $localFile->getName();
611 $comparableName = str_replace(
' ',
'_', $this->mDesiredDestName );
614 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
615 $warnings[
'badfilename'] = $filename;
617 wfDebugLog(
'upload',
"Filename: '$filename', mDesiredDestName: '$this->mDesiredDestName', comparableName: '$comparableName'" );
622 if ( $wgCheckFileExtensions ) {
624 if ( !$this->checkFileExtension( $this->mFinalExtension,
$extensions ) ) {
625 $warnings[
'filetype-unwanted-type'] =
array( $this->mFinalExtension,
630 global $wgUploadSizeWarning;
631 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
632 $warnings[
'large-file'] =
array( $wgUploadSizeWarning, $this->mFileSize );
635 if ( $this->mFileSize == 0 ) {
636 $warnings[
'emptyfile'] =
true;
639 $exists = self::getExistsWarning( $localFile );
640 if ( $exists !==
false ) {
641 $warnings[
'exists'] = $exists;
645 $hash = $this->getTempFileSha1Base36();
647 $title = $this->getTitle();
649 foreach ( $dupes
as $key => $dupe ) {
650 if (
$title->equals( $dupe->getTitle() ) ) {
651 unset( $dupes[$key] );
655 $warnings[
'duplicate'] = $dupes;
659 $archivedImage =
new ArchivedFile(
null, 0,
"{$hash}.{$this->mFinalExtension}" );
660 if ( $archivedImage->getID() > 0 ) {
662 $warnings[
'duplicate-archive'] = $archivedImage->getName();
664 $warnings[
'duplicate-archive'] =
'';
683 public function performUpload(
$comment, $pageText, $watch,
$user ) {
686 $status = $this->getLocalFile()->upload(
696 if ( $status->isGood() ) {
713 public function getTitle() {
714 if ( $this->mTitle !==
false ) {
715 return $this->mTitle;
722 $this->mFilteredName =
$title->getDBkey();
724 $this->mFilteredName = $this->mDesiredDestName;
727 # oi_archive_name is max 255 bytes, which include a timestamp and an
728 # exclamation mark, so restrict file name to 240 bytes.
729 if ( strlen( $this->mFilteredName ) > 240 ) {
730 $this->mTitleError = self::FILENAME_TOO_LONG;
731 $this->mTitle =
null;
732 return $this->mTitle;
743 if ( is_null( $nt ) ) {
744 $this->mTitleError = self::ILLEGAL_FILENAME;
745 $this->mTitle =
null;
746 return $this->mTitle;
748 $this->mFilteredName = $nt->getDBkey();
754 list( $partname,
$ext ) = $this->splitExtensions( $this->mFilteredName );
756 if ( count(
$ext ) ) {
757 $this->mFinalExtension = trim(
$ext[count(
$ext ) - 1] );
759 $this->mFinalExtension =
'';
761 # No extension, try guessing one
762 $magic = MimeMagic::singleton();
763 $mime = $magic->guessMimeType( $this->mTempPath );
764 if (
$mime !==
'unknown/unknown' ) {
765 # Get a space separated list of extensions
766 $extList = $magic->getExtensionsForType(
$mime );
768 # Set the extension to the canonical extension
769 $this->mFinalExtension = strtok( $extList,
' ' );
771 # Fix up the other variables
772 $this->mFilteredName .=
".{$this->mFinalExtension}";
780 global $wgCheckFileExtensions, $wgStrictFileExtensions;
783 $blackListedExtensions = $this->checkFileExtensionList(
$ext, $wgFileBlacklist );
785 if ( $this->mFinalExtension ==
'' ) {
786 $this->mTitleError = self::FILETYPE_MISSING;
787 $this->mTitle =
null;
788 return $this->mTitle;
789 } elseif ( $blackListedExtensions ||
790 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
792 $this->mBlackListedExtensions = $blackListedExtensions;
793 $this->mTitleError = self::FILETYPE_BADTYPE;
794 $this->mTitle =
null;
795 return $this->mTitle;
799 if (
wfIsWindows() && !preg_match(
'/^[\x0-\x7f]*$/', $nt->getText() ) ) {
800 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
801 $this->mTitle =
null;
802 return $this->mTitle;
805 # If there was more than one "extension", reassemble the base
806 # filename to prevent bogus complaints about length
807 if ( count(
$ext ) > 1 ) {
808 for ( $i = 0; $i < count(
$ext ) - 1; $i++ ) {
809 $partname .=
'.' .
$ext[$i];
813 if ( strlen( $partname ) < 1 ) {
814 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
815 $this->mTitle =
null;
816 return $this->mTitle;
820 return $this->mTitle;
828 public function getLocalFile() {
829 if ( is_null( $this->mLocalFile ) ) {
830 $nt = $this->getTitle();
831 $this->mLocalFile = is_null( $nt ) ? null :
wfLocalFile( $nt );
833 return $this->mLocalFile;
848 public function stashFile(
User $user =
null ) {
853 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
854 $this->mLocalFile =
$file;
865 public function stashFileGetKey() {
866 return $this->stashFile()->getFileKey();
874 public function stashSession() {
875 return $this->stashFileGetKey();
882 public function cleanupTempFile() {
883 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
884 wfDebug( __METHOD__ .
": Removing temporary file {$this->mTempPath}\n" );
885 unlink( $this->mTempPath );
889 public function getTempPath() {
890 return $this->mTempPath;
902 public static function splitExtensions( $filename ) {
903 $bits = explode(
'.', $filename );
904 $basename = array_shift( $bits );
905 return array( $basename, $bits );
916 public static function checkFileExtension(
$ext, $list ) {
917 return in_array( strtolower(
$ext ), $list );
928 public static function checkFileExtensionList(
$ext, $list ) {
929 return array_intersect( array_map(
'strtolower',
$ext ), $list );
939 public static function verifyExtension(
$mime, $extension ) {
940 $magic = MimeMagic::singleton();
943 if ( !$magic->isRecognizableExtension( $extension ) ) {
944 wfDebug( __METHOD__ .
": passing file with unknown detected mime type; " .
945 "unrecognized extension '$extension', can't verify\n" );
948 wfDebug( __METHOD__ .
": rejecting file with unknown detected mime type; " .
949 "recognized extension '$extension', so probably invalid file\n" );
954 $match = $magic->isMatchingExtension( $extension,
$mime );
956 if ( $match ===
null ) {
957 if ( $magic->getTypesForExtension( $extension ) !== null ) {
958 wfDebug( __METHOD__ .
": No extension known for $mime, but we know a mime for $extension\n" );
961 wfDebug( __METHOD__ .
": no file extension known for mime type $mime, passing file\n" );
964 } elseif ( $match ===
true ) {
965 wfDebug( __METHOD__ .
": mime type $mime matches extension $extension, passing file\n" );
967 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
971 wfDebug( __METHOD__ .
": mime type $mime mismatches file extension $extension, rejecting file\n" );
987 public static function detectScript(
$file,
$mime, $extension ) {
988 global $wgAllowTitlesInSVG;
991 # ugly hack: for text files, always look at the entire file.
992 # For binary field, just check the first K.
994 if ( strpos(
$mime,
'text/' ) === 0 ) {
995 $chunk = file_get_contents(
$file );
997 $fp = fopen(
$file,
'rb' );
998 $chunk = fread( $fp, 1024 );
1002 $chunk = strtolower( $chunk );
1009 # decode from UTF-16 if needed (could be used for obfuscation).
1010 if ( substr( $chunk, 0, 2 ) ==
"\xfe\xff" ) {
1012 } elseif ( substr( $chunk, 0, 2 ) ==
"\xff\xfe" ) {
1019 $chunk = iconv( $enc,
"ASCII//IGNORE", $chunk );
1022 $chunk = trim( $chunk );
1024 # @todo FIXME: Convert from UTF-16 if necessary!
1025 wfDebug( __METHOD__ .
": checking for embedded scripts and HTML stuff\n" );
1027 # check for HTML doctype
1028 if ( preg_match(
"/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1035 if ( $extension ==
'svg' || strpos(
$mime,
'image/svg' ) === 0 ) {
1036 if ( self::checkXMLEncodingMissmatch(
$file ) ) {
1061 '<html', #also
in safari
1064 '<script', #also
in safari
1068 if ( !$wgAllowTitlesInSVG && $extension !==
'svg' &&
$mime !==
'image/svg' ) {
1072 foreach ( $tags
as $tag ) {
1073 if (
false !== strpos( $chunk, $tag ) ) {
1074 wfDebug( __METHOD__ .
": found something that may make it be mistaken for html: $tag\n" );
1084 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1087 # look for script-types
1088 if ( preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1089 wfDebug( __METHOD__ .
": found script types\n" );
1094 # look for html-style script-urls
1095 if ( preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1096 wfDebug( __METHOD__ .
": found html-style script urls\n" );
1101 # look for css-style script-urls
1102 if ( preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1103 wfDebug( __METHOD__ .
": found css-style script urls\n" );
1108 wfDebug( __METHOD__ .
": no scripts found\n" );
1120 public static function checkXMLEncodingMissmatch(
$file ) {
1121 global $wgSVGMetadataCutoff;
1122 $contents = file_get_contents(
$file,
false,
null, -1, $wgSVGMetadataCutoff );
1123 $encodingRegex =
'!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1125 if ( preg_match(
"!<\?xml\b(.*?)\?>!si", $contents,
$matches ) ) {
1126 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1127 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1129 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1132 } elseif ( preg_match(
"!<\?xml\b!si", $contents ) ) {
1135 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1137 } elseif ( substr( $contents, 0, 4 ) ==
"\x4C\x6F\xA7\x94" ) {
1139 wfDebug( __METHOD__ .
": EBCDIC Encoded XML\n" );
1145 $attemptEncodings =
array(
'UTF-16',
'UTF-16BE',
'UTF-32',
'UTF-32BE' );
1146 foreach ( $attemptEncodings
as $encoding ) {
1148 $str = iconv( $encoding,
'UTF-8', $contents );
1150 if ( $str !=
'' && preg_match(
"!<\?xml\b(.*?)\?>!si", $str,
$matches ) ) {
1151 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1152 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1154 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1157 } elseif ( $str !=
'' && preg_match(
"!<\?xml\b!si", $str ) ) {
1160 wfDebug( __METHOD__ .
": Unmatched XML declaration start\n" );
1172 protected function detectScriptInSvg( $filename ) {
1173 $this->mSVGNSError =
false;
1176 array( $this,
'checkSvgScriptCallback' ),
1178 array(
'processing_instruction_handler' =>
'UploadBase::checkSvgPICallback' )
1180 if ( $check->wellFormed !==
true ) {
1182 return array(
'uploadinvalidxml' );
1183 } elseif ( $check->filterMatch ) {
1184 if ( $this->mSVGNSError ) {
1185 return array(
'uploadscriptednamespace', $this->mSVGNSError );
1187 return array(
'uploadscripted' );
1198 public static function checkSvgPICallback( $target, $data ) {
1200 if ( preg_match(
'/xml-stylesheet/i', $target ) ) {
1212 public function checkSvgScriptCallback( $element,
$attribs, $data =
null ) {
1214 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1216 static $validNamespaces =
array(
1219 'http://creativecommons.org/ns#',
1220 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1221 'http://ns.adobe.com/adobeillustrator/10.0/',
1222 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1223 'http://ns.adobe.com/extensibility/1.0/',
1224 'http://ns.adobe.com/flows/1.0/',
1225 'http://ns.adobe.com/illustrator/1.0/',
1226 'http://ns.adobe.com/imagereplacement/1.0/',
1227 'http://ns.adobe.com/pdf/1.3/',
1228 'http://ns.adobe.com/photoshop/1.0/',
1229 'http://ns.adobe.com/saveforweb/1.0/',
1230 'http://ns.adobe.com/variables/1.0/',
1231 'http://ns.adobe.com/xap/1.0/',
1232 'http://ns.adobe.com/xap/1.0/g/',
1233 'http://ns.adobe.com/xap/1.0/g/img/',
1234 'http://ns.adobe.com/xap/1.0/mm/',
1235 'http://ns.adobe.com/xap/1.0/rights/',
1236 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1237 'http://ns.adobe.com/xap/1.0/stype/font#',
1238 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1239 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1240 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1241 'http://ns.adobe.com/xap/1.0/t/pg/',
1242 'http://purl.org/dc/elements/1.1/',
1243 'http://purl.org/dc/elements/1.1',
1244 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1245 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1246 'http://web.resource.org/cc/',
1247 'http://www.freesoftware.fsf.org/bkchem/cdml',
1248 'http://www.inkscape.org/namespaces/inkscape',
1249 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1250 'http://www.w3.org/2000/svg',
1253 if ( !in_array( $namespace, $validNamespaces ) ) {
1254 wfDebug( __METHOD__ .
": Non-svg namespace '$namespace' in uploaded file.\n" );
1256 $this->mSVGNSError = $namespace;
1263 if ( $strippedElement ==
'script' ) {
1264 wfDebug( __METHOD__ .
": Found script element '$element' in uploaded file.\n" );
1268 # 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>
1269 if ( $strippedElement ==
'handler' ) {
1270 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1274 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1275 if ( $strippedElement ==
'stylesheet' ) {
1276 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file.\n" );
1280 # Block iframes, in case they pass the namespace check
1281 if ( $strippedElement ==
'iframe' ) {
1282 wfDebug( __METHOD__ .
": iframe in uploaded file.\n" );
1287 if ( $strippedElement ==
'style'
1290 wfDebug( __METHOD__ .
": hostile css in style element.\n" );
1295 $stripped = $this->stripXmlNamespace( $attrib );
1298 if ( substr( $stripped, 0, 2 ) ==
'on' ) {
1299 wfDebug( __METHOD__ .
": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1303 # href with non-local target (don't allow http://, javascript:, etc)
1304 if ( $stripped ==
'href'
1305 && strpos(
$value,
'data:' ) !== 0
1306 && strpos(
$value,
'#' ) !== 0
1308 if ( !( $strippedElement ===
'a'
1309 && preg_match(
'!^https?://!im',
$value ) )
1311 wfDebug( __METHOD__ .
": Found href attribute <$strippedElement "
1312 .
"'$attrib'='$value' in uploaded file.\n" );
1318 # only allow data: targets that should be safe. This prevents vectors like,
1319 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1320 if ( $stripped ==
'href' && strncasecmp(
'data:',
$value, 5 ) === 0 ) {
1322 $parameters =
'(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1323 if ( !preg_match(
"!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i",
$value ) ) {
1324 wfDebug( __METHOD__ .
": Found href to unwhitelisted data: uri "
1325 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1330 # Change href with animate from (http://html5sec.org/#137).
1331 if ( $stripped ===
'attributename'
1332 && $strippedElement ===
'animate'
1333 && $this->stripXmlNamespace(
$value ) ==
'href'
1335 wfDebug( __METHOD__ .
": Found animate that might be changing href using from "
1336 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1341 # use set/animate to add event-handler attribute to parent
1342 if ( ( $strippedElement ==
'set' || $strippedElement ==
'animate' ) && $stripped ==
'attributename' && substr(
$value, 0, 2 ) ==
'on' ) {
1343 wfDebug( __METHOD__ .
": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1347 # use set to add href attribute to parent element
1348 if ( $strippedElement ==
'set' && $stripped ==
'attributename' && strpos(
$value,
'href' ) !==
false ) {
1349 wfDebug( __METHOD__ .
": Found svg setting href attribute '$value' in uploaded file.\n" );
1353 # use set to add a remote / data / script target to an element
1354 if ( $strippedElement ==
'set' && $stripped ==
'to' && preg_match(
'!(http|https|data|script):!sim',
$value ) ) {
1355 wfDebug( __METHOD__ .
": Found svg setting attribute to '$value' in uploaded file.\n" );
1359 # use handler attribute with remote / data / script
1360 if ( $stripped ==
'handler' && preg_match(
'!(http|https|data|script):!sim',
$value ) ) {
1361 wfDebug( __METHOD__ .
": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1365 # use CSS styles to bring in remote code
1366 if ( $stripped ==
'style'
1369 wfDebug( __METHOD__ .
": Found svg setting a style with "
1370 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1374 # Several attributes can include css, css character escaping isn't allowed
1375 $cssAttrs =
array(
'font',
'clip-path',
'fill',
'filter',
'marker',
1376 'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke' );
1377 if ( in_array( $stripped, $cssAttrs )
1378 && self::checkCssFragment(
$value )
1380 wfDebug( __METHOD__ .
": Found svg setting a style with "
1381 .
"remote url '$attrib'='$value' in uploaded file.\n" );
1385 # image filters can pull in url, which could be svg that executes scripts
1386 if ( $strippedElement ==
'image' && $stripped ==
'filter' && preg_match(
'!url\s*\(!sim',
$value ) ) {
1387 wfDebug( __METHOD__ .
": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1403 private static function checkCssFragment(
$value ) {
1405 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1406 if ( stripos(
$value,
'@import' ) !==
false ) {
1410 # We allow @font-face to embed fonts with data: urls, so we snip the string
1411 # 'url' out so this case won't match when we check for urls below
1412 $pattern =
'!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1415 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1416 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1417 # Expression and -o-link don't seem to work either, but filtering them here in case.
1418 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1419 # but not local ones such as url("#..., url('#..., url(#....
1420 if ( preg_match(
'!expression
1422 | -o-link-source\s*:
1423 | -o-replace\s*:!imx',
$value ) ) {
1427 if ( preg_match_all(
1428 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1433 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1435 if ( !preg_match(
"!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1441 if ( preg_match(
'/[\000-\010\013\016-\037\177]/',
$value ) ) {
1453 private static function splitXmlNamespace( $element ) {
1455 $parts = explode(
':', strtolower( $element ) );
1456 $name = array_pop( $parts );
1457 $ns = implode(
':', $parts );
1465 private function stripXmlNamespace(
$name ) {
1467 $parts = explode(
':', strtolower(
$name ) );
1468 return array_pop( $parts );
1481 public static function detectVirus(
$file ) {
1482 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired,
$wgOut;
1485 if ( !$wgAntivirus ) {
1486 wfDebug( __METHOD__ .
": virus scanner disabled\n" );
1491 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1492 wfDebug( __METHOD__ .
": unknown virus scanner: $wgAntivirus\n" );
1493 $wgOut->wrapWikiMsg(
"<div class=\"error\">\n$1\n</div>",
1494 array(
'virus-badscanner', $wgAntivirus ) );
1496 return wfMessage(
'virus-unknownscanner' )->text() .
" $wgAntivirus";
1499 # look up scanner configuration
1500 $command = $wgAntivirusSetup[$wgAntivirus][
'command'];
1501 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus][
'codemap'];
1502 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus][
'messagepattern'] ) ?
1503 $wgAntivirusSetup[$wgAntivirus][
'messagepattern'] :
null;
1505 if ( strpos(
$command,
"%f" ) ===
false ) {
1506 # simple pattern: append file to scan
1509 # complex pattern: replace "%f" with file to scan
1513 wfDebug( __METHOD__ .
": running virus scan: $command \n" );
1515 # execute virus scanner
1518 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1519 # that does not seem to be worth the pain.
1520 # Ask me (Duesentrieb) about it if it's ever needed.
1523 # map exit code to AV_xxx constants.
1524 $mappedCode = $exitCode;
1525 if ( $exitCodeMap ) {
1526 if ( isset( $exitCodeMap[$exitCode] ) ) {
1527 $mappedCode = $exitCodeMap[$exitCode];
1528 } elseif ( isset( $exitCodeMap[
"*"] ) ) {
1529 $mappedCode = $exitCodeMap[
"*"];
1537 # scan failed (code was mapped to false by $exitCodeMap)
1538 wfDebug( __METHOD__ .
": failed to scan $file (code $exitCode).\n" );
1540 $output = $wgAntivirusRequired ?
wfMessage(
'virus-scanfailed',
array( $exitCode ) )->text() :
null;
1542 # scan failed because filetype is unknown (probably imune)
1543 wfDebug( __METHOD__ .
": unsupported file type $file (code $exitCode).\n" );
1547 wfDebug( __METHOD__ .
": file passed virus scan.\n" );
1554 } elseif ( $msgPattern ) {
1556 if ( preg_match( $msgPattern, $output, $groups ) ) {
1558 $output = $groups[1];
1563 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1566 wfProfileOut( __METHOD__ );
1578 private function checkOverwrite( $user ) {
1579 // First check whether the local file can be overwritten
1580 $file = $this->getLocalFile();
1581 if ( $file->exists() ) {
1582 if ( !self::userCanReUpload( $user, $file ) ) {
1583 return array( 'fileexists-forbidden
', $file->getName() );
1589 /* Check shared conflicts: if the local file does not exist, but
1590 * wfFindFile finds a file, it exists in a shared repository.
1592 $file = wfFindFile( $this->getTitle() );
1593 if ( $file && !$user->isAllowed( 'reupload-shared
' ) ) {
1594 return array( 'fileexists-shared-forbidden
', $file->getName() );
1607 public static function userCanReUpload( User $user, $img ) {
1608 if ( $user->isAllowed( 'reupload
' ) ) {
1609 return true; // non-conditional
1611 if ( !$user->isAllowed( 'reupload-own
' ) ) {
1614 if ( is_string( $img ) ) {
1615 $img = wfLocalFile( $img );
1617 if ( !( $img instanceof LocalFile ) ) {
1621 return $user->getId() == $img->getUser( 'id' );
1635 public static function getExistsWarning( $file ) {
1636 if ( $file->exists() ) {
1637 return array( 'warning
' => 'exists
', 'file' => $file );
1640 if ( $file->getTitle()->getArticleID() ) {
1641 return array( 'warning
' => 'page-exists
', 'file' => $file );
1644 if ( $file->wasDeleted() && !$file->exists() ) {
1645 return array( 'warning
' => 'was-deleted
', 'file' => $file );
1648 if ( strpos( $file->getName(), '.
' ) == false ) {
1649 $partname = $file->getName();
1652 $n = strrpos( $file->getName(), '.
' );
1653 $extension = substr( $file->getName(), $n + 1 );
1654 $partname = substr( $file->getName(), 0, $n );
1656 $normalizedExtension = File::normalizeExtension( $extension );
1658 if ( $normalizedExtension != $extension ) {
1659 // We're not
using the normalized
form of the extension.
1667 if ( $file_lc->exists() ) {
1669 'warning' =>
'exists-normalized',
1671 'normalizedFile' => $file_lc
1678 "{$partname}.", 1 );
1679 if ( count( $similarFiles ) ) {
1681 'warning' =>
'exists-normalized',
1683 'normalizedFile' => $similarFiles[0],
1687 if ( self::isThumbName(
$file->getName() ) ) {
1688 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1691 if ( $file_thb->exists() ) {
1693 'warning' =>
'thumb',
1695 'thumbFile' => $file_thb
1700 'warning' =>
'thumb-name',
1702 'thumbFile' => $file_thb
1707 foreach ( self::getFilenamePrefixBlacklist()
as $prefix ) {
1708 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1710 'warning' =>
'bad-prefix',
1725 public static function isThumbName( $filename ) {
1726 $n = strrpos( $filename,
'.' );
1727 $partname =
$n ? substr( $filename, 0,
$n ) : $filename;
1729 substr( $partname, 3, 3 ) ==
'px-' ||
1730 substr( $partname, 2, 3 ) ==
'px-'
1732 preg_match(
"/[0-9]{2}/", substr( $partname, 0, 2 ) );
1740 public static function getFilenamePrefixBlacklist() {
1741 $blacklist =
array();
1742 $message =
wfMessage(
'filename-prefix-blacklist' )->inContentLanguage();
1743 if ( !$message->isDisabled() ) {
1744 $lines = explode(
"\n", $message->plain() );
1756 $blacklist[] = trim(
$line );
1772 public function getImageInfo(
$result ) {
1773 $file = $this->getLocalFile();
1790 public function convertVerifyErrorToStatus(
$error ) {
1791 $code =
$error[
'status'];
1792 unset( $code[
'status'] );
1800 public static function getMaxUploadSize( $forType =
null ) {
1803 if ( is_array( $wgMaxUploadSize ) ) {
1804 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1805 return $wgMaxUploadSize[$forType];
1807 return $wgMaxUploadSize[
'*'];
1810 return intval( $wgMaxUploadSize );
1820 public static function getSessionStatus( $statusKey ) {
1821 return isset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] )
1822 ? $_SESSION[self::SESSION_STATUS_KEY][$statusKey]
1833 public static function setSessionStatus( $statusKey,
$value ) {
1834 if (
$value ===
false ) {
1835 unset( $_SESSION[self::SESSION_STATUS_KEY][$statusKey] );
1837 $_SESSION[self::SESSION_STATUS_KEY][$statusKey] =
$value;