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