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