Merge "Don't set the session name in CLI or when sessions are deactivated"
[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 */
470 protected function checkVerification( array $verification ) {
471 // @todo Move them to ApiBase's message map
472 switch ( $verification['status'] ) {
473 // Recoverable errors
474 case UploadBase::MIN_LENGTH_PARTNAME:
475 $this->dieRecoverableError( 'filename-tooshort', 'filename' );
476 break;
477 case UploadBase::ILLEGAL_FILENAME:
478 $this->dieRecoverableError( 'illegal-filename', 'filename',
479 array( 'filename' => $verification['filtered'] ) );
480 break;
481 case UploadBase::FILENAME_TOO_LONG:
482 $this->dieRecoverableError( 'filename-toolong', 'filename' );
483 break;
484 case UploadBase::FILETYPE_MISSING:
485 $this->dieRecoverableError( 'filetype-missing', 'filename' );
486 break;
487 case UploadBase::WINDOWS_NONASCII_FILENAME:
488 $this->dieRecoverableError( 'windows-nonascii-filename', 'filename' );
489 break;
490
491 // Unrecoverable errors
492 case UploadBase::EMPTY_FILE:
493 $this->dieUsage( 'The file you submitted was empty', 'empty-file' );
494 break;
495 case UploadBase::FILE_TOO_LARGE:
496 $this->dieUsage( 'The file you submitted was too large', 'file-too-large' );
497 break;
498
499 case UploadBase::FILETYPE_BADTYPE:
500 $extradata = array(
501 'filetype' => $verification['finalExt'],
502 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
503 );
504 $this->getResult()->setIndexedTagName( $extradata['allowed'], 'ext' );
505
506 $msg = "Filetype not permitted: ";
507 if ( isset( $verification['blacklistedExt'] ) ) {
508 $msg .= join( ', ', $verification['blacklistedExt'] );
509 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
510 $this->getResult()->setIndexedTagName( $extradata['blacklisted'], 'ext' );
511 } else {
512 $msg .= $verification['finalExt'];
513 }
514 $this->dieUsage( $msg, 'filetype-banned', 0, $extradata );
515 break;
516 case UploadBase::VERIFICATION_ERROR:
517 $this->getResult()->setIndexedTagName( $verification['details'], 'detail' );
518 $this->dieUsage( 'This file did not pass file verification', 'verification-error',
519 0, array( 'details' => $verification['details'] ) );
520 break;
521 case UploadBase::HOOK_ABORTED:
522 $this->dieUsage( "The modification you tried to make was aborted by an extension hook",
523 'hookaborted', 0, array( 'error' => $verification['error'] ) );
524 break;
525 default:
526 $this->dieUsage( 'An unknown error occurred', 'unknown-error',
527 0, array( 'code' => $verification['status'] ) );
528 break;
529 }
530 }
531
532 /**
533 * Check warnings.
534 * Returns a suitable array for inclusion into API results if there were warnings
535 * Returns the empty array if there were no warnings
536 *
537 * @return array
538 */
539 protected function getApiWarnings() {
540 $warnings = $this->mUpload->checkWarnings();
541
542 return $this->transformWarnings( $warnings );
543 }
544
545 protected function transformWarnings( $warnings ) {
546 if ( $warnings ) {
547 // Add indices
548 $result = $this->getResult();
549 $result->setIndexedTagName( $warnings, 'warning' );
550
551 if ( isset( $warnings['duplicate'] ) ) {
552 $dupes = array();
553 /** @var File $dupe */
554 foreach ( $warnings['duplicate'] as $dupe ) {
555 $dupes[] = $dupe->getName();
556 }
557 $result->setIndexedTagName( $dupes, 'duplicate' );
558 $warnings['duplicate'] = $dupes;
559 }
560
561 if ( isset( $warnings['exists'] ) ) {
562 $warning = $warnings['exists'];
563 unset( $warnings['exists'] );
564 /** @var LocalFile $localFile */
565 $localFile = isset( $warning['normalizedFile'] )
566 ? $warning['normalizedFile']
567 : $warning['file'];
568 $warnings[$warning['warning']] = $localFile->getName();
569 }
570 }
571
572 return $warnings;
573 }
574
575 /**
576 * Perform the actual upload. Returns a suitable result array on success;
577 * dies on failure.
578 *
579 * @param array $warnings Array of Api upload warnings
580 * @return array
581 */
582 protected function performUpload( $warnings ) {
583 // Use comment as initial page text by default
584 if ( is_null( $this->mParams['text'] ) ) {
585 $this->mParams['text'] = $this->mParams['comment'];
586 }
587
588 /** @var $file File */
589 $file = $this->mUpload->getLocalFile();
590
591 // For preferences mode, we want to watch if 'watchdefault' is set or
592 // if the *file* doesn't exist and 'watchcreations' is set. But
593 // getWatchlistValue()'s automatic handling checks if the *title*
594 // exists or not, so we need to check both prefs manually.
595 $watch = $this->getWatchlistValue(
596 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
597 );
598 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
599 $watch = $this->getWatchlistValue(
600 $this->mParams['watchlist'], $file->getTitle(), 'watchcreations'
601 );
602 }
603
604 // Deprecated parameters
605 if ( $this->mParams['watch'] ) {
606 $watch = true;
607 }
608
609 // No errors, no warnings: do the upload
610 if ( $this->mParams['async'] ) {
611 $progress = UploadBase::getSessionStatus( $this->mParams['filekey'] );
612 if ( $progress && $progress['result'] === 'Poll' ) {
613 $this->dieUsage( "Upload from stash already in progress.", 'publishfailed' );
614 }
615 UploadBase::setSessionStatus(
616 $this->mParams['filekey'],
617 array( 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() )
618 );
619 JobQueueGroup::singleton()->push( new PublishStashedFileJob(
620 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
621 array(
622 'filename' => $this->mParams['filename'],
623 'filekey' => $this->mParams['filekey'],
624 'comment' => $this->mParams['comment'],
625 'text' => $this->mParams['text'],
626 'watch' => $watch,
627 'session' => $this->getContext()->exportSession()
628 )
629 ) );
630 $result['result'] = 'Poll';
631 } else {
632 /** @var $status Status */
633 $status = $this->mUpload->performUpload( $this->mParams['comment'],
634 $this->mParams['text'], $watch, $this->getUser() );
635
636 if ( !$status->isGood() ) {
637 $error = $status->getErrorsArray();
638
639 if ( count( $error ) == 1 && $error[0][0] == 'async' ) {
640 // The upload can not be performed right now, because the user
641 // requested so
642 return array(
643 'result' => 'Queued',
644 'statuskey' => $error[0][1],
645 );
646 }
647
648 $this->getResult()->setIndexedTagName( $error, 'error' );
649 $this->dieUsage( 'An internal error occurred', 'internal-error', 0, $error );
650 }
651 $result['result'] = 'Success';
652 }
653
654 $result['filename'] = $file->getName();
655 if ( $warnings && count( $warnings ) > 0 ) {
656 $result['warnings'] = $warnings;
657 }
658
659 return $result;
660 }
661
662 /**
663 * Checks if asynchronous copy uploads are enabled and throws an error if they are not.
664 */
665 protected function checkAsyncDownloadEnabled() {
666 if ( !$this->getConfig()->get( 'AllowAsyncCopyUploads' ) ) {
667 $this->dieUsage( 'Asynchronous copy uploads disabled', 'asynccopyuploaddisabled' );
668 }
669 }
670
671 public function mustBePosted() {
672 return true;
673 }
674
675 public function isWriteMode() {
676 return true;
677 }
678
679 public function getAllowedParams() {
680 $params = array(
681 'filename' => array(
682 ApiBase::PARAM_TYPE => 'string',
683 ),
684 'comment' => array(
685 ApiBase::PARAM_DFLT => ''
686 ),
687 'text' => null,
688 'token' => array(
689 ApiBase::PARAM_TYPE => 'string',
690 ApiBase::PARAM_REQUIRED => true
691 ),
692 'watch' => array(
693 ApiBase::PARAM_DFLT => false,
694 ApiBase::PARAM_DEPRECATED => true,
695 ),
696 'watchlist' => array(
697 ApiBase::PARAM_DFLT => 'preferences',
698 ApiBase::PARAM_TYPE => array(
699 'watch',
700 'preferences',
701 'nochange'
702 ),
703 ),
704 'ignorewarnings' => false,
705 'file' => array(
706 ApiBase::PARAM_TYPE => 'upload',
707 ),
708 'url' => null,
709 'filekey' => null,
710 'sessionkey' => array(
711 ApiBase::PARAM_DFLT => null,
712 ApiBase::PARAM_DEPRECATED => true,
713 ),
714 'stash' => false,
715
716 'filesize' => null,
717 'offset' => null,
718 'chunk' => array(
719 ApiBase::PARAM_TYPE => 'upload',
720 ),
721
722 'async' => false,
723 'asyncdownload' => false,
724 'leavemessage' => false,
725 'statuskey' => null,
726 'checkstatus' => false,
727 );
728
729 return $params;
730 }
731
732 public function getParamDescription() {
733 $params = array(
734 'filename' => 'Target filename',
735 'token' => 'Edit token. You can get one of these through prop=info',
736 'comment' => 'Upload comment. Also used as the initial page text for new ' .
737 'files if "text" is not specified',
738 'text' => 'Initial page text for new files',
739 'watch' => 'Watch the page',
740 'watchlist' => 'Unconditionally add or remove the page from your watchlist, ' .
741 'use preferences or do not change watch',
742 'ignorewarnings' => 'Ignore any warnings',
743 'file' => 'File contents',
744 'url' => 'URL to fetch the file from',
745 'filekey' => 'Key that identifies a previous upload that was stashed temporarily.',
746 'sessionkey' => 'Same as filekey, maintained for backward compatibility.',
747 'stash' => 'If set, the server will not add the file to the repository ' .
748 'and stash it temporarily.',
749
750 'chunk' => 'Chunk contents',
751 'offset' => 'Offset of chunk in bytes',
752 'filesize' => 'Filesize of entire upload',
753
754 'async' => 'Make potentially large file operations asynchronous when possible',
755 'asyncdownload' => 'Make fetching a URL asynchronous',
756 'leavemessage' => 'If asyncdownload is used, leave a message on the user talk page if finished',
757 'statuskey' => 'Fetch the upload status for this file key (upload by URL)',
758 'checkstatus' => 'Only fetch the upload status for the given file key',
759 );
760
761 return $params;
762 }
763
764 public function getDescription() {
765 return array(
766 'Upload a file, or get the status of pending uploads. Several methods are available:',
767 ' * Upload file contents directly, using the "file" parameter',
768 ' * Have the MediaWiki server fetch a file from a URL, using the "url" parameter',
769 ' * Complete an earlier upload that failed due to warnings, using the "filekey" parameter',
770 'Note that the HTTP POST must be done as a file upload (i.e. using multipart/form-data) when',
771 'sending the "file". Also you must get and send an edit token before doing any upload stuff.'
772 );
773 }
774
775 public function needsToken() {
776 return true;
777 }
778
779 public function getTokenSalt() {
780 return '';
781 }
782
783 public function getExamples() {
784 return array(
785 'api.php?action=upload&filename=Wiki.png' .
786 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png'
787 => 'Upload from a URL',
788 'api.php?action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1'
789 => 'Complete an upload that failed due to warnings',
790 );
791 }
792
793 public function getHelpUrls() {
794 return 'https://www.mediawiki.org/wiki/API:Upload';
795 }
796 }