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