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 * See also includes/docs/upload.txt
36 * @author Brion Vibber
37 * @author Bryan Tong Minh
38 * @author Michael Dale
40 abstract class UploadBase
{
42 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
43 protected $mTitle = false, $mTitleError = 0;
44 protected $mFilteredName, $mFinalExtension;
45 protected $mLocalFile, $mFileSize, $mFileProps;
46 protected $mBlackListedExtensions;
47 protected $mJavaDetected;
49 protected static $safeXmlEncodings = array( 'UTF-8', 'ISO-8859-1', 'ISO-8859-2', 'UTF-16', 'UTF-32' );
54 const MIN_LENGTH_PARTNAME
= 4;
55 const ILLEGAL_FILENAME
= 5;
56 const OVERWRITE_EXISTING_FILE
= 7; # Not used anymore; handled by verifyTitlePermissions()
57 const FILETYPE_MISSING
= 8;
58 const FILETYPE_BADTYPE
= 9;
59 const VERIFICATION_ERROR
= 10;
61 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
62 const UPLOAD_VERIFICATION_ERROR
= 11;
63 const HOOK_ABORTED
= 11;
64 const FILE_TOO_LARGE
= 12;
65 const WINDOWS_NONASCII_FILENAME
= 13;
66 const FILENAME_TOO_LONG
= 14;
68 const SESSION_STATUS_KEY
= 'wsUploadStatusData';
74 public function getVerificationErrorCode( $error ) {
75 $code_to_status = array(
76 self
::EMPTY_FILE
=> 'empty-file',
77 self
::FILE_TOO_LARGE
=> 'file-too-large',
78 self
::FILETYPE_MISSING
=> 'filetype-missing',
79 self
::FILETYPE_BADTYPE
=> 'filetype-banned',
80 self
::MIN_LENGTH_PARTNAME
=> 'filename-tooshort',
81 self
::ILLEGAL_FILENAME
=> 'illegal-filename',
82 self
::OVERWRITE_EXISTING_FILE
=> 'overwrite',
83 self
::VERIFICATION_ERROR
=> 'verification-error',
84 self
::HOOK_ABORTED
=> 'hookaborted',
85 self
::WINDOWS_NONASCII_FILENAME
=> 'windows-nonascii-filename',
86 self
::FILENAME_TOO_LONG
=> 'filename-toolong',
88 if ( isset( $code_to_status[$error] ) ) {
89 return $code_to_status[$error];
92 return 'unknown-error';
96 * Returns true if uploads are enabled.
97 * Can be override by subclasses.
100 public static function isEnabled() {
101 global $wgEnableUploads;
103 if ( !$wgEnableUploads ) {
107 # Check php's file_uploads setting
108 return wfIsHHVM() ||
wfIniGetBool( 'file_uploads' );
112 * Returns true if the user can use this upload module or else a string
113 * identifying the missing permission.
114 * Can be overridden by subclasses.
119 public static function isAllowed( $user ) {
120 foreach ( array( 'upload', 'edit' ) as $permission ) {
121 if ( !$user->isAllowed( $permission ) ) {
128 // Upload handlers. Should probably just be a global.
129 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
132 * Create a form of UploadBase depending on wpSourceType and initializes it
134 * @param $request WebRequest
138 public static function createFromRequest( &$request, $type = null ) {
139 $type = $type ?
$type : $request->getVal( 'wpSourceType', 'File' );
145 // Get the upload class
146 $type = ucfirst( $type );
148 // Give hooks the chance to handle this request
150 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
151 if ( is_null( $className ) ) {
152 $className = 'UploadFrom' . $type;
153 wfDebug( __METHOD__
. ": class name: $className\n" );
154 if ( !in_array( $type, self
::$uploadHandlers ) ) {
159 // Check whether this upload class is enabled
160 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
164 // Check whether the request is valid
165 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
169 $handler = new $className;
171 $handler->initializeFromRequest( $request );
176 * Check whether a request if valid for this handler
180 public static function isValidRequest( $request ) {
184 public function __construct() {}
187 * Returns the upload type. Should be overridden by child classes
192 public function getSourceType() {
197 * Initialize the path information
198 * @param string $name the desired destination name
199 * @param string $tempPath the temporary path
200 * @param int $fileSize the file size
201 * @param bool $removeTempFile (false) remove the temporary file?
202 * @throws MWException
204 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
205 $this->mDesiredDestName
= $name;
206 if ( FileBackend
::isStoragePath( $tempPath ) ) {
207 throw new MWException( __METHOD__
. " given storage path `$tempPath`." );
209 $this->mTempPath
= $tempPath;
210 $this->mFileSize
= $fileSize;
211 $this->mRemoveTempFile
= $removeTempFile;
215 * Initialize from a WebRequest. Override this in a subclass.
217 abstract public function initializeFromRequest( &$request );
220 * Fetch the file. Usually a no-op
223 public function fetchFile() {
224 return Status
::newGood();
228 * Return true if the file is empty
231 public function isEmptyFile() {
232 return empty( $this->mFileSize
);
236 * Return the file size
239 public function getFileSize() {
240 return $this->mFileSize
;
244 * Get the base 36 SHA1 of the file
247 public function getTempFileSha1Base36() {
248 return FSFile
::getSha1Base36FromPath( $this->mTempPath
);
252 * @param string $srcPath the source path
253 * @return string|bool the real path if it was a virtual URL Returns false on failure
255 function getRealPath( $srcPath ) {
256 wfProfileIn( __METHOD__
);
257 $repo = RepoGroup
::singleton()->getLocalRepo();
258 if ( $repo->isVirtualUrl( $srcPath ) ) {
259 // @todo just make uploads work with storage paths
260 // UploadFromStash loads files via virtual URLs
261 $tmpFile = $repo->getLocalCopy( $srcPath );
263 $tmpFile->bind( $this ); // keep alive with $this
265 $path = $tmpFile ?
$tmpFile->getPath() : false;
269 wfProfileOut( __METHOD__
);
274 * Verify whether the upload is sane.
275 * @return mixed self::OK or else an array with error information
277 public function verifyUpload() {
278 wfProfileIn( __METHOD__
);
281 * If there was no filename or a zero size given, give up quick.
283 if ( $this->isEmptyFile() ) {
284 wfProfileOut( __METHOD__
);
285 return array( 'status' => self
::EMPTY_FILE
);
289 * Honor $wgMaxUploadSize
291 $maxSize = self
::getMaxUploadSize( $this->getSourceType() );
292 if ( $this->mFileSize
> $maxSize ) {
293 wfProfileOut( __METHOD__
);
295 'status' => self
::FILE_TOO_LARGE
,
301 * Look at the contents of the file; if we can recognize the
302 * type but it's corrupt or data of the wrong type, we should
303 * probably not accept it.
305 $verification = $this->verifyFile();
306 if ( $verification !== true ) {
307 wfProfileOut( __METHOD__
);
309 'status' => self
::VERIFICATION_ERROR
,
310 'details' => $verification
315 * Make sure this file can be created
317 $result = $this->validateName();
318 if ( $result !== true ) {
319 wfProfileOut( __METHOD__
);
324 if ( !wfRunHooks( 'UploadVerification',
325 array( $this->mDestName
, $this->mTempPath
, &$error ) )
327 wfProfileOut( __METHOD__
);
328 return array( 'status' => self
::HOOK_ABORTED
, 'error' => $error );
331 wfProfileOut( __METHOD__
);
332 return array( 'status' => self
::OK
);
336 * Verify that the name is valid and, if necessary, that we can overwrite
338 * @return mixed true if valid, otherwise and array with 'status'
341 public function validateName() {
342 $nt = $this->getTitle();
343 if ( is_null( $nt ) ) {
344 $result = array( 'status' => $this->mTitleError
);
345 if ( $this->mTitleError
== self
::ILLEGAL_FILENAME
) {
346 $result['filtered'] = $this->mFilteredName
;
348 if ( $this->mTitleError
== self
::FILETYPE_BADTYPE
) {
349 $result['finalExt'] = $this->mFinalExtension
;
350 if ( count( $this->mBlackListedExtensions
) ) {
351 $result['blacklistedExt'] = $this->mBlackListedExtensions
;
356 $this->mDestName
= $this->getLocalFile()->getName();
362 * Verify the mime type.
364 * @note Only checks that it is not an evil mime. The does it have
365 * correct extension given its mime type check is in verifyFile.
366 * @param string $mime representing the mime
367 * @return mixed true if the file is verified, an array otherwise
369 protected function verifyMimeType( $mime ) {
370 global $wgVerifyMimeType;
371 wfProfileIn( __METHOD__
);
372 if ( $wgVerifyMimeType ) {
373 wfDebug( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n" );
374 global $wgMimeTypeBlacklist;
375 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
376 wfProfileOut( __METHOD__
);
377 return array( 'filetype-badmime', $mime );
381 $fp = fopen( $this->mTempPath
, 'rb' );
382 $chunk = fread( $fp, 256 );
385 $magic = MimeMagic
::singleton();
386 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension
);
387 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath
, $chunk, $extMime );
388 foreach ( $ieTypes as $ieType ) {
389 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
390 wfProfileOut( __METHOD__
);
391 return array( 'filetype-bad-ie-mime', $ieType );
396 wfProfileOut( __METHOD__
);
401 * Verifies that it's ok to include the uploaded file
403 * @return mixed true of the file is verified, array otherwise.
405 protected function verifyFile() {
406 global $wgVerifyMimeType;
407 wfProfileIn( __METHOD__
);
409 $status = $this->verifyPartialFile();
410 if ( $status !== true ) {
411 wfProfileOut( __METHOD__
);
415 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
416 $mime = $this->mFileProps
['file-mime'];
418 if ( $wgVerifyMimeType ) {
419 # XXX: Missing extension will be caught by validateName() via getTitle()
420 if ( $this->mFinalExtension
!= '' && !$this->verifyExtension( $mime, $this->mFinalExtension
) ) {
421 wfProfileOut( __METHOD__
);
422 return array( 'filetype-mime-mismatch', $this->mFinalExtension
, $mime );
426 $handler = MediaHandler
::getHandler( $mime );
428 $handlerStatus = $handler->verifyUpload( $this->mTempPath
);
429 if ( !$handlerStatus->isOK() ) {
430 $errors = $handlerStatus->getErrorsArray();
431 wfProfileOut( __METHOD__
);
432 return reset( $errors );
436 wfRunHooks( 'UploadVerifyFile', array( $this, $mime, &$status ) );
437 if ( $status !== true ) {
438 wfProfileOut( __METHOD__
);
442 wfDebug( __METHOD__
. ": all clear; passing.\n" );
443 wfProfileOut( __METHOD__
);
448 * A verification routine suitable for partial files
450 * Runs the blacklist checks, but not any checks that may
451 * assume the entire file is present.
453 * @return Mixed true for valid or array with error message key.
455 protected function verifyPartialFile() {
456 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
457 wfProfileIn( __METHOD__
);
459 # getTitle() sets some internal parameters like $this->mFinalExtension
462 $this->mFileProps
= FSFile
::getPropsFromPath( $this->mTempPath
, $this->mFinalExtension
);
464 # check mime type, if desired
465 $mime = $this->mFileProps
['file-mime'];
466 $status = $this->verifyMimeType( $mime );
467 if ( $status !== true ) {
468 wfProfileOut( __METHOD__
);
472 # check for htmlish code and javascript
473 if ( !$wgDisableUploadScriptChecks ) {
474 if ( self
::detectScript( $this->mTempPath
, $mime, $this->mFinalExtension
) ) {
475 wfProfileOut( __METHOD__
);
476 return array( 'uploadscripted' );
478 if ( $this->mFinalExtension
== 'svg' ||
$mime == 'image/svg+xml' ) {
479 if ( $this->detectScriptInSvg( $this->mTempPath
) ) {
480 wfProfileOut( __METHOD__
);
481 return array( 'uploadscripted' );
486 # Check for Java applets, which if uploaded can bypass cross-site
488 if ( !$wgAllowJavaUploads ) {
489 $this->mJavaDetected
= false;
490 $zipStatus = ZipDirectoryReader
::read( $this->mTempPath
,
491 array( $this, 'zipEntryCallback' ) );
492 if ( !$zipStatus->isOK() ) {
493 $errors = $zipStatus->getErrorsArray();
494 $error = reset( $errors );
495 if ( $error[0] !== 'zip-wrong-format' ) {
496 wfProfileOut( __METHOD__
);
500 if ( $this->mJavaDetected
) {
501 wfProfileOut( __METHOD__
);
502 return array( 'uploadjava' );
506 # Scan the uploaded file for viruses
507 $virus = $this->detectVirus( $this->mTempPath
);
509 wfProfileOut( __METHOD__
);
510 return array( 'uploadvirus', $virus );
513 wfProfileOut( __METHOD__
);
518 * Callback for ZipDirectoryReader to detect Java class files.
520 function zipEntryCallback( $entry ) {
521 $names = array( $entry['name'] );
523 // If there is a null character, cut off the name at it, because JDK's
524 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
525 // were constructed which had ".class\0" followed by a string chosen to
526 // make the hash collide with the truncated name, that file could be
527 // returned in response to a request for the .class file.
528 $nullPos = strpos( $entry['name'], "\000" );
529 if ( $nullPos !== false ) {
530 $names[] = substr( $entry['name'], 0, $nullPos );
533 // If there is a trailing slash in the file name, we have to strip it,
534 // because that's what ZIP_GetEntry() does.
535 if ( preg_grep( '!\.class/?$!', $names ) ) {
536 $this->mJavaDetected
= true;
541 * Alias for verifyTitlePermissions. The function was originally 'verifyPermissions'
542 * but that suggests it's checking the user, when it's really checking the title + user combination.
543 * @param $user User object to verify the permissions against
544 * @return mixed An array as returned by getUserPermissionsErrors or true
545 * in case the user has proper permissions.
547 public function verifyPermissions( $user ) {
548 return $this->verifyTitlePermissions( $user );
552 * Check whether the user can edit, upload and create the image. This
553 * checks only against the current title; if it returns errors, it may
554 * very well be that another title will not give errors. Therefore
555 * isAllowed() should be called as well for generic is-user-blocked or
556 * can-user-upload checking.
558 * @param $user User object to verify the permissions against
559 * @return mixed An array as returned by getUserPermissionsErrors or true
560 * in case the user has proper permissions.
562 public function verifyTitlePermissions( $user ) {
564 * If the image is protected, non-sysop users won't be able
565 * to modify it by uploading a new revision.
567 $nt = $this->getTitle();
568 if ( is_null( $nt ) ) {
571 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
572 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
573 if ( !$nt->exists() ) {
574 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
576 $permErrorsCreate = array();
578 if ( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
579 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
580 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
584 $overwriteError = $this->checkOverwrite( $user );
585 if ( $overwriteError !== true ) {
586 return array( $overwriteError );
593 * Check for non fatal problems with the file.
595 * This should not assume that mTempPath is set.
597 * @return Array of warnings
599 public function checkWarnings() {
601 wfProfileIn( __METHOD__
);
605 $localFile = $this->getLocalFile();
606 $filename = $localFile->getName();
609 * Check whether the resulting filename is different from the desired one,
610 * but ignore things like ucfirst() and spaces/underscore things
612 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName
);
613 $comparableName = Title
::capitalize( $comparableName, NS_FILE
);
615 if ( $this->mDesiredDestName
!= $filename && $comparableName != $filename ) {
616 $warnings['badfilename'] = $filename;
619 // Check whether the file extension is on the unwanted list
620 global $wgCheckFileExtensions, $wgFileExtensions;
621 if ( $wgCheckFileExtensions ) {
622 $extensions = array_unique( $wgFileExtensions );
623 if ( !$this->checkFileExtension( $this->mFinalExtension
, $extensions ) ) {
624 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension
,
625 $wgLang->commaList( $extensions ), count( $extensions ) );
629 global $wgUploadSizeWarning;
630 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
631 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize
);
634 if ( $this->mFileSize
== 0 ) {
635 $warnings['emptyfile'] = true;
638 $exists = self
::getExistsWarning( $localFile );
639 if ( $exists !== false ) {
640 $warnings['exists'] = $exists;
643 // Check dupes against existing files
644 $hash = $this->getTempFileSha1Base36();
645 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
646 $title = $this->getTitle();
647 // Remove all matches against self
648 foreach ( $dupes as $key => $dupe ) {
649 if ( $title->equals( $dupe->getTitle() ) ) {
650 unset( $dupes[$key] );
654 $warnings['duplicate'] = $dupes;
657 // Check dupes against archives
658 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
659 if ( $archivedImage->getID() > 0 ) {
660 $warnings['duplicate-archive'] = $archivedImage->getName();
663 wfProfileOut( __METHOD__
);
668 * Really perform the upload. Stores the file in the local repo, watches
669 * if necessary and runs the UploadComplete hook.
676 * @return Status indicating the whether the upload succeeded.
678 public function performUpload( $comment, $pageText, $watch, $user ) {
679 wfProfileIn( __METHOD__
);
681 $status = $this->getLocalFile()->upload(
691 if ( $status->isGood() ) {
693 WatchAction
::doWatch( $this->getLocalFile()->getTitle(), $user, WatchedItem
::IGNORE_USER_RIGHTS
);
695 wfRunHooks( 'UploadComplete', array( &$this ) );
698 wfProfileOut( __METHOD__
);
703 * Returns the title of the file to be uploaded. Sets mTitleError in case
704 * the name was illegal.
706 * @return Title The title of the file or null in case the name was illegal
708 public function getTitle() {
709 if ( $this->mTitle
!== false ) {
710 return $this->mTitle
;
712 /* Assume that if a user specified File:Something.jpg, this is an error
713 * and that the namespace prefix needs to be stripped of.
715 $title = Title
::newFromText( $this->mDesiredDestName
);
716 if ( $title && $title->getNamespace() == NS_FILE
) {
717 $this->mFilteredName
= $title->getDBkey();
719 $this->mFilteredName
= $this->mDesiredDestName
;
722 # oi_archive_name is max 255 bytes, which include a timestamp and an
723 # exclamation mark, so restrict file name to 240 bytes.
724 if ( strlen( $this->mFilteredName
) > 240 ) {
725 $this->mTitleError
= self
::FILENAME_TOO_LONG
;
726 $this->mTitle
= null;
727 return $this->mTitle
;
731 * Chop off any directories in the given filename. Then
732 * filter out illegal characters, and try to make a legible name
733 * out of it. We'll strip some silently that Title would die on.
735 $this->mFilteredName
= wfStripIllegalFilenameChars( $this->mFilteredName
);
736 /* Normalize to title form before we do any further processing */
737 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
738 if ( is_null( $nt ) ) {
739 $this->mTitleError
= self
::ILLEGAL_FILENAME
;
740 $this->mTitle
= null;
741 return $this->mTitle
;
743 $this->mFilteredName
= $nt->getDBkey();
746 * We'll want to blacklist against *any* 'extension', and use
747 * only the final one for the whitelist.
749 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName
);
751 if ( count( $ext ) ) {
752 $this->mFinalExtension
= trim( $ext[count( $ext ) - 1] );
754 $this->mFinalExtension
= '';
756 # No extension, try guessing one
757 $magic = MimeMagic
::singleton();
758 $mime = $magic->guessMimeType( $this->mTempPath
);
759 if ( $mime !== 'unknown/unknown' ) {
760 # Get a space separated list of extensions
761 $extList = $magic->getExtensionsForType( $mime );
763 # Set the extension to the canonical extension
764 $this->mFinalExtension
= strtok( $extList, ' ' );
766 # Fix up the other variables
767 $this->mFilteredName
.= ".{$this->mFinalExtension}";
768 $nt = Title
::makeTitleSafe( NS_FILE
, $this->mFilteredName
);
769 $ext = array( $this->mFinalExtension
);
774 /* Don't allow users to override the blacklist (check file extension) */
775 global $wgCheckFileExtensions, $wgStrictFileExtensions;
776 global $wgFileExtensions, $wgFileBlacklist;
778 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
780 if ( $this->mFinalExtension
== '' ) {
781 $this->mTitleError
= self
::FILETYPE_MISSING
;
782 $this->mTitle
= null;
783 return $this->mTitle
;
784 } elseif ( $blackListedExtensions ||
785 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
786 !$this->checkFileExtensionList( $ext, $wgFileExtensions ) ) ) {
787 $this->mBlackListedExtensions
= $blackListedExtensions;
788 $this->mTitleError
= self
::FILETYPE_BADTYPE
;
789 $this->mTitle
= null;
790 return $this->mTitle
;
793 // Windows may be broken with special characters, see bug XXX
794 if ( wfIsWindows() && !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() ) ) {
795 $this->mTitleError
= self
::WINDOWS_NONASCII_FILENAME
;
796 $this->mTitle
= null;
797 return $this->mTitle
;
800 # If there was more than one "extension", reassemble the base
801 # filename to prevent bogus complaints about length
802 if ( count( $ext ) > 1 ) {
803 for ( $i = 0; $i < count( $ext ) - 1; $i++
) {
804 $partname .= '.' . $ext[$i];
808 if ( strlen( $partname ) < 1 ) {
809 $this->mTitleError
= self
::MIN_LENGTH_PARTNAME
;
810 $this->mTitle
= null;
811 return $this->mTitle
;
815 return $this->mTitle
;
819 * Return the local file and initializes if necessary.
821 * @return LocalFile|null
823 public function getLocalFile() {
824 if ( is_null( $this->mLocalFile
) ) {
825 $nt = $this->getTitle();
826 $this->mLocalFile
= is_null( $nt ) ?
null : wfLocalFile( $nt );
828 return $this->mLocalFile
;
832 * If the user does not supply all necessary information in the first upload form submission (either by accident or
833 * by design) then we may want to stash the file temporarily, get more information, and publish the file later.
835 * This method will stash a file in a temporary directory for later processing, and save the necessary descriptive info
837 * This method returns the file object, which also has a 'fileKey' property which can be passed through a form or
838 * API request to find this stashed file again.
841 * @return UploadStashFile stashed file
843 public function stashFile( User
$user = null ) {
844 // was stashSessionFile
845 wfProfileIn( __METHOD__
);
847 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $user );
848 $file = $stash->stashFile( $this->mTempPath
, $this->getSourceType() );
849 $this->mLocalFile
= $file;
851 wfProfileOut( __METHOD__
);
856 * Stash a file in a temporary directory, returning a key which can be used to find the file again. See stashFile().
858 * @return String: file key
860 public function stashFileGetKey() {
861 return $this->stashFile()->getFileKey();
865 * alias for stashFileGetKey, for backwards compatibility
867 * @return String: file key
869 public function stashSession() {
870 return $this->stashFileGetKey();
874 * If we've modified the upload file we need to manually remove it
875 * on exit to clean up.
877 public function cleanupTempFile() {
878 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
879 wfDebug( __METHOD__
. ": Removing temporary file {$this->mTempPath}\n" );
880 unlink( $this->mTempPath
);
884 public function getTempPath() {
885 return $this->mTempPath
;
889 * Split a file into a base name and all dot-delimited 'extensions'
890 * on the end. Some web server configurations will fall back to
891 * earlier pseudo-'extensions' to determine type and execute
892 * scripts, so the blacklist needs to check them all.
894 * @param $filename string
897 public static function splitExtensions( $filename ) {
898 $bits = explode( '.', $filename );
899 $basename = array_shift( $bits );
900 return array( $basename, $bits );
904 * Perform case-insensitive match against a list of file extensions.
905 * Returns true if the extension is in the list.
911 public static function checkFileExtension( $ext, $list ) {
912 return in_array( strtolower( $ext ), $list );
916 * Perform case-insensitive match against a list of file extensions.
917 * Returns an array of matching extensions.
923 public static function checkFileExtensionList( $ext, $list ) {
924 return array_intersect( array_map( 'strtolower', $ext ), $list );
928 * Checks if the mime type of the uploaded file matches the file extension.
930 * @param string $mime the mime type of the uploaded file
931 * @param string $extension the filename extension that the file is to be served with
934 public static function verifyExtension( $mime, $extension ) {
935 $magic = MimeMagic
::singleton();
937 if ( !$mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' ) {
938 if ( !$magic->isRecognizableExtension( $extension ) ) {
939 wfDebug( __METHOD__
. ": passing file with unknown detected mime type; " .
940 "unrecognized extension '$extension', can't verify\n" );
943 wfDebug( __METHOD__
. ": rejecting file with unknown detected mime type; " .
944 "recognized extension '$extension', so probably invalid file\n" );
949 $match = $magic->isMatchingExtension( $extension, $mime );
951 if ( $match === null ) {
952 if ( $magic->getTypesForExtension( $extension ) !== null ) {
953 wfDebug( __METHOD__
. ": No extension known for $mime, but we know a mime for $extension\n" );
956 wfDebug( __METHOD__
. ": no file extension known for mime type $mime, passing file\n" );
959 } elseif ( $match === true ) {
960 wfDebug( __METHOD__
. ": mime type $mime matches extension $extension, passing file\n" );
962 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
966 wfDebug( __METHOD__
. ": mime type $mime mismatches file extension $extension, rejecting file\n" );
972 * Heuristic for detecting files that *could* contain JavaScript instructions or
973 * things that may look like HTML to a browser and are thus
974 * potentially harmful. The present implementation will produce false
975 * positives in some situations.
977 * @param string $file pathname to the temporary upload file
978 * @param string $mime the mime type of the file
979 * @param string $extension the extension of the file
980 * @return Boolean: true if the file contains something looking like embedded scripts
982 public static function detectScript( $file, $mime, $extension ) {
983 global $wgAllowTitlesInSVG;
984 wfProfileIn( __METHOD__
);
986 # ugly hack: for text files, always look at the entire file.
987 # For binary field, just check the first K.
989 if ( strpos( $mime, 'text/' ) === 0 ) {
990 $chunk = file_get_contents( $file );
992 $fp = fopen( $file, 'rb' );
993 $chunk = fread( $fp, 1024 );
997 $chunk = strtolower( $chunk );
1000 wfProfileOut( __METHOD__
);
1004 # decode from UTF-16 if needed (could be used for obfuscation).
1005 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1007 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1014 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1017 $chunk = trim( $chunk );
1019 # @todo FIXME: Convert from UTF-16 if necessary!
1020 wfDebug( __METHOD__
. ": checking for embedded scripts and HTML stuff\n" );
1022 # check for HTML doctype
1023 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1024 wfProfileOut( __METHOD__
);
1028 // Some browsers will interpret obscure xml encodings as UTF-8, while
1029 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1030 if ( $extension == 'svg' ||
strpos( $mime, 'image/svg' ) === 0 ) {
1031 if ( self
::checkXMLEncodingMissmatch( $file ) ) {
1032 wfProfileOut( __METHOD__
);
1038 * Internet Explorer for Windows performs some really stupid file type
1039 * autodetection which can cause it to interpret valid image files as HTML
1040 * and potentially execute JavaScript, creating a cross-site scripting
1043 * Apple's Safari browser also performs some unsafe file type autodetection
1044 * which can cause legitimate files to be interpreted as HTML if the
1045 * web server is not correctly configured to send the right content-type
1046 * (or if you're really uploading plain text and octet streams!)
1048 * Returns true if IE is likely to mistake the given file for HTML.
1049 * Also returns true if Safari would mistake the given file for HTML
1050 * when served with a generic content-type.
1056 '<html', #also in safari
1059 '<script', #also in safari
1063 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1067 foreach ( $tags as $tag ) {
1068 if ( false !== strpos( $chunk, $tag ) ) {
1069 wfDebug( __METHOD__
. ": found something that may make it be mistaken for html: $tag\n" );
1070 wfProfileOut( __METHOD__
);
1076 * look for JavaScript
1079 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1080 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1082 # look for script-types
1083 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1084 wfDebug( __METHOD__
. ": found script types\n" );
1085 wfProfileOut( __METHOD__
);
1089 # look for html-style script-urls
1090 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1091 wfDebug( __METHOD__
. ": found html-style script urls\n" );
1092 wfProfileOut( __METHOD__
);
1096 # look for css-style script-urls
1097 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1098 wfDebug( __METHOD__
. ": found css-style script urls\n" );
1099 wfProfileOut( __METHOD__
);
1103 wfDebug( __METHOD__
. ": no scripts found\n" );
1104 wfProfileOut( __METHOD__
);
1109 * Check a whitelist of xml encodings that are known not to be interpreted differently
1110 * by the server's xml parser (expat) and some common browsers.
1112 * @param string $file pathname to the temporary upload file
1113 * @return Boolean: true if the file contains an encoding that could be misinterpreted
1115 public static function checkXMLEncodingMissmatch( $file ) {
1116 global $wgSVGMetadataCutoff;
1117 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1118 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1120 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1121 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1122 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1124 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1127 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1128 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1129 // bytes. There shouldn't be a legitimate reason for this to happen.
1130 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1132 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1133 // EBCDIC encoded XML
1134 wfDebug( __METHOD__
. ": EBCDIC Encoded XML\n" );
1138 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1139 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1140 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1141 foreach ( $attemptEncodings as $encoding ) {
1142 wfSuppressWarnings();
1143 $str = iconv( $encoding, 'UTF-8', $contents );
1144 wfRestoreWarnings();
1145 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1146 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1147 && !in_array( strtoupper( $encMatch[1] ), self
::$safeXmlEncodings )
1149 wfDebug( __METHOD__
. ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1152 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1153 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1154 // bytes. There shouldn't be a legitimate reason for this to happen.
1155 wfDebug( __METHOD__
. ": Unmatched XML declaration start\n" );
1164 * @param $filename string
1167 protected function detectScriptInSvg( $filename ) {
1168 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1169 return $check->filterMatch
;
1173 * @todo Replace this with a whitelist filter!
1174 * @param $element string
1175 * @param $attribs array
1178 public function checkSvgScriptCallback( $element, $attribs ) {
1179 $strippedElement = $this->stripXmlNamespace( $element );
1182 * check for elements that can contain javascript
1184 if ( $strippedElement == 'script' ) {
1185 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1189 # 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>
1190 if ( $strippedElement == 'handler' ) {
1191 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1195 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1196 if ( $strippedElement == 'stylesheet' ) {
1197 wfDebug( __METHOD__
. ": Found scriptable element '$element' in uploaded file.\n" );
1201 foreach ( $attribs as $attrib => $value ) {
1202 $stripped = $this->stripXmlNamespace( $attrib );
1203 $value = strtolower( $value );
1205 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1206 wfDebug( __METHOD__
. ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1210 # href with javascript target
1211 if ( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1212 wfDebug( __METHOD__
. ": Found script in href attribute '$attrib'='$value' in uploaded file.\n" );
1216 # href with embedded svg as target
1217 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1218 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1222 # href with embedded (text/xml) svg as target
1223 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1224 wfDebug( __METHOD__
. ": Found href to embedded svg \"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1228 # use set/animate to add event-handler attribute to parent
1229 if ( ( $strippedElement == 'set' ||
$strippedElement == 'animate' ) && $stripped == 'attributename' && substr( $value, 0, 2 ) == 'on' ) {
1230 wfDebug( __METHOD__
. ": Found svg setting event-handler attribute with \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1234 # use set to add href attribute to parent element
1235 if ( $strippedElement == 'set' && $stripped == 'attributename' && strpos( $value, 'href' ) !== false ) {
1236 wfDebug( __METHOD__
. ": Found svg setting href attribute '$value' in uploaded file.\n" );
1240 # use set to add a remote / data / script target to an element
1241 if ( $strippedElement == 'set' && $stripped == 'to' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1242 wfDebug( __METHOD__
. ": Found svg setting attribute to '$value' in uploaded file.\n" );
1246 # use handler attribute with remote / data / script
1247 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1248 wfDebug( __METHOD__
. ": Found svg setting handler with remote/data/script '$attrib'='$value' in uploaded file.\n" );
1252 # use CSS styles to bring in remote code
1253 # catch url("http:..., url('http:..., url(http:..., but not url("#..., url('#..., url(#....
1254 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 ) ) {
1255 foreach ( $matches[1] as $match ) {
1256 if ( !preg_match( '!(?:font|clip-path|fill|filter|marker|marker-end|marker-mid|marker-start|mask|stroke)\s*:\s*url\s*\(\s*(#|\'#|"#)!sim', $match ) ) {
1257 wfDebug( __METHOD__
. ": Found svg setting a style with remote url '$attrib'='$value' in uploaded file.\n" );
1263 # image filters can pull in url, which could be svg that executes scripts
1264 if ( $strippedElement == 'image' && $stripped == 'filter' && preg_match( '!url\s*\(!sim', $value ) ) {
1265 wfDebug( __METHOD__
. ": Found image filter with url: \"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1271 return false; //No scripts detected
1275 * @param $name string
1278 private function stripXmlNamespace( $name ) {
1279 // 'http://www.w3.org/2000/svg:script' -> 'script'
1280 $parts = explode( ':', strtolower( $name ) );
1281 return array_pop( $parts );
1285 * Generic wrapper function for a virus scanner program.
1286 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1287 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1289 * @param string $file pathname to the temporary upload file
1290 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1291 * or a string containing feedback from the virus scanner if a virus was found.
1292 * If textual feedback is missing but a virus was found, this function returns true.
1294 public static function detectVirus( $file ) {
1295 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1296 wfProfileIn( __METHOD__
);
1298 if ( !$wgAntivirus ) {
1299 wfDebug( __METHOD__
. ": virus scanner disabled\n" );
1300 wfProfileOut( __METHOD__
);
1304 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1305 wfDebug( __METHOD__
. ": unknown virus scanner: $wgAntivirus\n" );
1306 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1307 array( 'virus-badscanner', $wgAntivirus ) );
1308 wfProfileOut( __METHOD__
);
1309 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1312 # look up scanner configuration
1313 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1314 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1315 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1316 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1318 if ( strpos( $command, "%f" ) === false ) {
1319 # simple pattern: append file to scan
1320 $command .= " " . wfEscapeShellArg( $file );
1322 # complex pattern: replace "%f" with file to scan
1323 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1326 wfDebug( __METHOD__
. ": running virus scan: $command \n" );
1328 # execute virus scanner
1331 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1332 # that does not seem to be worth the pain.
1333 # Ask me (Duesentrieb) about it if it's ever needed.
1334 $output = wfShellExecWithStderr( $command, $exitCode );
1336 # map exit code to AV_xxx constants.
1337 $mappedCode = $exitCode;
1338 if ( $exitCodeMap ) {
1339 if ( isset( $exitCodeMap[$exitCode] ) ) {
1340 $mappedCode = $exitCodeMap[$exitCode];
1341 } elseif ( isset( $exitCodeMap["*"] ) ) {
1342 $mappedCode = $exitCodeMap["*"];
1346 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1347 * so we need the strict equalities === and thus can't use a switch here
1349 if ( $mappedCode === AV_SCAN_FAILED
) {
1350 # scan failed (code was mapped to false by $exitCodeMap)
1351 wfDebug( __METHOD__
. ": failed to scan $file (code $exitCode).\n" );
1353 $output = $wgAntivirusRequired ?
wfMessage( 'virus-scanfailed', array( $exitCode ) )->text() : null;
1354 } elseif ( $mappedCode === AV_SCAN_ABORTED
) {
1355 # scan failed because filetype is unknown (probably imune)
1356 wfDebug( __METHOD__
. ": unsupported file type $file (code $exitCode).\n" );
1358 } elseif ( $mappedCode === AV_NO_VIRUS
) {
1360 wfDebug( __METHOD__
. ": file passed virus scan.\n" );
1363 $output = trim( $output );
1366 $output = true; #if there's no output, return true
1367 } elseif ( $msgPattern ) {
1369 if ( preg_match( $msgPattern, $output, $groups ) ) {
1371 $output = $groups[1];
1376 wfDebug( __METHOD__
. ": FOUND VIRUS! scanner feedback: $output \n" );
1379 wfProfileOut( __METHOD__
);
1384 * Check if there's an overwrite conflict and, if so, if restrictions
1385 * forbid this user from performing the upload.
1389 * @return mixed true on success, array on failure
1391 private function checkOverwrite( $user ) {
1392 // First check whether the local file can be overwritten
1393 $file = $this->getLocalFile();
1394 if ( $file->exists() ) {
1395 if ( !self
::userCanReUpload( $user, $file ) ) {
1396 return array( 'fileexists-forbidden', $file->getName() );
1402 /* Check shared conflicts: if the local file does not exist, but
1403 * wfFindFile finds a file, it exists in a shared repository.
1405 $file = wfFindFile( $this->getTitle() );
1406 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1407 return array( 'fileexists-shared-forbidden', $file->getName() );
1414 * Check if a user is the last uploader
1416 * @param $user User object
1417 * @param string $img image name
1420 public static function userCanReUpload( User
$user, $img ) {
1421 if ( $user->isAllowed( 'reupload' ) ) {
1422 return true; // non-conditional
1424 if ( !$user->isAllowed( 'reupload-own' ) ) {
1427 if ( is_string( $img ) ) {
1428 $img = wfLocalFile( $img );
1430 if ( !( $img instanceof LocalFile
) ) {
1434 return $user->getId() == $img->getUser( 'id' );
1438 * Helper function that does various existence checks for a file.
1439 * The following checks are performed:
1441 * - Article with the same name as the file exists
1442 * - File exists with normalized extension
1443 * - The file looks like a thumbnail and the original exists
1445 * @param $file File The File object to check
1446 * @return mixed False if the file does not exists, else an array
1448 public static function getExistsWarning( $file ) {
1449 if ( $file->exists() ) {
1450 return array( 'warning' => 'exists', 'file' => $file );
1453 if ( $file->getTitle()->getArticleID() ) {
1454 return array( 'warning' => 'page-exists', 'file' => $file );
1457 if ( $file->wasDeleted() && !$file->exists() ) {
1458 return array( 'warning' => 'was-deleted', 'file' => $file );
1461 if ( strpos( $file->getName(), '.' ) == false ) {
1462 $partname = $file->getName();
1465 $n = strrpos( $file->getName(), '.' );
1466 $extension = substr( $file->getName(), $n +
1 );
1467 $partname = substr( $file->getName(), 0, $n );
1469 $normalizedExtension = File
::normalizeExtension( $extension );
1471 if ( $normalizedExtension != $extension ) {
1472 // We're not using the normalized form of the extension.
1473 // Normal form is lowercase, using most common of alternate
1474 // extensions (eg 'jpg' rather than 'JPEG').
1476 // Check for another file using the normalized form...
1477 $nt_lc = Title
::makeTitle( NS_FILE
, "{$partname}.{$normalizedExtension}" );
1478 $file_lc = wfLocalFile( $nt_lc );
1480 if ( $file_lc->exists() ) {
1482 'warning' => 'exists-normalized',
1484 'normalizedFile' => $file_lc
1489 // Check for files with the same name but a different extension
1490 $similarFiles = RepoGroup
::singleton()->getLocalRepo()->findFilesByPrefix(
1491 "{$partname}.", 1 );
1492 if ( count( $similarFiles ) ) {
1494 'warning' => 'exists-normalized',
1496 'normalizedFile' => $similarFiles[0],
1500 if ( self
::isThumbName( $file->getName() ) ) {
1501 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1502 $nt_thb = Title
::newFromText( substr( $partname, strpos( $partname, '-' ) +
1 ) . '.' . $extension, NS_FILE
);
1503 $file_thb = wfLocalFile( $nt_thb );
1504 if ( $file_thb->exists() ) {
1506 'warning' => 'thumb',
1508 'thumbFile' => $file_thb
1511 // File does not exist, but we just don't like the name
1513 'warning' => 'thumb-name',
1515 'thumbFile' => $file_thb
1520 foreach ( self
::getFilenamePrefixBlacklist() as $prefix ) {
1521 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1523 'warning' => 'bad-prefix',
1534 * Helper function that checks whether the filename looks like a thumbnail
1535 * @param $filename string
1538 public static function isThumbName( $filename ) {
1539 $n = strrpos( $filename, '.' );
1540 $partname = $n ?
substr( $filename, 0, $n ) : $filename;
1542 substr( $partname, 3, 3 ) == 'px-' ||
1543 substr( $partname, 2, 3 ) == 'px-'
1545 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1549 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1551 * @return array list of prefixes
1553 public static function getFilenamePrefixBlacklist() {
1554 $blacklist = array();
1555 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1556 if ( !$message->isDisabled() ) {
1557 $lines = explode( "\n", $message->plain() );
1558 foreach ( $lines as $line ) {
1559 // Remove comment lines
1560 $comment = substr( trim( $line ), 0, 1 );
1561 if ( $comment == '#' ||
$comment == '' ) {
1564 // Remove additional comments after a prefix
1565 $comment = strpos( $line, '#' );
1566 if ( $comment > 0 ) {
1567 $line = substr( $line, 0, $comment - 1 );
1569 $blacklist[] = trim( $line );
1576 * Gets image info about the file just uploaded.
1578 * Also has the effect of setting metadata to be an 'indexed tag name' in returned API result if
1579 * 'metadata' was requested. Oddly, we have to pass the "result" object down just so it can do that
1580 * with the appropriate format, presumably.
1582 * @param $result ApiResult:
1583 * @return Array: image info
1585 public function getImageInfo( $result ) {
1586 $file = $this->getLocalFile();
1587 // TODO This cries out for refactoring. We really want to say $file->getAllInfo(); here.
1588 // Perhaps "info" methods should be moved into files, and the API should just wrap them in queries.
1589 if ( $file instanceof UploadStashFile
) {
1590 $imParam = ApiQueryStashImageInfo
::getPropertyNames();
1591 $info = ApiQueryStashImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1593 $imParam = ApiQueryImageInfo
::getPropertyNames();
1594 $info = ApiQueryImageInfo
::getInfo( $file, array_flip( $imParam ), $result );
1600 * @param $error array
1603 public function convertVerifyErrorToStatus( $error ) {
1604 $code = $error['status'];
1605 unset( $code['status'] );
1606 return Status
::newFatal( $this->getVerificationErrorCode( $code ), $error );
1610 * @param $forType null|string
1613 public static function getMaxUploadSize( $forType = null ) {
1614 global $wgMaxUploadSize;
1616 if ( is_array( $wgMaxUploadSize ) ) {
1617 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1618 return $wgMaxUploadSize[$forType];
1620 return $wgMaxUploadSize['*'];
1623 return intval( $wgMaxUploadSize );
1628 * Get the current status of a chunked upload (used for polling).
1629 * The status will be read from the *current* user session.
1630 * @param $statusKey string
1631 * @return Array|bool
1633 public static function getSessionStatus( $statusKey ) {
1634 return isset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] )
1635 ?
$_SESSION[self
::SESSION_STATUS_KEY
][$statusKey]
1640 * Set the current status of a chunked upload (used for polling).
1641 * The status will be stored in the *current* user session.
1642 * @param $statusKey string
1643 * @param $value array|false
1646 public static function setSessionStatus( $statusKey, $value ) {
1647 if ( $value === false ) {
1648 unset( $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] );
1650 $_SESSION[self
::SESSION_STATUS_KEY
][$statusKey] = $value;