Merge "Add the required call to the parent setUp to DiffHistoryBlobTest::setUp()"
[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', 'status' => Status::newGood() )
215 );
216 $retVal = 1;
217 $cmd = wfShellWikiCmd(
218 "$IP/includes/upload/AssembleUploadChunks.php",
219 array(
220 '--filename', $this->mParams['filename'],
221 '--filekey', $this->mParams['filekey'],
222 '--userid', $this->getUser()->getId(),
223 '--sessionid', session_id(),
224 '--quiet'
225 )
226 ) . " < " . wfGetNull() . " > " . wfGetNull() . " 2>&1 &";
227 wfShellExec( $cmd, $retVal ); // start a process in the background
228 if ( $retVal == 0 ) {
229 $result['result'] = 'Poll';
230 } else {
231 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
232 $this->dieUsage(
233 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
234 }
235 } else {
236 $status = $this->mUpload->concatenateChunks();
237 if ( !$status->isGood() ) {
238 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
239 return array();
240 }
241
242 // We have a new filekey for the fully concatenated file.
243 $result['filekey'] = $this->mUpload->getLocalFile()->getFileKey();
244
245 // Remove chunk from stash. (Checks against user ownership of chunks.)
246 $this->mUpload->stash->removeFile( $this->mParams['filekey'] );
247
248 $result['result'] = 'Success';
249 }
250 } else {
251 // Continue passing through the filekey for adding further chunks.
252 $result['filekey'] = $this->mParams['filekey'];
253 }
254 }
255 $result['offset'] = $this->mParams['offset'] + $chunkSize;
256 return $result;
257 }
258
259 /**
260 * Stash the file and return the file key
261 * Also re-raises exceptions with slightly more informative message strings (useful for API)
262 * @throws MWException
263 * @return String file key
264 */
265 function performStash() {
266 try {
267 $stashFile = $this->mUpload->stashFile();
268
269 if ( !$stashFile ) {
270 throw new MWException( 'Invalid stashed file' );
271 }
272 $fileKey = $stashFile->getFileKey();
273 } catch ( MWException $e ) {
274 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
275 wfDebug( __METHOD__ . ' ' . $message . "\n");
276 throw new MWException( $message );
277 }
278 return $fileKey;
279 }
280
281 /**
282 * Throw an error that the user can recover from by providing a better
283 * value for $parameter
284 *
285 * @param $error array Error array suitable for passing to dieUsageMsg()
286 * @param $parameter string Parameter that needs revising
287 * @param $data array Optional extra data to pass to the user
288 * @throws UsageException
289 */
290 function dieRecoverableError( $error, $parameter, $data = array() ) {
291 try {
292 $data['filekey'] = $this->performStash();
293 $data['sessionkey'] = $data['filekey'];
294 } catch ( MWException $e ) {
295 $data['stashfailed'] = $e->getMessage();
296 }
297 $data['invalidparameter'] = $parameter;
298
299 $parsed = $this->parseMsg( $error );
300 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
301 }
302
303 /**
304 * Select an upload module and set it to mUpload. Dies on failure. If the
305 * request was a status request and not a true upload, returns false;
306 * otherwise true
307 *
308 * @return bool
309 */
310 protected function selectUploadModule() {
311 $request = $this->getMain()->getRequest();
312
313 // chunk or one and only one of the following parameters is needed
314 if ( !$this->mParams['chunk'] ) {
315 $this->requireOnlyOneParameter( $this->mParams,
316 'filekey', 'file', 'url', 'statuskey' );
317 }
318
319 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
320 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
321 if ( !$progress ) {
322 $this->dieUsage( 'No result in status data', 'missingresult' );
323 } elseif ( !$progress['status']->isGood() ) {
324 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
325 }
326 unset( $progress['status'] ); // remove Status object
327 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
328 return false;
329 }
330
331 if ( $this->mParams['statuskey'] ) {
332 $this->checkAsyncDownloadEnabled();
333
334 // Status request for an async upload
335 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
336 if ( !isset( $sessionData['result'] ) ) {
337 $this->dieUsage( 'No result in session data', 'missingresult' );
338 }
339 if ( $sessionData['result'] == 'Warning' ) {
340 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
341 $sessionData['sessionkey'] = $this->mParams['statuskey'];
342 }
343 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
344 return false;
345 }
346
347 // The following modules all require the filename parameter to be set
348 if ( is_null( $this->mParams['filename'] ) ) {
349 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
350 }
351
352 if ( $this->mParams['chunk'] ) {
353 // Chunk upload
354 $this->mUpload = new UploadFromChunks();
355 if( isset( $this->mParams['filekey'] ) ){
356 // handle new chunk
357 $this->mUpload->continueChunks(
358 $this->mParams['filename'],
359 $this->mParams['filekey'],
360 $request->getUpload( 'chunk' )
361 );
362 } else {
363 // handle first chunk
364 $this->mUpload->initialize(
365 $this->mParams['filename'],
366 $request->getUpload( 'chunk' )
367 );
368 }
369 } elseif ( isset( $this->mParams['filekey'] ) ) {
370 // Upload stashed in a previous request
371 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
372 $this->dieUsageMsg( 'invalid-file-key' );
373 }
374
375 $this->mUpload = new UploadFromStash( $this->getUser() );
376
377 $this->mUpload->initialize( $this->mParams['filekey'], $this->mParams['filename'] );
378 } elseif ( isset( $this->mParams['file'] ) ) {
379 $this->mUpload = new UploadFromFile();
380 $this->mUpload->initialize(
381 $this->mParams['filename'],
382 $request->getUpload( 'file' )
383 );
384 } elseif ( isset( $this->mParams['url'] ) ) {
385 // Make sure upload by URL is enabled:
386 if ( !UploadFromUrl::isEnabled() ) {
387 $this->dieUsageMsg( 'copyuploaddisabled' );
388 }
389
390 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
391 $this->dieUsageMsg( 'copyuploadbaddomain' );
392 }
393
394 $async = false;
395 if ( $this->mParams['asyncdownload'] ) {
396 $this->checkAsyncDownloadEnabled();
397
398 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
399 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
400 'missing-ignorewarnings' );
401 }
402
403 if ( $this->mParams['leavemessage'] ) {
404 $async = 'async-leavemessage';
405 } else {
406 $async = 'async';
407 }
408 }
409 $this->mUpload = new UploadFromUrl;
410 $this->mUpload->initialize( $this->mParams['filename'],
411 $this->mParams['url'], $async );
412 }
413
414 return true;
415 }
416
417 /**
418 * Checks that the user has permissions to perform this upload.
419 * Dies with usage message on inadequate permissions.
420 * @param $user User The user to check.
421 */
422 protected function checkPermissions( $user ) {
423 // Check whether the user has the appropriate permissions to upload anyway
424 $permission = $this->mUpload->isAllowed( $user );
425
426 if ( $permission !== true ) {
427 if ( !$user->isLoggedIn() ) {
428 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
429 } else {
430 $this->dieUsageMsg( 'badaccess-groups' );
431 }
432 }
433 }
434
435 /**
436 * Performs file verification, dies on error.
437 */
438 protected function verifyUpload( ) {
439 global $wgFileExtensions;
440
441 $verification = $this->mUpload->verifyUpload( );
442 if ( $verification['status'] === UploadBase::OK ) {
443 return;
444 }
445
446 // TODO: Move them to ApiBase's message map
447 switch( $verification['status'] ) {
448 // Recoverable errors
449 case UploadBase::MIN_LENGTH_PARTNAME:
450 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
451 break;
452 case UploadBase::ILLEGAL_FILENAME:
453 $this->dieRecoverableError( 'illegal-filename', 'filename',
454 array( 'filename' => $verification['filtered'] ) );
455 break;
456 case UploadBase::FILENAME_TOO_LONG:
457 $this->dieRecoverableError( 'filename-toolong', 'filename' );
458 break;
459 case UploadBase::FILETYPE_MISSING:
460 $this->dieRecoverableError( 'filetype-missing', 'filename' );
461 break;
462 case UploadBase::WINDOWS_NONASCII_FILENAME:
463 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
464 break;
465
466 // Unrecoverable errors
467 case UploadBase::EMPTY_FILE:
468 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
469 break;
470 case UploadBase::FILE_TOO_LARGE:
471 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
472 break;
473
474 case UploadBase::FILETYPE_BADTYPE:
475 $extradata = array(
476 'filetype' => $verification['finalExt'],
477 'allowed' => $wgFileExtensions
478 );
479 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
480
481 $msg = "Filetype not permitted: ";
482 if ( isset( $verification['blacklistedExt'] ) ) {
483 $msg .= join( ', ', $verification['blacklistedExt'] );
484 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
485 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
486 } else {
487 $msg .= $verification['finalExt'];
488 }
489 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
490 break;
491 case UploadBase::VERIFICATION_ERROR:
492 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
493 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
494 0, array( 'details' => $verification['details'] ) );
495 break;
496 case UploadBase::HOOK_ABORTED:
497 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
498 'hookaborted', 0, array( 'error' => $verification['error'] ) );
499 break;
500 default:
501 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
502 0, array( 'code' => $verification['status'] ) );
503 break;
504 }
505 }
506
507
508 /**
509 * Check warnings.
510 * Returns a suitable array for inclusion into API results if there were warnings
511 * Returns the empty array if there were no warnings
512 *
513 * @return array
514 */
515 protected function getApiWarnings() {
516 $warnings = $this->mUpload->checkWarnings();
517
518 return $this->transformWarnings( $warnings );
519 }
520
521 protected function transformWarnings( $warnings ) {
522 if ( $warnings ) {
523 // Add indices
524 $result = $this->getResult();
525 $result->setIndexedTagName( $warnings, 'warning' );
526
527 if ( isset( $warnings['duplicate'] ) ) {
528 $dupes = array();
529 foreach ( $warnings['duplicate'] as $dupe ) {
530 $dupes[] = $dupe->getName();
531 }
532 $result->setIndexedTagName( $dupes, 'duplicate' );
533 $warnings['duplicate'] = $dupes;
534 }
535
536 if ( isset( $warnings['exists'] ) ) {
537 $warning = $warnings['exists'];
538 unset( $warnings['exists'] );
539 $warnings[$warning['warning']] = $warning['file']->getName();
540 }
541 }
542 return $warnings;
543 }
544
545
546 /**
547 * Perform the actual upload. Returns a suitable result array on success;
548 * dies on failure.
549 *
550 * @param $warnings array Array of Api upload warnings
551 * @return array
552 */
553 protected function performUpload( $warnings ) {
554 // Use comment as initial page text by default
555 if ( is_null( $this->mParams['text'] ) ) {
556 $this->mParams['text'] = $this->mParams['comment'];
557 }
558
559 $file = $this->mUpload->getLocalFile();
560 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
561
562 // Deprecated parameters
563 if ( $this->mParams['watch'] ) {
564 $watch = true;
565 }
566
567 // No errors, no warnings: do the upload
568 $status = $this->mUpload->performUpload( $this->mParams['comment'],
569 $this->mParams['text'], $watch, $this->getUser() );
570
571 if ( !$status->isGood() ) {
572 $error = $status->getErrorsArray();
573
574 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
575 // The upload can not be performed right now, because the user
576 // requested so
577 return array(
578 'result' => 'Queued',
579 'statuskey' => $error[0][1],
580 );
581 } else {
582 $this->getResult()->setIndexedTagName( $error, 'error' );
583
584 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
585 }
586 }
587
588 $file = $this->mUpload->getLocalFile();
589
590 $result['result'] = 'Success';
591 $result['filename'] = $file->getName();
592 if ( $warnings && count( $warnings ) > 0 ) {
593 $result['warnings'] = $warnings;
594 }
595
596 return $result;
597 }
598
599 /**
600 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
601 */
602 protected function checkAsyncDownloadEnabled() {
603 global $wgAllowAsyncCopyUploads;
604 if ( !$wgAllowAsyncCopyUploads ) {
605 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled');
606 }
607 }
608
609 public function mustBePosted() {
610 return true;
611 }
612
613 public function isWriteMode() {
614 return true;
615 }
616
617 public function getAllowedParams() {
618 $params = array(
619 'filename' => array(
620 ApiBase::PARAM_TYPE => 'string',
621 ),
622 'comment' => array(
623 ApiBase::PARAM_DFLT => ''
624 ),
625 'text' => null,
626 'token' => array(
627 ApiBase::PARAM_TYPE => 'string',
628 ApiBase::PARAM_REQUIRED => true
629 ),
630 'watch' => array(
631 ApiBase::PARAM_DFLT => false,
632 ApiBase::PARAM_DEPRECATED => true,
633 ),
634 'watchlist' => array(
635 ApiBase::PARAM_DFLT => 'preferences',
636 ApiBase::PARAM_TYPE => array(
637 'watch',
638 'preferences',
639 'nochange'
640 ),
641 ),
642 'ignorewarnings' => false,
643 'file' => null,
644 'url' => null,
645 'filekey' => null,
646 'sessionkey' => array(
647 ApiBase::PARAM_DFLT => null,
648 ApiBase::PARAM_DEPRECATED => true,
649 ),
650 'stash' => false,
651
652 'filesize' => null,
653 'offset' => null,
654 'chunk' => null,
655
656 'async' => false,
657 'asyncdownload' => false,
658 'leavemessage' => false,
659 'statuskey' => null,
660 'checkstatus' => false,
661 );
662
663 return $params;
664 }
665
666 public function getParamDescription() {
667 $params = array(
668 'filename' => 'Target filename',
669 'token' => 'Edit token. You can get one of these through prop=info',
670 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
671 'text' => 'Initial page text for new files',
672 'watch' => 'Watch the page',
673 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
674 'ignorewarnings' => 'Ignore any warnings',
675 'file' => 'File contents',
676 'url' => 'URL to fetch the file from',
677 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
678 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
679 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
680
681 'chunk' => 'Chunk contents',
682 'offset' => 'Offset of chunk in bytes',
683 'filesize' => 'Filesize of entire upload',
684
685 'async', 'Make potentially large file operations asynchronous when possible',
686 'asyncdownload' => 'Make fetching a URL asynchronous',
687 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
688 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
689 'checkstatus' => 'Only fetch the upload status for the given file key',
690 );
691
692 return $params;
693
694 }
695
696 public function getResultProperties() {
697 return array(
698 '' => array(
699 'result' => array(
700 ApiBase::PROP_TYPE => array(
701 'Success',
702 'Warning',
703 'Continue',
704 'Queued'
705 ),
706 ),
707 'filekey' => array(
708 ApiBase::PROP_TYPE => 'string',
709 ApiBase::PROP_NULLABLE => true
710 ),
711 'sessionkey' => array(
712 ApiBase::PROP_TYPE => 'string',
713 ApiBase::PROP_NULLABLE => true
714 ),
715 'offset' => array(
716 ApiBase::PROP_TYPE => 'integer',
717 ApiBase::PROP_NULLABLE => true
718 ),
719 'statuskey' => array(
720 ApiBase::PROP_TYPE => 'string',
721 ApiBase::PROP_NULLABLE => true
722 ),
723 'filename' => array(
724 ApiBase::PROP_TYPE => 'string',
725 ApiBase::PROP_NULLABLE => true
726 )
727 )
728 );
729 }
730
731 public function getDescription() {
732 return array(
733 'Upload a file, or get the status of pending uploads. Several methods are available:',
734 ' * Upload file contents directly, using the "file" parameter',
735 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
736 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
737 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
738 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
739 );
740 }
741
742 public function getPossibleErrors() {
743 return array_merge( parent::getPossibleErrors(),
744 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
745 array(
746 array( 'uploaddisabled' ),
747 array( 'invalid-file-key' ),
748 array( 'uploaddisabled' ),
749 array( 'mustbeloggedin', 'upload' ),
750 array( 'badaccess-groups' ),
751 array( 'code' => 'fetchfileerror', 'info' => '' ),
752 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
753 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
754 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
755 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
756 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
757 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
758 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
759 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
760 array( 'fileexists-forbidden' ),
761 array( 'fileexists-shared-forbidden' ),
762 )
763 );
764 }
765
766 public function needsToken() {
767 return true;
768 }
769
770 public function getTokenSalt() {
771 return '';
772 }
773
774 public function getExamples() {
775 return array(
776 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
777 => 'Upload from a URL',
778 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
779 => 'Complete an upload that failed due to warnings',
780 );
781 }
782
783 public function getHelpUrls() {
784 return 'https://www.mediawiki.org/wiki/API:Upload';
785 }
786
787 public function getVersion() {
788 return __CLASS__ . ': $Id$';
789 }
790 }