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;
26 const MIN_LENGTH_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyPermissions()
29 const FILETYPE_MISSING
= 8;
30 const FILETYPE_BADTYPE
= 9;
31 const VERIFICATION_ERROR
= 10;
33 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
34 const UPLOAD_VERIFICATION_ERROR
= 11;
35 const HOOK_ABORTED
= 11;
36 const FILE_TOO_LARGE
= 12;
38 const SESSION_VERSION
= 2;
39 const SESSION_KEYNAME
= 'wsUploadData';
41 static public function getSessionKeyname() {
42 return self
::SESSION_KEYNAME
;
45 public function getVerificationErrorCode( $error ) {
46 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
47 self
::FILE_TOO_LARGE
=> 'file-too-large',
48 self
::FILETYPE_MISSING
=> 'filetype-missing',
49 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
50 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
51 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
52 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
53 self
::VERIFICATION_ERROR
=> 'verification-error',
54 self
::HOOK_ABORTED
=> 'hookaborted',
56 if( isset( $code_to_status[$error] ) ) {
57 return $code_to_status[$error];
60 return 'unknown-error';
64 * Returns true if uploads are enabled.
65 * Can be override by subclasses.
67 public static function isEnabled() {
68 global $wgEnableUploads;
69 if ( !$wgEnableUploads ) {
73 # Check php's file_uploads setting
74 if( !wfIniGetBool( 'file_uploads' ) ) {
81 * Returns true if the user can use this upload module or else a string
82 * identifying the missing permission.
83 * Can be overriden by subclasses.
85 public static function isAllowed( $user ) {
86 foreach ( array( 'upload', 'edit' ) as $permission ) {
87 if ( !$user->isAllowed( $permission ) ) {
94 // Upload handlers. Should probably just be a global.
95 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
98 * Create a form of UploadBase depending on wpSourceType and initializes it
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 * @param $srcPath String: the source path
212 * @return the real path if it was a virtual URL
214 function getRealPath( $srcPath ) {
215 $repo = RepoGroup
::singleton()->getLocalRepo();
216 if ( $repo->isVirtualUrl( $srcPath ) ) {
217 return $repo->resolveVirtualUrl( $srcPath );
223 * Verify whether the upload is sane.
224 * @return mixed self::OK or else an array with error information
226 public function verifyUpload() {
228 * If there was no filename or a zero size given, give up quick.
230 if( $this->isEmptyFile() ) {
231 return array( 'status' => self
::EMPTY_FILE
);
235 * Honor $wgMaxUploadSize
237 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
238 if( $this->mFileSize
> $maxSize ) {
240 'status' => self
::FILE_TOO_LARGE
,
246 * Look at the contents of the file; if we can recognize the
247 * type but it's corrupt or data of the wrong type, we should
248 * probably not accept it.
250 $verification = $this->verifyFile();
251 if( $verification !== true ) {
253 'status' => self
::VERIFICATION_ERROR
,
254 'details' => $verification
259 * Make sure this file can be created
261 $result = $this->validateName();
262 if( $result !== true ) {
267 if( !wfRunHooks( 'UploadVerification',
268 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
269 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
272 return array( 'status' => self
::OK
);
276 * Verify that the name is valid and, if necessary, that we can overwrite
278 * @return mixed true if valid, otherwise and array with 'status'
281 protected function validateName() {
282 $nt = $this->getTitle();
283 if( is_null( $nt ) ) {
284 $result = array( 'status' => $this->mTitleError
);
285 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
286 $result['filtered'] = $this->mFilteredName
;
288 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
289 $result['finalExt'] = $this->mFinalExtension
;
290 if ( count( $this->mBlackListedExtensions
) ) {
291 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
296 $this->mDestName
= $this->getLocalFile()->getName();
302 * Verify the mime type
304 * @param $mime string representing the mime
305 * @return mixed true if the file is verified, an array otherwise
307 protected function verifyMimeType( $mime ) {
308 global $wgVerifyMimeType;
309 if ( $wgVerifyMimeType ) {
310 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
311 global $wgMimeTypeBlacklist;
312 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
313 return array( 'filetype-badmime', $mime );
316 # XXX: Missing extension will be caught by validateName() via getTitle()
317 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
318 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
322 $fp = fopen( $this->mTempPath
, 'rb' );
323 $chunk = fread( $fp, 256 );
326 $magic = MimeMagic
::singleton();
327 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
328 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
329 foreach ( $ieTypes as $ieType ) {
330 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
331 return array( 'filetype-bad-ie-mime', $ieType );
340 * Verifies that it's ok to include the uploaded file
342 * @return mixed true of the file is verified, array otherwise.
344 protected function verifyFile() {
345 # get the title, even though we are doing nothing with it, because
346 # we need to populate mFinalExtension
349 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
350 $this->checkMacBinary();
352 # check mime type, if desired
353 $mime = $this->mFileProps
[ 'file-mime' ];
354 $status = $this->verifyMimeType( $mime );
355 if ( $status !== true ) {
359 # check for htmlish code and javascript
360 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
361 return array( 'uploadscripted' );
363 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
364 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
365 return array( 'uploadscripted' );
370 * Scan the uploaded file for viruses
372 $virus = $this->detectVirus( $this->mTempPath
);
374 return array( 'uploadvirus', $virus );
377 $handler = MediaHandler
::getHandler( $mime );
379 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
380 if ( !$handlerStatus->isOK() ) {
381 $errors = $handlerStatus->getErrorsArray();
382 return reset( $errors );
386 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
387 if ( $status !== true ) {
391 wfDebug( __METHOD__
. ": all clear; passing.\n" );
396 * Check whether the user can edit, upload and create the image. This
397 * checks only against the current title; if it returns errors, it may
398 * very well be that another title will not give errors. Therefore
399 * isAllowed() should be called as well for generic is-user-blocked or
400 * can-user-upload checking.
402 * @param $user the User object to verify the permissions against
403 * @return mixed An array as returned by getUserPermissionsErrors or true
404 * in case the user has proper permissions.
406 public function verifyPermissions( $user ) {
408 * If the image is protected, non-sysop users won't be able
409 * to modify it by uploading a new revision.
411 $nt = $this->getTitle();
412 if( is_null( $nt ) ) {
415 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
416 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
417 if ( $nt->exists() ) {
418 $permErrorsCreate = $nt->getUserPermissionsErrors( 'createpage', $user );
420 $permErrorsCreate = array();
422 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
423 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
424 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
428 $overwriteError = $this->checkOverwrite( $user );
429 if ( $overwriteError !== true ) {
430 return array( array( $overwriteError ) );
437 * Check for non fatal problems with the file
439 * @return Array of warnings
441 public function checkWarnings() {
444 $localFile = $this->getLocalFile();
445 $filename = $localFile->getName();
448 * Check whether the resulting filename is different from the desired one,
449 * but ignore things like ucfirst() and spaces/underscore things
451 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
452 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
454 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
455 $warnings['badfilename'] = $filename;
458 // Check whether the file extension is on the unwanted list
459 global $wgCheckFileExtensions, $wgFileExtensions;
460 if ( $wgCheckFileExtensions ) {
461 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
462 $warnings['filetype-unwanted-type'] = $this->mFinalExtension
;
466 global $wgUploadSizeWarning;
467 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
468 $warnings['large-file'] = $wgUploadSizeWarning;
471 if ( $this->mFileSize
== 0 ) {
472 $warnings['emptyfile'] = true;
475 $exists = self
::getExistsWarning( $localFile );
476 if( $exists !== false ) {
477 $warnings['exists'] = $exists;
480 // Check dupes against existing files
481 $hash = File
::sha1Base36( $this->mTempPath
);
482 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
483 $title = $this->getTitle();
484 // Remove all matches against self
485 foreach ( $dupes as $key => $dupe ) {
486 if( $title->equals( $dupe->getTitle() ) ) {
487 unset( $dupes[$key] );
491 $warnings['duplicate'] = $dupes;
494 // Check dupes against archives
495 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
496 if ( $archivedImage->getID() > 0 ) {
497 $warnings['duplicate-archive'] = $archivedImage->getName();
504 * Really perform the upload. Stores the file in the local repo, watches
505 * if necessary and runs the UploadComplete hook.
507 * @return Status indicating the whether the upload succeeded.
509 public function performUpload( $comment, $pageText, $watch, $user ) {
510 $status = $this->getLocalFile()->upload(
520 if( $status->isGood() ) {
522 $user->addWatch( $this->getLocalFile()->getTitle() );
525 wfRunHooks( 'UploadComplete', array( &$this ) );
532 * Returns the title of the file to be uploaded. Sets mTitleError in case
533 * the name was illegal.
535 * @return Title The title of the file or null in case the name was illegal
537 public function getTitle() {
538 if ( $this->mTitle
!== false ) {
539 return $this->mTitle
;
543 * Chop off any directories in the given filename. Then
544 * filter out illegal characters, and try to make a legible name
545 * out of it. We'll strip some silently that Title would die on.
547 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mDesiredDestName
);
548 /* Normalize to title form before we do any further processing */
549 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
550 if( is_null( $nt ) ) {
551 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
552 return $this->mTitle
= null;
554 $this->mFilteredName
= $nt->getDBkey();
557 * We'll want to blacklist against *any* 'extension', and use
558 * only the final one for the whitelist.
560 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
562 if( count( $ext ) ) {
563 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
565 $this->mFinalExtension
= '';
567 # No extension, try guessing one
568 $magic = MimeMagic
::singleton();
569 $mime = $magic->guessMimeType( $this->mTempPath
);
570 if ( $mime !== 'unknown/unknown' ) {
571 # Get a space separated list of extensions
572 $extList = $magic->getExtensionsForType( $mime );
574 # Set the extension to the canonical extension
575 $this->mFinalExtension
= strtok( $extList, ' ' );
577 # Fix up the other variables
578 $this->mFilteredName
.= ".{$this->mFinalExtension}";
579 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
580 $ext = array( $this->mFinalExtension
);
586 /* Don't allow users to override the blacklist (check file extension) */
587 global $wgCheckFileExtensions, $wgStrictFileExtensions;
588 global $wgFileExtensions, $wgFileBlacklist;
590 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
592 if ( $this->mFinalExtension
== '' ) {
593 $this->mTitleError
= self
::FILETYPE_MISSING
;
594 return $this->mTitle
= null;
595 } elseif ( $blackListedExtensions ||
596 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
597 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) ) {
598 $this->mBlackListedExtensions
= $blackListedExtensions;
599 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
600 return $this->mTitle
= null;
603 # If there was more than one "extension", reassemble the base
604 # filename to prevent bogus complaints about length
605 if( count( $ext ) > 1 ) {
606 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
607 $partname .= '.' . $ext[$i];
611 if( strlen( $partname ) < 1 ) {
612 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
613 return $this->mTitle
= null;
616 return $this->mTitle
= $nt;
620 * Return the local file and initializes if necessary.
622 public function getLocalFile() {
623 if( is_null( $this->mLocalFile
) ) {
624 $nt = $this->getTitle();
625 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
627 return $this->mLocalFile
;
631 * NOTE: Probably should be deprecated in favor of UploadStash, but this is sometimes
632 * called outside that context.
634 * Stash a file in a temporary directory for later processing
635 * after the user has confirmed it.
637 * If the user doesn't explicitly cancel or accept, these files
638 * can accumulate in the temp directory.
640 * @param $saveName String: the destination filename
641 * @param $tempSrc String: the source temporary file to save
642 * @return String: full path the stashed file, or false on failure
644 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
645 $repo = RepoGroup
::singleton()->getLocalRepo();
646 $status = $repo->storeTemp( $saveName, $tempSrc );
651 * If the user does not supply all necessary information in the first upload form submission (either by accident or
652 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
654 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
655 * into the user's session.
656 * This method returns the file object, which also has a 'sessionKey' property which can be passed through a form or
657 * API request to find this stashed file again.
659 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
660 * @return File stashed file
662 public function stashSessionFile( $key = null ) {
663 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
665 'mFileProps' => $this->mFileProps
,
666 'mSourceType' => $this->getSourceType(),
668 $file = $stash->stashFile( $this->mTempPath
, $data, $key );
669 $this->mLocalFile
= $file;
674 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashSessionFile().
676 * @param $key String: (optional) the session key used to find the file info again. If not supplied, a key will be autogenerated.
677 * @return String: session key
679 public function stashSession( $key = null ) {
680 return $this->stashSessionFile( $key )->getSessionKey();
684 * If we've modified the upload file we need to manually remove it
685 * on exit to clean up.
687 public function cleanupTempFile() {
688 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
689 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
690 unlink( $this->mTempPath
);
694 public function getTempPath() {
695 return $this->mTempPath
;
699 * Split a file into a base name and all dot-delimited 'extensions'
700 * on the end. Some web server configurations will fall back to
701 * earlier pseudo-'extensions' to determine type and execute
702 * scripts, so the blacklist needs to check them all.
706 public static function splitExtensions( $filename ) {
707 $bits = explode( '.', $filename );
708 $basename = array_shift( $bits );
709 return array( $basename, $bits );
713 * Perform case-insensitive match against a list of file extensions.
714 * Returns true if the extension is in the list.
720 public static function checkFileExtension( $ext, $list ) {
721 return in_array( strtolower( $ext ), $list );
725 * Perform case-insensitive match against a list of file extensions.
726 * Returns an array of matching extensions.
732 public static function checkFileExtensionList( $ext, $list ) {
733 return array_intersect( array_map( 'strtolower', $ext ), $list );
737 * Checks if the mime type of the uploaded file matches the file extension.
739 * @param $mime String: the mime type of the uploaded file
740 * @param $extension String: the filename extension that the file is to be served with
743 public static function verifyExtension( $mime, $extension ) {
744 $magic = MimeMagic
::singleton();
746 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
747 if ( !$magic->isRecognizableExtension( $extension ) ) {
748 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
749 "unrecognized extension '$extension', can't verify\n" );
752 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
753 "recognized extension '$extension', so probably invalid file\n" );
757 $match = $magic->isMatchingExtension( $extension, $mime );
759 if ( $match === null ) {
760 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
762 } elseif( $match === true ) {
763 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
765 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
769 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
775 * Heuristic for detecting files that *could* contain JavaScript instructions or
776 * things that may look like HTML to a browser and are thus
777 * potentially harmful. The present implementation will produce false
778 * positives in some situations.
780 * @param $file String: pathname to the temporary upload file
781 * @param $mime String: the mime type of the file
782 * @param $extension String: the extension of the file
783 * @return Boolean: true if the file contains something looking like embedded scripts
785 public static function detectScript( $file, $mime, $extension ) {
786 global $wgAllowTitlesInSVG;
788 # ugly hack: for text files, always look at the entire file.
789 # For binary field, just check the first K.
791 if( strpos( $mime,'text/' ) === 0 ) {
792 $chunk = file_get_contents( $file );
794 $fp = fopen( $file, 'rb' );
795 $chunk = fread( $fp, 1024 );
799 $chunk = strtolower( $chunk );
805 # decode from UTF-16 if needed (could be used for obfuscation).
806 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
808 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
815 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
818 $chunk = trim( $chunk );
820 # FIXME: convert from UTF-16 if necessarry!
821 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
823 # check for HTML doctype
824 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
829 * Internet Explorer for Windows performs some really stupid file type
830 * autodetection which can cause it to interpret valid image files as HTML
831 * and potentially execute JavaScript, creating a cross-site scripting
834 * Apple's Safari browser also performs some unsafe file type autodetection
835 * which can cause legitimate files to be interpreted as HTML if the
836 * web server is not correctly configured to send the right content-type
837 * (or if you're really uploading plain text and octet streams!)
839 * Returns true if IE is likely to mistake the given file for HTML.
840 * Also returns true if Safari would mistake the given file for HTML
841 * when served with a generic content-type.
847 '<html', #also in safari
850 '<script', #also in safari
854 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
858 foreach( $tags as $tag ) {
859 if( false !== strpos( $chunk, $tag ) ) {
865 * look for JavaScript
868 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
869 $chunk = Sanitizer
::decodeCharReferences( $chunk );
871 # look for script-types
872 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
876 # look for html-style script-urls
877 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
881 # look for css-style script-urls
882 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
886 wfDebug( __METHOD__
. ": no scripts found\n" );
890 protected function detectScriptInSvg( $filename ) {
891 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
892 return $check->filterMatch
;
896 * @todo Replace this with a whitelist filter!
898 public function checkSvgScriptCallback( $element, $attribs ) {
899 $stripped = $this->stripXmlNamespace( $element );
901 if( $stripped == 'script' ) {
902 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
906 foreach( $attribs as $attrib => $value ) {
907 $stripped = $this->stripXmlNamespace( $attrib );
908 if( substr( $stripped, 0, 2 ) == 'on' ) {
909 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
912 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
913 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
919 private function stripXmlNamespace( $name ) {
920 // 'http://www.w3.org/2000/svg:script' -> 'script'
921 $parts = explode( ':', strtolower( $name ) );
922 return array_pop( $parts );
926 * Generic wrapper function for a virus scanner program.
927 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
928 * $wgAntivirusRequired may be used to deny upload if the scan fails.
930 * @param $file String: pathname to the temporary upload file
931 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
932 * or a string containing feedback from the virus scanner if a virus was found.
933 * If textual feedback is missing but a virus was found, this function returns true.
935 public static function detectVirus( $file ) {
936 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
938 if ( !$wgAntivirus ) {
939 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
943 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
944 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
945 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
946 array( 'virus-badscanner', $wgAntivirus ) );
947 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
950 # look up scanner configuration
951 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
952 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
953 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
954 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
956 if ( strpos( $command, "%f" ) === false ) {
957 # simple pattern: append file to scan
958 $command .= " " . wfEscapeShellArg( $file );
960 # complex pattern: replace "%f" with file to scan
961 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
964 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
966 # execute virus scanner
969 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
970 # that does not seem to be worth the pain.
971 # Ask me (Duesentrieb) about it if it's ever needed.
972 $output = wfShellExec( "$command 2>&1", $exitCode );
974 # map exit code to AV_xxx constants.
975 $mappedCode = $exitCode;
976 if ( $exitCodeMap ) {
977 if ( isset( $exitCodeMap[$exitCode] ) ) {
978 $mappedCode = $exitCodeMap[$exitCode];
979 } elseif ( isset( $exitCodeMap["*"] ) ) {
980 $mappedCode = $exitCodeMap["*"];
984 if ( $mappedCode === AV_SCAN_FAILED
) {
985 # scan failed (code was mapped to false by $exitCodeMap)
986 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
988 if ( $wgAntivirusRequired ) {
989 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
993 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
994 # scan failed because filetype is unknown (probably imune)
995 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
997 } elseif ( $mappedCode === AV_NO_VIRUS
) {
999 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1002 $output = trim( $output );
1005 $output = true; #if there's no output, return true
1006 } elseif ( $msgPattern ) {
1008 if ( preg_match( $msgPattern, $output, $groups ) ) {
1010 $output = $groups[1];
1015 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1021 * Check if the temporary file is MacBinary-encoded, as some uploads
1022 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1023 * If so, the data fork will be extracted to a second temporary file,
1024 * which will then be checked for validity and either kept or discarded.
1026 private function checkMacBinary() {
1027 $macbin = new MacBinary( $this->mTempPath
);
1028 if( $macbin->isValid() ) {
1029 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
1030 $dataHandle = fopen( $dataFile, 'wb' );
1032 wfDebug( __METHOD__
. ": Extracting MacBinary data fork to $dataFile\n" );
1033 $macbin->extractData( $dataHandle );
1035 $this->mTempPath
= $dataFile;
1036 $this->mFileSize
= $macbin->dataForkLength();
1038 // We'll have to manually remove the new file if it's not kept.
1039 $this->mRemoveTempFile
= true;
1045 * Check if there's an overwrite conflict and, if so, if restrictions
1046 * forbid this user from performing the upload.
1048 * @return mixed true on success, error string on failure
1050 private function checkOverwrite( $user ) {
1051 // First check whether the local file can be overwritten
1052 $file = $this->getLocalFile();
1053 if( $file->exists() ) {
1054 if( !self
::userCanReUpload( $user, $file ) ) {
1055 return 'fileexists-forbidden';
1061 /* Check shared conflicts: if the local file does not exist, but
1062 * wfFindFile finds a file, it exists in a shared repository.
1064 $file = wfFindFile( $this->getTitle() );
1065 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1066 return 'fileexists-shared-forbidden';
1073 * Check if a user is the last uploader
1075 * @param $user User object
1076 * @param $img String: image name
1079 public static function userCanReUpload( User
$user, $img ) {
1080 if( $user->isAllowed( 'reupload' ) ) {
1081 return true; // non-conditional
1083 if( !$user->isAllowed( 'reupload-own' ) ) {
1086 if( is_string( $img ) ) {
1087 $img = wfLocalFile( $img );
1089 if ( !( $img instanceof LocalFile
) ) {
1093 return $user->getId() == $img->getUser( 'id' );
1097 * Helper function that does various existence checks for a file.
1098 * The following checks are performed:
1100 * - Article with the same name as the file exists
1101 * - File exists with normalized extension
1102 * - The file looks like a thumbnail and the original exists
1104 * @param $file File The File object to check
1105 * @return mixed False if the file does not exists, else an array
1107 public static function getExistsWarning( $file ) {
1108 if( $file->exists() ) {
1109 return array( 'warning' => 'exists', 'file' => $file );
1112 if( $file->getTitle()->getArticleID() ) {
1113 return array( 'warning' => 'page-exists', 'file' => $file );
1116 if ( $file->wasDeleted() && !$file->exists() ) {
1117 return array( 'warning' => 'was-deleted', 'file' => $file );
1120 if( strpos( $file->getName(), '.' ) == false ) {
1121 $partname = $file->getName();
1124 $n = strrpos( $file->getName(), '.' );
1125 $extension = substr( $file->getName(), $n +
1 );
1126 $partname = substr( $file->getName(), 0, $n );
1128 $normalizedExtension = File
::normalizeExtension( $extension );
1130 if ( $normalizedExtension != $extension ) {
1131 // We're not using the normalized form of the extension.
1132 // Normal form is lowercase, using most common of alternate
1133 // extensions (eg 'jpg' rather than 'JPEG').
1135 // Check for another file using the normalized form...
1136 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1137 $file_lc = wfLocalFile( $nt_lc );
1139 if( $file_lc->exists() ) {
1141 'warning' => 'exists-normalized',
1143 'normalizedFile' => $file_lc
1148 if ( self
::isThumbName( $file->getName() ) ) {
1149 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1150 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1151 $file_thb = wfLocalFile( $nt_thb );
1152 if( $file_thb->exists() ) {
1154 'warning' => 'thumb',
1156 'thumbFile' => $file_thb
1159 // File does not exist, but we just don't like the name
1161 'warning' => 'thumb-name',
1163 'thumbFile' => $file_thb
1169 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1170 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1172 'warning' => 'bad-prefix',
1183 * Helper function that checks whether the filename looks like a thumbnail
1185 public static function isThumbName( $filename ) {
1186 $n = strrpos( $filename, '.' );
1187 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1189 substr( $partname , 3, 3 ) == 'px-' ||
1190 substr( $partname , 2, 3 ) == 'px-'
1192 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1196 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1198 * @return array list of prefixes
1200 public static function getFilenamePrefixBlacklist() {
1201 $blacklist = array();
1202 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1203 if( !$message->isDisabled() ) {
1204 $lines = explode( "\n", $message->plain() );
1205 foreach( $lines as $line ) {
1206 // Remove comment lines
1207 $comment = substr( trim( $line ), 0, 1 );
1208 if ( $comment == '#' ||
$comment == '' ) {
1211 // Remove additional comments after a prefix
1212 $comment = strpos( $line, '#' );
1213 if ( $comment > 0 ) {
1214 $line = substr( $line, 0, $comment-1 );
1216 $blacklist[] = trim( $line );
1223 * Gets image info about the file just uploaded.
1225 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1226 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1227 * with the appropriate format, presumably.
1229 * @param $result ApiResult:
1230 * @return Array: image info
1232 public function getImageInfo( $result ) {
1233 $file = $this->getLocalFile();
1234 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1235 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1236 if ( $file instanceof UploadStashFile
) {
1237 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1238 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1240 $imParam = ApiQueryImageInfo
::getPropertyNames();
1241 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1247 public function convertVerifyErrorToStatus( $error ) {
1248 $code = $error['status'];
1249 unset( $code['status'] );
1250 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1253 public static function getMaxUploadSize( $forType = null ) {
1254 global $wgMaxUploadSize;
1256 if ( is_array( $wgMaxUploadSize ) ) {
1257 if ( !is_null( $forType) && isset( $wgMaxUploadSize[$forType] ) ) {
1258 return $wgMaxUploadSize[$forType];
1260 return $wgMaxUploadSize['*'];
1263 return intval( $wgMaxUploadSize );