3 * Base class for the backend of file upload.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Upload Upload related
31 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
32 * The frontends are formed by ApiUpload and SpecialUpload.
34 * See also includes/docs/upload.txt
36 * @author Brion Vibber
37 * @author Bryan Tong Minh
38 * @author Michael Dale
40 abstract class UploadBase
{
42 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
43 protected $mTitle = false, $mTitleError = 0;
44 protected $mFilteredName, $mFinalExtension;
45 protected $mLocalFile, $mFileSize, $mFileProps;
46 protected $mBlackListedExtensions;
47 protected $mJavaDetected;
52 const MIN_LENGTH_PARTNAME
= 4;
53 const ILLEGAL_FILENAME
= 5;
54 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
55 const FILETYPE_MISSING
= 8;
56 const FILETYPE_BADTYPE
= 9;
57 const VERIFICATION_ERROR
= 10;
59 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60 const UPLOAD_VERIFICATION_ERROR
= 11;
61 const HOOK_ABORTED
= 11;
62 const FILE_TOO_LARGE
= 12;
63 const WINDOWS_NONASCII_FILENAME
= 13;
64 const FILENAME_TOO_LONG
= 14;
66 const SESSION_STATUS_KEY
= 'wsUploadStatusData';
72 public function getVerificationErrorCode( $error ) {
73 $code_to_status = array(self
::EMPTY_FILE
=> 'empty-file',
74 self
::FILE_TOO_LARGE
=> 'file-too-large',
75 self
::FILETYPE_MISSING
=> 'filetype-missing',
76 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
77 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
78 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
79 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
80 self
::VERIFICATION_ERROR
=> 'verification-error',
81 self
::HOOK_ABORTED
=> 'hookaborted',
82 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
83 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
85 if( isset( $code_to_status[$error] ) ) {
86 return $code_to_status[$error];
89 return 'unknown-error';
93 * Returns true if uploads are enabled.
94 * Can be override by subclasses.
97 public static function isEnabled() {
98 global $wgEnableUploads;
100 if ( !$wgEnableUploads ) {
104 # Check php's file_uploads setting
105 return wfIsHipHop() ||
wfIniGetBool( 'file_uploads' );
109 * Returns true if the user can use this upload module or else a string
110 * identifying the missing permission.
111 * Can be overriden by subclasses.
116 public static function isAllowed( $user ) {
117 foreach ( array( 'upload', 'edit' ) as $permission ) {
118 if ( !$user->isAllowed( $permission ) ) {
125 // Upload handlers. Should probably just be a global.
126 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
129 * Create a form of UploadBase depending on wpSourceType and initializes it
131 * @param $request WebRequest
135 public static function createFromRequest( &$request, $type = null ) {
136 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
142 // Get the upload class
143 $type = ucfirst( $type );
145 // Give hooks the chance to handle this request
147 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
148 if ( is_null( $className ) ) {
149 $className = 'UploadFrom' . $type;
150 wfDebug( __METHOD__
. ": class name: $className\n" );
151 if( !in_array( $type, self
::$uploadHandlers ) ) {
156 // Check whether this upload class is enabled
157 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
161 // Check whether the request is valid
162 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
166 $handler = new $className;
168 $handler->initializeFromRequest( $request );
173 * Check whether a request if valid for this handler
177 public static function isValidRequest( $request ) {
181 public function __construct() {}
184 * Returns the upload type. Should be overridden by child classes
189 public function getSourceType() { return null; }
192 * Initialize the path information
193 * @param $name string the desired destination name
194 * @param $tempPath string the temporary path
195 * @param $fileSize int the file size
196 * @param $removeTempFile bool (false) remove the temporary file?
197 * @throws MWException
199 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
200 $this->mDesiredDestName
= $name;
201 if ( FileBackend
::isStoragePath( $tempPath ) ) {
202 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
204 $this->mTempPath
= $tempPath;
205 $this->mFileSize
= $fileSize;
206 $this->mRemoveTempFile
= $removeTempFile;
210 * Initialize from a WebRequest. Override this in a subclass.
212 abstract public function initializeFromRequest( &$request );
215 * Fetch the file. Usually a no-op
218 public function fetchFile() {
219 return Status
::newGood();
223 * Return true if the file is empty
226 public function isEmptyFile() {
227 return empty( $this->mFileSize
);
231 * Return the file size
234 public function getFileSize() {
235 return $this->mFileSize
;
239 * Get the base 36 SHA1 of the file
242 public function getTempFileSha1Base36() {
243 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
247 * @param $srcPath String: the source path
248 * @return string the real path if it was a virtual URL
250 function getRealPath( $srcPath ) {
251 wfProfileIn( __METHOD__
);
252 $repo = RepoGroup
::singleton()->getLocalRepo();
253 if ( $repo->isVirtualUrl( $srcPath ) ) {
254 // @TODO: just make uploads work with storage paths
255 // UploadFromStash loads files via virtuals URLs
256 $tmpFile = $repo->getLocalCopy( $srcPath );
257 $tmpFile->bind( $this ); // keep alive with $this
258 wfProfileOut( __METHOD__
);
259 return $tmpFile->getPath();
261 wfProfileOut( __METHOD__
);
266 * Verify whether the upload is sane.
267 * @return mixed self::OK or else an array with error information
269 public function verifyUpload() {
270 wfProfileIn( __METHOD__
);
273 * If there was no filename or a zero size given, give up quick.
275 if( $this->isEmptyFile() ) {
276 wfProfileOut( __METHOD__
);
277 return array( 'status' => self
::EMPTY_FILE
);
281 * Honor $wgMaxUploadSize
283 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
284 if( $this->mFileSize
> $maxSize ) {
285 wfProfileOut( __METHOD__
);
287 'status' => self
::FILE_TOO_LARGE
,
293 * Look at the contents of the file; if we can recognize the
294 * type but it's corrupt or data of the wrong type, we should
295 * probably not accept it.
297 $verification = $this->verifyFile();
298 if( $verification !== true ) {
299 wfProfileOut( __METHOD__
);
301 'status' => self
::VERIFICATION_ERROR
,
302 'details' => $verification
307 * Make sure this file can be created
309 $result = $this->validateName();
310 if( $result !== true ) {
311 wfProfileOut( __METHOD__
);
316 if( !wfRunHooks( 'UploadVerification',
317 array( $this->mDestName
, $this->mTempPath
, &$error ) ) )
319 wfProfileOut( __METHOD__
);
320 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
323 wfProfileOut( __METHOD__
);
324 return array( 'status' => self
::OK
);
328 * Verify that the name is valid and, if necessary, that we can overwrite
330 * @return mixed true if valid, otherwise and array with 'status'
333 protected function validateName() {
334 $nt = $this->getTitle();
335 if( is_null( $nt ) ) {
336 $result = array( 'status' => $this->mTitleError
);
337 if( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
338 $result['filtered'] = $this->mFilteredName
;
340 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
341 $result['finalExt'] = $this->mFinalExtension
;
342 if ( count( $this->mBlackListedExtensions
) ) {
343 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
348 $this->mDestName
= $this->getLocalFile()->getName();
354 * Verify the mime type
356 * @param $mime string representing the mime
357 * @return mixed true if the file is verified, an array otherwise
359 protected function verifyMimeType( $mime ) {
360 global $wgVerifyMimeType;
361 wfProfileIn( __METHOD__
);
362 if ( $wgVerifyMimeType ) {
363 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
364 global $wgMimeTypeBlacklist;
365 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
366 wfProfileOut( __METHOD__
);
367 return array( 'filetype-badmime', $mime );
370 # XXX: Missing extension will be caught by validateName() via getTitle()
371 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
372 wfProfileOut( __METHOD__
);
373 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
377 $fp = fopen( $this->mTempPath
, 'rb' );
378 $chunk = fread( $fp, 256 );
381 $magic = MimeMagic
::singleton();
382 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
383 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
384 foreach ( $ieTypes as $ieType ) {
385 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
386 wfProfileOut( __METHOD__
);
387 return array( 'filetype-bad-ie-mime', $ieType );
392 wfProfileOut( __METHOD__
);
397 * Verifies that it's ok to include the uploaded file
399 * @return mixed true of the file is verified, array otherwise.
401 protected function verifyFile() {
402 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
403 wfProfileIn( __METHOD__
);
405 # get the title, even though we are doing nothing with it, because
406 # we need to populate mFinalExtension
409 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
411 # check mime type, if desired
412 $mime = $this->mFileProps
['file-mime'];
413 $status = $this->verifyMimeType( $mime );
414 if ( $status !== true ) {
415 wfProfileOut( __METHOD__
);
419 # check for htmlish code and javascript
420 if ( !$wgDisableUploadScriptChecks ) {
421 if( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
422 wfProfileOut( __METHOD__
);
423 return array( 'uploadscripted' );
425 if( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
426 if( $this->detectScriptInSvg( $this->mTempPath
) ) {
427 wfProfileOut( __METHOD__
);
428 return array( 'uploadscripted' );
433 # Check for Java applets, which if uploaded can bypass cross-site
435 if ( !$wgAllowJavaUploads ) {
436 $this->mJavaDetected
= false;
437 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
438 array( $this, 'zipEntryCallback' ) );
439 if ( !$zipStatus->isOK() ) {
440 $errors = $zipStatus->getErrorsArray();
441 $error = reset( $errors );
442 if ( $error[0] !== 'zip-wrong-format' ) {
443 wfProfileOut( __METHOD__
);
447 if ( $this->mJavaDetected
) {
448 wfProfileOut( __METHOD__
);
449 return array( 'uploadjava' );
453 # Scan the uploaded file for viruses
454 $virus = $this->detectVirus( $this->mTempPath
);
456 wfProfileOut( __METHOD__
);
457 return array( 'uploadvirus', $virus );
460 $handler = MediaHandler
::getHandler( $mime );
462 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
463 if ( !$handlerStatus->isOK() ) {
464 $errors = $handlerStatus->getErrorsArray();
465 wfProfileOut( __METHOD__
);
466 return reset( $errors );
470 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
471 if ( $status !== true ) {
472 wfProfileOut( __METHOD__
);
476 wfDebug( __METHOD__
. ": all clear; passing.\n" );
477 wfProfileOut( __METHOD__
);
482 * Callback for ZipDirectoryReader to detect Java class files.
484 function zipEntryCallback( $entry ) {
485 $names = array( $entry['name'] );
487 // If there is a null character, cut off the name at it, because JDK's
488 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
489 // were constructed which had ".class\0" followed by a string chosen to
490 // make the hash collide with the truncated name, that file could be
491 // returned in response to a request for the .class file.
492 $nullPos = strpos( $entry['name'], "\000" );
493 if ( $nullPos !== false ) {
494 $names[] = substr( $entry['name'], 0, $nullPos );
497 // If there is a trailing slash in the file name, we have to strip it,
498 // because that's what ZIP_GetEntry() does.
499 if ( preg_grep( '!\.class/?$!', $names ) ) {
500 $this->mJavaDetected
= true;
505 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
506 * but that suggests it's checking the user, when it's really checking the title + user combination.
507 * @param $user User object to verify the permissions against
508 * @return mixed An array as returned by getUserPermissionsErrors or true
509 * in case the user has proper permissions.
511 public function verifyPermissions( $user ) {
512 return $this->verifyTitlePermissions( $user );
516 * Check whether the user can edit, upload and create the image. This
517 * checks only against the current title; if it returns errors, it may
518 * very well be that another title will not give errors. Therefore
519 * isAllowed() should be called as well for generic is-user-blocked or
520 * can-user-upload checking.
522 * @param $user User object to verify the permissions against
523 * @return mixed An array as returned by getUserPermissionsErrors or true
524 * in case the user has proper permissions.
526 public function verifyTitlePermissions( $user ) {
528 * If the image is protected, non-sysop users won't be able
529 * to modify it by uploading a new revision.
531 $nt = $this->getTitle();
532 if( is_null( $nt ) ) {
535 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
536 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
537 if ( !$nt->exists() ) {
538 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
540 $permErrorsCreate = array();
542 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
543 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
544 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
548 $overwriteError = $this->checkOverwrite( $user );
549 if ( $overwriteError !== true ) {
550 return array( $overwriteError );
557 * Check for non fatal problems with the file.
559 * This should not assume that mTempPath is set.
561 * @return Array of warnings
563 public function checkWarnings() {
565 wfProfileIn( __METHOD__
);
569 $localFile = $this->getLocalFile();
570 $filename = $localFile->getName();
573 * Check whether the resulting filename is different from the desired one,
574 * but ignore things like ucfirst() and spaces/underscore things
576 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
577 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
579 if( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
580 $warnings['badfilename'] = $filename;
583 // Check whether the file extension is on the unwanted list
584 global $wgCheckFileExtensions, $wgFileExtensions;
585 if ( $wgCheckFileExtensions ) {
586 if ( !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) ) {
587 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
588 $wgLang->commaList( $wgFileExtensions ), count( $wgFileExtensions ) );
592 global $wgUploadSizeWarning;
593 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
594 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
597 if ( $this->mFileSize
== 0 ) {
598 $warnings['emptyfile'] = true;
601 $exists = self
::getExistsWarning( $localFile );
602 if( $exists !== false ) {
603 $warnings['exists'] = $exists;
606 // Check dupes against existing files
607 $hash = $this->getTempFileSha1Base36();
608 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
609 $title = $this->getTitle();
610 // Remove all matches against self
611 foreach ( $dupes as $key => $dupe ) {
612 if( $title->equals( $dupe->getTitle() ) ) {
613 unset( $dupes[$key] );
617 $warnings['duplicate'] = $dupes;
620 // Check dupes against archives
621 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
622 if ( $archivedImage->getID() > 0 ) {
623 $warnings['duplicate-archive'] = $archivedImage->getName();
626 wfProfileOut( __METHOD__
);
631 * Really perform the upload. Stores the file in the local repo, watches
632 * if necessary and runs the UploadComplete hook.
639 * @return Status indicating the whether the upload succeeded.
641 public function performUpload( $comment, $pageText, $watch, $user ) {
642 wfProfileIn( __METHOD__
);
644 $status = $this->getLocalFile()->upload(
654 if( $status->isGood() ) {
656 $user->addWatch( $this->getLocalFile()->getTitle() );
658 wfRunHooks( 'UploadComplete', array( &$this ) );
661 wfProfileOut( __METHOD__
);
666 * Returns the title of the file to be uploaded. Sets mTitleError in case
667 * the name was illegal.
669 * @return Title The title of the file or null in case the name was illegal
671 public function getTitle() {
672 if ( $this->mTitle
!== false ) {
673 return $this->mTitle
;
676 /* Assume that if a user specified File:Something.jpg, this is an error
677 * and that the namespace prefix needs to be stripped of.
679 $title = Title
::newFromText( $this->mDesiredDestName
);
680 if ( $title && $title->getNamespace() == NS_FILE
) {
681 $this->mFilteredName
= $title->getDBkey();
683 $this->mFilteredName
= $this->mDesiredDestName
;
686 # oi_archive_name is max 255 bytes, which include a timestamp and an
687 # exclamation mark, so restrict file name to 240 bytes.
688 if ( strlen( $this->mFilteredName
) > 240 ) {
689 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
690 return $this->mTitle
= null;
694 * Chop off any directories in the given filename. Then
695 * filter out illegal characters, and try to make a legible name
696 * out of it. We'll strip some silently that Title would die on.
698 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
699 /* Normalize to title form before we do any further processing */
700 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
701 if( is_null( $nt ) ) {
702 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
703 return $this->mTitle
= null;
705 $this->mFilteredName
= $nt->getDBkey();
708 * We'll want to blacklist against *any* 'extension', and use
709 * only the final one for the whitelist.
711 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
713 if( count( $ext ) ) {
714 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
716 $this->mFinalExtension
= '';
718 # No extension, try guessing one
719 $magic = MimeMagic
::singleton();
720 $mime = $magic->guessMimeType( $this->mTempPath
);
721 if ( $mime !== 'unknown/unknown' ) {
722 # Get a space separated list of extensions
723 $extList = $magic->getExtensionsForType( $mime );
725 # Set the extension to the canonical extension
726 $this->mFinalExtension
= strtok( $extList, ' ' );
728 # Fix up the other variables
729 $this->mFilteredName
.= ".{$this->mFinalExtension}";
730 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
731 $ext = array( $this->mFinalExtension
);
736 /* Don't allow users to override the blacklist (check file extension) */
737 global $wgCheckFileExtensions, $wgStrictFileExtensions;
738 global $wgFileExtensions, $wgFileBlacklist;
740 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
742 if ( $this->mFinalExtension
== '' ) {
743 $this->mTitleError
= self
::FILETYPE_MISSING
;
744 return $this->mTitle
= null;
745 } elseif ( $blackListedExtensions ||
746 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
747 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
748 $this->mBlackListedExtensions
= $blackListedExtensions;
749 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
750 return $this->mTitle
= null;
753 // Windows may be broken with special characters, see bug XXX
754 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
755 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
756 return $this->mTitle
= null;
759 # If there was more than one "extension", reassemble the base
760 # filename to prevent bogus complaints about length
761 if( count( $ext ) > 1 ) {
762 for( $i = 0; $i < count( $ext ) - 1; $i++
) {
763 $partname .= '.' . $ext[$i];
767 if( strlen( $partname ) < 1 ) {
768 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
769 return $this->mTitle
= null;
772 return $this->mTitle
= $nt;
776 * Return the local file and initializes if necessary.
778 * @return LocalFile|null
780 public function getLocalFile() {
781 if( is_null( $this->mLocalFile
) ) {
782 $nt = $this->getTitle();
783 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
785 return $this->mLocalFile
;
789 * If the user does not supply all necessary information in the first upload form submission (either by accident or
790 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
792 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
794 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
795 * API request to find this stashed file again.
798 * @return UploadStashFile stashed file
800 public function stashFile( User
$user = null ) {
801 // was stashSessionFile
802 wfProfileIn( __METHOD__
);
804 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
805 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
806 $this->mLocalFile
= $file;
808 wfProfileOut( __METHOD__
);
813 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
815 * @return String: file key
817 public function stashFileGetKey() {
818 return $this->stashFile()->getFileKey();
822 * alias for stashFileGetKey, for backwards compatibility
824 * @return String: file key
826 public function stashSession() {
827 return $this->stashFileGetKey();
831 * If we've modified the upload file we need to manually remove it
832 * on exit to clean up.
834 public function cleanupTempFile() {
835 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
836 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
837 unlink( $this->mTempPath
);
841 public function getTempPath() {
842 return $this->mTempPath
;
846 * Split a file into a base name and all dot-delimited 'extensions'
847 * on the end. Some web server configurations will fall back to
848 * earlier pseudo-'extensions' to determine type and execute
849 * scripts, so the blacklist needs to check them all.
851 * @param $filename string
854 public static function splitExtensions( $filename ) {
855 $bits = explode( '.', $filename );
856 $basename = array_shift( $bits );
857 return array( $basename, $bits );
861 * Perform case-insensitive match against a list of file extensions.
862 * Returns true if the extension is in the list.
868 public static function checkFileExtension( $ext, $list ) {
869 return in_array( strtolower( $ext ), $list );
873 * Perform case-insensitive match against a list of file extensions.
874 * Returns an array of matching extensions.
880 public static function checkFileExtensionList( $ext, $list ) {
881 return array_intersect( array_map( 'strtolower', $ext ), $list );
885 * Checks if the mime type of the uploaded file matches the file extension.
887 * @param $mime String: the mime type of the uploaded file
888 * @param $extension String: the filename extension that the file is to be served with
891 public static function verifyExtension( $mime, $extension ) {
892 $magic = MimeMagic
::singleton();
894 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
895 if ( !$magic->isRecognizableExtension( $extension ) ) {
896 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
897 "unrecognized extension '$extension', can't verify\n" );
900 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; ".
901 "recognized extension '$extension', so probably invalid file\n" );
905 $match = $magic->isMatchingExtension( $extension, $mime );
907 if ( $match === null ) {
908 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
910 } elseif( $match === true ) {
911 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
913 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
917 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
923 * Heuristic for detecting files that *could* contain JavaScript instructions or
924 * things that may look like HTML to a browser and are thus
925 * potentially harmful. The present implementation will produce false
926 * positives in some situations.
928 * @param $file String: pathname to the temporary upload file
929 * @param $mime String: the mime type of the file
930 * @param $extension String: the extension of the file
931 * @return Boolean: true if the file contains something looking like embedded scripts
933 public static function detectScript( $file, $mime, $extension ) {
934 global $wgAllowTitlesInSVG;
935 wfProfileIn( __METHOD__
);
937 # ugly hack: for text files, always look at the entire file.
938 # For binary field, just check the first K.
940 if( strpos( $mime, 'text/' ) === 0 ) {
941 $chunk = file_get_contents( $file );
943 $fp = fopen( $file, 'rb' );
944 $chunk = fread( $fp, 1024 );
948 $chunk = strtolower( $chunk );
951 wfProfileOut( __METHOD__
);
955 # decode from UTF-16 if needed (could be used for obfuscation).
956 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
958 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
965 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
968 $chunk = trim( $chunk );
970 # @todo FIXME: Convert from UTF-16 if necessarry!
971 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
973 # check for HTML doctype
974 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
975 wfProfileOut( __METHOD__
);
980 * Internet Explorer for Windows performs some really stupid file type
981 * autodetection which can cause it to interpret valid image files as HTML
982 * and potentially execute JavaScript, creating a cross-site scripting
985 * Apple's Safari browser also performs some unsafe file type autodetection
986 * which can cause legitimate files to be interpreted as HTML if the
987 * web server is not correctly configured to send the right content-type
988 * (or if you're really uploading plain text and octet streams!)
990 * Returns true if IE is likely to mistake the given file for HTML.
991 * Also returns true if Safari would mistake the given file for HTML
992 * when served with a generic content-type.
998 '<html', #also in safari
1001 '<script', #also in safari
1005 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1009 foreach( $tags as $tag ) {
1010 if( false !== strpos( $chunk, $tag ) ) {
1011 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1012 wfProfileOut( __METHOD__
);
1018 * look for JavaScript
1021 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1022 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1024 # look for script-types
1025 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1026 wfDebug( __METHOD__
. ": found script types\n" );
1027 wfProfileOut( __METHOD__
);
1031 # look for html-style script-urls
1032 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1033 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1034 wfProfileOut( __METHOD__
);
1038 # look for css-style script-urls
1039 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1040 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1041 wfProfileOut( __METHOD__
);
1045 wfDebug( __METHOD__
. ": no scripts found\n" );
1046 wfProfileOut( __METHOD__
);
1051 * @param $filename string
1054 protected function detectScriptInSvg( $filename ) {
1055 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1056 return $check->filterMatch
;
1060 * @todo Replace this with a whitelist filter!
1061 * @param $element string
1062 * @param $attribs array
1065 public function checkSvgScriptCallback( $element, $attribs ) {
1066 $strippedElement = $this->stripXmlNamespace( $element );
1069 * check for elements that can contain javascript
1071 if( $strippedElement == 'script' ) {
1072 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1076 # 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>
1077 if( $strippedElement == 'handler' ) {
1078 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1082 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1083 if( $strippedElement == 'stylesheet' ) {
1084 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1088 foreach( $attribs as $attrib => $value ) {
1089 $stripped = $this->stripXmlNamespace( $attrib );
1090 $value = strtolower( $value );
1092 if( substr( $stripped, 0, 2 ) == 'on' ) {
1093 wfDebug( __METHOD__
. ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1097 # href with javascript target
1098 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1099 wfDebug( __METHOD__
. ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1103 # href with embeded svg as target
1104 if( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1105 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1109 # href with embeded (text/xml) svg as target
1110 if( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1111 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1115 # use set/animate to add event-handler attribute to parent
1116 if( ( $strippedElement == 'set' ||
$strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1117 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1121 # use set to add href attribute to parent element
1122 if( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1123 wfDebug( __METHOD__
. ": Found svg setting href attibute '$value' in uploaded file.\n" );
1127 # use set to add a remote / data / script target to an element
1128 if( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1129 wfDebug( __METHOD__
. ": Found svg setting attibute to '$value' in uploaded file.\n" );
1133 # use handler attribute with remote / data / script
1134 if( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1135 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1139 # use CSS styles to bring in remote code
1140 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1141 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 ) ) {
1142 foreach ( $matches[1] as $match ) {
1143 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1144 wfDebug( __METHOD__
. ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1150 # image filters can pull in url, which could be svg that executes scripts
1151 if( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1152 wfDebug( __METHOD__
. ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1158 return false; //No scripts detected
1162 * @param $name string
1165 private function stripXmlNamespace( $name ) {
1166 // 'http://www.w3.org/2000/svg:script' -> 'script'
1167 $parts = explode( ':', strtolower( $name ) );
1168 return array_pop( $parts );
1172 * Generic wrapper function for a virus scanner program.
1173 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1174 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1176 * @param $file String: pathname to the temporary upload file
1177 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1178 * or a string containing feedback from the virus scanner if a virus was found.
1179 * If textual feedback is missing but a virus was found, this function returns true.
1181 public static function detectVirus( $file ) {
1182 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1183 wfProfileIn( __METHOD__
);
1185 if ( !$wgAntivirus ) {
1186 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1187 wfProfileOut( __METHOD__
);
1191 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1192 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1193 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1194 array( 'virus-badscanner', $wgAntivirus ) );
1195 wfProfileOut( __METHOD__
);
1196 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1199 # look up scanner configuration
1200 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1201 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1202 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1203 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1205 if ( strpos( $command, "%f" ) === false ) {
1206 # simple pattern: append file to scan
1207 $command .= " " . wfEscapeShellArg( $file );
1209 # complex pattern: replace "%f" with file to scan
1210 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1213 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1215 # execute virus scanner
1218 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1219 # that does not seem to be worth the pain.
1220 # Ask me (Duesentrieb) about it if it's ever needed.
1221 $output = wfShellExec( "$command 2>&1", $exitCode );
1223 # map exit code to AV_xxx constants.
1224 $mappedCode = $exitCode;
1225 if ( $exitCodeMap ) {
1226 if ( isset( $exitCodeMap[$exitCode] ) ) {
1227 $mappedCode = $exitCodeMap[$exitCode];
1228 } elseif ( isset( $exitCodeMap["*"] ) ) {
1229 $mappedCode = $exitCodeMap["*"];
1233 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1234 * so we need the strict equalities === and thus can't use a switch here
1236 if ( $mappedCode === AV_SCAN_FAILED
) {
1237 # scan failed (code was mapped to false by $exitCodeMap)
1238 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1240 $output = $wgAntivirusRequired ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1241 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1242 # scan failed because filetype is unknown (probably imune)
1243 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1245 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1247 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1250 $output = trim( $output );
1253 $output = true; #if there's no output, return true
1254 } elseif ( $msgPattern ) {
1256 if ( preg_match( $msgPattern, $output, $groups ) ) {
1258 $output = $groups[1];
1263 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1266 wfProfileOut( __METHOD__
);
1271 * Check if there's an overwrite conflict and, if so, if restrictions
1272 * forbid this user from performing the upload.
1276 * @return mixed true on success, array on failure
1278 private function checkOverwrite( $user ) {
1279 // First check whether the local file can be overwritten
1280 $file = $this->getLocalFile();
1281 if( $file->exists() ) {
1282 if( !self
::userCanReUpload( $user, $file ) ) {
1283 return array( 'fileexists-forbidden', $file->getName() );
1289 /* Check shared conflicts: if the local file does not exist, but
1290 * wfFindFile finds a file, it exists in a shared repository.
1292 $file = wfFindFile( $this->getTitle() );
1293 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1294 return array( 'fileexists-shared-forbidden', $file->getName() );
1301 * Check if a user is the last uploader
1303 * @param $user User object
1304 * @param $img String: image name
1307 public static function userCanReUpload( User
$user, $img ) {
1308 if( $user->isAllowed( 'reupload' ) ) {
1309 return true; // non-conditional
1311 if( !$user->isAllowed( 'reupload-own' ) ) {
1314 if( is_string( $img ) ) {
1315 $img = wfLocalFile( $img );
1317 if ( !( $img instanceof LocalFile
) ) {
1321 return $user->getId() == $img->getUser( 'id' );
1325 * Helper function that does various existence checks for a file.
1326 * The following checks are performed:
1328 * - Article with the same name as the file exists
1329 * - File exists with normalized extension
1330 * - The file looks like a thumbnail and the original exists
1332 * @param $file File The File object to check
1333 * @return mixed False if the file does not exists, else an array
1335 public static function getExistsWarning( $file ) {
1336 if( $file->exists() ) {
1337 return array( 'warning' => 'exists', 'file' => $file );
1340 if( $file->getTitle()->getArticleID() ) {
1341 return array( 'warning' => 'page-exists', 'file' => $file );
1344 if ( $file->wasDeleted() && !$file->exists() ) {
1345 return array( 'warning' => 'was-deleted', 'file' => $file );
1348 if( strpos( $file->getName(), '.' ) == false ) {
1349 $partname = $file->getName();
1352 $n = strrpos( $file->getName(), '.' );
1353 $extension = substr( $file->getName(), $n +
1 );
1354 $partname = substr( $file->getName(), 0, $n );
1356 $normalizedExtension = File
::normalizeExtension( $extension );
1358 if ( $normalizedExtension != $extension ) {
1359 // We're not using the normalized form of the extension.
1360 // Normal form is lowercase, using most common of alternate
1361 // extensions (eg 'jpg' rather than 'JPEG').
1363 // Check for another file using the normalized form...
1364 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1365 $file_lc = wfLocalFile( $nt_lc );
1367 if( $file_lc->exists() ) {
1369 'warning' => 'exists-normalized',
1371 'normalizedFile' => $file_lc
1376 // Check for files with the same name but a different extension
1377 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1378 "{$partname}.", 1 );
1379 if ( count( $similarFiles ) ) {
1381 'warning' => 'exists-normalized',
1383 'normalizedFile' => $similarFiles[0],
1387 if ( self
::isThumbName( $file->getName() ) ) {
1388 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1389 $nt_thb = Title
::newFromText( substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1390 $file_thb = wfLocalFile( $nt_thb );
1391 if( $file_thb->exists() ) {
1393 'warning' => 'thumb',
1395 'thumbFile' => $file_thb
1398 // File does not exist, but we just don't like the name
1400 'warning' => 'thumb-name',
1402 'thumbFile' => $file_thb
1407 foreach( self
::getFilenamePrefixBlacklist() as $prefix ) {
1408 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1410 'warning' => 'bad-prefix',
1421 * Helper function that checks whether the filename looks like a thumbnail
1422 * @param $filename string
1425 public static function isThumbName( $filename ) {
1426 $n = strrpos( $filename, '.' );
1427 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1429 substr( $partname, 3, 3 ) == 'px-' ||
1430 substr( $partname, 2, 3 ) == 'px-'
1432 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1436 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1438 * @return array list of prefixes
1440 public static function getFilenamePrefixBlacklist() {
1441 $blacklist = array();
1442 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1443 if( !$message->isDisabled() ) {
1444 $lines = explode( "\n", $message->plain() );
1445 foreach( $lines as $line ) {
1446 // Remove comment lines
1447 $comment = substr( trim( $line ), 0, 1 );
1448 if ( $comment == '#' ||
$comment == '' ) {
1451 // Remove additional comments after a prefix
1452 $comment = strpos( $line, '#' );
1453 if ( $comment > 0 ) {
1454 $line = substr( $line, 0, $comment-1 );
1456 $blacklist[] = trim( $line );
1463 * Gets image info about the file just uploaded.
1465 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1466 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1467 * with the appropriate format, presumably.
1469 * @param $result ApiResult:
1470 * @return Array: image info
1472 public function getImageInfo( $result ) {
1473 $file = $this->getLocalFile();
1474 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1475 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1476 if ( $file instanceof UploadStashFile
) {
1477 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1478 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1480 $imParam = ApiQueryImageInfo
::getPropertyNames();
1481 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1487 * @param $error array
1490 public function convertVerifyErrorToStatus( $error ) {
1491 $code = $error['status'];
1492 unset( $code['status'] );
1493 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1497 * @param $forType null|string
1500 public static function getMaxUploadSize( $forType = null ) {
1501 global $wgMaxUploadSize;
1503 if ( is_array( $wgMaxUploadSize ) ) {
1504 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1505 return $wgMaxUploadSize[$forType];
1507 return $wgMaxUploadSize['*'];
1510 return intval( $wgMaxUploadSize );
1515 * Get the current status of a chunked upload (used for polling).
1516 * The status will be read from the *current* user session.
1517 * @param $statusKey string
1518 * @return Array|bool
1520 public static function getSessionStatus( $statusKey ) {
1521 return isset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] )
1522 ?
$_SESSION[self
::SESSION_STATUS_KEY
][$statusKey]
1527 * Set the current status of a chunked upload (used for polling).
1528 * The status will be stored in the *current* user session.
1529 * @param $statusKey string
1530 * @param $value array|false
1533 public static function setSessionStatus( $statusKey, $value ) {
1534 if ( $value === false ) {
1535 unset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] );
1537 $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] = $value;