Merge "[JobQueue] Some tweaks to reduce claimRandom() retries."
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 *
4 *
5 * Created on Aug 21, 2008
6 *
7 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
27 /**
28 * @ingroup API
29 */
30 class ApiUpload extends ApiBase {
31
32 /**
33 * @var UploadBase
34 */
35 protected $mUpload = null;
36
37 protected $mParams;
38
39 public function __construct( $main, $action ) {
40 parent::__construct( $main, $action );
41 }
42
43 public function execute() {
44 // Check whether upload is enabled
45 if ( !UploadBase::isEnabled() ) {
46 $this->dieUsageMsg( 'uploaddisabled' );
47 }
48
49 $user = $this->getUser();
50
51 // Parameter handling
52 $this->mParams = $this->extractRequestParams();
53 $request = $this->getMain()->getRequest();
54 // Add the uploaded file to the params array
55 $this->mParams['file'] = $request->getFileName( 'file' );
56 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
57
58 // Copy the session key to the file key, for backward compatibility.
59 if( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
60 $this->mParams['filekey'] = $this->mParams['sessionkey'];
61 }
62
63 // Select an upload module
64 if ( !$this->selectUploadModule() ) {
65 // This is not a true upload, but a status request or similar
66 return;
67 }
68 if ( !isset( $this->mUpload ) ) {
69 $this->dieUsage( 'No upload module set', 'nomodule' );
70 }
71
72 // First check permission to upload
73 $this->checkPermissions( $user );
74
75 // Fetch the file
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] );
81 }
82
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' );
88 }
89 if ( !$this->mUpload->getTitle() ) {
90 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
91 }
92 } else {
93 $this->verifyUpload();
94 }
95
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[0], 'filename' );
103 }
104 }
105 // Get the result based on the current upload context:
106 $result = $this->getContextResult();
107
108 if ( $result['result'] === 'Success' ) {
109 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
110 }
111
112 $this->getResult()->addValue( null, $this->getModuleName(), $result );
113
114 // Cleanup any temporary mess
115 $this->mUpload->cleanupTempFile();
116 }
117
118 /**
119 * Get an uplaod result based on upload context
120 * @return array
121 */
122 private function getContextResult(){
123 $warnings = $this->getApiWarnings();
124 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
125 // Get warnings formated in result array format
126 return $this->getWarningsResult( $warnings );
127 } elseif ( $this->mParams['chunk'] ) {
128 // Add chunk, and get result
129 return $this->getChunkResult( $warnings );
130 } elseif ( $this->mParams['stash'] ) {
131 // Stash the file and get stash result
132 return $this->getStashResult( $warnings );
133 }
134 // This is the most common case -- a normal upload with no warnings
135 // performUpload will return a formatted properly for the API with status
136 return $this->performUpload( $warnings );
137 }
138 /**
139 * Get Stash Result, throws an expetion if the file could not be stashed.
140 * @param $warnings array Array of Api upload warnings
141 * @return array
142 */
143 private function getStashResult( $warnings ){
144 $result = array ();
145 // Some uploads can request they be stashed, so as not to publish them immediately.
146 // In this case, a failure to stash ought to be fatal
147 try {
148 $result['result'] = 'Success';
149 $result['filekey'] = $this->performStash();
150 $result['sessionkey'] = $result['filekey']; // backwards compatibility
151 if ( $warnings && count( $warnings ) > 0 ) {
152 $result['warnings'] = $warnings;
153 }
154 } catch ( MWException $e ) {
155 $this->dieUsage( $e->getMessage(), 'stashfailed' );
156 }
157 return $result;
158 }
159 /**
160 * Get Warnings Result
161 * @param $warnings array Array of Api upload warnings
162 * @return array
163 */
164 private function getWarningsResult( $warnings ){
165 $result = array();
166 $result['result'] = 'Warning';
167 $result['warnings'] = $warnings;
168 // in case the warnings can be fixed with some further user action, let's stash this upload
169 // and return a key they can use to restart it
170 try {
171 $result['filekey'] = $this->performStash();
172 $result['sessionkey'] = $result['filekey']; // backwards compatibility
173 } catch ( MWException $e ) {
174 $result['warnings']['stashfailed'] = $e->getMessage();
175 }
176 return $result;
177 }
178 /**
179 * Get the result of a chunk upload.
180 * @param $warnings array Array of Api upload warnings
181 * @return array
182 */
183 private function getChunkResult( $warnings ) {
184 global $IP;
185
186 $result = array();
187
188 $result['result'] = 'Continue';
189 if ( $warnings && count( $warnings ) > 0 ) {
190 $result['warnings'] = $warnings;
191 }
192 $request = $this->getMain()->getRequest();
193 $chunkPath = $request->getFileTempname( 'chunk' );
194 $chunkSize = $request->getUpload( 'chunk' )->getSize();
195 if ($this->mParams['offset'] == 0) {
196 $result['filekey'] = $this->performStash();
197 } else {
198 $status = $this->mUpload->addChunk(
199 $chunkPath, $chunkSize, $this->mParams['offset'] );
200 if ( !$status->isGood() ) {
201 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
202 return array();
203 }
204
205 // Check we added the last chunk:
206 if( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
207 if ( $this->mParams['async'] && !wfIsWindows() ) {
208 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
209 if ( $progress && $progress['result'] !== 'Failed' ) {
210 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
211 }
212 UploadBase::setSessionStatus(
213 $this->mParams['filekey'],
214 array( 'result' => 'Poll',
215 'stage' => 'queued', 'status' => Status::newGood() )
216 );
217 $retVal = 1;
218 $cmd = wfShellWikiCmd(
219 "$IP/includes/upload/AssembleUploadChunks.php",
220 array(
221 '--wiki', wfWikiID(),
222 '--filename', $this->mParams['filename'],
223 '--filekey', $this->mParams['filekey'],
224 '--userid', $this->getUser()->getId(),
225 '--sessionid', session_id(),
226 '--quiet'
227 )
228 ) . " < " . wfGetNull() . " > " . wfGetNull() . " 2>&1 &";
229 // Start a process in the background. Enforce the time limits via PHP
230 // since ulimit4.sh seems to often not work for this particular usage.
231 wfShellExec( $cmd, $retVal, array(), array( 'time' => 0, 'memory' => 0 ) );
232 if ( $retVal == 0 ) {
233 $result['result'] = 'Poll';
234 } else {
235 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
236 $this->dieUsage(
237 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
238 }
239 } else {
240 $status = $this->mUpload->concatenateChunks();
241 if ( !$status->isGood() ) {
242 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
243 return array();
244 }
245
246 // We have a new filekey for the fully concatenated file.
247 $result['filekey'] = $this->mUpload->getLocalFile()->getFileKey();
248
249 // Remove chunk from stash. (Checks against user ownership of chunks.)
250 $this->mUpload->stash->removeFile( $this->mParams['filekey'] );
251
252 $result['result'] = 'Success';
253 }
254 } else {
255 // Continue passing through the filekey for adding further chunks.
256 $result['filekey'] = $this->mParams['filekey'];
257 }
258 }
259 $result['offset'] = $this->mParams['offset'] + $chunkSize;
260 return $result;
261 }
262
263 /**
264 * Stash the file and return the file key
265 * Also re-raises exceptions with slightly more informative message strings (useful for API)
266 * @throws MWException
267 * @return String file key
268 */
269 function performStash() {
270 try {
271 $stashFile = $this->mUpload->stashFile();
272
273 if ( !$stashFile ) {
274 throw new MWException( 'Invalid stashed file' );
275 }
276 $fileKey = $stashFile->getFileKey();
277 } catch ( MWException $e ) {
278 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
279 wfDebug( __METHOD__ . ' ' . $message . "\n");
280 throw new MWException( $message );
281 }
282 return $fileKey;
283 }
284
285 /**
286 * Throw an error that the user can recover from by providing a better
287 * value for $parameter
288 *
289 * @param $error array Error array suitable for passing to dieUsageMsg()
290 * @param $parameter string Parameter that needs revising
291 * @param $data array Optional extra data to pass to the user
292 * @throws UsageException
293 */
294 function dieRecoverableError( $error, $parameter, $data = array() ) {
295 try {
296 $data['filekey'] = $this->performStash();
297 $data['sessionkey'] = $data['filekey'];
298 } catch ( MWException $e ) {
299 $data['stashfailed'] = $e->getMessage();
300 }
301 $data['invalidparameter'] = $parameter;
302
303 $parsed = $this->parseMsg( $error );
304 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
305 }
306
307 /**
308 * Select an upload module and set it to mUpload. Dies on failure. If the
309 * request was a status request and not a true upload, returns false;
310 * otherwise true
311 *
312 * @return bool
313 */
314 protected function selectUploadModule() {
315 $request = $this->getMain()->getRequest();
316
317 // chunk or one and only one of the following parameters is needed
318 if ( !$this->mParams['chunk'] ) {
319 $this->requireOnlyOneParameter( $this->mParams,
320 'filekey', 'file', 'url', 'statuskey' );
321 }
322
323 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
324 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
325 if ( !$progress ) {
326 $this->dieUsage( 'No result in status data', 'missingresult' );
327 } elseif ( !$progress['status']->isGood() ) {
328 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
329 }
330 unset( $progress['status'] ); // remove Status object
331 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
332 return false;
333 }
334
335 if ( $this->mParams['statuskey'] ) {
336 $this->checkAsyncDownloadEnabled();
337
338 // Status request for an async upload
339 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
340 if ( !isset( $sessionData['result'] ) ) {
341 $this->dieUsage( 'No result in session data', 'missingresult' );
342 }
343 if ( $sessionData['result'] == 'Warning' ) {
344 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
345 $sessionData['sessionkey'] = $this->mParams['statuskey'];
346 }
347 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
348 return false;
349 }
350
351 // The following modules all require the filename parameter to be set
352 if ( is_null( $this->mParams['filename'] ) ) {
353 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
354 }
355
356 if ( $this->mParams['chunk'] ) {
357 // Chunk upload
358 $this->mUpload = new UploadFromChunks();
359 if( isset( $this->mParams['filekey'] ) ){
360 // handle new chunk
361 $this->mUpload->continueChunks(
362 $this->mParams['filename'],
363 $this->mParams['filekey'],
364 $request->getUpload( 'chunk' )
365 );
366 } else {
367 // handle first chunk
368 $this->mUpload->initialize(
369 $this->mParams['filename'],
370 $request->getUpload( 'chunk' )
371 );
372 }
373 } elseif ( isset( $this->mParams['filekey'] ) ) {
374 // Upload stashed in a previous request
375 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
376 $this->dieUsageMsg( 'invalid-file-key' );
377 }
378
379 $this->mUpload = new UploadFromStash( $this->getUser() );
380
381 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
382 } elseif ( isset( $this->mParams['file'] ) ) {
383 $this->mUpload = new UploadFromFile();
384 $this->mUpload->initialize(
385 $this->mParams['filename'],
386 $request->getUpload( 'file' )
387 );
388 } elseif ( isset( $this->mParams['url'] ) ) {
389 // Make sure upload by URL is enabled:
390 if ( !UploadFromUrl::isEnabled() ) {
391 $this->dieUsageMsg( 'copyuploaddisabled' );
392 }
393
394 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
395 $this->dieUsageMsg( 'copyuploadbaddomain' );
396 }
397
398 $async = false;
399 if ( $this->mParams['asyncdownload'] ) {
400 $this->checkAsyncDownloadEnabled();
401
402 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
403 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
404 'missing-ignorewarnings' );
405 }
406
407 if ( $this->mParams['leavemessage'] ) {
408 $async = 'async-leavemessage';
409 } else {
410 $async = 'async';
411 }
412 }
413 $this->mUpload = new UploadFromUrl;
414 $this->mUpload->initialize( $this->mParams['filename'],
415 $this->mParams['url'], $async );
416 }
417
418 return true;
419 }
420
421 /**
422 * Checks that the user has permissions to perform this upload.
423 * Dies with usage message on inadequate permissions.
424 * @param $user User The user to check.
425 */
426 protected function checkPermissions( $user ) {
427 // Check whether the user has the appropriate permissions to upload anyway
428 $permission = $this->mUpload->isAllowed( $user );
429
430 if ( $permission !== true ) {
431 if ( !$user->isLoggedIn() ) {
432 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
433 } else {
434 $this->dieUsageMsg( 'badaccess-groups' );
435 }
436 }
437 }
438
439 /**
440 * Performs file verification, dies on error.
441 */
442 protected function verifyUpload( ) {
443 global $wgFileExtensions;
444
445 $verification = $this->mUpload->verifyUpload( );
446 if ( $verification['status'] === UploadBase::OK ) {
447 return;
448 }
449
450 // TODO: Move them to ApiBase's message map
451 switch( $verification['status'] ) {
452 // Recoverable errors
453 case UploadBase::MIN_LENGTH_PARTNAME:
454 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
455 break;
456 case UploadBase::ILLEGAL_FILENAME:
457 $this->dieRecoverableError( 'illegal-filename', 'filename',
458 array( 'filename' => $verification['filtered'] ) );
459 break;
460 case UploadBase::FILENAME_TOO_LONG:
461 $this->dieRecoverableError( 'filename-toolong', 'filename' );
462 break;
463 case UploadBase::FILETYPE_MISSING:
464 $this->dieRecoverableError( 'filetype-missing', 'filename' );
465 break;
466 case UploadBase::WINDOWS_NONASCII_FILENAME:
467 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
468 break;
469
470 // Unrecoverable errors
471 case UploadBase::EMPTY_FILE:
472 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
473 break;
474 case UploadBase::FILE_TOO_LARGE:
475 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
476 break;
477
478 case UploadBase::FILETYPE_BADTYPE:
479 $extradata = array(
480 'filetype' => $verification['finalExt'],
481 'allowed' => $wgFileExtensions
482 );
483 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
484
485 $msg = "Filetype not permitted: ";
486 if ( isset( $verification['blacklistedExt'] ) ) {
487 $msg .= join( ', ', $verification['blacklistedExt'] );
488 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
489 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
490 } else {
491 $msg .= $verification['finalExt'];
492 }
493 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
494 break;
495 case UploadBase::VERIFICATION_ERROR:
496 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
497 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
498 0, array( 'details' => $verification['details'] ) );
499 break;
500 case UploadBase::HOOK_ABORTED:
501 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
502 'hookaborted', 0, array( 'error' => $verification['error'] ) );
503 break;
504 default:
505 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
506 0, array( 'code' => $verification['status'] ) );
507 break;
508 }
509 }
510
511
512 /**
513 * Check warnings.
514 * Returns a suitable array for inclusion into API results if there were warnings
515 * Returns the empty array if there were no warnings
516 *
517 * @return array
518 */
519 protected function getApiWarnings() {
520 $warnings = $this->mUpload->checkWarnings();
521
522 return $this->transformWarnings( $warnings );
523 }
524
525 protected function transformWarnings( $warnings ) {
526 if ( $warnings ) {
527 // Add indices
528 $result = $this->getResult();
529 $result->setIndexedTagName( $warnings, 'warning' );
530
531 if ( isset( $warnings['duplicate'] ) ) {
532 $dupes = array();
533 foreach ( $warnings['duplicate'] as $dupe ) {
534 $dupes[] = $dupe->getName();
535 }
536 $result->setIndexedTagName( $dupes, 'duplicate' );
537 $warnings['duplicate'] = $dupes;
538 }
539
540 if ( isset( $warnings['exists'] ) ) {
541 $warning = $warnings['exists'];
542 unset( $warnings['exists'] );
543 $warnings[$warning['warning']] = $warning['file']->getName();
544 }
545 }
546 return $warnings;
547 }
548
549
550 /**
551 * Perform the actual upload. Returns a suitable result array on success;
552 * dies on failure.
553 *
554 * @param $warnings array Array of Api upload warnings
555 * @return array
556 */
557 protected function performUpload( $warnings ) {
558 // Use comment as initial page text by default
559 if ( is_null( $this->mParams['text'] ) ) {
560 $this->mParams['text'] = $this->mParams['comment'];
561 }
562
563 $file = $this->mUpload->getLocalFile();
564 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
565
566 // Deprecated parameters
567 if ( $this->mParams['watch'] ) {
568 $watch = true;
569 }
570
571 // No errors, no warnings: do the upload
572 $status = $this->mUpload->performUpload( $this->mParams['comment'],
573 $this->mParams['text'], $watch, $this->getUser() );
574
575 if ( !$status->isGood() ) {
576 $error = $status->getErrorsArray();
577
578 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
579 // The upload can not be performed right now, because the user
580 // requested so
581 return array(
582 'result' => 'Queued',
583 'statuskey' => $error[0][1],
584 );
585 } else {
586 $this->getResult()->setIndexedTagName( $error, 'error' );
587
588 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
589 }
590 }
591
592 $file = $this->mUpload->getLocalFile();
593
594 $result['result'] = 'Success';
595 $result['filename'] = $file->getName();
596 if ( $warnings && count( $warnings ) > 0 ) {
597 $result['warnings'] = $warnings;
598 }
599
600 return $result;
601 }
602
603 /**
604 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
605 */
606 protected function checkAsyncDownloadEnabled() {
607 global $wgAllowAsyncCopyUploads;
608 if ( !$wgAllowAsyncCopyUploads ) {
609 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
610 }
611 }
612
613 public function mustBePosted() {
614 return true;
615 }
616
617 public function isWriteMode() {
618 return true;
619 }
620
621 public function getAllowedParams() {
622 $params = array(
623 'filename' => array(
624 ApiBase::PARAM_TYPE => 'string',
625 ),
626 'comment' => array(
627 ApiBase::PARAM_DFLT => ''
628 ),
629 'text' => null,
630 'token' => array(
631 ApiBase::PARAM_TYPE => 'string',
632 ApiBase::PARAM_REQUIRED => true
633 ),
634 'watch' => array(
635 ApiBase::PARAM_DFLT => false,
636 ApiBase::PARAM_DEPRECATED => true,
637 ),
638 'watchlist' => array(
639 ApiBase::PARAM_DFLT => 'preferences',
640 ApiBase::PARAM_TYPE => array(
641 'watch',
642 'preferences',
643 'nochange'
644 ),
645 ),
646 'ignorewarnings' => false,
647 'file' => null,
648 'url' => null,
649 'filekey' => null,
650 'sessionkey' => array(
651 ApiBase::PARAM_DFLT => null,
652 ApiBase::PARAM_DEPRECATED => true,
653 ),
654 'stash' => false,
655
656 'filesize' => null,
657 'offset' => null,
658 'chunk' => null,
659
660 'async' => false,
661 'asyncdownload' => false,
662 'leavemessage' => false,
663 'statuskey' => null,
664 'checkstatus' => false,
665 );
666
667 return $params;
668 }
669
670 public function getParamDescription() {
671 $params = array(
672 'filename' => 'Target filename',
673 'token' => 'Edit token. You can get one of these through prop=info',
674 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
675 'text' => 'Initial page text for new files',
676 'watch' => 'Watch the page',
677 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
678 'ignorewarnings' => 'Ignore any warnings',
679 'file' => 'File contents',
680 'url' => 'URL to fetch the file from',
681 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
682 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
683 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
684
685 'chunk' => 'Chunk contents',
686 'offset' => 'Offset of chunk in bytes',
687 'filesize' => 'Filesize of entire upload',
688
689 'async' => 'Make potentially large file operations asynchronous when possible',
690 'asyncdownload' => 'Make fetching a URL asynchronous',
691 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
692 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
693 'checkstatus' => 'Only fetch the upload status for the given file key',
694 );
695
696 return $params;
697
698 }
699
700 public function getResultProperties() {
701 return array(
702 '' => array(
703 'result' => array(
704 ApiBase::PROP_TYPE => array(
705 'Success',
706 'Warning',
707 'Continue',
708 'Queued'
709 ),
710 ),
711 'filekey' => array(
712 ApiBase::PROP_TYPE => 'string',
713 ApiBase::PROP_NULLABLE => true
714 ),
715 'sessionkey' => array(
716 ApiBase::PROP_TYPE => 'string',
717 ApiBase::PROP_NULLABLE => true
718 ),
719 'offset' => array(
720 ApiBase::PROP_TYPE => 'integer',
721 ApiBase::PROP_NULLABLE => true
722 ),
723 'statuskey' => array(
724 ApiBase::PROP_TYPE => 'string',
725 ApiBase::PROP_NULLABLE => true
726 ),
727 'filename' => array(
728 ApiBase::PROP_TYPE => 'string',
729 ApiBase::PROP_NULLABLE => true
730 )
731 )
732 );
733 }
734
735 public function getDescription() {
736 return array(
737 'Upload a file, or get the status of pending uploads. Several methods are available:',
738 ' * Upload file contents directly, using the "file" parameter',
739 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
740 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
741 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
742 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
743 );
744 }
745
746 public function getPossibleErrors() {
747 return array_merge( parent::getPossibleErrors(),
748 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
749 array(
750 array( 'uploaddisabled' ),
751 array( 'invalid-file-key' ),
752 array( 'uploaddisabled' ),
753 array( 'mustbeloggedin', 'upload' ),
754 array( 'badaccess-groups' ),
755 array( 'code' => 'fetchfileerror', 'info' => '' ),
756 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
757 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
758 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
759 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
760 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
761 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
762 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
763 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
764 array( 'fileexists-forbidden' ),
765 array( 'fileexists-shared-forbidden' ),
766 )
767 );
768 }
769
770 public function needsToken() {
771 return true;
772 }
773
774 public function getTokenSalt() {
775 return '';
776 }
777
778 public function getExamples() {
779 return array(
780 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
781 => 'Upload from a URL',
782 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
783 => 'Complete an upload that failed due to warnings',
784 );
785 }
786
787 public function getHelpUrls() {
788 return 'https://www.mediawiki.org/wiki/API:Upload';
789 }
790
791 public function getVersion() {
792 return __CLASS__ . ': $Id$';
793 }
794 }