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