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 public function getVerificationErrorCode( $error ) {
42 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
43 self
::FILE_TOO_LARGE
=> 'file-too-large',
44 self
::FILETYPE_MISSING
=> 'filetype-missing',
45 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
46 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
47 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
48 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
49 self
::VERIFICATION_ERROR
=> 'verification-error',
50 self
::HOOK_ABORTED
=> 'hookaborted',
51 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
53 if( isset( $code_to_status[$error] ) ) {
54 return $code_to_status[$error];
57 return 'unknown-error';
61 * Returns true if uploads are enabled.
62 * Can be override by subclasses.
64 public static function isEnabled() {
65 global $wgEnableUploads;
67 if ( !$wgEnableUploads ) {
71 # Check php's file_uploads setting
72 return wfIsHipHop() ||
wfIniGetBool( 'file_uploads' );
76 * Returns true if the user can use this upload module or else a string
77 * identifying the missing permission.
78 * Can be overriden by subclasses.
82 public static function isAllowed( $user ) {
83 foreach ( array( 'upload', 'edit' ) as $permission ) {
84 if ( !$user->isAllowed( $permission ) ) {
91 // Upload handlers. Should probably just be a global.
92 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
95 * Create a form of UploadBase depending on wpSourceType and initializes it
97 * @param $request WebRequest
100 public static function createFromRequest( &$request, $type = null ) {
101 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
107 // Get the upload class
108 $type = ucfirst( $type );
110 // Give hooks the chance to handle this request
112 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
113 if ( is_null( $className ) ) {
114 $className = 'UploadFrom' . $type;
115 wfDebug( __METHOD__
. ": class name: $className\n" );
116 if( !in_array( $type, self
::$uploadHandlers ) ) {
121 // Check whether this upload class is enabled
122 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
126 // Check whether the request is valid
127 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
131 $handler = new $className;
133 $handler->initializeFromRequest( $request );
138 * Check whether a request if valid for this handler
140 public static function isValidRequest( $request ) {
144 public function __construct() {}
147 * Returns the upload type. Should be overridden by child classes
152 public function getSourceType() { return null; }
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 * Finish appending to the Repo file
213 * @param $toAppendPath String: path to the Repo file that will be appended to.
214 * @return Status Status
216 protected function appendFinish( $toAppendPath ) {
217 $repo = RepoGroup
::singleton()->getLocalRepo();
218 $status = $repo->appendFinish( $toAppendPath );
224 * @param $srcPath String: the source path
225 * @return the real path if it was a virtual URL
227 function getRealPath( $srcPath ) {
228 $repo = RepoGroup
::singleton()->getLocalRepo();
229 if ( $repo->isVirtualUrl( $srcPath ) ) {
230 return $repo->resolveVirtualUrl( $srcPath );
236 * Verify whether the upload is sane.
237 * @return mixed self::OK or else an array with error information
239 public function verifyUpload() {
241 * If there was no filename or a zero size given, give up quick.
243 if( $this->isEmptyFile() ) {
244 return array( 'status' => self
::EMPTY_FILE
);
248 * Honor $wgMaxUploadSize
250 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
251 if( $this->mFileSize
> $maxSize ) {
253 'status' => self
::FILE_TOO_LARGE
,
259 * Look at the contents of the file; if we can recognize the
260 * type but it's corrupt or data of the wrong type, we should
261 * probably not accept it.
263 $verification = $this->verifyFile();
264 if( $verification !== true ) {
266 'status' => self
::VERIFICATION_ERROR
,
267 'details' => $verification
272 * Make sure this file can be created
274 $result = $this->validateName();
275 if( $result !== true ) {
280 if( !wfRunHooks( 'UploadVerification',
281 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
282 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
285 return array( 'status' => self
::OK
);
289 * Verify that the name is valid and, if necessary, that we can overwrite
291 * @return mixed true if valid, otherwise and array with 'status'
294 protected function validateName() {
295 $nt = $this->getTitle();
296 if( is_null( $nt ) ) {
297 $result = array( 'status' => $this->mTitleError
);
298 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
299 $result['filtered'] = $this->mFilteredName
;
301 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
302 $result['finalExt'] = $this->mFinalExtension
;
303 if ( count( $this->mBlackListedExtensions
) ) {
304 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
309 $this->mDestName
= $this->getLocalFile()->getName();
315 * Verify the mime type
317 * @param $mime string representing the mime
318 * @return mixed true if the file is verified, an array otherwise
320 protected function verifyMimeType( $mime ) {
321 global $wgVerifyMimeType;
322 if ( $wgVerifyMimeType ) {
323 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
324 global $wgMimeTypeBlacklist;
325 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
326 return array( 'filetype-badmime', $mime );
329 # XXX: Missing extension will be caught by validateName() via getTitle()
330 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
331 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
335 $fp = fopen( $this->mTempPath
, 'rb' );
336 $chunk = fread( $fp, 256 );
339 $magic = MimeMagic
::singleton();
340 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
341 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
342 foreach ( $ieTypes as $ieType ) {
343 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
344 return array( 'filetype-bad-ie-mime', $ieType );
353 * Verifies that it's ok to include the uploaded file
355 * @return mixed true of the file is verified, array otherwise.
357 protected function verifyFile() {
358 global $wgAllowJavaUploads;
359 # get the title, even though we are doing nothing with it, because
360 # we need to populate mFinalExtension
363 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
365 # check mime type, if desired
366 $mime = $this->mFileProps
[ 'file-mime' ];
367 $status = $this->verifyMimeType( $mime );
368 if ( $status !== true ) {
372 # check for htmlish code and javascript
373 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
374 return array( 'uploadscripted' );
376 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
377 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
378 return array( 'uploadscripted' );
382 # Check for Java applets, which if uploaded can bypass cross-site
384 if ( !$wgAllowJavaUploads ) {
385 $this->mJavaDetected
= false;
386 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
387 array( $this, 'zipEntryCallback' ) );
388 if ( !$zipStatus->isOK() ) {
389 $errors = $zipStatus->getErrorsArray();
390 $error = reset( $errors );
391 if ( $error[0] !== 'zip-wrong-format' ) {
395 if ( $this->mJavaDetected
) {
396 return array( 'uploadjava' );
400 # Scan the uploaded file for viruses
401 $virus = $this->detectVirus( $this->mTempPath
);
403 return array( 'uploadvirus', $virus );
406 $handler = MediaHandler
::getHandler( $mime );
408 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
409 if ( !$handlerStatus->isOK() ) {
410 $errors = $handlerStatus->getErrorsArray();
411 return reset( $errors );
415 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
416 if ( $status !== true ) {
420 wfDebug( __METHOD__
. ": all clear; passing.\n" );
425 * Callback for ZipDirectoryReader to detect Java class files.
427 function zipEntryCallback( $entry ) {
428 $names = array( $entry['name'] );
430 // If there is a null character, cut off the name at it, because JDK's
431 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
432 // were constructed which had ".class\0" followed by a string chosen to
433 // make the hash collide with the truncated name, that file could be
434 // returned in response to a request for the .class file.
435 $nullPos = strpos( $entry['name'], "\000" );
436 if ( $nullPos !== false ) {
437 $names[] = substr( $entry['name'], 0, $nullPos );
440 // If there is a trailing slash in the file name, we have to strip it,
441 // because that's what ZIP_GetEntry() does.
442 if ( preg_grep( '!\.class/?$!', $names ) ) {
443 $this->mJavaDetected
= true;
448 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
449 * but that suggests it's checking the user, when it's really checking the title + user combination.
450 * @param $user User object to verify the permissions against
451 * @return mixed An array as returned by getUserPermissionsErrors or true
452 * in case the user has proper permissions.
454 public function verifyPermissions( $user ) {
455 return $this->verifyTitlePermissions( $user );
459 * Check whether the user can edit, upload and create the image. This
460 * checks only against the current title; if it returns errors, it may
461 * very well be that another title will not give errors. Therefore
462 * isAllowed() should be called as well for generic is-user-blocked or
463 * can-user-upload checking.
465 * @param $user User object to verify the permissions against
466 * @return mixed An array as returned by getUserPermissionsErrors or true
467 * in case the user has proper permissions.
469 public function verifyTitlePermissions( $user ) {
471 * If the image is protected, non-sysop users won't be able
472 * to modify it by uploading a new revision.
474 $nt = $this->getTitle();
475 if( is_null( $nt ) ) {
478 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
479 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
480 if ( !$nt->exists() ) {
481 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
483 $permErrorsCreate = array();
485 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
486 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
487 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
491 $overwriteError = $this->checkOverwrite( $user );
492 if ( $overwriteError !== true ) {
493 return array( $overwriteError );
500 * Check for non fatal problems with the file
502 * @return Array of warnings
504 public function checkWarnings() {
509 $localFile = $this->getLocalFile();
510 $filename = $localFile->getName();
513 * Check whether the resulting filename is different from the desired one,
514 * but ignore things like ucfirst() and spaces/underscore things
516 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
517 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
519 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
520 $warnings['badfilename'] = $filename;
523 // Check whether the file extension is on the unwanted list
524 global $wgCheckFileExtensions, $wgFileExtensions;
525 if ( $wgCheckFileExtensions ) {
526 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
527 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
528 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
532 global $wgUploadSizeWarning;
533 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
534 $warnings['large-file'] = $wgUploadSizeWarning;
537 if ( $this->mFileSize
== 0 ) {
538 $warnings['emptyfile'] = true;
541 $exists = self
::getExistsWarning( $localFile );
542 if( $exists !== false ) {
543 $warnings['exists'] = $exists;
546 // Check dupes against existing files
547 $hash = File
::sha1Base36( $this->mTempPath
);
548 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
549 $title = $this->getTitle();
550 // Remove all matches against self
551 foreach ( $dupes as $key => $dupe ) {
552 if( $title->equals( $dupe->getTitle() ) ) {
553 unset( $dupes[$key] );
557 $warnings['duplicate'] = $dupes;
560 // Check dupes against archives
561 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
562 if ( $archivedImage->getID() > 0 ) {
563 $warnings['duplicate-archive'] = $archivedImage->getName();
570 * Really perform the upload. Stores the file in the local repo, watches
571 * if necessary and runs the UploadComplete hook.
575 * @return Status indicating the whether the upload succeeded.
577 public function performUpload( $comment, $pageText, $watch, $user ) {
578 $status = $this->getLocalFile()->upload(
588 if( $status->isGood() ) {
590 $user->addWatch( $this->getLocalFile()->getTitle() );
593 wfRunHooks( 'UploadComplete', array( &$this ) );
600 * Returns the title of the file to be uploaded. Sets mTitleError in case
601 * the name was illegal.
603 * @return Title The title of the file or null in case the name was illegal
605 public function getTitle() {
606 if ( $this->mTitle
!== false ) {
607 return $this->mTitle
;
610 /* Assume that if a user specified File:Something.jpg, this is an error
611 * and that the namespace prefix needs to be stripped of.
613 $title = Title
::newFromText( $this->mDesiredDestName
);
614 if ( $title && $title->getNamespace() == NS_FILE
) {
615 $this->mFilteredName
= $title->getDBkey();
617 $this->mFilteredName
= $this->mDesiredDestName
;
621 * Chop off any directories in the given filename. Then
622 * filter out illegal characters, and try to make a legible name
623 * out of it. We'll strip some silently that Title would die on.
625 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
626 /* Normalize to title form before we do any further processing */
627 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
628 if( is_null( $nt ) ) {
629 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
630 return $this->mTitle
= null;
632 $this->mFilteredName
= $nt->getDBkey();
634 # oi_archive_name is max 255 bytes, which include a timestamp and an
635 # exclamation mark, so restrict file name to 240 bytes. Return
636 # ILLEGAL_FILENAME, just like would have happened for >255 bytes
637 if ( strlen( $this->mFilteredName
) > 240 ) {
638 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
639 return $this->mTitle
= null;
643 * We'll want to blacklist against *any* 'extension', and use
644 * only the final one for the whitelist.
646 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
648 if( count( $ext ) ) {
649 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
651 $this->mFinalExtension
= '';
653 # No extension, try guessing one
654 $magic = MimeMagic
::singleton();
655 $mime = $magic->guessMimeType( $this->mTempPath
);
656 if ( $mime !== 'unknown/unknown' ) {
657 # Get a space separated list of extensions
658 $extList = $magic->getExtensionsForType( $mime );
660 # Set the extension to the canonical extension
661 $this->mFinalExtension
= strtok( $extList, ' ' );
663 # Fix up the other variables
664 $this->mFilteredName
.= ".{$this->mFinalExtension}";
665 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
666 $ext = array( $this->mFinalExtension
);
672 /* Don't allow users to override the blacklist (check file extension) */
673 global $wgCheckFileExtensions, $wgStrictFileExtensions;
674 global $wgFileExtensions, $wgFileBlacklist;
676 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
678 if ( $this->mFinalExtension
== '' ) {
679 $this->mTitleError
= self
::FILETYPE_MISSING
;
680 return $this->mTitle
= null;
681 } elseif ( $blackListedExtensions ||
682 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
683 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
684 $this->mBlackListedExtensions
= $blackListedExtensions;
685 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
686 return $this->mTitle
= null;
689 // Windows may be broken with special characters, see bug XXX
690 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
691 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
692 return $this->mTitle
= null;
695 # If there was more than one "extension", reassemble the base
696 # filename to prevent bogus complaints about length
697 if( count( $ext ) > 1 ) {
698 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
699 $partname .= '.' . $ext[$i];
703 if( strlen( $partname ) < 1 ) {
704 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
705 return $this->mTitle
= null;
708 return $this->mTitle
= $nt;
712 * Return the local file and initializes if necessary.
716 public function getLocalFile() {
717 if( is_null( $this->mLocalFile
) ) {
718 $nt = $this->getTitle();
719 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
721 return $this->mLocalFile
;
725 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
726 * called outside that context.
728 * Stash a file in a temporary directory for later processing
729 * after the user has confirmed it.
731 * If the user doesn't explicitly cancel or accept, these files
732 * can accumulate in the temp directory.
734 * @param $saveName String: the destination filename
735 * @param $tempSrc String: the source temporary file to save
736 * @return String: full path the stashed file, or false on failure
738 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
739 $repo = RepoGroup
::singleton()->getLocalRepo();
740 $status = $repo->storeTemp( $saveName, $tempSrc );
745 * If the user does not supply all necessary information in the first upload form submission (either by accident or
746 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
748 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
750 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
751 * API request to find this stashed file again.
753 * @return UploadStashFile stashed file
755 public function stashFile() {
756 // was stashSessionFile
757 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
759 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
760 $this->mLocalFile
= $file;
765 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
767 * @return String: file key
769 public function stashFileGetKey() {
770 return $this->stashFile()->getFileKey();
774 * alias for stashFileGetKey, for backwards compatibility
776 * @return String: file key
778 public function stashSession() {
779 return $this->stashFileGetKey();
783 * If we've modified the upload file we need to manually remove it
784 * on exit to clean up.
786 public function cleanupTempFile() {
787 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
788 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
789 unlink( $this->mTempPath
);
793 public function getTempPath() {
794 return $this->mTempPath
;
798 * Split a file into a base name and all dot-delimited 'extensions'
799 * on the end. Some web server configurations will fall back to
800 * earlier pseudo-'extensions' to determine type and execute
801 * scripts, so the blacklist needs to check them all.
805 public static function splitExtensions( $filename ) {
806 $bits = explode( '.', $filename );
807 $basename = array_shift( $bits );
808 return array( $basename, $bits );
812 * Perform case-insensitive match against a list of file extensions.
813 * Returns true if the extension is in the list.
819 public static function checkFileExtension( $ext, $list ) {
820 return in_array( strtolower( $ext ), $list );
824 * Perform case-insensitive match against a list of file extensions.
825 * Returns an array of matching extensions.
831 public static function checkFileExtensionList( $ext, $list ) {
832 return array_intersect( array_map( 'strtolower', $ext ), $list );
836 * Checks if the mime type of the uploaded file matches the file extension.
838 * @param $mime String: the mime type of the uploaded file
839 * @param $extension String: the filename extension that the file is to be served with
842 public static function verifyExtension( $mime, $extension ) {
843 $magic = MimeMagic
::singleton();
845 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
846 if ( !$magic->isRecognizableExtension( $extension ) ) {
847 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
848 "unrecognized extension '$extension', can't verify\n" );
851 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
852 "recognized extension '$extension', so probably invalid file\n" );
856 $match = $magic->isMatchingExtension( $extension, $mime );
858 if ( $match === null ) {
859 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
861 } elseif( $match === true ) {
862 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
864 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
868 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
874 * Heuristic for detecting files that *could* contain JavaScript instructions or
875 * things that may look like HTML to a browser and are thus
876 * potentially harmful. The present implementation will produce false
877 * positives in some situations.
879 * @param $file String: pathname to the temporary upload file
880 * @param $mime String: the mime type of the file
881 * @param $extension String: the extension of the file
882 * @return Boolean: true if the file contains something looking like embedded scripts
884 public static function detectScript( $file, $mime, $extension ) {
885 global $wgAllowTitlesInSVG;
887 # ugly hack: for text files, always look at the entire file.
888 # For binary field, just check the first K.
890 if( strpos( $mime,'text/' ) === 0 ) {
891 $chunk = file_get_contents( $file );
893 $fp = fopen( $file, 'rb' );
894 $chunk = fread( $fp, 1024 );
898 $chunk = strtolower( $chunk );
904 # decode from UTF-16 if needed (could be used for obfuscation).
905 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
907 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
914 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
917 $chunk = trim( $chunk );
919 # @todo FIXME: Convert from UTF-16 if necessarry!
920 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
922 # check for HTML doctype
923 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
928 * Internet Explorer for Windows performs some really stupid file type
929 * autodetection which can cause it to interpret valid image files as HTML
930 * and potentially execute JavaScript, creating a cross-site scripting
933 * Apple's Safari browser also performs some unsafe file type autodetection
934 * which can cause legitimate files to be interpreted as HTML if the
935 * web server is not correctly configured to send the right content-type
936 * (or if you're really uploading plain text and octet streams!)
938 * Returns true if IE is likely to mistake the given file for HTML.
939 * Also returns true if Safari would mistake the given file for HTML
940 * when served with a generic content-type.
946 '<html', #also in safari
949 '<script', #also in safari
953 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
957 foreach( $tags as $tag ) {
958 if( false !== strpos( $chunk, $tag ) ) {
959 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
965 * look for JavaScript
968 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
969 $chunk = Sanitizer
::decodeCharReferences( $chunk );
971 # look for script-types
972 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
973 wfDebug( __METHOD__
. ": found script types\n" );
977 # look for html-style script-urls
978 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
979 wfDebug( __METHOD__
. ": found html-style script urls\n" );
983 # look for css-style script-urls
984 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
985 wfDebug( __METHOD__
. ": found css-style script urls\n" );
989 wfDebug( __METHOD__
. ": no scripts found\n" );
993 protected function detectScriptInSvg( $filename ) {
994 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
995 return $check->filterMatch
;
999 * @todo Replace this with a whitelist filter!
1001 public function checkSvgScriptCallback( $element, $attribs ) {
1002 $stripped = $this->stripXmlNamespace( $element );
1004 if( $stripped == 'script' ) {
1005 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1009 foreach( $attribs as $attrib => $value ) {
1010 $stripped = $this->stripXmlNamespace( $attrib );
1011 if( substr( $stripped, 0, 2 ) == 'on' ) {
1012 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1015 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1016 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1022 private function stripXmlNamespace( $name ) {
1023 // 'http://www.w3.org/2000/svg:script' -> 'script'
1024 $parts = explode( ':', strtolower( $name ) );
1025 return array_pop( $parts );
1029 * Generic wrapper function for a virus scanner program.
1030 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1031 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1033 * @param $file String: pathname to the temporary upload file
1034 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1035 * or a string containing feedback from the virus scanner if a virus was found.
1036 * If textual feedback is missing but a virus was found, this function returns true.
1038 public static function detectVirus( $file ) {
1039 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1041 if ( !$wgAntivirus ) {
1042 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1046 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1047 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1048 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1049 array( 'virus-badscanner', $wgAntivirus ) );
1050 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1053 # look up scanner configuration
1054 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1055 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1056 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1057 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1059 if ( strpos( $command, "%f" ) === false ) {
1060 # simple pattern: append file to scan
1061 $command .= " " . wfEscapeShellArg( $file );
1063 # complex pattern: replace "%f" with file to scan
1064 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1067 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1069 # execute virus scanner
1072 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1073 # that does not seem to be worth the pain.
1074 # Ask me (Duesentrieb) about it if it's ever needed.
1075 $output = wfShellExec( "$command 2>&1", $exitCode );
1077 # map exit code to AV_xxx constants.
1078 $mappedCode = $exitCode;
1079 if ( $exitCodeMap ) {
1080 if ( isset( $exitCodeMap[$exitCode] ) ) {
1081 $mappedCode = $exitCodeMap[$exitCode];
1082 } elseif ( isset( $exitCodeMap["*"] ) ) {
1083 $mappedCode = $exitCodeMap["*"];
1087 if ( $mappedCode === AV_SCAN_FAILED
) {
1088 # scan failed (code was mapped to false by $exitCodeMap)
1089 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1091 if ( $wgAntivirusRequired ) {
1092 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1096 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1097 # scan failed because filetype is unknown (probably imune)
1098 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1100 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1102 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1105 $output = trim( $output );
1108 $output = true; #if there's no output, return true
1109 } elseif ( $msgPattern ) {
1111 if ( preg_match( $msgPattern, $output, $groups ) ) {
1113 $output = $groups[1];
1118 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1124 * Check if there's an overwrite conflict and, if so, if restrictions
1125 * forbid this user from performing the upload.
1129 * @return mixed true on success, array on failure
1131 private function checkOverwrite( $user ) {
1132 // First check whether the local file can be overwritten
1133 $file = $this->getLocalFile();
1134 if( $file->exists() ) {
1135 if( !self
::userCanReUpload( $user, $file ) ) {
1136 return array( 'fileexists-forbidden', $file->getName() );
1142 /* Check shared conflicts: if the local file does not exist, but
1143 * wfFindFile finds a file, it exists in a shared repository.
1145 $file = wfFindFile( $this->getTitle() );
1146 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1147 return array( 'fileexists-shared-forbidden', $file->getName() );
1154 * Check if a user is the last uploader
1156 * @param $user User object
1157 * @param $img String: image name
1160 public static function userCanReUpload( User
$user, $img ) {
1161 if( $user->isAllowed( 'reupload' ) ) {
1162 return true; // non-conditional
1164 if( !$user->isAllowed( 'reupload-own' ) ) {
1167 if( is_string( $img ) ) {
1168 $img = wfLocalFile( $img );
1170 if ( !( $img instanceof LocalFile
) ) {
1174 return $user->getId() == $img->getUser( 'id' );
1178 * Helper function that does various existence checks for a file.
1179 * The following checks are performed:
1181 * - Article with the same name as the file exists
1182 * - File exists with normalized extension
1183 * - The file looks like a thumbnail and the original exists
1185 * @param $file File The File object to check
1186 * @return mixed False if the file does not exists, else an array
1188 public static function getExistsWarning( $file ) {
1189 if( $file->exists() ) {
1190 return array( 'warning' => 'exists', 'file' => $file );
1193 if( $file->getTitle()->getArticleID() ) {
1194 return array( 'warning' => 'page-exists', 'file' => $file );
1197 if ( $file->wasDeleted() && !$file->exists() ) {
1198 return array( 'warning' => 'was-deleted', 'file' => $file );
1201 if( strpos( $file->getName(), '.' ) == false ) {
1202 $partname = $file->getName();
1205 $n = strrpos( $file->getName(), '.' );
1206 $extension = substr( $file->getName(), $n +
1 );
1207 $partname = substr( $file->getName(), 0, $n );
1209 $normalizedExtension = File
::normalizeExtension( $extension );
1211 if ( $normalizedExtension != $extension ) {
1212 // We're not using the normalized form of the extension.
1213 // Normal form is lowercase, using most common of alternate
1214 // extensions (eg 'jpg' rather than 'JPEG').
1216 // Check for another file using the normalized form...
1217 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1218 $file_lc = wfLocalFile( $nt_lc );
1220 if( $file_lc->exists() ) {
1222 'warning' => 'exists-normalized',
1224 'normalizedFile' => $file_lc
1229 if ( self
::isThumbName( $file->getName() ) ) {
1230 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1231 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1232 $file_thb = wfLocalFile( $nt_thb );
1233 if( $file_thb->exists() ) {
1235 'warning' => 'thumb',
1237 'thumbFile' => $file_thb
1240 // File does not exist, but we just don't like the name
1242 'warning' => 'thumb-name',
1244 'thumbFile' => $file_thb
1250 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1251 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1253 'warning' => 'bad-prefix',
1264 * Helper function that checks whether the filename looks like a thumbnail
1266 public static function isThumbName( $filename ) {
1267 $n = strrpos( $filename, '.' );
1268 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1270 substr( $partname , 3, 3 ) == 'px-' ||
1271 substr( $partname , 2, 3 ) == 'px-'
1273 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1277 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1279 * @return array list of prefixes
1281 public static function getFilenamePrefixBlacklist() {
1282 $blacklist = array();
1283 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1284 if( !$message->isDisabled() ) {
1285 $lines = explode( "\n", $message->plain() );
1286 foreach( $lines as $line ) {
1287 // Remove comment lines
1288 $comment = substr( trim( $line ), 0, 1 );
1289 if ( $comment == '#' ||
$comment == '' ) {
1292 // Remove additional comments after a prefix
1293 $comment = strpos( $line, '#' );
1294 if ( $comment > 0 ) {
1295 $line = substr( $line, 0, $comment-1 );
1297 $blacklist[] = trim( $line );
1304 * Gets image info about the file just uploaded.
1306 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1307 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1308 * with the appropriate format, presumably.
1310 * @param $result ApiResult:
1311 * @return Array: image info
1313 public function getImageInfo( $result ) {
1314 $file = $this->getLocalFile();
1315 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1316 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1317 if ( $file instanceof UploadStashFile
) {
1318 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1319 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1321 $imParam = ApiQueryImageInfo
::getPropertyNames();
1322 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1328 public function convertVerifyErrorToStatus( $error ) {
1329 $code = $error['status'];
1330 unset( $code['status'] );
1331 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1334 public static function getMaxUploadSize( $forType = null ) {
1335 global $wgMaxUploadSize;
1337 if ( is_array( $wgMaxUploadSize ) ) {
1338 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1339 return $wgMaxUploadSize[$forType];
1341 return $wgMaxUploadSize['*'];
1344 return intval( $wgMaxUploadSize );