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;
47 protected static $safeXmlEncodings = array( 'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'UTF-16', 'UTF-32' );
52 const MIN_LENGTH_PARTNAME
= 4;
53 const ILLEGAL_FILENAME
= 5;
54 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
55 const FILETYPE_MISSING
= 8;
56 const FILETYPE_BADTYPE
= 9;
57 const VERIFICATION_ERROR
= 10;
59 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
60 const UPLOAD_VERIFICATION_ERROR
= 11;
61 const HOOK_ABORTED
= 11;
62 const FILE_TOO_LARGE
= 12;
63 const WINDOWS_NONASCII_FILENAME
= 13;
64 const FILENAME_TOO_LONG
= 14;
66 const SESSION_STATUS_KEY
= 'wsUploadStatusData';
72 public function getVerificationErrorCode( $error ) {
73 $code_to_status = array(
74 self
::EMPTY_FILE
=> 'empty-file',
75 self
::FILE_TOO_LARGE
=> 'file-too-large',
76 self
::FILETYPE_MISSING
=> 'filetype-missing',
77 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
78 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
79 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
80 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
81 self
::VERIFICATION_ERROR
=> 'verification-error',
82 self
::HOOK_ABORTED
=> 'hookaborted',
83 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
84 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
86 if ( isset( $code_to_status[$error] ) ) {
87 return $code_to_status[$error];
90 return 'unknown-error';
94 * Returns true if uploads are enabled.
95 * Can be override by subclasses.
98 public static function isEnabled() {
99 global $wgEnableUploads;
101 if ( !$wgEnableUploads ) {
105 # Check php's file_uploads setting
106 return wfIsHHVM() ||
wfIniGetBool( 'file_uploads' );
110 * Returns true if the user can use this upload module or else a string
111 * identifying the missing permission.
112 * Can be overridden by subclasses.
117 public static function isAllowed( $user ) {
118 foreach ( array( 'upload', 'edit' ) as $permission ) {
119 if ( !$user->isAllowed( $permission ) ) {
126 // Upload handlers. Should probably just be a global.
127 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
130 * Create a form of UploadBase depending on wpSourceType and initializes it
132 * @param $request WebRequest
136 public static function createFromRequest( &$request, $type = null ) {
137 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
143 // Get the upload class
144 $type = ucfirst( $type );
146 // Give hooks the chance to handle this request
148 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
149 if ( is_null( $className ) ) {
150 $className = 'UploadFrom' . $type;
151 wfDebug( __METHOD__
. ": class name: $className\n" );
152 if ( !in_array( $type, self
::$uploadHandlers ) ) {
157 // Check whether this upload class is enabled
158 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
162 // Check whether the request is valid
163 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
167 $handler = new $className;
169 $handler->initializeFromRequest( $request );
174 * Check whether a request if valid for this handler
178 public static function isValidRequest( $request ) {
182 public function __construct() {}
185 * Returns the upload type. Should be overridden by child classes
190 public function getSourceType() {
195 * Initialize the path information
196 * @param string $name the desired destination name
197 * @param string $tempPath the temporary path
198 * @param int $fileSize the file size
199 * @param bool $removeTempFile (false) remove the temporary file?
200 * @throws MWException
202 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
203 $this->mDesiredDestName
= $name;
204 if ( FileBackend
::isStoragePath( $tempPath ) ) {
205 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
207 $this->mTempPath
= $tempPath;
208 $this->mFileSize
= $fileSize;
209 $this->mRemoveTempFile
= $removeTempFile;
213 * Initialize from a WebRequest. Override this in a subclass.
215 abstract public function initializeFromRequest( &$request );
218 * Fetch the file. Usually a no-op
221 public function fetchFile() {
222 return Status
::newGood();
226 * Return true if the file is empty
229 public function isEmptyFile() {
230 return empty( $this->mFileSize
);
234 * Return the file size
237 public function getFileSize() {
238 return $this->mFileSize
;
242 * Get the base 36 SHA1 of the file
245 public function getTempFileSha1Base36() {
246 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
250 * @param string $srcPath the source path
251 * @return string|bool the real path if it was a virtual URL Returns false on failure
253 function getRealPath( $srcPath ) {
254 wfProfileIn( __METHOD__
);
255 $repo = RepoGroup
::singleton()->getLocalRepo();
256 if ( $repo->isVirtualUrl( $srcPath ) ) {
257 // @todo just make uploads work with storage paths
258 // UploadFromStash loads files via virtual URLs
259 $tmpFile = $repo->getLocalCopy( $srcPath );
261 $tmpFile->bind( $this ); // keep alive with $this
263 $path = $tmpFile ?
$tmpFile->getPath() : false;
267 wfProfileOut( __METHOD__
);
272 * Verify whether the upload is sane.
273 * @return mixed self::OK or else an array with error information
275 public function verifyUpload() {
276 wfProfileIn( __METHOD__
);
279 * If there was no filename or a zero size given, give up quick.
281 if ( $this->isEmptyFile() ) {
282 wfProfileOut( __METHOD__
);
283 return array( 'status' => self
::EMPTY_FILE
);
287 * Honor $wgMaxUploadSize
289 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
290 if ( $this->mFileSize
> $maxSize ) {
291 wfProfileOut( __METHOD__
);
293 'status' => self
::FILE_TOO_LARGE
,
299 * Look at the contents of the file; if we can recognize the
300 * type but it's corrupt or data of the wrong type, we should
301 * probably not accept it.
303 $verification = $this->verifyFile();
304 if ( $verification !== true ) {
305 wfProfileOut( __METHOD__
);
307 'status' => self
::VERIFICATION_ERROR
,
308 'details' => $verification
313 * Make sure this file can be created
315 $result = $this->validateName();
316 if ( $result !== true ) {
317 wfProfileOut( __METHOD__
);
322 if ( !wfRunHooks( 'UploadVerification',
323 array( $this->mDestName
, $this->mTempPath
, &$error ) )
325 wfProfileOut( __METHOD__
);
326 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
329 wfProfileOut( __METHOD__
);
330 return array( 'status' => self
::OK
);
334 * Verify that the name is valid and, if necessary, that we can overwrite
336 * @return mixed true if valid, otherwise and array with 'status'
339 public function validateName() {
340 $nt = $this->getTitle();
341 if ( is_null( $nt ) ) {
342 $result = array( 'status' => $this->mTitleError
);
343 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
344 $result['filtered'] = $this->mFilteredName
;
346 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
347 $result['finalExt'] = $this->mFinalExtension
;
348 if ( count( $this->mBlackListedExtensions
) ) {
349 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
354 $this->mDestName
= $this->getLocalFile()->getName();
360 * Verify the mime type.
362 * @note Only checks that it is not an evil mime. The does it have
363 * correct extension given its mime type check is in verifyFile.
364 * @param string $mime representing the mime
365 * @return mixed true if the file is verified, an array otherwise
367 protected function verifyMimeType( $mime ) {
368 global $wgVerifyMimeType;
369 wfProfileIn( __METHOD__
);
370 if ( $wgVerifyMimeType ) {
371 wfDebug( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
372 global $wgMimeTypeBlacklist;
373 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
374 wfProfileOut( __METHOD__
);
375 return array( 'filetype-badmime', $mime );
379 $fp = fopen( $this->mTempPath
, 'rb' );
380 $chunk = fread( $fp, 256 );
383 $magic = MimeMagic
::singleton();
384 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
385 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
386 foreach ( $ieTypes as $ieType ) {
387 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
388 wfProfileOut( __METHOD__
);
389 return array( 'filetype-bad-ie-mime', $ieType );
394 wfProfileOut( __METHOD__
);
399 * Verifies that it's ok to include the uploaded file
401 * @return mixed true of the file is verified, array otherwise.
403 protected function verifyFile() {
404 global $wgVerifyMimeType;
405 wfProfileIn( __METHOD__
);
407 $status = $this->verifyPartialFile();
408 if ( $status !== true ) {
409 wfProfileOut( __METHOD__
);
413 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
414 $mime = $this->mFileProps
['file-mime'];
416 if ( $wgVerifyMimeType ) {
417 # XXX: Missing extension will be caught by validateName() via getTitle()
418 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
419 wfProfileOut( __METHOD__
);
420 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
424 $handler = MediaHandler
::getHandler( $mime );
426 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
427 if ( !$handlerStatus->isOK() ) {
428 $errors = $handlerStatus->getErrorsArray();
429 wfProfileOut( __METHOD__
);
430 return reset( $errors );
434 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
435 if ( $status !== true ) {
436 wfProfileOut( __METHOD__
);
440 wfDebug( __METHOD__
. ": all clear; passing.\n" );
441 wfProfileOut( __METHOD__
);
446 * A verification routine suitable for partial files
448 * Runs the blacklist checks, but not any checks that may
449 * assume the entire file is present.
451 * @return Mixed true for valid or array with error message key.
453 protected function verifyPartialFile() {
454 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
455 wfProfileIn( __METHOD__
);
457 # getTitle() sets some internal parameters like $this->mFinalExtension
460 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
462 # check mime type, if desired
463 $mime = $this->mFileProps
['file-mime'];
464 $status = $this->verifyMimeType( $mime );
465 if ( $status !== true ) {
466 wfProfileOut( __METHOD__
);
470 # check for htmlish code and javascript
471 if ( !$wgDisableUploadScriptChecks ) {
472 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
473 wfProfileOut( __METHOD__
);
474 return array( 'uploadscripted' );
476 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
477 if ( $this->detectScriptInSvg( $this->mTempPath
) ) {
478 wfProfileOut( __METHOD__
);
479 return array( 'uploadscripted' );
484 # Check for Java applets, which if uploaded can bypass cross-site
486 if ( !$wgAllowJavaUploads ) {
487 $this->mJavaDetected
= false;
488 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
489 array( $this, 'zipEntryCallback' ) );
490 if ( !$zipStatus->isOK() ) {
491 $errors = $zipStatus->getErrorsArray();
492 $error = reset( $errors );
493 if ( $error[0] !== 'zip-wrong-format' ) {
494 wfProfileOut( __METHOD__
);
498 if ( $this->mJavaDetected
) {
499 wfProfileOut( __METHOD__
);
500 return array( 'uploadjava' );
504 # Scan the uploaded file for viruses
505 $virus = $this->detectVirus( $this->mTempPath
);
507 wfProfileOut( __METHOD__
);
508 return array( 'uploadvirus', $virus );
511 wfProfileOut( __METHOD__
);
516 * Callback for ZipDirectoryReader to detect Java class files.
518 function zipEntryCallback( $entry ) {
519 $names = array( $entry['name'] );
521 // If there is a null character, cut off the name at it, because JDK's
522 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
523 // were constructed which had ".class\0" followed by a string chosen to
524 // make the hash collide with the truncated name, that file could be
525 // returned in response to a request for the .class file.
526 $nullPos = strpos( $entry['name'], "\000" );
527 if ( $nullPos !== false ) {
528 $names[] = substr( $entry['name'], 0, $nullPos );
531 // If there is a trailing slash in the file name, we have to strip it,
532 // because that's what ZIP_GetEntry() does.
533 if ( preg_grep( '!\.class/?$!', $names ) ) {
534 $this->mJavaDetected
= true;
539 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
540 * but that suggests it's checking the user, when it's really checking the title + user combination.
541 * @param $user User object to verify the permissions against
542 * @return mixed An array as returned by getUserPermissionsErrors or true
543 * in case the user has proper permissions.
545 public function verifyPermissions( $user ) {
546 return $this->verifyTitlePermissions( $user );
550 * Check whether the user can edit, upload and create the image. This
551 * checks only against the current title; if it returns errors, it may
552 * very well be that another title will not give errors. Therefore
553 * isAllowed() should be called as well for generic is-user-blocked or
554 * can-user-upload checking.
556 * @param $user User object to verify the permissions against
557 * @return mixed An array as returned by getUserPermissionsErrors or true
558 * in case the user has proper permissions.
560 public function verifyTitlePermissions( $user ) {
562 * If the image is protected, non-sysop users won't be able
563 * to modify it by uploading a new revision.
565 $nt = $this->getTitle();
566 if ( is_null( $nt ) ) {
569 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
570 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
571 if ( !$nt->exists() ) {
572 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
574 $permErrorsCreate = array();
576 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
577 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
578 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
582 $overwriteError = $this->checkOverwrite( $user );
583 if ( $overwriteError !== true ) {
584 return array( $overwriteError );
591 * Check for non fatal problems with the file.
593 * This should not assume that mTempPath is set.
595 * @return Array of warnings
597 public function checkWarnings() {
599 wfProfileIn( __METHOD__
);
603 $localFile = $this->getLocalFile();
604 $filename = $localFile->getName();
607 * Check whether the resulting filename is different from the desired one,
608 * but ignore things like ucfirst() and spaces/underscore things
610 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
611 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
613 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
614 $warnings['badfilename'] = $filename;
617 // Check whether the file extension is on the unwanted list
618 global $wgCheckFileExtensions, $wgFileExtensions;
619 if ( $wgCheckFileExtensions ) {
620 $extensions = array_unique( $wgFileExtensions );
621 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
622 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
623 $wgLang->commaList( $extensions ), count( $extensions ) );
627 global $wgUploadSizeWarning;
628 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
629 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
632 if ( $this->mFileSize
== 0 ) {
633 $warnings['emptyfile'] = true;
636 $exists = self
::getExistsWarning( $localFile );
637 if ( $exists !== false ) {
638 $warnings['exists'] = $exists;
641 // Check dupes against existing files
642 $hash = $this->getTempFileSha1Base36();
643 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
644 $title = $this->getTitle();
645 // Remove all matches against self
646 foreach ( $dupes as $key => $dupe ) {
647 if ( $title->equals( $dupe->getTitle() ) ) {
648 unset( $dupes[$key] );
652 $warnings['duplicate'] = $dupes;
655 // Check dupes against archives
656 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
657 if ( $archivedImage->getID() > 0 ) {
658 $warnings['duplicate-archive'] = $archivedImage->getName();
661 wfProfileOut( __METHOD__
);
666 * Really perform the upload. Stores the file in the local repo, watches
667 * if necessary and runs the UploadComplete hook.
674 * @return Status indicating the whether the upload succeeded.
676 public function performUpload( $comment, $pageText, $watch, $user ) {
677 wfProfileIn( __METHOD__
);
679 $status = $this->getLocalFile()->upload(
689 if ( $status->isGood() ) {
691 WatchAction
::doWatch( $this->getLocalFile()->getTitle(), $user, WatchedItem
::IGNORE_USER_RIGHTS
);
693 wfRunHooks( 'UploadComplete', array( &$this ) );
696 wfProfileOut( __METHOD__
);
701 * Returns the title of the file to be uploaded. Sets mTitleError in case
702 * the name was illegal.
704 * @return Title The title of the file or null in case the name was illegal
706 public function getTitle() {
707 if ( $this->mTitle
!== false ) {
708 return $this->mTitle
;
710 /* Assume that if a user specified File:Something.jpg, this is an error
711 * and that the namespace prefix needs to be stripped of.
713 $title = Title
::newFromText( $this->mDesiredDestName
);
714 if ( $title && $title->getNamespace() == NS_FILE
) {
715 $this->mFilteredName
= $title->getDBkey();
717 $this->mFilteredName
= $this->mDesiredDestName
;
720 # oi_archive_name is max 255 bytes, which include a timestamp and an
721 # exclamation mark, so restrict file name to 240 bytes.
722 if ( strlen( $this->mFilteredName
) > 240 ) {
723 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
724 $this->mTitle
= null;
725 return $this->mTitle
;
729 * Chop off any directories in the given filename. Then
730 * filter out illegal characters, and try to make a legible name
731 * out of it. We'll strip some silently that Title would die on.
733 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
734 /* Normalize to title form before we do any further processing */
735 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
736 if ( is_null( $nt ) ) {
737 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
738 $this->mTitle
= null;
739 return $this->mTitle
;
741 $this->mFilteredName
= $nt->getDBkey();
744 * We'll want to blacklist against *any* 'extension', and use
745 * only the final one for the whitelist.
747 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
749 if ( count( $ext ) ) {
750 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
752 $this->mFinalExtension
= '';
754 # No extension, try guessing one
755 $magic = MimeMagic
::singleton();
756 $mime = $magic->guessMimeType( $this->mTempPath
);
757 if ( $mime !== 'unknown/unknown' ) {
758 # Get a space separated list of extensions
759 $extList = $magic->getExtensionsForType( $mime );
761 # Set the extension to the canonical extension
762 $this->mFinalExtension
= strtok( $extList, ' ' );
764 # Fix up the other variables
765 $this->mFilteredName
.= ".{$this->mFinalExtension}";
766 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
767 $ext = array( $this->mFinalExtension
);
772 /* Don't allow users to override the blacklist (check file extension) */
773 global $wgCheckFileExtensions, $wgStrictFileExtensions;
774 global $wgFileExtensions, $wgFileBlacklist;
776 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
778 if ( $this->mFinalExtension
== '' ) {
779 $this->mTitleError
= self
::FILETYPE_MISSING
;
780 $this->mTitle
= null;
781 return $this->mTitle
;
782 } elseif ( $blackListedExtensions ||
783 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
784 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
785 $this->mBlackListedExtensions
= $blackListedExtensions;
786 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
787 $this->mTitle
= null;
788 return $this->mTitle
;
791 // Windows may be broken with special characters, see bug XXX
792 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
793 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
794 $this->mTitle
= null;
795 return $this->mTitle
;
798 # If there was more than one "extension", reassemble the base
799 # filename to prevent bogus complaints about length
800 if ( count( $ext ) > 1 ) {
801 for ( $i = 0; $i < count( $ext ) - 1; $i++
) {
802 $partname .= '.' . $ext[$i];
806 if ( strlen( $partname ) < 1 ) {
807 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
808 $this->mTitle
= null;
809 return $this->mTitle
;
813 return $this->mTitle
;
817 * Return the local file and initializes if necessary.
819 * @return LocalFile|null
821 public function getLocalFile() {
822 if ( is_null( $this->mLocalFile
) ) {
823 $nt = $this->getTitle();
824 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
826 return $this->mLocalFile
;
830 * If the user does not supply all necessary information in the first upload form submission (either by accident or
831 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
833 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
835 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
836 * API request to find this stashed file again.
839 * @return UploadStashFile stashed file
841 public function stashFile( User
$user = null ) {
842 // was stashSessionFile
843 wfProfileIn( __METHOD__
);
845 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
846 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
847 $this->mLocalFile
= $file;
849 wfProfileOut( __METHOD__
);
854 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
856 * @return String: file key
858 public function stashFileGetKey() {
859 return $this->stashFile()->getFileKey();
863 * alias for stashFileGetKey, for backwards compatibility
865 * @return String: file key
867 public function stashSession() {
868 return $this->stashFileGetKey();
872 * If we've modified the upload file we need to manually remove it
873 * on exit to clean up.
875 public function cleanupTempFile() {
876 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
877 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
878 unlink( $this->mTempPath
);
882 public function getTempPath() {
883 return $this->mTempPath
;
887 * Split a file into a base name and all dot-delimited 'extensions'
888 * on the end. Some web server configurations will fall back to
889 * earlier pseudo-'extensions' to determine type and execute
890 * scripts, so the blacklist needs to check them all.
892 * @param $filename string
895 public static function splitExtensions( $filename ) {
896 $bits = explode( '.', $filename );
897 $basename = array_shift( $bits );
898 return array( $basename, $bits );
902 * Perform case-insensitive match against a list of file extensions.
903 * Returns true if the extension is in the list.
909 public static function checkFileExtension( $ext, $list ) {
910 return in_array( strtolower( $ext ), $list );
914 * Perform case-insensitive match against a list of file extensions.
915 * Returns an array of matching extensions.
921 public static function checkFileExtensionList( $ext, $list ) {
922 return array_intersect( array_map( 'strtolower', $ext ), $list );
926 * Checks if the mime type of the uploaded file matches the file extension.
928 * @param string $mime the mime type of the uploaded file
929 * @param string $extension the filename extension that the file is to be served with
932 public static function verifyExtension( $mime, $extension ) {
933 $magic = MimeMagic
::singleton();
935 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
936 if ( !$magic->isRecognizableExtension( $extension ) ) {
937 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
938 "unrecognized extension '$extension', can't verify\n" );
941 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
942 "recognized extension '$extension', so probably invalid file\n" );
947 $match = $magic->isMatchingExtension( $extension, $mime );
949 if ( $match === null ) {
950 if ( $magic->getTypesForExtension( $extension ) !== null ) {
951 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
954 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
957 } elseif ( $match === true ) {
958 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
960 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
964 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
970 * Heuristic for detecting files that *could* contain JavaScript instructions or
971 * things that may look like HTML to a browser and are thus
972 * potentially harmful. The present implementation will produce false
973 * positives in some situations.
975 * @param string $file pathname to the temporary upload file
976 * @param string $mime the mime type of the file
977 * @param string $extension the extension of the file
978 * @return Boolean: true if the file contains something looking like embedded scripts
980 public static function detectScript( $file, $mime, $extension ) {
981 global $wgAllowTitlesInSVG;
982 wfProfileIn( __METHOD__
);
984 # ugly hack: for text files, always look at the entire file.
985 # For binary field, just check the first K.
987 if ( strpos( $mime, 'text/' ) === 0 ) {
988 $chunk = file_get_contents( $file );
990 $fp = fopen( $file, 'rb' );
991 $chunk = fread( $fp, 1024 );
995 $chunk = strtolower( $chunk );
998 wfProfileOut( __METHOD__
);
1002 # decode from UTF-16 if needed (could be used for obfuscation).
1003 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1005 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1012 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1015 $chunk = trim( $chunk );
1017 # @todo FIXME: Convert from UTF-16 if necessary!
1018 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1020 # check for HTML doctype
1021 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1022 wfProfileOut( __METHOD__
);
1026 // Some browsers will interpret obscure xml encodings as UTF-8, while
1027 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1028 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1029 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1030 wfProfileOut( __METHOD__
);
1036 * Internet Explorer for Windows performs some really stupid file type
1037 * autodetection which can cause it to interpret valid image files as HTML
1038 * and potentially execute JavaScript, creating a cross-site scripting
1041 * Apple's Safari browser also performs some unsafe file type autodetection
1042 * which can cause legitimate files to be interpreted as HTML if the
1043 * web server is not correctly configured to send the right content-type
1044 * (or if you're really uploading plain text and octet streams!)
1046 * Returns true if IE is likely to mistake the given file for HTML.
1047 * Also returns true if Safari would mistake the given file for HTML
1048 * when served with a generic content-type.
1054 '<html', #also in safari
1057 '<script', #also in safari
1061 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1065 foreach ( $tags as $tag ) {
1066 if ( false !== strpos( $chunk, $tag ) ) {
1067 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1068 wfProfileOut( __METHOD__
);
1074 * look for JavaScript
1077 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1078 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1080 # look for script-types
1081 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1082 wfDebug( __METHOD__
. ": found script types\n" );
1083 wfProfileOut( __METHOD__
);
1087 # look for html-style script-urls
1088 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1089 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1090 wfProfileOut( __METHOD__
);
1094 # look for css-style script-urls
1095 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1096 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1097 wfProfileOut( __METHOD__
);
1101 wfDebug( __METHOD__
. ": no scripts found\n" );
1102 wfProfileOut( __METHOD__
);
1107 * Check a whitelist of xml encodings that are known not to be interpreted differently
1108 * by the server's xml parser (expat) and some common browsers.
1110 * @param string $file pathname to the temporary upload file
1111 * @return Boolean: true if the file contains an encoding that could be misinterpreted
1113 public static function checkXMLEncodingMissmatch( $file ) {
1114 global $wgSVGMetadataCutoff;
1115 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1116 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1118 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1119 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1120 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1122 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1125 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1126 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1127 // bytes. There shouldn't be a legitimate reason for this to happen.
1128 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1130 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1131 // EBCDIC encoded XML
1132 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1136 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1137 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1138 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1139 foreach ( $attemptEncodings as $encoding ) {
1140 wfSuppressWarnings();
1141 $str = iconv( $encoding, 'UTF-8', $contents );
1142 wfRestoreWarnings();
1143 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1144 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1145 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1147 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1150 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1151 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1152 // bytes. There shouldn't be a legitimate reason for this to happen.
1153 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1162 * @param $filename string
1165 protected function detectScriptInSvg( $filename ) {
1166 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1167 return $check->filterMatch
;
1171 * @todo Replace this with a whitelist filter!
1172 * @param $element string
1173 * @param $attribs array
1176 public function checkSvgScriptCallback( $element, $attribs ) {
1177 $strippedElement = $this->stripXmlNamespace( $element );
1180 * check for elements that can contain javascript
1182 if ( $strippedElement == 'script' ) {
1183 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1187 # e.g., <svg xmlns="http://www.w3.org/2000/svg"> <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1188 if ( $strippedElement == 'handler' ) {
1189 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1193 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1194 if ( $strippedElement == 'stylesheet' ) {
1195 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1199 foreach ( $attribs as $attrib => $value ) {
1200 $stripped = $this->stripXmlNamespace( $attrib );
1201 $value = strtolower( $value );
1203 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1204 wfDebug( __METHOD__
. ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1208 # href with javascript target
1209 if ( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1210 wfDebug( __METHOD__
. ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1214 # href with embedded svg as target
1215 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1216 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1220 # href with embedded (text/xml) svg as target
1221 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1222 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1226 # use set/animate to add event-handler attribute to parent
1227 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1228 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1232 # use set to add href attribute to parent element
1233 if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1234 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1238 # use set to add a remote / data / script target to an element
1239 if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1240 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1244 # use handler attribute with remote / data / script
1245 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1246 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1250 # use CSS styles to bring in remote code
1251 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1252 if ( $stripped == 'style' && preg_match_all( '!((?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*["\']?\s*[^#]+.*?\))!sim', $value, $matches ) ) {
1253 foreach ( $matches[1] as $match ) {
1254 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1255 wfDebug( __METHOD__
. ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1261 # image filters can pull in url, which could be svg that executes scripts
1262 if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1263 wfDebug( __METHOD__
. ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1269 return false; //No scripts detected
1273 * @param $name string
1276 private function stripXmlNamespace( $name ) {
1277 // 'http://www.w3.org/2000/svg:script' -> 'script'
1278 $parts = explode( ':', strtolower( $name ) );
1279 return array_pop( $parts );
1283 * Generic wrapper function for a virus scanner program.
1284 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1285 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1287 * @param string $file pathname to the temporary upload file
1288 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1289 * or a string containing feedback from the virus scanner if a virus was found.
1290 * If textual feedback is missing but a virus was found, this function returns true.
1292 public static function detectVirus( $file ) {
1293 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1294 wfProfileIn( __METHOD__
);
1296 if ( !$wgAntivirus ) {
1297 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1298 wfProfileOut( __METHOD__
);
1302 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1303 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1304 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1305 array( 'virus-badscanner', $wgAntivirus ) );
1306 wfProfileOut( __METHOD__
);
1307 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1310 # look up scanner configuration
1311 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1312 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1313 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1314 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1316 if ( strpos( $command, "%f" ) === false ) {
1317 # simple pattern: append file to scan
1318 $command .= " " . wfEscapeShellArg( $file );
1320 # complex pattern: replace "%f" with file to scan
1321 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1324 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1326 # execute virus scanner
1329 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1330 # that does not seem to be worth the pain.
1331 # Ask me (Duesentrieb) about it if it's ever needed.
1332 $output = wfShellExecWithStderr( $command, $exitCode );
1334 # map exit code to AV_xxx constants.
1335 $mappedCode = $exitCode;
1336 if ( $exitCodeMap ) {
1337 if ( isset( $exitCodeMap[$exitCode] ) ) {
1338 $mappedCode = $exitCodeMap[$exitCode];
1339 } elseif ( isset( $exitCodeMap["*"] ) ) {
1340 $mappedCode = $exitCodeMap["*"];
1344 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1345 * so we need the strict equalities === and thus can't use a switch here
1347 if ( $mappedCode === AV_SCAN_FAILED
) {
1348 # scan failed (code was mapped to false by $exitCodeMap)
1349 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1351 $output = $wgAntivirusRequired ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1352 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1353 # scan failed because filetype is unknown (probably imune)
1354 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1356 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1358 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1361 $output = trim( $output );
1364 $output = true; #if there's no output, return true
1365 } elseif ( $msgPattern ) {
1367 if ( preg_match( $msgPattern, $output, $groups ) ) {
1369 $output = $groups[1];
1374 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1377 wfProfileOut( __METHOD__
);
1382 * Check if there's an overwrite conflict and, if so, if restrictions
1383 * forbid this user from performing the upload.
1387 * @return mixed true on success, array on failure
1389 private function checkOverwrite( $user ) {
1390 // First check whether the local file can be overwritten
1391 $file = $this->getLocalFile();
1392 if ( $file->exists() ) {
1393 if ( !self
::userCanReUpload( $user, $file ) ) {
1394 return array( 'fileexists-forbidden', $file->getName() );
1400 /* Check shared conflicts: if the local file does not exist, but
1401 * wfFindFile finds a file, it exists in a shared repository.
1403 $file = wfFindFile( $this->getTitle() );
1404 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1405 return array( 'fileexists-shared-forbidden', $file->getName() );
1412 * Check if a user is the last uploader
1414 * @param $user User object
1415 * @param string $img image name
1418 public static function userCanReUpload( User
$user, $img ) {
1419 if ( $user->isAllowed( 'reupload' ) ) {
1420 return true; // non-conditional
1422 if ( !$user->isAllowed( 'reupload-own' ) ) {
1425 if ( is_string( $img ) ) {
1426 $img = wfLocalFile( $img );
1428 if ( !( $img instanceof LocalFile
) ) {
1432 return $user->getId() == $img->getUser( 'id' );
1436 * Helper function that does various existence checks for a file.
1437 * The following checks are performed:
1439 * - Article with the same name as the file exists
1440 * - File exists with normalized extension
1441 * - The file looks like a thumbnail and the original exists
1443 * @param $file File The File object to check
1444 * @return mixed False if the file does not exists, else an array
1446 public static function getExistsWarning( $file ) {
1447 if ( $file->exists() ) {
1448 return array( 'warning' => 'exists', 'file' => $file );
1451 if ( $file->getTitle()->getArticleID() ) {
1452 return array( 'warning' => 'page-exists', 'file' => $file );
1455 if ( $file->wasDeleted() && !$file->exists() ) {
1456 return array( 'warning' => 'was-deleted', 'file' => $file );
1459 if ( strpos( $file->getName(), '.' ) == false ) {
1460 $partname = $file->getName();
1463 $n = strrpos( $file->getName(), '.' );
1464 $extension = substr( $file->getName(), $n +
1 );
1465 $partname = substr( $file->getName(), 0, $n );
1467 $normalizedExtension = File
::normalizeExtension( $extension );
1469 if ( $normalizedExtension != $extension ) {
1470 // We're not using the normalized form of the extension.
1471 // Normal form is lowercase, using most common of alternate
1472 // extensions (eg 'jpg' rather than 'JPEG').
1474 // Check for another file using the normalized form...
1475 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1476 $file_lc = wfLocalFile( $nt_lc );
1478 if ( $file_lc->exists() ) {
1480 'warning' => 'exists-normalized',
1482 'normalizedFile' => $file_lc
1487 // Check for files with the same name but a different extension
1488 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1489 "{$partname}.", 1 );
1490 if ( count( $similarFiles ) ) {
1492 'warning' => 'exists-normalized',
1494 'normalizedFile' => $similarFiles[0],
1498 if ( self
::isThumbName( $file->getName() ) ) {
1499 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1500 $nt_thb = Title
::newFromText( substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1501 $file_thb = wfLocalFile( $nt_thb );
1502 if ( $file_thb->exists() ) {
1504 'warning' => 'thumb',
1506 'thumbFile' => $file_thb
1509 // File does not exist, but we just don't like the name
1511 'warning' => 'thumb-name',
1513 'thumbFile' => $file_thb
1518 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1519 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1521 'warning' => 'bad-prefix',
1532 * Helper function that checks whether the filename looks like a thumbnail
1533 * @param $filename string
1536 public static function isThumbName( $filename ) {
1537 $n = strrpos( $filename, '.' );
1538 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1540 substr( $partname, 3, 3 ) == 'px-' ||
1541 substr( $partname, 2, 3 ) == 'px-'
1543 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1547 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1549 * @return array list of prefixes
1551 public static function getFilenamePrefixBlacklist() {
1552 $blacklist = array();
1553 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1554 if ( !$message->isDisabled() ) {
1555 $lines = explode( "\n", $message->plain() );
1556 foreach ( $lines as $line ) {
1557 // Remove comment lines
1558 $comment = substr( trim( $line ), 0, 1 );
1559 if ( $comment == '#' ||
$comment == '' ) {
1562 // Remove additional comments after a prefix
1563 $comment = strpos( $line, '#' );
1564 if ( $comment > 0 ) {
1565 $line = substr( $line, 0, $comment - 1 );
1567 $blacklist[] = trim( $line );
1574 * Gets image info about the file just uploaded.
1576 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1577 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1578 * with the appropriate format, presumably.
1580 * @param $result ApiResult:
1581 * @return Array: image info
1583 public function getImageInfo( $result ) {
1584 $file = $this->getLocalFile();
1585 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1586 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1587 if ( $file instanceof UploadStashFile
) {
1588 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1589 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1591 $imParam = ApiQueryImageInfo
::getPropertyNames();
1592 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1598 * @param $error array
1601 public function convertVerifyErrorToStatus( $error ) {
1602 $code = $error['status'];
1603 unset( $code['status'] );
1604 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1608 * @param $forType null|string
1611 public static function getMaxUploadSize( $forType = null ) {
1612 global $wgMaxUploadSize;
1614 if ( is_array( $wgMaxUploadSize ) ) {
1615 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1616 return $wgMaxUploadSize[$forType];
1618 return $wgMaxUploadSize['*'];
1621 return intval( $wgMaxUploadSize );
1626 * Get the current status of a chunked upload (used for polling).
1627 * The status will be read from the *current* user session.
1628 * @param $statusKey string
1629 * @return Array|bool
1631 public static function getSessionStatus( $statusKey ) {
1632 return isset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] )
1633 ?
$_SESSION[self
::SESSION_STATUS_KEY
][$statusKey]
1638 * Set the current status of a chunked upload (used for polling).
1639 * The status will be stored in the *current* user session.
1640 * @param $statusKey string
1641 * @param $value array|false
1644 public static function setSessionStatus( $statusKey, $value ) {
1645 if ( $value === false ) {
1646 unset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] );
1648 $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] = $value;