Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / api / ApiUpload.php
blob6b38302c8fc156a72d51cfd1b2cba3a7c49e1abe
1 <?php
2 /**
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
24 * @file
27 /**
28 * @ingroup API
30 class ApiUpload extends ApiBase {
31 /** @var UploadBase|UploadFromChunks */
32 protected $mUpload = null;
34 protected $mParams;
36 public function execute() {
37 // Check whether upload is enabled
38 if ( !UploadBase::isEnabled() ) {
39 $this->dieWithError( 'uploaddisabled' );
42 $user = $this->getUser();
44 // Parameter handling
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
60 try {
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
91 } else {
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:
107 try {
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
127 * @return array
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
156 * @return array
158 private function getStashResult( $warnings ) {
159 $result = [];
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 );
168 return $result;
172 * Get Warnings Result
173 * @param array $warnings Array of Api upload warnings
174 * @return array
176 private function getWarningsResult( $warnings ) {
177 $result = [];
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 );
184 return $result;
188 * Get the result of a chunk upload.
189 * @param array $warnings Array of Api upload warnings
190 * @return array
192 private function getChunkResult( $warnings ) {
193 $result = [];
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' );
217 } else {
218 $filekey = $this->mParams['filekey'];
220 // Don't allow further uploads to an already-completed session
221 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
222 if ( !$progress ) {
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() ) {
232 $extradata = [
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(
244 $this->getUser(),
245 $filekey,
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()
256 ) );
257 $result['result'] = 'Poll';
258 $result['stage'] = 'queued';
259 } else {
260 $status = $this->mUpload->concatenateChunks();
261 if ( !$status->isGood() ) {
262 UploadBase::setSessionStatus(
263 $this->getUser(),
264 $filekey,
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();
272 if ( $warnings ) {
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';
284 } else {
285 UploadBase::setSessionStatus(
286 $this->getUser(),
287 $filekey,
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;
301 return $result;
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'];
318 try {
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' ) ]
330 ) );
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" );
349 // Bad status
350 if ( $failureMode !== 'optional' ) {
351 $this->dieStatus( $status );
352 } else {
353 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
354 return null;
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 );
370 if ( $parameter ) {
371 $data['invalidparameter'] = $parameter;
374 $sv = StatusValue::newGood();
375 foreach ( $errors as $error ) {
376 $msg = ApiMessage::create( $error );
377 $msg->setApiData( $msg->getApiData() + $data );
378 $sv->fatal( $msg );
380 $this->dieStatus( $sv );
384 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
385 * IApiMessage.
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 );
399 $sv->fatal( $msg );
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;
407 * otherwise true
409 * @return bool
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'] );
423 if ( !$progress ) {
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'] );
433 if ( $warnings ) {
434 $progress['warnings'] = $warnings;
437 unset( $progress['status'] ); // remove Status object
438 $imageinfo = null;
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).
447 if ( $imageinfo ) {
448 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
451 return false;
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'] ) {
460 // Chunk upload
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' );
467 // handle new chunk
468 $this->mUpload->continueChunks(
469 $this->mParams['filename'],
470 $this->mParams['filekey'],
471 $request->getUpload( 'chunk' )
473 } else {
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'] );
521 return true;
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 ) );
541 // Check blocks
542 if ( $user->isBlocked() ) {
543 $this->dieBlocked( $user->getBlock() );
546 // Global blocks
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 ) {
558 return;
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' );
573 break;
574 case UploadBase::ILLEGAL_FILENAME:
575 $this->dieRecoverableError(
576 [ ApiMessage::create(
577 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
578 ) ], 'filename'
580 break;
581 case UploadBase::FILENAME_TOO_LONG:
582 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
583 break;
584 case UploadBase::FILETYPE_MISSING:
585 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
586 break;
587 case UploadBase::WINDOWS_NONASCII_FILENAME:
588 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
589 break;
591 // Unrecoverable errors
592 case UploadBase::EMPTY_FILE:
593 $this->dieWithError( 'empty-file' );
594 break;
595 case UploadBase::FILE_TOO_LARGE:
596 $this->dieWithError( 'file-too-large' );
597 break;
599 case UploadBase::FILETYPE_BADTYPE:
600 $extradata = [
601 'filetype' => $verification['finalExt'],
602 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
604 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
605 $msg = [
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' );
619 } else {
620 $msg[1] = $verification['finalExt'];
621 $msg[4] = 1;
624 $this->dieWithError( $msg, 'filetype-banned', $extradata );
625 break;
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() );
631 } else {
632 $details = $verification['details'];
634 ApiResult::setIndexedTagName( $details, 'detail' );
635 $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
636 $this->dieWithError( $msg );
637 break;
639 case UploadBase::HOOK_ABORTED:
640 $msg = $verification['error'] === '' ? 'hookaborted' : $verification['error'];
641 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
642 break;
643 default:
644 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
645 [ 'details' => [ 'code' => $verification['status'] ] ] );
646 break;
651 * Check warnings.
652 * Returns a suitable array for inclusion into API results if there were warnings
653 * Returns the empty array if there were no warnings
655 * @return array
657 protected function getApiWarnings() {
658 $warnings = $this->mUpload->checkWarnings();
660 return $this->transformWarnings( $warnings );
663 protected function transformWarnings( $warnings ) {
664 if ( $warnings ) {
665 // Add indices
666 ApiResult::setIndexedTagName( $warnings, 'warning' );
668 if ( isset( $warnings['duplicate'] ) ) {
669 $dupes = [];
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']
684 : $warning['file'];
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'] ) ) {
699 $dupes = [];
700 /** @var File $dupe */
701 foreach ( $warnings['duplicate-version'] as $dupe ) {
702 $dupes[] = [
703 'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
706 unset( $warnings['duplicate-version'] );
708 ApiResult::setIndexedTagName( $dupes, 'ver' );
709 $warnings['duplicateversions'] = $dupes;
713 return $warnings;
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';
726 break;
727 case 'UploadStashBadPathException':
728 $wrap = 'apierror-stashpathinvalid';
729 break;
730 case 'UploadStashFileException':
731 $wrap = 'apierror-stashfilestorage';
732 break;
733 case 'UploadStashZeroLengthFileException':
734 $wrap = 'apierror-stashzerolength';
735 break;
736 case 'UploadStashNotLoggedInException':
737 return StatusValue::newFatal( ApiMessage::create(
738 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
739 ) );
740 case 'UploadStashWrongOwnerException':
741 $wrap = 'apierror-stashwrongowner';
742 break;
743 case 'UploadStashNoSuchKeyException':
744 $wrap = 'apierror-stashnosuchfilekey';
745 break;
746 default:
747 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
748 break;
750 return StatusValue::newFatal(
751 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
756 * Perform the actual upload. Returns a suitable result array on success;
757 * dies on failure.
759 * @param array $warnings Array of Api upload warnings
760 * @return array
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() ) {
781 $watch = (
782 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
783 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
787 // Deprecated parameters
788 if ( $this->mParams['watch'] ) {
789 $watch = true;
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(
806 $this->getUser(),
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'],
818 'watch' => $watch,
819 'session' => $this->getContext()->exportSession()
821 ) );
822 $result['result'] = 'Poll';
823 $result['stage'] = 'queued';
824 } else {
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;
840 return $result;
843 public function mustBePosted() {
844 return true;
847 public function isWriteMode() {
848 return true;
851 public function getAllowedParams() {
852 $params = [
853 'filename' => [
854 ApiBase::PARAM_TYPE => 'string',
856 'comment' => [
857 ApiBase::PARAM_DFLT => ''
859 'tags' => [
860 ApiBase::PARAM_TYPE => 'tags',
861 ApiBase::PARAM_ISMULTI => true,
863 'text' => [
864 ApiBase::PARAM_TYPE => 'text',
866 'watch' => [
867 ApiBase::PARAM_DFLT => false,
868 ApiBase::PARAM_DEPRECATED => true,
870 'watchlist' => [
871 ApiBase::PARAM_DFLT => 'preferences',
872 ApiBase::PARAM_TYPE => [
873 'watch',
874 'preferences',
875 'nochange'
878 'ignorewarnings' => false,
879 'file' => [
880 ApiBase::PARAM_TYPE => 'upload',
882 'url' => null,
883 'filekey' => null,
884 'sessionkey' => [
885 ApiBase::PARAM_DEPRECATED => true,
887 'stash' => false,
889 'filesize' => [
890 ApiBase::PARAM_TYPE => 'integer',
891 ApiBase::PARAM_MIN => 0,
892 ApiBase::PARAM_MAX => UploadBase::getMaxUploadSize(),
894 'offset' => [
895 ApiBase::PARAM_TYPE => 'integer',
896 ApiBase::PARAM_MIN => 0,
898 'chunk' => [
899 ApiBase::PARAM_TYPE => 'upload',
902 'async' => false,
903 'checkstatus' => false,
906 return $params;
909 public function needsToken() {
910 return 'csrf';
913 protected function getExamplesMessages() {
914 return [
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';