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 * @author Brion Vibber
35 * @author Bryan Tong Minh
36 * @author Michael Dale
38 abstract class UploadBase
{
40 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
41 protected $mTitle = false, $mTitleError = 0;
42 protected $mFilteredName, $mFinalExtension;
43 protected $mLocalFile, $mFileSize, $mFileProps;
44 protected $mBlackListedExtensions;
45 protected $mJavaDetected, $mSVGNSError;
47 protected static $safeXmlEncodings = array(
58 const MIN_LENGTH_PARTNAME
= 4;
59 const ILLEGAL_FILENAME
= 5;
60 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
61 const FILETYPE_MISSING
= 8;
62 const FILETYPE_BADTYPE
= 9;
63 const VERIFICATION_ERROR
= 10;
64 const HOOK_ABORTED
= 11;
65 const FILE_TOO_LARGE
= 12;
66 const WINDOWS_NONASCII_FILENAME
= 13;
67 const FILENAME_TOO_LONG
= 14;
73 public function getVerificationErrorCode( $error ) {
74 $code_to_status = array(
75 self
::EMPTY_FILE
=> 'empty-file',
76 self
::FILE_TOO_LARGE
=> 'file-too-large',
77 self
::FILETYPE_MISSING
=> 'filetype-missing',
78 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
79 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
80 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
81 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
82 self
::VERIFICATION_ERROR
=> 'verification-error',
83 self
::HOOK_ABORTED
=> 'hookaborted',
84 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
85 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
87 if ( isset( $code_to_status[$error] ) ) {
88 return $code_to_status[$error];
91 return 'unknown-error';
95 * Returns true if uploads are enabled.
96 * Can be override by subclasses.
99 public static function isEnabled() {
100 global $wgEnableUploads;
102 if ( !$wgEnableUploads ) {
106 # Check php's file_uploads setting
107 return wfIsHHVM() ||
wfIniGetBool( 'file_uploads' );
111 * Returns true if the user can use this upload module or else a string
112 * identifying the missing permission.
113 * Can be overridden by subclasses.
116 * @return bool|string
118 public static function isAllowed( $user ) {
119 foreach ( array( 'upload', 'edit' ) as $permission ) {
120 if ( !$user->isAllowed( $permission ) ) {
128 // Upload handlers. Should probably just be a global.
129 private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
132 * Create a form of UploadBase depending on wpSourceType and initializes it
134 * @param WebRequest $request
135 * @param string|null $type
136 * @return null|UploadBase
138 public static function createFromRequest( &$request, $type = null ) {
139 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
145 // Get the upload class
146 $type = ucfirst( $type );
148 // Give hooks the chance to handle this request
150 Hooks
::run( 'UploadCreateFromRequest', array( $type, &$className ) );
151 if ( is_null( $className ) ) {
152 $className = 'UploadFrom' . $type;
153 wfDebug( __METHOD__
. ": class name: $className\n" );
154 if ( !in_array( $type, self
::$uploadHandlers ) ) {
159 // Check whether this upload class is enabled
160 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
164 // Check whether the request is valid
165 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
169 /** @var UploadBase $handler */
170 $handler = new $className;
172 $handler->initializeFromRequest( $request );
178 * Check whether a request if valid for this handler
179 * @param WebRequest $request
182 public static function isValidRequest( $request ) {
186 public function __construct() {
190 * Returns the upload type. Should be overridden by child classes
195 public function getSourceType() {
200 * Initialize the path information
201 * @param string $name The desired destination name
202 * @param string $tempPath The temporary path
203 * @param int $fileSize The file size
204 * @param bool $removeTempFile (false) remove the temporary file?
205 * @throws MWException
207 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
208 $this->mDesiredDestName
= $name;
209 if ( FileBackend
::isStoragePath( $tempPath ) ) {
210 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
212 $this->mTempPath
= $tempPath;
213 $this->mFileSize
= $fileSize;
214 $this->mRemoveTempFile
= $removeTempFile;
218 * Initialize from a WebRequest. Override this in a subclass.
220 * @param WebRequest $request
222 abstract public function initializeFromRequest( &$request );
225 * Fetch the file. Usually a no-op
228 public function fetchFile() {
229 return Status
::newGood();
233 * Return true if the file is empty
236 public function isEmptyFile() {
237 return empty( $this->mFileSize
);
241 * Return the file size
244 public function getFileSize() {
245 return $this->mFileSize
;
249 * Get the base 36 SHA1 of the file
252 public function getTempFileSha1Base36() {
253 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
257 * @param string $srcPath The source path
258 * @return string|bool The real path if it was a virtual URL Returns false on failure
260 function getRealPath( $srcPath ) {
261 $repo = RepoGroup
::singleton()->getLocalRepo();
262 if ( $repo->isVirtualUrl( $srcPath ) ) {
263 /** @todo Just make uploads work with storage paths UploadFromStash
264 * loads files via virtual URLs.
266 $tmpFile = $repo->getLocalCopy( $srcPath );
268 $tmpFile->bind( $this ); // keep alive with $this
270 $path = $tmpFile ?
$tmpFile->getPath() : false;
279 * Verify whether the upload is sane.
280 * @return mixed Const self::OK or else an array with error information
282 public function verifyUpload() {
285 * If there was no filename or a zero size given, give up quick.
287 if ( $this->isEmptyFile() ) {
288 return array( 'status' => self
::EMPTY_FILE
);
292 * Honor $wgMaxUploadSize
294 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
295 if ( $this->mFileSize
> $maxSize ) {
297 'status' => self
::FILE_TOO_LARGE
,
303 * Look at the contents of the file; if we can recognize the
304 * type but it's corrupt or data of the wrong type, we should
305 * probably not accept it.
307 $verification = $this->verifyFile();
308 if ( $verification !== true ) {
310 'status' => self
::VERIFICATION_ERROR
,
311 'details' => $verification
316 * Make sure this file can be created
318 $result = $this->validateName();
319 if ( $result !== true ) {
324 if ( !Hooks
::run( 'UploadVerification',
325 array( $this->mDestName
, $this->mTempPath
, &$error ) )
327 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
330 return array( 'status' => self
::OK
);
334 * Verify that the name is valid and, if necessary, that we can overwrite
336 * @return mixed True if valid, otherwise and array with 'status'
339 public function validateName() {
340 $nt = $this->getTitle();
341 if ( is_null( $nt ) ) {
342 $result = array( 'status' => $this->mTitleError
);
343 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
344 $result['filtered'] = $this->mFilteredName
;
346 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
347 $result['finalExt'] = $this->mFinalExtension
;
348 if ( count( $this->mBlackListedExtensions
) ) {
349 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
355 $this->mDestName
= $this->getLocalFile()->getName();
361 * Verify the MIME type.
363 * @note Only checks that it is not an evil MIME. The "does it have
364 * correct extension given its MIME type?" check is in verifyFile.
365 * in `verifyFile()` that MIME type and file extension correlate.
366 * @param string $mime Representing the MIME
367 * @return mixed True if the file is verified, an array otherwise
369 protected function verifyMimeType( $mime ) {
370 global $wgVerifyMimeType;
371 if ( $wgVerifyMimeType ) {
372 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
373 global $wgMimeTypeBlacklist;
374 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
375 return array( 'filetype-badmime', $mime );
378 # Check what Internet Explorer would detect
379 $fp = fopen( $this->mTempPath
, 'rb' );
380 $chunk = fread( $fp, 256 );
383 $magic = MimeMagic
::singleton();
384 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
385 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
386 foreach ( $ieTypes as $ieType ) {
387 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
388 return array( 'filetype-bad-ie-mime', $ieType );
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 $wgVerifyMimeType, $wgDisableUploadScriptChecks;
404 $status = $this->verifyPartialFile();
405 if ( $status !== true ) {
409 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
410 $mime = $this->mFileProps
['mime'];
412 if ( $wgVerifyMimeType ) {
413 # XXX: Missing extension will be caught by validateName() via getTitle()
414 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
415 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
419 # check for htmlish code and javascript
420 if ( !$wgDisableUploadScriptChecks ) {
421 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
422 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, false );
423 if ( $svgStatus !== false ) {
429 $handler = MediaHandler
::getHandler( $mime );
431 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
432 if ( !$handlerStatus->isOK() ) {
433 $errors = $handlerStatus->getErrorsArray();
435 return reset( $errors );
439 Hooks
::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
440 if ( $status !== true ) {
444 wfDebug( __METHOD__
. ": all clear; passing.\n" );
450 * A verification routine suitable for partial files
452 * Runs the blacklist checks, but not any checks that may
453 * assume the entire file is present.
455 * @return mixed True for valid or array with error message key.
457 protected function verifyPartialFile() {
458 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
460 # getTitle() sets some internal parameters like $this->mFinalExtension
463 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
465 # check MIME type, if desired
466 $mime = $this->mFileProps
['file-mime'];
467 $status = $this->verifyMimeType( $mime );
468 if ( $status !== true ) {
472 # check for htmlish code and javascript
473 if ( !$wgDisableUploadScriptChecks ) {
474 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
475 return array( 'uploadscripted' );
477 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
478 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, true );
479 if ( $svgStatus !== false ) {
485 # Check for Java applets, which if uploaded can bypass cross-site
487 if ( !$wgAllowJavaUploads ) {
488 $this->mJavaDetected
= false;
489 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
490 array( $this, 'zipEntryCallback' ) );
491 if ( !$zipStatus->isOK() ) {
492 $errors = $zipStatus->getErrorsArray();
493 $error = reset( $errors );
494 if ( $error[0] !== 'zip-wrong-format' ) {
498 if ( $this->mJavaDetected
) {
499 return array( 'uploadjava' );
503 # Scan the uploaded file for viruses
504 $virus = $this->detectVirus( $this->mTempPath
);
506 return array( 'uploadvirus', $virus );
513 * Callback for ZipDirectoryReader to detect Java class files.
515 * @param array $entry
517 function zipEntryCallback( $entry ) {
518 $names = array( $entry['name'] );
520 // If there is a null character, cut off the name at it, because JDK's
521 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
522 // were constructed which had ".class\0" followed by a string chosen to
523 // make the hash collide with the truncated name, that file could be
524 // returned in response to a request for the .class file.
525 $nullPos = strpos( $entry['name'], "\000" );
526 if ( $nullPos !== false ) {
527 $names[] = substr( $entry['name'], 0, $nullPos );
530 // If there is a trailing slash in the file name, we have to strip it,
531 // because that's what ZIP_GetEntry() does.
532 if ( preg_grep( '!\.class/?$!', $names ) ) {
533 $this->mJavaDetected
= true;
538 * Alias for verifyTitlePermissions. The function was originally
539 * 'verifyPermissions', but that suggests it's checking the user, when it's
540 * really checking the title + user combination.
542 * @param User $user User object to verify the permissions against
543 * @return mixed An array as returned by getUserPermissionsErrors or true
544 * in case the user has proper permissions.
546 public function verifyPermissions( $user ) {
547 return $this->verifyTitlePermissions( $user );
551 * Check whether the user can edit, upload and create the image. This
552 * checks only against the current title; if it returns errors, it may
553 * very well be that another title will not give errors. Therefore
554 * isAllowed() should be called as well for generic is-user-blocked or
555 * can-user-upload checking.
557 * @param User $user User object to verify the permissions against
558 * @return mixed An array as returned by getUserPermissionsErrors or true
559 * in case the user has proper permissions.
561 public function verifyTitlePermissions( $user ) {
563 * If the image is protected, non-sysop users won't be able
564 * to modify it by uploading a new revision.
566 $nt = $this->getTitle();
567 if ( is_null( $nt ) ) {
570 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
571 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
572 if ( !$nt->exists() ) {
573 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
575 $permErrorsCreate = array();
577 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
578 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
579 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
584 $overwriteError = $this->checkOverwrite( $user );
585 if ( $overwriteError !== true ) {
586 return array( $overwriteError );
593 * Check for non fatal problems with the file.
595 * This should not assume that mTempPath is set.
597 * @return array Array of warnings
599 public function checkWarnings() {
604 $localFile = $this->getLocalFile();
605 $localFile->load( File
::READ_LATEST
);
606 $filename = $localFile->getName();
609 * Check whether the resulting filename is different from the desired one,
610 * but ignore things like ucfirst() and spaces/underscore things
612 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
613 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
615 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
616 $warnings['badfilename'] = $filename;
617 // Debugging for bug 62241
618 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
619 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
622 // Check whether the file extension is on the unwanted list
623 global $wgCheckFileExtensions, $wgFileExtensions;
624 if ( $wgCheckFileExtensions ) {
625 $extensions = array_unique( $wgFileExtensions );
626 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
627 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
628 $wgLang->commaList( $extensions ), count( $extensions ) );
632 global $wgUploadSizeWarning;
633 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
634 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
637 if ( $this->mFileSize
== 0 ) {
638 $warnings['emptyfile'] = true;
641 $exists = self
::getExistsWarning( $localFile );
642 if ( $exists !== false ) {
643 $warnings['exists'] = $exists;
646 if ( $localFile->wasDeleted() && !$localFile->exists() ) {
647 $warnings['was-deleted'] = $filename;
650 // Check dupes against existing files
651 $hash = $this->getTempFileSha1Base36();
652 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
653 $title = $this->getTitle();
654 // Remove all matches against self
655 foreach ( $dupes as $key => $dupe ) {
656 if ( $title->equals( $dupe->getTitle() ) ) {
657 unset( $dupes[$key] );
661 $warnings['duplicate'] = $dupes;
664 // Check dupes against archives
665 $archivedFile = new ArchivedFile( null, 0, '', $hash );
666 if ( $archivedFile->getID() > 0 ) {
667 if ( $archivedFile->userCan( File
::DELETED_FILE
) ) {
668 $warnings['duplicate-archive'] = $archivedFile->getName();
670 $warnings['duplicate-archive'] = '';
678 * Really perform the upload. Stores the file in the local repo, watches
679 * if necessary and runs the UploadComplete hook.
681 * @param string $comment
682 * @param string $pageText
686 * @return Status Indicating the whether the upload succeeded.
688 public function performUpload( $comment, $pageText, $watch, $user ) {
689 $this->getLocalFile()->load( File
::READ_LATEST
);
691 $status = $this->getLocalFile()->upload(
701 if ( $status->isGood() ) {
703 WatchAction
::doWatch(
704 $this->getLocalFile()->getTitle(),
706 WatchedItem
::IGNORE_USER_RIGHTS
709 Hooks
::run( 'UploadComplete', array( &$this ) );
711 $this->postProcessUpload();
718 * Perform extra steps after a successful upload.
722 public function postProcessUpload() {
723 global $wgUploadThumbnailRenderMap;
727 $sizes = $wgUploadThumbnailRenderMap;
730 $file = $this->getLocalFile();
732 foreach ( $sizes as $size ) {
733 if ( $file->isVectorized() ||
$file->getWidth() > $size ) {
734 $jobs[] = new ThumbnailRenderJob(
736 array( 'transformParams' => array( 'width' => $size ) )
742 JobQueueGroup
::singleton()->push( $jobs );
747 * Returns the title of the file to be uploaded. Sets mTitleError in case
748 * the name was illegal.
750 * @return Title The title of the file or null in case the name was illegal
752 public function getTitle() {
753 if ( $this->mTitle
!== false ) {
754 return $this->mTitle
;
756 if ( !is_string( $this->mDesiredDestName
) ) {
757 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
758 $this->mTitle
= null;
760 return $this->mTitle
;
762 /* Assume that if a user specified File:Something.jpg, this is an error
763 * and that the namespace prefix needs to be stripped of.
765 $title = Title
::newFromText( $this->mDesiredDestName
);
766 if ( $title && $title->getNamespace() == NS_FILE
) {
767 $this->mFilteredName
= $title->getDBkey();
769 $this->mFilteredName
= $this->mDesiredDestName
;
772 # oi_archive_name is max 255 bytes, which include a timestamp and an
773 # exclamation mark, so restrict file name to 240 bytes.
774 if ( strlen( $this->mFilteredName
) > 240 ) {
775 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
776 $this->mTitle
= null;
778 return $this->mTitle
;
782 * Chop off any directories in the given filename. Then
783 * filter out illegal characters, and try to make a legible name
784 * out of it. We'll strip some silently that Title would die on.
786 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
787 /* Normalize to title form before we do any further processing */
788 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
789 if ( is_null( $nt ) ) {
790 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
791 $this->mTitle
= null;
793 return $this->mTitle
;
795 $this->mFilteredName
= $nt->getDBkey();
798 * We'll want to blacklist against *any* 'extension', and use
799 * only the final one for the whitelist.
801 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
803 if ( count( $ext ) ) {
804 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
806 $this->mFinalExtension
= '';
808 # No extension, try guessing one
809 $magic = MimeMagic
::singleton();
810 $mime = $magic->guessMimeType( $this->mTempPath
);
811 if ( $mime !== 'unknown/unknown' ) {
812 # Get a space separated list of extensions
813 $extList = $magic->getExtensionsForType( $mime );
815 # Set the extension to the canonical extension
816 $this->mFinalExtension
= strtok( $extList, ' ' );
818 # Fix up the other variables
819 $this->mFilteredName
.= ".{$this->mFinalExtension}";
820 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
821 $ext = array( $this->mFinalExtension
);
826 /* Don't allow users to override the blacklist (check file extension) */
827 global $wgCheckFileExtensions, $wgStrictFileExtensions;
828 global $wgFileExtensions, $wgFileBlacklist;
830 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
832 if ( $this->mFinalExtension
== '' ) {
833 $this->mTitleError
= self
::FILETYPE_MISSING
;
834 $this->mTitle
= null;
836 return $this->mTitle
;
837 } elseif ( $blackListedExtensions ||
838 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
839 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
841 $this->mBlackListedExtensions
= $blackListedExtensions;
842 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
843 $this->mTitle
= null;
845 return $this->mTitle
;
848 // Windows may be broken with special characters, see bug 1780
849 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
850 && !RepoGroup
::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
852 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
853 $this->mTitle
= null;
855 return $this->mTitle
;
858 # If there was more than one "extension", reassemble the base
859 # filename to prevent bogus complaints about length
860 if ( count( $ext ) > 1 ) {
861 $iterations = count( $ext ) - 1;
862 for ( $i = 0; $i < $iterations; $i++
) {
863 $partname .= '.' . $ext[$i];
867 if ( strlen( $partname ) < 1 ) {
868 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
869 $this->mTitle
= null;
871 return $this->mTitle
;
876 return $this->mTitle
;
880 * Return the local file and initializes if necessary.
882 * @return LocalFile|UploadStashFile|null
884 public function getLocalFile() {
885 if ( is_null( $this->mLocalFile
) ) {
886 $nt = $this->getTitle();
887 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
890 return $this->mLocalFile
;
894 * If the user does not supply all necessary information in the first upload
895 * form submission (either by accident or by design) then we may want to
896 * stash the file temporarily, get more information, and publish the file
899 * This method will stash a file in a temporary directory for later
900 * processing, and save the necessary descriptive info into the database.
901 * This method returns the file object, which also has a 'fileKey' property
902 * which can be passed through a form or API request to find this stashed
906 * @return UploadStashFile Stashed file
908 public function stashFile( User
$user = null ) {
909 // was stashSessionFile
911 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
912 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
913 $this->mLocalFile
= $file;
919 * Stash a file in a temporary directory, returning a key which can be used
920 * to find the file again. See stashFile().
922 * @return string File key
924 public function stashFileGetKey() {
925 return $this->stashFile()->getFileKey();
929 * alias for stashFileGetKey, for backwards compatibility
931 * @return string File key
933 public function stashSession() {
934 return $this->stashFileGetKey();
938 * If we've modified the upload file we need to manually remove it
939 * on exit to clean up.
941 public function cleanupTempFile() {
942 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
943 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
944 unlink( $this->mTempPath
);
948 public function getTempPath() {
949 return $this->mTempPath
;
953 * Split a file into a base name and all dot-delimited 'extensions'
954 * on the end. Some web server configurations will fall back to
955 * earlier pseudo-'extensions' to determine type and execute
956 * scripts, so the blacklist needs to check them all.
958 * @param string $filename
961 public static function splitExtensions( $filename ) {
962 $bits = explode( '.', $filename );
963 $basename = array_shift( $bits );
965 return array( $basename, $bits );
969 * Perform case-insensitive match against a list of file extensions.
970 * Returns true if the extension is in the list.
976 public static function checkFileExtension( $ext, $list ) {
977 return in_array( strtolower( $ext ), $list );
981 * Perform case-insensitive match against a list of file extensions.
982 * Returns an array of matching extensions.
988 public static function checkFileExtensionList( $ext, $list ) {
989 return array_intersect( array_map( 'strtolower', $ext ), $list );
993 * Checks if the MIME type of the uploaded file matches the file extension.
995 * @param string $mime The MIME type of the uploaded file
996 * @param string $extension The filename extension that the file is to be served with
999 public static function verifyExtension( $mime, $extension ) {
1000 $magic = MimeMagic
::singleton();
1002 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
1003 if ( !$magic->isRecognizableExtension( $extension ) ) {
1004 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
1005 "unrecognized extension '$extension', can't verify\n" );
1009 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
1010 "recognized extension '$extension', so probably invalid file\n" );
1016 $match = $magic->isMatchingExtension( $extension, $mime );
1018 if ( $match === null ) {
1019 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1020 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
1024 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
1028 } elseif ( $match === true ) {
1029 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
1031 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1035 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1042 * Heuristic for detecting files that *could* contain JavaScript instructions or
1043 * things that may look like HTML to a browser and are thus
1044 * potentially harmful. The present implementation will produce false
1045 * positives in some situations.
1047 * @param string $file Pathname to the temporary upload file
1048 * @param string $mime The MIME type of the file
1049 * @param string $extension The extension of the file
1050 * @return bool True if the file contains something looking like embedded scripts
1052 public static function detectScript( $file, $mime, $extension ) {
1053 global $wgAllowTitlesInSVG;
1055 # ugly hack: for text files, always look at the entire file.
1056 # For binary field, just check the first K.
1058 if ( strpos( $mime, 'text/' ) === 0 ) {
1059 $chunk = file_get_contents( $file );
1061 $fp = fopen( $file, 'rb' );
1062 $chunk = fread( $fp, 1024 );
1066 $chunk = strtolower( $chunk );
1072 # decode from UTF-16 if needed (could be used for obfuscation).
1073 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1075 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1082 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1085 $chunk = trim( $chunk );
1087 /** @todo FIXME: Convert from UTF-16 if necessary! */
1088 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1090 # check for HTML doctype
1091 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1095 // Some browsers will interpret obscure xml encodings as UTF-8, while
1096 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1097 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1098 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1104 * Internet Explorer for Windows performs some really stupid file type
1105 * autodetection which can cause it to interpret valid image files as HTML
1106 * and potentially execute JavaScript, creating a cross-site scripting
1109 * Apple's Safari browser also performs some unsafe file type autodetection
1110 * which can cause legitimate files to be interpreted as HTML if the
1111 * web server is not correctly configured to send the right content-type
1112 * (or if you're really uploading plain text and octet streams!)
1114 * Returns true if IE is likely to mistake the given file for HTML.
1115 * Also returns true if Safari would mistake the given file for HTML
1116 * when served with a generic content-type.
1122 '<html', # also in safari
1125 '<script', # also in safari
1129 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1133 foreach ( $tags as $tag ) {
1134 if ( false !== strpos( $chunk, $tag ) ) {
1135 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1142 * look for JavaScript
1145 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1146 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1148 # look for script-types
1149 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1150 wfDebug( __METHOD__
. ": found script types\n" );
1155 # look for html-style script-urls
1156 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1157 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1162 # look for css-style script-urls
1163 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1164 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1169 wfDebug( __METHOD__
. ": no scripts found\n" );
1175 * Check a whitelist of xml encodings that are known not to be interpreted differently
1176 * by the server's xml parser (expat) and some common browsers.
1178 * @param string $file Pathname to the temporary upload file
1179 * @return bool True if the file contains an encoding that could be misinterpreted
1181 public static function checkXMLEncodingMissmatch( $file ) {
1182 global $wgSVGMetadataCutoff;
1183 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1184 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1186 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1187 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1188 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1190 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1194 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1195 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1196 // bytes. There shouldn't be a legitimate reason for this to happen.
1197 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1200 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1201 // EBCDIC encoded XML
1202 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1207 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1208 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1209 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1210 foreach ( $attemptEncodings as $encoding ) {
1211 MediaWiki\
suppressWarnings();
1212 $str = iconv( $encoding, 'UTF-8', $contents );
1213 MediaWiki\restoreWarnings
();
1214 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1215 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1216 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1218 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1222 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1223 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1224 // bytes. There shouldn't be a legitimate reason for this to happen.
1225 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1235 * @param string $filename
1236 * @param bool $partial
1237 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1239 protected function detectScriptInSvg( $filename, $partial ) {
1240 $this->mSVGNSError
= false;
1241 $check = new XmlTypeCheck(
1243 array( $this, 'checkSvgScriptCallback' ),
1245 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1247 if ( $check->wellFormed
!== true ) {
1248 // Invalid xml (bug 58553)
1249 // But only when non-partial (bug 65724)
1250 return $partial ?
false : array( 'uploadinvalidxml' );
1251 } elseif ( $check->filterMatch
) {
1252 if ( $this->mSVGNSError
) {
1253 return array( 'uploadscriptednamespace', $this->mSVGNSError
);
1256 return $check->filterMatchType
;
1263 * Callback to filter SVG Processing Instructions.
1264 * @param string $target Processing instruction name
1265 * @param string $data Processing instruction attribute and value
1266 * @return bool (true if the filter identified something bad)
1268 public static function checkSvgPICallback( $target, $data ) {
1269 // Don't allow external stylesheets (bug 57550)
1270 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1271 return array( 'upload-scripted-pi-callback' );
1278 * @todo Replace this with a whitelist filter!
1279 * @param string $element
1280 * @param array $attribs
1283 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1285 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1287 // We specifically don't include:
1288 // http://www.w3.org/1999/xhtml (bug 60771)
1289 static $validNamespaces = array(
1292 'http://creativecommons.org/ns#',
1293 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1294 'http://ns.adobe.com/adobeillustrator/10.0/',
1295 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1296 'http://ns.adobe.com/extensibility/1.0/',
1297 'http://ns.adobe.com/flows/1.0/',
1298 'http://ns.adobe.com/illustrator/1.0/',
1299 'http://ns.adobe.com/imagereplacement/1.0/',
1300 'http://ns.adobe.com/pdf/1.3/',
1301 'http://ns.adobe.com/photoshop/1.0/',
1302 'http://ns.adobe.com/saveforweb/1.0/',
1303 'http://ns.adobe.com/variables/1.0/',
1304 'http://ns.adobe.com/xap/1.0/',
1305 'http://ns.adobe.com/xap/1.0/g/',
1306 'http://ns.adobe.com/xap/1.0/g/img/',
1307 'http://ns.adobe.com/xap/1.0/mm/',
1308 'http://ns.adobe.com/xap/1.0/rights/',
1309 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1310 'http://ns.adobe.com/xap/1.0/stype/font#',
1311 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1312 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1313 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1314 'http://ns.adobe.com/xap/1.0/t/pg/',
1315 'http://purl.org/dc/elements/1.1/',
1316 'http://purl.org/dc/elements/1.1',
1317 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1318 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1319 'http://taptrix.com/inkpad/svg_extensions',
1320 'http://web.resource.org/cc/',
1321 'http://www.freesoftware.fsf.org/bkchem/cdml',
1322 'http://www.inkscape.org/namespaces/inkscape',
1323 'http://www.opengis.net/gml',
1324 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1325 'http://www.w3.org/2000/svg',
1326 'http://www.w3.org/tr/rec-rdf-syntax/',
1329 if ( !in_array( $namespace, $validNamespaces ) ) {
1330 wfDebug( __METHOD__
. ": Non-svg namespace '$namespace' in uploaded file.\n" );
1331 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1332 $this->mSVGNSError
= $namespace;
1338 * check for elements that can contain javascript
1340 if ( $strippedElement == 'script' ) {
1341 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1343 return array( 'uploaded-script-svg', $strippedElement );
1346 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1347 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1348 if ( $strippedElement == 'handler' ) {
1349 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1351 return array( 'uploaded-script-svg', $strippedElement );
1354 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1355 if ( $strippedElement == 'stylesheet' ) {
1356 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1358 return array( 'uploaded-script-svg', $strippedElement );
1361 # Block iframes, in case they pass the namespace check
1362 if ( $strippedElement == 'iframe' ) {
1363 wfDebug( __METHOD__
. ": iframe in uploaded file.\n" );
1365 return array( 'uploaded-script-svg', $strippedElement );
1369 if ( $strippedElement == 'style'
1370 && self
::checkCssFragment( Sanitizer
::normalizeCss( $data ) )
1372 wfDebug( __METHOD__
. ": hostile css in style element.\n" );
1373 return array( 'uploaded-hostile-svg' );
1376 foreach ( $attribs as $attrib => $value ) {
1377 $stripped = $this->stripXmlNamespace( $attrib );
1378 $value = strtolower( $value );
1380 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1382 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1384 return array( 'uploaded-event-handler-on-svg', $attrib, $value );
1387 # href with non-local target (don't allow http://, javascript:, etc)
1388 if ( $stripped == 'href'
1389 && strpos( $value, 'data:' ) !== 0
1390 && strpos( $value, '#' ) !== 0
1392 if ( !( $strippedElement === 'a'
1393 && preg_match( '!^https?://!im', $value ) )
1395 wfDebug( __METHOD__
. ": Found href attribute <$strippedElement "
1396 . "'$attrib'='$value' in uploaded file.\n" );
1398 return array( 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value );
1402 # only allow data: targets that should be safe. This prevents vectors like,
1403 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1404 if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1405 // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1406 // @codingStandardsIgnoreStart Generic.Files.LineLength
1407 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1408 // @codingStandardsIgnoreEnd
1410 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1411 wfDebug( __METHOD__
. ": Found href to unwhitelisted data: uri "
1412 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1413 return array( 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value );
1417 # Change href with animate from (http://html5sec.org/#137).
1418 if ( $stripped === 'attributename'
1419 && $strippedElement === 'animate'
1420 && $this->stripXmlNamespace( $value ) == 'href'
1422 wfDebug( __METHOD__
. ": Found animate that might be changing href using from "
1423 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1425 return array( 'uploaded-animate-svg', $strippedElement, $attrib, $value );
1428 # use set/animate to add event-handler attribute to parent
1429 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' )
1430 && $stripped == 'attributename'
1431 && substr( $value, 0, 2 ) == 'on'
1433 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with "
1434 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1436 return array( 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value );
1439 # use set to add href attribute to parent element
1440 if ( $strippedElement == 'set'
1441 && $stripped == 'attributename'
1442 && strpos( $value, 'href' ) !== false
1444 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1446 return array( 'uploaded-setting-href-svg' );
1449 # use set to add a remote / data / script target to an element
1450 if ( $strippedElement == 'set'
1451 && $stripped == 'to'
1452 && preg_match( '!(http|https|data|script):!sim', $value )
1454 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1456 return array( 'uploaded-wrong-setting-svg', $value );
1459 # use handler attribute with remote / data / script
1460 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1461 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script "
1462 . "'$attrib'='$value' in uploaded file.\n" );
1464 return array( 'uploaded-setting-handler-svg', $attrib, $value );
1467 # use CSS styles to bring in remote code
1468 if ( $stripped == 'style'
1469 && self
::checkCssFragment( Sanitizer
::normalizeCss( $value ) )
1471 wfDebug( __METHOD__
. ": Found svg setting a style with "
1472 . "remote url '$attrib'='$value' in uploaded file.\n" );
1473 return array( 'uploaded-remote-url-svg', $attrib, $value );
1476 # Several attributes can include css, css character escaping isn't allowed
1477 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1478 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1479 if ( in_array( $stripped, $cssAttrs )
1480 && self
::checkCssFragment( $value )
1482 wfDebug( __METHOD__
. ": Found svg setting a style with "
1483 . "remote url '$attrib'='$value' in uploaded file.\n" );
1484 return array( 'uploaded-remote-url-svg', $attrib, $value );
1487 # image filters can pull in url, which could be svg that executes scripts
1488 if ( $strippedElement == 'image'
1489 && $stripped == 'filter'
1490 && preg_match( '!url\s*\(!sim', $value )
1492 wfDebug( __METHOD__
. ": Found image filter with url: "
1493 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1495 return array( 'uploaded-image-filter-svg', $strippedElement, $stripped, $value );
1499 return false; // No scripts detected
1503 * Check a block of CSS or CSS fragment for anything that looks like
1504 * it is bringing in remote code.
1505 * @param string $value a string of CSS
1506 * @param bool $propOnly only check css properties (start regex with :)
1507 * @return bool true if the CSS contains an illegal string, false if otherwise
1509 private static function checkCssFragment( $value ) {
1511 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1512 if ( stripos( $value, '@import' ) !== false ) {
1516 # We allow @font-face to embed fonts with data: urls, so we snip the string
1517 # 'url' out so this case won't match when we check for urls below
1518 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1519 $value = preg_replace( $pattern, '$1$2', $value );
1521 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1522 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1523 # Expression and -o-link don't seem to work either, but filtering them here in case.
1524 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1525 # but not local ones such as url("#..., url('#..., url(#....
1526 if ( preg_match( '!expression
1528 | -o-link-source\s*:
1529 | -o-replace\s*:!imx', $value ) ) {
1533 if ( preg_match_all(
1534 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1539 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1540 foreach ( $matches[1] as $match ) {
1541 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1547 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1555 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1556 * @param string $element
1557 * @return array Containing the namespace URI and prefix
1559 private static function splitXmlNamespace( $element ) {
1560 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1561 $parts = explode( ':', strtolower( $element ) );
1562 $name = array_pop( $parts );
1563 $ns = implode( ':', $parts );
1565 return array( $ns, $name );
1569 * @param string $name
1572 private function stripXmlNamespace( $name ) {
1573 // 'http://www.w3.org/2000/svg:script' -> 'script'
1574 $parts = explode( ':', strtolower( $name ) );
1576 return array_pop( $parts );
1580 * Generic wrapper function for a virus scanner program.
1581 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1582 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1584 * @param string $file Pathname to the temporary upload file
1585 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1586 * or a string containing feedback from the virus scanner if a virus was found.
1587 * If textual feedback is missing but a virus was found, this function returns true.
1589 public static function detectVirus( $file ) {
1590 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1592 if ( !$wgAntivirus ) {
1593 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1598 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1599 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1600 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1601 array( 'virus-badscanner', $wgAntivirus ) );
1603 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1606 # look up scanner configuration
1607 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1608 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1609 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1610 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1612 if ( strpos( $command, "%f" ) === false ) {
1613 # simple pattern: append file to scan
1614 $command .= " " . wfEscapeShellArg( $file );
1616 # complex pattern: replace "%f" with file to scan
1617 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1620 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1622 # execute virus scanner
1625 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1626 # that does not seem to be worth the pain.
1627 # Ask me (Duesentrieb) about it if it's ever needed.
1628 $output = wfShellExecWithStderr( $command, $exitCode );
1630 # map exit code to AV_xxx constants.
1631 $mappedCode = $exitCode;
1632 if ( $exitCodeMap ) {
1633 if ( isset( $exitCodeMap[$exitCode] ) ) {
1634 $mappedCode = $exitCodeMap[$exitCode];
1635 } elseif ( isset( $exitCodeMap["*"] ) ) {
1636 $mappedCode = $exitCodeMap["*"];
1640 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1641 * so we need the strict equalities === and thus can't use a switch here
1643 if ( $mappedCode === AV_SCAN_FAILED
) {
1644 # scan failed (code was mapped to false by $exitCodeMap)
1645 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1647 $output = $wgAntivirusRequired
1648 ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1650 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1651 # scan failed because filetype is unknown (probably imune)
1652 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1654 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1656 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1659 $output = trim( $output );
1662 $output = true; # if there's no output, return true
1663 } elseif ( $msgPattern ) {
1665 if ( preg_match( $msgPattern, $output, $groups ) ) {
1667 $output = $groups[1];
1672 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1679 * Check if there's an overwrite conflict and, if so, if restrictions
1680 * forbid this user from performing the upload.
1684 * @return mixed True on success, array on failure
1686 private function checkOverwrite( $user ) {
1687 // First check whether the local file can be overwritten
1688 $file = $this->getLocalFile();
1689 $file->load( File
::READ_LATEST
);
1690 if ( $file->exists() ) {
1691 if ( !self
::userCanReUpload( $user, $file ) ) {
1692 return array( 'fileexists-forbidden', $file->getName() );
1698 /* Check shared conflicts: if the local file does not exist, but
1699 * wfFindFile finds a file, it exists in a shared repository.
1701 $file = wfFindFile( $this->getTitle(), array( 'latest' => true ) );
1702 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1703 return array( 'fileexists-shared-forbidden', $file->getName() );
1710 * Check if a user is the last uploader
1716 public static function userCanReUpload( User
$user, File
$img ) {
1717 if ( $user->isAllowed( 'reupload' ) ) {
1718 return true; // non-conditional
1719 } elseif ( !$user->isAllowed( 'reupload-own' ) ) {
1723 if ( !( $img instanceof LocalFile
) ) {
1729 return $user->getId() == $img->getUser( 'id' );
1733 * Helper function that does various existence checks for a file.
1734 * The following checks are performed:
1736 * - Article with the same name as the file exists
1737 * - File exists with normalized extension
1738 * - The file looks like a thumbnail and the original exists
1740 * @param File $file The File object to check
1741 * @return mixed False if the file does not exists, else an array
1743 public static function getExistsWarning( $file ) {
1744 if ( $file->exists() ) {
1745 return array( 'warning' => 'exists', 'file' => $file );
1748 if ( $file->getTitle()->getArticleID() ) {
1749 return array( 'warning' => 'page-exists', 'file' => $file );
1752 if ( strpos( $file->getName(), '.' ) == false ) {
1753 $partname = $file->getName();
1756 $n = strrpos( $file->getName(), '.' );
1757 $extension = substr( $file->getName(), $n +
1 );
1758 $partname = substr( $file->getName(), 0, $n );
1760 $normalizedExtension = File
::normalizeExtension( $extension );
1762 if ( $normalizedExtension != $extension ) {
1763 // We're not using the normalized form of the extension.
1764 // Normal form is lowercase, using most common of alternate
1765 // extensions (eg 'jpg' rather than 'JPEG').
1767 // Check for another file using the normalized form...
1768 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1769 $file_lc = wfLocalFile( $nt_lc );
1771 if ( $file_lc->exists() ) {
1773 'warning' => 'exists-normalized',
1775 'normalizedFile' => $file_lc
1780 // Check for files with the same name but a different extension
1781 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1782 "{$partname}.", 1 );
1783 if ( count( $similarFiles ) ) {
1785 'warning' => 'exists-normalized',
1787 'normalizedFile' => $similarFiles[0],
1791 if ( self
::isThumbName( $file->getName() ) ) {
1792 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1793 $nt_thb = Title
::newFromText(
1794 substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension,
1797 $file_thb = wfLocalFile( $nt_thb );
1798 if ( $file_thb->exists() ) {
1800 'warning' => 'thumb',
1802 'thumbFile' => $file_thb
1805 // File does not exist, but we just don't like the name
1807 'warning' => 'thumb-name',
1809 'thumbFile' => $file_thb
1814 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1815 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1817 'warning' => 'bad-prefix',
1828 * Helper function that checks whether the filename looks like a thumbnail
1829 * @param string $filename
1832 public static function isThumbName( $filename ) {
1833 $n = strrpos( $filename, '.' );
1834 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1837 substr( $partname, 3, 3 ) == 'px-' ||
1838 substr( $partname, 2, 3 ) == 'px-'
1840 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1844 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1846 * @return array List of prefixes
1848 public static function getFilenamePrefixBlacklist() {
1849 $blacklist = array();
1850 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1851 if ( !$message->isDisabled() ) {
1852 $lines = explode( "\n", $message->plain() );
1853 foreach ( $lines as $line ) {
1854 // Remove comment lines
1855 $comment = substr( trim( $line ), 0, 1 );
1856 if ( $comment == '#' ||
$comment == '' ) {
1859 // Remove additional comments after a prefix
1860 $comment = strpos( $line, '#' );
1861 if ( $comment > 0 ) {
1862 $line = substr( $line, 0, $comment - 1 );
1864 $blacklist[] = trim( $line );
1872 * Gets image info about the file just uploaded.
1874 * Also has the effect of setting metadata to be an 'indexed tag name' in
1875 * returned API result if 'metadata' was requested. Oddly, we have to pass
1876 * the "result" object down just so it can do that with the appropriate
1877 * format, presumably.
1879 * @param ApiResult $result
1880 * @return array Image info
1882 public function getImageInfo( $result ) {
1883 $file = $this->getLocalFile();
1884 /** @todo This cries out for refactoring.
1885 * We really want to say $file->getAllInfo(); here.
1886 * Perhaps "info" methods should be moved into files, and the API should
1887 * just wrap them in queries.
1889 if ( $file instanceof UploadStashFile
) {
1890 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1891 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1893 $imParam = ApiQueryImageInfo
::getPropertyNames();
1894 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1901 * @param array $error
1904 public function convertVerifyErrorToStatus( $error ) {
1905 $code = $error['status'];
1906 unset( $code['status'] );
1908 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1912 * @param null|string $forType
1915 public static function getMaxUploadSize( $forType = null ) {
1916 global $wgMaxUploadSize;
1918 if ( is_array( $wgMaxUploadSize ) ) {
1919 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1920 return $wgMaxUploadSize[$forType];
1922 return $wgMaxUploadSize['*'];
1925 return intval( $wgMaxUploadSize );
1930 * Get the current status of a chunked upload (used for polling)
1932 * The value will be read from cache.
1935 * @param string $statusKey
1936 * @return Status[]|bool
1938 public static function getSessionStatus( User
$user, $statusKey ) {
1939 $key = wfMemcKey( 'uploadstatus', $user->getId() ?
: md5( $user->getName() ), $statusKey );
1941 return ObjectCache
::getMainStashInstance()->get( $key );
1945 * Set the current status of a chunked upload (used for polling)
1947 * The value will be set in cache for 1 day
1950 * @param string $statusKey
1951 * @param array|bool $value
1954 public static function setSessionStatus( User
$user, $statusKey, $value ) {
1955 $key = wfMemcKey( 'uploadstatus', $user->getId() ?
: md5( $user->getName() ), $statusKey );
1957 $cache = ObjectCache
::getMainStashInstance();
1958 if ( $value === false ) {
1959 $cache->delete( $key );
1961 $cache->set( $key, $value, 86400 );