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();
635 * We'll want to blacklist against *any* 'extension', and use
636 * only the final one for the whitelist.
638 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
640 if( count( $ext ) ) {
641 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
643 $this->mFinalExtension
= '';
645 # No extension, try guessing one
646 $magic = MimeMagic
::singleton();
647 $mime = $magic->guessMimeType( $this->mTempPath
);
648 if ( $mime !== 'unknown/unknown' ) {
649 # Get a space separated list of extensions
650 $extList = $magic->getExtensionsForType( $mime );
652 # Set the extension to the canonical extension
653 $this->mFinalExtension
= strtok( $extList, ' ' );
655 # Fix up the other variables
656 $this->mFilteredName
.= ".{$this->mFinalExtension}";
657 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
658 $ext = array( $this->mFinalExtension
);
664 /* Don't allow users to override the blacklist (check file extension) */
665 global $wgCheckFileExtensions, $wgStrictFileExtensions;
666 global $wgFileExtensions, $wgFileBlacklist;
668 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
670 if ( $this->mFinalExtension
== '' ) {
671 $this->mTitleError
= self
::FILETYPE_MISSING
;
672 return $this->mTitle
= null;
673 } elseif ( $blackListedExtensions ||
674 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
675 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
676 $this->mBlackListedExtensions
= $blackListedExtensions;
677 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
678 return $this->mTitle
= null;
681 // Windows may be broken with special characters, see bug XXX
682 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
683 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
684 return $this->mTitle
= null;
687 # If there was more than one "extension", reassemble the base
688 # filename to prevent bogus complaints about length
689 if( count( $ext ) > 1 ) {
690 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
691 $partname .= '.' . $ext[$i];
695 if( strlen( $partname ) < 1 ) {
696 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
697 return $this->mTitle
= null;
700 return $this->mTitle
= $nt;
704 * Return the local file and initializes if necessary.
708 public function getLocalFile() {
709 if( is_null( $this->mLocalFile
) ) {
710 $nt = $this->getTitle();
711 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
713 return $this->mLocalFile
;
717 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
718 * called outside that context.
720 * Stash a file in a temporary directory for later processing
721 * after the user has confirmed it.
723 * If the user doesn't explicitly cancel or accept, these files
724 * can accumulate in the temp directory.
726 * @param $saveName String: the destination filename
727 * @param $tempSrc String: the source temporary file to save
728 * @return String: full path the stashed file, or false on failure
730 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
731 $repo = RepoGroup
::singleton()->getLocalRepo();
732 $status = $repo->storeTemp( $saveName, $tempSrc );
737 * If the user does not supply all necessary information in the first upload form submission (either by accident or
738 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
740 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
742 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
743 * API request to find this stashed file again.
745 * @return UploadStashFile stashed file
747 public function stashFile() {
748 // was stashSessionFile
749 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
751 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
752 $this->mLocalFile
= $file;
757 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
759 * @return String: file key
761 public function stashFileGetKey() {
762 return $this->stashFile()->getFileKey();
766 * alias for stashFileGetKey, for backwards compatibility
768 * @return String: file key
770 public function stashSession() {
771 return $this->stashFileGetKey();
775 * If we've modified the upload file we need to manually remove it
776 * on exit to clean up.
778 public function cleanupTempFile() {
779 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
780 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
781 unlink( $this->mTempPath
);
785 public function getTempPath() {
786 return $this->mTempPath
;
790 * Split a file into a base name and all dot-delimited 'extensions'
791 * on the end. Some web server configurations will fall back to
792 * earlier pseudo-'extensions' to determine type and execute
793 * scripts, so the blacklist needs to check them all.
797 public static function splitExtensions( $filename ) {
798 $bits = explode( '.', $filename );
799 $basename = array_shift( $bits );
800 return array( $basename, $bits );
804 * Perform case-insensitive match against a list of file extensions.
805 * Returns true if the extension is in the list.
811 public static function checkFileExtension( $ext, $list ) {
812 return in_array( strtolower( $ext ), $list );
816 * Perform case-insensitive match against a list of file extensions.
817 * Returns an array of matching extensions.
823 public static function checkFileExtensionList( $ext, $list ) {
824 return array_intersect( array_map( 'strtolower', $ext ), $list );
828 * Checks if the mime type of the uploaded file matches the file extension.
830 * @param $mime String: the mime type of the uploaded file
831 * @param $extension String: the filename extension that the file is to be served with
834 public static function verifyExtension( $mime, $extension ) {
835 $magic = MimeMagic
::singleton();
837 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
838 if ( !$magic->isRecognizableExtension( $extension ) ) {
839 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
840 "unrecognized extension '$extension', can't verify\n" );
843 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
844 "recognized extension '$extension', so probably invalid file\n" );
848 $match = $magic->isMatchingExtension( $extension, $mime );
850 if ( $match === null ) {
851 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
853 } elseif( $match === true ) {
854 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
856 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
860 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
866 * Heuristic for detecting files that *could* contain JavaScript instructions or
867 * things that may look like HTML to a browser and are thus
868 * potentially harmful. The present implementation will produce false
869 * positives in some situations.
871 * @param $file String: pathname to the temporary upload file
872 * @param $mime String: the mime type of the file
873 * @param $extension String: the extension of the file
874 * @return Boolean: true if the file contains something looking like embedded scripts
876 public static function detectScript( $file, $mime, $extension ) {
877 global $wgAllowTitlesInSVG;
879 # ugly hack: for text files, always look at the entire file.
880 # For binary field, just check the first K.
882 if( strpos( $mime,'text/' ) === 0 ) {
883 $chunk = file_get_contents( $file );
885 $fp = fopen( $file, 'rb' );
886 $chunk = fread( $fp, 1024 );
890 $chunk = strtolower( $chunk );
896 # decode from UTF-16 if needed (could be used for obfuscation).
897 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
899 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
906 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
909 $chunk = trim( $chunk );
911 # @todo FIXME: Convert from UTF-16 if necessarry!
912 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
914 # check for HTML doctype
915 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
920 * Internet Explorer for Windows performs some really stupid file type
921 * autodetection which can cause it to interpret valid image files as HTML
922 * and potentially execute JavaScript, creating a cross-site scripting
925 * Apple's Safari browser also performs some unsafe file type autodetection
926 * which can cause legitimate files to be interpreted as HTML if the
927 * web server is not correctly configured to send the right content-type
928 * (or if you're really uploading plain text and octet streams!)
930 * Returns true if IE is likely to mistake the given file for HTML.
931 * Also returns true if Safari would mistake the given file for HTML
932 * when served with a generic content-type.
938 '<html', #also in safari
941 '<script', #also in safari
945 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
949 foreach( $tags as $tag ) {
950 if( false !== strpos( $chunk, $tag ) ) {
951 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
957 * look for JavaScript
960 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
961 $chunk = Sanitizer
::decodeCharReferences( $chunk );
963 # look for script-types
964 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
965 wfDebug( __METHOD__
. ": found script types\n" );
969 # look for html-style script-urls
970 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
971 wfDebug( __METHOD__
. ": found html-style script urls\n" );
975 # look for css-style script-urls
976 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
977 wfDebug( __METHOD__
. ": found css-style script urls\n" );
981 wfDebug( __METHOD__
. ": no scripts found\n" );
985 protected function detectScriptInSvg( $filename ) {
986 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
987 return $check->filterMatch
;
991 * @todo Replace this with a whitelist filter!
993 public function checkSvgScriptCallback( $element, $attribs ) {
994 $stripped = $this->stripXmlNamespace( $element );
996 if( $stripped == 'script' ) {
997 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1001 foreach( $attribs as $attrib => $value ) {
1002 $stripped = $this->stripXmlNamespace( $attrib );
1003 if( substr( $stripped, 0, 2 ) == 'on' ) {
1004 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1007 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1008 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1014 private function stripXmlNamespace( $name ) {
1015 // 'http://www.w3.org/2000/svg:script' -> 'script'
1016 $parts = explode( ':', strtolower( $name ) );
1017 return array_pop( $parts );
1021 * Generic wrapper function for a virus scanner program.
1022 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1023 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1025 * @param $file String: pathname to the temporary upload file
1026 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1027 * or a string containing feedback from the virus scanner if a virus was found.
1028 * If textual feedback is missing but a virus was found, this function returns true.
1030 public static function detectVirus( $file ) {
1031 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1033 if ( !$wgAntivirus ) {
1034 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1038 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1039 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1040 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1041 array( 'virus-badscanner', $wgAntivirus ) );
1042 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1045 # look up scanner configuration
1046 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1047 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1048 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1049 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1051 if ( strpos( $command, "%f" ) === false ) {
1052 # simple pattern: append file to scan
1053 $command .= " " . wfEscapeShellArg( $file );
1055 # complex pattern: replace "%f" with file to scan
1056 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1059 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1061 # execute virus scanner
1064 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1065 # that does not seem to be worth the pain.
1066 # Ask me (Duesentrieb) about it if it's ever needed.
1067 $output = wfShellExec( "$command 2>&1", $exitCode );
1069 # map exit code to AV_xxx constants.
1070 $mappedCode = $exitCode;
1071 if ( $exitCodeMap ) {
1072 if ( isset( $exitCodeMap[$exitCode] ) ) {
1073 $mappedCode = $exitCodeMap[$exitCode];
1074 } elseif ( isset( $exitCodeMap["*"] ) ) {
1075 $mappedCode = $exitCodeMap["*"];
1079 if ( $mappedCode === AV_SCAN_FAILED
) {
1080 # scan failed (code was mapped to false by $exitCodeMap)
1081 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1083 if ( $wgAntivirusRequired ) {
1084 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1088 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1089 # scan failed because filetype is unknown (probably imune)
1090 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1092 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1094 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1097 $output = trim( $output );
1100 $output = true; #if there's no output, return true
1101 } elseif ( $msgPattern ) {
1103 if ( preg_match( $msgPattern, $output, $groups ) ) {
1105 $output = $groups[1];
1110 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1116 * Check if there's an overwrite conflict and, if so, if restrictions
1117 * forbid this user from performing the upload.
1121 * @return mixed true on success, array on failure
1123 private function checkOverwrite( $user ) {
1124 // First check whether the local file can be overwritten
1125 $file = $this->getLocalFile();
1126 if( $file->exists() ) {
1127 if( !self
::userCanReUpload( $user, $file ) ) {
1128 return array( 'fileexists-forbidden', $file->getName() );
1134 /* Check shared conflicts: if the local file does not exist, but
1135 * wfFindFile finds a file, it exists in a shared repository.
1137 $file = wfFindFile( $this->getTitle() );
1138 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1139 return array( 'fileexists-shared-forbidden', $file->getName() );
1146 * Check if a user is the last uploader
1148 * @param $user User object
1149 * @param $img String: image name
1152 public static function userCanReUpload( User
$user, $img ) {
1153 if( $user->isAllowed( 'reupload' ) ) {
1154 return true; // non-conditional
1156 if( !$user->isAllowed( 'reupload-own' ) ) {
1159 if( is_string( $img ) ) {
1160 $img = wfLocalFile( $img );
1162 if ( !( $img instanceof LocalFile
) ) {
1166 return $user->getId() == $img->getUser( 'id' );
1170 * Helper function that does various existence checks for a file.
1171 * The following checks are performed:
1173 * - Article with the same name as the file exists
1174 * - File exists with normalized extension
1175 * - The file looks like a thumbnail and the original exists
1177 * @param $file File The File object to check
1178 * @return mixed False if the file does not exists, else an array
1180 public static function getExistsWarning( $file ) {
1181 if( $file->exists() ) {
1182 return array( 'warning' => 'exists', 'file' => $file );
1185 if( $file->getTitle()->getArticleID() ) {
1186 return array( 'warning' => 'page-exists', 'file' => $file );
1189 if ( $file->wasDeleted() && !$file->exists() ) {
1190 return array( 'warning' => 'was-deleted', 'file' => $file );
1193 if( strpos( $file->getName(), '.' ) == false ) {
1194 $partname = $file->getName();
1197 $n = strrpos( $file->getName(), '.' );
1198 $extension = substr( $file->getName(), $n +
1 );
1199 $partname = substr( $file->getName(), 0, $n );
1201 $normalizedExtension = File
::normalizeExtension( $extension );
1203 if ( $normalizedExtension != $extension ) {
1204 // We're not using the normalized form of the extension.
1205 // Normal form is lowercase, using most common of alternate
1206 // extensions (eg 'jpg' rather than 'JPEG').
1208 // Check for another file using the normalized form...
1209 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1210 $file_lc = wfLocalFile( $nt_lc );
1212 if( $file_lc->exists() ) {
1214 'warning' => 'exists-normalized',
1216 'normalizedFile' => $file_lc
1221 if ( self
::isThumbName( $file->getName() ) ) {
1222 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1223 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1224 $file_thb = wfLocalFile( $nt_thb );
1225 if( $file_thb->exists() ) {
1227 'warning' => 'thumb',
1229 'thumbFile' => $file_thb
1232 // File does not exist, but we just don't like the name
1234 'warning' => 'thumb-name',
1236 'thumbFile' => $file_thb
1242 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1243 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1245 'warning' => 'bad-prefix',
1256 * Helper function that checks whether the filename looks like a thumbnail
1258 public static function isThumbName( $filename ) {
1259 $n = strrpos( $filename, '.' );
1260 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1262 substr( $partname , 3, 3 ) == 'px-' ||
1263 substr( $partname , 2, 3 ) == 'px-'
1265 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1269 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1271 * @return array list of prefixes
1273 public static function getFilenamePrefixBlacklist() {
1274 $blacklist = array();
1275 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1276 if( !$message->isDisabled() ) {
1277 $lines = explode( "\n", $message->plain() );
1278 foreach( $lines as $line ) {
1279 // Remove comment lines
1280 $comment = substr( trim( $line ), 0, 1 );
1281 if ( $comment == '#' ||
$comment == '' ) {
1284 // Remove additional comments after a prefix
1285 $comment = strpos( $line, '#' );
1286 if ( $comment > 0 ) {
1287 $line = substr( $line, 0, $comment-1 );
1289 $blacklist[] = trim( $line );
1296 * Gets image info about the file just uploaded.
1298 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1299 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1300 * with the appropriate format, presumably.
1302 * @param $result ApiResult:
1303 * @return Array: image info
1305 public function getImageInfo( $result ) {
1306 $file = $this->getLocalFile();
1307 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1308 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1309 if ( $file instanceof UploadStashFile
) {
1310 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1311 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1313 $imParam = ApiQueryImageInfo
::getPropertyNames();
1314 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1320 public function convertVerifyErrorToStatus( $error ) {
1321 $code = $error['status'];
1322 unset( $code['status'] );
1323 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1326 public static function getMaxUploadSize( $forType = null ) {
1327 global $wgMaxUploadSize;
1329 if ( is_array( $wgMaxUploadSize ) ) {
1330 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1331 return $wgMaxUploadSize[$forType];
1333 return $wgMaxUploadSize['*'];
1336 return intval( $wgMaxUploadSize );