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