Don't bother showing prev/next links navigation when there's few results
[mediawiki.git] / includes / api / ApiUpload.php
blob3ef2bbe46eece9e292f48133c3cd8368c6d666f3
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 */
32 protected $mUpload = null;
34 protected $mParams;
36 public function execute() {
37 global $wgEnableAsyncUploads;
39 // Check whether upload is enabled
40 if ( !UploadBase::isEnabled() ) {
41 $this->dieUsageMsg( 'uploaddisabled' );
44 $user = $this->getUser();
46 // Parameter handling
47 $this->mParams = $this->extractRequestParams();
48 $request = $this->getMain()->getRequest();
49 // Check if async mode is actually supported (jobs done in cli mode)
50 $this->mParams['async'] = ( $this->mParams['async'] && $wgEnableAsyncUploads );
51 // Add the uploaded file to the params array
52 $this->mParams['file'] = $request->getFileName( 'file' );
53 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
55 // Copy the session key to the file key, for backward compatibility.
56 if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
57 $this->mParams['filekey'] = $this->mParams['sessionkey'];
60 // Select an upload module
61 try {
62 if ( !$this->selectUploadModule() ) {
63 return; // not a true upload, but a status request or similar
64 } elseif ( !isset( $this->mUpload ) ) {
65 $this->dieUsage( 'No upload module set', 'nomodule' );
67 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
68 $this->dieUsage( get_class( $e ) . ": " . $e->getMessage(), 'stasherror' );
71 // First check permission to upload
72 $this->checkPermissions( $user );
74 // Fetch the file (usually a no-op)
75 /** @var $status Status */
76 $status = $this->mUpload->fetchFile();
77 if ( !$status->isGood() ) {
78 $errors = $status->getErrorsArray();
79 $error = array_shift( $errors[0] );
80 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
83 // Check if the uploaded file is sane
84 if ( $this->mParams['chunk'] ) {
85 $maxSize = $this->mUpload->getMaxUploadSize();
86 if ( $this->mParams['filesize'] > $maxSize ) {
87 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
89 if ( !$this->mUpload->getTitle() ) {
90 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
92 } elseif ( $this->mParams['async'] && $this->mParams['filekey'] ) {
93 // defer verification to background process
94 } else {
95 wfDebug( __METHOD__ . " about to verify\n" );
96 $this->verifyUpload();
99 // Check if the user has the rights to modify or overwrite the requested title
100 // (This check is irrelevant if stashing is already requested, since the errors
101 // can always be fixed by changing the title)
102 if ( !$this->mParams['stash'] ) {
103 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
104 if ( $permErrors !== true ) {
105 $this->dieRecoverableError( $permErrors[0], 'filename' );
109 // Get the result based on the current upload context:
110 try {
111 $result = $this->getContextResult();
112 if ( $result['result'] === 'Success' ) {
113 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
115 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
116 $this->dieUsage( get_class( $e ) . ": " . $e->getMessage(), 'stasherror' );
119 $this->getResult()->addValue( null, $this->getModuleName(), $result );
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 // This is the most common case -- a normal upload with no warnings
143 // performUpload will return a formatted properly for the API with status
144 return $this->performUpload( $warnings );
148 * Get Stash Result, throws an exception if the file could not be stashed.
149 * @param array $warnings Array of Api upload warnings
150 * @return array
152 private function getStashResult( $warnings ) {
153 $result = array();
154 // Some uploads can request they be stashed, so as not to publish them immediately.
155 // In this case, a failure to stash ought to be fatal
156 try {
157 $result['result'] = 'Success';
158 $result['filekey'] = $this->performStash();
159 $result['sessionkey'] = $result['filekey']; // backwards compatibility
160 if ( $warnings && count( $warnings ) > 0 ) {
161 $result['warnings'] = $warnings;
163 } catch ( MWException $e ) {
164 $this->dieUsage( $e->getMessage(), 'stashfailed' );
167 return $result;
171 * Get Warnings Result
172 * @param array $warnings Array of Api upload warnings
173 * @return array
175 private function getWarningsResult( $warnings ) {
176 $result = array();
177 $result['result'] = 'Warning';
178 $result['warnings'] = $warnings;
179 // in case the warnings can be fixed with some further user action, let's stash this upload
180 // and return a key they can use to restart it
181 try {
182 $result['filekey'] = $this->performStash();
183 $result['sessionkey'] = $result['filekey']; // backwards compatibility
184 } catch ( MWException $e ) {
185 $result['warnings']['stashfailed'] = $e->getMessage();
188 return $result;
192 * Get the result of a chunk upload.
193 * @param array $warnings Array of Api upload warnings
194 * @return array
196 private function getChunkResult( $warnings ) {
197 $result = array();
199 $result['result'] = 'Continue';
200 if ( $warnings && count( $warnings ) > 0 ) {
201 $result['warnings'] = $warnings;
203 $request = $this->getMain()->getRequest();
204 $chunkPath = $request->getFileTempname( 'chunk' );
205 $chunkSize = $request->getUpload( 'chunk' )->getSize();
206 if ( $this->mParams['offset'] == 0 ) {
207 try {
208 $filekey = $this->performStash();
209 } catch ( MWException $e ) {
210 // FIXME: Error handling here is wrong/different from rest of this
211 $this->dieUsage( $e->getMessage(), 'stashfailed' );
213 } else {
214 $filekey = $this->mParams['filekey'];
215 /** @var $status Status */
216 $status = $this->mUpload->addChunk(
217 $chunkPath, $chunkSize, $this->mParams['offset'] );
218 if ( !$status->isGood() ) {
219 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
221 return array();
225 // Check we added the last chunk:
226 if ( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
227 if ( $this->mParams['async'] ) {
228 $progress = UploadBase::getSessionStatus( $filekey );
229 if ( $progress && $progress['result'] === 'Poll' ) {
230 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
232 UploadBase::setSessionStatus(
233 $filekey,
234 array( 'result' => 'Poll',
235 'stage' => 'queued', 'status' => Status::newGood() )
237 $ok = JobQueueGroup::singleton()->push( new AssembleUploadChunksJob(
238 Title::makeTitle( NS_FILE, $filekey ),
239 array(
240 'filename' => $this->mParams['filename'],
241 'filekey' => $filekey,
242 'session' => $this->getContext()->exportSession()
244 ) );
245 if ( $ok ) {
246 $result['result'] = 'Poll';
247 } else {
248 UploadBase::setSessionStatus( $filekey, false );
249 $this->dieUsage(
250 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
252 } else {
253 $status = $this->mUpload->concatenateChunks();
254 if ( !$status->isGood() ) {
255 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
257 return array();
260 // The fully concatenated file has a new filekey. So remove
261 // the old filekey and fetch the new one.
262 $this->mUpload->stash->removeFile( $filekey );
263 $filekey = $this->mUpload->getLocalFile()->getFileKey();
265 $result['result'] = 'Success';
268 $result['filekey'] = $filekey;
269 $result['offset'] = $this->mParams['offset'] + $chunkSize;
271 return $result;
275 * Stash the file and return the file key
276 * Also re-raises exceptions with slightly more informative message strings (useful for API)
277 * @throws MWException
278 * @return string File key
280 private function performStash() {
281 try {
282 $stashFile = $this->mUpload->stashFile();
284 if ( !$stashFile ) {
285 throw new MWException( 'Invalid stashed file' );
287 $fileKey = $stashFile->getFileKey();
288 } catch ( MWException $e ) {
289 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
290 wfDebug( __METHOD__ . ' ' . $message . "\n" );
291 throw new MWException( $message );
294 return $fileKey;
298 * Throw an error that the user can recover from by providing a better
299 * value for $parameter
301 * @param array $error Error array suitable for passing to dieUsageMsg()
302 * @param string $parameter Parameter that needs revising
303 * @param array $data Optional extra data to pass to the user
304 * @throws UsageException
306 private function dieRecoverableError( $error, $parameter, $data = array() ) {
307 try {
308 $data['filekey'] = $this->performStash();
309 $data['sessionkey'] = $data['filekey'];
310 } catch ( MWException $e ) {
311 $data['stashfailed'] = $e->getMessage();
313 $data['invalidparameter'] = $parameter;
315 $parsed = $this->parseMsg( $error );
316 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
320 * Select an upload module and set it to mUpload. Dies on failure. If the
321 * request was a status request and not a true upload, returns false;
322 * otherwise true
324 * @return bool
326 protected function selectUploadModule() {
327 $request = $this->getMain()->getRequest();
329 // chunk or one and only one of the following parameters is needed
330 if ( !$this->mParams['chunk'] ) {
331 $this->requireOnlyOneParameter( $this->mParams,
332 'filekey', 'file', 'url', 'statuskey' );
335 // Status report for "upload to stash"/"upload from stash"
336 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
337 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
338 if ( !$progress ) {
339 $this->dieUsage( 'No result in status data', 'missingresult' );
340 } elseif ( !$progress['status']->isGood() ) {
341 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
343 if ( isset( $progress['status']->value['verification'] ) ) {
344 $this->checkVerification( $progress['status']->value['verification'] );
346 unset( $progress['status'] ); // remove Status object
347 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
349 return false;
352 if ( $this->mParams['statuskey'] ) {
353 $this->checkAsyncDownloadEnabled();
355 // Status request for an async upload
356 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
357 if ( !isset( $sessionData['result'] ) ) {
358 $this->dieUsage( 'No result in session data', 'missingresult' );
360 if ( $sessionData['result'] == 'Warning' ) {
361 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
362 $sessionData['sessionkey'] = $this->mParams['statuskey'];
364 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
366 return false;
369 // The following modules all require the filename parameter to be set
370 if ( is_null( $this->mParams['filename'] ) ) {
371 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
374 if ( $this->mParams['chunk'] ) {
375 // Chunk upload
376 $this->mUpload = new UploadFromChunks();
377 if ( isset( $this->mParams['filekey'] ) ) {
378 // handle new chunk
379 $this->mUpload->continueChunks(
380 $this->mParams['filename'],
381 $this->mParams['filekey'],
382 $request->getUpload( 'chunk' )
384 } else {
385 // handle first chunk
386 $this->mUpload->initialize(
387 $this->mParams['filename'],
388 $request->getUpload( 'chunk' )
391 } elseif ( isset( $this->mParams['filekey'] ) ) {
392 // Upload stashed in a previous request
393 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
394 $this->dieUsageMsg( 'invalid-file-key' );
397 $this->mUpload = new UploadFromStash( $this->getUser() );
398 // This will not download the temp file in initialize() in async mode.
399 // We still have enough information to call checkWarnings() and such.
400 $this->mUpload->initialize(
401 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
403 } elseif ( isset( $this->mParams['file'] ) ) {
404 $this->mUpload = new UploadFromFile();
405 $this->mUpload->initialize(
406 $this->mParams['filename'],
407 $request->getUpload( 'file' )
409 } elseif ( isset( $this->mParams['url'] ) ) {
410 // Make sure upload by URL is enabled:
411 if ( !UploadFromUrl::isEnabled() ) {
412 $this->dieUsageMsg( 'copyuploaddisabled' );
415 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
416 $this->dieUsageMsg( 'copyuploadbaddomain' );
419 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
420 $this->dieUsageMsg( 'copyuploadbadurl' );
423 $async = false;
424 if ( $this->mParams['asyncdownload'] ) {
425 $this->checkAsyncDownloadEnabled();
427 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
428 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
429 'missing-ignorewarnings' );
432 if ( $this->mParams['leavemessage'] ) {
433 $async = 'async-leavemessage';
434 } else {
435 $async = 'async';
438 $this->mUpload = new UploadFromUrl;
439 $this->mUpload->initialize( $this->mParams['filename'],
440 $this->mParams['url'], $async );
443 return true;
447 * Checks that the user has permissions to perform this upload.
448 * Dies with usage message on inadequate permissions.
449 * @param User $user The user to check.
451 protected function checkPermissions( $user ) {
452 // Check whether the user has the appropriate permissions to upload anyway
453 $permission = $this->mUpload->isAllowed( $user );
455 if ( $permission !== true ) {
456 if ( !$user->isLoggedIn() ) {
457 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
460 $this->dieUsageMsg( 'badaccess-groups' );
465 * Performs file verification, dies on error.
467 protected function verifyUpload() {
468 $verification = $this->mUpload->verifyUpload();
469 if ( $verification['status'] === UploadBase::OK ) {
470 return;
473 $this->checkVerification( $verification );
477 * Performs file verification, dies on error.
479 protected function checkVerification( array $verification ) {
480 global $wgFileExtensions;
482 // @todo Move them to ApiBase's message map
483 switch ( $verification['status'] ) {
484 // Recoverable errors
485 case UploadBase::MIN_LENGTH_PARTNAME:
486 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
487 break;
488 case UploadBase::ILLEGAL_FILENAME:
489 $this->dieRecoverableError( 'illegal-filename', 'filename',
490 array( 'filename' => $verification['filtered'] ) );
491 break;
492 case UploadBase::FILENAME_TOO_LONG:
493 $this->dieRecoverableError( 'filename-toolong', 'filename' );
494 break;
495 case UploadBase::FILETYPE_MISSING:
496 $this->dieRecoverableError( 'filetype-missing', 'filename' );
497 break;
498 case UploadBase::WINDOWS_NONASCII_FILENAME:
499 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
500 break;
502 // Unrecoverable errors
503 case UploadBase::EMPTY_FILE:
504 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
505 break;
506 case UploadBase::FILE_TOO_LARGE:
507 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
508 break;
510 case UploadBase::FILETYPE_BADTYPE:
511 $extradata = array(
512 'filetype' => $verification['finalExt'],
513 'allowed' => array_values( array_unique( $wgFileExtensions ) )
515 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
517 $msg = "Filetype not permitted: ";
518 if ( isset( $verification['blacklistedExt'] ) ) {
519 $msg .= join( ', ', $verification['blacklistedExt'] );
520 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
521 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
522 } else {
523 $msg .= $verification['finalExt'];
525 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
526 break;
527 case UploadBase::VERIFICATION_ERROR:
528 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
529 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
530 0, array( 'details' => $verification['details'] ) );
531 break;
532 case UploadBase::HOOK_ABORTED:
533 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
534 'hookaborted', 0, array( 'error' => $verification['error'] ) );
535 break;
536 default:
537 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
538 0, array( 'code' => $verification['status'] ) );
539 break;
544 * Check warnings.
545 * Returns a suitable array for inclusion into API results if there were warnings
546 * Returns the empty array if there were no warnings
548 * @return array
550 protected function getApiWarnings() {
551 $warnings = $this->mUpload->checkWarnings();
553 return $this->transformWarnings( $warnings );
556 protected function transformWarnings( $warnings ) {
557 if ( $warnings ) {
558 // Add indices
559 $result = $this->getResult();
560 $result->setIndexedTagName( $warnings, 'warning' );
562 if ( isset( $warnings['duplicate'] ) ) {
563 $dupes = array();
564 foreach ( $warnings['duplicate'] as $dupe ) {
565 $dupes[] = $dupe->getName();
567 $result->setIndexedTagName( $dupes, 'duplicate' );
568 $warnings['duplicate'] = $dupes;
571 if ( isset( $warnings['exists'] ) ) {
572 $warning = $warnings['exists'];
573 unset( $warnings['exists'] );
574 $localFile = isset( $warning['normalizedFile'] )
575 ? $warning['normalizedFile']
576 : $warning['file'];
577 $warnings[$warning['warning']] = $localFile->getName();
581 return $warnings;
585 * Perform the actual upload. Returns a suitable result array on success;
586 * dies on failure.
588 * @param array $warnings Array of Api upload warnings
589 * @return array
591 protected function performUpload( $warnings ) {
592 // Use comment as initial page text by default
593 if ( is_null( $this->mParams['text'] ) ) {
594 $this->mParams['text'] = $this->mParams['comment'];
597 /** @var $file File */
598 $file = $this->mUpload->getLocalFile();
600 // For preferences mode, we want to watch if 'watchdefault' is set or
601 // if the *file* doesn't exist and 'watchcreations' is set. But
602 // getWatchlistValue()'s automatic handling checks if the *title*
603 // exists or not, so we need to check both prefs manually.
604 $watch = $this->getWatchlistValue(
605 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
607 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
608 $watch = $this->getWatchlistValue(
609 $this->mParams['watchlist'], $file->getTitle(), 'watchcreations'
613 // Deprecated parameters
614 if ( $this->mParams['watch'] ) {
615 $watch = true;
618 // No errors, no warnings: do the upload
619 if ( $this->mParams['async'] ) {
620 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
621 if ( $progress && $progress['result'] === 'Poll' ) {
622 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
624 UploadBase::setSessionStatus(
625 $this->mParams['filekey'],
626 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
628 $ok = JobQueueGroup::singleton()->push( new PublishStashedFileJob(
629 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
630 array(
631 'filename' => $this->mParams['filename'],
632 'filekey' => $this->mParams['filekey'],
633 'comment' => $this->mParams['comment'],
634 'text' => $this->mParams['text'],
635 'watch' => $watch,
636 'session' => $this->getContext()->exportSession()
638 ) );
639 if ( $ok ) {
640 $result['result'] = 'Poll';
641 } else {
642 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
643 $this->dieUsage(
644 "Failed to start PublishStashedFile.php", 'publishfailed' );
646 } else {
647 /** @var $status Status */
648 $status = $this->mUpload->performUpload( $this->mParams['comment'],
649 $this->mParams['text'], $watch, $this->getUser() );
651 if ( !$status->isGood() ) {
652 $error = $status->getErrorsArray();
654 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
655 // The upload can not be performed right now, because the user
656 // requested so
657 return array(
658 'result' => 'Queued',
659 'statuskey' => $error[0][1],
663 $this->getResult()->setIndexedTagName( $error, 'error' );
664 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
666 $result['result'] = 'Success';
669 $result['filename'] = $file->getName();
670 if ( $warnings && count( $warnings ) > 0 ) {
671 $result['warnings'] = $warnings;
674 return $result;
678 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
680 protected function checkAsyncDownloadEnabled() {
681 global $wgAllowAsyncCopyUploads;
682 if ( !$wgAllowAsyncCopyUploads ) {
683 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
687 public function mustBePosted() {
688 return true;
691 public function isWriteMode() {
692 return true;
695 public function getAllowedParams() {
696 $params = array(
697 'filename' => array(
698 ApiBase::PARAM_TYPE => 'string',
700 'comment' => array(
701 ApiBase::PARAM_DFLT => ''
703 'text' => null,
704 'token' => array(
705 ApiBase::PARAM_TYPE => 'string',
706 ApiBase::PARAM_REQUIRED => true
708 'watch' => array(
709 ApiBase::PARAM_DFLT => false,
710 ApiBase::PARAM_DEPRECATED => true,
712 'watchlist' => array(
713 ApiBase::PARAM_DFLT => 'preferences',
714 ApiBase::PARAM_TYPE => array(
715 'watch',
716 'preferences',
717 'nochange'
720 'ignorewarnings' => false,
721 'file' => array(
722 ApiBase::PARAM_TYPE => 'upload',
724 'url' => null,
725 'filekey' => null,
726 'sessionkey' => array(
727 ApiBase::PARAM_DFLT => null,
728 ApiBase::PARAM_DEPRECATED => true,
730 'stash' => false,
732 'filesize' => null,
733 'offset' => null,
734 'chunk' => array(
735 ApiBase::PARAM_TYPE => 'upload',
738 'async' => false,
739 'asyncdownload' => false,
740 'leavemessage' => false,
741 'statuskey' => null,
742 'checkstatus' => false,
745 return $params;
748 public function getParamDescription() {
749 $params = array(
750 'filename' => 'Target filename',
751 'token' => 'Edit token. You can get one of these through prop=info',
752 'comment' => 'Upload comment. Also used as the initial page text for new ' .
753 'files if "text" is not specified',
754 'text' => 'Initial page text for new files',
755 'watch' => 'Watch the page',
756 'watchlist' => 'Unconditionally add or remove the page from your watchlist, ' .
757 'use preferences or do not change watch',
758 'ignorewarnings' => 'Ignore any warnings',
759 'file' => 'File contents',
760 'url' => 'URL to fetch the file from',
761 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
762 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
763 'stash' => 'If set, the server will not add the file to the repository ' .
764 'and stash it temporarily.',
766 'chunk' => 'Chunk contents',
767 'offset' => 'Offset of chunk in bytes',
768 'filesize' => 'Filesize of entire upload',
770 'async' => 'Make potentially large file operations asynchronous when possible',
771 'asyncdownload' => 'Make fetching a URL asynchronous',
772 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
773 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
774 'checkstatus' => 'Only fetch the upload status for the given file key',
777 return $params;
780 public function getResultProperties() {
781 return array(
782 '' => array(
783 'result' => array(
784 ApiBase::PROP_TYPE => array(
785 'Success',
786 'Warning',
787 'Continue',
788 'Queued'
791 'filekey' => array(
792 ApiBase::PROP_TYPE => 'string',
793 ApiBase::PROP_NULLABLE => true
795 'sessionkey' => array(
796 ApiBase::PROP_TYPE => 'string',
797 ApiBase::PROP_NULLABLE => true
799 'offset' => array(
800 ApiBase::PROP_TYPE => 'integer',
801 ApiBase::PROP_NULLABLE => true
803 'statuskey' => array(
804 ApiBase::PROP_TYPE => 'string',
805 ApiBase::PROP_NULLABLE => true
807 'filename' => array(
808 ApiBase::PROP_TYPE => 'string',
809 ApiBase::PROP_NULLABLE => true
815 public function getDescription() {
816 return array(
817 'Upload a file, or get the status of pending uploads. Several methods are available:',
818 ' * Upload file contents directly, using the "file" parameter',
819 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
820 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
821 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
822 'sending the "file". Also you must get and send an edit token before doing any upload stuff.'
826 public function getPossibleErrors() {
827 return array_merge( parent::getPossibleErrors(),
828 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
829 array(
830 array( 'uploaddisabled' ),
831 array( 'invalid-file-key' ),
832 array( 'uploaddisabled' ),
833 array( 'mustbeloggedin', 'upload' ),
834 array( 'badaccess-groups' ),
835 array( 'code' => 'fetchfileerror', 'info' => '' ),
836 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
837 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
838 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
839 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
840 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
841 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
842 array( 'code' => 'publishfailed', 'info' => 'Publishing of stashed file failed' ),
843 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
844 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
845 array( 'code' => 'stasherror', 'info' => 'An upload stash error occurred' ),
846 array( 'fileexists-forbidden' ),
847 array( 'fileexists-shared-forbidden' ),
852 public function needsToken() {
853 return true;
856 public function getTokenSalt() {
857 return '';
860 public function getExamples() {
861 return array(
862 'api.php?action=upload&filename=Wiki.png' .
863 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
864 => 'Upload from a URL',
865 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
866 => 'Complete an upload that failed due to warnings',
870 public function getHelpUrls() {
871 return 'https://www.mediawiki.org/wiki/API:Upload';