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