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