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 an array of permissions that is required to upload a file
85 public static function getRequiredPermissions() {
86 return array( 'upload', 'create', 'edit' );
89 * Returns true if the user can use this upload module or else a string
90 * identifying the missing permission.
91 * Can be overriden by subclasses.
93 public static function isAllowed( $user ) {
94 foreach ( self
::getRequiredPermissions
as $permission ) {
95 if ( !$user->isAllowed( $permission ) ) {
102 // Upload handlers. Should probably just be a global.
103 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
106 * Create a form of UploadBase depending on wpSourceType and initializes it
108 public static function createFromRequest( &$request, $type = null ) {
109 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
115 // Get the upload class
116 $type = ucfirst( $type );
118 // Give hooks the chance to handle this request
120 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
121 if ( is_null( $className ) ) {
122 $className = 'UploadFrom' . $type;
123 wfDebug( __METHOD__
. ": class name: $className\n" );
124 if( !in_array( $type, self
::$uploadHandlers ) ) {
129 // Check whether this upload class is enabled
130 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
134 // Check whether the request is valid
135 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
139 $handler = new $className;
141 $handler->initializeFromRequest( $request );
146 * Check whether a request if valid for this handler
148 public static function isValidRequest( $request ) {
152 public function __construct() {}
155 * Initialize the path information
156 * @param $name string the desired destination name
157 * @param $tempPath string the temporary path
158 * @param $fileSize int the file size
159 * @param $removeTempFile bool (false) remove the temporary file?
162 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
163 $this->mDesiredDestName
= $name;
164 $this->mTempPath
= $tempPath;
165 $this->mFileSize
= $fileSize;
166 $this->mRemoveTempFile
= $removeTempFile;
170 * Initialize from a WebRequest. Override this in a subclass.
172 public abstract function initializeFromRequest( &$request );
175 * Fetch the file. Usually a no-op
177 public function fetchFile() {
178 return Status
::newGood();
182 * Return true if the file is empty
185 public function isEmptyFile() {
186 return empty( $this->mFileSize
);
190 * Return the file size
193 public function getFileSize() {
194 return $this->mFileSize
;
198 * Append a file to the Repo file
200 * @param $srcPath String: path to source file
201 * @param $toAppendPath String: path to the Repo file that will be appended to.
202 * @return Status Status
204 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
205 $repo = RepoGroup
::singleton()->getLocalRepo();
206 $status = $repo->append( $srcPath, $toAppendPath );
211 * @param $srcPath String: the source path
212 * @return the real path if it was a virtual URL
214 function getRealPath( $srcPath ) {
215 $repo = RepoGroup
::singleton()->getLocalRepo();
216 if ( $repo->isVirtualUrl( $srcPath ) ) {
217 return $repo->resolveVirtualUrl( $srcPath );
223 * Verify whether the upload is sane.
224 * @return mixed self::OK or else an array with error information
226 public function verifyUpload( ) {
228 * If there was no filename or a zero size given, give up quick.
230 if( $this->isEmptyFile() ) {
231 return array( 'status' => self
::EMPTY_FILE
);
235 * Honor $wgMaxUploadSize
237 global $wgMaxUploadSize;
238 if( $this->mFileSize
> $wgMaxUploadSize ) {
239 return array( 'status' => self
::FILE_TOO_LARGE
);
243 * Look at the contents of the file; if we can recognize the
244 * type but it's corrupt or data of the wrong type, we should
245 * probably not accept it.
247 $verification = $this->verifyFile();
248 if( $verification !== true ) {
250 'status' => self
::VERIFICATION_ERROR
,
251 'details' => $verification
256 * Make sure this file can be created
258 $result = $this->validateNameAndOverwrite();
259 if( $result !== true ) {
264 if( !wfRunHooks( 'UploadVerification',
265 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
266 // @fixme This status needs another name...
267 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
270 return array( 'status' => self
::OK
);
274 * Verify that the name is valid and, if necessary, that we can overwrite
276 * @return mixed true if valid, otherwise and array with 'status'
279 public function validateNameAndOverwrite() {
280 $nt = $this->getTitle();
281 if( is_null( $nt ) ) {
282 $result = array( 'status' => $this->mTitleError
);
283 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
284 $result['filtered'] = $this->mFilteredName
;
286 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
287 $result['finalExt'] = $this->mFinalExtension
;
291 $this->mDestName
= $this->getLocalFile()->getName();
294 * In some cases we may forbid overwriting of existing files.
296 $overwrite = $this->checkOverwrite();
297 if( $overwrite !== true ) {
299 'status' => self
::OVERWRITE_EXISTING_FILE
,
300 'overwrite' => $overwrite
307 * Verify the mime type
308 * @param $magic MagicMime object
309 * @param $mime string representing the mime
310 * @return mixed true if the file is verified, an array otherwise
312 protected function verifyMimeType( $magic, $mime ) {
313 global $wgVerifyMimeType;
314 if ( $wgVerifyMimeType ) {
315 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
316 if ( !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
317 return array( 'filetype-mime-mismatch' );
320 global $wgMimeTypeBlacklist;
321 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
322 return array( 'filetype-badmime', $mime );
326 $fp = fopen( $this->mTempPath
, 'rb' );
327 $chunk = fread( $fp, 256 );
329 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
330 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
331 foreach ( $ieTypes as $ieType ) {
332 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
333 return array( 'filetype-bad-ie-mime', $ieType );
342 * Verifies that it's ok to include the uploaded file
344 * @return mixed true of the file is verified, array otherwise.
346 protected function verifyFile() {
347 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
348 $this->checkMacBinary();
350 # magically determine mime type
351 $magic = MimeMagic
::singleton();
352 $mime = $magic->guessMimeType( $this->mTempPath
, false );
354 # check mime type, if desired
355 $status = $this->verifyMimeType( $magic, $mime );
356 if ( $status !== true ) {
360 # check for htmlish code and javascript
361 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
362 return array( 'uploadscripted' );
364 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
365 if( self
::detectScriptInSvg( $this->mTempPath
) ) {
366 return array( 'uploadscripted' );
371 * Scan the uploaded file for viruses
373 $virus = $this->detectVirus( $this->mTempPath
);
375 return array( 'uploadvirus', $virus );
377 wfDebug( __METHOD__
. ": all clear; passing.\n" );
382 * Check whether the user can edit, upload and create the image.
384 * @param $user the User object to verify the permissions against
385 * @return mixed An array as returned by getUserPermissionsErrors or true
386 * in case the user has proper permissions.
388 public function verifyPermissions( $user ) {
390 * If the image is protected, non-sysop users won't be able
391 * to modify it by uploading a new revision.
393 $nt = $this->getTitle();
394 if( is_null( $nt ) ) {
397 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
398 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
399 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $user ) );
400 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
401 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
402 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
409 * Check for non fatal problems with the file
411 * @return Array of warnings
413 public function checkWarnings() {
416 $localFile = $this->getLocalFile();
417 $filename = $localFile->getName();
418 $n = strrpos( $filename, '.' );
419 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
422 * Check whether the resulting filename is different from the desired one,
423 * but ignore things like ucfirst() and spaces/underscore things
425 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
426 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
428 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
429 $warnings['badfilename'] = $filename;
432 // Check whether the file extension is on the unwanted list
433 global $wgCheckFileExtensions, $wgFileExtensions;
434 if ( $wgCheckFileExtensions ) {
435 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
436 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
440 global $wgUploadSizeWarning;
441 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
442 $warnings['large-file'] = $wgUploadSizeWarning;
445 if ( $this->mFileSize
== 0 ) {
446 $warnings['emptyfile'] = true;
449 $exists = self
::getExistsWarning( $localFile );
450 if( $exists !== false ) {
451 $warnings['exists'] = $exists;
454 // Check dupes against existing files
455 $hash = File
::sha1Base36( $this->mTempPath
);
456 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
457 $title = $this->getTitle();
458 // Remove all matches against self
459 foreach ( $dupes as $key => $dupe ) {
460 if( $title->equals( $dupe->getTitle() ) ) {
461 unset( $dupes[$key] );
465 $warnings['duplicate'] = $dupes;
468 // Check dupes against archives
469 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
470 if ( $archivedImage->getID() > 0 ) {
471 $warnings['duplicate-archive'] = $archivedImage->getName();
478 * Really perform the upload. Stores the file in the local repo, watches
479 * if necessary and runs the UploadComplete hook.
481 * @return mixed Status indicating the whether the upload succeeded.
483 public function performUpload( $comment, $pageText, $watch, $user ) {
484 wfDebug( "\n\n\performUpload: sum: " . $comment . ' c: ' . $pageText .
486 $status = $this->getLocalFile()->upload( $this->mTempPath
, $comment, $pageText,
487 File
::DELETE_SOURCE
, $this->mFileProps
, false, $user );
489 if( $status->isGood() ) {
491 $user->addWatch( $this->getLocalFile()->getTitle() );
494 wfRunHooks( 'UploadComplete', array( &$this ) );
501 * Returns the title of the file to be uploaded. Sets mTitleError in case
502 * the name was illegal.
504 * @return Title The title of the file or null in case the name was illegal
506 public function getTitle() {
507 if ( $this->mTitle
!== false ) {
508 return $this->mTitle
;
512 * Chop off any directories in the given filename. Then
513 * filter out illegal characters, and try to make a legible name
514 * out of it. We'll strip some silently that Title would die on.
516 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mDesiredDestName
);
517 /* Normalize to title form before we do any further processing */
518 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
519 if( is_null( $nt ) ) {
520 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
521 return $this->mTitle
= null;
523 $this->mFilteredName
= $nt->getDBkey();
526 * We'll want to blacklist against *any* 'extension', and use
527 * only the final one for the whitelist.
529 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
531 if( count( $ext ) ) {
532 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
534 $this->mFinalExtension
= '';
537 /* Don't allow users to override the blacklist (check file extension) */
538 global $wgCheckFileExtensions, $wgStrictFileExtensions;
539 global $wgFileExtensions, $wgFileBlacklist;
540 if ( $this->mFinalExtension
== '' ) {
541 $this->mTitleError
= self
::FILETYPE_MISSING
;
542 return $this->mTitle
= null;
543 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
544 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
545 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
546 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
547 return $this->mTitle
= null;
550 # If there was more than one "extension", reassemble the base
551 # filename to prevent bogus complaints about length
552 if( count( $ext ) > 1 ) {
553 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
554 $partname .= '.' . $ext[$i];
558 if( strlen( $partname ) < 1 ) {
559 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
560 return $this->mTitle
= null;
563 return $this->mTitle
= $nt;
567 * Return the local file and initializes if necessary.
569 public function getLocalFile() {
570 if( is_null( $this->mLocalFile
) ) {
571 $nt = $this->getTitle();
572 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
574 return $this->mLocalFile
;
578 * Stash a file in a temporary directory for later processing
579 * after the user has confirmed it.
581 * If the user doesn't explicitly cancel or accept, these files
582 * can accumulate in the temp directory.
584 * @param $saveName String: the destination filename
585 * @param $tempSrc String: the source temporary file to save
586 * @return String: full path the stashed file, or false on failure
588 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
589 $repo = RepoGroup
::singleton()->getLocalRepo();
590 $status = $repo->storeTemp( $saveName, $tempSrc );
595 * Stash a file in a temporary directory for later processing,
596 * and save the necessary descriptive info into the session.
597 * Returns a key value which will be passed through a form
598 * to pick up the path info on a later invocation.
600 * @return Integer: session key
602 public function stashSession() {
603 $status = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
604 if( !$status->isOK() ) {
605 # Couldn't save the file.
609 $key = $this->getSessionKey();
610 $_SESSION[self
::SESSION_KEYNAME
][$key] = array(
611 'mTempPath' => $status->value
,
612 'mFileSize' => $this->mFileSize
,
613 'mFileProps' => $this->mFileProps
,
614 'version' => self
::SESSION_VERSION
,
620 * Generate a random session key from stash in cases where we want
621 * to start an upload without much information
623 protected function getSessionKey() {
624 $key = mt_rand( 0, 0x7fffffff );
625 $_SESSION[self
::SESSION_KEYNAME
][$key] = array();
630 * If we've modified the upload file we need to manually remove it
631 * on exit to clean up.
633 public function cleanupTempFile() {
634 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
635 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
636 unlink( $this->mTempPath
);
640 public function getTempPath() {
641 return $this->mTempPath
;
645 * Split a file into a base name and all dot-delimited 'extensions'
646 * on the end. Some web server configurations will fall back to
647 * earlier pseudo-'extensions' to determine type and execute
648 * scripts, so the blacklist needs to check them all.
652 public static function splitExtensions( $filename ) {
653 $bits = explode( '.', $filename );
654 $basename = array_shift( $bits );
655 return array( $basename, $bits );
659 * Perform case-insensitive match against a list of file extensions.
660 * Returns true if the extension is in the list.
666 public static function checkFileExtension( $ext, $list ) {
667 return in_array( strtolower( $ext ), $list );
671 * Perform case-insensitive match against a list of file extensions.
672 * Returns true if any of the extensions are in the list.
678 public static function checkFileExtensionList( $ext, $list ) {
679 foreach( $ext as $e ) {
680 if( in_array( strtolower( $e ), $list ) ) {
688 * Checks if the mime type of the uploaded file matches the file extension.
690 * @param $mime String: the mime type of the uploaded file
691 * @param $extension String: the filename extension that the file is to be served with
694 public static function verifyExtension( $mime, $extension ) {
695 $magic = MimeMagic
::singleton();
697 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
698 if ( !$magic->isRecognizableExtension( $extension ) ) {
699 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
700 "unrecognized extension '$extension', can't verify\n" );
703 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
704 "recognized extension '$extension', so probably invalid file\n" );
708 $match = $magic->isMatchingExtension( $extension, $mime );
710 if ( $match === null ) {
711 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
713 } elseif( $match === true ) {
714 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
716 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
720 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
726 * Heuristic for detecting files that *could* contain JavaScript instructions or
727 * things that may look like HTML to a browser and are thus
728 * potentially harmful. The present implementation will produce false
729 * positives in some situations.
731 * @param $file String: pathname to the temporary upload file
732 * @param $mime String: the mime type of the file
733 * @param $extension String: the extension of the file
734 * @return Boolean: true if the file contains something looking like embedded scripts
736 public static function detectScript( $file, $mime, $extension ) {
737 global $wgAllowTitlesInSVG;
739 # ugly hack: for text files, always look at the entire file.
740 # For binary field, just check the first K.
742 if( strpos( $mime,'text/' ) === 0 ) {
743 $chunk = file_get_contents( $file );
745 $fp = fopen( $file, 'rb' );
746 $chunk = fread( $fp, 1024 );
750 $chunk = strtolower( $chunk );
756 # decode from UTF-16 if needed (could be used for obfuscation).
757 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
759 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
766 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
769 $chunk = trim( $chunk );
771 # FIXME: convert from UTF-16 if necessarry!
772 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
774 # check for HTML doctype
775 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
780 * Internet Explorer for Windows performs some really stupid file type
781 * autodetection which can cause it to interpret valid image files as HTML
782 * and potentially execute JavaScript, creating a cross-site scripting
785 * Apple's Safari browser also performs some unsafe file type autodetection
786 * which can cause legitimate files to be interpreted as HTML if the
787 * web server is not correctly configured to send the right content-type
788 * (or if you're really uploading plain text and octet streams!)
790 * Returns true if IE is likely to mistake the given file for HTML.
791 * Also returns true if Safari would mistake the given file for HTML
792 * when served with a generic content-type.
798 '<html', #also in safari
801 '<script', #also in safari
805 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
809 foreach( $tags as $tag ) {
810 if( false !== strpos( $chunk, $tag ) ) {
816 * look for JavaScript
819 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
820 $chunk = Sanitizer
::decodeCharReferences( $chunk );
822 # look for script-types
823 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
827 # look for html-style script-urls
828 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
832 # look for css-style script-urls
833 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
837 wfDebug( __METHOD__
. ": no scripts found\n" );
841 protected function detectScriptInSvg( $filename ) {
842 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
843 return $check->filterMatch
;
847 * @todo Replace this with a whitelist filter!
849 public function checkSvgScriptCallback( $element, $attribs ) {
850 $stripped = $this->stripXmlNamespace( $element );
852 if( $stripped == 'script' ) {
853 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
857 foreach( $attribs as $attrib => $value ) {
858 $stripped = $this->stripXmlNamespace( $attrib );
859 if( substr( $stripped, 0, 2 ) == 'on' ) {
860 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
863 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
864 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
870 private function stripXmlNamespace( $name ) {
871 // 'http://www.w3.org/2000/svg:script' -> 'script'
872 $parts = explode( ':', strtolower( $name ) );
873 return array_pop( $parts );
877 * Generic wrapper function for a virus scanner program.
878 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
879 * $wgAntivirusRequired may be used to deny upload if the scan fails.
881 * @param $file String: pathname to the temporary upload file
882 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
883 * or a string containing feedback from the virus scanner if a virus was found.
884 * If textual feedback is missing but a virus was found, this function returns true.
886 public static function detectVirus( $file ) {
887 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
889 if ( !$wgAntivirus ) {
890 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
894 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
895 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
896 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>",
897 array( 'virus-badscanner', $wgAntivirus ) );
898 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
901 # look up scanner configuration
902 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
903 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
904 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
905 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
907 if ( strpos( $command, "%f" ) === false ) {
908 # simple pattern: append file to scan
909 $command .= " " . wfEscapeShellArg( $file );
911 # complex pattern: replace "%f" with file to scan
912 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
915 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
917 # execute virus scanner
920 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
921 # that does not seem to be worth the pain.
922 # Ask me (Duesentrieb) about it if it's ever needed.
923 $output = wfShellExec( "$command 2>&1", $exitCode );
925 # map exit code to AV_xxx constants.
926 $mappedCode = $exitCode;
927 if ( $exitCodeMap ) {
928 if ( isset( $exitCodeMap[$exitCode] ) ) {
929 $mappedCode = $exitCodeMap[$exitCode];
930 } elseif ( isset( $exitCodeMap["*"] ) ) {
931 $mappedCode = $exitCodeMap["*"];
935 if ( $mappedCode === AV_SCAN_FAILED
) {
936 # scan failed (code was mapped to false by $exitCodeMap)
937 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
939 if ( $wgAntivirusRequired ) {
940 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
944 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
945 # scan failed because filetype is unknown (probably imune)
946 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
948 } elseif ( $mappedCode === AV_NO_VIRUS
) {
950 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
953 $output = trim( $output );
956 $output = true; #if there's no output, return true
957 } elseif ( $msgPattern ) {
959 if ( preg_match( $msgPattern, $output, $groups ) ) {
961 $output = $groups[1];
966 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
972 * Check if the temporary file is MacBinary-encoded, as some uploads
973 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
974 * If so, the data fork will be extracted to a second temporary file,
975 * which will then be checked for validity and either kept or discarded.
977 private function checkMacBinary() {
978 $macbin = new MacBinary( $this->mTempPath
);
979 if( $macbin->isValid() ) {
980 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
981 $dataHandle = fopen( $dataFile, 'wb' );
983 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
984 $macbin->extractData( $dataHandle );
986 $this->mTempPath
= $dataFile;
987 $this->mFileSize
= $macbin->dataForkLength();
989 // We'll have to manually remove the new file if it's not kept.
990 $this->mRemoveTempFile
= true;
996 * Check if there's an overwrite conflict and, if so, if restrictions
997 * forbid this user from performing the upload.
999 * @return mixed true on success, error string on failure
1001 private function checkOverwrite() {
1003 // First check whether the local file can be overwritten
1004 $file = $this->getLocalFile();
1005 if( $file->exists() ) {
1006 if( !self
::userCanReUpload( $wgUser, $file ) ) {
1007 return 'fileexists-forbidden';
1013 /* Check shared conflicts: if the local file does not exist, but
1014 * wfFindFile finds a file, it exists in a shared repository.
1016 $file = wfFindFile( $this->getTitle() );
1017 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
1018 return 'fileexists-shared-forbidden';
1025 * Check if a user is the last uploader
1027 * @param $user User object
1028 * @param $img String: image name
1031 public static function userCanReUpload( User
$user, $img ) {
1032 if( $user->isAllowed( 'reupload' ) ) {
1033 return true; // non-conditional
1035 if( !$user->isAllowed( 'reupload-own' ) ) {
1038 if( is_string( $img ) ) {
1039 $img = wfLocalFile( $img );
1041 if ( !( $img instanceof LocalFile
) ) {
1045 return $user->getId() == $img->getUser( 'id' );
1049 * Helper function that does various existence checks for a file.
1050 * The following checks are performed:
1052 * - Article with the same name as the file exists
1053 * - File exists with normalized extension
1054 * - The file looks like a thumbnail and the original exists
1056 * @param $file The File object to check
1057 * @return mixed False if the file does not exists, else an array
1059 public static function getExistsWarning( $file ) {
1060 if( $file->exists() ) {
1061 return array( 'warning' => 'exists', 'file' => $file );
1064 if( $file->getTitle()->getArticleID() ) {
1065 return array( 'warning' => 'page-exists', 'file' => $file );
1068 if ( $file->wasDeleted() && !$file->exists() ) {
1069 return array( 'warning' => 'was-deleted', 'file' => $file );
1072 if( strpos( $file->getName(), '.' ) == false ) {
1073 $partname = $file->getName();
1076 $n = strrpos( $file->getName(), '.' );
1077 $extension = substr( $file->getName(), $n +
1 );
1078 $partname = substr( $file->getName(), 0, $n );
1080 $normalizedExtension = File
::normalizeExtension( $extension );
1082 if ( $normalizedExtension != $extension ) {
1083 // We're not using the normalized form of the extension.
1084 // Normal form is lowercase, using most common of alternate
1085 // extensions (eg 'jpg' rather than 'JPEG').
1087 // Check for another file using the normalized form...
1088 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1089 $file_lc = wfLocalFile( $nt_lc );
1091 if( $file_lc->exists() ) {
1093 'warning' => 'exists-normalized',
1095 'normalizedFile' => $file_lc
1100 if ( self
::isThumbName( $file->getName() ) ) {
1101 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1102 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1103 $file_thb = wfLocalFile( $nt_thb );
1104 if( $file_thb->exists() ) {
1106 'warning' => 'thumb',
1108 'thumbFile' => $file_thb
1111 // File does not exist, but we just don't like the name
1113 'warning' => 'thumb-name',
1115 'thumbFile' => $file_thb
1121 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1122 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1124 'warning' => 'bad-prefix',
1135 * Helper function that checks whether the filename looks like a thumbnail
1137 public static function isThumbName( $filename ) {
1138 $n = strrpos( $filename, '.' );
1139 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1141 substr( $partname , 3, 3 ) == 'px-' ||
1142 substr( $partname , 2, 3 ) == 'px-'
1144 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1148 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1150 * @return array list of prefixes
1152 public static function getFilenamePrefixBlacklist() {
1153 $blacklist = array();
1154 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1155 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
1156 $lines = explode( "\n", $message );
1157 foreach( $lines as $line ) {
1158 // Remove comment lines
1159 $comment = substr( trim( $line ), 0, 1 );
1160 if ( $comment == '#' ||
$comment == '' ) {
1163 // Remove additional comments after a prefix
1164 $comment = strpos( $line, '#' );
1165 if ( $comment > 0 ) {
1166 $line = substr( $line, 0, $comment-1 );
1168 $blacklist[] = trim( $line );
1174 public function getImageInfo( $result ) {
1175 $file = $this->getLocalFile();
1176 $imParam = ApiQueryImageInfo
::getPropertyNames();
1177 return ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1180 public function convertVerifyErrorToStatus( $error ) {
1181 $args = func_get_args();
1183 return Status
::newFatal( $this->getVerificationErrorCode( $error ), $args );