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, $mFileSize, $mFileProps;
22 protected $mBlackListedExtensions;
23 protected $mJavaDetected;
28 const MIN_LENGTH_PARTNAME
= 4;
29 const ILLEGAL_FILENAME
= 5;
30 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
31 const FILETYPE_MISSING
= 8;
32 const FILETYPE_BADTYPE
= 9;
33 const VERIFICATION_ERROR
= 10;
35 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
36 const UPLOAD_VERIFICATION_ERROR
= 11;
37 const HOOK_ABORTED
= 11;
38 const FILE_TOO_LARGE
= 12;
39 const WINDOWS_NONASCII_FILENAME
= 13;
41 const SESSION_VERSION
= 2;
42 const SESSION_KEYNAME
= 'wsUploadData';
44 static public function getSessionKeyname() {
45 return self
::SESSION_KEYNAME
;
48 public function getVerificationErrorCode( $error ) {
49 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
50 self
::FILE_TOO_LARGE
=> 'file-too-large',
51 self
::FILETYPE_MISSING
=> 'filetype-missing',
52 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
53 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
54 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
55 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
56 self
::VERIFICATION_ERROR
=> 'verification-error',
57 self
::HOOK_ABORTED
=> 'hookaborted',
58 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
60 if( isset( $code_to_status[$error] ) ) {
61 return $code_to_status[$error];
64 return 'unknown-error';
68 * Returns true if uploads are enabled.
69 * Can be override by subclasses.
71 public static function isEnabled() {
72 global $wgEnableUploads;
74 if ( !$wgEnableUploads ) {
78 # Check php's file_uploads setting
79 return wfIsHipHop() ||
wfIniGetBool( 'file_uploads' );
83 * Returns true if the user can use this upload module or else a string
84 * identifying the missing permission.
85 * Can be overriden by subclasses.
89 public static function isAllowed( $user ) {
90 foreach ( array( 'upload', 'edit' ) as $permission ) {
91 if ( !$user->isAllowed( $permission ) ) {
98 // Upload handlers. Should probably just be a global.
99 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
102 * Create a form of UploadBase depending on wpSourceType and initializes it
104 * @param $request WebRequest
106 public static function createFromRequest( &$request, $type = null ) {
107 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
113 // Get the upload class
114 $type = ucfirst( $type );
116 // Give hooks the chance to handle this request
118 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
119 if ( is_null( $className ) ) {
120 $className = 'UploadFrom' . $type;
121 wfDebug( __METHOD__
. ": class name: $className\n" );
122 if( !in_array( $type, self
::$uploadHandlers ) ) {
127 // Check whether this upload class is enabled
128 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
132 // Check whether the request is valid
133 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
137 $handler = new $className;
139 $handler->initializeFromRequest( $request );
144 * Check whether a request if valid for this handler
146 public static function isValidRequest( $request ) {
150 public function __construct() {}
153 * Returns the upload type. Should be overridden by child classes
158 public function getSourceType() { return null; }
161 * Initialize the path information
162 * @param $name string the desired destination name
163 * @param $tempPath string the temporary path
164 * @param $fileSize int the file size
165 * @param $removeTempFile bool (false) remove the temporary file?
168 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
169 $this->mDesiredDestName
= $name;
170 $this->mTempPath
= $tempPath;
171 $this->mFileSize
= $fileSize;
172 $this->mRemoveTempFile
= $removeTempFile;
176 * Initialize from a WebRequest. Override this in a subclass.
178 public abstract function initializeFromRequest( &$request );
181 * Fetch the file. Usually a no-op
183 public function fetchFile() {
184 return Status
::newGood();
188 * Return true if the file is empty
191 public function isEmptyFile() {
192 return empty( $this->mFileSize
);
196 * Return the file size
199 public function getFileSize() {
200 return $this->mFileSize
;
204 * Append a file to the Repo file
206 * @param $srcPath String: path to source file
207 * @param $toAppendPath String: path to the Repo file that will be appended to.
208 * @return Status Status
210 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
211 $repo = RepoGroup
::singleton()->getLocalRepo();
212 $status = $repo->append( $srcPath, $toAppendPath );
217 * Finish appending to the Repo file
219 * @param $toAppendPath String: path to the Repo file that will be appended to.
220 * @return Status Status
222 protected function appendFinish( $toAppendPath ) {
223 $repo = RepoGroup
::singleton()->getLocalRepo();
224 $status = $repo->appendFinish( $toAppendPath );
230 * @param $srcPath String: the source path
231 * @return the real path if it was a virtual URL
233 function getRealPath( $srcPath ) {
234 $repo = RepoGroup
::singleton()->getLocalRepo();
235 if ( $repo->isVirtualUrl( $srcPath ) ) {
236 return $repo->resolveVirtualUrl( $srcPath );
242 * Verify whether the upload is sane.
243 * @return mixed self::OK or else an array with error information
245 public function verifyUpload() {
247 * If there was no filename or a zero size given, give up quick.
249 if( $this->isEmptyFile() ) {
250 return array( 'status' => self
::EMPTY_FILE
);
254 * Honor $wgMaxUploadSize
256 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
257 if( $this->mFileSize
> $maxSize ) {
259 'status' => self
::FILE_TOO_LARGE
,
265 * Look at the contents of the file; if we can recognize the
266 * type but it's corrupt or data of the wrong type, we should
267 * probably not accept it.
269 $verification = $this->verifyFile();
270 if( $verification !== true ) {
272 'status' => self
::VERIFICATION_ERROR
,
273 'details' => $verification
278 * Make sure this file can be created
280 $result = $this->validateName();
281 if( $result !== true ) {
286 if( !wfRunHooks( 'UploadVerification',
287 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
288 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
291 return array( 'status' => self
::OK
);
295 * Verify that the name is valid and, if necessary, that we can overwrite
297 * @return mixed true if valid, otherwise and array with 'status'
300 protected function validateName() {
301 $nt = $this->getTitle();
302 if( is_null( $nt ) ) {
303 $result = array( 'status' => $this->mTitleError
);
304 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
305 $result['filtered'] = $this->mFilteredName
;
307 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
308 $result['finalExt'] = $this->mFinalExtension
;
309 if ( count( $this->mBlackListedExtensions
) ) {
310 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
315 $this->mDestName
= $this->getLocalFile()->getName();
321 * Verify the mime type
323 * @param $mime string representing the mime
324 * @return mixed true if the file is verified, an array otherwise
326 protected function verifyMimeType( $mime ) {
327 global $wgVerifyMimeType;
328 if ( $wgVerifyMimeType ) {
329 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
330 global $wgMimeTypeBlacklist;
331 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
332 return array( 'filetype-badmime', $mime );
335 # XXX: Missing extension will be caught by validateName() via getTitle()
336 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
337 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
341 $fp = fopen( $this->mTempPath
, 'rb' );
342 $chunk = fread( $fp, 256 );
345 $magic = MimeMagic
::singleton();
346 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
347 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
348 foreach ( $ieTypes as $ieType ) {
349 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
350 return array( 'filetype-bad-ie-mime', $ieType );
359 * Verifies that it's ok to include the uploaded file
361 * @return mixed true of the file is verified, array otherwise.
363 protected function verifyFile() {
364 global $wgAllowJavaUploads;
365 # get the title, even though we are doing nothing with it, because
366 # we need to populate mFinalExtension
369 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
370 $this->checkMacBinary();
372 # check mime type, if desired
373 $mime = $this->mFileProps
[ 'file-mime' ];
374 $status = $this->verifyMimeType( $mime );
375 if ( $status !== true ) {
379 # check for htmlish code and javascript
380 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
381 return array( 'uploadscripted' );
383 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
384 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
385 return array( 'uploadscripted' );
389 # Check for Java applets, which if uploaded can bypass cross-site
391 if ( !$wgAllowJavaUploads ) {
392 $this->mJavaDetected
= false;
393 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
394 array( $this, 'zipEntryCallback' ) );
395 if ( !$zipStatus->isOK() ) {
396 $errors = $zipStatus->getErrorsArray();
397 $error = reset( $errors );
398 if ( $error[0] !== 'zip-wrong-format' ) {
402 if ( $this->mJavaDetected
) {
403 return array( 'uploadjava' );
407 # Scan the uploaded file for viruses
408 $virus = $this->detectVirus( $this->mTempPath
);
410 return array( 'uploadvirus', $virus );
413 $handler = MediaHandler
::getHandler( $mime );
415 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
416 if ( !$handlerStatus->isOK() ) {
417 $errors = $handlerStatus->getErrorsArray();
418 return reset( $errors );
422 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
423 if ( $status !== true ) {
427 wfDebug( __METHOD__
. ": all clear; passing.\n" );
432 * Callback for ZipDirectoryReader to detect Java class files.
434 function zipEntryCallback( $entry ) {
435 $names = array( $entry['name'] );
437 // If there is a null character, cut off the name at it, because JDK's
438 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
439 // were constructed which had ".class\0" followed by a string chosen to
440 // make the hash collide with the truncated name, that file could be
441 // returned in response to a request for the .class file.
442 $nullPos = strpos( $entry['name'], "\000" );
443 if ( $nullPos !== false ) {
444 $names[] = substr( $entry['name'], 0, $nullPos );
447 // If there is a trailing slash in the file name, we have to strip it,
448 // because that's what ZIP_GetEntry() does.
449 if ( preg_grep( '!\.class/?$!', $names ) ) {
450 $this->mJavaDetected
= true;
455 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
456 * but that suggests it's checking the user, when it's really checking the title + user combination.
457 * @param $user User object to verify the permissions against
458 * @return mixed An array as returned by getUserPermissionsErrors or true
459 * in case the user has proper permissions.
461 public function verifyPermissions( $user ) {
462 return $this->verifyTitlePermissions( $user );
466 * Check whether the user can edit, upload and create the image. This
467 * checks only against the current title; if it returns errors, it may
468 * very well be that another title will not give errors. Therefore
469 * isAllowed() should be called as well for generic is-user-blocked or
470 * can-user-upload checking.
472 * @param $user User object to verify the permissions against
473 * @return mixed An array as returned by getUserPermissionsErrors or true
474 * in case the user has proper permissions.
476 public function verifyTitlePermissions( $user ) {
478 * If the image is protected, non-sysop users won't be able
479 * to modify it by uploading a new revision.
481 $nt = $this->getTitle();
482 if( is_null( $nt ) ) {
485 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
486 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
487 if ( !$nt->exists() ) {
488 $permErrorsCreate = $nt->getUserPermissionsErrors( 'createpage', $user );
490 $permErrorsCreate = array();
492 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
493 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
494 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
498 $overwriteError = $this->checkOverwrite( $user );
499 if ( $overwriteError !== true ) {
500 return array( $overwriteError );
507 * Check for non fatal problems with the file
509 * @return Array of warnings
511 public function checkWarnings() {
514 $localFile = $this->getLocalFile();
515 $filename = $localFile->getName();
518 * Check whether the resulting filename is different from the desired one,
519 * but ignore things like ucfirst() and spaces/underscore things
521 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
522 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
524 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
525 $warnings['badfilename'] = $filename;
528 // Check whether the file extension is on the unwanted list
529 global $wgCheckFileExtensions, $wgFileExtensions;
530 if ( $wgCheckFileExtensions ) {
531 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
532 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
536 global $wgUploadSizeWarning;
537 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
538 $warnings['large-file'] = $wgUploadSizeWarning;
541 if ( $this->mFileSize
== 0 ) {
542 $warnings['emptyfile'] = true;
545 $exists = self
::getExistsWarning( $localFile );
546 if( $exists !== false ) {
547 $warnings['exists'] = $exists;
550 // Check dupes against existing files
551 $hash = File
::sha1Base36( $this->mTempPath
);
552 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
553 $title = $this->getTitle();
554 // Remove all matches against self
555 foreach ( $dupes as $key => $dupe ) {
556 if( $title->equals( $dupe->getTitle() ) ) {
557 unset( $dupes[$key] );
561 $warnings['duplicate'] = $dupes;
564 // Check dupes against archives
565 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
566 if ( $archivedImage->getID() > 0 ) {
567 $warnings['duplicate-archive'] = $archivedImage->getName();
574 * Really perform the upload. Stores the file in the local repo, watches
575 * if necessary and runs the UploadComplete hook.
579 * @return Status indicating the whether the upload succeeded.
581 public function performUpload( $comment, $pageText, $watch, $user ) {
582 $status = $this->getLocalFile()->upload(
592 if( $status->isGood() ) {
594 $user->addWatch( $this->getLocalFile()->getTitle() );
597 wfRunHooks( 'UploadComplete', array( &$this ) );
604 * Returns the title of the file to be uploaded. Sets mTitleError in case
605 * the name was illegal.
607 * @return Title The title of the file or null in case the name was illegal
609 public function getTitle() {
610 if ( $this->mTitle
!== false ) {
611 return $this->mTitle
;
614 /* Assume that if a user specified File:Something.jpg, this is an error
615 * and that the namespace prefix needs to be stripped of.
617 $title = Title
::newFromText( $this->mDesiredDestName
);
618 if ( $title->getNamespace() == NS_FILE
) {
619 $this->mFilteredName
= $title->getDBkey();
621 $this->mFilteredName
= $this->mDesiredDestName
;
625 * Chop off any directories in the given filename. Then
626 * filter out illegal characters, and try to make a legible name
627 * out of it. We'll strip some silently that Title would die on.
629 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
630 /* Normalize to title form before we do any further processing */
631 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
632 if( is_null( $nt ) ) {
633 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
634 return $this->mTitle
= null;
636 $this->mFilteredName
= $nt->getDBkey();
639 * We'll want to blacklist against *any* 'extension', and use
640 * only the final one for the whitelist.
642 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
644 if( count( $ext ) ) {
645 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
647 $this->mFinalExtension
= '';
649 # No extension, try guessing one
650 $magic = MimeMagic
::singleton();
651 $mime = $magic->guessMimeType( $this->mTempPath
);
652 if ( $mime !== 'unknown/unknown' ) {
653 # Get a space separated list of extensions
654 $extList = $magic->getExtensionsForType( $mime );
656 # Set the extension to the canonical extension
657 $this->mFinalExtension
= strtok( $extList, ' ' );
659 # Fix up the other variables
660 $this->mFilteredName
.= ".{$this->mFinalExtension}";
661 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
662 $ext = array( $this->mFinalExtension
);
668 /* Don't allow users to override the blacklist (check file extension) */
669 global $wgCheckFileExtensions, $wgStrictFileExtensions;
670 global $wgFileExtensions, $wgFileBlacklist;
672 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
674 if ( $this->mFinalExtension
== '' ) {
675 $this->mTitleError
= self
::FILETYPE_MISSING
;
676 return $this->mTitle
= null;
677 } elseif ( $blackListedExtensions ||
678 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
679 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
680 $this->mBlackListedExtensions
= $blackListedExtensions;
681 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
682 return $this->mTitle
= null;
685 // Windows may be broken with special characters, see bug XXX
686 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
687 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
688 return $this->mTitle
= null;
691 # If there was more than one "extension", reassemble the base
692 # filename to prevent bogus complaints about length
693 if( count( $ext ) > 1 ) {
694 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
695 $partname .= '.' . $ext[$i];
699 if( strlen( $partname ) < 1 ) {
700 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
701 return $this->mTitle
= null;
704 return $this->mTitle
= $nt;
708 * Return the local file and initializes if necessary.
712 public function getLocalFile() {
713 if( is_null( $this->mLocalFile
) ) {
714 $nt = $this->getTitle();
715 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
717 return $this->mLocalFile
;
721 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
722 * called outside that context.
724 * Stash a file in a temporary directory for later processing
725 * after the user has confirmed it.
727 * If the user doesn't explicitly cancel or accept, these files
728 * can accumulate in the temp directory.
730 * @param $saveName String: the destination filename
731 * @param $tempSrc String: the source temporary file to save
732 * @return String: full path the stashed file, or false on failure
734 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
735 $repo = RepoGroup
::singleton()->getLocalRepo();
736 $status = $repo->storeTemp( $saveName, $tempSrc );
741 * If the user does not supply all necessary information in the first upload form submission (either by accident or
742 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
744 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
745 * into the user's session.
746 * This method returns the file object, which also has a 'sessionKey' property which can be passed through a form or
747 * API request to find this stashed file again.
749 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
750 * @return UploadStashFile stashed file
752 public function stashSessionFile( $key = null ) {
753 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
755 'mFileProps' => $this->mFileProps
,
756 'mSourceType' => $this->getSourceType(),
758 $file = $stash->stashFile( $this->mTempPath
, $data, $key );
759 $this->mLocalFile
= $file;
764 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashSessionFile().
766 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
767 * @return String: session key
769 public function stashSession( $key = null ) {
770 return $this->stashSessionFile( $key )->getSessionKey();
774 * If we've modified the upload file we need to manually remove it
775 * on exit to clean up.
777 public function cleanupTempFile() {
778 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
779 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
780 unlink( $this->mTempPath
);
784 public function getTempPath() {
785 return $this->mTempPath
;
789 * Split a file into a base name and all dot-delimited 'extensions'
790 * on the end. Some web server configurations will fall back to
791 * earlier pseudo-'extensions' to determine type and execute
792 * scripts, so the blacklist needs to check them all.
796 public static function splitExtensions( $filename ) {
797 $bits = explode( '.', $filename );
798 $basename = array_shift( $bits );
799 return array( $basename, $bits );
803 * Perform case-insensitive match against a list of file extensions.
804 * Returns true if the extension is in the list.
810 public static function checkFileExtension( $ext, $list ) {
811 return in_array( strtolower( $ext ), $list );
815 * Perform case-insensitive match against a list of file extensions.
816 * Returns an array of matching extensions.
822 public static function checkFileExtensionList( $ext, $list ) {
823 return array_intersect( array_map( 'strtolower', $ext ), $list );
827 * Checks if the mime type of the uploaded file matches the file extension.
829 * @param $mime String: the mime type of the uploaded file
830 * @param $extension String: the filename extension that the file is to be served with
833 public static function verifyExtension( $mime, $extension ) {
834 $magic = MimeMagic
::singleton();
836 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
837 if ( !$magic->isRecognizableExtension( $extension ) ) {
838 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
839 "unrecognized extension '$extension', can't verify\n" );
842 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
843 "recognized extension '$extension', so probably invalid file\n" );
847 $match = $magic->isMatchingExtension( $extension, $mime );
849 if ( $match === null ) {
850 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
852 } elseif( $match === true ) {
853 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
855 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
859 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
865 * Heuristic for detecting files that *could* contain JavaScript instructions or
866 * things that may look like HTML to a browser and are thus
867 * potentially harmful. The present implementation will produce false
868 * positives in some situations.
870 * @param $file String: pathname to the temporary upload file
871 * @param $mime String: the mime type of the file
872 * @param $extension String: the extension of the file
873 * @return Boolean: true if the file contains something looking like embedded scripts
875 public static function detectScript( $file, $mime, $extension ) {
876 global $wgAllowTitlesInSVG;
878 # ugly hack: for text files, always look at the entire file.
879 # For binary field, just check the first K.
881 if( strpos( $mime,'text/' ) === 0 ) {
882 $chunk = file_get_contents( $file );
884 $fp = fopen( $file, 'rb' );
885 $chunk = fread( $fp, 1024 );
889 $chunk = strtolower( $chunk );
895 # decode from UTF-16 if needed (could be used for obfuscation).
896 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
898 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
905 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
908 $chunk = trim( $chunk );
910 # @todo FIXME: Convert from UTF-16 if necessarry!
911 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
913 # check for HTML doctype
914 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
919 * Internet Explorer for Windows performs some really stupid file type
920 * autodetection which can cause it to interpret valid image files as HTML
921 * and potentially execute JavaScript, creating a cross-site scripting
924 * Apple's Safari browser also performs some unsafe file type autodetection
925 * which can cause legitimate files to be interpreted as HTML if the
926 * web server is not correctly configured to send the right content-type
927 * (or if you're really uploading plain text and octet streams!)
929 * Returns true if IE is likely to mistake the given file for HTML.
930 * Also returns true if Safari would mistake the given file for HTML
931 * when served with a generic content-type.
937 '<html', #also in safari
940 '<script', #also in safari
944 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
948 foreach( $tags as $tag ) {
949 if( false !== strpos( $chunk, $tag ) ) {
950 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
956 * look for JavaScript
959 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
960 $chunk = Sanitizer
::decodeCharReferences( $chunk );
962 # look for script-types
963 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
964 wfDebug( __METHOD__
. ": found script types\n" );
968 # look for html-style script-urls
969 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
970 wfDebug( __METHOD__
. ": found html-style script urls\n" );
974 # look for css-style script-urls
975 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
976 wfDebug( __METHOD__
. ": found css-style script urls\n" );
980 wfDebug( __METHOD__
. ": no scripts found\n" );
984 protected function detectScriptInSvg( $filename ) {
985 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
986 return $check->filterMatch
;
990 * @todo Replace this with a whitelist filter!
992 public function checkSvgScriptCallback( $element, $attribs ) {
993 $stripped = $this->stripXmlNamespace( $element );
995 if( $stripped == 'script' ) {
996 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1000 foreach( $attribs as $attrib => $value ) {
1001 $stripped = $this->stripXmlNamespace( $attrib );
1002 if( substr( $stripped, 0, 2 ) == 'on' ) {
1003 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1006 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1007 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1013 private function stripXmlNamespace( $name ) {
1014 // 'http://www.w3.org/2000/svg:script' -> 'script'
1015 $parts = explode( ':', strtolower( $name ) );
1016 return array_pop( $parts );
1020 * Generic wrapper function for a virus scanner program.
1021 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1022 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1024 * @param $file String: pathname to the temporary upload file
1025 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1026 * or a string containing feedback from the virus scanner if a virus was found.
1027 * If textual feedback is missing but a virus was found, this function returns true.
1029 public static function detectVirus( $file ) {
1030 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1032 if ( !$wgAntivirus ) {
1033 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1037 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1038 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1039 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1040 array( 'virus-badscanner', $wgAntivirus ) );
1041 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1044 # look up scanner configuration
1045 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1046 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1047 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1048 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1050 if ( strpos( $command, "%f" ) === false ) {
1051 # simple pattern: append file to scan
1052 $command .= " " . wfEscapeShellArg( $file );
1054 # complex pattern: replace "%f" with file to scan
1055 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1058 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1060 # execute virus scanner
1063 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1064 # that does not seem to be worth the pain.
1065 # Ask me (Duesentrieb) about it if it's ever needed.
1066 $output = wfShellExec( "$command 2>&1", $exitCode );
1068 # map exit code to AV_xxx constants.
1069 $mappedCode = $exitCode;
1070 if ( $exitCodeMap ) {
1071 if ( isset( $exitCodeMap[$exitCode] ) ) {
1072 $mappedCode = $exitCodeMap[$exitCode];
1073 } elseif ( isset( $exitCodeMap["*"] ) ) {
1074 $mappedCode = $exitCodeMap["*"];
1078 if ( $mappedCode === AV_SCAN_FAILED
) {
1079 # scan failed (code was mapped to false by $exitCodeMap)
1080 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1082 if ( $wgAntivirusRequired ) {
1083 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1087 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1088 # scan failed because filetype is unknown (probably imune)
1089 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1091 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1093 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1096 $output = trim( $output );
1099 $output = true; #if there's no output, return true
1100 } elseif ( $msgPattern ) {
1102 if ( preg_match( $msgPattern, $output, $groups ) ) {
1104 $output = $groups[1];
1109 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1115 * Check if the temporary file is MacBinary-encoded, as some uploads
1116 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1117 * If so, the data fork will be extracted to a second temporary file,
1118 * which will then be checked for validity and either kept or discarded.
1120 private function checkMacBinary() {
1121 $macbin = new MacBinary( $this->mTempPath
);
1122 if( $macbin->isValid() ) {
1123 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
1124 $dataHandle = fopen( $dataFile, 'wb' );
1126 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
1127 $macbin->extractData( $dataHandle );
1129 $this->mTempPath
= $dataFile;
1130 $this->mFileSize
= $macbin->dataForkLength();
1132 // We'll have to manually remove the new file if it's not kept.
1133 $this->mRemoveTempFile
= true;
1139 * Check if there's an overwrite conflict and, if so, if restrictions
1140 * forbid this user from performing the upload.
1144 * @return mixed true on success, array on failure
1146 private function checkOverwrite( $user ) {
1147 // First check whether the local file can be overwritten
1148 $file = $this->getLocalFile();
1149 if( $file->exists() ) {
1150 if( !self
::userCanReUpload( $user, $file ) ) {
1151 return array( 'fileexists-forbidden', $file->getName() );
1157 /* Check shared conflicts: if the local file does not exist, but
1158 * wfFindFile finds a file, it exists in a shared repository.
1160 $file = wfFindFile( $this->getTitle() );
1161 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1162 return array( 'fileexists-shared-forbidden', $file->getName() );
1169 * Check if a user is the last uploader
1171 * @param $user User object
1172 * @param $img String: image name
1175 public static function userCanReUpload( User
$user, $img ) {
1176 if( $user->isAllowed( 'reupload' ) ) {
1177 return true; // non-conditional
1179 if( !$user->isAllowed( 'reupload-own' ) ) {
1182 if( is_string( $img ) ) {
1183 $img = wfLocalFile( $img );
1185 if ( !( $img instanceof LocalFile
) ) {
1189 return $user->getId() == $img->getUser( 'id' );
1193 * Helper function that does various existence checks for a file.
1194 * The following checks are performed:
1196 * - Article with the same name as the file exists
1197 * - File exists with normalized extension
1198 * - The file looks like a thumbnail and the original exists
1200 * @param $file File The File object to check
1201 * @return mixed False if the file does not exists, else an array
1203 public static function getExistsWarning( $file ) {
1204 if( $file->exists() ) {
1205 return array( 'warning' => 'exists', 'file' => $file );
1208 if( $file->getTitle()->getArticleID() ) {
1209 return array( 'warning' => 'page-exists', 'file' => $file );
1212 if ( $file->wasDeleted() && !$file->exists() ) {
1213 return array( 'warning' => 'was-deleted', 'file' => $file );
1216 if( strpos( $file->getName(), '.' ) == false ) {
1217 $partname = $file->getName();
1220 $n = strrpos( $file->getName(), '.' );
1221 $extension = substr( $file->getName(), $n +
1 );
1222 $partname = substr( $file->getName(), 0, $n );
1224 $normalizedExtension = File
::normalizeExtension( $extension );
1226 if ( $normalizedExtension != $extension ) {
1227 // We're not using the normalized form of the extension.
1228 // Normal form is lowercase, using most common of alternate
1229 // extensions (eg 'jpg' rather than 'JPEG').
1231 // Check for another file using the normalized form...
1232 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1233 $file_lc = wfLocalFile( $nt_lc );
1235 if( $file_lc->exists() ) {
1237 'warning' => 'exists-normalized',
1239 'normalizedFile' => $file_lc
1244 if ( self
::isThumbName( $file->getName() ) ) {
1245 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1246 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1247 $file_thb = wfLocalFile( $nt_thb );
1248 if( $file_thb->exists() ) {
1250 'warning' => 'thumb',
1252 'thumbFile' => $file_thb
1255 // File does not exist, but we just don't like the name
1257 'warning' => 'thumb-name',
1259 'thumbFile' => $file_thb
1265 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1266 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1268 'warning' => 'bad-prefix',
1279 * Helper function that checks whether the filename looks like a thumbnail
1281 public static function isThumbName( $filename ) {
1282 $n = strrpos( $filename, '.' );
1283 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1285 substr( $partname , 3, 3 ) == 'px-' ||
1286 substr( $partname , 2, 3 ) == 'px-'
1288 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1292 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1294 * @return array list of prefixes
1296 public static function getFilenamePrefixBlacklist() {
1297 $blacklist = array();
1298 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1299 if( !$message->isDisabled() ) {
1300 $lines = explode( "\n", $message->plain() );
1301 foreach( $lines as $line ) {
1302 // Remove comment lines
1303 $comment = substr( trim( $line ), 0, 1 );
1304 if ( $comment == '#' ||
$comment == '' ) {
1307 // Remove additional comments after a prefix
1308 $comment = strpos( $line, '#' );
1309 if ( $comment > 0 ) {
1310 $line = substr( $line, 0, $comment-1 );
1312 $blacklist[] = trim( $line );
1319 * Gets image info about the file just uploaded.
1321 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1322 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1323 * with the appropriate format, presumably.
1325 * @param $result ApiResult:
1326 * @return Array: image info
1328 public function getImageInfo( $result ) {
1329 $file = $this->getLocalFile();
1330 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1331 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1332 if ( $file instanceof UploadStashFile
) {
1333 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1334 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1336 $imParam = ApiQueryImageInfo
::getPropertyNames();
1337 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1343 public function convertVerifyErrorToStatus( $error ) {
1344 $code = $error['status'];
1345 unset( $code['status'] );
1346 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1349 public static function getMaxUploadSize( $forType = null ) {
1350 global $wgMaxUploadSize;
1352 if ( is_array( $wgMaxUploadSize ) ) {
1353 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1354 return $wgMaxUploadSize[$forType];
1356 return $wgMaxUploadSize['*'];
1359 return intval( $wgMaxUploadSize );