Added spaces before and removed spaces after 'array'
[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 /** @var $status Status */
75 $status = $this->mUpload->fetchFile();
76 if ( !$status->isGood() ) {
77 $errors = $status->getErrorsArray();
78 $error = array_shift( $errors[0] );
79 $this->dieUsage( 'Error fetching file from remote source', $error, 0, $errors[0] );
80 }
81
82 // Check if the uploaded file is sane
83 if ( $this->mParams['chunk'] ) {
84 $maxSize = $this->mUpload->getMaxUploadSize();
85 if( $this->mParams['filesize'] > $maxSize ) {
86 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
87 }
88 if ( !$this->mUpload->getTitle() ) {
89 $this->dieUsage( 'Invalid file title supplied', 'internal-error' );
90 }
91 } elseif ( $this->mParams['async'] ) {
92 // defer verification to background process
93 } else {
94 $this->verifyUpload();
95 }
96
97 // Check if the user has the rights to modify or overwrite the requested title
98 // (This check is irrelevant if stashing is already requested, since the errors
99 // can always be fixed by changing the title)
100 if ( !$this->mParams['stash'] ) {
101 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
102 if ( $permErrors !== true ) {
103 $this->dieRecoverableError( $permErrors[0], 'filename' );
104 }
105 }
106
107 // Get the result based on the current upload context:
108 $result = $this->getContextResult();
109 if ( $result['result'] === 'Success' ) {
110 $result['imageinfo'] = $this->mUpload->getImageInfo( $this->getResult() );
111 }
112
113 $this->getResult()->addValue( null, $this->getModuleName(), $result );
114
115 // Cleanup any temporary mess
116 $this->mUpload->cleanupTempFile();
117 }
118
119 /**
120 * Get an upload result based on upload context
121 * @return array
122 */
123 private function getContextResult() {
124 $warnings = $this->getApiWarnings();
125 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
126 // Get warnings formatted in result array format
127 return $this->getWarningsResult( $warnings );
128 } elseif ( $this->mParams['chunk'] ) {
129 // Add chunk, and get result
130 return $this->getChunkResult( $warnings );
131 } elseif ( $this->mParams['stash'] ) {
132 // Stash the file and get stash result
133 return $this->getStashResult( $warnings );
134 }
135 // This is the most common case -- a normal upload with no warnings
136 // performUpload will return a formatted properly for the API with status
137 return $this->performUpload( $warnings );
138 }
139
140 /**
141 * Get Stash Result, throws an exception if the file could not be stashed.
142 * @param array $warnings Array of Api upload warnings
143 * @return array
144 */
145 private function getStashResult( $warnings ) {
146 $result = array();
147 // Some uploads can request they be stashed, so as not to publish them immediately.
148 // In this case, a failure to stash ought to be fatal
149 try {
150 $result['result'] = 'Success';
151 $result['filekey'] = $this->performStash();
152 $result['sessionkey'] = $result['filekey']; // backwards compatibility
153 if ( $warnings && count( $warnings ) > 0 ) {
154 $result['warnings'] = $warnings;
155 }
156 } catch ( MWException $e ) {
157 $this->dieUsage( $e->getMessage(), 'stashfailed' );
158 }
159 return $result;
160 }
161
162 /**
163 * Get Warnings Result
164 * @param array $warnings Array of Api upload warnings
165 * @return array
166 */
167 private function getWarningsResult( $warnings ) {
168 $result = array();
169 $result['result'] = 'Warning';
170 $result['warnings'] = $warnings;
171 // in case the warnings can be fixed with some further user action, let's stash this upload
172 // and return a key they can use to restart it
173 try {
174 $result['filekey'] = $this->performStash();
175 $result['sessionkey'] = $result['filekey']; // backwards compatibility
176 } catch ( MWException $e ) {
177 $result['warnings']['stashfailed'] = $e->getMessage();
178 }
179 return $result;
180 }
181
182 /**
183 * Get the result of a chunk upload.
184 * @param array $warnings Array of Api upload warnings
185 * @return array
186 */
187 private function getChunkResult( $warnings ) {
188 $result = array();
189
190 $result['result'] = 'Continue';
191 if ( $warnings && count( $warnings ) > 0 ) {
192 $result['warnings'] = $warnings;
193 }
194 $request = $this->getMain()->getRequest();
195 $chunkPath = $request->getFileTempname( 'chunk' );
196 $chunkSize = $request->getUpload( 'chunk' )->getSize();
197 if ( $this->mParams['offset'] == 0 ) {
198 $filekey = $this->performStash();
199 } else {
200 $filekey = $this->mParams['filekey'];
201 /** @var $status Status */
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->getContext()->exportSession()
228 )
229 ) );
230 if ( $ok ) {
231 $result['result'] = 'Poll';
232 } else {
233 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
234 $this->dieUsage(
235 "Failed to start AssembleUploadChunks.php", 'stashfailed' );
236 }
237 } else {
238 $status = $this->mUpload->concatenateChunks();
239 if ( !$status->isGood() ) {
240 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
241 return array();
242 }
243
244 // The fully concatenated file has a new filekey. So remove
245 // the old filekey and fetch the new one.
246 $this->mUpload->stash->removeFile( $filekey );
247 $filekey = $this->mUpload->getLocalFile()->getFileKey();
248
249 $result['result'] = 'Success';
250 }
251 }
252 $result['filekey'] = $filekey;
253 $result['offset'] = $this->mParams['offset'] + $chunkSize;
254 return $result;
255 }
256
257 /**
258 * Stash the file and return the file key
259 * Also re-raises exceptions with slightly more informative message strings (useful for API)
260 * @throws MWException
261 * @return String file key
262 */
263 private function performStash() {
264 try {
265 $stashFile = $this->mUpload->stashFile();
266
267 if ( !$stashFile ) {
268 throw new MWException( 'Invalid stashed file' );
269 }
270 $fileKey = $stashFile->getFileKey();
271 } catch ( MWException $e ) {
272 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
273 wfDebug( __METHOD__ . ' ' . $message . "\n" );
274 throw new MWException( $message );
275 }
276 return $fileKey;
277 }
278
279 /**
280 * Throw an error that the user can recover from by providing a better
281 * value for $parameter
282 *
283 * @param array $error Error array suitable for passing to dieUsageMsg()
284 * @param string $parameter Parameter that needs revising
285 * @param array $data Optional extra data to pass to the user
286 * @throws UsageException
287 */
288 private function dieRecoverableError( $error, $parameter, $data = array() ) {
289 try {
290 $data['filekey'] = $this->performStash();
291 $data['sessionkey'] = $data['filekey'];
292 } catch ( MWException $e ) {
293 $data['stashfailed'] = $e->getMessage();
294 }
295 $data['invalidparameter'] = $parameter;
296
297 $parsed = $this->parseMsg( $error );
298 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
299 }
300
301 /**
302 * Select an upload module and set it to mUpload. Dies on failure. If the
303 * request was a status request and not a true upload, returns false;
304 * otherwise true
305 *
306 * @return bool
307 */
308 protected function selectUploadModule() {
309 $request = $this->getMain()->getRequest();
310
311 // chunk or one and only one of the following parameters is needed
312 if ( !$this->mParams['chunk'] ) {
313 $this->requireOnlyOneParameter( $this->mParams,
314 'filekey', 'file', 'url', 'statuskey' );
315 }
316
317 // Status report for "upload to stash"/"upload from stash"
318 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
319 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
320 if ( !$progress ) {
321 $this->dieUsage( 'No result in status data', 'missingresult' );
322 } elseif ( !$progress['status']->isGood() ) {
323 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
324 }
325 if ( isset( $progress['status']->value['verification'] ) ) {
326 $this->checkVerification( $progress['status']->value['verification'] );
327 }
328 unset( $progress['status'] ); // remove Status object
329 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
330 return false;
331 }
332
333 if ( $this->mParams['statuskey'] ) {
334 $this->checkAsyncDownloadEnabled();
335
336 // Status request for an async upload
337 $sessionData = UploadFromUrlJob::getSessionData( $this->mParams['statuskey'] );
338 if ( !isset( $sessionData['result'] ) ) {
339 $this->dieUsage( 'No result in session data', 'missingresult' );
340 }
341 if ( $sessionData['result'] == 'Warning' ) {
342 $sessionData['warnings'] = $this->transformWarnings( $sessionData['warnings'] );
343 $sessionData['sessionkey'] = $this->mParams['statuskey'];
344 }
345 $this->getResult()->addValue( null, $this->getModuleName(), $sessionData );
346 return false;
347 }
348
349 // The following modules all require the filename parameter to be set
350 if ( is_null( $this->mParams['filename'] ) ) {
351 $this->dieUsageMsg( array( 'missingparam', 'filename' ) );
352 }
353
354 if ( $this->mParams['chunk'] ) {
355 // Chunk upload
356 $this->mUpload = new UploadFromChunks();
357 if( isset( $this->mParams['filekey'] ) ) {
358 // handle new chunk
359 $this->mUpload->continueChunks(
360 $this->mParams['filename'],
361 $this->mParams['filekey'],
362 $request->getUpload( 'chunk' )
363 );
364 } else {
365 // handle first chunk
366 $this->mUpload->initialize(
367 $this->mParams['filename'],
368 $request->getUpload( 'chunk' )
369 );
370 }
371 } elseif ( isset( $this->mParams['filekey'] ) ) {
372 // Upload stashed in a previous request
373 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
374 $this->dieUsageMsg( 'invalid-file-key' );
375 }
376
377 $this->mUpload = new UploadFromStash( $this->getUser() );
378 // This will not download the temp file in initialize() in async mode.
379 // We still have enough information to call checkWarnings() and such.
380 $this->mUpload->initialize(
381 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
382 );
383 } elseif ( isset( $this->mParams['file'] ) ) {
384 $this->mUpload = new UploadFromFile();
385 $this->mUpload->initialize(
386 $this->mParams['filename'],
387 $request->getUpload( 'file' )
388 );
389 } elseif ( isset( $this->mParams['url'] ) ) {
390 // Make sure upload by URL is enabled:
391 if ( !UploadFromUrl::isEnabled() ) {
392 $this->dieUsageMsg( 'copyuploaddisabled' );
393 }
394
395 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
396 $this->dieUsageMsg( 'copyuploadbaddomain' );
397 }
398
399 $async = false;
400 if ( $this->mParams['asyncdownload'] ) {
401 $this->checkAsyncDownloadEnabled();
402
403 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
404 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
405 'missing-ignorewarnings' );
406 }
407
408 if ( $this->mParams['leavemessage'] ) {
409 $async = 'async-leavemessage';
410 } else {
411 $async = 'async';
412 }
413 }
414 $this->mUpload = new UploadFromUrl;
415 $this->mUpload->initialize( $this->mParams['filename'],
416 $this->mParams['url'], $async );
417 }
418
419 return true;
420 }
421
422 /**
423 * Checks that the user has permissions to perform this upload.
424 * Dies with usage message on inadequate permissions.
425 * @param $user User The user to check.
426 */
427 protected function checkPermissions( $user ) {
428 // Check whether the user has the appropriate permissions to upload anyway
429 $permission = $this->mUpload->isAllowed( $user );
430
431 if ( $permission !== true ) {
432 if ( !$user->isLoggedIn() ) {
433 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
434 } else {
435 $this->dieUsageMsg( 'badaccess-groups' );
436 }
437 }
438 }
439
440 /**
441 * Performs file verification, dies on error.
442 */
443 protected function verifyUpload() {
444 $verification = $this->mUpload->verifyUpload();
445 if ( $verification['status'] === UploadBase::OK ) {
446 return;
447 }
448
449 $this->checkVerification( $verification );
450 }
451
452 /**
453 * Performs file verification, dies on error.
454 */
455 protected function checkVerification( array $verification ) {
456 global $wgFileExtensions;
457
458 // @todo Move them to ApiBase's message map
459 switch( $verification['status'] ) {
460 // Recoverable errors
461 case UploadBase::MIN_LENGTH_PARTNAME:
462 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
463 break;
464 case UploadBase::ILLEGAL_FILENAME:
465 $this->dieRecoverableError( 'illegal-filename', 'filename',
466 array( 'filename' => $verification['filtered'] ) );
467 break;
468 case UploadBase::FILENAME_TOO_LONG:
469 $this->dieRecoverableError( 'filename-toolong', 'filename' );
470 break;
471 case UploadBase::FILETYPE_MISSING:
472 $this->dieRecoverableError( 'filetype-missing', 'filename' );
473 break;
474 case UploadBase::WINDOWS_NONASCII_FILENAME:
475 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
476 break;
477
478 // Unrecoverable errors
479 case UploadBase::EMPTY_FILE:
480 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
481 break;
482 case UploadBase::FILE_TOO_LARGE:
483 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
484 break;
485
486 case UploadBase::FILETYPE_BADTYPE:
487 $extradata = array(
488 'filetype' => $verification['finalExt'],
489 'allowed' => $wgFileExtensions
490 );
491 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
492
493 $msg = "Filetype not permitted: ";
494 if ( isset( $verification['blacklistedExt'] ) ) {
495 $msg .= join( ', ', $verification['blacklistedExt'] );
496 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
497 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
498 } else {
499 $msg .= $verification['finalExt'];
500 }
501 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
502 break;
503 case UploadBase::VERIFICATION_ERROR:
504 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
505 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
506 0, array( 'details' => $verification['details'] ) );
507 break;
508 case UploadBase::HOOK_ABORTED:
509 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
510 'hookaborted', 0, array( 'error' => $verification['error'] ) );
511 break;
512 default:
513 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
514 0, array( 'code' => $verification['status'] ) );
515 break;
516 }
517 }
518
519 /**
520 * Check warnings.
521 * Returns a suitable array for inclusion into API results if there were warnings
522 * Returns the empty array if there were no warnings
523 *
524 * @return array
525 */
526 protected function getApiWarnings() {
527 $warnings = $this->mUpload->checkWarnings();
528
529 return $this->transformWarnings( $warnings );
530 }
531
532 protected function transformWarnings( $warnings ) {
533 if ( $warnings ) {
534 // Add indices
535 $result = $this->getResult();
536 $result->setIndexedTagName( $warnings, 'warning' );
537
538 if ( isset( $warnings['duplicate'] ) ) {
539 $dupes = array();
540 foreach ( $warnings['duplicate'] as $dupe ) {
541 $dupes[] = $dupe->getName();
542 }
543 $result->setIndexedTagName( $dupes, 'duplicate' );
544 $warnings['duplicate'] = $dupes;
545 }
546
547 if ( isset( $warnings['exists'] ) ) {
548 $warning = $warnings['exists'];
549 unset( $warnings['exists'] );
550 $warnings[$warning['warning']] = $warning['file']->getName();
551 }
552 }
553 return $warnings;
554 }
555
556 /**
557 * Perform the actual upload. Returns a suitable result array on success;
558 * dies on failure.
559 *
560 * @param array $warnings Array of Api upload warnings
561 * @return array
562 */
563 protected function performUpload( $warnings ) {
564 // Use comment as initial page text by default
565 if ( is_null( $this->mParams['text'] ) ) {
566 $this->mParams['text'] = $this->mParams['comment'];
567 }
568
569 /** @var $file File */
570 $file = $this->mUpload->getLocalFile();
571 $watch = $this->getWatchlistValue( $this->mParams['watchlist'], $file->getTitle() );
572
573 // Deprecated parameters
574 if ( $this->mParams['watch'] ) {
575 $watch = true;
576 }
577
578 // No errors, no warnings: do the upload
579 if ( $this->mParams['async'] ) {
580 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
581 if ( $progress && $progress['result'] === 'Poll' ) {
582 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
583 }
584 UploadBase::setSessionStatus(
585 $this->mParams['filekey'],
586 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
587 );
588 $ok = JobQueueGroup::singleton()->push( new PublishStashedFileJob(
589 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
590 array(
591 'filename' => $this->mParams['filename'],
592 'filekey' => $this->mParams['filekey'],
593 'comment' => $this->mParams['comment'],
594 'text' => $this->mParams['text'],
595 'watch' => $watch,
596 'session' => $this->getContext()->exportSession()
597 )
598 ) );
599 if ( $ok ) {
600 $result['result'] = 'Poll';
601 } else {
602 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
603 $this->dieUsage(
604 "Failed to start PublishStashedFile.php", 'publishfailed' );
605 }
606 } else {
607 /** @var $status Status */
608 $status = $this->mUpload->performUpload( $this->mParams['comment'],
609 $this->mParams['text'], $watch, $this->getUser() );
610
611 if ( !$status->isGood() ) {
612 $error = $status->getErrorsArray();
613
614 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
615 // The upload can not be performed right now, because the user
616 // requested so
617 return array(
618 'result' => 'Queued',
619 'statuskey' => $error[0][1],
620 );
621 } else {
622 $this->getResult()->setIndexedTagName( $error, 'error' );
623
624 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
625 }
626 }
627 $result['result'] = 'Success';
628 }
629
630 $result['filename'] = $file->getName();
631 if ( $warnings && count( $warnings ) > 0 ) {
632 $result['warnings'] = $warnings;
633 }
634
635 return $result;
636 }
637
638 /**
639 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
640 */
641 protected function checkAsyncDownloadEnabled() {
642 global $wgAllowAsyncCopyUploads;
643 if ( !$wgAllowAsyncCopyUploads ) {
644 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
645 }
646 }
647
648 public function mustBePosted() {
649 return true;
650 }
651
652 public function isWriteMode() {
653 return true;
654 }
655
656 public function getAllowedParams() {
657 $params = array(
658 'filename' => array(
659 ApiBase::PARAM_TYPE => 'string',
660 ),
661 'comment' => array(
662 ApiBase::PARAM_DFLT => ''
663 ),
664 'text' => null,
665 'token' => array(
666 ApiBase::PARAM_TYPE => 'string',
667 ApiBase::PARAM_REQUIRED => true
668 ),
669 'watch' => array(
670 ApiBase::PARAM_DFLT => false,
671 ApiBase::PARAM_DEPRECATED => true,
672 ),
673 'watchlist' => array(
674 ApiBase::PARAM_DFLT => 'preferences',
675 ApiBase::PARAM_TYPE => array(
676 'watch',
677 'preferences',
678 'nochange'
679 ),
680 ),
681 'ignorewarnings' => false,
682 'file' => array(
683 ApiBase::PARAM_TYPE => 'upload',
684 ),
685 'url' => null,
686 'filekey' => null,
687 'sessionkey' => array(
688 ApiBase::PARAM_DFLT => null,
689 ApiBase::PARAM_DEPRECATED => true,
690 ),
691 'stash' => false,
692
693 'filesize' => null,
694 'offset' => null,
695 'chunk' => array(
696 ApiBase::PARAM_TYPE => 'upload',
697 ),
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 }