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 ApiMessage( 'apierror-stashinvalidfile', '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( $this->getErrorFormatter()->getMessageFromException(
329 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
333 if ( $status->isGood() ) {
334 $stashFile = $status->getValue();
335 $data['filekey'] = $stashFile->getFileKey();
336 // Backwards compatibility
337 $data['sessionkey'] = $data['filekey'];
338 return $data['filekey'];
341 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
342 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
343 // Statuses for it. Just extract the exception details and parse them ourselves.
344 list( $exceptionType, $message ) = $status->getMessage()->getParams();
345 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
346 wfDebug( __METHOD__
. ' ' . $debugMessage . "\n" );
350 if ( $failureMode !== 'optional' ) {
351 $this->dieStatus( $status );
353 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
359 * Throw an error that the user can recover from by providing a better
360 * value for $parameter
362 * @param array $errors Array of Message objects, message keys, key+param
363 * arrays, or StatusValue::getErrors()-style arrays
364 * @param string|null $parameter Parameter that needs revising
365 * @throws ApiUsageException
367 private function dieRecoverableError( $errors, $parameter = null ) {
368 $this->performStash( 'optional', $data );
371 $data['invalidparameter'] = $parameter;
374 $sv = StatusValue
::newGood();
375 foreach ( $errors as $error ) {
376 $msg = ApiMessage
::create( $error );
377 $msg->setApiData( $msg->getApiData() +
$data );
380 $this->dieStatus( $sv );
384 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
387 * @param Status $status
388 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
389 * @param array|null $moreExtraData
390 * @throws ApiUsageException
392 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
393 $sv = StatusValue
::newGood();
394 foreach ( $status->getErrors() as $error ) {
395 $msg = ApiMessage
::create( $error, $overrideCode );
396 if ( $moreExtraData ) {
397 $msg->setApiData( $msg->getApiData() +
$moreExtraData );
401 $this->dieStatus( $sv );
405 * Select an upload module and set it to mUpload. Dies on failure. If the
406 * request was a status request and not a true upload, returns false;
411 protected function selectUploadModule() {
412 $request = $this->getMain()->getRequest();
414 // chunk or one and only one of the following parameters is needed
415 if ( !$this->mParams
['chunk'] ) {
416 $this->requireOnlyOneParameter( $this->mParams
,
417 'filekey', 'file', 'url' );
420 // Status report for "upload to stash"/"upload from stash"
421 if ( $this->mParams
['filekey'] && $this->mParams
['checkstatus'] ) {
422 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
424 $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
425 } elseif ( !$progress['status']->isGood() ) {
426 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
428 if ( isset( $progress['status']->value
['verification'] ) ) {
429 $this->checkVerification( $progress['status']->value
['verification'] );
431 if ( isset( $progress['status']->value
['warnings'] ) ) {
432 $warnings = $this->transformWarnings( $progress['status']->value
['warnings'] );
434 $progress['warnings'] = $warnings;
437 unset( $progress['status'] ); // remove Status object
439 if ( isset( $progress['imageinfo'] ) ) {
440 $imageinfo = $progress['imageinfo'];
441 unset( $progress['imageinfo'] );
444 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
445 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
446 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
448 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
454 // The following modules all require the filename parameter to be set
455 if ( is_null( $this->mParams
['filename'] ) ) {
456 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
459 if ( $this->mParams
['chunk'] ) {
461 $this->mUpload
= new UploadFromChunks( $this->getUser() );
462 if ( isset( $this->mParams
['filekey'] ) ) {
463 if ( $this->mParams
['offset'] === 0 ) {
464 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
468 $this->mUpload
->continueChunks(
469 $this->mParams
['filename'],
470 $this->mParams
['filekey'],
471 $request->getUpload( 'chunk' )
474 if ( $this->mParams
['offset'] !== 0 ) {
475 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
478 // handle first chunk
479 $this->mUpload
->initialize(
480 $this->mParams
['filename'],
481 $request->getUpload( 'chunk' )
484 } elseif ( isset( $this->mParams
['filekey'] ) ) {
485 // Upload stashed in a previous request
486 if ( !UploadFromStash
::isValidKey( $this->mParams
['filekey'] ) ) {
487 $this->dieWithError( 'apierror-invalid-file-key' );
490 $this->mUpload
= new UploadFromStash( $this->getUser() );
491 // This will not download the temp file in initialize() in async mode.
492 // We still have enough information to call checkWarnings() and such.
493 $this->mUpload
->initialize(
494 $this->mParams
['filekey'], $this->mParams
['filename'], !$this->mParams
['async']
496 } elseif ( isset( $this->mParams
['file'] ) ) {
497 $this->mUpload
= new UploadFromFile();
498 $this->mUpload
->initialize(
499 $this->mParams
['filename'],
500 $request->getUpload( 'file' )
502 } elseif ( isset( $this->mParams
['url'] ) ) {
503 // Make sure upload by URL is enabled:
504 if ( !UploadFromUrl
::isEnabled() ) {
505 $this->dieWithError( 'copyuploaddisabled' );
508 if ( !UploadFromUrl
::isAllowedHost( $this->mParams
['url'] ) ) {
509 $this->dieWithError( 'apierror-copyuploadbaddomain' );
512 if ( !UploadFromUrl
::isAllowedUrl( $this->mParams
['url'] ) ) {
513 $this->dieWithError( 'apierror-copyuploadbadurl' );
516 $this->mUpload
= new UploadFromUrl
;
517 $this->mUpload
->initialize( $this->mParams
['filename'],
518 $this->mParams
['url'] );
525 * Checks that the user has permissions to perform this upload.
526 * Dies with usage message on inadequate permissions.
527 * @param User $user The user to check.
529 protected function checkPermissions( $user ) {
530 // Check whether the user has the appropriate permissions to upload anyway
531 $permission = $this->mUpload
->isAllowed( $user );
533 if ( $permission !== true ) {
534 if ( !$user->isLoggedIn() ) {
535 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
538 $this->dieStatus( User
::newFatalPermissionDeniedStatus( $permission ) );
542 if ( $user->isBlocked() ) {
543 $this->dieBlocked( $user->getBlock() );
547 if ( $user->isBlockedGlobally() ) {
548 $this->dieBlocked( $user->getGlobalBlock() );
553 * Performs file verification, dies on error.
555 protected function verifyUpload() {
556 $verification = $this->mUpload
->verifyUpload();
557 if ( $verification['status'] === UploadBase
::OK
) {
561 $this->checkVerification( $verification );
565 * Performs file verification, dies on error.
566 * @param array $verification
568 protected function checkVerification( array $verification ) {
569 switch ( $verification['status'] ) {
570 // Recoverable errors
571 case UploadBase
::MIN_LENGTH_PARTNAME
:
572 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
574 case UploadBase
::ILLEGAL_FILENAME
:
575 $this->dieRecoverableError(
576 [ ApiMessage
::create(
577 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
581 case UploadBase
::FILENAME_TOO_LONG
:
582 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
584 case UploadBase
::FILETYPE_MISSING
:
585 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
587 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
588 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
591 // Unrecoverable errors
592 case UploadBase
::EMPTY_FILE
:
593 $this->dieWithError( 'empty-file' );
595 case UploadBase
::FILE_TOO_LARGE
:
596 $this->dieWithError( 'file-too-large' );
599 case UploadBase
::FILETYPE_BADTYPE
:
601 'filetype' => $verification['finalExt'],
602 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
604 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
606 'filetype-banned-type',
607 null, // filled in below
608 Message
::listParam( $extensions, 'comma' ),
609 count( $extensions ),
610 null, // filled in below
612 ApiResult
::setIndexedTagName( $extradata['allowed'], 'ext' );
614 if ( isset( $verification['blacklistedExt'] ) ) {
615 $msg[1] = Message
::listParam( $verification['blacklistedExt'], 'comma' );
616 $msg[4] = count( $verification['blacklistedExt'] );
617 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
618 ApiResult
::setIndexedTagName( $extradata['blacklisted'], 'ext' );
620 $msg[1] = $verification['finalExt'];
624 $this->dieWithError( $msg, 'filetype-banned', $extradata );
627 case UploadBase
::VERIFICATION_ERROR
:
628 $msg = ApiMessage
::create( $verification['details'], 'verification-error' );
629 if ( $verification['details'][0] instanceof MessageSpecifier
) {
630 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
632 $details = $verification['details'];
634 ApiResult
::setIndexedTagName( $details, 'detail' );
635 $msg->setApiData( $msg->getApiData() +
[ 'details' => $details ] );
636 $this->dieWithError( $msg );
639 case UploadBase
::HOOK_ABORTED
:
640 $msg = $verification['error'] === '' ?
'hookaborted' : $verification['error'];
641 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
644 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
645 [ 'details' => [ 'code' => $verification['status'] ] ] );
652 * Returns a suitable array for inclusion into API results if there were warnings
653 * Returns the empty array if there were no warnings
657 protected function getApiWarnings() {
658 $warnings = $this->mUpload
->checkWarnings();
660 return $this->transformWarnings( $warnings );
663 protected function transformWarnings( $warnings ) {
666 ApiResult
::setIndexedTagName( $warnings, 'warning' );
668 if ( isset( $warnings['duplicate'] ) ) {
670 /** @var File $dupe */
671 foreach ( $warnings['duplicate'] as $dupe ) {
672 $dupes[] = $dupe->getName();
674 ApiResult
::setIndexedTagName( $dupes, 'duplicate' );
675 $warnings['duplicate'] = $dupes;
678 if ( isset( $warnings['exists'] ) ) {
679 $warning = $warnings['exists'];
680 unset( $warnings['exists'] );
681 /** @var LocalFile $localFile */
682 $localFile = isset( $warning['normalizedFile'] )
683 ?
$warning['normalizedFile']
685 $warnings[$warning['warning']] = $localFile->getName();
688 if ( isset( $warnings['no-change'] ) ) {
689 /** @var File $file */
690 $file = $warnings['no-change'];
691 unset( $warnings['no-change'] );
693 $warnings['nochange'] = [
694 'timestamp' => wfTimestamp( TS_ISO_8601
, $file->getTimestamp() )
698 if ( isset( $warnings['duplicate-version'] ) ) {
700 /** @var File $dupe */
701 foreach ( $warnings['duplicate-version'] as $dupe ) {
703 'timestamp' => wfTimestamp( TS_ISO_8601
, $dupe->getTimestamp() )
706 unset( $warnings['duplicate-version'] );
708 ApiResult
::setIndexedTagName( $dupes, 'ver' );
709 $warnings['duplicateversions'] = $dupes;
717 * Handles a stash exception, giving a useful error to the user.
718 * @todo Internationalize the exceptions then get rid of this
719 * @param Exception $e
720 * @return StatusValue
722 protected function handleStashException( $e ) {
723 switch ( get_class( $e ) ) {
724 case 'UploadStashFileNotFoundException':
725 $wrap = 'apierror-stashedfilenotfound';
727 case 'UploadStashBadPathException':
728 $wrap = 'apierror-stashpathinvalid';
730 case 'UploadStashFileException':
731 $wrap = 'apierror-stashfilestorage';
733 case 'UploadStashZeroLengthFileException':
734 $wrap = 'apierror-stashzerolength';
736 case 'UploadStashNotLoggedInException':
737 return StatusValue
::newFatal( ApiMessage
::create(
738 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
740 case 'UploadStashWrongOwnerException':
741 $wrap = 'apierror-stashwrongowner';
743 case 'UploadStashNoSuchKeyException':
744 $wrap = 'apierror-stashnosuchfilekey';
747 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
750 return StatusValue
::newFatal(
751 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
756 * Perform the actual upload. Returns a suitable result array on success;
759 * @param array $warnings Array of Api upload warnings
762 protected function performUpload( $warnings ) {
763 // Use comment as initial page text by default
764 if ( is_null( $this->mParams
['text'] ) ) {
765 $this->mParams
['text'] = $this->mParams
['comment'];
768 /** @var $file LocalFile */
769 $file = $this->mUpload
->getLocalFile();
771 // For preferences mode, we want to watch if 'watchdefault' is set,
772 // or if the *file* doesn't exist, and either 'watchuploads' or
773 // 'watchcreations' is set. But getWatchlistValue()'s automatic
774 // handling checks if the *title* exists or not, so we need to check
775 // all three preferences manually.
776 $watch = $this->getWatchlistValue(
777 $this->mParams
['watchlist'], $file->getTitle(), 'watchdefault'
780 if ( !$watch && $this->mParams
['watchlist'] == 'preferences' && !$file->exists() ) {
782 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
783 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
787 // Deprecated parameters
788 if ( $this->mParams
['watch'] ) {
792 if ( $this->mParams
['tags'] ) {
793 $status = ChangeTags
::canAddTagsAccompanyingChange( $this->mParams
['tags'], $this->getUser() );
794 if ( !$status->isOK() ) {
795 $this->dieStatus( $status );
799 // No errors, no warnings: do the upload
800 if ( $this->mParams
['async'] ) {
801 $progress = UploadBase
::getSessionStatus( $this->getUser(), $this->mParams
['filekey'] );
802 if ( $progress && $progress['result'] === 'Poll' ) {
803 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
805 UploadBase
::setSessionStatus(
807 $this->mParams
['filekey'],
808 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status
::newGood() ]
810 JobQueueGroup
::singleton()->push( new PublishStashedFileJob(
811 Title
::makeTitle( NS_FILE
, $this->mParams
['filename'] ),
813 'filename' => $this->mParams
['filename'],
814 'filekey' => $this->mParams
['filekey'],
815 'comment' => $this->mParams
['comment'],
816 'tags' => $this->mParams
['tags'],
817 'text' => $this->mParams
['text'],
819 'session' => $this->getContext()->exportSession()
822 $result['result'] = 'Poll';
823 $result['stage'] = 'queued';
825 /** @var $status Status */
826 $status = $this->mUpload
->performUpload( $this->mParams
['comment'],
827 $this->mParams
['text'], $watch, $this->getUser(), $this->mParams
['tags'] );
829 if ( !$status->isGood() ) {
830 $this->dieRecoverableError( $status->getErrors() );
832 $result['result'] = 'Success';
835 $result['filename'] = $file->getName();
836 if ( $warnings && count( $warnings ) > 0 ) {
837 $result['warnings'] = $warnings;
843 public function mustBePosted() {
847 public function isWriteMode() {
851 public function getAllowedParams() {
854 ApiBase
::PARAM_TYPE
=> 'string',
857 ApiBase
::PARAM_DFLT
=> ''
860 ApiBase
::PARAM_TYPE
=> 'tags',
861 ApiBase
::PARAM_ISMULTI
=> true,
864 ApiBase
::PARAM_TYPE
=> 'text',
867 ApiBase
::PARAM_DFLT
=> false,
868 ApiBase
::PARAM_DEPRECATED
=> true,
871 ApiBase
::PARAM_DFLT
=> 'preferences',
872 ApiBase
::PARAM_TYPE
=> [
878 'ignorewarnings' => false,
880 ApiBase
::PARAM_TYPE
=> 'upload',
885 ApiBase
::PARAM_DEPRECATED
=> true,
890 ApiBase
::PARAM_TYPE
=> 'integer',
891 ApiBase
::PARAM_MIN
=> 0,
892 ApiBase
::PARAM_MAX
=> UploadBase
::getMaxUploadSize(),
895 ApiBase
::PARAM_TYPE
=> 'integer',
896 ApiBase
::PARAM_MIN
=> 0,
899 ApiBase
::PARAM_TYPE
=> 'upload',
903 'checkstatus' => false,
909 public function needsToken() {
913 protected function getExamplesMessages() {
915 'action=upload&filename=Wiki.png' .
916 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
917 => 'apihelp-upload-example-url',
918 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
919 => 'apihelp-upload-example-filekey',
923 public function getHelpUrls() {
924 return 'https://www.mediawiki.org/wiki/API:Upload';