5 * Created on Aug 21, 2008
7 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
30 class ApiUpload
extends ApiBase
{
31 /** @var UploadBase|UploadFromChunks */
32 protected $mUpload = null;
36 public function execute() {
37 // Check whether upload is enabled
38 if ( !UploadBase
::isEnabled() ) {
39 $this->dieUsageMsg( 'uploaddisabled' );
42 $user = $this->getUser();
45 $this->mParams
= $this->extractRequestParams();
46 $request = $this->getMain()->getRequest();
47 // Check if async mode is actually supported (jobs done in cli mode)
48 $this->mParams
['async'] = ( $this->mParams
['async'] &&
49 $this->getConfig()->get( 'EnableAsyncUploads' ) );
50 // Add the uploaded file to the params array
51 $this->mParams
['file'] = $request->getFileName( 'file' );
52 $this->mParams
['chunk'] = $request->getFileName( 'chunk' );
54 // Copy the session key to the file key, for backward compatibility.
55 if ( !$this->mParams
['filekey'] && $this->mParams
['sessionkey'] ) {
56 $this->logFeatureUsage( 'action=upload&sessionkey' );
57 $this->mParams
['filekey'] = $this->mParams
['sessionkey'];
60 // Select an upload module
62 if ( !$this->selectUploadModule() ) {
63 return; // not a true upload, but a status request or similar
64 } elseif ( !isset( $this->mUpload
) ) {
65 $this->dieUsage( 'No upload module set', 'nomodule' );
67 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
68 $this->handleStashException( $e );
71 // First check permission to upload
72 $this->checkPermissions( $user );
74 // Fetch the file (usually a no-op)
75 /** @var $status Status */
76 $status = $this->mUpload
->fetchFile();
77 if ( !$status->isGood() ) {
78 $errors = $status->getErrorsArray();
79 $error = array_shift( $errors[0] );
80 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
83 // Check if the uploaded file is sane
84 if ( $this->mParams
['chunk'] ) {
85 $maxSize = UploadBase
::getMaxUploadSize();
86 if ( $this->mParams
['filesize'] > $maxSize ) {
87 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
89 if ( !$this->mUpload
->getTitle() ) {
90 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
92 } elseif ( $this->mParams
['async'] && $this->mParams
['filekey'] ) {
93 // defer verification to background process
95 wfDebug( __METHOD__
. " about to verify\n" );
96 $this->verifyUpload();
99 // Check if the user has the rights to modify or overwrite the requested title
100 // (This check is irrelevant if stashing is already requested, since the errors
101 // can always be fixed by changing the title)
102 if ( !$this->mParams
['stash'] ) {
103 $permErrors = $this->mUpload
->verifyTitlePermissions( $user );
104 if ( $permErrors !== true ) {
105 $this->dieRecoverableError( $permErrors[0], 'filename' );
109 // Get the result based on the current upload context:
111 $result = $this->getContextResult();
112 if ( $result['result'] === 'Success' ) {
113 $result['imageinfo'] = $this->mUpload
->getImageInfo( $this->getResult() );
115 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
116 $this->handleStashException( $e );
119 $this->getResult()->addValue( null, $this->getModuleName(), $result );
121 // Cleanup any temporary mess
122 $this->mUpload
->cleanupTempFile();
126 * Get an upload result based on upload context
129 private function getContextResult() {
130 $warnings = $this->getApiWarnings();
131 if ( $warnings && !$this->mParams
['ignorewarnings'] ) {
132 // Get warnings formatted in result array format
133 return $this->getWarningsResult( $warnings );
134 } elseif ( $this->mParams
['chunk'] ) {
135 // Add chunk, and get result
136 return $this->getChunkResult( $warnings );
137 } elseif ( $this->mParams
['stash'] ) {
138 // Stash the file and get stash result
139 return $this->getStashResult( $warnings );
142 // Check throttle after we've handled warnings
143 if ( UploadBase
::isThrottled( $this->getUser() )
145 $this->dieUsageMsg( 'actionthrottledtext' );
148 // This is the most common case -- a normal upload with no warnings
149 // performUpload will return a formatted properly for the API with status
150 return $this->performUpload( $warnings );
154 * Get Stash Result, throws an exception if the file could not be stashed.
155 * @param array $warnings Array of Api upload warnings
158 private function getStashResult( $warnings ) {
160 // Some uploads can request they be stashed, so as not to publish them immediately.
161 // In this case, a failure to stash ought to be fatal
163 $result['result'] = 'Success';
164 $result['filekey'] = $this->performStash();
165 $result['sessionkey'] = $result['filekey']; // backwards compatibility
166 if ( $warnings && count( $warnings ) > 0 ) {
167 $result['warnings'] = $warnings;
169 } catch ( UploadStashException
$e ) {
170 $this->handleStashException( $e );
171 } catch ( Exception
$e ) {
172 $this->dieUsage( $e->getMessage(), 'stashfailed' );
179 * Get Warnings Result
180 * @param array $warnings Array of Api upload warnings
183 private function getWarningsResult( $warnings ) {
185 $result['result'] = 'Warning';
186 $result['warnings'] = $warnings;
187 // in case the warnings can be fixed with some further user action, let's stash this upload
188 // and return a key they can use to restart it
190 $result['filekey'] = $this->performStash();
191 $result['sessionkey'] = $result['filekey']; // backwards compatibility
192 } catch ( Exception
$e ) {
193 $result['warnings']['stashfailed'] = $e->getMessage();
200 * Get the result of a chunk upload.
201 * @param array $warnings Array of Api upload warnings
204 private function getChunkResult( $warnings ) {
207 if ( $warnings && count( $warnings ) > 0 ) {
208 $result['warnings'] = $warnings;
211 $request = $this->getMain()->getRequest();
212 $chunkPath = $request->getFileTempname( 'chunk' );
213 $chunkSize = $request->getUpload( 'chunk' )->getSize();
214 $totalSoFar = $this->mParams
['offset'] +
$chunkSize;
215 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
217 // Sanity check sizing
218 if ( $totalSoFar > $this->mParams
['filesize'] ) {
220 'Offset plus current chunk is greater than claimed file size', 'invalid-chunk'
224 // Enforce minimum chunk size
225 if ( $totalSoFar != $this->mParams
['filesize'] && $chunkSize < $minChunkSize ) {
227 "Minimum chunk size is $minChunkSize bytes for non-final chunks", 'chunk-too-small'
231 if ( $this->mParams
['offset'] == 0 ) {
233 $filekey = $this->performStash();
234 } catch ( UploadStashException
$e ) {
235 $this->handleStashException( $e );
236 } catch ( Exception
$e ) {
237 // FIXME: Error handling here is wrong/different from rest of this
238 $this->dieUsage( $e->getMessage(), 'stashfailed' );
241 $filekey = $this->mParams
['filekey'];
243 // Don't allow further uploads to an already-completed session
244 $progress = UploadBase
::getSessionStatus( $this->getUser(), $filekey );
246 // Probably can't get here, but check anyway just in case
247 $this->dieUsage( 'No chunked upload session with this key', 'stashfailed' );
248 } elseif ( $progress['result'] !== 'Continue' ||
$progress['stage'] !== 'uploading' ) {
250 'Chunked upload is already completed, check status for details', 'stashfailed'
254 $status = $this->mUpload
->addChunk(
255 $chunkPath, $chunkSize, $this->mParams
['offset'] );
256 if ( !$status->isGood() ) {
258 'offset' => $this->mUpload
->getOffset(),
261 $this->dieUsage( $status->getWikiText(), 'stashfailed', 0, $extradata );
265 // Check we added the last chunk:
266 if ( $totalSoFar == $this->mParams
['filesize'] ) {
267 if ( $this->mParams
['async'] ) {
268 UploadBase
::setSessionStatus(
271 array( 'result' => 'Poll',
272 'stage' => 'queued', 'status' => Status
::newGood() )
274 JobQueueGroup
::singleton()->push( new AssembleUploadChunksJob(
275 Title
::makeTitle( NS_FILE
, $filekey ),
277 'filename' => $this->mParams
['filename'],
278 'filekey' => $filekey,
279 'session' => $this->getContext()->exportSession()
282 $result['result'] = 'Poll';
283 $result['stage'] = 'queued';
285 $status = $this->mUpload
->concatenateChunks();
286 if ( !$status->isGood() ) {
287 UploadBase
::setSessionStatus(
290 array( 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status )
292 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
295 // The fully concatenated file has a new filekey. So remove
296 // the old filekey and fetch the new one.
297 UploadBase
::setSessionStatus( $this->getUser(), $filekey, false );
298 $this->mUpload
->stash
->removeFile( $filekey );
299 $filekey = $this->mUpload
->getLocalFile()->getFileKey();
301 $result['result'] = 'Success';
304 UploadBase
::setSessionStatus(
308 'result' => 'Continue',
309 'stage' => 'uploading',
310 'offset' => $totalSoFar,
311 'status' => Status
::newGood(),
314 $result['result'] = 'Continue';
315 $result['offset'] = $totalSoFar;
318 $result['filekey'] = $filekey;
324 * Stash the file and return the file key
325 * Also re-raises exceptions with slightly more informative message strings (useful for API)
326 * @throws MWException
327 * @return string File key
329 private function performStash() {
331 $stashFile = $this->mUpload
->stashFile( $this->getUser() );
334 throw new MWException( 'Invalid stashed file' );
336 $fileKey = $stashFile->getFileKey();
337 } catch ( Exception
$e ) {
338 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
339 wfDebug( __METHOD__
. ' ' . $message . "\n" );
340 $className = get_class( $e );
341 throw new $className( $message );
348 * Throw an error that the user can recover from by providing a better
349 * value for $parameter
351 * @param array $error Error array suitable for passing to dieUsageMsg()
352 * @param string $parameter Parameter that needs revising
353 * @param array $data Optional extra data to pass to the user
354 * @throws UsageException
356 private function dieRecoverableError( $error, $parameter, $data = array() ) {
358 $data['filekey'] = $this->performStash();
359 $data['sessionkey'] = $data['filekey'];
360 } catch ( Exception
$e ) {
361 $data['stashfailed'] = $e->getMessage();
363 $data['invalidparameter'] = $parameter;
365 $parsed = $this->parseMsg( $error );
366 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
370 * Select an upload module and set it to mUpload. Dies on failure. If the
371 * request was a status request and not a true upload, returns false;
376 protected function selectUploadModule() {
377 $request = $this->getMain()->getRequest();
379 // chunk or one and only one of the following parameters is needed
380 if ( !$this->mParams
['chunk'] ) {
381 $this->requireOnlyOneParameter( $this->mParams
,
382 'filekey', 'file', 'url', 'statuskey' );
385 // Status report for "upload to stash"/"upload from stash"
386 if ( $this->mParams
['filekey'] && $this->mParams
['checkstatus'] ) {
387 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
389 $this->dieUsage( 'No result in status data', 'missingresult' );
390 } elseif ( !$progress['status']->isGood() ) {
391 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
393 if ( isset( $progress['status']->value
['verification'] ) ) {
394 $this->checkVerification( $progress['status']->value
['verification'] );
396 unset( $progress['status'] ); // remove Status object
397 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
402 if ( $this->mParams
['statuskey'] ) {
403 $this->checkAsyncDownloadEnabled();
405 // Status request for an async upload
406 $sessionData = UploadFromUrlJob
::getSessionData( $this->mParams
['statuskey'] );
407 if ( !isset( $sessionData['result'] ) ) {
408 $this->dieUsage( 'No result in session data', 'missingresult' );
410 if ( $sessionData['result'] == 'Warning' ) {
411 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
412 $sessionData['sessionkey'] = $this->mParams
['statuskey'];
414 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
419 // The following modules all require the filename parameter to be set
420 if ( is_null( $this->mParams
['filename'] ) ) {
421 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
424 if ( $this->mParams
['chunk'] ) {
426 $this->mUpload
= new UploadFromChunks();
427 if ( isset( $this->mParams
['filekey'] ) ) {
428 if ( $this->mParams
['offset'] === 0 ) {
429 $this->dieUsage( 'Cannot supply a filekey when offset is 0', 'badparams' );
433 $this->mUpload
->continueChunks(
434 $this->mParams
['filename'],
435 $this->mParams
['filekey'],
436 $request->getUpload( 'chunk' )
439 if ( $this->mParams
['offset'] !== 0 ) {
440 $this->dieUsage( 'Must supply a filekey when offset is non-zero', 'badparams' );
443 // handle first chunk
444 $this->mUpload
->initialize(
445 $this->mParams
['filename'],
446 $request->getUpload( 'chunk' )
449 } elseif ( isset( $this->mParams
['filekey'] ) ) {
450 // Upload stashed in a previous request
451 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
452 $this->dieUsageMsg( 'invalid-file-key' );
455 $this->mUpload
= new UploadFromStash( $this->getUser() );
456 // This will not download the temp file in initialize() in async mode.
457 // We still have enough information to call checkWarnings() and such.
458 $this->mUpload
->initialize(
459 $this->mParams
['filekey'], $this->mParams
['filename'], !$this->mParams
['async']
461 } elseif ( isset( $this->mParams
['file'] ) ) {
462 $this->mUpload
= new UploadFromFile();
463 $this->mUpload
->initialize(
464 $this->mParams
['filename'],
465 $request->getUpload( 'file' )
467 } elseif ( isset( $this->mParams
['url'] ) ) {
468 // Make sure upload by URL is enabled:
469 if ( !UploadFromUrl
::isEnabled() ) {
470 $this->dieUsageMsg( 'copyuploaddisabled' );
473 if ( !UploadFromUrl
::isAllowedHost( $this->mParams
['url'] ) ) {
474 $this->dieUsageMsg( 'copyuploadbaddomain' );
477 if ( !UploadFromUrl
::isAllowedUrl( $this->mParams
['url'] ) ) {
478 $this->dieUsageMsg( 'copyuploadbadurl' );
482 if ( $this->mParams
['asyncdownload'] ) {
483 $this->checkAsyncDownloadEnabled();
485 if ( $this->mParams
['leavemessage'] && !$this->mParams
['ignorewarnings'] ) {
486 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
487 'missing-ignorewarnings' );
490 if ( $this->mParams
['leavemessage'] ) {
491 $async = 'async-leavemessage';
496 $this->mUpload
= new UploadFromUrl
;
497 $this->mUpload
->initialize( $this->mParams
['filename'],
498 $this->mParams
['url'], $async );
505 * Checks that the user has permissions to perform this upload.
506 * Dies with usage message on inadequate permissions.
507 * @param User $user The user to check.
509 protected function checkPermissions( $user ) {
510 // Check whether the user has the appropriate permissions to upload anyway
511 $permission = $this->mUpload
->isAllowed( $user );
513 if ( $permission !== true ) {
514 if ( !$user->isLoggedIn() ) {
515 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
518 $this->dieUsageMsg( 'badaccess-groups' );
523 * Performs file verification, dies on error.
525 protected function verifyUpload() {
526 $verification = $this->mUpload
->verifyUpload();
527 if ( $verification['status'] === UploadBase
::OK
) {
531 $this->checkVerification( $verification );
535 * Performs file verification, dies on error.
536 * @param array $verification
538 protected function checkVerification( array $verification ) {
539 // @todo Move them to ApiBase's message map
540 switch ( $verification['status'] ) {
541 // Recoverable errors
542 case UploadBase
::MIN_LENGTH_PARTNAME
:
543 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
545 case UploadBase
::ILLEGAL_FILENAME
:
546 $this->dieRecoverableError( 'illegal-filename', 'filename',
547 array( 'filename' => $verification['filtered'] ) );
549 case UploadBase
::FILENAME_TOO_LONG
:
550 $this->dieRecoverableError( 'filename-toolong', 'filename' );
552 case UploadBase
::FILETYPE_MISSING
:
553 $this->dieRecoverableError( 'filetype-missing', 'filename' );
555 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
556 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
559 // Unrecoverable errors
560 case UploadBase
::EMPTY_FILE
:
561 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
563 case UploadBase
::FILE_TOO_LARGE
:
564 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
567 case UploadBase
::FILETYPE_BADTYPE
:
569 'filetype' => $verification['finalExt'],
570 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
572 ApiResult
::setIndexedTagName( $extradata['allowed'], 'ext' );
574 $msg = "Filetype not permitted: ";
575 if ( isset( $verification['blacklistedExt'] ) ) {
576 $msg .= join( ', ', $verification['blacklistedExt'] );
577 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
578 ApiResult
::setIndexedTagName( $extradata['blacklisted'], 'ext' );
580 $msg .= $verification['finalExt'];
582 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
584 case UploadBase
::VERIFICATION_ERROR
:
585 $params = $verification['details'];
586 $key = array_shift( $params );
587 $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
588 ApiResult
::setIndexedTagName( $verification['details'], 'detail' );
589 $this->dieUsage( "This file did not pass file verification: $msg", 'verification-error',
590 0, array( 'details' => $verification['details'] ) );
592 case UploadBase
::HOOK_ABORTED
:
593 if ( is_array( $verification['error'] ) ) {
594 $params = $verification['error'];
595 } elseif ( $verification['error'] !== '' ) {
596 $params = array( $verification['error'] );
598 $params = array( 'hookaborted' );
600 $key = array_shift( $params );
601 $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
602 $this->dieUsage( $msg, 'hookaborted', 0, array( 'details' => $verification['error'] ) );
605 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
606 0, array( 'details' => array( 'code' => $verification['status'] ) ) );
613 * Returns a suitable array for inclusion into API results if there were warnings
614 * Returns the empty array if there were no warnings
618 protected function getApiWarnings() {
619 $warnings = $this->mUpload
->checkWarnings();
621 return $this->transformWarnings( $warnings );
624 protected function transformWarnings( $warnings ) {
627 $result = $this->getResult();
628 ApiResult
::setIndexedTagName( $warnings, 'warning' );
630 if ( isset( $warnings['duplicate'] ) ) {
632 /** @var File $dupe */
633 foreach ( $warnings['duplicate'] as $dupe ) {
634 $dupes[] = $dupe->getName();
636 ApiResult
::setIndexedTagName( $dupes, 'duplicate' );
637 $warnings['duplicate'] = $dupes;
640 if ( isset( $warnings['exists'] ) ) {
641 $warning = $warnings['exists'];
642 unset( $warnings['exists'] );
643 /** @var LocalFile $localFile */
644 $localFile = isset( $warning['normalizedFile'] )
645 ?
$warning['normalizedFile']
647 $warnings[$warning['warning']] = $localFile->getName();
655 * Handles a stash exception, giving a useful error to the user.
656 * @param Exception $e The exception we encountered.
658 protected function handleStashException( $e ) {
659 $exceptionType = get_class( $e );
661 switch ( $exceptionType ) {
662 case 'UploadStashFileNotFoundException':
664 'Could not find the file in the stash: ' . $e->getMessage(),
665 'stashedfilenotfound'
668 case 'UploadStashBadPathException':
670 'File key of improper format or otherwise invalid: ' . $e->getMessage(),
674 case 'UploadStashFileException':
676 'Could not store upload in the stash: ' . $e->getMessage(),
680 case 'UploadStashZeroLengthFileException':
682 'File is of zero length, and could not be stored in the stash: ' .
687 case 'UploadStashNotLoggedInException':
688 $this->dieUsage( 'Not logged in: ' . $e->getMessage(), 'stashnotloggedin' );
690 case 'UploadStashWrongOwnerException':
691 $this->dieUsage( 'Wrong owner: ' . $e->getMessage(), 'stashwrongowner' );
693 case 'UploadStashNoSuchKeyException':
694 $this->dieUsage( 'No such filekey: ' . $e->getMessage(), 'stashnosuchfilekey' );
697 $this->dieUsage( $exceptionType . ": " . $e->getMessage(), 'stasherror' );
703 * Perform the actual upload. Returns a suitable result array on success;
706 * @param array $warnings Array of Api upload warnings
709 protected function performUpload( $warnings ) {
710 // Use comment as initial page text by default
711 if ( is_null( $this->mParams
['text'] ) ) {
712 $this->mParams
['text'] = $this->mParams
['comment'];
715 /** @var $file File */
716 $file = $this->mUpload
->getLocalFile();
718 // For preferences mode, we want to watch if 'watchdefault' is set or
719 // if the *file* doesn't exist and 'watchcreations' is set. But
720 // getWatchlistValue()'s automatic handling checks if the *title*
721 // exists or not, so we need to check both prefs manually.
722 $watch = $this->getWatchlistValue(
723 $this->mParams
['watchlist'], $file->getTitle(), 'watchdefault'
725 if ( !$watch && $this->mParams
['watchlist'] == 'preferences' && !$file->exists() ) {
726 $watch = $this->getWatchlistValue(
727 $this->mParams
['watchlist'], $file->getTitle(), 'watchcreations'
731 // Deprecated parameters
732 if ( $this->mParams
['watch'] ) {
733 $this->logFeatureUsage( 'action=upload&watch' );
737 // No errors, no warnings: do the upload
738 if ( $this->mParams
['async'] ) {
739 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
740 if ( $progress && $progress['result'] === 'Poll' ) {
741 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
743 UploadBase
::setSessionStatus(
745 $this->mParams
['filekey'],
746 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status
::newGood() )
748 JobQueueGroup
::singleton()->push( new PublishStashedFileJob(
749 Title
::makeTitle( NS_FILE
, $this->mParams
['filename'] ),
751 'filename' => $this->mParams
['filename'],
752 'filekey' => $this->mParams
['filekey'],
753 'comment' => $this->mParams
['comment'],
754 'text' => $this->mParams
['text'],
756 'session' => $this->getContext()->exportSession()
759 $result['result'] = 'Poll';
760 $result['stage'] = 'queued';
762 /** @var $status Status */
763 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
764 $this->mParams
['text'], $watch, $this->getUser() );
766 if ( !$status->isGood() ) {
767 $error = $status->getErrorsArray();
769 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
770 // The upload can not be performed right now, because the user
773 'result' => 'Queued',
774 'statuskey' => $error[0][1],
778 ApiResult
::setIndexedTagName( $error, 'error' );
779 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
781 $result['result'] = 'Success';
784 $result['filename'] = $file->getName();
785 if ( $warnings && count( $warnings ) > 0 ) {
786 $result['warnings'] = $warnings;
793 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
795 protected function checkAsyncDownloadEnabled() {
796 if ( !$this->getConfig()->get( 'AllowAsyncCopyUploads' ) ) {
797 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
801 public function mustBePosted() {
805 public function isWriteMode() {
809 public function getAllowedParams() {
812 ApiBase
::PARAM_TYPE
=> 'string',
815 ApiBase
::PARAM_DFLT
=> ''
818 ApiBase
::PARAM_TYPE
=> 'text',
821 ApiBase
::PARAM_DFLT
=> false,
822 ApiBase
::PARAM_DEPRECATED
=> true,
824 'watchlist' => array(
825 ApiBase
::PARAM_DFLT
=> 'preferences',
826 ApiBase
::PARAM_TYPE
=> array(
832 'ignorewarnings' => false,
834 ApiBase
::PARAM_TYPE
=> 'upload',
838 'sessionkey' => array(
839 ApiBase
::PARAM_DFLT
=> null,
840 ApiBase
::PARAM_DEPRECATED
=> true,
845 ApiBase
::PARAM_TYPE
=> 'integer',
846 ApiBase
::PARAM_MIN
=> 0,
847 ApiBase
::PARAM_MAX
=> UploadBase
::getMaxUploadSize(),
850 ApiBase
::PARAM_TYPE
=> 'integer',
851 ApiBase
::PARAM_MIN
=> 0,
854 ApiBase
::PARAM_TYPE
=> 'upload',
858 'asyncdownload' => false,
859 'leavemessage' => false,
861 'checkstatus' => false,
867 public function needsToken() {
871 protected function getExamplesMessages() {
873 'action=upload&filename=Wiki.png' .
874 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
875 => 'apihelp-upload-example-url',
876 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
877 => 'apihelp-upload-example-filekey',
881 public function getHelpUrls() {
882 return 'https://www.mediawiki.org/wiki/API:Upload';