9 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
10 * The frontends are formed by ApiUpload and SpecialUpload.
12 * See also includes/docs/upload.txt
14 * @author Brion Vibber
15 * @author Bryan Tong Minh
16 * @author Michael Dale
18 abstract class UploadBase
{
20 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
21 protected $mTitle = false, $mTitleError = 0;
22 protected $mFilteredName, $mFinalExtension;
23 protected $mLocalFile, $mFileSize, $mFileProps;
24 protected $mBlackListedExtensions;
25 protected $mJavaDetected;
30 const MIN_LENGTH_PARTNAME
= 4;
31 const ILLEGAL_FILENAME
= 5;
32 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
33 const FILETYPE_MISSING
= 8;
34 const FILETYPE_BADTYPE
= 9;
35 const VERIFICATION_ERROR
= 10;
37 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
38 const UPLOAD_VERIFICATION_ERROR
= 11;
39 const HOOK_ABORTED
= 11;
40 const FILE_TOO_LARGE
= 12;
41 const WINDOWS_NONASCII_FILENAME
= 13;
42 const FILENAME_TOO_LONG
= 14;
44 public function getVerificationErrorCode( $error ) {
45 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
46 self
::FILE_TOO_LARGE
=> 'file-too-large',
47 self
::FILETYPE_MISSING
=> 'filetype-missing',
48 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
49 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
50 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
51 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
52 self
::VERIFICATION_ERROR
=> 'verification-error',
53 self
::HOOK_ABORTED
=> 'hookaborted',
54 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
55 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
57 if( isset( $code_to_status[$error] ) ) {
58 return $code_to_status[$error];
61 return 'unknown-error';
65 * Returns true if uploads are enabled.
66 * Can be override by subclasses.
69 public static function isEnabled() {
70 global $wgEnableUploads;
72 if ( !$wgEnableUploads ) {
76 # Check php's file_uploads setting
77 return wfIsHipHop() ||
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.
88 public static function isAllowed( $user ) {
89 foreach ( array( 'upload', 'edit' ) as $permission ) {
90 if ( !$user->isAllowed( $permission ) ) {
97 // Upload handlers. Should probably just be a global.
98 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
101 * Create a form of UploadBase depending on wpSourceType and initializes it
103 * @param $request WebRequest
107 public static function createFromRequest( &$request, $type = null ) {
108 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
114 // Get the upload class
115 $type = ucfirst( $type );
117 // Give hooks the chance to handle this request
119 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
120 if ( is_null( $className ) ) {
121 $className = 'UploadFrom' . $type;
122 wfDebug( __METHOD__
. ": class name: $className\n" );
123 if( !in_array( $type, self
::$uploadHandlers ) ) {
128 // Check whether this upload class is enabled
129 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
133 // Check whether the request is valid
134 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
138 $handler = new $className;
140 $handler->initializeFromRequest( $request );
145 * Check whether a request if valid for this handler
148 public static function isValidRequest( $request ) {
152 public function __construct() {}
155 * Returns the upload type. Should be overridden by child classes
160 public function getSourceType() { return null; }
163 * Initialize the path information
164 * @param $name string the desired destination name
165 * @param $tempPath string the temporary path
166 * @param $fileSize int the file size
167 * @param $removeTempFile bool (false) remove the temporary file?
170 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
171 $this->mDesiredDestName
= $name;
172 if ( FileBackend
::isStoragePath( $tempPath ) ) {
173 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
175 $this->mTempPath
= $tempPath;
176 $this->mFileSize
= $fileSize;
177 $this->mRemoveTempFile
= $removeTempFile;
181 * Initialize from a WebRequest. Override this in a subclass.
183 public abstract function initializeFromRequest( &$request );
186 * Fetch the file. Usually a no-op
189 public function fetchFile() {
190 return Status
::newGood();
194 * Return true if the file is empty
197 public function isEmptyFile() {
198 return empty( $this->mFileSize
);
202 * Return the file size
205 public function getFileSize() {
206 return $this->mFileSize
;
210 * @param $srcPath String: the source path
211 * @return stringthe real path if it was a virtual URL
213 function getRealPath( $srcPath ) {
214 wfProfileIn( __METHOD__
);
215 $repo = RepoGroup
::singleton()->getLocalRepo();
216 if ( $repo->isVirtualUrl( $srcPath ) ) {
217 // @TODO: just make uploads work with storage paths
218 // UploadFromStash loads files via virtuals URLs
219 $tmpFile = $repo->getLocalCopy( $srcPath );
220 $tmpFile->bind( $this ); // keep alive with $thumb
221 wfProfileOut( __METHOD__
);
222 return $tmpFile->getPath();
224 wfProfileOut( __METHOD__
);
229 * Verify whether the upload is sane.
230 * @return mixed self::OK or else an array with error information
232 public function verifyUpload() {
233 wfProfileIn( __METHOD__
);
236 * If there was no filename or a zero size given, give up quick.
238 if( $this->isEmptyFile() ) {
239 wfProfileOut( __METHOD__
);
240 return array( 'status' => self
::EMPTY_FILE
);
244 * Honor $wgMaxUploadSize
246 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
247 if( $this->mFileSize
> $maxSize ) {
248 wfProfileOut( __METHOD__
);
250 'status' => self
::FILE_TOO_LARGE
,
256 * Look at the contents of the file; if we can recognize the
257 * type but it's corrupt or data of the wrong type, we should
258 * probably not accept it.
260 $verification = $this->verifyFile();
261 if( $verification !== true ) {
262 wfProfileOut( __METHOD__
);
264 'status' => self
::VERIFICATION_ERROR
,
265 'details' => $verification
270 * Make sure this file can be created
272 $result = $this->validateName();
273 if( $result !== true ) {
274 wfProfileOut( __METHOD__
);
279 if( !wfRunHooks( 'UploadVerification',
280 array( $this->mDestName
, $this->mTempPath
, &$error ) ) )
282 wfProfileOut( __METHOD__
);
283 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
286 wfProfileOut( __METHOD__
);
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 wfProfileIn( __METHOD__
);
325 if ( $wgVerifyMimeType ) {
326 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
327 global $wgMimeTypeBlacklist;
328 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
329 wfProfileOut( __METHOD__
);
330 return array( 'filetype-badmime', $mime );
333 # XXX: Missing extension will be caught by validateName() via getTitle()
334 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
335 wfProfileOut( __METHOD__
);
336 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
340 $fp = fopen( $this->mTempPath
, 'rb' );
341 $chunk = fread( $fp, 256 );
344 $magic = MimeMagic
::singleton();
345 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
346 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
347 foreach ( $ieTypes as $ieType ) {
348 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
349 wfProfileOut( __METHOD__
);
350 return array( 'filetype-bad-ie-mime', $ieType );
355 wfProfileOut( __METHOD__
);
360 * Verifies that it's ok to include the uploaded file
362 * @return mixed true of the file is verified, array otherwise.
364 protected function verifyFile() {
365 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
366 wfProfileIn( __METHOD__
);
368 # get the title, even though we are doing nothing with it, because
369 # we need to populate mFinalExtension
372 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
374 # check mime type, if desired
375 $mime = $this->mFileProps
[ 'file-mime' ];
376 $status = $this->verifyMimeType( $mime );
377 if ( $status !== true ) {
378 wfProfileOut( __METHOD__
);
382 # check for htmlish code and javascript
383 if ( !$wgDisableUploadScriptChecks ) {
384 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
385 wfProfileOut( __METHOD__
);
386 return array( 'uploadscripted' );
388 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
389 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
390 wfProfileOut( __METHOD__
);
391 return array( 'uploadscripted' );
396 # Check for Java applets, which if uploaded can bypass cross-site
398 if ( !$wgAllowJavaUploads ) {
399 $this->mJavaDetected
= false;
400 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
401 array( $this, 'zipEntryCallback' ) );
402 if ( !$zipStatus->isOK() ) {
403 $errors = $zipStatus->getErrorsArray();
404 $error = reset( $errors );
405 if ( $error[0] !== 'zip-wrong-format' ) {
406 wfProfileOut( __METHOD__
);
410 if ( $this->mJavaDetected
) {
411 wfProfileOut( __METHOD__
);
412 return array( 'uploadjava' );
416 # Scan the uploaded file for viruses
417 $virus = $this->detectVirus( $this->mTempPath
);
419 wfProfileOut( __METHOD__
);
420 return array( 'uploadvirus', $virus );
423 $handler = MediaHandler
::getHandler( $mime );
425 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
426 if ( !$handlerStatus->isOK() ) {
427 $errors = $handlerStatus->getErrorsArray();
428 wfProfileOut( __METHOD__
);
429 return reset( $errors );
433 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
434 if ( $status !== true ) {
435 wfProfileOut( __METHOD__
);
439 wfDebug( __METHOD__
. ": all clear; passing.\n" );
440 wfProfileOut( __METHOD__
);
445 * Callback for ZipDirectoryReader to detect Java class files.
447 function zipEntryCallback( $entry ) {
448 $names = array( $entry['name'] );
450 // If there is a null character, cut off the name at it, because JDK's
451 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
452 // were constructed which had ".class\0" followed by a string chosen to
453 // make the hash collide with the truncated name, that file could be
454 // returned in response to a request for the .class file.
455 $nullPos = strpos( $entry['name'], "\000" );
456 if ( $nullPos !== false ) {
457 $names[] = substr( $entry['name'], 0, $nullPos );
460 // If there is a trailing slash in the file name, we have to strip it,
461 // because that's what ZIP_GetEntry() does.
462 if ( preg_grep( '!\.class/?$!', $names ) ) {
463 $this->mJavaDetected
= true;
468 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
469 * but that suggests it's checking the user, when it's really checking the title + user combination.
470 * @param $user User object to verify the permissions against
471 * @return mixed An array as returned by getUserPermissionsErrors or true
472 * in case the user has proper permissions.
474 public function verifyPermissions( $user ) {
475 return $this->verifyTitlePermissions( $user );
479 * Check whether the user can edit, upload and create the image. This
480 * checks only against the current title; if it returns errors, it may
481 * very well be that another title will not give errors. Therefore
482 * isAllowed() should be called as well for generic is-user-blocked or
483 * can-user-upload checking.
485 * @param $user User object to verify the permissions against
486 * @return mixed An array as returned by getUserPermissionsErrors or true
487 * in case the user has proper permissions.
489 public function verifyTitlePermissions( $user ) {
491 * If the image is protected, non-sysop users won't be able
492 * to modify it by uploading a new revision.
494 $nt = $this->getTitle();
495 if( is_null( $nt ) ) {
498 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
499 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
500 if ( !$nt->exists() ) {
501 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
503 $permErrorsCreate = array();
505 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
506 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
507 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
511 $overwriteError = $this->checkOverwrite( $user );
512 if ( $overwriteError !== true ) {
513 return array( $overwriteError );
520 * Check for non fatal problems with the file
522 * @return Array of warnings
524 public function checkWarnings() {
526 wfProfileIn( __METHOD__
);
530 $localFile = $this->getLocalFile();
531 $filename = $localFile->getName();
534 * Check whether the resulting filename is different from the desired one,
535 * but ignore things like ucfirst() and spaces/underscore things
537 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
538 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
540 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
541 $warnings['badfilename'] = $filename;
544 // Check whether the file extension is on the unwanted list
545 global $wgCheckFileExtensions, $wgFileExtensions;
546 if ( $wgCheckFileExtensions ) {
547 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
548 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
549 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
553 global $wgUploadSizeWarning;
554 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
555 $warnings['large-file'] = $wgUploadSizeWarning;
558 if ( $this->mFileSize
== 0 ) {
559 $warnings['emptyfile'] = true;
562 $exists = self
::getExistsWarning( $localFile );
563 if( $exists !== false ) {
564 $warnings['exists'] = $exists;
567 // Check dupes against existing files
568 $hash = FSFile
::getSha1Base36FromPath( $this->mTempPath
);
569 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
570 $title = $this->getTitle();
571 // Remove all matches against self
572 foreach ( $dupes as $key => $dupe ) {
573 if( $title->equals( $dupe->getTitle() ) ) {
574 unset( $dupes[$key] );
578 $warnings['duplicate'] = $dupes;
581 // Check dupes against archives
582 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
583 if ( $archivedImage->getID() > 0 ) {
584 $warnings['duplicate-archive'] = $archivedImage->getName();
587 wfProfileOut( __METHOD__
);
592 * Really perform the upload. Stores the file in the local repo, watches
593 * if necessary and runs the UploadComplete hook.
597 * @return Status indicating the whether the upload succeeded.
599 public function performUpload( $comment, $pageText, $watch, $user ) {
600 wfProfileIn( __METHOD__
);
602 $status = $this->getLocalFile()->upload(
612 if( $status->isGood() ) {
614 $user->addWatch( $this->getLocalFile()->getTitle() );
616 wfRunHooks( 'UploadComplete', array( &$this ) );
619 wfProfileOut( __METHOD__
);
624 * Returns the title of the file to be uploaded. Sets mTitleError in case
625 * the name was illegal.
627 * @return Title The title of the file or null in case the name was illegal
629 public function getTitle() {
630 if ( $this->mTitle
!== false ) {
631 return $this->mTitle
;
634 /* Assume that if a user specified File:Something.jpg, this is an error
635 * and that the namespace prefix needs to be stripped of.
637 $title = Title
::newFromText( $this->mDesiredDestName
);
638 if ( $title && $title->getNamespace() == NS_FILE
) {
639 $this->mFilteredName
= $title->getDBkey();
641 $this->mFilteredName
= $this->mDesiredDestName
;
644 # oi_archive_name is max 255 bytes, which include a timestamp and an
645 # exclamation mark, so restrict file name to 240 bytes.
646 if ( strlen( $this->mFilteredName
) > 240 ) {
647 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
648 return $this->mTitle
= null;
652 * Chop off any directories in the given filename. Then
653 * filter out illegal characters, and try to make a legible name
654 * out of it. We'll strip some silently that Title would die on.
656 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
657 /* Normalize to title form before we do any further processing */
658 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
659 if( is_null( $nt ) ) {
660 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
661 return $this->mTitle
= null;
663 $this->mFilteredName
= $nt->getDBkey();
668 * We'll want to blacklist against *any* 'extension', and use
669 * only the final one for the whitelist.
671 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
673 if( count( $ext ) ) {
674 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
676 $this->mFinalExtension
= '';
678 # No extension, try guessing one
679 $magic = MimeMagic
::singleton();
680 $mime = $magic->guessMimeType( $this->mTempPath
);
681 if ( $mime !== 'unknown/unknown' ) {
682 # Get a space separated list of extensions
683 $extList = $magic->getExtensionsForType( $mime );
685 # Set the extension to the canonical extension
686 $this->mFinalExtension
= strtok( $extList, ' ' );
688 # Fix up the other variables
689 $this->mFilteredName
.= ".{$this->mFinalExtension}";
690 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
691 $ext = array( $this->mFinalExtension
);
697 /* Don't allow users to override the blacklist (check file extension) */
698 global $wgCheckFileExtensions, $wgStrictFileExtensions;
699 global $wgFileExtensions, $wgFileBlacklist;
701 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
703 if ( $this->mFinalExtension
== '' ) {
704 $this->mTitleError
= self
::FILETYPE_MISSING
;
705 return $this->mTitle
= null;
706 } elseif ( $blackListedExtensions ||
707 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
708 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
709 $this->mBlackListedExtensions
= $blackListedExtensions;
710 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
711 return $this->mTitle
= null;
714 // Windows may be broken with special characters, see bug XXX
715 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
716 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
717 return $this->mTitle
= null;
720 # If there was more than one "extension", reassemble the base
721 # filename to prevent bogus complaints about length
722 if( count( $ext ) > 1 ) {
723 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
724 $partname .= '.' . $ext[$i];
728 if( strlen( $partname ) < 1 ) {
729 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
730 return $this->mTitle
= null;
733 return $this->mTitle
= $nt;
737 * Return the local file and initializes if necessary.
741 public function getLocalFile() {
742 if( is_null( $this->mLocalFile
) ) {
743 $nt = $this->getTitle();
744 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
746 return $this->mLocalFile
;
750 * If the user does not supply all necessary information in the first upload form submission (either by accident or
751 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
753 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
755 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
756 * API request to find this stashed file again.
758 * @return UploadStashFile stashed file
760 public function stashFile() {
761 // was stashSessionFile
762 wfProfileIn( __METHOD__
);
764 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
765 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
766 $this->mLocalFile
= $file;
768 wfProfileOut( __METHOD__
);
773 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
775 * @return String: file key
777 public function stashFileGetKey() {
778 return $this->stashFile()->getFileKey();
782 * alias for stashFileGetKey, for backwards compatibility
784 * @return String: file key
786 public function stashSession() {
787 return $this->stashFileGetKey();
791 * If we've modified the upload file we need to manually remove it
792 * on exit to clean up.
794 public function cleanupTempFile() {
795 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
796 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
797 unlink( $this->mTempPath
);
801 public function getTempPath() {
802 return $this->mTempPath
;
806 * Split a file into a base name and all dot-delimited 'extensions'
807 * on the end. Some web server configurations will fall back to
808 * earlier pseudo-'extensions' to determine type and execute
809 * scripts, so the blacklist needs to check them all.
813 public static function splitExtensions( $filename ) {
814 $bits = explode( '.', $filename );
815 $basename = array_shift( $bits );
816 return array( $basename, $bits );
820 * Perform case-insensitive match against a list of file extensions.
821 * Returns true if the extension is in the list.
827 public static function checkFileExtension( $ext, $list ) {
828 return in_array( strtolower( $ext ), $list );
832 * Perform case-insensitive match against a list of file extensions.
833 * Returns an array of matching extensions.
839 public static function checkFileExtensionList( $ext, $list ) {
840 return array_intersect( array_map( 'strtolower', $ext ), $list );
844 * Checks if the mime type of the uploaded file matches the file extension.
846 * @param $mime String: the mime type of the uploaded file
847 * @param $extension String: the filename extension that the file is to be served with
850 public static function verifyExtension( $mime, $extension ) {
851 $magic = MimeMagic
::singleton();
853 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
854 if ( !$magic->isRecognizableExtension( $extension ) ) {
855 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
856 "unrecognized extension '$extension', can't verify\n" );
859 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
860 "recognized extension '$extension', so probably invalid file\n" );
864 $match = $magic->isMatchingExtension( $extension, $mime );
866 if ( $match === null ) {
867 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
869 } elseif( $match === true ) {
870 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
872 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
876 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
882 * Heuristic for detecting files that *could* contain JavaScript instructions or
883 * things that may look like HTML to a browser and are thus
884 * potentially harmful. The present implementation will produce false
885 * positives in some situations.
887 * @param $file String: pathname to the temporary upload file
888 * @param $mime String: the mime type of the file
889 * @param $extension String: the extension of the file
890 * @return Boolean: true if the file contains something looking like embedded scripts
892 public static function detectScript( $file, $mime, $extension ) {
893 global $wgAllowTitlesInSVG;
894 wfProfileIn( __METHOD__
);
896 # ugly hack: for text files, always look at the entire file.
897 # For binary field, just check the first K.
899 if( strpos( $mime,'text/' ) === 0 ) {
900 $chunk = file_get_contents( $file );
902 $fp = fopen( $file, 'rb' );
903 $chunk = fread( $fp, 1024 );
907 $chunk = strtolower( $chunk );
910 wfProfileOut( __METHOD__
);
914 # decode from UTF-16 if needed (could be used for obfuscation).
915 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
917 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
924 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
927 $chunk = trim( $chunk );
929 # @todo FIXME: Convert from UTF-16 if necessarry!
930 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
932 # check for HTML doctype
933 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
934 wfProfileOut( __METHOD__
);
939 * Internet Explorer for Windows performs some really stupid file type
940 * autodetection which can cause it to interpret valid image files as HTML
941 * and potentially execute JavaScript, creating a cross-site scripting
944 * Apple's Safari browser also performs some unsafe file type autodetection
945 * which can cause legitimate files to be interpreted as HTML if the
946 * web server is not correctly configured to send the right content-type
947 * (or if you're really uploading plain text and octet streams!)
949 * Returns true if IE is likely to mistake the given file for HTML.
950 * Also returns true if Safari would mistake the given file for HTML
951 * when served with a generic content-type.
957 '<html', #also in safari
960 '<script', #also in safari
964 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
968 foreach( $tags as $tag ) {
969 if( false !== strpos( $chunk, $tag ) ) {
970 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
971 wfProfileOut( __METHOD__
);
977 * look for JavaScript
980 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
981 $chunk = Sanitizer
::decodeCharReferences( $chunk );
983 # look for script-types
984 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
985 wfDebug( __METHOD__
. ": found script types\n" );
986 wfProfileOut( __METHOD__
);
990 # look for html-style script-urls
991 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
992 wfDebug( __METHOD__
. ": found html-style script urls\n" );
993 wfProfileOut( __METHOD__
);
997 # look for css-style script-urls
998 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
999 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1000 wfProfileOut( __METHOD__
);
1004 wfDebug( __METHOD__
. ": no scripts found\n" );
1005 wfProfileOut( __METHOD__
);
1009 protected function detectScriptInSvg( $filename ) {
1010 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1011 return $check->filterMatch
;
1015 * @todo Replace this with a whitelist filter!
1018 public function checkSvgScriptCallback( $element, $attribs ) {
1019 $strippedElement = $this->stripXmlNamespace( $element );
1022 * check for elements that can contain javascript
1024 if( $strippedElement == 'script' ) {
1025 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1029 # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1030 if( $strippedElement == 'handler' ) {
1031 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1035 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1036 if( $strippedElement == 'stylesheet' ) {
1037 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1041 foreach( $attribs as $attrib => $value ) {
1042 $stripped = $this->stripXmlNamespace( $attrib );
1043 $value = strtolower($value);
1045 if( substr( $stripped, 0, 2 ) == 'on' ) {
1046 wfDebug( __METHOD__
. ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1050 # href with javascript target
1051 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1052 wfDebug( __METHOD__
. ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1056 # href with embeded svg as target
1057 if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1058 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1062 # href with embeded (text/xml) svg as target
1063 if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1064 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1068 # use set/animate to add event-handler attribute to parent
1069 if( ( $strippedElement == 'set' ||
$strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1070 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1074 # use set to add href attribute to parent element
1075 if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1076 wfDebug( __METHOD__
. ": Found svg setting href attibute '$value' in uploaded file.\n" );
1080 # use set to add a remote / data / script target to an element
1081 if( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1082 wfDebug( __METHOD__
. ": Found svg setting attibute to '$value' in uploaded file.\n" );
1087 # use handler attribute with remote / data / script
1088 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1089 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1093 # use CSS styles to bring in remote code
1094 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1095 if( $stripped == 'style' && preg_match_all( '!((?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim', $value, $matches ) ) {
1096 foreach ($matches[1] as $match) {
1097 if (!preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1098 wfDebug( __METHOD__
. ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1104 # image filters can pull in url, which could be svg that executes scripts
1105 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1106 wfDebug( __METHOD__
. ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1112 return false; //No scripts detected
1115 private function stripXmlNamespace( $name ) {
1116 // 'http://www.w3.org/2000/svg:script' -> 'script'
1117 $parts = explode( ':', strtolower( $name ) );
1118 return array_pop( $parts );
1122 * Generic wrapper function for a virus scanner program.
1123 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1124 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1126 * @param $file String: pathname to the temporary upload file
1127 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1128 * or a string containing feedback from the virus scanner if a virus was found.
1129 * If textual feedback is missing but a virus was found, this function returns true.
1131 public static function detectVirus( $file ) {
1132 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1133 wfProfileIn( __METHOD__
);
1135 if ( !$wgAntivirus ) {
1136 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1137 wfProfileOut( __METHOD__
);
1141 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1142 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1143 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1144 array( 'virus-badscanner', $wgAntivirus ) );
1145 wfProfileOut( __METHOD__
);
1146 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
1149 # look up scanner configuration
1150 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1151 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1152 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1153 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1155 if ( strpos( $command, "%f" ) === false ) {
1156 # simple pattern: append file to scan
1157 $command .= " " . wfEscapeShellArg( $file );
1159 # complex pattern: replace "%f" with file to scan
1160 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1163 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1165 # execute virus scanner
1168 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1169 # that does not seem to be worth the pain.
1170 # Ask me (Duesentrieb) about it if it's ever needed.
1171 $output = wfShellExec( "$command 2>&1", $exitCode );
1173 # map exit code to AV_xxx constants.
1174 $mappedCode = $exitCode;
1175 if ( $exitCodeMap ) {
1176 if ( isset( $exitCodeMap[$exitCode] ) ) {
1177 $mappedCode = $exitCodeMap[$exitCode];
1178 } elseif ( isset( $exitCodeMap["*"] ) ) {
1179 $mappedCode = $exitCodeMap["*"];
1183 if ( $mappedCode === AV_SCAN_FAILED
) {
1184 # scan failed (code was mapped to false by $exitCodeMap)
1185 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1187 if ( $wgAntivirusRequired ) {
1188 wfProfileOut( __METHOD__
);
1189 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
1191 wfProfileOut( __METHOD__
);
1194 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1195 # scan failed because filetype is unknown (probably imune)
1196 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1197 wfProfileOut( __METHOD__
);
1199 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1201 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1202 wfProfileOut( __METHOD__
);
1205 $output = trim( $output );
1208 $output = true; #if there's no output, return true
1209 } elseif ( $msgPattern ) {
1211 if ( preg_match( $msgPattern, $output, $groups ) ) {
1213 $output = $groups[1];
1218 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1219 wfProfileOut( __METHOD__
);
1225 * Check if there's an overwrite conflict and, if so, if restrictions
1226 * forbid this user from performing the upload.
1230 * @return mixed true on success, array on failure
1232 private function checkOverwrite( $user ) {
1233 // First check whether the local file can be overwritten
1234 $file = $this->getLocalFile();
1235 if( $file->exists() ) {
1236 if( !self
::userCanReUpload( $user, $file ) ) {
1237 return array( 'fileexists-forbidden', $file->getName() );
1243 /* Check shared conflicts: if the local file does not exist, but
1244 * wfFindFile finds a file, it exists in a shared repository.
1246 $file = wfFindFile( $this->getTitle() );
1247 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1248 return array( 'fileexists-shared-forbidden', $file->getName() );
1255 * Check if a user is the last uploader
1257 * @param $user User object
1258 * @param $img String: image name
1261 public static function userCanReUpload( User
$user, $img ) {
1262 if( $user->isAllowed( 'reupload' ) ) {
1263 return true; // non-conditional
1265 if( !$user->isAllowed( 'reupload-own' ) ) {
1268 if( is_string( $img ) ) {
1269 $img = wfLocalFile( $img );
1271 if ( !( $img instanceof LocalFile
) ) {
1275 return $user->getId() == $img->getUser( 'id' );
1279 * Helper function that does various existence checks for a file.
1280 * The following checks are performed:
1282 * - Article with the same name as the file exists
1283 * - File exists with normalized extension
1284 * - The file looks like a thumbnail and the original exists
1286 * @param $file File The File object to check
1287 * @return mixed False if the file does not exists, else an array
1289 public static function getExistsWarning( $file ) {
1290 if( $file->exists() ) {
1291 return array( 'warning' => 'exists', 'file' => $file );
1294 if( $file->getTitle()->getArticleID() ) {
1295 return array( 'warning' => 'page-exists', 'file' => $file );
1298 if ( $file->wasDeleted() && !$file->exists() ) {
1299 return array( 'warning' => 'was-deleted', 'file' => $file );
1302 if( strpos( $file->getName(), '.' ) == false ) {
1303 $partname = $file->getName();
1306 $n = strrpos( $file->getName(), '.' );
1307 $extension = substr( $file->getName(), $n +
1 );
1308 $partname = substr( $file->getName(), 0, $n );
1310 $normalizedExtension = File
::normalizeExtension( $extension );
1312 if ( $normalizedExtension != $extension ) {
1313 // We're not using the normalized form of the extension.
1314 // Normal form is lowercase, using most common of alternate
1315 // extensions (eg 'jpg' rather than 'JPEG').
1317 // Check for another file using the normalized form...
1318 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1319 $file_lc = wfLocalFile( $nt_lc );
1321 if( $file_lc->exists() ) {
1323 'warning' => 'exists-normalized',
1325 'normalizedFile' => $file_lc
1330 if ( self
::isThumbName( $file->getName() ) ) {
1331 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1332 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1333 $file_thb = wfLocalFile( $nt_thb );
1334 if( $file_thb->exists() ) {
1336 'warning' => 'thumb',
1338 'thumbFile' => $file_thb
1341 // File does not exist, but we just don't like the name
1343 'warning' => 'thumb-name',
1345 'thumbFile' => $file_thb
1351 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1352 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1354 'warning' => 'bad-prefix',
1365 * Helper function that checks whether the filename looks like a thumbnail
1368 public static function isThumbName( $filename ) {
1369 $n = strrpos( $filename, '.' );
1370 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1372 substr( $partname , 3, 3 ) == 'px-' ||
1373 substr( $partname , 2, 3 ) == 'px-'
1375 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1379 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1381 * @return array list of prefixes
1383 public static function getFilenamePrefixBlacklist() {
1384 $blacklist = array();
1385 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1386 if( !$message->isDisabled() ) {
1387 $lines = explode( "\n", $message->plain() );
1388 foreach( $lines as $line ) {
1389 // Remove comment lines
1390 $comment = substr( trim( $line ), 0, 1 );
1391 if ( $comment == '#' ||
$comment == '' ) {
1394 // Remove additional comments after a prefix
1395 $comment = strpos( $line, '#' );
1396 if ( $comment > 0 ) {
1397 $line = substr( $line, 0, $comment-1 );
1399 $blacklist[] = trim( $line );
1406 * Gets image info about the file just uploaded.
1408 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1409 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1410 * with the appropriate format, presumably.
1412 * @param $result ApiResult:
1413 * @return Array: image info
1415 public function getImageInfo( $result ) {
1416 $file = $this->getLocalFile();
1417 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1418 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1419 if ( $file instanceof UploadStashFile
) {
1420 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1421 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1423 $imParam = ApiQueryImageInfo
::getPropertyNames();
1424 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1430 public function convertVerifyErrorToStatus( $error ) {
1431 $code = $error['status'];
1432 unset( $code['status'] );
1433 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1436 public static function getMaxUploadSize( $forType = null ) {
1437 global $wgMaxUploadSize;
1439 if ( is_array( $wgMaxUploadSize ) ) {
1440 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1441 return $wgMaxUploadSize[$forType];
1443 return $wgMaxUploadSize['*'];
1446 return intval( $wgMaxUploadSize );