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;
65 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
66 const UPLOAD_VERIFICATION_ERROR
= 11;
67 const HOOK_ABORTED
= 11;
68 const FILE_TOO_LARGE
= 12;
69 const WINDOWS_NONASCII_FILENAME
= 13;
70 const FILENAME_TOO_LONG
= 14;
72 const SESSION_STATUS_KEY
= 'wsUploadStatusData';
78 public function getVerificationErrorCode( $error ) {
79 $code_to_status = array(
80 self
::EMPTY_FILE
=> 'empty-file',
81 self
::FILE_TOO_LARGE
=> 'file-too-large',
82 self
::FILETYPE_MISSING
=> 'filetype-missing',
83 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
84 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
85 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
86 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
87 self
::VERIFICATION_ERROR
=> 'verification-error',
88 self
::HOOK_ABORTED
=> 'hookaborted',
89 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
90 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
92 if ( isset( $code_to_status[$error] ) ) {
93 return $code_to_status[$error];
96 return 'unknown-error';
100 * Returns true if uploads are enabled.
101 * Can be override by subclasses.
104 public static function isEnabled() {
105 global $wgEnableUploads;
107 if ( !$wgEnableUploads ) {
111 # Check php's file_uploads setting
112 return wfIsHHVM() ||
wfIniGetBool( 'file_uploads' );
116 * Returns true if the user can use this upload module or else a string
117 * identifying the missing permission.
118 * Can be overridden by subclasses.
121 * @return bool|string
123 public static function isAllowed( $user ) {
124 foreach ( array( 'upload', 'edit' ) as $permission ) {
125 if ( !$user->isAllowed( $permission ) ) {
133 // Upload handlers. Should probably just be a global.
134 private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
137 * Create a form of UploadBase depending on wpSourceType and initializes it
139 * @param WebRequest $request
140 * @param string|null $type
141 * @return null|UploadBase
143 public static function createFromRequest( &$request, $type = null ) {
144 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
150 // Get the upload class
151 $type = ucfirst( $type );
153 // Give hooks the chance to handle this request
155 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
156 if ( is_null( $className ) ) {
157 $className = 'UploadFrom' . $type;
158 wfDebug( __METHOD__
. ": class name: $className\n" );
159 if ( !in_array( $type, self
::$uploadHandlers ) ) {
164 // Check whether this upload class is enabled
165 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
169 // Check whether the request is valid
170 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
174 /** @var UploadBase $handler */
175 $handler = new $className;
177 $handler->initializeFromRequest( $request );
183 * Check whether a request if valid for this handler
184 * @param WebRequest $request
187 public static function isValidRequest( $request ) {
191 public function __construct() {
195 * Returns the upload type. Should be overridden by child classes
200 public function getSourceType() {
205 * Initialize the path information
206 * @param string $name The desired destination name
207 * @param string $tempPath The temporary path
208 * @param int $fileSize The file size
209 * @param bool $removeTempFile (false) remove the temporary file?
210 * @throws MWException
212 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
213 $this->mDesiredDestName
= $name;
214 if ( FileBackend
::isStoragePath( $tempPath ) ) {
215 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
217 $this->mTempPath
= $tempPath;
218 $this->mFileSize
= $fileSize;
219 $this->mRemoveTempFile
= $removeTempFile;
223 * Initialize from a WebRequest. Override this in a subclass.
225 * @param WebRequest $request
227 abstract public function initializeFromRequest( &$request );
230 * Fetch the file. Usually a no-op
233 public function fetchFile() {
234 return Status
::newGood();
238 * Return true if the file is empty
241 public function isEmptyFile() {
242 return empty( $this->mFileSize
);
246 * Return the file size
249 public function getFileSize() {
250 return $this->mFileSize
;
254 * Get the base 36 SHA1 of the file
257 public function getTempFileSha1Base36() {
258 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
262 * @param string $srcPath The source path
263 * @return string|bool The real path if it was a virtual URL Returns false on failure
265 function getRealPath( $srcPath ) {
266 wfProfileIn( __METHOD__
);
267 $repo = RepoGroup
::singleton()->getLocalRepo();
268 if ( $repo->isVirtualUrl( $srcPath ) ) {
269 /** @todo Just make uploads work with storage paths UploadFromStash
270 * loads files via virtual URLs.
272 $tmpFile = $repo->getLocalCopy( $srcPath );
274 $tmpFile->bind( $this ); // keep alive with $this
276 $path = $tmpFile ?
$tmpFile->getPath() : false;
280 wfProfileOut( __METHOD__
);
286 * Verify whether the upload is sane.
287 * @return mixed Const self::OK or else an array with error information
289 public function verifyUpload() {
290 wfProfileIn( __METHOD__
);
293 * If there was no filename or a zero size given, give up quick.
295 if ( $this->isEmptyFile() ) {
296 wfProfileOut( __METHOD__
);
298 return array( 'status' => self
::EMPTY_FILE
);
302 * Honor $wgMaxUploadSize
304 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
305 if ( $this->mFileSize
> $maxSize ) {
306 wfProfileOut( __METHOD__
);
309 'status' => self
::FILE_TOO_LARGE
,
315 * Look at the contents of the file; if we can recognize the
316 * type but it's corrupt or data of the wrong type, we should
317 * probably not accept it.
319 $verification = $this->verifyFile();
320 if ( $verification !== true ) {
321 wfProfileOut( __METHOD__
);
324 'status' => self
::VERIFICATION_ERROR
,
325 'details' => $verification
330 * Make sure this file can be created
332 $result = $this->validateName();
333 if ( $result !== true ) {
334 wfProfileOut( __METHOD__
);
340 if ( !wfRunHooks( 'UploadVerification',
341 array( $this->mDestName
, $this->mTempPath
, &$error ) )
343 wfProfileOut( __METHOD__
);
345 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
348 wfProfileOut( __METHOD__
);
350 return array( 'status' => self
::OK
);
354 * Verify that the name is valid and, if necessary, that we can overwrite
356 * @return mixed True if valid, otherwise and array with 'status'
359 public function validateName() {
360 $nt = $this->getTitle();
361 if ( is_null( $nt ) ) {
362 $result = array( 'status' => $this->mTitleError
);
363 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
364 $result['filtered'] = $this->mFilteredName
;
366 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
367 $result['finalExt'] = $this->mFinalExtension
;
368 if ( count( $this->mBlackListedExtensions
) ) {
369 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
375 $this->mDestName
= $this->getLocalFile()->getName();
381 * Verify the MIME type.
383 * @note Only checks that it is not an evil MIME. The "does it have
384 * correct extension given its MIME type?" check is in verifyFile.
385 * in `verifyFile()` that MIME type and file extension correlate.
386 * @param string $mime Representing the MIME
387 * @return mixed True if the file is verified, an array otherwise
389 protected function verifyMimeType( $mime ) {
390 global $wgVerifyMimeType;
391 wfProfileIn( __METHOD__
);
392 if ( $wgVerifyMimeType ) {
393 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
394 global $wgMimeTypeBlacklist;
395 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
396 wfProfileOut( __METHOD__
);
398 return array( 'filetype-badmime', $mime );
401 # Check what Internet Explorer would detect
402 $fp = fopen( $this->mTempPath
, 'rb' );
403 $chunk = fread( $fp, 256 );
406 $magic = MimeMagic
::singleton();
407 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
408 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
409 foreach ( $ieTypes as $ieType ) {
410 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
411 wfProfileOut( __METHOD__
);
413 return array( 'filetype-bad-ie-mime', $ieType );
418 wfProfileOut( __METHOD__
);
424 * Verifies that it's ok to include the uploaded file
426 * @return mixed True of the file is verified, array otherwise.
428 protected function verifyFile() {
429 global $wgVerifyMimeType;
430 wfProfileIn( __METHOD__
);
432 $status = $this->verifyPartialFile();
433 if ( $status !== true ) {
434 wfProfileOut( __METHOD__
);
439 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
440 $mime = $this->mFileProps
['mime'];
442 if ( $wgVerifyMimeType ) {
443 # XXX: Missing extension will be caught by validateName() via getTitle()
444 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
445 wfProfileOut( __METHOD__
);
447 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
451 $handler = MediaHandler
::getHandler( $mime );
453 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
454 if ( !$handlerStatus->isOK() ) {
455 $errors = $handlerStatus->getErrorsArray();
456 wfProfileOut( __METHOD__
);
458 return reset( $errors );
462 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
463 if ( $status !== true ) {
464 wfProfileOut( __METHOD__
);
469 wfDebug( __METHOD__
. ": all clear; passing.\n" );
470 wfProfileOut( __METHOD__
);
476 * A verification routine suitable for partial files
478 * Runs the blacklist checks, but not any checks that may
479 * assume the entire file is present.
481 * @return mixed True for valid or array with error message key.
483 protected function verifyPartialFile() {
484 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
485 wfProfileIn( __METHOD__
);
487 # getTitle() sets some internal parameters like $this->mFinalExtension
490 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
492 # check MIME type, if desired
493 $mime = $this->mFileProps
['file-mime'];
494 $status = $this->verifyMimeType( $mime );
495 if ( $status !== true ) {
496 wfProfileOut( __METHOD__
);
501 # check for htmlish code and javascript
502 if ( !$wgDisableUploadScriptChecks ) {
503 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
504 wfProfileOut( __METHOD__
);
506 return array( 'uploadscripted' );
508 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
509 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
);
510 if ( $svgStatus !== false ) {
511 wfProfileOut( __METHOD__
);
518 # Check for Java applets, which if uploaded can bypass cross-site
520 if ( !$wgAllowJavaUploads ) {
521 $this->mJavaDetected
= false;
522 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
523 array( $this, 'zipEntryCallback' ) );
524 if ( !$zipStatus->isOK() ) {
525 $errors = $zipStatus->getErrorsArray();
526 $error = reset( $errors );
527 if ( $error[0] !== 'zip-wrong-format' ) {
528 wfProfileOut( __METHOD__
);
533 if ( $this->mJavaDetected
) {
534 wfProfileOut( __METHOD__
);
536 return array( 'uploadjava' );
540 # Scan the uploaded file for viruses
541 $virus = $this->detectVirus( $this->mTempPath
);
543 wfProfileOut( __METHOD__
);
545 return array( 'uploadvirus', $virus );
548 wfProfileOut( __METHOD__
);
554 * Callback for ZipDirectoryReader to detect Java class files.
556 * @param array $entry
558 function zipEntryCallback( $entry ) {
559 $names = array( $entry['name'] );
561 // If there is a null character, cut off the name at it, because JDK's
562 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
563 // were constructed which had ".class\0" followed by a string chosen to
564 // make the hash collide with the truncated name, that file could be
565 // returned in response to a request for the .class file.
566 $nullPos = strpos( $entry['name'], "\000" );
567 if ( $nullPos !== false ) {
568 $names[] = substr( $entry['name'], 0, $nullPos );
571 // If there is a trailing slash in the file name, we have to strip it,
572 // because that's what ZIP_GetEntry() does.
573 if ( preg_grep( '!\.class/?$!', $names ) ) {
574 $this->mJavaDetected
= true;
579 * Alias for verifyTitlePermissions. The function was originally
580 * 'verifyPermissions', but that suggests it's checking the user, when it's
581 * really checking the title + user combination.
583 * @param User $user User object to verify the permissions against
584 * @return mixed An array as returned by getUserPermissionsErrors or true
585 * in case the user has proper permissions.
587 public function verifyPermissions( $user ) {
588 return $this->verifyTitlePermissions( $user );
592 * Check whether the user can edit, upload and create the image. This
593 * checks only against the current title; if it returns errors, it may
594 * very well be that another title will not give errors. Therefore
595 * isAllowed() should be called as well for generic is-user-blocked or
596 * can-user-upload checking.
598 * @param User $user User object to verify the permissions against
599 * @return mixed An array as returned by getUserPermissionsErrors or true
600 * in case the user has proper permissions.
602 public function verifyTitlePermissions( $user ) {
604 * If the image is protected, non-sysop users won't be able
605 * to modify it by uploading a new revision.
607 $nt = $this->getTitle();
608 if ( is_null( $nt ) ) {
611 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
612 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
613 if ( !$nt->exists() ) {
614 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
616 $permErrorsCreate = array();
618 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
619 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
620 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
625 $overwriteError = $this->checkOverwrite( $user );
626 if ( $overwriteError !== true ) {
627 return array( $overwriteError );
634 * Check for non fatal problems with the file.
636 * This should not assume that mTempPath is set.
638 * @return array Array of warnings
640 public function checkWarnings() {
642 wfProfileIn( __METHOD__
);
646 $localFile = $this->getLocalFile();
647 $filename = $localFile->getName();
650 * Check whether the resulting filename is different from the desired one,
651 * but ignore things like ucfirst() and spaces/underscore things
653 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
654 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
656 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
657 $warnings['badfilename'] = $filename;
658 // Debugging for bug 62241
659 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
660 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
663 // Check whether the file extension is on the unwanted list
664 global $wgCheckFileExtensions, $wgFileExtensions;
665 if ( $wgCheckFileExtensions ) {
666 $extensions = array_unique( $wgFileExtensions );
667 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
668 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
669 $wgLang->commaList( $extensions ), count( $extensions ) );
673 global $wgUploadSizeWarning;
674 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
675 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
678 if ( $this->mFileSize
== 0 ) {
679 $warnings['emptyfile'] = true;
682 $exists = self
::getExistsWarning( $localFile );
683 if ( $exists !== false ) {
684 $warnings['exists'] = $exists;
687 // Check dupes against existing files
688 $hash = $this->getTempFileSha1Base36();
689 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
690 $title = $this->getTitle();
691 // Remove all matches against self
692 foreach ( $dupes as $key => $dupe ) {
693 if ( $title->equals( $dupe->getTitle() ) ) {
694 unset( $dupes[$key] );
698 $warnings['duplicate'] = $dupes;
701 // Check dupes against archives
702 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
703 if ( $archivedImage->getID() > 0 ) {
704 if ( $archivedImage->userCan( File
::DELETED_FILE
) ) {
705 $warnings['duplicate-archive'] = $archivedImage->getName();
707 $warnings['duplicate-archive'] = '';
711 wfProfileOut( __METHOD__
);
717 * Really perform the upload. Stores the file in the local repo, watches
718 * if necessary and runs the UploadComplete hook.
720 * @param string $comment
721 * @param string $pageText
725 * @return Status Indicating the whether the upload succeeded.
727 public function performUpload( $comment, $pageText, $watch, $user ) {
728 wfProfileIn( __METHOD__
);
730 $status = $this->getLocalFile()->upload(
740 if ( $status->isGood() ) {
742 WatchAction
::doWatch(
743 $this->getLocalFile()->getTitle(),
745 WatchedItem
::IGNORE_USER_RIGHTS
748 wfRunHooks( 'UploadComplete', array( &$this ) );
750 $this->postProcessUpload();
753 wfProfileOut( __METHOD__
);
759 * Perform extra steps after a successful upload.
763 public function postProcessUpload() {
764 global $wgUploadThumbnailRenderMap;
768 $sizes = $wgUploadThumbnailRenderMap;
771 foreach ( $sizes as $size ) {
772 $jobs[] = new ThumbnailRenderJob( $this->getLocalFile()->getTitle(), array(
773 'transformParams' => array( 'width' => $size ),
777 JobQueueGroup
::singleton()->push( $jobs );
781 * Returns the title of the file to be uploaded. Sets mTitleError in case
782 * the name was illegal.
784 * @return Title The title of the file or null in case the name was illegal
786 public function getTitle() {
787 if ( $this->mTitle
!== false ) {
788 return $this->mTitle
;
790 /* Assume that if a user specified File:Something.jpg, this is an error
791 * and that the namespace prefix needs to be stripped of.
793 $title = Title
::newFromText( $this->mDesiredDestName
);
794 if ( $title && $title->getNamespace() == NS_FILE
) {
795 $this->mFilteredName
= $title->getDBkey();
797 $this->mFilteredName
= $this->mDesiredDestName
;
800 # oi_archive_name is max 255 bytes, which include a timestamp and an
801 # exclamation mark, so restrict file name to 240 bytes.
802 if ( strlen( $this->mFilteredName
) > 240 ) {
803 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
804 $this->mTitle
= null;
806 return $this->mTitle
;
810 * Chop off any directories in the given filename. Then
811 * filter out illegal characters, and try to make a legible name
812 * out of it. We'll strip some silently that Title would die on.
814 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
815 /* Normalize to title form before we do any further processing */
816 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
817 if ( is_null( $nt ) ) {
818 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
819 $this->mTitle
= null;
821 return $this->mTitle
;
823 $this->mFilteredName
= $nt->getDBkey();
826 * We'll want to blacklist against *any* 'extension', and use
827 * only the final one for the whitelist.
829 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
831 if ( count( $ext ) ) {
832 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
834 $this->mFinalExtension
= '';
836 # No extension, try guessing one
837 $magic = MimeMagic
::singleton();
838 $mime = $magic->guessMimeType( $this->mTempPath
);
839 if ( $mime !== 'unknown/unknown' ) {
840 # Get a space separated list of extensions
841 $extList = $magic->getExtensionsForType( $mime );
843 # Set the extension to the canonical extension
844 $this->mFinalExtension
= strtok( $extList, ' ' );
846 # Fix up the other variables
847 $this->mFilteredName
.= ".{$this->mFinalExtension}";
848 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
849 $ext = array( $this->mFinalExtension
);
854 /* Don't allow users to override the blacklist (check file extension) */
855 global $wgCheckFileExtensions, $wgStrictFileExtensions;
856 global $wgFileExtensions, $wgFileBlacklist;
858 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
860 if ( $this->mFinalExtension
== '' ) {
861 $this->mTitleError
= self
::FILETYPE_MISSING
;
862 $this->mTitle
= null;
864 return $this->mTitle
;
865 } elseif ( $blackListedExtensions ||
866 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
867 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
869 $this->mBlackListedExtensions
= $blackListedExtensions;
870 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
871 $this->mTitle
= null;
873 return $this->mTitle
;
876 // Windows may be broken with special characters, see bug 1780
877 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
878 && !RepoGroup
::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
880 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
881 $this->mTitle
= null;
883 return $this->mTitle
;
886 # If there was more than one "extension", reassemble the base
887 # filename to prevent bogus complaints about length
888 if ( count( $ext ) > 1 ) {
889 $iterations = count( $ext ) - 1;
890 for ( $i = 0; $i < $iterations; $i++
) {
891 $partname .= '.' . $ext[$i];
895 if ( strlen( $partname ) < 1 ) {
896 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
897 $this->mTitle
= null;
899 return $this->mTitle
;
904 return $this->mTitle
;
908 * Return the local file and initializes if necessary.
910 * @return LocalFile|UploadStashFile|null
912 public function getLocalFile() {
913 if ( is_null( $this->mLocalFile
) ) {
914 $nt = $this->getTitle();
915 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
918 return $this->mLocalFile
;
922 * If the user does not supply all necessary information in the first upload
923 * form submission (either by accident or by design) then we may want to
924 * stash the file temporarily, get more information, and publish the file
927 * This method will stash a file in a temporary directory for later
928 * processing, and save the necessary descriptive info into the database.
929 * This method returns the file object, which also has a 'fileKey' property
930 * which can be passed through a form or API request to find this stashed
934 * @return UploadStashFile Stashed file
936 public function stashFile( User
$user = null ) {
937 // was stashSessionFile
938 wfProfileIn( __METHOD__
);
940 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
941 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
942 $this->mLocalFile
= $file;
944 wfProfileOut( __METHOD__
);
950 * Stash a file in a temporary directory, returning a key which can be used
951 * to find the file again. See stashFile().
953 * @return string File key
955 public function stashFileGetKey() {
956 return $this->stashFile()->getFileKey();
960 * alias for stashFileGetKey, for backwards compatibility
962 * @return string File key
964 public function stashSession() {
965 return $this->stashFileGetKey();
969 * If we've modified the upload file we need to manually remove it
970 * on exit to clean up.
972 public function cleanupTempFile() {
973 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
974 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
975 unlink( $this->mTempPath
);
979 public function getTempPath() {
980 return $this->mTempPath
;
984 * Split a file into a base name and all dot-delimited 'extensions'
985 * on the end. Some web server configurations will fall back to
986 * earlier pseudo-'extensions' to determine type and execute
987 * scripts, so the blacklist needs to check them all.
989 * @param string $filename
992 public static function splitExtensions( $filename ) {
993 $bits = explode( '.', $filename );
994 $basename = array_shift( $bits );
996 return array( $basename, $bits );
1000 * Perform case-insensitive match against a list of file extensions.
1001 * Returns true if the extension is in the list.
1003 * @param string $ext
1004 * @param array $list
1007 public static function checkFileExtension( $ext, $list ) {
1008 return in_array( strtolower( $ext ), $list );
1012 * Perform case-insensitive match against a list of file extensions.
1013 * Returns an array of matching extensions.
1016 * @param array $list
1019 public static function checkFileExtensionList( $ext, $list ) {
1020 return array_intersect( array_map( 'strtolower', $ext ), $list );
1024 * Checks if the MIME type of the uploaded file matches the file extension.
1026 * @param string $mime The MIME type of the uploaded file
1027 * @param string $extension The filename extension that the file is to be served with
1030 public static function verifyExtension( $mime, $extension ) {
1031 $magic = MimeMagic
::singleton();
1033 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
1034 if ( !$magic->isRecognizableExtension( $extension ) ) {
1035 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
1036 "unrecognized extension '$extension', can't verify\n" );
1040 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
1041 "recognized extension '$extension', so probably invalid file\n" );
1047 $match = $magic->isMatchingExtension( $extension, $mime );
1049 if ( $match === null ) {
1050 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1051 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
1055 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
1059 } elseif ( $match === true ) {
1060 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
1062 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1066 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1073 * Heuristic for detecting files that *could* contain JavaScript instructions or
1074 * things that may look like HTML to a browser and are thus
1075 * potentially harmful. The present implementation will produce false
1076 * positives in some situations.
1078 * @param string $file Pathname to the temporary upload file
1079 * @param string $mime The MIME type of the file
1080 * @param string $extension The extension of the file
1081 * @return bool True if the file contains something looking like embedded scripts
1083 public static function detectScript( $file, $mime, $extension ) {
1084 global $wgAllowTitlesInSVG;
1085 wfProfileIn( __METHOD__
);
1087 # ugly hack: for text files, always look at the entire file.
1088 # For binary field, just check the first K.
1090 if ( strpos( $mime, 'text/' ) === 0 ) {
1091 $chunk = file_get_contents( $file );
1093 $fp = fopen( $file, 'rb' );
1094 $chunk = fread( $fp, 1024 );
1098 $chunk = strtolower( $chunk );
1101 wfProfileOut( __METHOD__
);
1106 # decode from UTF-16 if needed (could be used for obfuscation).
1107 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1109 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1116 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1119 $chunk = trim( $chunk );
1121 /** @todo FIXME: Convert from UTF-16 if necessary! */
1122 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1124 # check for HTML doctype
1125 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1126 wfProfileOut( __METHOD__
);
1131 // Some browsers will interpret obscure xml encodings as UTF-8, while
1132 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1133 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1134 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1135 wfProfileOut( __METHOD__
);
1142 * Internet Explorer for Windows performs some really stupid file type
1143 * autodetection which can cause it to interpret valid image files as HTML
1144 * and potentially execute JavaScript, creating a cross-site scripting
1147 * Apple's Safari browser also performs some unsafe file type autodetection
1148 * which can cause legitimate files to be interpreted as HTML if the
1149 * web server is not correctly configured to send the right content-type
1150 * (or if you're really uploading plain text and octet streams!)
1152 * Returns true if IE is likely to mistake the given file for HTML.
1153 * Also returns true if Safari would mistake the given file for HTML
1154 * when served with a generic content-type.
1160 '<html', #also in safari
1163 '<script', #also in safari
1167 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1171 foreach ( $tags as $tag ) {
1172 if ( false !== strpos( $chunk, $tag ) ) {
1173 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1174 wfProfileOut( __METHOD__
);
1181 * look for JavaScript
1184 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1185 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1187 # look for script-types
1188 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1189 wfDebug( __METHOD__
. ": found script types\n" );
1190 wfProfileOut( __METHOD__
);
1195 # look for html-style script-urls
1196 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1197 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1198 wfProfileOut( __METHOD__
);
1203 # look for css-style script-urls
1204 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1205 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1206 wfProfileOut( __METHOD__
);
1211 wfDebug( __METHOD__
. ": no scripts found\n" );
1212 wfProfileOut( __METHOD__
);
1218 * Check a whitelist of xml encodings that are known not to be interpreted differently
1219 * by the server's xml parser (expat) and some common browsers.
1221 * @param string $file Pathname to the temporary upload file
1222 * @return bool True if the file contains an encoding that could be misinterpreted
1224 public static function checkXMLEncodingMissmatch( $file ) {
1225 global $wgSVGMetadataCutoff;
1226 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1227 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1229 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1230 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1231 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1233 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1237 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1238 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1239 // bytes. There shouldn't be a legitimate reason for this to happen.
1240 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1243 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1244 // EBCDIC encoded XML
1245 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1250 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1251 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1252 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1253 foreach ( $attemptEncodings as $encoding ) {
1254 wfSuppressWarnings();
1255 $str = iconv( $encoding, 'UTF-8', $contents );
1256 wfRestoreWarnings();
1257 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1258 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1259 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1261 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1265 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1266 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1267 // bytes. There shouldn't be a legitimate reason for this to happen.
1268 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1278 * @param string $filename
1279 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1281 protected function detectScriptInSvg( $filename ) {
1282 $this->mSVGNSError
= false;
1283 $check = new XmlTypeCheck(
1285 array( $this, 'checkSvgScriptCallback' ),
1287 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1289 if ( $check->wellFormed
!== true ) {
1290 // Invalid xml (bug 58553)
1291 return array( 'uploadinvalidxml' );
1292 } elseif ( $check->filterMatch
) {
1293 if ( $this->mSVGNSError
) {
1294 return array( 'uploadscriptednamespace', $this->mSVGNSError
);
1297 return array( 'uploadscripted' );
1304 * Callback to filter SVG Processing Instructions.
1305 * @param string $target Processing instruction name
1306 * @param string $data Processing instruction attribute and value
1307 * @return bool (true if the filter identified something bad)
1309 public static function checkSvgPICallback( $target, $data ) {
1310 // Don't allow external stylesheets (bug 57550)
1311 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1319 * @todo Replace this with a whitelist filter!
1320 * @param string $element
1321 * @param array $attribs
1324 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1326 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1328 // We specifically don't include:
1329 // http://www.w3.org/1999/xhtml (bug 60771)
1330 static $validNamespaces = array(
1333 'http://creativecommons.org/ns#',
1334 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1335 'http://ns.adobe.com/adobeillustrator/10.0/',
1336 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1337 'http://ns.adobe.com/extensibility/1.0/',
1338 'http://ns.adobe.com/flows/1.0/',
1339 'http://ns.adobe.com/illustrator/1.0/',
1340 'http://ns.adobe.com/imagereplacement/1.0/',
1341 'http://ns.adobe.com/pdf/1.3/',
1342 'http://ns.adobe.com/photoshop/1.0/',
1343 'http://ns.adobe.com/saveforweb/1.0/',
1344 'http://ns.adobe.com/variables/1.0/',
1345 'http://ns.adobe.com/xap/1.0/',
1346 'http://ns.adobe.com/xap/1.0/g/',
1347 'http://ns.adobe.com/xap/1.0/g/img/',
1348 'http://ns.adobe.com/xap/1.0/mm/',
1349 'http://ns.adobe.com/xap/1.0/rights/',
1350 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1351 'http://ns.adobe.com/xap/1.0/stype/font#',
1352 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1353 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1354 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1355 'http://ns.adobe.com/xap/1.0/t/pg/',
1356 'http://purl.org/dc/elements/1.1/',
1357 'http://purl.org/dc/elements/1.1',
1358 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1359 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1360 'http://taptrix.com/inkpad/svg_extensions',
1361 'http://web.resource.org/cc/',
1362 'http://www.freesoftware.fsf.org/bkchem/cdml',
1363 'http://www.inkscape.org/namespaces/inkscape',
1364 'http://www.opengis.net/gml',
1365 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1366 'http://www.w3.org/2000/svg',
1367 'http://www.w3.org/tr/rec-rdf-syntax/',
1370 if ( !in_array( $namespace, $validNamespaces ) ) {
1371 wfDebug( __METHOD__
. ": Non-svg namespace '$namespace' in uploaded file.\n" );
1372 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1373 $this->mSVGNSError
= $namespace;
1379 * check for elements that can contain javascript
1381 if ( $strippedElement == 'script' ) {
1382 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1387 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1388 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1389 if ( $strippedElement == 'handler' ) {
1390 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1395 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1396 if ( $strippedElement == 'stylesheet' ) {
1397 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1402 # Block iframes, in case they pass the namespace check
1403 if ( $strippedElement == 'iframe' ) {
1404 wfDebug( __METHOD__
. ": iframe in uploaded file.\n" );
1410 if ( $strippedElement == 'style'
1411 && self
::checkCssFragment( Sanitizer
::normalizeCss( $data ) )
1413 wfDebug( __METHOD__
. ": hostile css in style element.\n" );
1417 foreach ( $attribs as $attrib => $value ) {
1418 $stripped = $this->stripXmlNamespace( $attrib );
1419 $value = strtolower( $value );
1421 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1423 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1428 # href with non-local target (don't allow http://, javascript:, etc)
1429 if ( $stripped == 'href'
1430 && strpos( $value, 'data:' ) !== 0
1431 && strpos( $value, '#' ) !== 0
1433 if ( !( $strippedElement === 'a'
1434 && preg_match( '!^https?://!im', $value ) )
1436 wfDebug( __METHOD__
. ": Found href attribute <$strippedElement "
1437 . "'$attrib'='$value' in uploaded file.\n" );
1443 # href with embedded svg as target
1444 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1445 wfDebug( __METHOD__
. ": Found href to embedded svg "
1446 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1451 # href with embedded (text/xml) svg as target
1452 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1453 wfDebug( __METHOD__
. ": Found href to embedded svg "
1454 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1459 # Change href with animate from (http://html5sec.org/#137). This doesn't seem
1460 # possible without embedding the svg, but filter here in case.
1461 if ( $stripped == 'from'
1462 && $strippedElement === 'animate'
1463 && !preg_match( '!^https?://!im', $value )
1465 wfDebug( __METHOD__
. ": Found animate that might be changing href using from "
1466 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1471 # use set/animate to add event-handler attribute to parent
1472 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' )
1473 && $stripped == 'attributename'
1474 && substr( $value, 0, 2 ) == 'on'
1476 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with "
1477 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1482 # use set to add href attribute to parent element
1483 if ( $strippedElement == 'set'
1484 && $stripped == 'attributename'
1485 && strpos( $value, 'href' ) !== false
1487 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1492 # use set to add a remote / data / script target to an element
1493 if ( $strippedElement == 'set'
1494 && $stripped == 'to'
1495 && preg_match( '!(http|https|data|script):!sim', $value )
1497 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1502 # use handler attribute with remote / data / script
1503 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1504 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script "
1505 . "'$attrib'='$value' in uploaded file.\n" );
1510 # use CSS styles to bring in remote code
1511 if ( $stripped == 'style'
1512 && self
::checkCssFragment( Sanitizer
::normalizeCss( $value ) )
1514 wfDebug( __METHOD__
. ": Found svg setting a style with "
1515 . "remote url '$attrib'='$value' in uploaded file.\n" );
1519 # Several attributes can include css, css character escaping isn't allowed
1520 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1521 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1522 if ( in_array( $stripped, $cssAttrs )
1523 && self
::checkCssFragment( $value )
1525 wfDebug( __METHOD__
. ": Found svg setting a style with "
1526 . "remote url '$attrib'='$value' in uploaded file.\n" );
1530 # image filters can pull in url, which could be svg that executes scripts
1531 if ( $strippedElement == 'image'
1532 && $stripped == 'filter'
1533 && preg_match( '!url\s*\(!sim', $value )
1535 wfDebug( __METHOD__
. ": Found image filter with url: "
1536 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1542 return false; //No scripts detected
1546 * Check a block of CSS or CSS fragment for anything that looks like
1547 * it is bringing in remote code.
1548 * @param string $value a string of CSS
1549 * @param bool $propOnly only check css properties (start regex with :)
1550 * @return bool true if the CSS contains an illegal string, false if otherwise
1552 private static function checkCssFragment( $value ) {
1554 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1555 if ( strpos( $value, '@import' ) !== false ) {
1559 # We allow @font-face to embed fonts with data: urls, so we snip the string
1560 # 'url' out so this case won't match when we check for urls below
1561 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1562 $value = preg_replace( $pattern, '$1$2', $value );
1564 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1565 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1566 # Expression and -o-link don't seem to work either, but filtering them here in case.
1567 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1568 # but not local ones such as url("#..., url('#..., url(#....
1569 if ( preg_match( '!expression
1571 | -o-link-source\s*:
1572 | -o-replace\s*:!imx', $value ) ) {
1576 if ( preg_match_all(
1577 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1582 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1583 foreach ( $matches[1] as $match ) {
1584 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1590 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1598 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1599 * @param string $element
1600 * @return array Containing the namespace URI and prefix
1602 private static function splitXmlNamespace( $element ) {
1603 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1604 $parts = explode( ':', strtolower( $element ) );
1605 $name = array_pop( $parts );
1606 $ns = implode( ':', $parts );
1608 return array( $ns, $name );
1612 * @param string $name
1615 private function stripXmlNamespace( $name ) {
1616 // 'http://www.w3.org/2000/svg:script' -> 'script'
1617 $parts = explode( ':', strtolower( $name ) );
1619 return array_pop( $parts );
1623 * Generic wrapper function for a virus scanner program.
1624 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1625 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1627 * @param string $file Pathname to the temporary upload file
1628 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1629 * or a string containing feedback from the virus scanner if a virus was found.
1630 * If textual feedback is missing but a virus was found, this function returns true.
1632 public static function detectVirus( $file ) {
1633 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1634 wfProfileIn( __METHOD__
);
1636 if ( !$wgAntivirus ) {
1637 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1638 wfProfileOut( __METHOD__
);
1643 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1644 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1645 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1646 array( 'virus-badscanner', $wgAntivirus ) );
1647 wfProfileOut( __METHOD__
);
1649 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1652 # look up scanner configuration
1653 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1654 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1655 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1656 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1658 if ( strpos( $command, "%f" ) === false ) {
1659 # simple pattern: append file to scan
1660 $command .= " " . wfEscapeShellArg( $file );
1662 # complex pattern: replace "%f" with file to scan
1663 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1666 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1668 # execute virus scanner
1671 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1672 # that does not seem to be worth the pain.
1673 # Ask me (Duesentrieb) about it if it's ever needed.
1674 $output = wfShellExecWithStderr( $command, $exitCode );
1676 # map exit code to AV_xxx constants.
1677 $mappedCode = $exitCode;
1678 if ( $exitCodeMap ) {
1679 if ( isset( $exitCodeMap[$exitCode] ) ) {
1680 $mappedCode = $exitCodeMap[$exitCode];
1681 } elseif ( isset( $exitCodeMap["*"] ) ) {
1682 $mappedCode = $exitCodeMap["*"];
1686 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1687 * so we need the strict equalities === and thus can't use a switch here
1689 if ( $mappedCode === AV_SCAN_FAILED
) {
1690 # scan failed (code was mapped to false by $exitCodeMap)
1691 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1693 $output = $wgAntivirusRequired
1694 ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1696 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1697 # scan failed because filetype is unknown (probably imune)
1698 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1700 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1702 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1705 $output = trim( $output );
1708 $output = true; #if there's no output, return true
1709 } elseif ( $msgPattern ) {
1711 if ( preg_match( $msgPattern, $output, $groups ) ) {
1713 $output = $groups[1];
1718 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1721 wfProfileOut( __METHOD__
);
1727 * Check if there's an overwrite conflict and, if so, if restrictions
1728 * forbid this user from performing the upload.
1732 * @return mixed True on success, array on failure
1734 private function checkOverwrite( $user ) {
1735 // First check whether the local file can be overwritten
1736 $file = $this->getLocalFile();
1737 if ( $file->exists() ) {
1738 if ( !self
::userCanReUpload( $user, $file ) ) {
1739 return array( 'fileexists-forbidden', $file->getName() );
1745 /* Check shared conflicts: if the local file does not exist, but
1746 * wfFindFile finds a file, it exists in a shared repository.
1748 $file = wfFindFile( $this->getTitle() );
1749 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1750 return array( 'fileexists-shared-forbidden', $file->getName() );
1757 * Check if a user is the last uploader
1760 * @param string $img Image name
1763 public static function userCanReUpload( User
$user, $img ) {
1764 if ( $user->isAllowed( 'reupload' ) ) {
1765 return true; // non-conditional
1767 if ( !$user->isAllowed( 'reupload-own' ) ) {
1770 if ( is_string( $img ) ) {
1771 $img = wfLocalFile( $img );
1773 if ( !( $img instanceof LocalFile
) ) {
1777 return $user->getId() == $img->getUser( 'id' );
1781 * Helper function that does various existence checks for a file.
1782 * The following checks are performed:
1784 * - Article with the same name as the file exists
1785 * - File exists with normalized extension
1786 * - The file looks like a thumbnail and the original exists
1788 * @param File $file The File object to check
1789 * @return mixed False if the file does not exists, else an array
1791 public static function getExistsWarning( $file ) {
1792 if ( $file->exists() ) {
1793 return array( 'warning' => 'exists', 'file' => $file );
1796 if ( $file->getTitle()->getArticleID() ) {
1797 return array( 'warning' => 'page-exists', 'file' => $file );
1800 if ( $file->wasDeleted() && !$file->exists() ) {
1801 return array( 'warning' => 'was-deleted', 'file' => $file );
1804 if ( strpos( $file->getName(), '.' ) == false ) {
1805 $partname = $file->getName();
1808 $n = strrpos( $file->getName(), '.' );
1809 $extension = substr( $file->getName(), $n +
1 );
1810 $partname = substr( $file->getName(), 0, $n );
1812 $normalizedExtension = File
::normalizeExtension( $extension );
1814 if ( $normalizedExtension != $extension ) {
1815 // We're not using the normalized form of the extension.
1816 // Normal form is lowercase, using most common of alternate
1817 // extensions (eg 'jpg' rather than 'JPEG').
1819 // Check for another file using the normalized form...
1820 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1821 $file_lc = wfLocalFile( $nt_lc );
1823 if ( $file_lc->exists() ) {
1825 'warning' => 'exists-normalized',
1827 'normalizedFile' => $file_lc
1832 // Check for files with the same name but a different extension
1833 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1834 "{$partname}.", 1 );
1835 if ( count( $similarFiles ) ) {
1837 'warning' => 'exists-normalized',
1839 'normalizedFile' => $similarFiles[0],
1843 if ( self
::isThumbName( $file->getName() ) ) {
1844 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1845 $nt_thb = Title
::newFromText(
1846 substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension,
1849 $file_thb = wfLocalFile( $nt_thb );
1850 if ( $file_thb->exists() ) {
1852 'warning' => 'thumb',
1854 'thumbFile' => $file_thb
1857 // File does not exist, but we just don't like the name
1859 'warning' => 'thumb-name',
1861 'thumbFile' => $file_thb
1866 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1867 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1869 'warning' => 'bad-prefix',
1880 * Helper function that checks whether the filename looks like a thumbnail
1881 * @param string $filename
1884 public static function isThumbName( $filename ) {
1885 $n = strrpos( $filename, '.' );
1886 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1889 substr( $partname, 3, 3 ) == 'px-' ||
1890 substr( $partname, 2, 3 ) == 'px-'
1892 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1896 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1898 * @return array List of prefixes
1900 public static function getFilenamePrefixBlacklist() {
1901 $blacklist = array();
1902 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1903 if ( !$message->isDisabled() ) {
1904 $lines = explode( "\n", $message->plain() );
1905 foreach ( $lines as $line ) {
1906 // Remove comment lines
1907 $comment = substr( trim( $line ), 0, 1 );
1908 if ( $comment == '#' ||
$comment == '' ) {
1911 // Remove additional comments after a prefix
1912 $comment = strpos( $line, '#' );
1913 if ( $comment > 0 ) {
1914 $line = substr( $line, 0, $comment - 1 );
1916 $blacklist[] = trim( $line );
1924 * Gets image info about the file just uploaded.
1926 * Also has the effect of setting metadata to be an 'indexed tag name' in
1927 * returned API result if 'metadata' was requested. Oddly, we have to pass
1928 * the "result" object down just so it can do that with the appropriate
1929 * format, presumably.
1931 * @param ApiResult $result
1932 * @return array Image info
1934 public function getImageInfo( $result ) {
1935 $file = $this->getLocalFile();
1936 /** @todo This cries out for refactoring.
1937 * We really want to say $file->getAllInfo(); here.
1938 * Perhaps "info" methods should be moved into files, and the API should
1939 * just wrap them in queries.
1941 if ( $file instanceof UploadStashFile
) {
1942 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1943 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1945 $imParam = ApiQueryImageInfo
::getPropertyNames();
1946 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1953 * @param array $error
1956 public function convertVerifyErrorToStatus( $error ) {
1957 $code = $error['status'];
1958 unset( $code['status'] );
1960 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1964 * @param null|string $forType
1967 public static function getMaxUploadSize( $forType = null ) {
1968 global $wgMaxUploadSize;
1970 if ( is_array( $wgMaxUploadSize ) ) {
1971 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1972 return $wgMaxUploadSize[$forType];
1974 return $wgMaxUploadSize['*'];
1977 return intval( $wgMaxUploadSize );
1982 * Get the current status of a chunked upload (used for polling).
1983 * The status will be read from the *current* user session.
1984 * @param string $statusKey
1985 * @return Status[]|bool
1987 public static function getSessionStatus( $statusKey ) {
1988 return isset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] )
1989 ?
$_SESSION[self
::SESSION_STATUS_KEY
][$statusKey]
1994 * Set the current status of a chunked upload (used for polling).
1995 * The status will be stored in the *current* user session.
1996 * @param string $statusKey
1997 * @param array|bool $value
2000 public static function setSessionStatus( $statusKey, $value ) {
2001 if ( $value === false ) {
2002 unset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] );
2004 $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] = $value;