Several minor fixes.
[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 $result = array();
188
189 $result['result'] = 'Continue';
190 if ( $warnings && count( $warnings ) > 0 ) {
191 $result['warnings'] = $warnings;
192 }
193 $request = $this->getMain()->getRequest();
194 $chunkPath = $request->getFileTempname( 'chunk' );
195 $chunkSize = $request->getUpload( 'chunk' )->getSize();
196 if ( $this->mParams['offset'] == 0 ) {
197 $filekey = $this->performStash();
198 } else {
199 $filekey = $this->mParams['filekey'];
200 $status = $this->mUpload->addChunk(
201 $chunkPath, $chunkSize, $this->mParams['offset'] );
202 if ( !$status->isGood() ) {
203 $this->dieUsage( $status->getWikiText(), 'stashfailed' );
204 return array();
205 }
206 }
207
208 // Check we added the last chunk:
209 if ( $this->mParams['offset'] + $chunkSize == $this->mParams['filesize'] ) {
210 if ( $this->mParams['async'] ) {
211 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
212 if ( $progress && $progress['result'] === 'Poll' ) {
213 $this->dieUsage( "Chunk assembly already in progress.", 'stashfailed' );
214 }
215 UploadBase::setSessionStatus(
216 $this->mParams['filekey'],
217 array( 'result' => 'Poll',
218 'stage' => 'queued', 'status' => Status::newGood() )
219 );
220 $ok = JobQueueGroup::singleton()->push( new AssembleUploadChunksJob(
221 Title::makeTitle( NS_FILE, $this->mParams['filekey'] ),
222 array(
223 'filename' => $this->mParams['filename'],
224 'filekey' => $this->mParams['filekey'],
225 'session' => $this->getRequest()->exportUserSession(),
226 'userid' => $this->getUser()->getId()
227 )
228 ) );
229 if ( $ok ) {
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 // The fully concatenated file has a new filekey. So remove
244 // the old filekey and fetch the new one.
245 $this->mUpload->stash->removeFile( $filekey );
246 $filekey = $this->mUpload->getLocalFile()->getFileKey();
247
248 $result['result'] = 'Success';
249 }
250 }
251 $result['filekey'] = $filekey;
252 $result['offset'] = $this->mParams['offset'] + $chunkSize;
253 return $result;
254 }
255
256 /**
257 * Stash the file and return the file key
258 * Also re-raises exceptions with slightly more informative message strings (useful for API)
259 * @throws MWException
260 * @return String file key
261 */
262 private function performStash() {
263 try {
264 $stashFile = $this->mUpload->stashFile();
265
266 if ( !$stashFile ) {
267 throw new MWException( 'Invalid stashed file' );
268 }
269 $fileKey = $stashFile->getFileKey();
270 } catch ( MWException $e ) {
271 $message = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
272 wfDebug( __METHOD__ . ' ' . $message . "\n" );
273 throw new MWException( $message );
274 }
275 return $fileKey;
276 }
277
278 /**
279 * Throw an error that the user can recover from by providing a better
280 * value for $parameter
281 *
282 * @param $error array Error array suitable for passing to dieUsageMsg()
283 * @param $parameter string Parameter that needs revising
284 * @param $data array Optional extra data to pass to the user
285 * @throws UsageException
286 */
287 private function dieRecoverableError( $error, $parameter, $data = array() ) {
288 try {
289 $data['filekey'] = $this->performStash();
290 $data['sessionkey'] = $data['filekey'];
291 } catch ( MWException $e ) {
292 $data['stashfailed'] = $e->getMessage();
293 }
294 $data['invalidparameter'] = $parameter;
295
296 $parsed = $this->parseMsg( $error );
297 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $data );
298 }
299
300 /**
301 * Select an upload module and set it to mUpload. Dies on failure. If the
302 * request was a status request and not a true upload, returns false;
303 * otherwise true
304 *
305 * @return bool
306 */
307 protected function selectUploadModule() {
308 $request = $this->getMain()->getRequest();
309
310 // chunk or one and only one of the following parameters is needed
311 if ( !$this->mParams['chunk'] ) {
312 $this->requireOnlyOneParameter( $this->mParams,
313 'filekey', 'file', 'url', 'statuskey' );
314 }
315
316 // Status report for "upload to stash"/"upload from stash"
317 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
318 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
319 if ( !$progress ) {
320 $this->dieUsage( 'No result in status data', 'missingresult' );
321 } elseif ( !$progress['status']->isGood() ) {
322 $this->dieUsage( $progress['status']->getWikiText(), 'stashfailed' );
323 }
324 if ( isset( $progress['status']->value['verification'] ) ) {
325 $this->checkVerification( $progress['status']->value['verification'] );
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 // This will not download the temp file in initialize() in async mode.
378 // We still have enough information to call checkWarnings() and such.
379 $this->mUpload->initialize(
380 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
381 );
382 } elseif ( isset( $this->mParams['file'] ) ) {
383 $this->mUpload = new UploadFromFile();
384 $this->mUpload->initialize(
385 $this->mParams['filename'],
386 $request->getUpload( 'file' )
387 );
388 } elseif ( isset( $this->mParams['url'] ) ) {
389 // Make sure upload by URL is enabled:
390 if ( !UploadFromUrl::isEnabled() ) {
391 $this->dieUsageMsg( 'copyuploaddisabled' );
392 }
393
394 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
395 $this->dieUsageMsg( 'copyuploadbaddomain' );
396 }
397
398 $async = false;
399 if ( $this->mParams['asyncdownload'] ) {
400 $this->checkAsyncDownloadEnabled();
401
402 if ( $this->mParams['leavemessage'] && !$this->mParams['ignorewarnings'] ) {
403 $this->dieUsage( 'Using leavemessage without ignorewarnings is not supported',
404 'missing-ignorewarnings' );
405 }
406
407 if ( $this->mParams['leavemessage'] ) {
408 $async = 'async-leavemessage';
409 } else {
410 $async = 'async';
411 }
412 }
413 $this->mUpload = new UploadFromUrl;
414 $this->mUpload->initialize( $this->mParams['filename'],
415 $this->mParams['url'], $async );
416 }
417
418 return true;
419 }
420
421 /**
422 * Checks that the user has permissions to perform this upload.
423 * Dies with usage message on inadequate permissions.
424 * @param $user User The user to check.
425 */
426 protected function checkPermissions( $user ) {
427 // Check whether the user has the appropriate permissions to upload anyway
428 $permission = $this->mUpload->isAllowed( $user );
429
430 if ( $permission !== true ) {
431 if ( !$user->isLoggedIn() ) {
432 $this->dieUsageMsg( array( 'mustbeloggedin', 'upload' ) );
433 } else {
434 $this->dieUsageMsg( 'badaccess-groups' );
435 }
436 }
437 }
438
439 /**
440 * Performs file verification, dies on error.
441 */
442 protected function verifyUpload( ) {
443 $verification = $this->mUpload->verifyUpload( );
444 if ( $verification['status'] === UploadBase::OK ) {
445 return;
446 } else {
447 return $this->checkVerification( $verification );
448 }
449 }
450
451 /**
452 * Performs file verification, dies on error.
453 */
454 protected function checkVerification( array $verification ) {
455 global $wgFileExtensions;
456
457 // TODO: Move them to ApiBase's message map
458 switch( $verification['status'] ) {
459 // Recoverable errors
460 case UploadBase::MIN_LENGTH_PARTNAME:
461 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
462 break;
463 case UploadBase::ILLEGAL_FILENAME:
464 $this->dieRecoverableError( 'illegal-filename', 'filename',
465 array( 'filename' => $verification['filtered'] ) );
466 break;
467 case UploadBase::FILENAME_TOO_LONG:
468 $this->dieRecoverableError( 'filename-toolong', 'filename' );
469 break;
470 case UploadBase::FILETYPE_MISSING:
471 $this->dieRecoverableError( 'filetype-missing', 'filename' );
472 break;
473 case UploadBase::WINDOWS_NONASCII_FILENAME:
474 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
475 break;
476
477 // Unrecoverable errors
478 case UploadBase::EMPTY_FILE:
479 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
480 break;
481 case UploadBase::FILE_TOO_LARGE:
482 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
483 break;
484
485 case UploadBase::FILETYPE_BADTYPE:
486 $extradata = array(
487 'filetype' => $verification['finalExt'],
488 'allowed' => $wgFileExtensions
489 );
490 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
491
492 $msg = "Filetype not permitted: ";
493 if ( isset( $verification['blacklistedExt'] ) ) {
494 $msg .= join( ', ', $verification['blacklistedExt'] );
495 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
496 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
497 } else {
498 $msg .= $verification['finalExt'];
499 }
500 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
501 break;
502 case UploadBase::VERIFICATION_ERROR:
503 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
504 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
505 0, array( 'details' => $verification['details'] ) );
506 break;
507 case UploadBase::HOOK_ABORTED:
508 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
509 'hookaborted', 0, array( 'error' => $verification['error'] ) );
510 break;
511 default:
512 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
513 0, array( 'code' => $verification['status'] ) );
514 break;
515 }
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 /**
558 * Perform the actual upload. Returns a suitable result array on success;
559 * dies on failure.
560 *
561 * @param $warnings array Array of Api upload warnings
562 * @return array
563 */
564 protected function performUpload( $warnings ) {
565 // Use comment as initial page text by default
566 if ( is_null( $this->mParams['text'] ) ) {
567 $this->mParams['text'] = $this->mParams['comment'];
568 }
569
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->getRequest()->exportUserSession(),
597 'userid' => $this->getUser()->getId()
598 )
599 ) );
600 if ( $ok ) {
601 $result['result'] = 'Poll';
602 } else {
603 UploadBase::setSessionStatus( $this->mParams['filekey'], false );
604 $this->dieUsage(
605 "Failed to start PublishStashedFile.php", 'publishfailed' );
606 }
607 } else {
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' => null,
683 'url' => null,
684 'filekey' => null,
685 'sessionkey' => array(
686 ApiBase::PARAM_DFLT => null,
687 ApiBase::PARAM_DEPRECATED => true,
688 ),
689 'stash' => false,
690
691 'filesize' => null,
692 'offset' => null,
693 'chunk' => null,
694
695 'async' => false,
696 'asyncdownload' => false,
697 'leavemessage' => false,
698 'statuskey' => null,
699 'checkstatus' => false,
700 );
701
702 return $params;
703 }
704
705 public function getParamDescription() {
706 $params = array(
707 'filename' => 'Target filename',
708 'token' => 'Edit token. You can get one of these through prop=info',
709 'comment' => 'Upload comment. Also used as the initial page text for new files if "text" is not specified',
710 'text' => 'Initial page text for new files',
711 'watch' => 'Watch the page',
712 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
713 'ignorewarnings' => 'Ignore any warnings',
714 'file' => 'File contents',
715 'url' => 'URL to fetch the file from',
716 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
717 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
718 'stash' => 'If set, the server will not add the file to the repository and stash it temporarily.',
719
720 'chunk' => 'Chunk contents',
721 'offset' => 'Offset of chunk in bytes',
722 'filesize' => 'Filesize of entire upload',
723
724 'async' => 'Make potentially large file operations asynchronous when possible',
725 'asyncdownload' => 'Make fetching a URL asynchronous',
726 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
727 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
728 'checkstatus' => 'Only fetch the upload status for the given file key',
729 );
730
731 return $params;
732
733 }
734
735 public function getResultProperties() {
736 return array(
737 '' => array(
738 'result' => array(
739 ApiBase::PROP_TYPE => array(
740 'Success',
741 'Warning',
742 'Continue',
743 'Queued'
744 ),
745 ),
746 'filekey' => array(
747 ApiBase::PROP_TYPE => 'string',
748 ApiBase::PROP_NULLABLE => true
749 ),
750 'sessionkey' => array(
751 ApiBase::PROP_TYPE => 'string',
752 ApiBase::PROP_NULLABLE => true
753 ),
754 'offset' => array(
755 ApiBase::PROP_TYPE => 'integer',
756 ApiBase::PROP_NULLABLE => true
757 ),
758 'statuskey' => array(
759 ApiBase::PROP_TYPE => 'string',
760 ApiBase::PROP_NULLABLE => true
761 ),
762 'filename' => array(
763 ApiBase::PROP_TYPE => 'string',
764 ApiBase::PROP_NULLABLE => true
765 )
766 )
767 );
768 }
769
770 public function getDescription() {
771 return array(
772 'Upload a file, or get the status of pending uploads. Several methods are available:',
773 ' * Upload file contents directly, using the "file" parameter',
774 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
775 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
776 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
777 'sending the "file". Also you must get and send an edit token before doing any upload stuff'
778 );
779 }
780
781 public function getPossibleErrors() {
782 return array_merge( parent::getPossibleErrors(),
783 $this->getRequireOnlyOneParameterErrorMessages( array( 'filekey', 'file', 'url', 'statuskey' ) ),
784 array(
785 array( 'uploaddisabled' ),
786 array( 'invalid-file-key' ),
787 array( 'uploaddisabled' ),
788 array( 'mustbeloggedin', 'upload' ),
789 array( 'badaccess-groups' ),
790 array( 'code' => 'fetchfileerror', 'info' => '' ),
791 array( 'code' => 'nomodule', 'info' => 'No upload module set' ),
792 array( 'code' => 'empty-file', 'info' => 'The file you submitted was empty' ),
793 array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
794 array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
795 array( 'code' => 'overwrite', 'info' => 'Overwriting an existing file is not allowed' ),
796 array( 'code' => 'stashfailed', 'info' => 'Stashing temporary file failed' ),
797 array( 'code' => 'publishfailed', 'info' => 'Publishing of stashed file failed' ),
798 array( 'code' => 'internal-error', 'info' => 'An internal error occurred' ),
799 array( 'code' => 'asynccopyuploaddisabled', 'info' => 'Asynchronous copy uploads disabled' ),
800 array( 'fileexists-forbidden' ),
801 array( 'fileexists-shared-forbidden' ),
802 )
803 );
804 }
805
806 public function needsToken() {
807 return true;
808 }
809
810 public function getTokenSalt() {
811 return '';
812 }
813
814 public function getExamples() {
815 return array(
816 'api.php?action=upload&filename=Wiki.png&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
817 => 'Upload from a URL',
818 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
819 => 'Complete an upload that failed due to warnings',
820 );
821 }
822
823 public function getHelpUrls() {
824 return 'https://www.mediawiki.org/wiki/API:Upload';
825 }
826 }