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