Merge "Import: Handle uploads with sha1 starting with 0 properly"
[mediawiki.git] / includes / api / ApiUpload.php
blobe76b3651ebf0988c7d857e3d6bf535132dd6b700
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->dieUsageMsg( '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->dieUsage( 'No upload module set', 'nomodule' );
66 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
67 $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 $errors = $status->getErrorsArray();
78 $error = array_shift( $errors[0] );
79 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
82 // Check if the uploaded file is sane
83 if ( $this->mParams['chunk'] ) {
84 $maxSize = UploadBase::getMaxUploadSize();
85 if ( $this->mParams['filesize'] > $maxSize ) {
86 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
88 if ( !$this->mUpload->getTitle() ) {
89 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
91 } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
92 // defer verification to background process
93 } else {
94 wfDebug( __METHOD__ . " about to verify\n" );
95 $this->verifyUpload();
98 // Check if the user has the rights to modify or overwrite the requested title
99 // (This check is irrelevant if stashing is already requested, since the errors
100 // can always be fixed by changing the title)
101 if ( !$this->mParams['stash'] ) {
102 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
103 if ( $permErrors !== true ) {
104 $this->dieRecoverableError( $permErrors[0], 'filename' );
108 // Get the result based on the current upload context:
109 try {
110 $result = $this->getContextResult();
111 if ( $result['result'] === 'Success' ) {
112 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
114 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
115 $this->handleStashException( $e );
118 $this->getResult()->addValue( null, $this->getModuleName(), $result );
120 // Cleanup any temporary mess
121 $this->mUpload->cleanupTempFile();
125 * Get an upload result based on upload context
126 * @return array
128 private function getContextResult() {
129 $warnings = $this->getApiWarnings();
130 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
131 // Get warnings formatted in result array format
132 return $this->getWarningsResult( $warnings );
133 } elseif ( $this->mParams['chunk'] ) {
134 // Add chunk, and get result
135 return $this->getChunkResult( $warnings );
136 } elseif ( $this->mParams['stash'] ) {
137 // Stash the file and get stash result
138 return $this->getStashResult( $warnings );
141 // Check throttle after we've handled warnings
142 if ( UploadBase::isThrottled( $this->getUser() )
144 $this->dieUsageMsg( 'actionthrottledtext' );
147 // This is the most common case -- a normal upload with no warnings
148 // performUpload will return a formatted properly for the API with status
149 return $this->performUpload( $warnings );
153 * Get Stash Result, throws an exception if the file could not be stashed.
154 * @param array $warnings Array of Api upload warnings
155 * @return array
157 private function getStashResult( $warnings ) {
158 $result = array();
159 // Some uploads can request they be stashed, so as not to publish them immediately.
160 // In this case, a failure to stash ought to be fatal
161 try {
162 $result['result'] = 'Success';
163 $result['filekey'] = $this->performStash();
164 $result['sessionkey'] = $result['filekey']; // backwards compatibility
165 if ( $warnings && count( $warnings ) > 0 ) {
166 $result['warnings'] = $warnings;
168 } catch ( UploadStashException $e ) {
169 $this->handleStashException( $e );
170 } catch ( Exception $e ) {
171 $this->dieUsage( $e->getMessage(), 'stashfailed' );
174 return $result;
178 * Get Warnings Result
179 * @param array $warnings Array of Api upload warnings
180 * @return array
182 private function getWarningsResult( $warnings ) {
183 $result = array();
184 $result['result'] = 'Warning';
185 $result['warnings'] = $warnings;
186 // in case the warnings can be fixed with some further user action, let's stash this upload
187 // and return a key they can use to restart it
188 try {
189 $result['filekey'] = $this->performStash();
190 $result['sessionkey'] = $result['filekey']; // backwards compatibility
191 } catch ( Exception $e ) {
192 $result['warnings']['stashfailed'] = $e->getMessage();
195 return $result;
199 * Get the result of a chunk upload.
200 * @param array $warnings Array of Api upload warnings
201 * @return array
203 private function getChunkResult( $warnings ) {
204 $result = array();
206 if ( $warnings && count( $warnings ) > 0 ) {
207 $result['warnings'] = $warnings;
210 $request = $this->getMain()->getRequest();
211 $chunkPath = $request->getFileTempname( 'chunk' );
212 $chunkSize = $request->getUpload( 'chunk' )->getSize();
213 $totalSoFar = $this->mParams['offset'] + $chunkSize;
214 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
216 // Sanity check sizing
217 if ( $totalSoFar > $this->mParams['filesize'] ) {
218 $this->dieUsage(
219 'Offset plus current chunk is greater than claimed file size', 'invalid-chunk'
223 // Enforce minimum chunk size
224 if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
225 $this->dieUsage(
226 "Minimum chunk size is $minChunkSize bytes for non-final chunks", 'chunk-too-small'
230 if ( $this->mParams['offset'] == 0 ) {
231 try {
232 $filekey = $this->performStash();
233 } catch ( UploadStashException $e ) {
234 $this->handleStashException( $e );
235 } catch ( Exception $e ) {
236 // FIXME: Error handling here is wrong/different from rest of this
237 $this->dieUsage( $e->getMessage(), 'stashfailed' );
239 } else {
240 $filekey = $this->mParams['filekey'];
242 // Don't allow further uploads to an already-completed session
243 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
244 if ( !$progress ) {
245 // Probably can't get here, but check anyway just in case
246 $this->dieUsage( 'No chunked upload session with this key', 'stashfailed' );
247 } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
248 $this->dieUsage(
249 'Chunked upload is already completed, check status for details', 'stashfailed'
253 $status = $this->mUpload->addChunk(
254 $chunkPath, $chunkSize, $this->mParams['offset'] );
255 if ( !$status->isGood() ) {
256 $extradata = array(
257 'offset' => $this->mUpload->getOffset(),
260 $this->dieUsage( $status->getWikiText(), 'stashfailed', 0, $extradata );
264 // Check we added the last chunk:
265 if ( $totalSoFar == $this->mParams['filesize'] ) {
266 if ( $this->mParams['async'] ) {
267 UploadBase::setSessionStatus(
268 $this->getUser(),
269 $filekey,
270 array( 'result' => 'Poll',
271 'stage' => 'queued', 'status' => Status::newGood() )
273 JobQueueGroup::singleton()->push( new AssembleUploadChunksJob(
274 Title::makeTitle( NS_FILE, $filekey ),
275 array(
276 'filename' => $this->mParams['filename'],
277 'filekey' => $filekey,
278 'session' => $this->getContext()->exportSession()
280 ) );
281 $result['result'] = 'Poll';
282 $result['stage'] = 'queued';
283 } else {
284 $status = $this->mUpload->concatenateChunks();
285 if ( !$status->isGood() ) {
286 UploadBase::setSessionStatus(
287 $this->getUser(),
288 $filekey,
289 array( 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status )
291 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
294 // The fully concatenated file has a new filekey. So remove
295 // the old filekey and fetch the new one.
296 UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
297 $this->mUpload->stash->removeFile( $filekey );
298 $filekey = $this->mUpload->getLocalFile()->getFileKey();
300 $result['result'] = 'Success';
302 } else {
303 UploadBase::setSessionStatus(
304 $this->getUser(),
305 $filekey,
306 array(
307 'result' => 'Continue',
308 'stage' => 'uploading',
309 'offset' => $totalSoFar,
310 'status' => Status::newGood(),
313 $result['result'] = 'Continue';
314 $result['offset'] = $totalSoFar;
317 $result['filekey'] = $filekey;
319 return $result;
323 * Stash the file and return the file key
324 * Also re-raises exceptions with slightly more informative message strings (useful for API)
325 * @throws MWException
326 * @return string File key
328 private function performStash() {
329 try {
330 $stashFile = $this->mUpload->stashFile( $this->getUser() );
332 if ( !$stashFile ) {
333 throw new MWException( 'Invalid stashed file' );
335 $fileKey = $stashFile->getFileKey();
336 } catch ( Exception $e ) {
337 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
338 wfDebug( __METHOD__ . ' ' . $message . "\n" );
339 $className = get_class( $e );
340 throw new $className( $message );
343 return $fileKey;
347 * Throw an error that the user can recover from by providing a better
348 * value for $parameter
350 * @param array $error Error array suitable for passing to dieUsageMsg()
351 * @param string $parameter Parameter that needs revising
352 * @param array $data Optional extra data to pass to the user
353 * @throws UsageException
355 private function dieRecoverableError( $error, $parameter, $data = array() ) {
356 try {
357 $data['filekey'] = $this->performStash();
358 $data['sessionkey'] = $data['filekey'];
359 } catch ( Exception $e ) {
360 $data['stashfailed'] = $e->getMessage();
362 $data['invalidparameter'] = $parameter;
364 $parsed = $this->parseMsg( $error );
365 if ( isset( $parsed['data'] ) ) {
366 $data = array_merge( $data, $parsed['data'] );
369 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
373 * Select an upload module and set it to mUpload. Dies on failure. If the
374 * request was a status request and not a true upload, returns false;
375 * otherwise true
377 * @return bool
379 protected function selectUploadModule() {
380 $request = $this->getMain()->getRequest();
382 // chunk or one and only one of the following parameters is needed
383 if ( !$this->mParams['chunk'] ) {
384 $this->requireOnlyOneParameter( $this->mParams,
385 'filekey', 'file', 'url', 'statuskey' );
388 // Status report for "upload to stash"/"upload from stash"
389 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
390 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
391 if ( !$progress ) {
392 $this->dieUsage( 'No result in status data', 'missingresult' );
393 } elseif ( !$progress['status']->isGood() ) {
394 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
396 if ( isset( $progress['status']->value['verification'] ) ) {
397 $this->checkVerification( $progress['status']->value['verification'] );
399 unset( $progress['status'] ); // remove Status object
400 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
402 return false;
405 if ( $this->mParams['statuskey'] ) {
406 $this->checkAsyncDownloadEnabled();
408 // Status request for an async upload
409 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
410 if ( !isset( $sessionData['result'] ) ) {
411 $this->dieUsage( 'No result in session data', 'missingresult' );
413 if ( $sessionData['result'] == 'Warning' ) {
414 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
415 $sessionData['sessionkey'] = $this->mParams['statuskey'];
417 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
419 return false;
422 // The following modules all require the filename parameter to be set
423 if ( is_null( $this->mParams['filename'] ) ) {
424 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
427 if ( $this->mParams['chunk'] ) {
428 // Chunk upload
429 $this->mUpload = new UploadFromChunks();
430 if ( isset( $this->mParams['filekey'] ) ) {
431 if ( $this->mParams['offset'] === 0 ) {
432 $this->dieUsage( 'Cannot supply a filekey when offset is 0', 'badparams' );
435 // handle new chunk
436 $this->mUpload->continueChunks(
437 $this->mParams['filename'],
438 $this->mParams['filekey'],
439 $request->getUpload( 'chunk' )
441 } else {
442 if ( $this->mParams['offset'] !== 0 ) {
443 $this->dieUsage( 'Must supply a filekey when offset is non-zero', 'badparams' );
446 // handle first chunk
447 $this->mUpload->initialize(
448 $this->mParams['filename'],
449 $request->getUpload( 'chunk' )
452 } elseif ( isset( $this->mParams['filekey'] ) ) {
453 // Upload stashed in a previous request
454 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
455 $this->dieUsageMsg( 'invalid-file-key' );
458 $this->mUpload = new UploadFromStash( $this->getUser() );
459 // This will not download the temp file in initialize() in async mode.
460 // We still have enough information to call checkWarnings() and such.
461 $this->mUpload->initialize(
462 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
464 } elseif ( isset( $this->mParams['file'] ) ) {
465 $this->mUpload = new UploadFromFile();
466 $this->mUpload->initialize(
467 $this->mParams['filename'],
468 $request->getUpload( 'file' )
470 } elseif ( isset( $this->mParams['url'] ) ) {
471 // Make sure upload by URL is enabled:
472 if ( !UploadFromUrl::isEnabled() ) {
473 $this->dieUsageMsg( 'copyuploaddisabled' );
476 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
477 $this->dieUsageMsg( 'copyuploadbaddomain' );
480 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
481 $this->dieUsageMsg( 'copyuploadbadurl' );
484 $async = false;
485 if ( $this->mParams['asyncdownload'] ) {
486 $this->checkAsyncDownloadEnabled();
488 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
489 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
490 'missing-ignorewarnings' );
493 if ( $this->mParams['leavemessage'] ) {
494 $async = 'async-leavemessage';
495 } else {
496 $async = 'async';
499 $this->mUpload = new UploadFromUrl;
500 $this->mUpload->initialize( $this->mParams['filename'],
501 $this->mParams['url'], $async );
504 return true;
508 * Checks that the user has permissions to perform this upload.
509 * Dies with usage message on inadequate permissions.
510 * @param User $user The user to check.
512 protected function checkPermissions( $user ) {
513 // Check whether the user has the appropriate permissions to upload anyway
514 $permission = $this->mUpload->isAllowed( $user );
516 if ( $permission !== true ) {
517 if ( !$user->isLoggedIn() ) {
518 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
521 $this->dieUsageMsg( 'badaccess-groups' );
526 * Performs file verification, dies on error.
528 protected function verifyUpload() {
529 $verification = $this->mUpload->verifyUpload();
530 if ( $verification['status'] === UploadBase::OK ) {
531 return;
534 $this->checkVerification( $verification );
538 * Performs file verification, dies on error.
539 * @param array $verification
541 protected function checkVerification( array $verification ) {
542 // @todo Move them to ApiBase's message map
543 switch ( $verification['status'] ) {
544 // Recoverable errors
545 case UploadBase::MIN_LENGTH_PARTNAME:
546 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
547 break;
548 case UploadBase::ILLEGAL_FILENAME:
549 $this->dieRecoverableError( 'illegal-filename', 'filename',
550 array( 'filename' => $verification['filtered'] ) );
551 break;
552 case UploadBase::FILENAME_TOO_LONG:
553 $this->dieRecoverableError( 'filename-toolong', 'filename' );
554 break;
555 case UploadBase::FILETYPE_MISSING:
556 $this->dieRecoverableError( 'filetype-missing', 'filename' );
557 break;
558 case UploadBase::WINDOWS_NONASCII_FILENAME:
559 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
560 break;
562 // Unrecoverable errors
563 case UploadBase::EMPTY_FILE:
564 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
565 break;
566 case UploadBase::FILE_TOO_LARGE:
567 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
568 break;
570 case UploadBase::FILETYPE_BADTYPE:
571 $extradata = array(
572 'filetype' => $verification['finalExt'],
573 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
575 ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
577 $msg = "Filetype not permitted: ";
578 if ( isset( $verification['blacklistedExt'] ) ) {
579 $msg .= join( ', ', $verification['blacklistedExt'] );
580 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
581 ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
582 } else {
583 $msg .= $verification['finalExt'];
585 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
586 break;
587 case UploadBase::VERIFICATION_ERROR:
588 $params = $verification['details'];
589 $key = array_shift( $params );
590 $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
591 ApiResult::setIndexedTagName( $verification['details'], 'detail' );
592 $this->dieUsage( "This file did not pass file verification: $msg", 'verification-error',
593 0, array( 'details' => $verification['details'] ) );
594 break;
595 case UploadBase::HOOK_ABORTED:
596 if ( is_array( $verification['error'] ) ) {
597 $params = $verification['error'];
598 } elseif ( $verification['error'] !== '' ) {
599 $params = array( $verification['error'] );
600 } else {
601 $params = array( 'hookaborted' );
603 $key = array_shift( $params );
604 $msg = $this->msg( $key, $params )->inLanguage( 'en' )->useDatabase( false )->text();
605 $this->dieUsage( $msg, 'hookaborted', 0, array( 'details' => $verification['error'] ) );
606 break;
607 default:
608 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
609 0, array( 'details' => array( 'code' => $verification['status'] ) ) );
610 break;
615 * Check warnings.
616 * Returns a suitable array for inclusion into API results if there were warnings
617 * Returns the empty array if there were no warnings
619 * @return array
621 protected function getApiWarnings() {
622 $warnings = $this->mUpload->checkWarnings();
624 return $this->transformWarnings( $warnings );
627 protected function transformWarnings( $warnings ) {
628 if ( $warnings ) {
629 // Add indices
630 ApiResult::setIndexedTagName( $warnings, 'warning' );
632 if ( isset( $warnings['duplicate'] ) ) {
633 $dupes = array();
634 /** @var File $dupe */
635 foreach ( $warnings['duplicate'] as $dupe ) {
636 $dupes[] = $dupe->getName();
638 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
639 $warnings['duplicate'] = $dupes;
642 if ( isset( $warnings['exists'] ) ) {
643 $warning = $warnings['exists'];
644 unset( $warnings['exists'] );
645 /** @var LocalFile $localFile */
646 $localFile = isset( $warning['normalizedFile'] )
647 ? $warning['normalizedFile']
648 : $warning['file'];
649 $warnings[$warning['warning']] = $localFile->getName();
653 return $warnings;
657 * Handles a stash exception, giving a useful error to the user.
658 * @param Exception $e The exception we encountered.
660 protected function handleStashException( $e ) {
661 $exceptionType = get_class( $e );
663 switch ( $exceptionType ) {
664 case 'UploadStashFileNotFoundException':
665 $this->dieUsage(
666 'Could not find the file in the stash: ' . $e->getMessage(),
667 'stashedfilenotfound'
669 break;
670 case 'UploadStashBadPathException':
671 $this->dieUsage(
672 'File key of improper format or otherwise invalid: ' . $e->getMessage(),
673 'stashpathinvalid'
675 break;
676 case 'UploadStashFileException':
677 $this->dieUsage(
678 'Could not store upload in the stash: ' . $e->getMessage(),
679 'stashfilestorage'
681 break;
682 case 'UploadStashZeroLengthFileException':
683 $this->dieUsage(
684 'File is of zero length, and could not be stored in the stash: ' .
685 $e->getMessage(),
686 'stashzerolength'
688 break;
689 case 'UploadStashNotLoggedInException':
690 $this->dieUsage( 'Not logged in: ' . $e->getMessage(), 'stashnotloggedin' );
691 break;
692 case 'UploadStashWrongOwnerException':
693 $this->dieUsage( 'Wrong owner: ' . $e->getMessage(), 'stashwrongowner' );
694 break;
695 case 'UploadStashNoSuchKeyException':
696 $this->dieUsage( 'No such filekey: ' . $e->getMessage(), 'stashnosuchfilekey' );
697 break;
698 default:
699 $this->dieUsage( $exceptionType . ": " . $e->getMessage(), 'stasherror' );
700 break;
705 * Perform the actual upload. Returns a suitable result array on success;
706 * dies on failure.
708 * @param array $warnings Array of Api upload warnings
709 * @return array
711 protected function performUpload( $warnings ) {
712 // Use comment as initial page text by default
713 if ( is_null( $this->mParams['text'] ) ) {
714 $this->mParams['text'] = $this->mParams['comment'];
717 /** @var $file File */
718 $file = $this->mUpload->getLocalFile();
720 // For preferences mode, we want to watch if 'watchdefault' is set or
721 // if the *file* doesn't exist and 'watchcreations' is set. But
722 // getWatchlistValue()'s automatic handling checks if the *title*
723 // exists or not, so we need to check both prefs manually.
724 $watch = $this->getWatchlistValue(
725 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
727 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
728 $watch = $this->getWatchlistValue(
729 $this->mParams['watchlist'], $file->getTitle(), 'watchcreations'
733 // Deprecated parameters
734 if ( $this->mParams['watch'] ) {
735 $watch = true;
738 // No errors, no warnings: do the upload
739 if ( $this->mParams['async'] ) {
740 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
741 if ( $progress && $progress['result'] === 'Poll' ) {
742 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
744 UploadBase::setSessionStatus(
745 $this->getUser(),
746 $this->mParams['filekey'],
747 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
749 JobQueueGroup::singleton()->push( new PublishStashedFileJob(
750 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
751 array(
752 'filename' => $this->mParams['filename'],
753 'filekey' => $this->mParams['filekey'],
754 'comment' => $this->mParams['comment'],
755 'text' => $this->mParams['text'],
756 'watch' => $watch,
757 'session' => $this->getContext()->exportSession()
759 ) );
760 $result['result'] = 'Poll';
761 $result['stage'] = 'queued';
762 } else {
763 /** @var $status Status */
764 $status = $this->mUpload->performUpload( $this->mParams['comment'],
765 $this->mParams['text'], $watch, $this->getUser() );
767 if ( !$status->isGood() ) {
768 $error = $status->getErrorsArray();
770 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
771 // The upload can not be performed right now, because the user
772 // requested so
773 return array(
774 'result' => 'Queued',
775 'statuskey' => $error[0][1],
779 ApiResult::setIndexedTagName( $error, 'error' );
780 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
782 $result['result'] = 'Success';
785 $result['filename'] = $file->getName();
786 if ( $warnings && count( $warnings ) > 0 ) {
787 $result['warnings'] = $warnings;
790 return $result;
794 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
796 protected function checkAsyncDownloadEnabled() {
797 if ( !$this->getConfig()->get( 'AllowAsyncCopyUploads' ) ) {
798 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
802 public function mustBePosted() {
803 return true;
806 public function isWriteMode() {
807 return true;
810 public function getAllowedParams() {
811 $params = array(
812 'filename' => array(
813 ApiBase::PARAM_TYPE => 'string',
815 'comment' => array(
816 ApiBase::PARAM_DFLT => ''
818 'text' => array(
819 ApiBase::PARAM_TYPE => 'text',
821 'watch' => array(
822 ApiBase::PARAM_DFLT => false,
823 ApiBase::PARAM_DEPRECATED => true,
825 'watchlist' => array(
826 ApiBase::PARAM_DFLT => 'preferences',
827 ApiBase::PARAM_TYPE => array(
828 'watch',
829 'preferences',
830 'nochange'
833 'ignorewarnings' => false,
834 'file' => array(
835 ApiBase::PARAM_TYPE => 'upload',
837 'url' => null,
838 'filekey' => null,
839 'sessionkey' => array(
840 ApiBase::PARAM_DEPRECATED => true,
842 'stash' => false,
844 'filesize' => array(
845 ApiBase::PARAM_TYPE => 'integer',
846 ApiBase::PARAM_MIN => 0,
847 ApiBase::PARAM_MAX => UploadBase::getMaxUploadSize(),
849 'offset' => array(
850 ApiBase::PARAM_TYPE => 'integer',
851 ApiBase::PARAM_MIN => 0,
853 'chunk' => array(
854 ApiBase::PARAM_TYPE => 'upload',
857 'async' => false,
858 'asyncdownload' => false,
859 'leavemessage' => false,
860 'statuskey' => null,
861 'checkstatus' => false,
864 return $params;
867 public function needsToken() {
868 return 'csrf';
871 protected function getExamplesMessages() {
872 return array(
873 'action=upload&filename=Wiki.png' .
874 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
875 => 'apihelp-upload-example-url',
876 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
877 => 'apihelp-upload-example-filekey',
881 public function getHelpUrls() {
882 return 'https://www.mediawiki.org/wiki/API:Upload';