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