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 $handler = new $className;
176 $handler->initializeFromRequest( $request );
182 * Check whether a request if valid for this handler
183 * @param WebRequest $request
186 public static function isValidRequest( $request ) {
190 public function __construct() {
194 * Returns the upload type. Should be overridden by child classes
199 public function getSourceType() {
204 * Initialize the path information
205 * @param string $name The desired destination name
206 * @param string $tempPath The temporary path
207 * @param int $fileSize The file size
208 * @param bool $removeTempFile (false) remove the temporary file?
209 * @throws MWException
211 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
212 $this->mDesiredDestName
= $name;
213 if ( FileBackend
::isStoragePath( $tempPath ) ) {
214 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
216 $this->mTempPath
= $tempPath;
217 $this->mFileSize
= $fileSize;
218 $this->mRemoveTempFile
= $removeTempFile;
222 * Initialize from a WebRequest. Override this in a subclass.
224 * @param WebRequest $request
226 abstract public function initializeFromRequest( &$request );
229 * Fetch the file. Usually a no-op
232 public function fetchFile() {
233 return Status
::newGood();
237 * Return true if the file is empty
240 public function isEmptyFile() {
241 return empty( $this->mFileSize
);
245 * Return the file size
248 public function getFileSize() {
249 return $this->mFileSize
;
253 * Get the base 36 SHA1 of the file
256 public function getTempFileSha1Base36() {
257 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
261 * @param string $srcPath The source path
262 * @return string|bool The real path if it was a virtual URL Returns false on failure
264 function getRealPath( $srcPath ) {
265 wfProfileIn( __METHOD__
);
266 $repo = RepoGroup
::singleton()->getLocalRepo();
267 if ( $repo->isVirtualUrl( $srcPath ) ) {
268 /** @todo Just make uploads work with storage paths UploadFromStash
269 * loads files via virtual URLs.
271 $tmpFile = $repo->getLocalCopy( $srcPath );
273 $tmpFile->bind( $this ); // keep alive with $this
275 $path = $tmpFile ?
$tmpFile->getPath() : false;
279 wfProfileOut( __METHOD__
);
285 * Verify whether the upload is sane.
286 * @return mixed Const self::OK or else an array with error information
288 public function verifyUpload() {
289 wfProfileIn( __METHOD__
);
292 * If there was no filename or a zero size given, give up quick.
294 if ( $this->isEmptyFile() ) {
295 wfProfileOut( __METHOD__
);
297 return array( 'status' => self
::EMPTY_FILE
);
301 * Honor $wgMaxUploadSize
303 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
304 if ( $this->mFileSize
> $maxSize ) {
305 wfProfileOut( __METHOD__
);
308 'status' => self
::FILE_TOO_LARGE
,
314 * Look at the contents of the file; if we can recognize the
315 * type but it's corrupt or data of the wrong type, we should
316 * probably not accept it.
318 $verification = $this->verifyFile();
319 if ( $verification !== true ) {
320 wfProfileOut( __METHOD__
);
323 'status' => self
::VERIFICATION_ERROR
,
324 'details' => $verification
329 * Make sure this file can be created
331 $result = $this->validateName();
332 if ( $result !== true ) {
333 wfProfileOut( __METHOD__
);
339 if ( !wfRunHooks( 'UploadVerification',
340 array( $this->mDestName
, $this->mTempPath
, &$error ) )
342 wfProfileOut( __METHOD__
);
344 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
347 wfProfileOut( __METHOD__
);
349 return array( 'status' => self
::OK
);
353 * Verify that the name is valid and, if necessary, that we can overwrite
355 * @return mixed True if valid, otherwise and array with 'status'
358 public function validateName() {
359 $nt = $this->getTitle();
360 if ( is_null( $nt ) ) {
361 $result = array( 'status' => $this->mTitleError
);
362 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
363 $result['filtered'] = $this->mFilteredName
;
365 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
366 $result['finalExt'] = $this->mFinalExtension
;
367 if ( count( $this->mBlackListedExtensions
) ) {
368 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
374 $this->mDestName
= $this->getLocalFile()->getName();
380 * Verify the MIME type.
382 * @note Only checks that it is not an evil MIME. The "does it have
383 * correct extension given its MIME type?" check is in verifyFile.
384 * in `verifyFile()` that MIME type and file extension correlate.
385 * @param string $mime Representing the MIME
386 * @return mixed True if the file is verified, an array otherwise
388 protected function verifyMimeType( $mime ) {
389 global $wgVerifyMimeType;
390 wfProfileIn( __METHOD__
);
391 if ( $wgVerifyMimeType ) {
392 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
393 global $wgMimeTypeBlacklist;
394 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
395 wfProfileOut( __METHOD__
);
397 return array( 'filetype-badmime', $mime );
400 # Check what Internet Explorer would detect
401 $fp = fopen( $this->mTempPath
, 'rb' );
402 $chunk = fread( $fp, 256 );
405 $magic = MimeMagic
::singleton();
406 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
407 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
408 foreach ( $ieTypes as $ieType ) {
409 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
410 wfProfileOut( __METHOD__
);
412 return array( 'filetype-bad-ie-mime', $ieType );
417 wfProfileOut( __METHOD__
);
423 * Verifies that it's ok to include the uploaded file
425 * @return mixed True of the file is verified, array otherwise.
427 protected function verifyFile() {
428 global $wgVerifyMimeType;
429 wfProfileIn( __METHOD__
);
431 $status = $this->verifyPartialFile();
432 if ( $status !== true ) {
433 wfProfileOut( __METHOD__
);
438 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
439 $mime = $this->mFileProps
['mime'];
441 if ( $wgVerifyMimeType ) {
442 # XXX: Missing extension will be caught by validateName() via getTitle()
443 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
444 wfProfileOut( __METHOD__
);
446 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
450 $handler = MediaHandler
::getHandler( $mime );
452 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
453 if ( !$handlerStatus->isOK() ) {
454 $errors = $handlerStatus->getErrorsArray();
455 wfProfileOut( __METHOD__
);
457 return reset( $errors );
461 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
462 if ( $status !== true ) {
463 wfProfileOut( __METHOD__
);
468 wfDebug( __METHOD__
. ": all clear; passing.\n" );
469 wfProfileOut( __METHOD__
);
475 * A verification routine suitable for partial files
477 * Runs the blacklist checks, but not any checks that may
478 * assume the entire file is present.
480 * @return mixed True for valid or array with error message key.
482 protected function verifyPartialFile() {
483 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
484 wfProfileIn( __METHOD__
);
486 # getTitle() sets some internal parameters like $this->mFinalExtension
489 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
491 # check MIME type, if desired
492 $mime = $this->mFileProps
['file-mime'];
493 $status = $this->verifyMimeType( $mime );
494 if ( $status !== true ) {
495 wfProfileOut( __METHOD__
);
500 # check for htmlish code and javascript
501 if ( !$wgDisableUploadScriptChecks ) {
502 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
503 wfProfileOut( __METHOD__
);
505 return array( 'uploadscripted' );
507 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
508 $svgStatus = $this->detectScriptInSvg( $this->mTempPath
);
509 if ( $svgStatus !== false ) {
510 wfProfileOut( __METHOD__
);
517 # Check for Java applets, which if uploaded can bypass cross-site
519 if ( !$wgAllowJavaUploads ) {
520 $this->mJavaDetected
= false;
521 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
522 array( $this, 'zipEntryCallback' ) );
523 if ( !$zipStatus->isOK() ) {
524 $errors = $zipStatus->getErrorsArray();
525 $error = reset( $errors );
526 if ( $error[0] !== 'zip-wrong-format' ) {
527 wfProfileOut( __METHOD__
);
532 if ( $this->mJavaDetected
) {
533 wfProfileOut( __METHOD__
);
535 return array( 'uploadjava' );
539 # Scan the uploaded file for viruses
540 $virus = $this->detectVirus( $this->mTempPath
);
542 wfProfileOut( __METHOD__
);
544 return array( 'uploadvirus', $virus );
547 wfProfileOut( __METHOD__
);
553 * Callback for ZipDirectoryReader to detect Java class files.
555 * @param array $entry
557 function zipEntryCallback( $entry ) {
558 $names = array( $entry['name'] );
560 // If there is a null character, cut off the name at it, because JDK's
561 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
562 // were constructed which had ".class\0" followed by a string chosen to
563 // make the hash collide with the truncated name, that file could be
564 // returned in response to a request for the .class file.
565 $nullPos = strpos( $entry['name'], "\000" );
566 if ( $nullPos !== false ) {
567 $names[] = substr( $entry['name'], 0, $nullPos );
570 // If there is a trailing slash in the file name, we have to strip it,
571 // because that's what ZIP_GetEntry() does.
572 if ( preg_grep( '!\.class/?$!', $names ) ) {
573 $this->mJavaDetected
= true;
578 * Alias for verifyTitlePermissions. The function was originally
579 * 'verifyPermissions', but that suggests it's checking the user, when it's
580 * really checking the title + user combination.
582 * @param User $user User object to verify the permissions against
583 * @return mixed An array as returned by getUserPermissionsErrors or true
584 * in case the user has proper permissions.
586 public function verifyPermissions( $user ) {
587 return $this->verifyTitlePermissions( $user );
591 * Check whether the user can edit, upload and create the image. This
592 * checks only against the current title; if it returns errors, it may
593 * very well be that another title will not give errors. Therefore
594 * isAllowed() should be called as well for generic is-user-blocked or
595 * can-user-upload checking.
597 * @param User $user User object to verify the permissions against
598 * @return mixed An array as returned by getUserPermissionsErrors or true
599 * in case the user has proper permissions.
601 public function verifyTitlePermissions( $user ) {
603 * If the image is protected, non-sysop users won't be able
604 * to modify it by uploading a new revision.
606 $nt = $this->getTitle();
607 if ( is_null( $nt ) ) {
610 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
611 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
612 if ( !$nt->exists() ) {
613 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
615 $permErrorsCreate = array();
617 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
618 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
619 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
624 $overwriteError = $this->checkOverwrite( $user );
625 if ( $overwriteError !== true ) {
626 return array( $overwriteError );
633 * Check for non fatal problems with the file.
635 * This should not assume that mTempPath is set.
637 * @return array Array of warnings
639 public function checkWarnings() {
641 wfProfileIn( __METHOD__
);
645 $localFile = $this->getLocalFile();
646 $filename = $localFile->getName();
649 * Check whether the resulting filename is different from the desired one,
650 * but ignore things like ucfirst() and spaces/underscore things
652 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
653 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
655 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
656 $warnings['badfilename'] = $filename;
657 // Debugging for bug 62241
658 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
659 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
662 // Check whether the file extension is on the unwanted list
663 global $wgCheckFileExtensions, $wgFileExtensions;
664 if ( $wgCheckFileExtensions ) {
665 $extensions = array_unique( $wgFileExtensions );
666 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
667 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
668 $wgLang->commaList( $extensions ), count( $extensions ) );
672 global $wgUploadSizeWarning;
673 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
674 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
677 if ( $this->mFileSize
== 0 ) {
678 $warnings['emptyfile'] = true;
681 $exists = self
::getExistsWarning( $localFile );
682 if ( $exists !== false ) {
683 $warnings['exists'] = $exists;
686 // Check dupes against existing files
687 $hash = $this->getTempFileSha1Base36();
688 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
689 $title = $this->getTitle();
690 // Remove all matches against self
691 foreach ( $dupes as $key => $dupe ) {
692 if ( $title->equals( $dupe->getTitle() ) ) {
693 unset( $dupes[$key] );
697 $warnings['duplicate'] = $dupes;
700 // Check dupes against archives
701 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
702 if ( $archivedImage->getID() > 0 ) {
703 if ( $archivedImage->userCan( File
::DELETED_FILE
) ) {
704 $warnings['duplicate-archive'] = $archivedImage->getName();
706 $warnings['duplicate-archive'] = '';
710 wfProfileOut( __METHOD__
);
716 * Really perform the upload. Stores the file in the local repo, watches
717 * if necessary and runs the UploadComplete hook.
719 * @param string $comment
720 * @param string $pageText
724 * @return Status Indicating the whether the upload succeeded.
726 public function performUpload( $comment, $pageText, $watch, $user ) {
727 wfProfileIn( __METHOD__
);
729 $status = $this->getLocalFile()->upload(
739 if ( $status->isGood() ) {
741 WatchAction
::doWatch(
742 $this->getLocalFile()->getTitle(),
744 WatchedItem
::IGNORE_USER_RIGHTS
747 wfRunHooks( 'UploadComplete', array( &$this ) );
750 wfProfileOut( __METHOD__
);
756 * Returns the title of the file to be uploaded. Sets mTitleError in case
757 * the name was illegal.
759 * @return Title The title of the file or null in case the name was illegal
761 public function getTitle() {
762 if ( $this->mTitle
!== false ) {
763 return $this->mTitle
;
765 /* Assume that if a user specified File:Something.jpg, this is an error
766 * and that the namespace prefix needs to be stripped of.
768 $title = Title
::newFromText( $this->mDesiredDestName
);
769 if ( $title && $title->getNamespace() == NS_FILE
) {
770 $this->mFilteredName
= $title->getDBkey();
772 $this->mFilteredName
= $this->mDesiredDestName
;
775 # oi_archive_name is max 255 bytes, which include a timestamp and an
776 # exclamation mark, so restrict file name to 240 bytes.
777 if ( strlen( $this->mFilteredName
) > 240 ) {
778 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
779 $this->mTitle
= null;
781 return $this->mTitle
;
785 * Chop off any directories in the given filename. Then
786 * filter out illegal characters, and try to make a legible name
787 * out of it. We'll strip some silently that Title would die on.
789 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
790 /* Normalize to title form before we do any further processing */
791 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
792 if ( is_null( $nt ) ) {
793 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
794 $this->mTitle
= null;
796 return $this->mTitle
;
798 $this->mFilteredName
= $nt->getDBkey();
801 * We'll want to blacklist against *any* 'extension', and use
802 * only the final one for the whitelist.
804 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
806 if ( count( $ext ) ) {
807 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
809 $this->mFinalExtension
= '';
811 # No extension, try guessing one
812 $magic = MimeMagic
::singleton();
813 $mime = $magic->guessMimeType( $this->mTempPath
);
814 if ( $mime !== 'unknown/unknown' ) {
815 # Get a space separated list of extensions
816 $extList = $magic->getExtensionsForType( $mime );
818 # Set the extension to the canonical extension
819 $this->mFinalExtension
= strtok( $extList, ' ' );
821 # Fix up the other variables
822 $this->mFilteredName
.= ".{$this->mFinalExtension}";
823 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
824 $ext = array( $this->mFinalExtension
);
829 /* Don't allow users to override the blacklist (check file extension) */
830 global $wgCheckFileExtensions, $wgStrictFileExtensions;
831 global $wgFileExtensions, $wgFileBlacklist;
833 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
835 if ( $this->mFinalExtension
== '' ) {
836 $this->mTitleError
= self
::FILETYPE_MISSING
;
837 $this->mTitle
= null;
839 return $this->mTitle
;
840 } elseif ( $blackListedExtensions ||
841 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
842 !$this->checkFileExtension( $this->mFinalExtension
, $wgFileExtensions ) )
844 $this->mBlackListedExtensions
= $blackListedExtensions;
845 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
846 $this->mTitle
= null;
848 return $this->mTitle
;
851 // Windows may be broken with special characters, see bug 1780
852 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
853 && !RepoGroup
::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
855 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
856 $this->mTitle
= null;
858 return $this->mTitle
;
861 # If there was more than one "extension", reassemble the base
862 # filename to prevent bogus complaints about length
863 if ( count( $ext ) > 1 ) {
864 $iterations = count( $ext ) - 1;
865 for ( $i = 0; $i < $iterations; $i++
) {
866 $partname .= '.' . $ext[$i];
870 if ( strlen( $partname ) < 1 ) {
871 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
872 $this->mTitle
= null;
874 return $this->mTitle
;
879 return $this->mTitle
;
883 * Return the local file and initializes if necessary.
885 * @return LocalFile|null
887 public function getLocalFile() {
888 if ( is_null( $this->mLocalFile
) ) {
889 $nt = $this->getTitle();
890 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
893 return $this->mLocalFile
;
897 * If the user does not supply all necessary information in the first upload
898 * form submission (either by accident or by design) then we may want to
899 * stash the file temporarily, get more information, and publish the file
902 * This method will stash a file in a temporary directory for later
903 * processing, and save the necessary descriptive info into the database.
904 * This method returns the file object, which also has a 'fileKey' property
905 * which can be passed through a form or API request to find this stashed
909 * @return UploadStashFile Stashed file
911 public function stashFile( User
$user = null ) {
912 // was stashSessionFile
913 wfProfileIn( __METHOD__
);
915 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
916 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
917 $this->mLocalFile
= $file;
919 wfProfileOut( __METHOD__
);
925 * Stash a file in a temporary directory, returning a key which can be used
926 * to find the file again. See stashFile().
928 * @return string File key
930 public function stashFileGetKey() {
931 return $this->stashFile()->getFileKey();
935 * alias for stashFileGetKey, for backwards compatibility
937 * @return string File key
939 public function stashSession() {
940 return $this->stashFileGetKey();
944 * If we've modified the upload file we need to manually remove it
945 * on exit to clean up.
947 public function cleanupTempFile() {
948 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
949 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
950 unlink( $this->mTempPath
);
954 public function getTempPath() {
955 return $this->mTempPath
;
959 * Split a file into a base name and all dot-delimited 'extensions'
960 * on the end. Some web server configurations will fall back to
961 * earlier pseudo-'extensions' to determine type and execute
962 * scripts, so the blacklist needs to check them all.
964 * @param string $filename
967 public static function splitExtensions( $filename ) {
968 $bits = explode( '.', $filename );
969 $basename = array_shift( $bits );
971 return array( $basename, $bits );
975 * Perform case-insensitive match against a list of file extensions.
976 * Returns true if the extension is in the list.
982 public static function checkFileExtension( $ext, $list ) {
983 return in_array( strtolower( $ext ), $list );
987 * Perform case-insensitive match against a list of file extensions.
988 * Returns an array of matching extensions.
994 public static function checkFileExtensionList( $ext, $list ) {
995 return array_intersect( array_map( 'strtolower', $ext ), $list );
999 * Checks if the MIME type of the uploaded file matches the file extension.
1001 * @param string $mime The MIME type of the uploaded file
1002 * @param string $extension The filename extension that the file is to be served with
1005 public static function verifyExtension( $mime, $extension ) {
1006 $magic = MimeMagic
::singleton();
1008 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
1009 if ( !$magic->isRecognizableExtension( $extension ) ) {
1010 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
1011 "unrecognized extension '$extension', can't verify\n" );
1015 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
1016 "recognized extension '$extension', so probably invalid file\n" );
1022 $match = $magic->isMatchingExtension( $extension, $mime );
1024 if ( $match === null ) {
1025 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1026 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
1030 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
1034 } elseif ( $match === true ) {
1035 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
1037 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1041 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1048 * Heuristic for detecting files that *could* contain JavaScript instructions or
1049 * things that may look like HTML to a browser and are thus
1050 * potentially harmful. The present implementation will produce false
1051 * positives in some situations.
1053 * @param string $file Pathname to the temporary upload file
1054 * @param string $mime The MIME type of the file
1055 * @param string $extension The extension of the file
1056 * @return bool True if the file contains something looking like embedded scripts
1058 public static function detectScript( $file, $mime, $extension ) {
1059 global $wgAllowTitlesInSVG;
1060 wfProfileIn( __METHOD__
);
1062 # ugly hack: for text files, always look at the entire file.
1063 # For binary field, just check the first K.
1065 if ( strpos( $mime, 'text/' ) === 0 ) {
1066 $chunk = file_get_contents( $file );
1068 $fp = fopen( $file, 'rb' );
1069 $chunk = fread( $fp, 1024 );
1073 $chunk = strtolower( $chunk );
1076 wfProfileOut( __METHOD__
);
1081 # decode from UTF-16 if needed (could be used for obfuscation).
1082 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1084 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1091 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1094 $chunk = trim( $chunk );
1096 /** @todo FIXME: Convert from UTF-16 if necessary! */
1097 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1099 # check for HTML doctype
1100 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1101 wfProfileOut( __METHOD__
);
1106 // Some browsers will interpret obscure xml encodings as UTF-8, while
1107 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1108 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1109 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1110 wfProfileOut( __METHOD__
);
1117 * Internet Explorer for Windows performs some really stupid file type
1118 * autodetection which can cause it to interpret valid image files as HTML
1119 * and potentially execute JavaScript, creating a cross-site scripting
1122 * Apple's Safari browser also performs some unsafe file type autodetection
1123 * which can cause legitimate files to be interpreted as HTML if the
1124 * web server is not correctly configured to send the right content-type
1125 * (or if you're really uploading plain text and octet streams!)
1127 * Returns true if IE is likely to mistake the given file for HTML.
1128 * Also returns true if Safari would mistake the given file for HTML
1129 * when served with a generic content-type.
1135 '<html', #also in safari
1138 '<script', #also in safari
1142 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1146 foreach ( $tags as $tag ) {
1147 if ( false !== strpos( $chunk, $tag ) ) {
1148 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1149 wfProfileOut( __METHOD__
);
1156 * look for JavaScript
1159 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1160 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1162 # look for script-types
1163 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1164 wfDebug( __METHOD__
. ": found script types\n" );
1165 wfProfileOut( __METHOD__
);
1170 # look for html-style script-urls
1171 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1172 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1173 wfProfileOut( __METHOD__
);
1178 # look for css-style script-urls
1179 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1180 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1181 wfProfileOut( __METHOD__
);
1186 wfDebug( __METHOD__
. ": no scripts found\n" );
1187 wfProfileOut( __METHOD__
);
1193 * Check a whitelist of xml encodings that are known not to be interpreted differently
1194 * by the server's xml parser (expat) and some common browsers.
1196 * @param string $file Pathname to the temporary upload file
1197 * @return bool True if the file contains an encoding that could be misinterpreted
1199 public static function checkXMLEncodingMissmatch( $file ) {
1200 global $wgSVGMetadataCutoff;
1201 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1202 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1204 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1205 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1206 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1208 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1212 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1213 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1214 // bytes. There shouldn't be a legitimate reason for this to happen.
1215 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1218 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1219 // EBCDIC encoded XML
1220 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1225 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1226 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1227 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1228 foreach ( $attemptEncodings as $encoding ) {
1229 wfSuppressWarnings();
1230 $str = iconv( $encoding, 'UTF-8', $contents );
1231 wfRestoreWarnings();
1232 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1233 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1234 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1236 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1240 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1241 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1242 // bytes. There shouldn't be a legitimate reason for this to happen.
1243 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1253 * @param string $filename
1254 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1256 protected function detectScriptInSvg( $filename ) {
1257 $this->mSVGNSError
= false;
1258 $check = new XmlTypeCheck(
1260 array( $this, 'checkSvgScriptCallback' ),
1262 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1264 if ( $check->wellFormed
!== true ) {
1265 // Invalid xml (bug 58553)
1266 return array( 'uploadinvalidxml' );
1267 } elseif ( $check->filterMatch
) {
1268 if ( $this->mSVGNSError
) {
1269 return array( 'uploadscriptednamespace', $this->mSVGNSError
);
1272 return array( 'uploadscripted' );
1279 * Callback to filter SVG Processing Instructions.
1280 * @param string $target Processing instruction name
1281 * @param string $data Processing instruction attribute and value
1282 * @return bool (true if the filter identified something bad)
1284 public static function checkSvgPICallback( $target, $data ) {
1285 // Don't allow external stylesheets (bug 57550)
1286 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1294 * @todo Replace this with a whitelist filter!
1295 * @param string $element
1296 * @param array $attribs
1299 public function checkSvgScriptCallback( $element, $attribs ) {
1300 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1302 // We specifically don't include:
1303 // http://www.w3.org/1999/xhtml (bug 60771)
1304 static $validNamespaces = array(
1307 'http://creativecommons.org/ns#',
1308 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1309 'http://ns.adobe.com/adobeillustrator/10.0/',
1310 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1311 'http://ns.adobe.com/extensibility/1.0/',
1312 'http://ns.adobe.com/flows/1.0/',
1313 'http://ns.adobe.com/illustrator/1.0/',
1314 'http://ns.adobe.com/imagereplacement/1.0/',
1315 'http://ns.adobe.com/pdf/1.3/',
1316 'http://ns.adobe.com/photoshop/1.0/',
1317 'http://ns.adobe.com/saveforweb/1.0/',
1318 'http://ns.adobe.com/variables/1.0/',
1319 'http://ns.adobe.com/xap/1.0/',
1320 'http://ns.adobe.com/xap/1.0/g/',
1321 'http://ns.adobe.com/xap/1.0/g/img/',
1322 'http://ns.adobe.com/xap/1.0/mm/',
1323 'http://ns.adobe.com/xap/1.0/rights/',
1324 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1325 'http://ns.adobe.com/xap/1.0/stype/font#',
1326 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1327 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1328 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1329 'http://ns.adobe.com/xap/1.0/t/pg/',
1330 'http://purl.org/dc/elements/1.1/',
1331 'http://purl.org/dc/elements/1.1',
1332 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1333 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1334 'http://taptrix.com/inkpad/svg_extensions',
1335 'http://web.resource.org/cc/',
1336 'http://www.freesoftware.fsf.org/bkchem/cdml',
1337 'http://www.inkscape.org/namespaces/inkscape',
1338 'http://www.opengis.net/gml',
1339 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1340 'http://www.w3.org/2000/svg',
1341 'http://www.w3.org/tr/rec-rdf-syntax/',
1344 if ( !in_array( $namespace, $validNamespaces ) ) {
1345 wfDebug( __METHOD__
. ": Non-svg namespace '$namespace' in uploaded file.\n" );
1346 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1347 $this->mSVGNSError
= $namespace;
1353 * check for elements that can contain javascript
1355 if ( $strippedElement == 'script' ) {
1356 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1361 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1362 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1363 if ( $strippedElement == 'handler' ) {
1364 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1369 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1370 if ( $strippedElement == 'stylesheet' ) {
1371 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1376 # Block iframes, in case they pass the namespace check
1377 if ( $strippedElement == 'iframe' ) {
1378 wfDebug( __METHOD__
. ": iframe in uploaded file.\n" );
1383 foreach ( $attribs as $attrib => $value ) {
1384 $stripped = $this->stripXmlNamespace( $attrib );
1385 $value = strtolower( $value );
1387 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1389 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1394 # href with non-local target (don't allow http://, javascript:, etc)
1395 if ( $stripped == 'href'
1396 && strpos( $value, 'data:' ) !== 0
1397 && strpos( $value, '#' ) !== 0
1399 if ( !( $strippedElement === 'a'
1400 && preg_match( '!^https?://!im', $value ) )
1402 wfDebug( __METHOD__
. ": Found href attribute <$strippedElement "
1403 . "'$attrib'='$value' in uploaded file.\n" );
1409 # href with embedded svg as target
1410 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1411 wfDebug( __METHOD__
. ": Found href to embedded svg "
1412 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1417 # href with embedded (text/xml) svg as target
1418 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1419 wfDebug( __METHOD__
. ": Found href to embedded svg "
1420 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1425 # use set/animate to add event-handler attribute to parent
1426 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' )
1427 && $stripped == 'attributename'
1428 && substr( $value, 0, 2 ) == 'on'
1430 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with "
1431 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1436 # use set to add href attribute to parent element
1437 if ( $strippedElement == 'set'
1438 && $stripped == 'attributename'
1439 && strpos( $value, 'href' ) !== false
1441 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1446 # use set to add a remote / data / script target to an element
1447 if ( $strippedElement == 'set'
1448 && $stripped == 'to'
1449 && preg_match( '!(http|https|data|script):!sim', $value )
1451 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1456 # use handler attribute with remote / data / script
1457 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1458 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script "
1459 . "'$attrib'='$value' in uploaded file.\n" );
1464 # use CSS styles to bring in remote code
1465 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1466 $tagsList = "font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke";
1467 if ( $stripped == 'style'
1469 '!((?:' . $tagsList . ')\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim',
1474 foreach ( $matches[1] as $match ) {
1475 if ( !preg_match( '!(?:' . $tagsList . ')\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1476 wfDebug( __METHOD__
. ": Found svg setting a style with "
1477 . "remote url '$attrib'='$value' in uploaded file.\n" );
1484 # image filters can pull in url, which could be svg that executes scripts
1485 if ( $strippedElement == 'image'
1486 && $stripped == 'filter'
1487 && preg_match( '!url\s*\(!sim', $value )
1489 wfDebug( __METHOD__
. ": Found image filter with url: "
1490 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1496 return false; //No scripts detected
1500 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1501 * @param string $name
1502 * @return array Containing the namespace URI and prefix
1504 private static function splitXmlNamespace( $element ) {
1505 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1506 $parts = explode( ':', strtolower( $element ) );
1507 $name = array_pop( $parts );
1508 $ns = implode( ':', $parts );
1510 return array( $ns, $name );
1514 * @param string $name
1517 private function stripXmlNamespace( $name ) {
1518 // 'http://www.w3.org/2000/svg:script' -> 'script'
1519 $parts = explode( ':', strtolower( $name ) );
1521 return array_pop( $parts );
1525 * Generic wrapper function for a virus scanner program.
1526 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1527 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1529 * @param string $file Pathname to the temporary upload file
1530 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1531 * or a string containing feedback from the virus scanner if a virus was found.
1532 * If textual feedback is missing but a virus was found, this function returns true.
1534 public static function detectVirus( $file ) {
1535 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1536 wfProfileIn( __METHOD__
);
1538 if ( !$wgAntivirus ) {
1539 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1540 wfProfileOut( __METHOD__
);
1545 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1546 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1547 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1548 array( 'virus-badscanner', $wgAntivirus ) );
1549 wfProfileOut( __METHOD__
);
1551 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1554 # look up scanner configuration
1555 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1556 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1557 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1558 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1560 if ( strpos( $command, "%f" ) === false ) {
1561 # simple pattern: append file to scan
1562 $command .= " " . wfEscapeShellArg( $file );
1564 # complex pattern: replace "%f" with file to scan
1565 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1568 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1570 # execute virus scanner
1573 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1574 # that does not seem to be worth the pain.
1575 # Ask me (Duesentrieb) about it if it's ever needed.
1576 $output = wfShellExecWithStderr( $command, $exitCode );
1578 # map exit code to AV_xxx constants.
1579 $mappedCode = $exitCode;
1580 if ( $exitCodeMap ) {
1581 if ( isset( $exitCodeMap[$exitCode] ) ) {
1582 $mappedCode = $exitCodeMap[$exitCode];
1583 } elseif ( isset( $exitCodeMap["*"] ) ) {
1584 $mappedCode = $exitCodeMap["*"];
1588 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1589 * so we need the strict equalities === and thus can't use a switch here
1591 if ( $mappedCode === AV_SCAN_FAILED
) {
1592 # scan failed (code was mapped to false by $exitCodeMap)
1593 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1595 $output = $wgAntivirusRequired
1596 ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1598 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1599 # scan failed because filetype is unknown (probably imune)
1600 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1602 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1604 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1607 $output = trim( $output );
1610 $output = true; #if there's no output, return true
1611 } elseif ( $msgPattern ) {
1613 if ( preg_match( $msgPattern, $output, $groups ) ) {
1615 $output = $groups[1];
1620 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1623 wfProfileOut( __METHOD__
);
1629 * Check if there's an overwrite conflict and, if so, if restrictions
1630 * forbid this user from performing the upload.
1634 * @return mixed True on success, array on failure
1636 private function checkOverwrite( $user ) {
1637 // First check whether the local file can be overwritten
1638 $file = $this->getLocalFile();
1639 if ( $file->exists() ) {
1640 if ( !self
::userCanReUpload( $user, $file ) ) {
1641 return array( 'fileexists-forbidden', $file->getName() );
1647 /* Check shared conflicts: if the local file does not exist, but
1648 * wfFindFile finds a file, it exists in a shared repository.
1650 $file = wfFindFile( $this->getTitle() );
1651 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1652 return array( 'fileexists-shared-forbidden', $file->getName() );
1659 * Check if a user is the last uploader
1662 * @param string $img Image name
1665 public static function userCanReUpload( User
$user, $img ) {
1666 if ( $user->isAllowed( 'reupload' ) ) {
1667 return true; // non-conditional
1669 if ( !$user->isAllowed( 'reupload-own' ) ) {
1672 if ( is_string( $img ) ) {
1673 $img = wfLocalFile( $img );
1675 if ( !( $img instanceof LocalFile
) ) {
1679 return $user->getId() == $img->getUser( 'id' );
1683 * Helper function that does various existence checks for a file.
1684 * The following checks are performed:
1686 * - Article with the same name as the file exists
1687 * - File exists with normalized extension
1688 * - The file looks like a thumbnail and the original exists
1690 * @param File $file The File object to check
1691 * @return mixed False if the file does not exists, else an array
1693 public static function getExistsWarning( $file ) {
1694 if ( $file->exists() ) {
1695 return array( 'warning' => 'exists', 'file' => $file );
1698 if ( $file->getTitle()->getArticleID() ) {
1699 return array( 'warning' => 'page-exists', 'file' => $file );
1702 if ( $file->wasDeleted() && !$file->exists() ) {
1703 return array( 'warning' => 'was-deleted', 'file' => $file );
1706 if ( strpos( $file->getName(), '.' ) == false ) {
1707 $partname = $file->getName();
1710 $n = strrpos( $file->getName(), '.' );
1711 $extension = substr( $file->getName(), $n +
1 );
1712 $partname = substr( $file->getName(), 0, $n );
1714 $normalizedExtension = File
::normalizeExtension( $extension );
1716 if ( $normalizedExtension != $extension ) {
1717 // We're not using the normalized form of the extension.
1718 // Normal form is lowercase, using most common of alternate
1719 // extensions (eg 'jpg' rather than 'JPEG').
1721 // Check for another file using the normalized form...
1722 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1723 $file_lc = wfLocalFile( $nt_lc );
1725 if ( $file_lc->exists() ) {
1727 'warning' => 'exists-normalized',
1729 'normalizedFile' => $file_lc
1734 // Check for files with the same name but a different extension
1735 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1736 "{$partname}.", 1 );
1737 if ( count( $similarFiles ) ) {
1739 'warning' => 'exists-normalized',
1741 'normalizedFile' => $similarFiles[0],
1745 if ( self
::isThumbName( $file->getName() ) ) {
1746 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1747 $nt_thb = Title
::newFromText(
1748 substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension,
1751 $file_thb = wfLocalFile( $nt_thb );
1752 if ( $file_thb->exists() ) {
1754 'warning' => 'thumb',
1756 'thumbFile' => $file_thb
1759 // File does not exist, but we just don't like the name
1761 'warning' => 'thumb-name',
1763 'thumbFile' => $file_thb
1768 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1769 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1771 'warning' => 'bad-prefix',
1782 * Helper function that checks whether the filename looks like a thumbnail
1783 * @param string $filename
1786 public static function isThumbName( $filename ) {
1787 $n = strrpos( $filename, '.' );
1788 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1791 substr( $partname, 3, 3 ) == 'px-' ||
1792 substr( $partname, 2, 3 ) == 'px-'
1794 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1798 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1800 * @return array List of prefixes
1802 public static function getFilenamePrefixBlacklist() {
1803 $blacklist = array();
1804 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1805 if ( !$message->isDisabled() ) {
1806 $lines = explode( "\n", $message->plain() );
1807 foreach ( $lines as $line ) {
1808 // Remove comment lines
1809 $comment = substr( trim( $line ), 0, 1 );
1810 if ( $comment == '#' ||
$comment == '' ) {
1813 // Remove additional comments after a prefix
1814 $comment = strpos( $line, '#' );
1815 if ( $comment > 0 ) {
1816 $line = substr( $line, 0, $comment - 1 );
1818 $blacklist[] = trim( $line );
1826 * Gets image info about the file just uploaded.
1828 * Also has the effect of setting metadata to be an 'indexed tag name' in
1829 * returned API result if 'metadata' was requested. Oddly, we have to pass
1830 * the "result" object down just so it can do that with the appropriate
1831 * format, presumably.
1833 * @param ApiResult $result
1834 * @return array Image info
1836 public function getImageInfo( $result ) {
1837 $file = $this->getLocalFile();
1838 /** @todo This cries out for refactoring.
1839 * We really want to say $file->getAllInfo(); here.
1840 * Perhaps "info" methods should be moved into files, and the API should
1841 * just wrap them in queries.
1843 if ( $file instanceof UploadStashFile
) {
1844 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1845 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1847 $imParam = ApiQueryImageInfo
::getPropertyNames();
1848 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1855 * @param array $error
1858 public function convertVerifyErrorToStatus( $error ) {
1859 $code = $error['status'];
1860 unset( $code['status'] );
1862 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1866 * @param null|string $forType
1869 public static function getMaxUploadSize( $forType = null ) {
1870 global $wgMaxUploadSize;
1872 if ( is_array( $wgMaxUploadSize ) ) {
1873 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1874 return $wgMaxUploadSize[$forType];
1876 return $wgMaxUploadSize['*'];
1879 return intval( $wgMaxUploadSize );
1884 * Get the current status of a chunked upload (used for polling).
1885 * The status will be read from the *current* user session.
1886 * @param string $statusKey
1887 * @return array|bool
1889 public static function getSessionStatus( $statusKey ) {
1890 return isset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] )
1891 ?
$_SESSION[self
::SESSION_STATUS_KEY
][$statusKey]
1896 * Set the current status of a chunked upload (used for polling).
1897 * The status will be stored in the *current* user session.
1898 * @param string $statusKey
1899 * @param array|bool $value
1902 public static function setSessionStatus( $statusKey, $value ) {
1903 if ( $value === false ) {
1904 unset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] );
1906 $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] = $value;