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;
40 const FILENAME_TOO_LONG
= 14;
42 public function getVerificationErrorCode( $error ) {
43 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
44 self
::FILE_TOO_LARGE
=> 'file-too-large',
45 self
::FILETYPE_MISSING
=> 'filetype-missing',
46 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
47 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
48 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
49 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
50 self
::VERIFICATION_ERROR
=> 'verification-error',
51 self
::HOOK_ABORTED
=> 'hookaborted',
52 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
53 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
55 if( isset( $code_to_status[$error] ) ) {
56 return $code_to_status[$error];
59 return 'unknown-error';
63 * Returns true if uploads are enabled.
64 * Can be override by subclasses.
66 public static function isEnabled() {
67 global $wgEnableUploads;
69 if ( !$wgEnableUploads ) {
73 # Check php's file_uploads setting
74 return wfIsHipHop() ||
wfIniGetBool( 'file_uploads' );
78 * Returns true if the user can use this upload module or else a string
79 * identifying the missing permission.
80 * Can be overriden by subclasses.
84 public static function isAllowed( $user ) {
85 foreach ( array( 'upload', 'edit' ) as $permission ) {
86 if ( !$user->isAllowed( $permission ) ) {
93 // Upload handlers. Should probably just be a global.
94 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
97 * Create a form of UploadBase depending on wpSourceType and initializes it
99 * @param $request WebRequest
102 public static function createFromRequest( &$request, $type = null ) {
103 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
109 // Get the upload class
110 $type = ucfirst( $type );
112 // Give hooks the chance to handle this request
114 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
115 if ( is_null( $className ) ) {
116 $className = 'UploadFrom' . $type;
117 wfDebug( __METHOD__
. ": class name: $className\n" );
118 if( !in_array( $type, self
::$uploadHandlers ) ) {
123 // Check whether this upload class is enabled
124 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
128 // Check whether the request is valid
129 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
133 $handler = new $className;
135 $handler->initializeFromRequest( $request );
140 * Check whether a request if valid for this handler
142 public static function isValidRequest( $request ) {
146 public function __construct() {}
149 * Returns the upload type. Should be overridden by child classes
154 public function getSourceType() { return null; }
157 * Initialize the path information
158 * @param $name string the desired destination name
159 * @param $tempPath string the temporary path
160 * @param $fileSize int the file size
161 * @param $removeTempFile bool (false) remove the temporary file?
164 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
165 $this->mDesiredDestName
= $name;
166 $this->mTempPath
= $tempPath;
167 $this->mFileSize
= $fileSize;
168 $this->mRemoveTempFile
= $removeTempFile;
172 * Initialize from a WebRequest. Override this in a subclass.
174 public abstract function initializeFromRequest( &$request );
177 * Fetch the file. Usually a no-op
179 public function fetchFile() {
180 return Status
::newGood();
184 * Return true if the file is empty
187 public function isEmptyFile() {
188 return empty( $this->mFileSize
);
192 * Return the file size
195 public function getFileSize() {
196 return $this->mFileSize
;
200 * Append a file to the Repo file
202 * @param $srcPath String: path to source file
203 * @param $toAppendPath String: path to the Repo file that will be appended to.
204 * @return Status Status
206 protected function appendToUploadFile( $srcPath, $toAppendPath ) {
207 $repo = RepoGroup
::singleton()->getLocalRepo();
208 $status = $repo->append( $srcPath, $toAppendPath );
213 * Finish appending to the Repo file
215 * @param $toAppendPath String: path to the Repo file that will be appended to.
216 * @return Status Status
218 protected function appendFinish( $toAppendPath ) {
219 $repo = RepoGroup
::singleton()->getLocalRepo();
220 $status = $repo->appendFinish( $toAppendPath );
226 * @param $srcPath String: the source path
227 * @return the real path if it was a virtual URL
229 function getRealPath( $srcPath ) {
230 $repo = RepoGroup
::singleton()->getLocalRepo();
231 if ( $repo->isVirtualUrl( $srcPath ) ) {
232 return $repo->resolveVirtualUrl( $srcPath );
238 * Verify whether the upload is sane.
239 * @return mixed self::OK or else an array with error information
241 public function verifyUpload() {
243 * If there was no filename or a zero size given, give up quick.
245 if( $this->isEmptyFile() ) {
246 return array( 'status' => self
::EMPTY_FILE
);
250 * Honor $wgMaxUploadSize
252 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
253 if( $this->mFileSize
> $maxSize ) {
255 'status' => self
::FILE_TOO_LARGE
,
261 * Look at the contents of the file; if we can recognize the
262 * type but it's corrupt or data of the wrong type, we should
263 * probably not accept it.
265 $verification = $this->verifyFile();
266 if( $verification !== true ) {
268 'status' => self
::VERIFICATION_ERROR
,
269 'details' => $verification
274 * Make sure this file can be created
276 $result = $this->validateName();
277 if( $result !== true ) {
282 if( !wfRunHooks( 'UploadVerification',
283 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
284 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
287 return array( 'status' => self
::OK
);
291 * Verify that the name is valid and, if necessary, that we can overwrite
293 * @return mixed true if valid, otherwise and array with 'status'
296 protected function validateName() {
297 $nt = $this->getTitle();
298 if( is_null( $nt ) ) {
299 $result = array( 'status' => $this->mTitleError
);
300 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
301 $result['filtered'] = $this->mFilteredName
;
303 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
304 $result['finalExt'] = $this->mFinalExtension
;
305 if ( count( $this->mBlackListedExtensions
) ) {
306 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
311 $this->mDestName
= $this->getLocalFile()->getName();
317 * Verify the mime type
319 * @param $mime string representing the mime
320 * @return mixed true if the file is verified, an array otherwise
322 protected function verifyMimeType( $mime ) {
323 global $wgVerifyMimeType;
324 if ( $wgVerifyMimeType ) {
325 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
326 global $wgMimeTypeBlacklist;
327 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
328 return array( 'filetype-badmime', $mime );
331 # XXX: Missing extension will be caught by validateName() via getTitle()
332 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
333 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
337 $fp = fopen( $this->mTempPath
, 'rb' );
338 $chunk = fread( $fp, 256 );
341 $magic = MimeMagic
::singleton();
342 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
343 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
344 foreach ( $ieTypes as $ieType ) {
345 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
346 return array( 'filetype-bad-ie-mime', $ieType );
355 * Verifies that it's ok to include the uploaded file
357 * @return mixed true of the file is verified, array otherwise.
359 protected function verifyFile() {
360 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
361 # get the title, even though we are doing nothing with it, because
362 # we need to populate mFinalExtension
365 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
367 # check mime type, if desired
368 $mime = $this->mFileProps
[ 'file-mime' ];
369 $status = $this->verifyMimeType( $mime );
370 if ( $status !== true ) {
374 # check for htmlish code and javascript
375 if ( !$wgDisableUploadScriptChecks ) {
376 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
377 return array( 'uploadscripted' );
379 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
380 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
381 return array( 'uploadscripted' );
386 # Check for Java applets, which if uploaded can bypass cross-site
388 if ( !$wgAllowJavaUploads ) {
389 $this->mJavaDetected
= false;
390 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
391 array( $this, 'zipEntryCallback' ) );
392 if ( !$zipStatus->isOK() ) {
393 $errors = $zipStatus->getErrorsArray();
394 $error = reset( $errors );
395 if ( $error[0] !== 'zip-wrong-format' ) {
399 if ( $this->mJavaDetected
) {
400 return array( 'uploadjava' );
404 # Scan the uploaded file for viruses
405 $virus = $this->detectVirus( $this->mTempPath
);
407 return array( 'uploadvirus', $virus );
410 $handler = MediaHandler
::getHandler( $mime );
412 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
413 if ( !$handlerStatus->isOK() ) {
414 $errors = $handlerStatus->getErrorsArray();
415 return reset( $errors );
419 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
420 if ( $status !== true ) {
424 wfDebug( __METHOD__
. ": all clear; passing.\n" );
429 * Callback for ZipDirectoryReader to detect Java class files.
431 function zipEntryCallback( $entry ) {
432 $names = array( $entry['name'] );
434 // If there is a null character, cut off the name at it, because JDK's
435 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
436 // were constructed which had ".class\0" followed by a string chosen to
437 // make the hash collide with the truncated name, that file could be
438 // returned in response to a request for the .class file.
439 $nullPos = strpos( $entry['name'], "\000" );
440 if ( $nullPos !== false ) {
441 $names[] = substr( $entry['name'], 0, $nullPos );
444 // If there is a trailing slash in the file name, we have to strip it,
445 // because that's what ZIP_GetEntry() does.
446 if ( preg_grep( '!\.class/?$!', $names ) ) {
447 $this->mJavaDetected
= true;
452 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
453 * but that suggests it's checking the user, when it's really checking the title + user combination.
454 * @param $user User object to verify the permissions against
455 * @return mixed An array as returned by getUserPermissionsErrors or true
456 * in case the user has proper permissions.
458 public function verifyPermissions( $user ) {
459 return $this->verifyTitlePermissions( $user );
463 * Check whether the user can edit, upload and create the image. This
464 * checks only against the current title; if it returns errors, it may
465 * very well be that another title will not give errors. Therefore
466 * isAllowed() should be called as well for generic is-user-blocked or
467 * can-user-upload checking.
469 * @param $user User object to verify the permissions against
470 * @return mixed An array as returned by getUserPermissionsErrors or true
471 * in case the user has proper permissions.
473 public function verifyTitlePermissions( $user ) {
475 * If the image is protected, non-sysop users won't be able
476 * to modify it by uploading a new revision.
478 $nt = $this->getTitle();
479 if( is_null( $nt ) ) {
482 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
483 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
484 if ( !$nt->exists() ) {
485 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
487 $permErrorsCreate = array();
489 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
490 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
491 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
495 $overwriteError = $this->checkOverwrite( $user );
496 if ( $overwriteError !== true ) {
497 return array( $overwriteError );
504 * Check for non fatal problems with the file
506 * @return Array of warnings
508 public function checkWarnings() {
513 $localFile = $this->getLocalFile();
514 $filename = $localFile->getName();
517 * Check whether the resulting filename is different from the desired one,
518 * but ignore things like ucfirst() and spaces/underscore things
520 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
521 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
523 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
524 $warnings['badfilename'] = $filename;
527 // Check whether the file extension is on the unwanted list
528 global $wgCheckFileExtensions, $wgFileExtensions;
529 if ( $wgCheckFileExtensions ) {
530 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
531 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
532 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
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 && $title->getNamespace() == NS_FILE
) {
619 $this->mFilteredName
= $title->getDBkey();
621 $this->mFilteredName
= $this->mDesiredDestName
;
624 # oi_archive_name is max 255 bytes, which include a timestamp and an
625 # exclamation mark, so restrict file name to 240 bytes.
626 if ( strlen( $this->mFilteredName
) > 240 ) {
627 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
628 return $this->mTitle
= null;
632 * Chop off any directories in the given filename. Then
633 * filter out illegal characters, and try to make a legible name
634 * out of it. We'll strip some silently that Title would die on.
636 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
637 /* Normalize to title form before we do any further processing */
638 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
639 if( is_null( $nt ) ) {
640 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
641 return $this->mTitle
= null;
643 $this->mFilteredName
= $nt->getDBkey();
648 * We'll want to blacklist against *any* 'extension', and use
649 * only the final one for the whitelist.
651 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
653 if( count( $ext ) ) {
654 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
656 $this->mFinalExtension
= '';
658 # No extension, try guessing one
659 $magic = MimeMagic
::singleton();
660 $mime = $magic->guessMimeType( $this->mTempPath
);
661 if ( $mime !== 'unknown/unknown' ) {
662 # Get a space separated list of extensions
663 $extList = $magic->getExtensionsForType( $mime );
665 # Set the extension to the canonical extension
666 $this->mFinalExtension
= strtok( $extList, ' ' );
668 # Fix up the other variables
669 $this->mFilteredName
.= ".{$this->mFinalExtension}";
670 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
671 $ext = array( $this->mFinalExtension
);
677 /* Don't allow users to override the blacklist (check file extension) */
678 global $wgCheckFileExtensions, $wgStrictFileExtensions;
679 global $wgFileExtensions, $wgFileBlacklist;
681 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
683 if ( $this->mFinalExtension
== '' ) {
684 $this->mTitleError
= self
::FILETYPE_MISSING
;
685 return $this->mTitle
= null;
686 } elseif ( $blackListedExtensions ||
687 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
688 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
689 $this->mBlackListedExtensions
= $blackListedExtensions;
690 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
691 return $this->mTitle
= null;
694 // Windows may be broken with special characters, see bug XXX
695 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
696 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
697 return $this->mTitle
= null;
700 # If there was more than one "extension", reassemble the base
701 # filename to prevent bogus complaints about length
702 if( count( $ext ) > 1 ) {
703 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
704 $partname .= '.' . $ext[$i];
708 if( strlen( $partname ) < 1 ) {
709 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
710 return $this->mTitle
= null;
713 return $this->mTitle
= $nt;
717 * Return the local file and initializes if necessary.
721 public function getLocalFile() {
722 if( is_null( $this->mLocalFile
) ) {
723 $nt = $this->getTitle();
724 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
726 return $this->mLocalFile
;
730 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
731 * called outside that context.
733 * Stash a file in a temporary directory for later processing
734 * after the user has confirmed it.
736 * If the user doesn't explicitly cancel or accept, these files
737 * can accumulate in the temp directory.
739 * @param $saveName String: the destination filename
740 * @param $tempSrc String: the source temporary file to save
741 * @return String: full path the stashed file, or false on failure
743 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
744 $repo = RepoGroup
::singleton()->getLocalRepo();
745 $status = $repo->storeTemp( $saveName, $tempSrc );
750 * If the user does not supply all necessary information in the first upload form submission (either by accident or
751 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
753 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
755 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
756 * API request to find this stashed file again.
758 * @return UploadStashFile stashed file
760 public function stashFile() {
761 // was stashSessionFile
762 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
764 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
765 $this->mLocalFile
= $file;
770 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
772 * @return String: file key
774 public function stashFileGetKey() {
775 return $this->stashFile()->getFileKey();
779 * alias for stashFileGetKey, for backwards compatibility
781 * @return String: file key
783 public function stashSession() {
784 return $this->stashFileGetKey();
788 * If we've modified the upload file we need to manually remove it
789 * on exit to clean up.
791 public function cleanupTempFile() {
792 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
793 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
794 unlink( $this->mTempPath
);
798 public function getTempPath() {
799 return $this->mTempPath
;
803 * Split a file into a base name and all dot-delimited 'extensions'
804 * on the end. Some web server configurations will fall back to
805 * earlier pseudo-'extensions' to determine type and execute
806 * scripts, so the blacklist needs to check them all.
810 public static function splitExtensions( $filename ) {
811 $bits = explode( '.', $filename );
812 $basename = array_shift( $bits );
813 return array( $basename, $bits );
817 * Perform case-insensitive match against a list of file extensions.
818 * Returns true if the extension is in the list.
824 public static function checkFileExtension( $ext, $list ) {
825 return in_array( strtolower( $ext ), $list );
829 * Perform case-insensitive match against a list of file extensions.
830 * Returns an array of matching extensions.
836 public static function checkFileExtensionList( $ext, $list ) {
837 return array_intersect( array_map( 'strtolower', $ext ), $list );
841 * Checks if the mime type of the uploaded file matches the file extension.
843 * @param $mime String: the mime type of the uploaded file
844 * @param $extension String: the filename extension that the file is to be served with
847 public static function verifyExtension( $mime, $extension ) {
848 $magic = MimeMagic
::singleton();
850 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
851 if ( !$magic->isRecognizableExtension( $extension ) ) {
852 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
853 "unrecognized extension '$extension', can't verify\n" );
856 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
857 "recognized extension '$extension', so probably invalid file\n" );
861 $match = $magic->isMatchingExtension( $extension, $mime );
863 if ( $match === null ) {
864 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
866 } elseif( $match === true ) {
867 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
869 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
873 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
879 * Heuristic for detecting files that *could* contain JavaScript instructions or
880 * things that may look like HTML to a browser and are thus
881 * potentially harmful. The present implementation will produce false
882 * positives in some situations.
884 * @param $file String: pathname to the temporary upload file
885 * @param $mime String: the mime type of the file
886 * @param $extension String: the extension of the file
887 * @return Boolean: true if the file contains something looking like embedded scripts
889 public static function detectScript( $file, $mime, $extension ) {
890 global $wgAllowTitlesInSVG;
892 # ugly hack: for text files, always look at the entire file.
893 # For binary field, just check the first K.
895 if( strpos( $mime,'text/' ) === 0 ) {
896 $chunk = file_get_contents( $file );
898 $fp = fopen( $file, 'rb' );
899 $chunk = fread( $fp, 1024 );
903 $chunk = strtolower( $chunk );
909 # decode from UTF-16 if needed (could be used for obfuscation).
910 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
912 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
919 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
922 $chunk = trim( $chunk );
924 # @todo FIXME: Convert from UTF-16 if necessarry!
925 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
927 # check for HTML doctype
928 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
933 * Internet Explorer for Windows performs some really stupid file type
934 * autodetection which can cause it to interpret valid image files as HTML
935 * and potentially execute JavaScript, creating a cross-site scripting
938 * Apple's Safari browser also performs some unsafe file type autodetection
939 * which can cause legitimate files to be interpreted as HTML if the
940 * web server is not correctly configured to send the right content-type
941 * (or if you're really uploading plain text and octet streams!)
943 * Returns true if IE is likely to mistake the given file for HTML.
944 * Also returns true if Safari would mistake the given file for HTML
945 * when served with a generic content-type.
951 '<html', #also in safari
954 '<script', #also in safari
958 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
962 foreach( $tags as $tag ) {
963 if( false !== strpos( $chunk, $tag ) ) {
964 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
970 * look for JavaScript
973 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
974 $chunk = Sanitizer
::decodeCharReferences( $chunk );
976 # look for script-types
977 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
978 wfDebug( __METHOD__
. ": found script types\n" );
982 # look for html-style script-urls
983 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
984 wfDebug( __METHOD__
. ": found html-style script urls\n" );
988 # look for css-style script-urls
989 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
990 wfDebug( __METHOD__
. ": found css-style script urls\n" );
994 wfDebug( __METHOD__
. ": no scripts found\n" );
998 protected function detectScriptInSvg( $filename ) {
999 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1000 return $check->filterMatch
;
1004 * @todo Replace this with a whitelist filter!
1006 public function checkSvgScriptCallback( $element, $attribs ) {
1007 $stripped = $this->stripXmlNamespace( $element );
1009 if( $stripped == 'script' ) {
1010 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1014 foreach( $attribs as $attrib => $value ) {
1015 $stripped = $this->stripXmlNamespace( $attrib );
1016 if( substr( $stripped, 0, 2 ) == 'on' ) {
1017 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1020 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1021 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1027 private function stripXmlNamespace( $name ) {
1028 // 'http://www.w3.org/2000/svg:script' -> 'script'
1029 $parts = explode( ':', strtolower( $name ) );
1030 return array_pop( $parts );
1034 * Generic wrapper function for a virus scanner program.
1035 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1036 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1038 * @param $file String: pathname to the temporary upload file
1039 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1040 * or a string containing feedback from the virus scanner if a virus was found.
1041 * If textual feedback is missing but a virus was found, this function returns true.
1043 public static function detectVirus( $file ) {
1044 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1046 if ( !$wgAntivirus ) {
1047 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1051 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1052 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1053 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1054 array( 'virus-badscanner', $wgAntivirus ) );
1055 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1058 # look up scanner configuration
1059 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1060 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1061 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1062 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1064 if ( strpos( $command, "%f" ) === false ) {
1065 # simple pattern: append file to scan
1066 $command .= " " . wfEscapeShellArg( $file );
1068 # complex pattern: replace "%f" with file to scan
1069 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1072 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1074 # execute virus scanner
1077 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1078 # that does not seem to be worth the pain.
1079 # Ask me (Duesentrieb) about it if it's ever needed.
1080 $output = wfShellExec( "$command 2>&1", $exitCode );
1082 # map exit code to AV_xxx constants.
1083 $mappedCode = $exitCode;
1084 if ( $exitCodeMap ) {
1085 if ( isset( $exitCodeMap[$exitCode] ) ) {
1086 $mappedCode = $exitCodeMap[$exitCode];
1087 } elseif ( isset( $exitCodeMap["*"] ) ) {
1088 $mappedCode = $exitCodeMap["*"];
1092 if ( $mappedCode === AV_SCAN_FAILED
) {
1093 # scan failed (code was mapped to false by $exitCodeMap)
1094 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1096 if ( $wgAntivirusRequired ) {
1097 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1101 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1102 # scan failed because filetype is unknown (probably imune)
1103 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1105 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1107 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1110 $output = trim( $output );
1113 $output = true; #if there's no output, return true
1114 } elseif ( $msgPattern ) {
1116 if ( preg_match( $msgPattern, $output, $groups ) ) {
1118 $output = $groups[1];
1123 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1129 * Check if there's an overwrite conflict and, if so, if restrictions
1130 * forbid this user from performing the upload.
1134 * @return mixed true on success, array on failure
1136 private function checkOverwrite( $user ) {
1137 // First check whether the local file can be overwritten
1138 $file = $this->getLocalFile();
1139 if( $file->exists() ) {
1140 if( !self
::userCanReUpload( $user, $file ) ) {
1141 return array( 'fileexists-forbidden', $file->getName() );
1147 /* Check shared conflicts: if the local file does not exist, but
1148 * wfFindFile finds a file, it exists in a shared repository.
1150 $file = wfFindFile( $this->getTitle() );
1151 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1152 return array( 'fileexists-shared-forbidden', $file->getName() );
1159 * Check if a user is the last uploader
1161 * @param $user User object
1162 * @param $img String: image name
1165 public static function userCanReUpload( User
$user, $img ) {
1166 if( $user->isAllowed( 'reupload' ) ) {
1167 return true; // non-conditional
1169 if( !$user->isAllowed( 'reupload-own' ) ) {
1172 if( is_string( $img ) ) {
1173 $img = wfLocalFile( $img );
1175 if ( !( $img instanceof LocalFile
) ) {
1179 return $user->getId() == $img->getUser( 'id' );
1183 * Helper function that does various existence checks for a file.
1184 * The following checks are performed:
1186 * - Article with the same name as the file exists
1187 * - File exists with normalized extension
1188 * - The file looks like a thumbnail and the original exists
1190 * @param $file File The File object to check
1191 * @return mixed False if the file does not exists, else an array
1193 public static function getExistsWarning( $file ) {
1194 if( $file->exists() ) {
1195 return array( 'warning' => 'exists', 'file' => $file );
1198 if( $file->getTitle()->getArticleID() ) {
1199 return array( 'warning' => 'page-exists', 'file' => $file );
1202 if ( $file->wasDeleted() && !$file->exists() ) {
1203 return array( 'warning' => 'was-deleted', 'file' => $file );
1206 if( strpos( $file->getName(), '.' ) == false ) {
1207 $partname = $file->getName();
1210 $n = strrpos( $file->getName(), '.' );
1211 $extension = substr( $file->getName(), $n +
1 );
1212 $partname = substr( $file->getName(), 0, $n );
1214 $normalizedExtension = File
::normalizeExtension( $extension );
1216 if ( $normalizedExtension != $extension ) {
1217 // We're not using the normalized form of the extension.
1218 // Normal form is lowercase, using most common of alternate
1219 // extensions (eg 'jpg' rather than 'JPEG').
1221 // Check for another file using the normalized form...
1222 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1223 $file_lc = wfLocalFile( $nt_lc );
1225 if( $file_lc->exists() ) {
1227 'warning' => 'exists-normalized',
1229 'normalizedFile' => $file_lc
1234 if ( self
::isThumbName( $file->getName() ) ) {
1235 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1236 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1237 $file_thb = wfLocalFile( $nt_thb );
1238 if( $file_thb->exists() ) {
1240 'warning' => 'thumb',
1242 'thumbFile' => $file_thb
1245 // File does not exist, but we just don't like the name
1247 'warning' => 'thumb-name',
1249 'thumbFile' => $file_thb
1255 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1256 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1258 'warning' => 'bad-prefix',
1269 * Helper function that checks whether the filename looks like a thumbnail
1271 public static function isThumbName( $filename ) {
1272 $n = strrpos( $filename, '.' );
1273 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1275 substr( $partname , 3, 3 ) == 'px-' ||
1276 substr( $partname , 2, 3 ) == 'px-'
1278 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1282 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1284 * @return array list of prefixes
1286 public static function getFilenamePrefixBlacklist() {
1287 $blacklist = array();
1288 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1289 if( !$message->isDisabled() ) {
1290 $lines = explode( "\n", $message->plain() );
1291 foreach( $lines as $line ) {
1292 // Remove comment lines
1293 $comment = substr( trim( $line ), 0, 1 );
1294 if ( $comment == '#' ||
$comment == '' ) {
1297 // Remove additional comments after a prefix
1298 $comment = strpos( $line, '#' );
1299 if ( $comment > 0 ) {
1300 $line = substr( $line, 0, $comment-1 );
1302 $blacklist[] = trim( $line );
1309 * Gets image info about the file just uploaded.
1311 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1312 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1313 * with the appropriate format, presumably.
1315 * @param $result ApiResult:
1316 * @return Array: image info
1318 public function getImageInfo( $result ) {
1319 $file = $this->getLocalFile();
1320 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1321 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1322 if ( $file instanceof UploadStashFile
) {
1323 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1324 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1326 $imParam = ApiQueryImageInfo
::getPropertyNames();
1327 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1333 public function convertVerifyErrorToStatus( $error ) {
1334 $code = $error['status'];
1335 unset( $code['status'] );
1336 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1339 public static function getMaxUploadSize( $forType = null ) {
1340 global $wgMaxUploadSize;
1342 if ( is_array( $wgMaxUploadSize ) ) {
1343 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1344 return $wgMaxUploadSize[$forType];
1346 return $wgMaxUploadSize['*'];
1349 return intval( $wgMaxUploadSize );