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;
73 if ( !$wgEnableUploads ) {
77 # Check php's file_uploads setting
78 if( !wfIniGetBool( 'file_uploads' ) ) {
85 * Returns true if the user can use this upload module or else a string
86 * identifying the missing permission.
87 * Can be overriden by subclasses.
91 public static function isAllowed( $user ) {
92 foreach ( array( 'upload', 'edit' ) as $permission ) {
93 if ( !$user->isAllowed( $permission ) ) {
100 // Upload handlers. Should probably just be a global.
101 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
104 * Create a form of UploadBase depending on wpSourceType and initializes it
106 * @param $request WebRequest
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 * Returns the upload type. Should be overridden by child classes
160 public function getSourceType() { return null; }
163 * Initialize the path information
164 * @param $name string the desired destination name
165 * @param $tempPath string the temporary path
166 * @param $fileSize int the file size
167 * @param $removeTempFile bool (false) remove the temporary file?
170 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
171 $this->mDesiredDestName
= $name;
172 $this->mTempPath
= $tempPath;
173 $this->mFileSize
= $fileSize;
174 $this->mRemoveTempFile
= $removeTempFile;
178 * Initialize from a WebRequest. Override this in a subclass.
180 public abstract function initializeFromRequest( &$request );
183 * Fetch the file. Usually a no-op
185 public function fetchFile() {
186 return Status
::newGood();
190 * Return true if the file is empty
193 public function isEmptyFile() {
194 return empty( $this->mFileSize
);
198 * Return the file size
201 public function getFileSize() {
202 return $this->mFileSize
;
206 * Append a file to the Repo file
208 * @param $srcPath String: path to source file
209 * @param $toAppendPath String: path to the Repo file that will be appended to.
210 * @return Status Status
212 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
213 $repo = RepoGroup
::singleton()->getLocalRepo();
214 $status = $repo->append( $srcPath, $toAppendPath );
219 * Finish appending to the Repo file
221 * @param $toAppendPath String: path to the Repo file that will be appended to.
222 * @return Status Status
224 protected function appendFinish( $toAppendPath ) {
225 $repo = RepoGroup
::singleton()->getLocalRepo();
226 $status = $repo->appendFinish( $toAppendPath );
232 * @param $srcPath String: the source path
233 * @return the real path if it was a virtual URL
235 function getRealPath( $srcPath ) {
236 $repo = RepoGroup
::singleton()->getLocalRepo();
237 if ( $repo->isVirtualUrl( $srcPath ) ) {
238 return $repo->resolveVirtualUrl( $srcPath );
244 * Verify whether the upload is sane.
245 * @return mixed self::OK or else an array with error information
247 public function verifyUpload() {
249 * If there was no filename or a zero size given, give up quick.
251 if( $this->isEmptyFile() ) {
252 return array( 'status' => self
::EMPTY_FILE
);
256 * Honor $wgMaxUploadSize
258 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
259 if( $this->mFileSize
> $maxSize ) {
261 'status' => self
::FILE_TOO_LARGE
,
267 * Look at the contents of the file; if we can recognize the
268 * type but it's corrupt or data of the wrong type, we should
269 * probably not accept it.
271 $verification = $this->verifyFile();
272 if( $verification !== true ) {
274 'status' => self
::VERIFICATION_ERROR
,
275 'details' => $verification
280 * Make sure this file can be created
282 $result = $this->validateName();
283 if( $result !== true ) {
288 if( !wfRunHooks( 'UploadVerification',
289 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
290 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
293 return array( 'status' => self
::OK
);
297 * Verify that the name is valid and, if necessary, that we can overwrite
299 * @return mixed true if valid, otherwise and array with 'status'
302 protected function validateName() {
303 $nt = $this->getTitle();
304 if( is_null( $nt ) ) {
305 $result = array( 'status' => $this->mTitleError
);
306 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
307 $result['filtered'] = $this->mFilteredName
;
309 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
310 $result['finalExt'] = $this->mFinalExtension
;
311 if ( count( $this->mBlackListedExtensions
) ) {
312 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
317 $this->mDestName
= $this->getLocalFile()->getName();
323 * Verify the mime type
325 * @param $mime string representing the mime
326 * @return mixed true if the file is verified, an array otherwise
328 protected function verifyMimeType( $mime ) {
329 global $wgVerifyMimeType;
330 if ( $wgVerifyMimeType ) {
331 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
332 global $wgMimeTypeBlacklist;
333 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
334 return array( 'filetype-badmime', $mime );
337 # XXX: Missing extension will be caught by validateName() via getTitle()
338 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
339 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
343 $fp = fopen( $this->mTempPath
, 'rb' );
344 $chunk = fread( $fp, 256 );
347 $magic = MimeMagic
::singleton();
348 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
349 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
350 foreach ( $ieTypes as $ieType ) {
351 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
352 return array( 'filetype-bad-ie-mime', $ieType );
361 * Verifies that it's ok to include the uploaded file
363 * @return mixed true of the file is verified, array otherwise.
365 protected function verifyFile() {
366 global $wgAllowJavaUploads;
367 # get the title, even though we are doing nothing with it, because
368 # we need to populate mFinalExtension
371 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
372 $this->checkMacBinary();
374 # check mime type, if desired
375 $mime = $this->mFileProps
[ 'file-mime' ];
376 $status = $this->verifyMimeType( $mime );
377 if ( $status !== true ) {
381 # check for htmlish code and javascript
382 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
383 return array( 'uploadscripted' );
385 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
386 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
387 return array( 'uploadscripted' );
391 # Check for Java applets, which if uploaded can bypass cross-site
393 if ( !$wgAllowJavaUploads ) {
394 $this->mJavaDetected
= false;
395 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
396 array( $this, 'zipEntryCallback' ) );
397 if ( !$zipStatus->isOK() ) {
398 $errors = $zipStatus->getErrorsArray();
399 $error = reset( $errors );
400 if ( $error[0] !== 'zip-wrong-format' ) {
404 if ( $this->mJavaDetected
) {
405 return array( 'uploadjava' );
409 # Scan the uploaded file for viruses
410 $virus = $this->detectVirus( $this->mTempPath
);
412 return array( 'uploadvirus', $virus );
415 $handler = MediaHandler
::getHandler( $mime );
417 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
418 if ( !$handlerStatus->isOK() ) {
419 $errors = $handlerStatus->getErrorsArray();
420 return reset( $errors );
424 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
425 if ( $status !== true ) {
429 wfDebug( __METHOD__
. ": all clear; passing.\n" );
434 * Callback for ZipDirectoryReader to detect Java class files.
436 function zipEntryCallback( $entry ) {
437 $names = array( $entry['name'] );
439 // If there is a null character, cut off the name at it, because JDK's
440 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
441 // were constructed which had ".class\0" followed by a string chosen to
442 // make the hash collide with the truncated name, that file could be
443 // returned in response to a request for the .class file.
444 $nullPos = strpos( $entry['name'], "\000" );
445 if ( $nullPos !== false ) {
446 $names[] = substr( $entry['name'], 0, $nullPos );
449 // If there is a trailing slash in the file name, we have to strip it,
450 // because that's what ZIP_GetEntry() does.
451 if ( preg_grep( '!\.class/?$!', $names ) ) {
452 $this->mJavaDetected
= true;
457 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
458 * but that suggests it's checking the user, when it's really checking the title + user combination.
459 * @param $user User object to verify the permissions against
460 * @return mixed An array as returned by getUserPermissionsErrors or true
461 * in case the user has proper permissions.
463 public function verifyPermissions( $user ) {
464 return $this->verifyTitlePermissions( $user );
468 * Check whether the user can edit, upload and create the image. This
469 * checks only against the current title; if it returns errors, it may
470 * very well be that another title will not give errors. Therefore
471 * isAllowed() should be called as well for generic is-user-blocked or
472 * can-user-upload checking.
474 * @param $user User object to verify the permissions against
475 * @return mixed An array as returned by getUserPermissionsErrors or true
476 * in case the user has proper permissions.
478 public function verifyTitlePermissions( $user ) {
480 * If the image is protected, non-sysop users won't be able
481 * to modify it by uploading a new revision.
483 $nt = $this->getTitle();
484 if( is_null( $nt ) ) {
487 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
488 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
489 if ( !$nt->exists() ) {
490 $permErrorsCreate = $nt->getUserPermissionsErrors( 'createpage', $user );
492 $permErrorsCreate = array();
494 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
495 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
496 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
500 $overwriteError = $this->checkOverwrite( $user );
501 if ( $overwriteError !== true ) {
502 return array( $overwriteError );
509 * Check for non fatal problems with the file
511 * @return Array of warnings
513 public function checkWarnings() {
516 $localFile = $this->getLocalFile();
517 $filename = $localFile->getName();
520 * Check whether the resulting filename is different from the desired one,
521 * but ignore things like ucfirst() and spaces/underscore things
523 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
524 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
526 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
527 $warnings['badfilename'] = $filename;
530 // Check whether the file extension is on the unwanted list
531 global $wgCheckFileExtensions, $wgFileExtensions;
532 if ( $wgCheckFileExtensions ) {
533 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
534 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
538 global $wgUploadSizeWarning;
539 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
540 $warnings['large-file'] = $wgUploadSizeWarning;
543 if ( $this->mFileSize
== 0 ) {
544 $warnings['emptyfile'] = true;
547 $exists = self
::getExistsWarning( $localFile );
548 if( $exists !== false ) {
549 $warnings['exists'] = $exists;
552 // Check dupes against existing files
553 $hash = File
::sha1Base36( $this->mTempPath
);
554 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
555 $title = $this->getTitle();
556 // Remove all matches against self
557 foreach ( $dupes as $key => $dupe ) {
558 if( $title->equals( $dupe->getTitle() ) ) {
559 unset( $dupes[$key] );
563 $warnings['duplicate'] = $dupes;
566 // Check dupes against archives
567 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
568 if ( $archivedImage->getID() > 0 ) {
569 $warnings['duplicate-archive'] = $archivedImage->getName();
576 * Really perform the upload. Stores the file in the local repo, watches
577 * if necessary and runs the UploadComplete hook.
581 * @return Status indicating the whether the upload succeeded.
583 public function performUpload( $comment, $pageText, $watch, $user ) {
584 $status = $this->getLocalFile()->upload(
594 if( $status->isGood() ) {
596 $user->addWatch( $this->getLocalFile()->getTitle() );
599 wfRunHooks( 'UploadComplete', array( &$this ) );
606 * Returns the title of the file to be uploaded. Sets mTitleError in case
607 * the name was illegal.
609 * @return Title The title of the file or null in case the name was illegal
611 public function getTitle() {
612 if ( $this->mTitle
!== false ) {
613 return $this->mTitle
;
616 /* Assume that if a user specified File:Something.jpg, this is an error
617 * and that the namespace prefix needs to be stripped of.
619 $title = Title
::newFromText( $this->mDesiredDestName
);
620 if ( $title->getNamespace() == NS_FILE
) {
621 $this->mFilteredName
= $title->getDBkey();
623 $this->mFilteredName
= $this->mDesiredDestName
;
627 * Chop off any directories in the given filename. Then
628 * filter out illegal characters, and try to make a legible name
629 * out of it. We'll strip some silently that Title would die on.
631 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
632 /* Normalize to title form before we do any further processing */
633 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
634 if( is_null( $nt ) ) {
635 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
636 return $this->mTitle
= null;
638 $this->mFilteredName
= $nt->getDBkey();
641 * We'll want to blacklist against *any* 'extension', and use
642 * only the final one for the whitelist.
644 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
646 if( count( $ext ) ) {
647 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
649 $this->mFinalExtension
= '';
651 # No extension, try guessing one
652 $magic = MimeMagic
::singleton();
653 $mime = $magic->guessMimeType( $this->mTempPath
);
654 if ( $mime !== 'unknown/unknown' ) {
655 # Get a space separated list of extensions
656 $extList = $magic->getExtensionsForType( $mime );
658 # Set the extension to the canonical extension
659 $this->mFinalExtension
= strtok( $extList, ' ' );
661 # Fix up the other variables
662 $this->mFilteredName
.= ".{$this->mFinalExtension}";
663 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
664 $ext = array( $this->mFinalExtension
);
670 /* Don't allow users to override the blacklist (check file extension) */
671 global $wgCheckFileExtensions, $wgStrictFileExtensions;
672 global $wgFileExtensions, $wgFileBlacklist;
674 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
676 if ( $this->mFinalExtension
== '' ) {
677 $this->mTitleError
= self
::FILETYPE_MISSING
;
678 return $this->mTitle
= null;
679 } elseif ( $blackListedExtensions ||
680 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
681 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
682 $this->mBlackListedExtensions
= $blackListedExtensions;
683 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
684 return $this->mTitle
= null;
687 // Windows may be broken with special characters, see bug XXX
688 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
689 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
690 return $this->mTitle
= null;
693 # If there was more than one "extension", reassemble the base
694 # filename to prevent bogus complaints about length
695 if( count( $ext ) > 1 ) {
696 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
697 $partname .= '.' . $ext[$i];
701 if( strlen( $partname ) < 1 ) {
702 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
703 return $this->mTitle
= null;
706 return $this->mTitle
= $nt;
710 * Return the local file and initializes if necessary.
714 public function getLocalFile() {
715 if( is_null( $this->mLocalFile
) ) {
716 $nt = $this->getTitle();
717 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
719 return $this->mLocalFile
;
723 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
724 * called outside that context.
726 * Stash a file in a temporary directory for later processing
727 * after the user has confirmed it.
729 * If the user doesn't explicitly cancel or accept, these files
730 * can accumulate in the temp directory.
732 * @param $saveName String: the destination filename
733 * @param $tempSrc String: the source temporary file to save
734 * @return String: full path the stashed file, or false on failure
736 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
737 $repo = RepoGroup
::singleton()->getLocalRepo();
738 $status = $repo->storeTemp( $saveName, $tempSrc );
743 * If the user does not supply all necessary information in the first upload form submission (either by accident or
744 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
746 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
747 * into the user's session.
748 * This method returns the file object, which also has a 'sessionKey' property which can be passed through a form or
749 * API request to find this stashed file again.
751 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
752 * @return UploadStashFile stashed file
754 public function stashSessionFile( $key = null ) {
755 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
757 'mFileProps' => $this->mFileProps
,
758 'mSourceType' => $this->getSourceType(),
760 $file = $stash->stashFile( $this->mTempPath
, $data, $key );
761 $this->mLocalFile
= $file;
766 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashSessionFile().
768 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
769 * @return String: session key
771 public function stashSession( $key = null ) {
772 return $this->stashSessionFile( $key )->getSessionKey();
776 * If we've modified the upload file we need to manually remove it
777 * on exit to clean up.
779 public function cleanupTempFile() {
780 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
781 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
782 unlink( $this->mTempPath
);
786 public function getTempPath() {
787 return $this->mTempPath
;
791 * Split a file into a base name and all dot-delimited 'extensions'
792 * on the end. Some web server configurations will fall back to
793 * earlier pseudo-'extensions' to determine type and execute
794 * scripts, so the blacklist needs to check them all.
798 public static function splitExtensions( $filename ) {
799 $bits = explode( '.', $filename );
800 $basename = array_shift( $bits );
801 return array( $basename, $bits );
805 * Perform case-insensitive match against a list of file extensions.
806 * Returns true if the extension is in the list.
812 public static function checkFileExtension( $ext, $list ) {
813 return in_array( strtolower( $ext ), $list );
817 * Perform case-insensitive match against a list of file extensions.
818 * Returns an array of matching extensions.
824 public static function checkFileExtensionList( $ext, $list ) {
825 return array_intersect( array_map( 'strtolower', $ext ), $list );
829 * Checks if the mime type of the uploaded file matches the file extension.
831 * @param $mime String: the mime type of the uploaded file
832 * @param $extension String: the filename extension that the file is to be served with
835 public static function verifyExtension( $mime, $extension ) {
836 $magic = MimeMagic
::singleton();
838 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
839 if ( !$magic->isRecognizableExtension( $extension ) ) {
840 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
841 "unrecognized extension '$extension', can't verify\n" );
844 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
845 "recognized extension '$extension', so probably invalid file\n" );
849 $match = $magic->isMatchingExtension( $extension, $mime );
851 if ( $match === null ) {
852 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
854 } elseif( $match === true ) {
855 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
857 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
861 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
867 * Heuristic for detecting files that *could* contain JavaScript instructions or
868 * things that may look like HTML to a browser and are thus
869 * potentially harmful. The present implementation will produce false
870 * positives in some situations.
872 * @param $file String: pathname to the temporary upload file
873 * @param $mime String: the mime type of the file
874 * @param $extension String: the extension of the file
875 * @return Boolean: true if the file contains something looking like embedded scripts
877 public static function detectScript( $file, $mime, $extension ) {
878 global $wgAllowTitlesInSVG;
880 # ugly hack: for text files, always look at the entire file.
881 # For binary field, just check the first K.
883 if( strpos( $mime,'text/' ) === 0 ) {
884 $chunk = file_get_contents( $file );
886 $fp = fopen( $file, 'rb' );
887 $chunk = fread( $fp, 1024 );
891 $chunk = strtolower( $chunk );
897 # decode from UTF-16 if needed (could be used for obfuscation).
898 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
900 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
907 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
910 $chunk = trim( $chunk );
912 # @todo FIXME: Convert from UTF-16 if necessarry!
913 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
915 # check for HTML doctype
916 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
921 * Internet Explorer for Windows performs some really stupid file type
922 * autodetection which can cause it to interpret valid image files as HTML
923 * and potentially execute JavaScript, creating a cross-site scripting
926 * Apple's Safari browser also performs some unsafe file type autodetection
927 * which can cause legitimate files to be interpreted as HTML if the
928 * web server is not correctly configured to send the right content-type
929 * (or if you're really uploading plain text and octet streams!)
931 * Returns true if IE is likely to mistake the given file for HTML.
932 * Also returns true if Safari would mistake the given file for HTML
933 * when served with a generic content-type.
939 '<html', #also in safari
942 '<script', #also in safari
946 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
950 foreach( $tags as $tag ) {
951 if( false !== strpos( $chunk, $tag ) ) {
952 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
958 * look for JavaScript
961 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
962 $chunk = Sanitizer
::decodeCharReferences( $chunk );
964 # look for script-types
965 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
966 wfDebug( __METHOD__
. ": found script types\n" );
970 # look for html-style script-urls
971 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
972 wfDebug( __METHOD__
. ": found html-style script urls\n" );
976 # look for css-style script-urls
977 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
978 wfDebug( __METHOD__
. ": found css-style script urls\n" );
982 wfDebug( __METHOD__
. ": no scripts found\n" );
986 protected function detectScriptInSvg( $filename ) {
987 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
988 return $check->filterMatch
;
992 * @todo Replace this with a whitelist filter!
994 public function checkSvgScriptCallback( $element, $attribs ) {
995 $stripped = $this->stripXmlNamespace( $element );
997 if( $stripped == 'script' ) {
998 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1002 foreach( $attribs as $attrib => $value ) {
1003 $stripped = $this->stripXmlNamespace( $attrib );
1004 if( substr( $stripped, 0, 2 ) == 'on' ) {
1005 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1008 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1009 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1015 private function stripXmlNamespace( $name ) {
1016 // 'http://www.w3.org/2000/svg:script' -> 'script'
1017 $parts = explode( ':', strtolower( $name ) );
1018 return array_pop( $parts );
1022 * Generic wrapper function for a virus scanner program.
1023 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1024 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1026 * @param $file String: pathname to the temporary upload file
1027 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1028 * or a string containing feedback from the virus scanner if a virus was found.
1029 * If textual feedback is missing but a virus was found, this function returns true.
1031 public static function detectVirus( $file ) {
1032 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1034 if ( !$wgAntivirus ) {
1035 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1039 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1040 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1041 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1042 array( 'virus-badscanner', $wgAntivirus ) );
1043 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1046 # look up scanner configuration
1047 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1048 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1049 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1050 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1052 if ( strpos( $command, "%f" ) === false ) {
1053 # simple pattern: append file to scan
1054 $command .= " " . wfEscapeShellArg( $file );
1056 # complex pattern: replace "%f" with file to scan
1057 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1060 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1062 # execute virus scanner
1065 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1066 # that does not seem to be worth the pain.
1067 # Ask me (Duesentrieb) about it if it's ever needed.
1068 $output = wfShellExec( "$command 2>&1", $exitCode );
1070 # map exit code to AV_xxx constants.
1071 $mappedCode = $exitCode;
1072 if ( $exitCodeMap ) {
1073 if ( isset( $exitCodeMap[$exitCode] ) ) {
1074 $mappedCode = $exitCodeMap[$exitCode];
1075 } elseif ( isset( $exitCodeMap["*"] ) ) {
1076 $mappedCode = $exitCodeMap["*"];
1080 if ( $mappedCode === AV_SCAN_FAILED
) {
1081 # scan failed (code was mapped to false by $exitCodeMap)
1082 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1084 if ( $wgAntivirusRequired ) {
1085 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1089 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1090 # scan failed because filetype is unknown (probably imune)
1091 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1093 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1095 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1098 $output = trim( $output );
1101 $output = true; #if there's no output, return true
1102 } elseif ( $msgPattern ) {
1104 if ( preg_match( $msgPattern, $output, $groups ) ) {
1106 $output = $groups[1];
1111 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1117 * Check if the temporary file is MacBinary-encoded, as some uploads
1118 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1119 * If so, the data fork will be extracted to a second temporary file,
1120 * which will then be checked for validity and either kept or discarded.
1122 private function checkMacBinary() {
1123 $macbin = new MacBinary( $this->mTempPath
);
1124 if( $macbin->isValid() ) {
1125 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
1126 $dataHandle = fopen( $dataFile, 'wb' );
1128 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
1129 $macbin->extractData( $dataHandle );
1131 $this->mTempPath
= $dataFile;
1132 $this->mFileSize
= $macbin->dataForkLength();
1134 // We'll have to manually remove the new file if it's not kept.
1135 $this->mRemoveTempFile
= true;
1141 * Check if there's an overwrite conflict and, if so, if restrictions
1142 * forbid this user from performing the upload.
1146 * @return mixed true on success, array on failure
1148 private function checkOverwrite( $user ) {
1149 // First check whether the local file can be overwritten
1150 $file = $this->getLocalFile();
1151 if( $file->exists() ) {
1152 if( !self
::userCanReUpload( $user, $file ) ) {
1153 return array( 'fileexists-forbidden', $file->getName() );
1159 /* Check shared conflicts: if the local file does not exist, but
1160 * wfFindFile finds a file, it exists in a shared repository.
1162 $file = wfFindFile( $this->getTitle() );
1163 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1164 return array( 'fileexists-shared-forbidden', $file->getName() );
1171 * Check if a user is the last uploader
1173 * @param $user User object
1174 * @param $img String: image name
1177 public static function userCanReUpload( User
$user, $img ) {
1178 if( $user->isAllowed( 'reupload' ) ) {
1179 return true; // non-conditional
1181 if( !$user->isAllowed( 'reupload-own' ) ) {
1184 if( is_string( $img ) ) {
1185 $img = wfLocalFile( $img );
1187 if ( !( $img instanceof LocalFile
) ) {
1191 return $user->getId() == $img->getUser( 'id' );
1195 * Helper function that does various existence checks for a file.
1196 * The following checks are performed:
1198 * - Article with the same name as the file exists
1199 * - File exists with normalized extension
1200 * - The file looks like a thumbnail and the original exists
1202 * @param $file File The File object to check
1203 * @return mixed False if the file does not exists, else an array
1205 public static function getExistsWarning( $file ) {
1206 if( $file->exists() ) {
1207 return array( 'warning' => 'exists', 'file' => $file );
1210 if( $file->getTitle()->getArticleID() ) {
1211 return array( 'warning' => 'page-exists', 'file' => $file );
1214 if ( $file->wasDeleted() && !$file->exists() ) {
1215 return array( 'warning' => 'was-deleted', 'file' => $file );
1218 if( strpos( $file->getName(), '.' ) == false ) {
1219 $partname = $file->getName();
1222 $n = strrpos( $file->getName(), '.' );
1223 $extension = substr( $file->getName(), $n +
1 );
1224 $partname = substr( $file->getName(), 0, $n );
1226 $normalizedExtension = File
::normalizeExtension( $extension );
1228 if ( $normalizedExtension != $extension ) {
1229 // We're not using the normalized form of the extension.
1230 // Normal form is lowercase, using most common of alternate
1231 // extensions (eg 'jpg' rather than 'JPEG').
1233 // Check for another file using the normalized form...
1234 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1235 $file_lc = wfLocalFile( $nt_lc );
1237 if( $file_lc->exists() ) {
1239 'warning' => 'exists-normalized',
1241 'normalizedFile' => $file_lc
1246 if ( self
::isThumbName( $file->getName() ) ) {
1247 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1248 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1249 $file_thb = wfLocalFile( $nt_thb );
1250 if( $file_thb->exists() ) {
1252 'warning' => 'thumb',
1254 'thumbFile' => $file_thb
1257 // File does not exist, but we just don't like the name
1259 'warning' => 'thumb-name',
1261 'thumbFile' => $file_thb
1267 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1268 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1270 'warning' => 'bad-prefix',
1281 * Helper function that checks whether the filename looks like a thumbnail
1283 public static function isThumbName( $filename ) {
1284 $n = strrpos( $filename, '.' );
1285 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1287 substr( $partname , 3, 3 ) == 'px-' ||
1288 substr( $partname , 2, 3 ) == 'px-'
1290 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1294 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1296 * @return array list of prefixes
1298 public static function getFilenamePrefixBlacklist() {
1299 $blacklist = array();
1300 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1301 if( !$message->isDisabled() ) {
1302 $lines = explode( "\n", $message->plain() );
1303 foreach( $lines as $line ) {
1304 // Remove comment lines
1305 $comment = substr( trim( $line ), 0, 1 );
1306 if ( $comment == '#' ||
$comment == '' ) {
1309 // Remove additional comments after a prefix
1310 $comment = strpos( $line, '#' );
1311 if ( $comment > 0 ) {
1312 $line = substr( $line, 0, $comment-1 );
1314 $blacklist[] = trim( $line );
1321 * Gets image info about the file just uploaded.
1323 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1324 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1325 * with the appropriate format, presumably.
1327 * @param $result ApiResult:
1328 * @return Array: image info
1330 public function getImageInfo( $result ) {
1331 $file = $this->getLocalFile();
1332 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1333 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1334 if ( $file instanceof UploadStashFile
) {
1335 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1336 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1338 $imParam = ApiQueryImageInfo
::getPropertyNames();
1339 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1345 public function convertVerifyErrorToStatus( $error ) {
1346 $code = $error['status'];
1347 unset( $code['status'] );
1348 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1351 public static function getMaxUploadSize( $forType = null ) {
1352 global $wgMaxUploadSize;
1354 if ( is_array( $wgMaxUploadSize ) ) {
1355 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1356 return $wgMaxUploadSize[$forType];
1358 return $wgMaxUploadSize['*'];
1361 return intval( $wgMaxUploadSize );