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;
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( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
376 return array( 'uploadscripted' );
378 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
379 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
380 return array( 'uploadscripted' );
384 # Check for Java applets, which if uploaded can bypass cross-site
386 if ( !$wgAllowJavaUploads ) {
387 $this->mJavaDetected
= false;
388 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
389 array( $this, 'zipEntryCallback' ) );
390 if ( !$zipStatus->isOK() ) {
391 $errors = $zipStatus->getErrorsArray();
392 $error = reset( $errors );
393 if ( $error[0] !== 'zip-wrong-format' ) {
397 if ( $this->mJavaDetected
) {
398 return array( 'uploadjava' );
402 # Scan the uploaded file for viruses
403 $virus = $this->detectVirus( $this->mTempPath
);
405 return array( 'uploadvirus', $virus );
408 $handler = MediaHandler
::getHandler( $mime );
410 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
411 if ( !$handlerStatus->isOK() ) {
412 $errors = $handlerStatus->getErrorsArray();
413 return reset( $errors );
417 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
418 if ( $status !== true ) {
422 wfDebug( __METHOD__
. ": all clear; passing.\n" );
427 * Callback for ZipDirectoryReader to detect Java class files.
429 function zipEntryCallback( $entry ) {
430 $names = array( $entry['name'] );
432 // If there is a null character, cut off the name at it, because JDK's
433 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
434 // were constructed which had ".class\0" followed by a string chosen to
435 // make the hash collide with the truncated name, that file could be
436 // returned in response to a request for the .class file.
437 $nullPos = strpos( $entry['name'], "\000" );
438 if ( $nullPos !== false ) {
439 $names[] = substr( $entry['name'], 0, $nullPos );
442 // If there is a trailing slash in the file name, we have to strip it,
443 // because that's what ZIP_GetEntry() does.
444 if ( preg_grep( '!\.class/?$!', $names ) ) {
445 $this->mJavaDetected
= true;
450 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
451 * but that suggests it's checking the user, when it's really checking the title + user combination.
452 * @param $user User object to verify the permissions against
453 * @return mixed An array as returned by getUserPermissionsErrors or true
454 * in case the user has proper permissions.
456 public function verifyPermissions( $user ) {
457 return $this->verifyTitlePermissions( $user );
461 * Check whether the user can edit, upload and create the image. This
462 * checks only against the current title; if it returns errors, it may
463 * very well be that another title will not give errors. Therefore
464 * isAllowed() should be called as well for generic is-user-blocked or
465 * can-user-upload checking.
467 * @param $user User object to verify the permissions against
468 * @return mixed An array as returned by getUserPermissionsErrors or true
469 * in case the user has proper permissions.
471 public function verifyTitlePermissions( $user ) {
473 * If the image is protected, non-sysop users won't be able
474 * to modify it by uploading a new revision.
476 $nt = $this->getTitle();
477 if( is_null( $nt ) ) {
480 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
481 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
482 if ( !$nt->exists() ) {
483 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
485 $permErrorsCreate = array();
487 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
488 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
489 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
493 $overwriteError = $this->checkOverwrite( $user );
494 if ( $overwriteError !== true ) {
495 return array( $overwriteError );
502 * Check for non fatal problems with the file
504 * @return Array of warnings
506 public function checkWarnings() {
511 $localFile = $this->getLocalFile();
512 $filename = $localFile->getName();
515 * Check whether the resulting filename is different from the desired one,
516 * but ignore things like ucfirst() and spaces/underscore things
518 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
519 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
521 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
522 $warnings['badfilename'] = $filename;
525 // Check whether the file extension is on the unwanted list
526 global $wgCheckFileExtensions, $wgFileExtensions;
527 if ( $wgCheckFileExtensions ) {
528 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
529 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
530 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
534 global $wgUploadSizeWarning;
535 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
536 $warnings['large-file'] = $wgUploadSizeWarning;
539 if ( $this->mFileSize
== 0 ) {
540 $warnings['emptyfile'] = true;
543 $exists = self
::getExistsWarning( $localFile );
544 if( $exists !== false ) {
545 $warnings['exists'] = $exists;
548 // Check dupes against existing files
549 $hash = File
::sha1Base36( $this->mTempPath
);
550 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
551 $title = $this->getTitle();
552 // Remove all matches against self
553 foreach ( $dupes as $key => $dupe ) {
554 if( $title->equals( $dupe->getTitle() ) ) {
555 unset( $dupes[$key] );
559 $warnings['duplicate'] = $dupes;
562 // Check dupes against archives
563 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
564 if ( $archivedImage->getID() > 0 ) {
565 $warnings['duplicate-archive'] = $archivedImage->getName();
572 * Really perform the upload. Stores the file in the local repo, watches
573 * if necessary and runs the UploadComplete hook.
577 * @return Status indicating the whether the upload succeeded.
579 public function performUpload( $comment, $pageText, $watch, $user ) {
580 $status = $this->getLocalFile()->upload(
590 if( $status->isGood() ) {
592 $user->addWatch( $this->getLocalFile()->getTitle() );
595 wfRunHooks( 'UploadComplete', array( &$this ) );
602 * Returns the title of the file to be uploaded. Sets mTitleError in case
603 * the name was illegal.
605 * @return Title The title of the file or null in case the name was illegal
607 public function getTitle() {
608 if ( $this->mTitle
!== false ) {
609 return $this->mTitle
;
612 /* Assume that if a user specified File:Something.jpg, this is an error
613 * and that the namespace prefix needs to be stripped of.
615 $title = Title
::newFromText( $this->mDesiredDestName
);
616 if ( $title && $title->getNamespace() == NS_FILE
) {
617 $this->mFilteredName
= $title->getDBkey();
619 $this->mFilteredName
= $this->mDesiredDestName
;
622 # oi_archive_name is max 255 bytes, which include a timestamp and an
623 # exclamation mark, so restrict file name to 240 bytes.
624 if ( strlen( $this->mFilteredName
) > 240 ) {
625 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
626 return $this->mTitle
= null;
630 * Chop off any directories in the given filename. Then
631 * filter out illegal characters, and try to make a legible name
632 * out of it. We'll strip some silently that Title would die on.
634 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
635 /* Normalize to title form before we do any further processing */
636 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
637 if( is_null( $nt ) ) {
638 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
639 return $this->mTitle
= null;
641 $this->mFilteredName
= $nt->getDBkey();
646 * We'll want to blacklist against *any* 'extension', and use
647 * only the final one for the whitelist.
649 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
651 if( count( $ext ) ) {
652 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
654 $this->mFinalExtension
= '';
656 # No extension, try guessing one
657 $magic = MimeMagic
::singleton();
658 $mime = $magic->guessMimeType( $this->mTempPath
);
659 if ( $mime !== 'unknown/unknown' ) {
660 # Get a space separated list of extensions
661 $extList = $magic->getExtensionsForType( $mime );
663 # Set the extension to the canonical extension
664 $this->mFinalExtension
= strtok( $extList, ' ' );
666 # Fix up the other variables
667 $this->mFilteredName
.= ".{$this->mFinalExtension}";
668 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
669 $ext = array( $this->mFinalExtension
);
675 /* Don't allow users to override the blacklist (check file extension) */
676 global $wgCheckFileExtensions, $wgStrictFileExtensions;
677 global $wgFileExtensions, $wgFileBlacklist;
679 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
681 if ( $this->mFinalExtension
== '' ) {
682 $this->mTitleError
= self
::FILETYPE_MISSING
;
683 return $this->mTitle
= null;
684 } elseif ( $blackListedExtensions ||
685 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
686 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
687 $this->mBlackListedExtensions
= $blackListedExtensions;
688 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
689 return $this->mTitle
= null;
692 // Windows may be broken with special characters, see bug XXX
693 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
694 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
695 return $this->mTitle
= null;
698 # If there was more than one "extension", reassemble the base
699 # filename to prevent bogus complaints about length
700 if( count( $ext ) > 1 ) {
701 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
702 $partname .= '.' . $ext[$i];
706 if( strlen( $partname ) < 1 ) {
707 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
708 return $this->mTitle
= null;
711 return $this->mTitle
= $nt;
715 * Return the local file and initializes if necessary.
719 public function getLocalFile() {
720 if( is_null( $this->mLocalFile
) ) {
721 $nt = $this->getTitle();
722 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
724 return $this->mLocalFile
;
728 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
729 * called outside that context.
731 * Stash a file in a temporary directory for later processing
732 * after the user has confirmed it.
734 * If the user doesn't explicitly cancel or accept, these files
735 * can accumulate in the temp directory.
737 * @param $saveName String: the destination filename
738 * @param $tempSrc String: the source temporary file to save
739 * @return String: full path the stashed file, or false on failure
741 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
742 $repo = RepoGroup
::singleton()->getLocalRepo();
743 $status = $repo->storeTemp( $saveName, $tempSrc );
748 * If the user does not supply all necessary information in the first upload form submission (either by accident or
749 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
751 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
753 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
754 * API request to find this stashed file again.
756 * @return UploadStashFile stashed file
758 public function stashFile() {
759 // was stashSessionFile
760 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
762 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
763 $this->mLocalFile
= $file;
768 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
770 * @return String: file key
772 public function stashFileGetKey() {
773 return $this->stashFile()->getFileKey();
777 * alias for stashFileGetKey, for backwards compatibility
779 * @return String: file key
781 public function stashSession() {
782 return $this->stashFileGetKey();
786 * If we've modified the upload file we need to manually remove it
787 * on exit to clean up.
789 public function cleanupTempFile() {
790 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
791 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
792 unlink( $this->mTempPath
);
796 public function getTempPath() {
797 return $this->mTempPath
;
801 * Split a file into a base name and all dot-delimited 'extensions'
802 * on the end. Some web server configurations will fall back to
803 * earlier pseudo-'extensions' to determine type and execute
804 * scripts, so the blacklist needs to check them all.
808 public static function splitExtensions( $filename ) {
809 $bits = explode( '.', $filename );
810 $basename = array_shift( $bits );
811 return array( $basename, $bits );
815 * Perform case-insensitive match against a list of file extensions.
816 * Returns true if the extension is in the list.
822 public static function checkFileExtension( $ext, $list ) {
823 return in_array( strtolower( $ext ), $list );
827 * Perform case-insensitive match against a list of file extensions.
828 * Returns an array of matching extensions.
834 public static function checkFileExtensionList( $ext, $list ) {
835 return array_intersect( array_map( 'strtolower', $ext ), $list );
839 * Checks if the mime type of the uploaded file matches the file extension.
841 * @param $mime String: the mime type of the uploaded file
842 * @param $extension String: the filename extension that the file is to be served with
845 public static function verifyExtension( $mime, $extension ) {
846 $magic = MimeMagic
::singleton();
848 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
849 if ( !$magic->isRecognizableExtension( $extension ) ) {
850 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
851 "unrecognized extension '$extension', can't verify\n" );
854 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
855 "recognized extension '$extension', so probably invalid file\n" );
859 $match = $magic->isMatchingExtension( $extension, $mime );
861 if ( $match === null ) {
862 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
864 } elseif( $match === true ) {
865 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
867 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
871 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
877 * Heuristic for detecting files that *could* contain JavaScript instructions or
878 * things that may look like HTML to a browser and are thus
879 * potentially harmful. The present implementation will produce false
880 * positives in some situations.
882 * @param $file String: pathname to the temporary upload file
883 * @param $mime String: the mime type of the file
884 * @param $extension String: the extension of the file
885 * @return Boolean: true if the file contains something looking like embedded scripts
887 public static function detectScript( $file, $mime, $extension ) {
888 global $wgAllowTitlesInSVG;
890 # ugly hack: for text files, always look at the entire file.
891 # For binary field, just check the first K.
893 if( strpos( $mime,'text/' ) === 0 ) {
894 $chunk = file_get_contents( $file );
896 $fp = fopen( $file, 'rb' );
897 $chunk = fread( $fp, 1024 );
901 $chunk = strtolower( $chunk );
907 # decode from UTF-16 if needed (could be used for obfuscation).
908 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
910 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
917 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
920 $chunk = trim( $chunk );
922 # @todo FIXME: Convert from UTF-16 if necessarry!
923 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
925 # check for HTML doctype
926 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
931 * Internet Explorer for Windows performs some really stupid file type
932 * autodetection which can cause it to interpret valid image files as HTML
933 * and potentially execute JavaScript, creating a cross-site scripting
936 * Apple's Safari browser also performs some unsafe file type autodetection
937 * which can cause legitimate files to be interpreted as HTML if the
938 * web server is not correctly configured to send the right content-type
939 * (or if you're really uploading plain text and octet streams!)
941 * Returns true if IE is likely to mistake the given file for HTML.
942 * Also returns true if Safari would mistake the given file for HTML
943 * when served with a generic content-type.
949 '<html', #also in safari
952 '<script', #also in safari
956 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
960 foreach( $tags as $tag ) {
961 if( false !== strpos( $chunk, $tag ) ) {
962 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
968 * look for JavaScript
971 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
972 $chunk = Sanitizer
::decodeCharReferences( $chunk );
974 # look for script-types
975 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
976 wfDebug( __METHOD__
. ": found script types\n" );
980 # look for html-style script-urls
981 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
982 wfDebug( __METHOD__
. ": found html-style script urls\n" );
986 # look for css-style script-urls
987 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
988 wfDebug( __METHOD__
. ": found css-style script urls\n" );
992 wfDebug( __METHOD__
. ": no scripts found\n" );
996 protected function detectScriptInSvg( $filename ) {
997 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
998 return $check->filterMatch
;
1002 * @todo Replace this with a whitelist filter!
1004 public function checkSvgScriptCallback( $element, $attribs ) {
1005 $stripped = $this->stripXmlNamespace( $element );
1007 if( $stripped == 'script' ) {
1008 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1012 foreach( $attribs as $attrib => $value ) {
1013 $stripped = $this->stripXmlNamespace( $attrib );
1014 if( substr( $stripped, 0, 2 ) == 'on' ) {
1015 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1018 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1019 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1025 private function stripXmlNamespace( $name ) {
1026 // 'http://www.w3.org/2000/svg:script' -> 'script'
1027 $parts = explode( ':', strtolower( $name ) );
1028 return array_pop( $parts );
1032 * Generic wrapper function for a virus scanner program.
1033 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1034 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1036 * @param $file String: pathname to the temporary upload file
1037 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1038 * or a string containing feedback from the virus scanner if a virus was found.
1039 * If textual feedback is missing but a virus was found, this function returns true.
1041 public static function detectVirus( $file ) {
1042 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1044 if ( !$wgAntivirus ) {
1045 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1049 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1050 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1051 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1052 array( 'virus-badscanner', $wgAntivirus ) );
1053 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1056 # look up scanner configuration
1057 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1058 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1059 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1060 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1062 if ( strpos( $command, "%f" ) === false ) {
1063 # simple pattern: append file to scan
1064 $command .= " " . wfEscapeShellArg( $file );
1066 # complex pattern: replace "%f" with file to scan
1067 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1070 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1072 # execute virus scanner
1075 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1076 # that does not seem to be worth the pain.
1077 # Ask me (Duesentrieb) about it if it's ever needed.
1078 $output = wfShellExec( "$command 2>&1", $exitCode );
1080 # map exit code to AV_xxx constants.
1081 $mappedCode = $exitCode;
1082 if ( $exitCodeMap ) {
1083 if ( isset( $exitCodeMap[$exitCode] ) ) {
1084 $mappedCode = $exitCodeMap[$exitCode];
1085 } elseif ( isset( $exitCodeMap["*"] ) ) {
1086 $mappedCode = $exitCodeMap["*"];
1090 if ( $mappedCode === AV_SCAN_FAILED
) {
1091 # scan failed (code was mapped to false by $exitCodeMap)
1092 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1094 if ( $wgAntivirusRequired ) {
1095 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1099 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1100 # scan failed because filetype is unknown (probably imune)
1101 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1103 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1105 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1108 $output = trim( $output );
1111 $output = true; #if there's no output, return true
1112 } elseif ( $msgPattern ) {
1114 if ( preg_match( $msgPattern, $output, $groups ) ) {
1116 $output = $groups[1];
1121 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1127 * Check if there's an overwrite conflict and, if so, if restrictions
1128 * forbid this user from performing the upload.
1132 * @return mixed true on success, array on failure
1134 private function checkOverwrite( $user ) {
1135 // First check whether the local file can be overwritten
1136 $file = $this->getLocalFile();
1137 if( $file->exists() ) {
1138 if( !self
::userCanReUpload( $user, $file ) ) {
1139 return array( 'fileexists-forbidden', $file->getName() );
1145 /* Check shared conflicts: if the local file does not exist, but
1146 * wfFindFile finds a file, it exists in a shared repository.
1148 $file = wfFindFile( $this->getTitle() );
1149 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1150 return array( 'fileexists-shared-forbidden', $file->getName() );
1157 * Check if a user is the last uploader
1159 * @param $user User object
1160 * @param $img String: image name
1163 public static function userCanReUpload( User
$user, $img ) {
1164 if( $user->isAllowed( 'reupload' ) ) {
1165 return true; // non-conditional
1167 if( !$user->isAllowed( 'reupload-own' ) ) {
1170 if( is_string( $img ) ) {
1171 $img = wfLocalFile( $img );
1173 if ( !( $img instanceof LocalFile
) ) {
1177 return $user->getId() == $img->getUser( 'id' );
1181 * Helper function that does various existence checks for a file.
1182 * The following checks are performed:
1184 * - Article with the same name as the file exists
1185 * - File exists with normalized extension
1186 * - The file looks like a thumbnail and the original exists
1188 * @param $file File The File object to check
1189 * @return mixed False if the file does not exists, else an array
1191 public static function getExistsWarning( $file ) {
1192 if( $file->exists() ) {
1193 return array( 'warning' => 'exists', 'file' => $file );
1196 if( $file->getTitle()->getArticleID() ) {
1197 return array( 'warning' => 'page-exists', 'file' => $file );
1200 if ( $file->wasDeleted() && !$file->exists() ) {
1201 return array( 'warning' => 'was-deleted', 'file' => $file );
1204 if( strpos( $file->getName(), '.' ) == false ) {
1205 $partname = $file->getName();
1208 $n = strrpos( $file->getName(), '.' );
1209 $extension = substr( $file->getName(), $n +
1 );
1210 $partname = substr( $file->getName(), 0, $n );
1212 $normalizedExtension = File
::normalizeExtension( $extension );
1214 if ( $normalizedExtension != $extension ) {
1215 // We're not using the normalized form of the extension.
1216 // Normal form is lowercase, using most common of alternate
1217 // extensions (eg 'jpg' rather than 'JPEG').
1219 // Check for another file using the normalized form...
1220 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1221 $file_lc = wfLocalFile( $nt_lc );
1223 if( $file_lc->exists() ) {
1225 'warning' => 'exists-normalized',
1227 'normalizedFile' => $file_lc
1232 if ( self
::isThumbName( $file->getName() ) ) {
1233 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1234 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1235 $file_thb = wfLocalFile( $nt_thb );
1236 if( $file_thb->exists() ) {
1238 'warning' => 'thumb',
1240 'thumbFile' => $file_thb
1243 // File does not exist, but we just don't like the name
1245 'warning' => 'thumb-name',
1247 'thumbFile' => $file_thb
1253 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1254 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1256 'warning' => 'bad-prefix',
1267 * Helper function that checks whether the filename looks like a thumbnail
1269 public static function isThumbName( $filename ) {
1270 $n = strrpos( $filename, '.' );
1271 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1273 substr( $partname , 3, 3 ) == 'px-' ||
1274 substr( $partname , 2, 3 ) == 'px-'
1276 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1280 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1282 * @return array list of prefixes
1284 public static function getFilenamePrefixBlacklist() {
1285 $blacklist = array();
1286 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1287 if( !$message->isDisabled() ) {
1288 $lines = explode( "\n", $message->plain() );
1289 foreach( $lines as $line ) {
1290 // Remove comment lines
1291 $comment = substr( trim( $line ), 0, 1 );
1292 if ( $comment == '#' ||
$comment == '' ) {
1295 // Remove additional comments after a prefix
1296 $comment = strpos( $line, '#' );
1297 if ( $comment > 0 ) {
1298 $line = substr( $line, 0, $comment-1 );
1300 $blacklist[] = trim( $line );
1307 * Gets image info about the file just uploaded.
1309 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1310 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1311 * with the appropriate format, presumably.
1313 * @param $result ApiResult:
1314 * @return Array: image info
1316 public function getImageInfo( $result ) {
1317 $file = $this->getLocalFile();
1318 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1319 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1320 if ( $file instanceof UploadStashFile
) {
1321 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1322 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1324 $imParam = ApiQueryImageInfo
::getPropertyNames();
1325 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1331 public function convertVerifyErrorToStatus( $error ) {
1332 $code = $error['status'];
1333 unset( $code['status'] );
1334 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1337 public static function getMaxUploadSize( $forType = null ) {
1338 global $wgMaxUploadSize;
1340 if ( is_array( $wgMaxUploadSize ) ) {
1341 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1342 return $wgMaxUploadSize[$forType];
1344 return $wgMaxUploadSize['*'];
1347 return intval( $wgMaxUploadSize );