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