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;
76 public function getVerificationErrorCode( $error ) {
77 $code_to_status = array(
78 self
::EMPTY_FILE
=> 'empty-file',
79 self
::FILE_TOO_LARGE
=> 'file-too-large',
80 self
::FILETYPE_MISSING
=> 'filetype-missing',
81 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
82 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
83 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
84 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
85 self
::VERIFICATION_ERROR
=> 'verification-error',
86 self
::HOOK_ABORTED
=> 'hookaborted',
87 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
88 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
90 if ( isset( $code_to_status[$error] ) ) {
91 return $code_to_status[$error];
94 return 'unknown-error';
98 * Returns true if uploads are enabled.
99 * Can be override by subclasses.
102 public static function isEnabled() {
103 global $wgEnableUploads;
105 if ( !$wgEnableUploads ) {
109 # Check php's file_uploads setting
110 return wfIsHHVM() ||
wfIniGetBool( 'file_uploads' );
114 * Returns true if the user can use this upload module or else a string
115 * identifying the missing permission.
116 * Can be overridden by subclasses.
119 * @return bool|string
121 public static function isAllowed( $user ) {
122 foreach ( array( 'upload', 'edit' ) as $permission ) {
123 if ( !$user->isAllowed( $permission ) ) {
131 // Upload handlers. Should probably just be a global.
132 private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
135 * Create a form of UploadBase depending on wpSourceType and initializes it
137 * @param WebRequest $request
138 * @param string|null $type
139 * @return null|UploadBase
141 public static function createFromRequest( &$request, $type = null ) {
142 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
148 // Get the upload class
149 $type = ucfirst( $type );
151 // Give hooks the chance to handle this request
153 Hooks
::run( 'UploadCreateFromRequest', array( $type, &$className ) );
154 if ( is_null( $className ) ) {
155 $className = 'UploadFrom' . $type;
156 wfDebug( __METHOD__
. ": class name: $className\n" );
157 if ( !in_array( $type, self
::$uploadHandlers ) ) {
162 // Check whether this upload class is enabled
163 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
167 // Check whether the request is valid
168 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
172 /** @var UploadBase $handler */
173 $handler = new $className;
175 $handler->initializeFromRequest( $request );
181 * Check whether a request if valid for this handler
182 * @param WebRequest $request
185 public static function isValidRequest( $request ) {
189 public function __construct() {
193 * Returns the upload type. Should be overridden by child classes
198 public function getSourceType() {
203 * Initialize the path information
204 * @param string $name The desired destination name
205 * @param string $tempPath The temporary path
206 * @param int $fileSize The file size
207 * @param bool $removeTempFile (false) remove the temporary file?
208 * @throws MWException
210 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
211 $this->mDesiredDestName
= $name;
212 if ( FileBackend
::isStoragePath( $tempPath ) ) {
213 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
215 $this->mTempPath
= $tempPath;
216 $this->mFileSize
= $fileSize;
217 $this->mRemoveTempFile
= $removeTempFile;
221 * Initialize from a WebRequest. Override this in a subclass.
223 * @param WebRequest $request
225 abstract public function initializeFromRequest( &$request );
228 * Fetch the file. Usually a no-op
231 public function fetchFile() {
232 return Status
::newGood();
236 * Return true if the file is empty
239 public function isEmptyFile() {
240 return empty( $this->mFileSize
);
244 * Return the file size
247 public function getFileSize() {
248 return $this->mFileSize
;
252 * Get the base 36 SHA1 of the file
255 public function getTempFileSha1Base36() {
256 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
260 * @param string $srcPath The source path
261 * @return string|bool The real path if it was a virtual URL Returns false on failure
263 function getRealPath( $srcPath ) {
264 $repo = RepoGroup
::singleton()->getLocalRepo();
265 if ( $repo->isVirtualUrl( $srcPath ) ) {
266 /** @todo Just make uploads work with storage paths UploadFromStash
267 * loads files via virtual URLs.
269 $tmpFile = $repo->getLocalCopy( $srcPath );
271 $tmpFile->bind( $this ); // keep alive with $this
273 $path = $tmpFile ?
$tmpFile->getPath() : false;
282 * Verify whether the upload is sane.
283 * @return mixed Const self::OK or else an array with error information
285 public function verifyUpload() {
288 * If there was no filename or a zero size given, give up quick.
290 if ( $this->isEmptyFile() ) {
291 return array( 'status' => self
::EMPTY_FILE
);
295 * Honor $wgMaxUploadSize
297 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
298 if ( $this->mFileSize
> $maxSize ) {
300 'status' => self
::FILE_TOO_LARGE
,
306 * Look at the contents of the file; if we can recognize the
307 * type but it's corrupt or data of the wrong type, we should
308 * probably not accept it.
310 $verification = $this->verifyFile();
311 if ( $verification !== true ) {
313 'status' => self
::VERIFICATION_ERROR
,
314 'details' => $verification
319 * Make sure this file can be created
321 $result = $this->validateName();
322 if ( $result !== true ) {
327 if ( !Hooks
::run( 'UploadVerification',
328 array( $this->mDestName
, $this->mTempPath
, &$error ) )
330 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
333 return array( 'status' => self
::OK
);
337 * Verify that the name is valid and, if necessary, that we can overwrite
339 * @return mixed True if valid, otherwise and array with 'status'
342 public function validateName() {
343 $nt = $this->getTitle();
344 if ( is_null( $nt ) ) {
345 $result = array( 'status' => $this->mTitleError
);
346 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
347 $result['filtered'] = $this->mFilteredName
;
349 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
350 $result['finalExt'] = $this->mFinalExtension
;
351 if ( count( $this->mBlackListedExtensions
) ) {
352 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
358 $this->mDestName
= $this->getLocalFile()->getName();
364 * Verify the MIME type.
366 * @note Only checks that it is not an evil MIME. The "does it have
367 * correct extension given its MIME type?" check is in verifyFile.
368 * in `verifyFile()` that MIME type and file extension correlate.
369 * @param string $mime Representing the MIME
370 * @return mixed True if the file is verified, an array otherwise
372 protected function verifyMimeType( $mime ) {
373 global $wgVerifyMimeType;
374 if ( $wgVerifyMimeType ) {
375 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
376 global $wgMimeTypeBlacklist;
377 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
378 return array( 'filetype-badmime', $mime );
381 # Check what Internet Explorer would detect
382 $fp = fopen( $this->mTempPath
, 'rb' );
383 $chunk = fread( $fp, 256 );
386 $magic = MimeMagic
::singleton();
387 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
388 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
389 foreach ( $ieTypes as $ieType ) {
390 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
391 return array( 'filetype-bad-ie-mime', $ieType );
400 * Verifies that it's ok to include the uploaded file
402 * @return mixed True of the file is verified, array otherwise.
404 protected function verifyFile() {
405 global $wgVerifyMimeType, $wgDisableUploadScriptChecks;
407 $status = $this->verifyPartialFile();
408 if ( $status !== true ) {
412 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
413 $mime = $this->mFileProps
['mime'];
415 if ( $wgVerifyMimeType ) {
416 # XXX: Missing extension will be caught by validateName() via getTitle()
417 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
418 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
422 # check for htmlish code and javascript
423 if ( !$wgDisableUploadScriptChecks ) {
424 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
425 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, false );
426 if ( $svgStatus !== false ) {
432 $handler = MediaHandler
::getHandler( $mime );
434 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
435 if ( !$handlerStatus->isOK() ) {
436 $errors = $handlerStatus->getErrorsArray();
438 return reset( $errors );
442 Hooks
::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
443 if ( $status !== true ) {
447 wfDebug( __METHOD__
. ": all clear; passing.\n" );
453 * A verification routine suitable for partial files
455 * Runs the blacklist checks, but not any checks that may
456 * assume the entire file is present.
458 * @return mixed True for valid or array with error message key.
460 protected function verifyPartialFile() {
461 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
463 # getTitle() sets some internal parameters like $this->mFinalExtension
466 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
468 # check MIME type, if desired
469 $mime = $this->mFileProps
['file-mime'];
470 $status = $this->verifyMimeType( $mime );
471 if ( $status !== true ) {
475 # check for htmlish code and javascript
476 if ( !$wgDisableUploadScriptChecks ) {
477 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
478 return array( 'uploadscripted' );
480 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
481 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
, true );
482 if ( $svgStatus !== false ) {
488 # Check for Java applets, which if uploaded can bypass cross-site
490 if ( !$wgAllowJavaUploads ) {
491 $this->mJavaDetected
= false;
492 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
493 array( $this, 'zipEntryCallback' ) );
494 if ( !$zipStatus->isOK() ) {
495 $errors = $zipStatus->getErrorsArray();
496 $error = reset( $errors );
497 if ( $error[0] !== 'zip-wrong-format' ) {
501 if ( $this->mJavaDetected
) {
502 return array( 'uploadjava' );
506 # Scan the uploaded file for viruses
507 $virus = $this->detectVirus( $this->mTempPath
);
509 return array( 'uploadvirus', $virus );
516 * Callback for ZipDirectoryReader to detect Java class files.
518 * @param array $entry
520 function zipEntryCallback( $entry ) {
521 $names = array( $entry['name'] );
523 // If there is a null character, cut off the name at it, because JDK's
524 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
525 // were constructed which had ".class\0" followed by a string chosen to
526 // make the hash collide with the truncated name, that file could be
527 // returned in response to a request for the .class file.
528 $nullPos = strpos( $entry['name'], "\000" );
529 if ( $nullPos !== false ) {
530 $names[] = substr( $entry['name'], 0, $nullPos );
533 // If there is a trailing slash in the file name, we have to strip it,
534 // because that's what ZIP_GetEntry() does.
535 if ( preg_grep( '!\.class/?$!', $names ) ) {
536 $this->mJavaDetected
= true;
541 * Alias for verifyTitlePermissions. The function was originally
542 * 'verifyPermissions', but that suggests it's checking the user, when it's
543 * really checking the title + user combination.
545 * @param User $user User object to verify the permissions against
546 * @return mixed An array as returned by getUserPermissionsErrors or true
547 * in case the user has proper permissions.
549 public function verifyPermissions( $user ) {
550 return $this->verifyTitlePermissions( $user );
554 * Check whether the user can edit, upload and create the image. This
555 * checks only against the current title; if it returns errors, it may
556 * very well be that another title will not give errors. Therefore
557 * isAllowed() should be called as well for generic is-user-blocked or
558 * can-user-upload checking.
560 * @param User $user User object to verify the permissions against
561 * @return mixed An array as returned by getUserPermissionsErrors or true
562 * in case the user has proper permissions.
564 public function verifyTitlePermissions( $user ) {
566 * If the image is protected, non-sysop users won't be able
567 * to modify it by uploading a new revision.
569 $nt = $this->getTitle();
570 if ( is_null( $nt ) ) {
573 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
574 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
575 if ( !$nt->exists() ) {
576 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
578 $permErrorsCreate = array();
580 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
581 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
582 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
587 $overwriteError = $this->checkOverwrite( $user );
588 if ( $overwriteError !== true ) {
589 return array( $overwriteError );
596 * Check for non fatal problems with the file.
598 * This should not assume that mTempPath is set.
600 * @return array Array of warnings
602 public function checkWarnings() {
607 $localFile = $this->getLocalFile();
608 $localFile->load( File
::READ_LATEST
);
609 $filename = $localFile->getName();
612 * Check whether the resulting filename is different from the desired one,
613 * but ignore things like ucfirst() and spaces/underscore things
615 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
616 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
618 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
619 $warnings['badfilename'] = $filename;
620 // Debugging for bug 62241
621 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
622 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
625 // Check whether the file extension is on the unwanted list
626 global $wgCheckFileExtensions, $wgFileExtensions;
627 if ( $wgCheckFileExtensions ) {
628 $extensions = array_unique( $wgFileExtensions );
629 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
630 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
631 $wgLang->commaList( $extensions ), count( $extensions ) );
635 global $wgUploadSizeWarning;
636 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
637 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
640 if ( $this->mFileSize
== 0 ) {
641 $warnings['emptyfile'] = true;
644 $exists = self
::getExistsWarning( $localFile );
645 if ( $exists !== false ) {
646 $warnings['exists'] = $exists;
649 // Check dupes against existing files
650 $hash = $this->getTempFileSha1Base36();
651 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
652 $title = $this->getTitle();
653 // Remove all matches against self
654 foreach ( $dupes as $key => $dupe ) {
655 if ( $title->equals( $dupe->getTitle() ) ) {
656 unset( $dupes[$key] );
660 $warnings['duplicate'] = $dupes;
663 // Check dupes against archives
664 $archivedFile = new ArchivedFile( null, 0, '', $hash );
665 if ( $archivedFile->getID() > 0 ) {
666 if ( $archivedFile->userCan( File
::DELETED_FILE
) ) {
667 $warnings['duplicate-archive'] = $archivedFile->getName();
669 $warnings['duplicate-archive'] = '';
677 * Really perform the upload. Stores the file in the local repo, watches
678 * if necessary and runs the UploadComplete hook.
680 * @param string $comment
681 * @param string $pageText
685 * @return Status Indicating the whether the upload succeeded.
687 public function performUpload( $comment, $pageText, $watch, $user ) {
688 $this->getLocalFile()->load( File
::READ_LATEST
);
690 $status = $this->getLocalFile()->upload(
700 if ( $status->isGood() ) {
702 WatchAction
::doWatch(
703 $this->getLocalFile()->getTitle(),
705 WatchedItem
::IGNORE_USER_RIGHTS
708 Hooks
::run( 'UploadComplete', array( &$this ) );
710 $this->postProcessUpload();
717 * Perform extra steps after a successful upload.
721 public function postProcessUpload() {
722 global $wgUploadThumbnailRenderMap;
726 $sizes = $wgUploadThumbnailRenderMap;
729 $file = $this->getLocalFile();
731 foreach ( $sizes as $size ) {
732 if ( $file->isVectorized() ||
$file->getWidth() > $size ) {
733 $jobs[] = new ThumbnailRenderJob(
735 array( 'transformParams' => array( 'width' => $size ) )
741 JobQueueGroup
::singleton()->push( $jobs );
746 * Returns the title of the file to be uploaded. Sets mTitleError in case
747 * the name was illegal.
749 * @return Title The title of the file or null in case the name was illegal
751 public function getTitle() {
752 if ( $this->mTitle
!== false ) {
753 return $this->mTitle
;
755 /* Assume that if a user specified File:Something.jpg, this is an error
756 * and that the namespace prefix needs to be stripped of.
758 $title = Title
::newFromText( $this->mDesiredDestName
);
759 if ( $title && $title->getNamespace() == NS_FILE
) {
760 $this->mFilteredName
= $title->getDBkey();
762 $this->mFilteredName
= $this->mDesiredDestName
;
765 # oi_archive_name is max 255 bytes, which include a timestamp and an
766 # exclamation mark, so restrict file name to 240 bytes.
767 if ( strlen( $this->mFilteredName
) > 240 ) {
768 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
769 $this->mTitle
= null;
771 return $this->mTitle
;
775 * Chop off any directories in the given filename. Then
776 * filter out illegal characters, and try to make a legible name
777 * out of it. We'll strip some silently that Title would die on.
779 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
780 /* Normalize to title form before we do any further processing */
781 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
782 if ( is_null( $nt ) ) {
783 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
784 $this->mTitle
= null;
786 return $this->mTitle
;
788 $this->mFilteredName
= $nt->getDBkey();
791 * We'll want to blacklist against *any* 'extension', and use
792 * only the final one for the whitelist.
794 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
796 if ( count( $ext ) ) {
797 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
799 $this->mFinalExtension
= '';
801 # No extension, try guessing one
802 $magic = MimeMagic
::singleton();
803 $mime = $magic->guessMimeType( $this->mTempPath
);
804 if ( $mime !== 'unknown/unknown' ) {
805 # Get a space separated list of extensions
806 $extList = $magic->getExtensionsForType( $mime );
808 # Set the extension to the canonical extension
809 $this->mFinalExtension
= strtok( $extList, ' ' );
811 # Fix up the other variables
812 $this->mFilteredName
.= ".{$this->mFinalExtension}";
813 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
814 $ext = array( $this->mFinalExtension
);
819 /* Don't allow users to override the blacklist (check file extension) */
820 global $wgCheckFileExtensions, $wgStrictFileExtensions;
821 global $wgFileExtensions, $wgFileBlacklist;
823 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
825 if ( $this->mFinalExtension
== '' ) {
826 $this->mTitleError
= self
::FILETYPE_MISSING
;
827 $this->mTitle
= null;
829 return $this->mTitle
;
830 } elseif ( $blackListedExtensions ||
831 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
832 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
834 $this->mBlackListedExtensions
= $blackListedExtensions;
835 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
836 $this->mTitle
= null;
838 return $this->mTitle
;
841 // Windows may be broken with special characters, see bug 1780
842 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
843 && !RepoGroup
::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
845 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
846 $this->mTitle
= null;
848 return $this->mTitle
;
851 # If there was more than one "extension", reassemble the base
852 # filename to prevent bogus complaints about length
853 if ( count( $ext ) > 1 ) {
854 $iterations = count( $ext ) - 1;
855 for ( $i = 0; $i < $iterations; $i++
) {
856 $partname .= '.' . $ext[$i];
860 if ( strlen( $partname ) < 1 ) {
861 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
862 $this->mTitle
= null;
864 return $this->mTitle
;
869 return $this->mTitle
;
873 * Return the local file and initializes if necessary.
875 * @return LocalFile|UploadStashFile|null
877 public function getLocalFile() {
878 if ( is_null( $this->mLocalFile
) ) {
879 $nt = $this->getTitle();
880 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
883 return $this->mLocalFile
;
887 * If the user does not supply all necessary information in the first upload
888 * form submission (either by accident or by design) then we may want to
889 * stash the file temporarily, get more information, and publish the file
892 * This method will stash a file in a temporary directory for later
893 * processing, and save the necessary descriptive info into the database.
894 * This method returns the file object, which also has a 'fileKey' property
895 * which can be passed through a form or API request to find this stashed
899 * @return UploadStashFile Stashed file
901 public function stashFile( User
$user = null ) {
902 // was stashSessionFile
904 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
905 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
906 $this->mLocalFile
= $file;
912 * Stash a file in a temporary directory, returning a key which can be used
913 * to find the file again. See stashFile().
915 * @return string File key
917 public function stashFileGetKey() {
918 return $this->stashFile()->getFileKey();
922 * alias for stashFileGetKey, for backwards compatibility
924 * @return string File key
926 public function stashSession() {
927 return $this->stashFileGetKey();
931 * If we've modified the upload file we need to manually remove it
932 * on exit to clean up.
934 public function cleanupTempFile() {
935 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
936 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
937 unlink( $this->mTempPath
);
941 public function getTempPath() {
942 return $this->mTempPath
;
946 * Split a file into a base name and all dot-delimited 'extensions'
947 * on the end. Some web server configurations will fall back to
948 * earlier pseudo-'extensions' to determine type and execute
949 * scripts, so the blacklist needs to check them all.
951 * @param string $filename
954 public static function splitExtensions( $filename ) {
955 $bits = explode( '.', $filename );
956 $basename = array_shift( $bits );
958 return array( $basename, $bits );
962 * Perform case-insensitive match against a list of file extensions.
963 * Returns true if the extension is in the list.
969 public static function checkFileExtension( $ext, $list ) {
970 return in_array( strtolower( $ext ), $list );
974 * Perform case-insensitive match against a list of file extensions.
975 * Returns an array of matching extensions.
981 public static function checkFileExtensionList( $ext, $list ) {
982 return array_intersect( array_map( 'strtolower', $ext ), $list );
986 * Checks if the MIME type of the uploaded file matches the file extension.
988 * @param string $mime The MIME type of the uploaded file
989 * @param string $extension The filename extension that the file is to be served with
992 public static function verifyExtension( $mime, $extension ) {
993 $magic = MimeMagic
::singleton();
995 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
996 if ( !$magic->isRecognizableExtension( $extension ) ) {
997 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
998 "unrecognized extension '$extension', can't verify\n" );
1002 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
1003 "recognized extension '$extension', so probably invalid file\n" );
1009 $match = $magic->isMatchingExtension( $extension, $mime );
1011 if ( $match === null ) {
1012 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1013 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
1017 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
1021 } elseif ( $match === true ) {
1022 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
1024 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1028 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1035 * Heuristic for detecting files that *could* contain JavaScript instructions or
1036 * things that may look like HTML to a browser and are thus
1037 * potentially harmful. The present implementation will produce false
1038 * positives in some situations.
1040 * @param string $file Pathname to the temporary upload file
1041 * @param string $mime The MIME type of the file
1042 * @param string $extension The extension of the file
1043 * @return bool True if the file contains something looking like embedded scripts
1045 public static function detectScript( $file, $mime, $extension ) {
1046 global $wgAllowTitlesInSVG;
1048 # ugly hack: for text files, always look at the entire file.
1049 # For binary field, just check the first K.
1051 if ( strpos( $mime, 'text/' ) === 0 ) {
1052 $chunk = file_get_contents( $file );
1054 $fp = fopen( $file, 'rb' );
1055 $chunk = fread( $fp, 1024 );
1059 $chunk = strtolower( $chunk );
1065 # decode from UTF-16 if needed (could be used for obfuscation).
1066 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1068 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1075 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1078 $chunk = trim( $chunk );
1080 /** @todo FIXME: Convert from UTF-16 if necessary! */
1081 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1083 # check for HTML doctype
1084 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1088 // Some browsers will interpret obscure xml encodings as UTF-8, while
1089 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1090 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1091 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1097 * Internet Explorer for Windows performs some really stupid file type
1098 * autodetection which can cause it to interpret valid image files as HTML
1099 * and potentially execute JavaScript, creating a cross-site scripting
1102 * Apple's Safari browser also performs some unsafe file type autodetection
1103 * which can cause legitimate files to be interpreted as HTML if the
1104 * web server is not correctly configured to send the right content-type
1105 * (or if you're really uploading plain text and octet streams!)
1107 * Returns true if IE is likely to mistake the given file for HTML.
1108 * Also returns true if Safari would mistake the given file for HTML
1109 * when served with a generic content-type.
1115 '<html', #also in safari
1118 '<script', #also in safari
1122 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1126 foreach ( $tags as $tag ) {
1127 if ( false !== strpos( $chunk, $tag ) ) {
1128 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1135 * look for JavaScript
1138 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1139 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1141 # look for script-types
1142 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1143 wfDebug( __METHOD__
. ": found script types\n" );
1148 # look for html-style script-urls
1149 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1150 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1155 # look for css-style script-urls
1156 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1157 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1162 wfDebug( __METHOD__
. ": no scripts found\n" );
1168 * Check a whitelist of xml encodings that are known not to be interpreted differently
1169 * by the server's xml parser (expat) and some common browsers.
1171 * @param string $file Pathname to the temporary upload file
1172 * @return bool True if the file contains an encoding that could be misinterpreted
1174 public static function checkXMLEncodingMissmatch( $file ) {
1175 global $wgSVGMetadataCutoff;
1176 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1177 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1179 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1180 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1181 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1183 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1187 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1188 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1189 // bytes. There shouldn't be a legitimate reason for this to happen.
1190 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1193 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1194 // EBCDIC encoded XML
1195 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1200 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1201 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1202 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1203 foreach ( $attemptEncodings as $encoding ) {
1204 MediaWiki\
suppressWarnings();
1205 $str = iconv( $encoding, 'UTF-8', $contents );
1206 MediaWiki\restoreWarnings
();
1207 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1208 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1209 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1211 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1215 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1216 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1217 // bytes. There shouldn't be a legitimate reason for this to happen.
1218 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1228 * @param string $filename
1229 * @param bool $partial
1230 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1232 protected function detectScriptInSvg( $filename, $partial ) {
1233 $this->mSVGNSError
= false;
1234 $check = new XmlTypeCheck(
1236 array( $this, 'checkSvgScriptCallback' ),
1238 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1240 if ( $check->wellFormed
!== true ) {
1241 // Invalid xml (bug 58553)
1242 // But only when non-partial (bug 65724)
1243 return $partial ?
false : array( 'uploadinvalidxml' );
1244 } elseif ( $check->filterMatch
) {
1245 if ( $this->mSVGNSError
) {
1246 return array( 'uploadscriptednamespace', $this->mSVGNSError
);
1249 return $check->filterMatchType
;
1256 * Callback to filter SVG Processing Instructions.
1257 * @param string $target Processing instruction name
1258 * @param string $data Processing instruction attribute and value
1259 * @return bool (true if the filter identified something bad)
1261 public static function checkSvgPICallback( $target, $data ) {
1262 // Don't allow external stylesheets (bug 57550)
1263 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1264 return array( 'upload-scripted-pi-callback' );
1271 * @todo Replace this with a whitelist filter!
1272 * @param string $element
1273 * @param array $attribs
1276 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1278 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1280 // We specifically don't include:
1281 // http://www.w3.org/1999/xhtml (bug 60771)
1282 static $validNamespaces = array(
1285 'http://creativecommons.org/ns#',
1286 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1287 'http://ns.adobe.com/adobeillustrator/10.0/',
1288 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1289 'http://ns.adobe.com/extensibility/1.0/',
1290 'http://ns.adobe.com/flows/1.0/',
1291 'http://ns.adobe.com/illustrator/1.0/',
1292 'http://ns.adobe.com/imagereplacement/1.0/',
1293 'http://ns.adobe.com/pdf/1.3/',
1294 'http://ns.adobe.com/photoshop/1.0/',
1295 'http://ns.adobe.com/saveforweb/1.0/',
1296 'http://ns.adobe.com/variables/1.0/',
1297 'http://ns.adobe.com/xap/1.0/',
1298 'http://ns.adobe.com/xap/1.0/g/',
1299 'http://ns.adobe.com/xap/1.0/g/img/',
1300 'http://ns.adobe.com/xap/1.0/mm/',
1301 'http://ns.adobe.com/xap/1.0/rights/',
1302 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1303 'http://ns.adobe.com/xap/1.0/stype/font#',
1304 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1305 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1306 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1307 'http://ns.adobe.com/xap/1.0/t/pg/',
1308 'http://purl.org/dc/elements/1.1/',
1309 'http://purl.org/dc/elements/1.1',
1310 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1311 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1312 'http://taptrix.com/inkpad/svg_extensions',
1313 'http://web.resource.org/cc/',
1314 'http://www.freesoftware.fsf.org/bkchem/cdml',
1315 'http://www.inkscape.org/namespaces/inkscape',
1316 'http://www.opengis.net/gml',
1317 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1318 'http://www.w3.org/2000/svg',
1319 'http://www.w3.org/tr/rec-rdf-syntax/',
1322 if ( !in_array( $namespace, $validNamespaces ) ) {
1323 wfDebug( __METHOD__
. ": Non-svg namespace '$namespace' in uploaded file.\n" );
1324 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1325 $this->mSVGNSError
= $namespace;
1331 * check for elements that can contain javascript
1333 if ( $strippedElement == 'script' ) {
1334 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1336 return array( 'uploaded-script-svg', $strippedElement );
1339 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1340 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1341 if ( $strippedElement == 'handler' ) {
1342 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1344 return array( 'uploaded-script-svg', $strippedElement );
1347 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1348 if ( $strippedElement == 'stylesheet' ) {
1349 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1351 return array( 'uploaded-script-svg', $strippedElement );
1354 # Block iframes, in case they pass the namespace check
1355 if ( $strippedElement == 'iframe' ) {
1356 wfDebug( __METHOD__
. ": iframe in uploaded file.\n" );
1358 return array( 'uploaded-script-svg', $strippedElement );
1362 if ( $strippedElement == 'style'
1363 && self
::checkCssFragment( Sanitizer
::normalizeCss( $data ) )
1365 wfDebug( __METHOD__
. ": hostile css in style element.\n" );
1366 return array( 'uploaded-hostile-svg' );
1369 foreach ( $attribs as $attrib => $value ) {
1370 $stripped = $this->stripXmlNamespace( $attrib );
1371 $value = strtolower( $value );
1373 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1375 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1377 return array( 'uploaded-event-handler-on-svg', $attrib, $value );
1380 # href with non-local target (don't allow http://, javascript:, etc)
1381 if ( $stripped == 'href'
1382 && strpos( $value, 'data:' ) !== 0
1383 && strpos( $value, '#' ) !== 0
1385 if ( !( $strippedElement === 'a'
1386 && preg_match( '!^https?://!im', $value ) )
1388 wfDebug( __METHOD__
. ": Found href attribute <$strippedElement "
1389 . "'$attrib'='$value' in uploaded file.\n" );
1391 return array( 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value );
1395 # only allow data: targets that should be safe. This prevents vectors like,
1396 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1397 if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1398 // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1399 $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1400 if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1401 wfDebug( __METHOD__
. ": Found href to unwhitelisted data: uri "
1402 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1403 return array( 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value );
1407 # Change href with animate from (http://html5sec.org/#137).
1408 if ( $stripped === 'attributename'
1409 && $strippedElement === 'animate'
1410 && $this->stripXmlNamespace( $value ) == 'href'
1412 wfDebug( __METHOD__
. ": Found animate that might be changing href using from "
1413 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1415 return array( 'uploaded-animate-svg', $strippedElement, $attrib, $value );
1418 # use set/animate to add event-handler attribute to parent
1419 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' )
1420 && $stripped == 'attributename'
1421 && substr( $value, 0, 2 ) == 'on'
1423 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with "
1424 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1426 return array( 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value );
1429 # use set to add href attribute to parent element
1430 if ( $strippedElement == 'set'
1431 && $stripped == 'attributename'
1432 && strpos( $value, 'href' ) !== false
1434 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1436 return array( 'uploaded-setting-href-svg' );
1439 # use set to add a remote / data / script target to an element
1440 if ( $strippedElement == 'set'
1441 && $stripped == 'to'
1442 && preg_match( '!(http|https|data|script):!sim', $value )
1444 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1446 return array( 'uploaded-wrong-setting-svg', $value );
1449 # use handler attribute with remote / data / script
1450 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1451 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script "
1452 . "'$attrib'='$value' in uploaded file.\n" );
1454 return array( 'uploaded-setting-handler-svg', $attrib, $value );
1457 # use CSS styles to bring in remote code
1458 if ( $stripped == 'style'
1459 && self
::checkCssFragment( Sanitizer
::normalizeCss( $value ) )
1461 wfDebug( __METHOD__
. ": Found svg setting a style with "
1462 . "remote url '$attrib'='$value' in uploaded file.\n" );
1463 return array( 'uploaded-remote-url-svg', $attrib, $value );
1466 # Several attributes can include css, css character escaping isn't allowed
1467 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1468 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1469 if ( in_array( $stripped, $cssAttrs )
1470 && self
::checkCssFragment( $value )
1472 wfDebug( __METHOD__
. ": Found svg setting a style with "
1473 . "remote url '$attrib'='$value' in uploaded file.\n" );
1474 return array( 'uploaded-remote-url-svg', $attrib, $value );
1477 # image filters can pull in url, which could be svg that executes scripts
1478 if ( $strippedElement == 'image'
1479 && $stripped == 'filter'
1480 && preg_match( '!url\s*\(!sim', $value )
1482 wfDebug( __METHOD__
. ": Found image filter with url: "
1483 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1485 return array( 'uploaded-image-filter-svg', $strippedElement, $stripped, $value );
1489 return false; //No scripts detected
1493 * Check a block of CSS or CSS fragment for anything that looks like
1494 * it is bringing in remote code.
1495 * @param string $value a string of CSS
1496 * @param bool $propOnly only check css properties (start regex with :)
1497 * @return bool true if the CSS contains an illegal string, false if otherwise
1499 private static function checkCssFragment( $value ) {
1501 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1502 if ( stripos( $value, '@import' ) !== false ) {
1506 # We allow @font-face to embed fonts with data: urls, so we snip the string
1507 # 'url' out so this case won't match when we check for urls below
1508 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1509 $value = preg_replace( $pattern, '$1$2', $value );
1511 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1512 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1513 # Expression and -o-link don't seem to work either, but filtering them here in case.
1514 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1515 # but not local ones such as url("#..., url('#..., url(#....
1516 if ( preg_match( '!expression
1518 | -o-link-source\s*:
1519 | -o-replace\s*:!imx', $value ) ) {
1523 if ( preg_match_all(
1524 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1529 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1530 foreach ( $matches[1] as $match ) {
1531 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1537 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1545 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1546 * @param string $element
1547 * @return array Containing the namespace URI and prefix
1549 private static function splitXmlNamespace( $element ) {
1550 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1551 $parts = explode( ':', strtolower( $element ) );
1552 $name = array_pop( $parts );
1553 $ns = implode( ':', $parts );
1555 return array( $ns, $name );
1559 * @param string $name
1562 private function stripXmlNamespace( $name ) {
1563 // 'http://www.w3.org/2000/svg:script' -> 'script'
1564 $parts = explode( ':', strtolower( $name ) );
1566 return array_pop( $parts );
1570 * Generic wrapper function for a virus scanner program.
1571 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1572 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1574 * @param string $file Pathname to the temporary upload file
1575 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1576 * or a string containing feedback from the virus scanner if a virus was found.
1577 * If textual feedback is missing but a virus was found, this function returns true.
1579 public static function detectVirus( $file ) {
1580 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1582 if ( !$wgAntivirus ) {
1583 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1588 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1589 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1590 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1591 array( 'virus-badscanner', $wgAntivirus ) );
1593 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1596 # look up scanner configuration
1597 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1598 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1599 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1600 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1602 if ( strpos( $command, "%f" ) === false ) {
1603 # simple pattern: append file to scan
1604 $command .= " " . wfEscapeShellArg( $file );
1606 # complex pattern: replace "%f" with file to scan
1607 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1610 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1612 # execute virus scanner
1615 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1616 # that does not seem to be worth the pain.
1617 # Ask me (Duesentrieb) about it if it's ever needed.
1618 $output = wfShellExecWithStderr( $command, $exitCode );
1620 # map exit code to AV_xxx constants.
1621 $mappedCode = $exitCode;
1622 if ( $exitCodeMap ) {
1623 if ( isset( $exitCodeMap[$exitCode] ) ) {
1624 $mappedCode = $exitCodeMap[$exitCode];
1625 } elseif ( isset( $exitCodeMap["*"] ) ) {
1626 $mappedCode = $exitCodeMap["*"];
1630 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1631 * so we need the strict equalities === and thus can't use a switch here
1633 if ( $mappedCode === AV_SCAN_FAILED
) {
1634 # scan failed (code was mapped to false by $exitCodeMap)
1635 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1637 $output = $wgAntivirusRequired
1638 ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1640 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1641 # scan failed because filetype is unknown (probably imune)
1642 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1644 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1646 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1649 $output = trim( $output );
1652 $output = true; #if there's no output, return true
1653 } elseif ( $msgPattern ) {
1655 if ( preg_match( $msgPattern, $output, $groups ) ) {
1657 $output = $groups[1];
1662 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1669 * Check if there's an overwrite conflict and, if so, if restrictions
1670 * forbid this user from performing the upload.
1674 * @return mixed True on success, array on failure
1676 private function checkOverwrite( $user ) {
1677 // First check whether the local file can be overwritten
1678 $file = $this->getLocalFile();
1679 $file->load( File
::READ_LATEST
);
1680 if ( $file->exists() ) {
1681 if ( !self
::userCanReUpload( $user, $file ) ) {
1682 return array( 'fileexists-forbidden', $file->getName() );
1688 /* Check shared conflicts: if the local file does not exist, but
1689 * wfFindFile finds a file, it exists in a shared repository.
1691 $file = wfFindFile( $this->getTitle(), array( 'latest' => true ) );
1692 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1693 return array( 'fileexists-shared-forbidden', $file->getName() );
1700 * Check if a user is the last uploader
1703 * @param string $img Image name
1706 public static function userCanReUpload( User
$user, $img ) {
1707 if ( $user->isAllowed( 'reupload' ) ) {
1708 return true; // non-conditional
1710 if ( !$user->isAllowed( 'reupload-own' ) ) {
1713 if ( is_string( $img ) ) {
1714 $img = wfLocalFile( $img );
1716 if ( !( $img instanceof LocalFile
) ) {
1720 $img->load( File
::READ_LATEST
);
1722 return $user->getId() == $img->getUser( 'id' );
1726 * Helper function that does various existence checks for a file.
1727 * The following checks are performed:
1729 * - Article with the same name as the file exists
1730 * - File exists with normalized extension
1731 * - The file looks like a thumbnail and the original exists
1733 * @param File $file The File object to check
1734 * @return mixed False if the file does not exists, else an array
1736 public static function getExistsWarning( $file ) {
1737 if ( $file->exists() ) {
1738 return array( 'warning' => 'exists', 'file' => $file );
1741 if ( $file->getTitle()->getArticleID() ) {
1742 return array( 'warning' => 'page-exists', 'file' => $file );
1745 if ( $file->wasDeleted() && !$file->exists() ) {
1746 return array( 'warning' => 'was-deleted', 'file' => $file );
1749 if ( strpos( $file->getName(), '.' ) == false ) {
1750 $partname = $file->getName();
1753 $n = strrpos( $file->getName(), '.' );
1754 $extension = substr( $file->getName(), $n +
1 );
1755 $partname = substr( $file->getName(), 0, $n );
1757 $normalizedExtension = File
::normalizeExtension( $extension );
1759 if ( $normalizedExtension != $extension ) {
1760 // We're not using the normalized form of the extension.
1761 // Normal form is lowercase, using most common of alternate
1762 // extensions (eg 'jpg' rather than 'JPEG').
1764 // Check for another file using the normalized form...
1765 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1766 $file_lc = wfLocalFile( $nt_lc );
1768 if ( $file_lc->exists() ) {
1770 'warning' => 'exists-normalized',
1772 'normalizedFile' => $file_lc
1777 // Check for files with the same name but a different extension
1778 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1779 "{$partname}.", 1 );
1780 if ( count( $similarFiles ) ) {
1782 'warning' => 'exists-normalized',
1784 'normalizedFile' => $similarFiles[0],
1788 if ( self
::isThumbName( $file->getName() ) ) {
1789 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1790 $nt_thb = Title
::newFromText(
1791 substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension,
1794 $file_thb = wfLocalFile( $nt_thb );
1795 if ( $file_thb->exists() ) {
1797 'warning' => 'thumb',
1799 'thumbFile' => $file_thb
1802 // File does not exist, but we just don't like the name
1804 'warning' => 'thumb-name',
1806 'thumbFile' => $file_thb
1811 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1812 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1814 'warning' => 'bad-prefix',
1825 * Helper function that checks whether the filename looks like a thumbnail
1826 * @param string $filename
1829 public static function isThumbName( $filename ) {
1830 $n = strrpos( $filename, '.' );
1831 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1834 substr( $partname, 3, 3 ) == 'px-' ||
1835 substr( $partname, 2, 3 ) == 'px-'
1837 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1841 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1843 * @return array List of prefixes
1845 public static function getFilenamePrefixBlacklist() {
1846 $blacklist = array();
1847 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1848 if ( !$message->isDisabled() ) {
1849 $lines = explode( "\n", $message->plain() );
1850 foreach ( $lines as $line ) {
1851 // Remove comment lines
1852 $comment = substr( trim( $line ), 0, 1 );
1853 if ( $comment == '#' ||
$comment == '' ) {
1856 // Remove additional comments after a prefix
1857 $comment = strpos( $line, '#' );
1858 if ( $comment > 0 ) {
1859 $line = substr( $line, 0, $comment - 1 );
1861 $blacklist[] = trim( $line );
1869 * Gets image info about the file just uploaded.
1871 * Also has the effect of setting metadata to be an 'indexed tag name' in
1872 * returned API result if 'metadata' was requested. Oddly, we have to pass
1873 * the "result" object down just so it can do that with the appropriate
1874 * format, presumably.
1876 * @param ApiResult $result
1877 * @return array Image info
1879 public function getImageInfo( $result ) {
1880 $file = $this->getLocalFile();
1881 /** @todo This cries out for refactoring.
1882 * We really want to say $file->getAllInfo(); here.
1883 * Perhaps "info" methods should be moved into files, and the API should
1884 * just wrap them in queries.
1886 if ( $file instanceof UploadStashFile
) {
1887 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1888 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1890 $imParam = ApiQueryImageInfo
::getPropertyNames();
1891 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1898 * @param array $error
1901 public function convertVerifyErrorToStatus( $error ) {
1902 $code = $error['status'];
1903 unset( $code['status'] );
1905 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1909 * @param null|string $forType
1912 public static function getMaxUploadSize( $forType = null ) {
1913 global $wgMaxUploadSize;
1915 if ( is_array( $wgMaxUploadSize ) ) {
1916 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1917 return $wgMaxUploadSize[$forType];
1919 return $wgMaxUploadSize['*'];
1922 return intval( $wgMaxUploadSize );
1927 * Get the current status of a chunked upload (used for polling)
1929 * The value will be read from cache.
1932 * @param string $statusKey
1933 * @return Status[]|bool
1935 public static function getSessionStatus( User
$user, $statusKey ) {
1936 $key = wfMemcKey( 'uploadstatus', $user->getId() ?
: md5( $user->getName() ), $statusKey );
1938 return wfGetCache( CACHE_ANYTHING
)->get( $key );
1942 * Set the current status of a chunked upload (used for polling)
1944 * The value will be set in cache for 1 day
1947 * @param string $statusKey
1948 * @param array|bool $value
1951 public static function setSessionStatus( User
$user, $statusKey, $value ) {
1952 $key = wfMemcKey( 'uploadstatus', $user->getId() ?
: md5( $user->getName() ), $statusKey );
1954 $cache = wfGetCache( CACHE_ANYTHING
);
1955 if ( $value === false ) {
1956 $cache->delete( $key );
1958 $cache->set( $key, $value, 86400 );