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