6 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
7 * The frontends are formed by ApiUpload and SpecialUpload.
9 * See also includes/docs/upload.txt
11 * @author Brion Vibber
12 * @author Bryan Tong Minh
13 * @author Michael Dale
16 abstract class UploadBase
{
18 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
19 protected $mTitle = false, $mTitleError = 0;
20 protected $mFilteredName, $mFinalExtension;
21 protected $mLocalFile;
26 const MIN_LENGTH_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const OVERWRITE_EXISTING_FILE
= 7;
29 const FILETYPE_MISSING
= 8;
30 const FILETYPE_BADTYPE
= 9;
31 const VERIFICATION_ERROR
= 10;
33 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
34 const UPLOAD_VERIFICATION_ERROR
= 11;
35 const HOOK_ABORTED
= 11;
36 const FILE_TOO_LARGE
= 12;
38 const SESSION_VERSION
= 2;
39 const SESSION_KEYNAME
= 'wsUploadData';
41 static public function getSessionKeyname() {
42 return self
::SESSION_KEYNAME
;
45 public function getVerificationErrorCode( $error ) {
46 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
47 self
::FILE_TOO_LARGE
=> 'file-too-large',
48 self
::FILETYPE_MISSING
=> 'filetype-missing',
49 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
50 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
51 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
52 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
53 self
::VERIFICATION_ERROR
=> 'verification-error',
54 self
::HOOK_ABORTED
=> 'hookaborted',
56 if( isset( $code_to_status[$error] ) ) {
57 return $code_to_status[$error];
60 return 'unknown-error';
64 * Returns true if uploads are enabled.
65 * Can be override by subclasses.
67 public static function isEnabled() {
68 global $wgEnableUploads;
69 if ( !$wgEnableUploads ) {
73 # Check php's file_uploads setting
74 if( !wfIniGetBool( 'file_uploads' ) ) {
81 * Returns true if the user can use this upload module or else a string
82 * identifying the missing permission.
83 * Can be overriden by subclasses.
85 public static function isAllowed( $user ) {
86 if( !$user->isAllowed( 'upload' ) ) {
92 // Upload handlers. Should probably just be a global.
93 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
96 * Create a form of UploadBase depending on wpSourceType and initializes it
98 public static function createFromRequest( &$request, $type = null ) {
99 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
105 // Get the upload class
106 $type = ucfirst( $type );
108 // Give hooks the chance to handle this request
110 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
111 if ( is_null( $className ) ) {
112 $className = 'UploadFrom' . $type;
113 wfDebug( __METHOD__
. ": class name: $className\n" );
114 if( !in_array( $type, self
::$uploadHandlers ) ) {
119 // Check whether this upload class is enabled
120 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
124 // Check whether the request is valid
125 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
129 $handler = new $className;
131 $handler->initializeFromRequest( $request );
136 * Check whether a request if valid for this handler
138 public static function isValidRequest( $request ) {
142 public function __construct() {}
145 * Initialize the path information
146 * @param $name string the desired destination name
147 * @param $tempPath string the temporary path
148 * @param $fileSize int the file size
149 * @param $removeTempFile bool (false) remove the temporary file?
152 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
153 $this->mDesiredDestName
= $name;
154 $this->mTempPath
= $tempPath;
155 $this->mFileSize
= $fileSize;
156 $this->mRemoveTempFile
= $removeTempFile;
160 * Initialize from a WebRequest. Override this in a subclass.
162 public abstract function initializeFromRequest( &$request );
165 * Fetch the file. Usually a no-op
167 public function fetchFile() {
168 return Status
::newGood();
172 * Return true if the file is empty
175 public function isEmptyFile() {
176 return empty( $this->mFileSize
);
180 * Return the file size
183 public function getFileSize() {
184 return $this->mFileSize
;
188 * Append a file to the Repo file
190 * @param $srcPath String: path to source file
191 * @param $toAppendPath String: path to the Repo file that will be appended to.
192 * @return Status Status
194 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
195 $repo = RepoGroup
::singleton()->getLocalRepo();
196 $status = $repo->append( $srcPath, $toAppendPath );
201 * @param $srcPath String: the source path
202 * @return the real path if it was a virtual URL
204 function getRealPath( $srcPath ) {
205 $repo = RepoGroup
::singleton()->getLocalRepo();
206 if ( $repo->isVirtualUrl( $srcPath ) ) {
207 return $repo->resolveVirtualUrl( $srcPath );
213 * Verify whether the upload is sane.
214 * @return mixed self::OK or else an array with error information
216 public function verifyUpload( ) {
218 * If there was no filename or a zero size given, give up quick.
220 if( $this->isEmptyFile() ) {
221 return array( 'status' => self
::EMPTY_FILE
);
225 * Honor $wgMaxUploadSize
227 global $wgMaxUploadSize;
228 if( $this->mFileSize
> $wgMaxUploadSize ) {
229 return array( 'status' => self
::FILE_TOO_LARGE
);
233 * Look at the contents of the file; if we can recognize the
234 * type but it's corrupt or data of the wrong type, we should
235 * probably not accept it.
237 $verification = $this->verifyFile();
238 if( $verification !== true ) {
240 'status' => self
::VERIFICATION_ERROR
,
241 'details' => $verification
246 * Make sure this file can be created
248 $result = $this->validateNameAndOverwrite();
249 if( $result !== true ) {
254 if( !wfRunHooks( 'UploadVerification',
255 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
256 // @fixme This status needs another name...
257 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
260 return array( 'status' => self
::OK
);
264 * Verify that the name is valid and, if necessary, that we can overwrite
266 * @return mixed true if valid, otherwise and array with 'status'
269 public function validateNameAndOverwrite() {
270 $nt = $this->getTitle();
271 if( is_null( $nt ) ) {
272 $result = array( 'status' => $this->mTitleError
);
273 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
274 $result['filtered'] = $this->mFilteredName
;
276 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
277 $result['finalExt'] = $this->mFinalExtension
;
281 $this->mDestName
= $this->getLocalFile()->getName();
284 * In some cases we may forbid overwriting of existing files.
286 $overwrite = $this->checkOverwrite();
287 if( $overwrite !== true ) {
289 'status' => self
::OVERWRITE_EXISTING_FILE
,
290 'overwrite' => $overwrite
297 * Verify the mime type
298 * @param $magic MagicMime object
299 * @param $mime string representing the mime
300 * @return mixed true if the file is verified, an array otherwise
302 protected function verifyMimeType( $magic, $mime ) {
303 global $wgVerifyMimeType;
304 if ( $wgVerifyMimeType ) {
305 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
306 if ( !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
307 return array( 'filetype-mime-mismatch' );
310 global $wgMimeTypeBlacklist;
311 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
312 return array( 'filetype-badmime', $mime );
316 $fp = fopen( $this->mTempPath
, 'rb' );
317 $chunk = fread( $fp, 256 );
319 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
320 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
321 foreach ( $ieTypes as $ieType ) {
322 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
323 return array( 'filetype-bad-ie-mime', $ieType );
332 * Verifies that it's ok to include the uploaded file
334 * @return mixed true of the file is verified, array otherwise.
336 protected function verifyFile() {
337 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
338 $this->checkMacBinary();
340 # magically determine mime type
341 $magic = MimeMagic
::singleton();
342 $mime = $magic->guessMimeType( $this->mTempPath
, false );
344 # check mime type, if desired
345 $status = $this->verifyMimeType( $magic, $mime );
346 if ( $status !== true ) {
350 # check for htmlish code and javascript
351 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
352 return array( 'uploadscripted' );
354 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
355 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
356 return array( 'uploadscripted' );
361 * Scan the uploaded file for viruses
363 $virus = $this->detectVirus( $this->mTempPath
);
365 return array( 'uploadvirus', $virus );
367 wfDebug( __METHOD__
. ": all clear; passing.\n" );
372 * Check whether the user can edit, upload and create the image.
374 * @param $user the User object to verify the permissions against
375 * @return mixed An array as returned by getUserPermissionsErrors or true
376 * in case the user has proper permissions.
378 public function verifyPermissions( $user ) {
380 * If the image is protected, non-sysop users won't be able
381 * to modify it by uploading a new revision.
383 $nt = $this->getTitle();
384 if( is_null( $nt ) ) {
387 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
388 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
389 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
390 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
391 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
392 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
399 * Check for non fatal problems with the file
401 * @return Array of warnings
403 public function checkWarnings() {
406 $localFile = $this->getLocalFile();
407 $filename = $localFile->getName();
408 $n = strrpos( $filename, '.' );
409 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
412 * Check whether the resulting filename is different from the desired one,
413 * but ignore things like ucfirst() and spaces/underscore things
415 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
416 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
418 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
419 $warnings['badfilename'] = $filename;
422 // Check whether the file extension is on the unwanted list
423 global $wgCheckFileExtensions, $wgFileExtensions;
424 if ( $wgCheckFileExtensions ) {
425 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
426 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
430 global $wgUploadSizeWarning;
431 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
432 $warnings['large-file'] = $wgUploadSizeWarning;
435 if ( $this->mFileSize
== 0 ) {
436 $warnings['emptyfile'] = true;
439 $exists = self
::getExistsWarning( $localFile );
440 if( $exists !== false ) {
441 $warnings['exists'] = $exists;
444 // Check dupes against existing files
445 $hash = File
::sha1Base36( $this->mTempPath
);
446 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
447 $title = $this->getTitle();
448 // Remove all matches against self
449 foreach ( $dupes as $key => $dupe ) {
450 if( $title->equals( $dupe->getTitle() ) ) {
451 unset( $dupes[$key] );
455 $warnings['duplicate'] = $dupes;
458 // Check dupes against archives
459 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
460 if ( $archivedImage->getID() > 0 ) {
461 $warnings['duplicate-archive'] = $archivedImage->getName();
468 * Really perform the upload. Stores the file in the local repo, watches
469 * if necessary and runs the UploadComplete hook.
471 * @return mixed Status indicating the whether the upload succeeded.
473 public function performUpload( $comment, $pageText, $watch, $user ) {
474 wfDebug( "\n\n\performUpload: sum: " . $comment . ' c: ' . $pageText .
476 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
477 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
479 if( $status->isGood() ) {
481 $user->addWatch( $this->getLocalFile()->getTitle() );
484 wfRunHooks( 'UploadComplete', array( &$this ) );
491 * Returns the title of the file to be uploaded. Sets mTitleError in case
492 * the name was illegal.
494 * @return Title The title of the file or null in case the name was illegal
496 public function getTitle() {
497 if ( $this->mTitle
!== false ) {
498 return $this->mTitle
;
502 * Chop off any directories in the given filename. Then
503 * filter out illegal characters, and try to make a legible name
504 * out of it. We'll strip some silently that Title would die on.
506 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mDesiredDestName
);
507 /* Normalize to title form before we do any further processing */
508 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
509 if( is_null( $nt ) ) {
510 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
511 return $this->mTitle
= null;
513 $this->mFilteredName
= $nt->getDBkey();
516 * We'll want to blacklist against *any* 'extension', and use
517 * only the final one for the whitelist.
519 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
521 if( count( $ext ) ) {
522 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
524 $this->mFinalExtension
= '';
527 /* Don't allow users to override the blacklist (check file extension) */
528 global $wgCheckFileExtensions, $wgStrictFileExtensions;
529 global $wgFileExtensions, $wgFileBlacklist;
530 if ( $this->mFinalExtension
== '' ) {
531 $this->mTitleError
= self
::FILETYPE_MISSING
;
532 return $this->mTitle
= null;
533 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
534 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
535 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
536 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
537 return $this->mTitle
= null;
540 # If there was more than one "extension", reassemble the base
541 # filename to prevent bogus complaints about length
542 if( count( $ext ) > 1 ) {
543 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
544 $partname .= '.' . $ext[$i];
548 if( strlen( $partname ) < 1 ) {
549 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
550 return $this->mTitle
= null;
553 return $this->mTitle
= $nt;
557 * Return the local file and initializes if necessary.
559 public function getLocalFile() {
560 if( is_null( $this->mLocalFile
) ) {
561 $nt = $this->getTitle();
562 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
564 return $this->mLocalFile
;
568 * Stash a file in a temporary directory for later processing
569 * after the user has confirmed it.
571 * If the user doesn't explicitly cancel or accept, these files
572 * can accumulate in the temp directory.
574 * @param $saveName String: the destination filename
575 * @param $tempSrc String: the source temporary file to save
576 * @return String: full path the stashed file, or false on failure
578 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
579 $repo = RepoGroup
::singleton()->getLocalRepo();
580 $status = $repo->storeTemp( $saveName, $tempSrc );
585 * Stash a file in a temporary directory for later processing,
586 * and save the necessary descriptive info into the session.
587 * Returns a key value which will be passed through a form
588 * to pick up the path info on a later invocation.
590 * @return Integer: session key
592 public function stashSession() {
593 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
594 if( !$status->isOK() ) {
595 # Couldn't save the file.
599 $key = $this->getSessionKey();
600 $_SESSION[self
::SESSION_KEYNAME
][$key] = array(
601 'mTempPath' => $status->value
,
602 'mFileSize' => $this->mFileSize
,
603 'mFileProps' => $this->mFileProps
,
604 'version' => self
::SESSION_VERSION
,
610 * Generate a random session key from stash in cases where we want
611 * to start an upload without much information
613 protected function getSessionKey() {
614 $key = mt_rand( 0, 0x7fffffff );
615 $_SESSION[self
::SESSION_KEYNAME
][$key] = array();
620 * If we've modified the upload file we need to manually remove it
621 * on exit to clean up.
623 public function cleanupTempFile() {
624 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
625 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
626 unlink( $this->mTempPath
);
630 public function getTempPath() {
631 return $this->mTempPath
;
635 * Split a file into a base name and all dot-delimited 'extensions'
636 * on the end. Some web server configurations will fall back to
637 * earlier pseudo-'extensions' to determine type and execute
638 * scripts, so the blacklist needs to check them all.
642 public static function splitExtensions( $filename ) {
643 $bits = explode( '.', $filename );
644 $basename = array_shift( $bits );
645 return array( $basename, $bits );
649 * Perform case-insensitive match against a list of file extensions.
650 * Returns true if the extension is in the list.
656 public static function checkFileExtension( $ext, $list ) {
657 return in_array( strtolower( $ext ), $list );
661 * Perform case-insensitive match against a list of file extensions.
662 * Returns true if any of the extensions are in the list.
668 public static function checkFileExtensionList( $ext, $list ) {
669 foreach( $ext as $e ) {
670 if( in_array( strtolower( $e ), $list ) ) {
678 * Checks if the mime type of the uploaded file matches the file extension.
680 * @param $mime String: the mime type of the uploaded file
681 * @param $extension String: the filename extension that the file is to be served with
684 public static function verifyExtension( $mime, $extension ) {
685 $magic = MimeMagic
::singleton();
687 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
688 if ( !$magic->isRecognizableExtension( $extension ) ) {
689 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
690 "unrecognized extension '$extension', can't verify\n" );
693 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
694 "recognized extension '$extension', so probably invalid file\n" );
698 $match = $magic->isMatchingExtension( $extension, $mime );
700 if ( $match === null ) {
701 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
703 } elseif( $match === true ) {
704 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
706 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
710 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
716 * Heuristic for detecting files that *could* contain JavaScript instructions or
717 * things that may look like HTML to a browser and are thus
718 * potentially harmful. The present implementation will produce false
719 * positives in some situations.
721 * @param $file String: pathname to the temporary upload file
722 * @param $mime String: the mime type of the file
723 * @param $extension String: the extension of the file
724 * @return Boolean: true if the file contains something looking like embedded scripts
726 public static function detectScript( $file, $mime, $extension ) {
727 global $wgAllowTitlesInSVG;
729 # ugly hack: for text files, always look at the entire file.
730 # For binary field, just check the first K.
732 if( strpos( $mime,'text/' ) === 0 ) {
733 $chunk = file_get_contents( $file );
735 $fp = fopen( $file, 'rb' );
736 $chunk = fread( $fp, 1024 );
740 $chunk = strtolower( $chunk );
746 # decode from UTF-16 if needed (could be used for obfuscation).
747 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
749 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
756 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
759 $chunk = trim( $chunk );
761 # FIXME: convert from UTF-16 if necessarry!
762 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
764 # check for HTML doctype
765 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
770 * Internet Explorer for Windows performs some really stupid file type
771 * autodetection which can cause it to interpret valid image files as HTML
772 * and potentially execute JavaScript, creating a cross-site scripting
775 * Apple's Safari browser also performs some unsafe file type autodetection
776 * which can cause legitimate files to be interpreted as HTML if the
777 * web server is not correctly configured to send the right content-type
778 * (or if you're really uploading plain text and octet streams!)
780 * Returns true if IE is likely to mistake the given file for HTML.
781 * Also returns true if Safari would mistake the given file for HTML
782 * when served with a generic content-type.
788 '<html', #also in safari
791 '<script', #also in safari
795 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
799 foreach( $tags as $tag ) {
800 if( false !== strpos( $chunk, $tag ) ) {
806 * look for JavaScript
809 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
810 $chunk = Sanitizer
::decodeCharReferences( $chunk );
812 # look for script-types
813 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
817 # look for html-style script-urls
818 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
822 # look for css-style script-urls
823 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
827 wfDebug( __METHOD__
. ": no scripts found\n" );
831 protected function detectScriptInSvg( $filename ) {
832 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
833 return $check->filterMatch
;
837 * @todo Replace this with a whitelist filter!
839 public function checkSvgScriptCallback( $element, $attribs ) {
840 $stripped = $this->stripXmlNamespace( $element );
842 if( $stripped == 'script' ) {
843 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
847 foreach( $attribs as $attrib => $value ) {
848 $stripped = $this->stripXmlNamespace( $attrib );
849 if( substr( $stripped, 0, 2 ) == 'on' ) {
850 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
853 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
854 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
860 private function stripXmlNamespace( $name ) {
861 // 'http://www.w3.org/2000/svg:script' -> 'script'
862 $parts = explode( ':', strtolower( $name ) );
863 return array_pop( $parts );
867 * Generic wrapper function for a virus scanner program.
868 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
869 * $wgAntivirusRequired may be used to deny upload if the scan fails.
871 * @param $file String: pathname to the temporary upload file
872 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
873 * or a string containing feedback from the virus scanner if a virus was found.
874 * If textual feedback is missing but a virus was found, this function returns true.
876 public static function detectVirus( $file ) {
877 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
879 if ( !$wgAntivirus ) {
880 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
884 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
885 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
886 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>",
887 array( 'virus-badscanner', $wgAntivirus ) );
888 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
891 # look up scanner configuration
892 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
893 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
894 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
895 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
897 if ( strpos( $command, "%f" ) === false ) {
898 # simple pattern: append file to scan
899 $command .= " " . wfEscapeShellArg( $file );
901 # complex pattern: replace "%f" with file to scan
902 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
905 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
907 # execute virus scanner
910 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
911 # that does not seem to be worth the pain.
912 # Ask me (Duesentrieb) about it if it's ever needed.
913 $output = wfShellExec( "$command 2>&1", $exitCode );
915 # map exit code to AV_xxx constants.
916 $mappedCode = $exitCode;
917 if ( $exitCodeMap ) {
918 if ( isset( $exitCodeMap[$exitCode] ) ) {
919 $mappedCode = $exitCodeMap[$exitCode];
920 } elseif ( isset( $exitCodeMap["*"] ) ) {
921 $mappedCode = $exitCodeMap["*"];
925 if ( $mappedCode === AV_SCAN_FAILED
) {
926 # scan failed (code was mapped to false by $exitCodeMap)
927 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
929 if ( $wgAntivirusRequired ) {
930 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
934 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
935 # scan failed because filetype is unknown (probably imune)
936 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
938 } elseif ( $mappedCode === AV_NO_VIRUS
) {
940 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
943 $output = trim( $output );
946 $output = true; #if there's no output, return true
947 } elseif ( $msgPattern ) {
949 if ( preg_match( $msgPattern, $output, $groups ) ) {
951 $output = $groups[1];
956 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
962 * Check if the temporary file is MacBinary-encoded, as some uploads
963 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
964 * If so, the data fork will be extracted to a second temporary file,
965 * which will then be checked for validity and either kept or discarded.
967 private function checkMacBinary() {
968 $macbin = new MacBinary( $this->mTempPath
);
969 if( $macbin->isValid() ) {
970 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
971 $dataHandle = fopen( $dataFile, 'wb' );
973 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
974 $macbin->extractData( $dataHandle );
976 $this->mTempPath
= $dataFile;
977 $this->mFileSize
= $macbin->dataForkLength();
979 // We'll have to manually remove the new file if it's not kept.
980 $this->mRemoveTempFile
= true;
986 * Check if there's an overwrite conflict and, if so, if restrictions
987 * forbid this user from performing the upload.
989 * @return mixed true on success, error string on failure
991 private function checkOverwrite() {
993 // First check whether the local file can be overwritten
994 $file = $this->getLocalFile();
995 if( $file->exists() ) {
996 if( !self
::userCanReUpload( $wgUser, $file ) ) {
997 return 'fileexists-forbidden';
1003 /* Check shared conflicts: if the local file does not exist, but
1004 * wfFindFile finds a file, it exists in a shared repository.
1006 $file = wfFindFile( $this->getTitle() );
1007 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
1008 return 'fileexists-shared-forbidden';
1015 * Check if a user is the last uploader
1017 * @param $user User object
1018 * @param $img String: image name
1021 public static function userCanReUpload( User
$user, $img ) {
1022 if( $user->isAllowed( 'reupload' ) ) {
1023 return true; // non-conditional
1025 if( !$user->isAllowed( 'reupload-own' ) ) {
1028 if( is_string( $img ) ) {
1029 $img = wfLocalFile( $img );
1031 if ( !( $img instanceof LocalFile
) ) {
1035 return $user->getId() == $img->getUser( 'id' );
1039 * Helper function that does various existence checks for a file.
1040 * The following checks are performed:
1042 * - Article with the same name as the file exists
1043 * - File exists with normalized extension
1044 * - The file looks like a thumbnail and the original exists
1046 * @param $file The File object to check
1047 * @return mixed False if the file does not exists, else an array
1049 public static function getExistsWarning( $file ) {
1050 if( $file->exists() ) {
1051 return array( 'warning' => 'exists', 'file' => $file );
1054 if( $file->getTitle()->getArticleID() ) {
1055 return array( 'warning' => 'page-exists', 'file' => $file );
1058 if ( $file->wasDeleted() && !$file->exists() ) {
1059 return array( 'warning' => 'was-deleted', 'file' => $file );
1062 if( strpos( $file->getName(), '.' ) == false ) {
1063 $partname = $file->getName();
1066 $n = strrpos( $file->getName(), '.' );
1067 $extension = substr( $file->getName(), $n +
1 );
1068 $partname = substr( $file->getName(), 0, $n );
1070 $normalizedExtension = File
::normalizeExtension( $extension );
1072 if ( $normalizedExtension != $extension ) {
1073 // We're not using the normalized form of the extension.
1074 // Normal form is lowercase, using most common of alternate
1075 // extensions (eg 'jpg' rather than 'JPEG').
1077 // Check for another file using the normalized form...
1078 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1079 $file_lc = wfLocalFile( $nt_lc );
1081 if( $file_lc->exists() ) {
1083 'warning' => 'exists-normalized',
1085 'normalizedFile' => $file_lc
1090 if ( self
::isThumbName( $file->getName() ) ) {
1091 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1092 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1093 $file_thb = wfLocalFile( $nt_thb );
1094 if( $file_thb->exists() ) {
1096 'warning' => 'thumb',
1098 'thumbFile' => $file_thb
1101 // File does not exist, but we just don't like the name
1103 'warning' => 'thumb-name',
1105 'thumbFile' => $file_thb
1111 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1112 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1114 'warning' => 'bad-prefix',
1125 * Helper function that checks whether the filename looks like a thumbnail
1127 public static function isThumbName( $filename ) {
1128 $n = strrpos( $filename, '.' );
1129 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1131 substr( $partname , 3, 3 ) == 'px-' ||
1132 substr( $partname , 2, 3 ) == 'px-'
1134 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1138 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1140 * @return array list of prefixes
1142 public static function getFilenamePrefixBlacklist() {
1143 $blacklist = array();
1144 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1145 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1146 $lines = explode( "\n", $message );
1147 foreach( $lines as $line ) {
1148 // Remove comment lines
1149 $comment = substr( trim( $line ), 0, 1 );
1150 if ( $comment == '#' ||
$comment == '' ) {
1153 // Remove additional comments after a prefix
1154 $comment = strpos( $line, '#' );
1155 if ( $comment > 0 ) {
1156 $line = substr( $line, 0, $comment-1 );
1158 $blacklist[] = trim( $line );
1164 public function getImageInfo( $result ) {
1165 $file = $this->getLocalFile();
1166 $imParam = ApiQueryImageInfo
::getPropertyNames();
1167 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1170 public function convertVerifyErrorToStatus( $error ) {
1171 $args = func_get_args();
1173 return Status
::newFatal( $this->getVerificationErrorCode( $error ), $args );