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