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->dieWithError( '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->dieDebug( __METHOD__
, 'No upload module set' );
66 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
67 $this->dieStatus( $this->handleStashException( $e ) );
70 // First check permission to upload
71 $this->checkPermissions( $user );
73 // Fetch the file (usually a no-op)
74 /** @var $status Status */
75 $status = $this->mUpload
->fetchFile();
76 if ( !$status->isGood() ) {
77 $this->dieStatus( $status );
80 // Check if the uploaded file is sane
81 if ( $this->mParams
['chunk'] ) {
82 $maxSize = UploadBase
::getMaxUploadSize();
83 if ( $this->mParams
['filesize'] > $maxSize ) {
84 $this->dieWithError( 'file-too-large' );
86 if ( !$this->mUpload
->getTitle() ) {
87 $this->dieWithError( 'illegal-filename' );
89 } elseif ( $this->mParams
['async'] && $this->mParams
['filekey'] ) {
90 // defer verification to background process
92 wfDebug( __METHOD__
. " about to verify\n" );
93 $this->verifyUpload();
96 // Check if the user has the rights to modify or overwrite the requested title
97 // (This check is irrelevant if stashing is already requested, since the errors
98 // can always be fixed by changing the title)
99 if ( !$this->mParams
['stash'] ) {
100 $permErrors = $this->mUpload
->verifyTitlePermissions( $user );
101 if ( $permErrors !== true ) {
102 $this->dieRecoverableError( $permErrors, 'filename' );
106 // Get the result based on the current upload context:
108 $result = $this->getContextResult();
109 } catch ( UploadStashException
$e ) { // XXX: don't spam exception log
110 $this->dieStatus( $this->handleStashException( $e ) );
112 $this->getResult()->addValue( null, $this->getModuleName(), $result );
114 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
115 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
116 if ( $result['result'] === 'Success' ) {
117 $imageinfo = $this->mUpload
->getImageInfo( $this->getResult() );
118 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
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->dieWithError( 'apierror-ratelimited' );
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 $result['result'] = 'Success';
161 if ( $warnings && count( $warnings ) > 0 ) {
162 $result['warnings'] = $warnings;
164 // Some uploads can request they be stashed, so as not to publish them immediately.
165 // In this case, a failure to stash ought to be fatal
166 $this->performStash( 'critical', $result );
172 * Get Warnings Result
173 * @param array $warnings Array of Api upload warnings
176 private function getWarningsResult( $warnings ) {
178 $result['result'] = 'Warning';
179 $result['warnings'] = $warnings;
180 // in case the warnings can be fixed with some further user action, let's stash this upload
181 // and return a key they can use to restart it
182 $this->performStash( 'optional', $result );
188 * Get the result of a chunk upload.
189 * @param array $warnings Array of Api upload warnings
192 private function getChunkResult( $warnings ) {
195 if ( $warnings && count( $warnings ) > 0 ) {
196 $result['warnings'] = $warnings;
199 $request = $this->getMain()->getRequest();
200 $chunkPath = $request->getFileTempname( 'chunk' );
201 $chunkSize = $request->getUpload( 'chunk' )->getSize();
202 $totalSoFar = $this->mParams
['offset'] +
$chunkSize;
203 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
205 // Sanity check sizing
206 if ( $totalSoFar > $this->mParams
['filesize'] ) {
207 $this->dieWithError( 'apierror-invalid-chunk' );
210 // Enforce minimum chunk size
211 if ( $totalSoFar != $this->mParams
['filesize'] && $chunkSize < $minChunkSize ) {
212 $this->dieWithError( [ 'apierror-chunk-too-small', Message
::numParam( $minChunkSize ) ] );
215 if ( $this->mParams
['offset'] == 0 ) {
216 $filekey = $this->performStash( 'critical' );
218 $filekey = $this->mParams
['filekey'];
220 // Don't allow further uploads to an already-completed session
221 $progress = UploadBase
::getSessionStatus( $this->getUser(), $filekey );
223 // Probably can't get here, but check anyway just in case
224 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
225 } elseif ( $progress['result'] !== 'Continue' ||
$progress['stage'] !== 'uploading' ) {
226 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
229 $status = $this->mUpload
->addChunk(
230 $chunkPath, $chunkSize, $this->mParams
['offset'] );
231 if ( !$status->isGood() ) {
233 'offset' => $this->mUpload
->getOffset(),
236 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
240 // Check we added the last chunk:
241 if ( $totalSoFar == $this->mParams
['filesize'] ) {
242 if ( $this->mParams
['async'] ) {
243 UploadBase
::setSessionStatus(
246 [ 'result' => 'Poll',
247 'stage' => 'queued', 'status' => Status
::newGood() ]
249 JobQueueGroup
::singleton()->push( new AssembleUploadChunksJob(
250 Title
::makeTitle( NS_FILE
, $filekey ),
252 'filename' => $this->mParams
['filename'],
253 'filekey' => $filekey,
254 'session' => $this->getContext()->exportSession()
257 $result['result'] = 'Poll';
258 $result['stage'] = 'queued';
260 $status = $this->mUpload
->concatenateChunks();
261 if ( !$status->isGood() ) {
262 UploadBase
::setSessionStatus(
265 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
267 $this->dieStatusWithCode( $status, 'stashfailed' );
270 // We can only get warnings like 'duplicate' after concatenating the chunks
271 $warnings = $this->getApiWarnings();
273 $result['warnings'] = $warnings;
276 // The fully concatenated file has a new filekey. So remove
277 // the old filekey and fetch the new one.
278 UploadBase
::setSessionStatus( $this->getUser(), $filekey, false );
279 $this->mUpload
->stash
->removeFile( $filekey );
280 $filekey = $this->mUpload
->getStashFile()->getFileKey();
282 $result['result'] = 'Success';
285 UploadBase
::setSessionStatus(
289 'result' => 'Continue',
290 'stage' => 'uploading',
291 'offset' => $totalSoFar,
292 'status' => Status
::newGood(),
295 $result['result'] = 'Continue';
296 $result['offset'] = $totalSoFar;
299 $result['filekey'] = $filekey;
305 * Stash the file and add the file key, or error information if it fails, to the data.
307 * @param string $failureMode What to do on failure to stash:
308 * - When 'critical', use dieStatus() to produce an error response and throw an exception.
309 * Use this when stashing the file was the primary purpose of the API request.
310 * - When 'optional', only add a 'stashfailed' key to the data and return null.
311 * Use this when some error happened for a non-stash upload and we're stashing the file
312 * only to save the client the trouble of re-uploading it.
313 * @param array &$data API result to which to add the information
314 * @return string|null File key
316 private function performStash( $failureMode, &$data = null ) {
317 $isPartial = (bool)$this->mParams
['chunk'];
319 $status = $this->mUpload
->tryStashFile( $this->getUser(), $isPartial );
321 if ( $status->isGood() && !$status->getValue() ) {
322 // Not actually a 'good' status...
323 $status->fatal( new ApiRawMessage( 'Invalid stashed file', 'stashfailed' ) );
325 } catch ( Exception
$e ) {
326 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
327 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
328 $status = Status
::newFatal( new ApiRawMessage( $e->getMessage(), 'stashfailed' ) );
331 if ( $status->isGood() ) {
332 $stashFile = $status->getValue();
333 $data['filekey'] = $stashFile->getFileKey();
334 // Backwards compatibility
335 $data['sessionkey'] = $data['filekey'];
336 return $data['filekey'];
339 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
340 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
341 // Statuses for it. Just extract the exception details and parse them ourselves.
342 list( $exceptionType, $message ) = $status->getMessage()->getParams();
343 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
344 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
348 if ( $failureMode !== 'optional' ) {
349 $this->dieStatus( $status );
351 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
357 * Throw an error that the user can recover from by providing a better
358 * value for $parameter
360 * @param array $errors Array of Message objects, message keys, key+param
361 * arrays, or StatusValue::getErrors()-style arrays
362 * @param string|null $parameter Parameter that needs revising
363 * @throws ApiUsageException
365 private function dieRecoverableError( $errors, $parameter = null ) {
366 $this->performStash( 'optional', $data );
369 $data['invalidparameter'] = $parameter;
372 $sv = StatusValue
::newGood();
373 foreach ( $errors as $error ) {
374 $msg = ApiMessage
::create( $error );
375 $msg->setApiData( $msg->getApiData() +
$data );
378 $this->dieStatus( $sv );
382 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
385 * @param Status $status
386 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
387 * @param array|null $moreExtraData
388 * @throws ApiUsageException
390 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
391 $sv = StatusValue
::newGood();
392 foreach ( $status->getErrors() as $error ) {
393 $msg = ApiMessage
::create( $error, $overrideCode );
394 if ( $moreExtraData ) {
395 $msg->setApiData( $msg->getApiData() +
$moreExtraData );
399 $this->dieStatus( $sv );
403 * Select an upload module and set it to mUpload. Dies on failure. If the
404 * request was a status request and not a true upload, returns false;
409 protected function selectUploadModule() {
410 $request = $this->getMain()->getRequest();
412 // chunk or one and only one of the following parameters is needed
413 if ( !$this->mParams
['chunk'] ) {
414 $this->requireOnlyOneParameter( $this->mParams
,
415 'filekey', 'file', 'url' );
418 // Status report for "upload to stash"/"upload from stash"
419 if ( $this->mParams
['filekey'] && $this->mParams
['checkstatus'] ) {
420 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
422 $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
423 } elseif ( !$progress['status']->isGood() ) {
424 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
426 if ( isset( $progress['status']->value
['verification'] ) ) {
427 $this->checkVerification( $progress['status']->value
['verification'] );
429 if ( isset( $progress['status']->value
['warnings'] ) ) {
430 $warnings = $this->transformWarnings( $progress['status']->value
['warnings'] );
432 $progress['warnings'] = $warnings;
435 unset( $progress['status'] ); // remove Status object
437 if ( isset( $progress['imageinfo'] ) ) {
438 $imageinfo = $progress['imageinfo'];
439 unset( $progress['imageinfo'] );
442 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
443 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
444 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
446 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
452 // The following modules all require the filename parameter to be set
453 if ( is_null( $this->mParams
['filename'] ) ) {
454 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
457 if ( $this->mParams
['chunk'] ) {
459 $this->mUpload
= new UploadFromChunks( $this->getUser() );
460 if ( isset( $this->mParams
['filekey'] ) ) {
461 if ( $this->mParams
['offset'] === 0 ) {
462 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
466 $this->mUpload
->continueChunks(
467 $this->mParams
['filename'],
468 $this->mParams
['filekey'],
469 $request->getUpload( 'chunk' )
472 if ( $this->mParams
['offset'] !== 0 ) {
473 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
476 // handle first chunk
477 $this->mUpload
->initialize(
478 $this->mParams
['filename'],
479 $request->getUpload( 'chunk' )
482 } elseif ( isset( $this->mParams
['filekey'] ) ) {
483 // Upload stashed in a previous request
484 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
485 $this->dieWithError( 'apierror-invalid-file-key' );
488 $this->mUpload
= new UploadFromStash( $this->getUser() );
489 // This will not download the temp file in initialize() in async mode.
490 // We still have enough information to call checkWarnings() and such.
491 $this->mUpload
->initialize(
492 $this->mParams
['filekey'], $this->mParams
['filename'], !$this->mParams
['async']
494 } elseif ( isset( $this->mParams
['file'] ) ) {
495 $this->mUpload
= new UploadFromFile();
496 $this->mUpload
->initialize(
497 $this->mParams
['filename'],
498 $request->getUpload( 'file' )
500 } elseif ( isset( $this->mParams
['url'] ) ) {
501 // Make sure upload by URL is enabled:
502 if ( !UploadFromUrl
::isEnabled() ) {
503 $this->dieWithError( 'copyuploaddisabled' );
506 if ( !UploadFromUrl
::isAllowedHost( $this->mParams
['url'] ) ) {
507 $this->dieWithError( 'apierror-copyuploadbaddomain' );
510 if ( !UploadFromUrl
::isAllowedUrl( $this->mParams
['url'] ) ) {
511 $this->dieWithError( 'apierror-copyuploadbadurl' );
514 $this->mUpload
= new UploadFromUrl
;
515 $this->mUpload
->initialize( $this->mParams
['filename'],
516 $this->mParams
['url'] );
523 * Checks that the user has permissions to perform this upload.
524 * Dies with usage message on inadequate permissions.
525 * @param User $user The user to check.
527 protected function checkPermissions( $user ) {
528 // Check whether the user has the appropriate permissions to upload anyway
529 $permission = $this->mUpload
->isAllowed( $user );
531 if ( $permission !== true ) {
532 if ( !$user->isLoggedIn() ) {
533 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
536 $this->dieStatus( User
::newFatalPermissionDeniedStatus( $permission ) );
540 if ( $user->isBlocked() ) {
541 $this->dieBlocked( $user->getBlock() );
545 if ( $user->isBlockedGlobally() ) {
546 $this->dieBlocked( $user->getGlobalBlock() );
551 * Performs file verification, dies on error.
553 protected function verifyUpload() {
554 $verification = $this->mUpload
->verifyUpload();
555 if ( $verification['status'] === UploadBase
::OK
) {
559 $this->checkVerification( $verification );
563 * Performs file verification, dies on error.
564 * @param array $verification
566 protected function checkVerification( array $verification ) {
567 // @todo Move them to ApiBase's message map
568 switch ( $verification['status'] ) {
569 // Recoverable errors
570 case UploadBase
::MIN_LENGTH_PARTNAME
:
571 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
573 case UploadBase
::ILLEGAL_FILENAME
:
574 $this->dieRecoverableError(
575 [ ApiMessage
::create(
576 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
580 case UploadBase
::FILENAME_TOO_LONG
:
581 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
583 case UploadBase
::FILETYPE_MISSING
:
584 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
586 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
587 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
590 // Unrecoverable errors
591 case UploadBase
::EMPTY_FILE
:
592 $this->dieWithError( 'empty-file' );
594 case UploadBase
::FILE_TOO_LARGE
:
595 $this->dieWithError( 'file-too-large' );
598 case UploadBase
::FILETYPE_BADTYPE
:
600 'filetype' => $verification['finalExt'],
601 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
603 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
605 'filetype-banned-type',
606 null, // filled in below
607 Message
::listParam( $extensions, 'comma' ),
608 count( $extensions ),
609 null, // filled in below
611 ApiResult
::setIndexedTagName( $extradata['allowed'], 'ext' );
613 if ( isset( $verification['blacklistedExt'] ) ) {
614 $msg[1] = Message
::listParam( $verification['blacklistedExt'], 'comma' );
615 $msg[4] = count( $verification['blacklistedExt'] );
616 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
617 ApiResult
::setIndexedTagName( $extradata['blacklisted'], 'ext' );
619 $msg[1] = $verification['finalExt'];
623 $this->dieWithError( $msg, 'filetype-banned', $extradata );
626 case UploadBase
::VERIFICATION_ERROR
:
627 $msg = ApiMessage
::create( $verification['details'], 'verification-error' );
628 if ( $verification['details'][0] instanceof MessageSpecifier
) {
629 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
631 $details = $verification['details'];
633 ApiResult
::setIndexedTagName( $details, 'detail' );
634 $msg->setApiData( $msg->getApiData() +
[ 'details' => $details ] );
635 $this->dieWithError( $msg );
638 case UploadBase
::HOOK_ABORTED
:
639 $this->dieWithError( $params, 'hookaborted', [ 'details' => $verification['error'] ] );
642 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
643 [ 'details' => [ 'code' => $verification['status'] ] ] );
650 * Returns a suitable array for inclusion into API results if there were warnings
651 * Returns the empty array if there were no warnings
655 protected function getApiWarnings() {
656 $warnings = $this->mUpload
->checkWarnings();
658 return $this->transformWarnings( $warnings );
661 protected function transformWarnings( $warnings ) {
664 ApiResult
::setIndexedTagName( $warnings, 'warning' );
666 if ( isset( $warnings['duplicate'] ) ) {
668 /** @var File $dupe */
669 foreach ( $warnings['duplicate'] as $dupe ) {
670 $dupes[] = $dupe->getName();
672 ApiResult
::setIndexedTagName( $dupes, 'duplicate' );
673 $warnings['duplicate'] = $dupes;
676 if ( isset( $warnings['exists'] ) ) {
677 $warning = $warnings['exists'];
678 unset( $warnings['exists'] );
679 /** @var LocalFile $localFile */
680 $localFile = isset( $warning['normalizedFile'] )
681 ?
$warning['normalizedFile']
683 $warnings[$warning['warning']] = $localFile->getName();
686 if ( isset( $warnings['no-change'] ) ) {
687 /** @var File $file */
688 $file = $warnings['no-change'];
689 unset( $warnings['no-change'] );
691 $warnings['nochange'] = [
692 'timestamp' => wfTimestamp( TS_ISO_8601
, $file->getTimestamp() )
696 if ( isset( $warnings['duplicate-version'] ) ) {
698 /** @var File $dupe */
699 foreach ( $warnings['duplicate-version'] as $dupe ) {
701 'timestamp' => wfTimestamp( TS_ISO_8601
, $dupe->getTimestamp() )
704 unset( $warnings['duplicate-version'] );
706 ApiResult
::setIndexedTagName( $dupes, 'ver' );
707 $warnings['duplicateversions'] = $dupes;
715 * Handles a stash exception, giving a useful error to the user.
716 * @todo Internationalize the exceptions
717 * @param Exception $e
718 * @return StatusValue
720 protected function handleStashException( $e ) {
721 $err = wfEscapeWikiText( $e->getMessage() );
722 switch ( get_class( $exception ) ) {
723 case 'UploadStashFileNotFoundException':
724 return StatusValue
::newFatal( 'apierror-stashedfilenotfound', $err );
725 case 'UploadStashBadPathException':
726 return StatusValue
::newFatal( 'apierror-stashpathinvalid', $err );
727 case 'UploadStashFileException':
728 return StatusValue
::newFatal( 'apierror-stashfilestorage', $err );
729 case 'UploadStashZeroLengthFileException':
730 return StatusValue
::newFatal( 'apierror-stashzerolength', $err );
731 case 'UploadStashNotLoggedInException':
732 return StatusValue
::newFatal( ApiMessage
::create(
733 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
735 case 'UploadStashWrongOwnerException':
736 return StatusValue
::newFatal( 'apierror-stashwrongowner', $err );
737 case 'UploadStashNoSuchKeyException':
738 return StatusValue
::newFatal( 'apierror-stashnosuchfilekey', $err );
740 return StatusValue
::newFatal( 'uploadstash-exception', get_class( $e ), $err );
745 * Perform the actual upload. Returns a suitable result array on success;
748 * @param array $warnings Array of Api upload warnings
751 protected function performUpload( $warnings ) {
752 // Use comment as initial page text by default
753 if ( is_null( $this->mParams
['text'] ) ) {
754 $this->mParams
['text'] = $this->mParams
['comment'];
757 /** @var $file LocalFile */
758 $file = $this->mUpload
->getLocalFile();
760 // For preferences mode, we want to watch if 'watchdefault' is set,
761 // or if the *file* doesn't exist, and either 'watchuploads' or
762 // 'watchcreations' is set. But getWatchlistValue()'s automatic
763 // handling checks if the *title* exists or not, so we need to check
764 // all three preferences manually.
765 $watch = $this->getWatchlistValue(
766 $this->mParams
['watchlist'], $file->getTitle(), 'watchdefault'
769 if ( !$watch && $this->mParams
['watchlist'] == 'preferences' && !$file->exists() ) {
771 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
772 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
776 // Deprecated parameters
777 if ( $this->mParams
['watch'] ) {
781 if ( $this->mParams
['tags'] ) {
782 $status = ChangeTags
::canAddTagsAccompanyingChange( $this->mParams
['tags'], $this->getUser() );
783 if ( !$status->isOK() ) {
784 $this->dieStatus( $status );
788 // No errors, no warnings: do the upload
789 if ( $this->mParams
['async'] ) {
790 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
791 if ( $progress && $progress['result'] === 'Poll' ) {
792 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
794 UploadBase
::setSessionStatus(
796 $this->mParams
['filekey'],
797 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status
::newGood() ]
799 JobQueueGroup
::singleton()->push( new PublishStashedFileJob(
800 Title
::makeTitle( NS_FILE
, $this->mParams
['filename'] ),
802 'filename' => $this->mParams
['filename'],
803 'filekey' => $this->mParams
['filekey'],
804 'comment' => $this->mParams
['comment'],
805 'tags' => $this->mParams
['tags'],
806 'text' => $this->mParams
['text'],
808 'session' => $this->getContext()->exportSession()
811 $result['result'] = 'Poll';
812 $result['stage'] = 'queued';
814 /** @var $status Status */
815 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
816 $this->mParams
['text'], $watch, $this->getUser(), $this->mParams
['tags'] );
818 if ( !$status->isGood() ) {
819 $this->dieRecoverableError( $status->getErrors() );
821 $result['result'] = 'Success';
824 $result['filename'] = $file->getName();
825 if ( $warnings && count( $warnings ) > 0 ) {
826 $result['warnings'] = $warnings;
832 public function mustBePosted() {
836 public function isWriteMode() {
840 public function getAllowedParams() {
843 ApiBase
::PARAM_TYPE
=> 'string',
846 ApiBase
::PARAM_DFLT
=> ''
849 ApiBase
::PARAM_TYPE
=> 'tags',
850 ApiBase
::PARAM_ISMULTI
=> true,
853 ApiBase
::PARAM_TYPE
=> 'text',
856 ApiBase
::PARAM_DFLT
=> false,
857 ApiBase
::PARAM_DEPRECATED
=> true,
860 ApiBase
::PARAM_DFLT
=> 'preferences',
861 ApiBase
::PARAM_TYPE
=> [
867 'ignorewarnings' => false,
869 ApiBase
::PARAM_TYPE
=> 'upload',
874 ApiBase
::PARAM_DEPRECATED
=> true,
879 ApiBase
::PARAM_TYPE
=> 'integer',
880 ApiBase
::PARAM_MIN
=> 0,
881 ApiBase
::PARAM_MAX
=> UploadBase
::getMaxUploadSize(),
884 ApiBase
::PARAM_TYPE
=> 'integer',
885 ApiBase
::PARAM_MIN
=> 0,
888 ApiBase
::PARAM_TYPE
=> 'upload',
892 'checkstatus' => false,
898 public function needsToken() {
902 protected function getExamplesMessages() {
904 'action=upload&filename=Wiki.png' .
905 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
906 => 'apihelp-upload-example-url',
907 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
908 => 'apihelp-upload-example-filekey',
912 public function getHelpUrls() {
913 return 'https://www.mediawiki.org/wiki/API:Upload';