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->mParams
['filekey'] = $this->mParams
['sessionkey'];
59 // Select an upload module
61 if ( !$this->selectUploadModule() ) {
62 return; // not a true upload, but a status request or similar
63 } elseif ( !isset( $this->mUpload
) ) {
64 $this->dieUsage( 'No upload module set', 'nomodule' );
66 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
67 list( $msg, $code ) = $this->handleStashException( get_class( $e ), $e->getMessage() );
68 $this->dieUsage( $msg, $code );
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 list( $msg, $code ) = $this->handleStashException( get_class( $e ), $e->getMessage() );
117 $this->dieUsage( $msg, $code );
120 $this->getResult()->addValue( null, $this->getModuleName(), $result );
122 // Cleanup any temporary mess
123 $this->mUpload
->cleanupTempFile();
127 * Get an upload result based on upload context
130 private function getContextResult() {
131 $warnings = $this->getApiWarnings();
132 if ( $warnings && !$this->mParams
['ignorewarnings'] ) {
133 // Get warnings formatted in result array format
134 return $this->getWarningsResult( $warnings );
135 } elseif ( $this->mParams
['chunk'] ) {
136 // Add chunk, and get result
137 return $this->getChunkResult( $warnings );
138 } elseif ( $this->mParams
['stash'] ) {
139 // Stash the file and get stash result
140 return $this->getStashResult( $warnings );
143 // Check throttle after we've handled warnings
144 if ( UploadBase
::isThrottled( $this->getUser() )
146 $this->dieUsageMsg( 'actionthrottledtext' );
149 // This is the most common case -- a normal upload with no warnings
150 // performUpload will return a formatted properly for the API with status
151 return $this->performUpload( $warnings );
155 * Get Stash Result, throws an exception if the file could not be stashed.
156 * @param array $warnings Array of Api upload warnings
159 private function getStashResult( $warnings ) {
161 $result['result'] = 'Success';
162 if ( $warnings && count( $warnings ) > 0 ) {
163 $result['warnings'] = $warnings;
165 // Some uploads can request they be stashed, so as not to publish them immediately.
166 // In this case, a failure to stash ought to be fatal
167 $this->performStash( 'critical', $result );
173 * Get Warnings Result
174 * @param array $warnings Array of Api upload warnings
177 private function getWarningsResult( $warnings ) {
179 $result['result'] = 'Warning';
180 $result['warnings'] = $warnings;
181 // in case the warnings can be fixed with some further user action, let's stash this upload
182 // and return a key they can use to restart it
183 $this->performStash( 'optional', $result );
189 * Get the result of a chunk upload.
190 * @param array $warnings Array of Api upload warnings
193 private function getChunkResult( $warnings ) {
196 if ( $warnings && count( $warnings ) > 0 ) {
197 $result['warnings'] = $warnings;
200 $request = $this->getMain()->getRequest();
201 $chunkPath = $request->getFileTempname( 'chunk' );
202 $chunkSize = $request->getUpload( 'chunk' )->getSize();
203 $totalSoFar = $this->mParams
['offset'] +
$chunkSize;
204 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
206 // Sanity check sizing
207 if ( $totalSoFar > $this->mParams
['filesize'] ) {
209 'Offset plus current chunk is greater than claimed file size', 'invalid-chunk'
213 // Enforce minimum chunk size
214 if ( $totalSoFar != $this->mParams
['filesize'] && $chunkSize < $minChunkSize ) {
216 "Minimum chunk size is $minChunkSize bytes for non-final chunks", 'chunk-too-small'
220 if ( $this->mParams
['offset'] == 0 ) {
221 $filekey = $this->performStash( 'critical' );
223 $filekey = $this->mParams
['filekey'];
225 // Don't allow further uploads to an already-completed session
226 $progress = UploadBase
::getSessionStatus( $this->getUser(), $filekey );
228 // Probably can't get here, but check anyway just in case
229 $this->dieUsage( 'No chunked upload session with this key', 'stashfailed' );
230 } elseif ( $progress['result'] !== 'Continue' ||
$progress['stage'] !== 'uploading' ) {
232 'Chunked upload is already completed, check status for details', 'stashfailed'
236 $status = $this->mUpload
->addChunk(
237 $chunkPath, $chunkSize, $this->mParams
['offset'] );
238 if ( !$status->isGood() ) {
240 'offset' => $this->mUpload
->getOffset(),
243 $this->dieUsage( $status->getWikiText( false, false, 'en' ), 'stashfailed', 0, $extradata );
247 // Check we added the last chunk:
248 if ( $totalSoFar == $this->mParams
['filesize'] ) {
249 if ( $this->mParams
['async'] ) {
250 UploadBase
::setSessionStatus(
253 [ 'result' => 'Poll',
254 'stage' => 'queued', 'status' => Status
::newGood() ]
256 JobQueueGroup
::singleton()->push( new AssembleUploadChunksJob(
257 Title
::makeTitle( NS_FILE
, $filekey ),
259 'filename' => $this->mParams
['filename'],
260 'filekey' => $filekey,
261 'session' => $this->getContext()->exportSession()
264 $result['result'] = 'Poll';
265 $result['stage'] = 'queued';
267 $status = $this->mUpload
->concatenateChunks();
268 if ( !$status->isGood() ) {
269 UploadBase
::setSessionStatus(
272 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
274 $this->dieUsage( $status->getWikiText( false, false, 'en' ), 'stashfailed' );
277 // The fully concatenated file has a new filekey. So remove
278 // the old filekey and fetch the new one.
279 UploadBase
::setSessionStatus( $this->getUser(), $filekey, false );
280 $this->mUpload
->stash
->removeFile( $filekey );
281 $filekey = $this->mUpload
->getLocalFile()->getFileKey();
283 $result['result'] = 'Success';
286 UploadBase
::setSessionStatus(
290 'result' => 'Continue',
291 'stage' => 'uploading',
292 'offset' => $totalSoFar,
293 'status' => Status
::newGood(),
296 $result['result'] = 'Continue';
297 $result['offset'] = $totalSoFar;
300 $result['filekey'] = $filekey;
306 * Stash the file and add the file key, or error information if it fails, to the data.
308 * @param string $failureMode What to do on failure to stash:
309 * - When 'critical', use dieStatus() to produce an error response and throw an exception.
310 * Use this when stashing the file was the primary purpose of the API request.
311 * - When 'optional', only add a 'stashfailed' key to the data and return null.
312 * Use this when some error happened for a non-stash upload and we're stashing the file
313 * only to save the client the trouble of re-uploading it.
314 * @param array &$data API result to which to add the information
315 * @return string|null File key
317 private function performStash( $failureMode, &$data = null ) {
318 $isPartial = (bool)$this->mParams
['chunk'];
320 $status = $this->mUpload
->tryStashFile( $this->getUser(), $isPartial );
322 if ( $status->isGood() && !$status->getValue() ) {
323 // Not actually a 'good' status...
324 $status->fatal( new ApiRawMessage( 'Invalid stashed file', 'stashfailed' ) );
326 } catch ( Exception
$e ) {
327 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
328 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
329 $status = Status
::newFatal( new ApiRawMessage( $e->getMessage(), 'stashfailed' ) );
332 if ( $status->isGood() ) {
333 $stashFile = $status->getValue();
334 $data['filekey'] = $stashFile->getFileKey();
335 // Backwards compatibility
336 $data['sessionkey'] = $data['filekey'];
337 return $data['filekey'];
340 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
341 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
342 // Statuses for it. Just extract the exception details and parse them ourselves.
343 list( $exceptionType, $message ) = $status->getMessage()->getParams();
344 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
345 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
346 list( $msg, $code ) = $this->handleStashException( $exceptionType, $message );
347 $status = Status
::newFatal( new ApiRawMessage( $msg, $code ) );
351 if ( $failureMode !== 'optional' ) {
352 $this->dieStatus( $status );
354 list( $code, $msg ) = $this->getErrorFromStatus( $status );
355 $data['stashfailed'] = $msg;
361 * Throw an error that the user can recover from by providing a better
362 * value for $parameter
364 * @param array|string|MessageSpecifier $error Error suitable for passing to dieUsageMsg()
365 * @param string $parameter Parameter that needs revising
366 * @param array $data Optional extra data to pass to the user
367 * @param string $code Error code to use if the error is unknown
368 * @throws UsageException
370 private function dieRecoverableError( $error, $parameter, $data = [], $code = 'unknownerror' ) {
371 $this->performStash( 'optional', $data );
372 $data['invalidparameter'] = $parameter;
374 $parsed = $this->parseMsg( $error );
375 if ( isset( $parsed['data'] ) ) {
376 $data = array_merge( $data, $parsed['data'] );
378 if ( $parsed['code'] === 'unknownerror' ) {
379 $parsed['code'] = $code;
382 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
386 * Select an upload module and set it to mUpload. Dies on failure. If the
387 * request was a status request and not a true upload, returns false;
392 protected function selectUploadModule() {
393 $request = $this->getMain()->getRequest();
395 // chunk or one and only one of the following parameters is needed
396 if ( !$this->mParams
['chunk'] ) {
397 $this->requireOnlyOneParameter( $this->mParams
,
398 'filekey', 'file', 'url' );
401 // Status report for "upload to stash"/"upload from stash"
402 if ( $this->mParams
['filekey'] && $this->mParams
['checkstatus'] ) {
403 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
405 $this->dieUsage( 'No result in status data', 'missingresult' );
406 } elseif ( !$progress['status']->isGood() ) {
407 $this->dieUsage( $progress['status']->getWikiText( false, false, 'en' ), 'stashfailed' );
409 if ( isset( $progress['status']->value
['verification'] ) ) {
410 $this->checkVerification( $progress['status']->value
['verification'] );
412 unset( $progress['status'] ); // remove Status object
413 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
418 // The following modules all require the filename parameter to be set
419 if ( is_null( $this->mParams
['filename'] ) ) {
420 $this->dieUsageMsg( [ 'missingparam', 'filename' ] );
423 if ( $this->mParams
['chunk'] ) {
425 $this->mUpload
= new UploadFromChunks();
426 if ( isset( $this->mParams
['filekey'] ) ) {
427 if ( $this->mParams
['offset'] === 0 ) {
428 $this->dieUsage( 'Cannot supply a filekey when offset is 0', 'badparams' );
432 $this->mUpload
->continueChunks(
433 $this->mParams
['filename'],
434 $this->mParams
['filekey'],
435 $request->getUpload( 'chunk' )
438 if ( $this->mParams
['offset'] !== 0 ) {
439 $this->dieUsage( 'Must supply a filekey when offset is non-zero', 'badparams' );
442 // handle first chunk
443 $this->mUpload
->initialize(
444 $this->mParams
['filename'],
445 $request->getUpload( 'chunk' )
448 } elseif ( isset( $this->mParams
['filekey'] ) ) {
449 // Upload stashed in a previous request
450 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
451 $this->dieUsageMsg( 'invalid-file-key' );
454 $this->mUpload
= new UploadFromStash( $this->getUser() );
455 // This will not download the temp file in initialize() in async mode.
456 // We still have enough information to call checkWarnings() and such.
457 $this->mUpload
->initialize(
458 $this->mParams
['filekey'], $this->mParams
['filename'], !$this->mParams
['async']
460 } elseif ( isset( $this->mParams
['file'] ) ) {
461 $this->mUpload
= new UploadFromFile();
462 $this->mUpload
->initialize(
463 $this->mParams
['filename'],
464 $request->getUpload( 'file' )
466 } elseif ( isset( $this->mParams
['url'] ) ) {
467 // Make sure upload by URL is enabled:
468 if ( !UploadFromUrl
::isEnabled() ) {
469 $this->dieUsageMsg( 'copyuploaddisabled' );
472 if ( !UploadFromUrl
::isAllowedHost( $this->mParams
['url'] ) ) {
473 $this->dieUsageMsg( 'copyuploadbaddomain' );
476 if ( !UploadFromUrl
::isAllowedUrl( $this->mParams
['url'] ) ) {
477 $this->dieUsageMsg( 'copyuploadbadurl' );
480 $this->mUpload
= new UploadFromUrl
;
481 $this->mUpload
->initialize( $this->mParams
['filename'],
482 $this->mParams
['url'] );
489 * Checks that the user has permissions to perform this upload.
490 * Dies with usage message on inadequate permissions.
491 * @param User $user The user to check.
493 protected function checkPermissions( $user ) {
494 // Check whether the user has the appropriate permissions to upload anyway
495 $permission = $this->mUpload
->isAllowed( $user );
497 if ( $permission !== true ) {
498 if ( !$user->isLoggedIn() ) {
499 $this->dieUsageMsg( [ 'mustbeloggedin', 'upload' ] );
502 $this->dieUsageMsg( 'badaccess-groups' );
506 if ( $user->isBlocked() ) {
507 $this->dieBlocked( $user->getBlock() );
511 if ( $user->isBlockedGlobally() ) {
512 $this->dieBlocked( $user->getGlobalBlock() );
517 * Performs file verification, dies on error.
519 protected function verifyUpload() {
520 $verification = $this->mUpload
->verifyUpload();
521 if ( $verification['status'] === UploadBase
::OK
) {
525 $this->checkVerification( $verification );
529 * Performs file verification, dies on error.
530 * @param array $verification
532 protected function checkVerification( array $verification ) {
533 // @todo Move them to ApiBase's message map
534 switch ( $verification['status'] ) {
535 // Recoverable errors
536 case UploadBase
::MIN_LENGTH_PARTNAME
:
537 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
539 case UploadBase
::ILLEGAL_FILENAME
:
540 $this->dieRecoverableError( 'illegal-filename', 'filename',
541 [ 'filename' => $verification['filtered'] ] );
543 case UploadBase
::FILENAME_TOO_LONG
:
544 $this->dieRecoverableError( 'filename-toolong', 'filename' );
546 case UploadBase
::FILETYPE_MISSING
:
547 $this->dieRecoverableError( 'filetype-missing', 'filename' );
549 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
550 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
553 // Unrecoverable errors
554 case UploadBase
::EMPTY_FILE
:
555 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
557 case UploadBase
::FILE_TOO_LARGE
:
558 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
561 case UploadBase
::FILETYPE_BADTYPE
:
563 'filetype' => $verification['finalExt'],
564 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
566 ApiResult
::setIndexedTagName( $extradata['allowed'], 'ext' );
568 $msg = 'Filetype not permitted: ';
569 if ( isset( $verification['blacklistedExt'] ) ) {
570 $msg .= implode( ', ', $verification['blacklistedExt'] );
571 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
572 ApiResult
::setIndexedTagName( $extradata['blacklisted'], 'ext' );
574 $msg .= $verification['finalExt'];
576 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
578 case UploadBase
::VERIFICATION_ERROR
:
579 $parsed = $this->parseMsg( $verification['details'] );
580 $info = "This file did not pass file verification: {$parsed['info']}";
581 if ( $verification['details'][0] instanceof IApiMessage
) {
582 $code = $parsed['code'];
584 // For backwards-compatibility, all of the errors from UploadBase::verifyFile() are
585 // reported as 'verification-error', and the real error code is reported in 'details'.
586 $code = 'verification-error';
588 if ( $verification['details'][0] instanceof IApiMessage
) {
589 $msg = $verification['details'][0];
590 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
592 $details = $verification['details'];
594 ApiResult
::setIndexedTagName( $details, 'detail' );
595 $data = [ 'details' => $details ];
596 if ( isset( $parsed['data'] ) ) {
597 $data = array_merge( $data, $parsed['data'] );
600 $this->dieUsage( $info, $code, 0, $data );
602 case UploadBase
::HOOK_ABORTED
:
603 if ( is_array( $verification['error'] ) ) {
604 $params = $verification['error'];
605 } elseif ( $verification['error'] !== '' ) {
606 $params = [ $verification['error'] ];
608 $params = [ 'hookaborted' ];
610 $key = array_shift( $params );
611 $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
612 $this->dieUsage( $msg, 'hookaborted', 0, [ 'details' => $verification['error'] ] );
615 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
616 0, [ 'details' => [ 'code' => $verification['status'] ] ] );
623 * Returns a suitable array for inclusion into API results if there were warnings
624 * Returns the empty array if there were no warnings
628 protected function getApiWarnings() {
629 $warnings = $this->mUpload
->checkWarnings();
631 return $this->transformWarnings( $warnings );
634 protected function transformWarnings( $warnings ) {
637 ApiResult
::setIndexedTagName( $warnings, 'warning' );
639 if ( isset( $warnings['duplicate'] ) ) {
641 /** @var File $dupe */
642 foreach ( $warnings['duplicate'] as $dupe ) {
643 $dupes[] = $dupe->getName();
645 ApiResult
::setIndexedTagName( $dupes, 'duplicate' );
646 $warnings['duplicate'] = $dupes;
649 if ( isset( $warnings['exists'] ) ) {
650 $warning = $warnings['exists'];
651 unset( $warnings['exists'] );
652 /** @var LocalFile $localFile */
653 $localFile = isset( $warning['normalizedFile'] )
654 ?
$warning['normalizedFile']
656 $warnings[$warning['warning']] = $localFile->getName();
664 * Handles a stash exception, giving a useful error to the user.
665 * @param string $exceptionType Class name of the exception we encountered.
666 * @param string $message Message of the exception we encountered.
667 * @return array Array of message and code, suitable for passing to dieUsage()
669 protected function handleStashException( $exceptionType, $message ) {
670 switch ( $exceptionType ) {
671 case 'UploadStashFileNotFoundException':
673 'Could not find the file in the stash: ' . $message,
674 'stashedfilenotfound'
676 case 'UploadStashBadPathException':
678 'File key of improper format or otherwise invalid: ' . $message,
681 case 'UploadStashFileException':
683 'Could not store upload in the stash: ' . $message,
686 case 'UploadStashZeroLengthFileException':
688 'File is of zero length, and could not be stored in the stash: ' .
692 case 'UploadStashNotLoggedInException':
693 return [ 'Not logged in: ' . $message, 'stashnotloggedin' ];
694 case 'UploadStashWrongOwnerException':
695 return [ 'Wrong owner: ' . $message, 'stashwrongowner' ];
696 case 'UploadStashNoSuchKeyException':
697 return [ 'No such filekey: ' . $message, 'stashnosuchfilekey' ];
699 return [ $exceptionType . ': ' . $message, 'stasherror' ];
704 * Perform the actual upload. Returns a suitable result array on success;
707 * @param array $warnings Array of Api upload warnings
710 protected function performUpload( $warnings ) {
711 // Use comment as initial page text by default
712 if ( is_null( $this->mParams
['text'] ) ) {
713 $this->mParams
['text'] = $this->mParams
['comment'];
716 /** @var $file File */
717 $file = $this->mUpload
->getLocalFile();
719 // For preferences mode, we want to watch if 'watchdefault' is set,
720 // or if the *file* doesn't exist, and either 'watchuploads' or
721 // 'watchcreations' is set. But getWatchlistValue()'s automatic
722 // handling checks if the *title* exists or not, so we need to check
723 // all three preferences manually.
724 $watch = $this->getWatchlistValue(
725 $this->mParams
['watchlist'], $file->getTitle(), 'watchdefault'
728 if ( !$watch && $this->mParams
['watchlist'] == 'preferences' && !$file->exists() ) {
730 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
731 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
735 // Deprecated parameters
736 if ( $this->mParams
['watch'] ) {
740 if ( $this->mParams
['tags'] ) {
741 $status = ChangeTags
::canAddTagsAccompanyingChange( $this->mParams
['tags'], $this->getUser() );
742 if ( !$status->isOK() ) {
743 $this->dieStatus( $status );
747 // No errors, no warnings: do the upload
748 if ( $this->mParams
['async'] ) {
749 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
750 if ( $progress && $progress['result'] === 'Poll' ) {
751 $this->dieUsage( 'Upload from stash already in progress.', 'publishfailed' );
753 UploadBase
::setSessionStatus(
755 $this->mParams
['filekey'],
756 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status
::newGood() ]
758 JobQueueGroup
::singleton()->push( new PublishStashedFileJob(
759 Title
::makeTitle( NS_FILE
, $this->mParams
['filename'] ),
761 'filename' => $this->mParams
['filename'],
762 'filekey' => $this->mParams
['filekey'],
763 'comment' => $this->mParams
['comment'],
764 'tags' => $this->mParams
['tags'],
765 'text' => $this->mParams
['text'],
767 'session' => $this->getContext()->exportSession()
770 $result['result'] = 'Poll';
771 $result['stage'] = 'queued';
773 /** @var $status Status */
774 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
775 $this->mParams
['text'], $watch, $this->getUser(), $this->mParams
['tags'] );
777 if ( !$status->isGood() ) {
778 // Is there really no better way to do this?
779 $errors = $status->getErrorsByType( 'error' );
780 $msg = array_merge( [ $errors[0]['message'] ], $errors[0]['params'] );
781 $data = $status->getErrorsArray();
782 ApiResult
::setIndexedTagName( $data, 'error' );
783 // For backwards-compatibility, we use the 'internal-error' fallback key and merge $data
784 // into the root of the response (rather than something sane like [ 'details' => $data ]).
785 $this->dieRecoverableError( $msg, null, $data, 'internal-error' );
787 $result['result'] = 'Success';
790 $result['filename'] = $file->getName();
791 if ( $warnings && count( $warnings ) > 0 ) {
792 $result['warnings'] = $warnings;
798 public function mustBePosted() {
802 public function isWriteMode() {
806 public function getAllowedParams() {
809 ApiBase
::PARAM_TYPE
=> 'string',
812 ApiBase
::PARAM_DFLT
=> ''
815 ApiBase
::PARAM_TYPE
=> 'tags',
816 ApiBase
::PARAM_ISMULTI
=> true,
819 ApiBase
::PARAM_TYPE
=> 'text',
822 ApiBase
::PARAM_DFLT
=> false,
823 ApiBase
::PARAM_DEPRECATED
=> true,
826 ApiBase
::PARAM_DFLT
=> 'preferences',
827 ApiBase
::PARAM_TYPE
=> [
833 'ignorewarnings' => false,
835 ApiBase
::PARAM_TYPE
=> 'upload',
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 'checkstatus' => false,
864 public function needsToken() {
868 protected function getExamplesMessages() {
870 'action=upload&filename=Wiki.png' .
871 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
872 => 'apihelp-upload-example-url',
873 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
874 => 'apihelp-upload-example-filekey',
878 public function getHelpUrls() {
879 return 'https://www.mediawiki.org/wiki/API:Upload';