Merge "Add another Bengali synonym for HIDDENCAT in MessagesBn.php"
[lhc/web/wiklou.git] / includes / api / ApiUpload.php
1 <?php
2 /**
3 * Copyright © 2008 - 2010 Bryan Tong Minh <Bryan.TongMinh@Gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * @ingroup API
25 */
26 class ApiUpload extends ApiBase {
27 /** @var UploadBase|UploadFromChunks */
28 protected $mUpload = null;
29
30 protected $mParams;
31
32 public function execute() {
33 // Check whether upload is enabled
34 if ( !UploadBase::isEnabled() ) {
35 $this->dieWithError( 'uploaddisabled' );
36 }
37
38 $user = $this->getUser();
39
40 // Parameter handling
41 $this->mParams = $this->extractRequestParams();
42 $request = $this->getMain()->getRequest();
43 // Check if async mode is actually supported (jobs done in cli mode)
44 $this->mParams['async'] = ( $this->mParams['async'] &&
45 $this->getConfig()->get( 'EnableAsyncUploads' ) );
46 // Add the uploaded file to the params array
47 $this->mParams['file'] = $request->getFileName( 'file' );
48 $this->mParams['chunk'] = $request->getFileName( 'chunk' );
49
50 // Copy the session key to the file key, for backward compatibility.
51 if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
52 $this->mParams['filekey'] = $this->mParams['sessionkey'];
53 }
54
55 // Select an upload module
56 try {
57 if ( !$this->selectUploadModule() ) {
58 return; // not a true upload, but a status request or similar
59 } elseif ( !isset( $this->mUpload ) ) {
60 $this->dieDebug( __METHOD__, 'No upload module set' );
61 }
62 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
63 $this->dieStatus( $this->handleStashException( $e ) );
64 }
65
66 // First check permission to upload
67 $this->checkPermissions( $user );
68
69 // Fetch the file (usually a no-op)
70 /** @var Status $status */
71 $status = $this->mUpload->fetchFile();
72 if ( !$status->isGood() ) {
73 $this->dieStatus( $status );
74 }
75
76 // Check if the uploaded file is sane
77 wfDebug( __METHOD__ . " about to verify\n" );
78 $this->verifyUpload();
79
80 // Check if the user has the rights to modify or overwrite the requested title
81 // (This check is irrelevant if stashing is already requested, since the errors
82 // can always be fixed by changing the title)
83 if ( !$this->mParams['stash'] ) {
84 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
85 if ( $permErrors !== true ) {
86 $this->dieRecoverableError( $permErrors, 'filename' );
87 }
88 }
89
90 // Get the result based on the current upload context:
91 try {
92 $result = $this->getContextResult();
93 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
94 $this->dieStatus( $this->handleStashException( $e ) );
95 }
96 $this->getResult()->addValue( null, $this->getModuleName(), $result );
97
98 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
99 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
100 if ( $result['result'] === 'Success' ) {
101 $imageinfo = $this->mUpload->getImageInfo( $this->getResult() );
102 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
103 }
104
105 // Cleanup any temporary mess
106 $this->mUpload->cleanupTempFile();
107 }
108
109 /**
110 * Get an upload result based on upload context
111 * @return array
112 */
113 private function getContextResult() {
114 $warnings = $this->getApiWarnings();
115 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
116 // Get warnings formatted in result array format
117 return $this->getWarningsResult( $warnings );
118 } elseif ( $this->mParams['chunk'] ) {
119 // Add chunk, and get result
120 return $this->getChunkResult( $warnings );
121 } elseif ( $this->mParams['stash'] ) {
122 // Stash the file and get stash result
123 return $this->getStashResult( $warnings );
124 }
125
126 // Check throttle after we've handled warnings
127 if ( UploadBase::isThrottled( $this->getUser() )
128 ) {
129 $this->dieWithError( 'apierror-ratelimited' );
130 }
131
132 // This is the most common case -- a normal upload with no warnings
133 // performUpload will return a formatted properly for the API with status
134 return $this->performUpload( $warnings );
135 }
136
137 /**
138 * Get Stash Result, throws an exception if the file could not be stashed.
139 * @param array $warnings Array of Api upload warnings
140 * @return array
141 */
142 private function getStashResult( $warnings ) {
143 $result = [];
144 $result['result'] = 'Success';
145 if ( $warnings && count( $warnings ) > 0 ) {
146 $result['warnings'] = $warnings;
147 }
148 // Some uploads can request they be stashed, so as not to publish them immediately.
149 // In this case, a failure to stash ought to be fatal
150 $this->performStash( 'critical', $result );
151
152 return $result;
153 }
154
155 /**
156 * Get Warnings Result
157 * @param array $warnings Array of Api upload warnings
158 * @return array
159 */
160 private function getWarningsResult( $warnings ) {
161 $result = [];
162 $result['result'] = 'Warning';
163 $result['warnings'] = $warnings;
164 // in case the warnings can be fixed with some further user action, let's stash this upload
165 // and return a key they can use to restart it
166 $this->performStash( 'optional', $result );
167
168 return $result;
169 }
170
171 /**
172 * Get the result of a chunk upload.
173 * @param array $warnings Array of Api upload warnings
174 * @return array
175 */
176 private function getChunkResult( $warnings ) {
177 $result = [];
178
179 if ( $warnings && count( $warnings ) > 0 ) {
180 $result['warnings'] = $warnings;
181 }
182
183 $request = $this->getMain()->getRequest();
184 $chunkPath = $request->getFileTempname( 'chunk' );
185 $chunkSize = $request->getUpload( 'chunk' )->getSize();
186 $totalSoFar = $this->mParams['offset'] + $chunkSize;
187 $minChunkSize = $this->getConfig()->get( 'MinUploadChunkSize' );
188
189 // Sanity check sizing
190 if ( $totalSoFar > $this->mParams['filesize'] ) {
191 $this->dieWithError( 'apierror-invalid-chunk' );
192 }
193
194 // Enforce minimum chunk size
195 if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
196 $this->dieWithError( [ 'apierror-chunk-too-small', Message::numParam( $minChunkSize ) ] );
197 }
198
199 if ( $this->mParams['offset'] == 0 ) {
200 $filekey = $this->performStash( 'critical' );
201 } else {
202 $filekey = $this->mParams['filekey'];
203
204 // Don't allow further uploads to an already-completed session
205 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
206 if ( !$progress ) {
207 // Probably can't get here, but check anyway just in case
208 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
209 } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
210 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
211 }
212
213 $status = $this->mUpload->addChunk(
214 $chunkPath, $chunkSize, $this->mParams['offset'] );
215 if ( !$status->isGood() ) {
216 $extradata = [
217 'offset' => $this->mUpload->getOffset(),
218 ];
219
220 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
221 }
222 }
223
224 // Check we added the last chunk:
225 if ( $totalSoFar == $this->mParams['filesize'] ) {
226 if ( $this->mParams['async'] ) {
227 UploadBase::setSessionStatus(
228 $this->getUser(),
229 $filekey,
230 [ 'result' => 'Poll',
231 'stage' => 'queued', 'status' => Status::newGood() ]
232 );
233 JobQueueGroup::singleton()->push( new AssembleUploadChunksJob(
234 Title::makeTitle( NS_FILE, $filekey ),
235 [
236 'filename' => $this->mParams['filename'],
237 'filekey' => $filekey,
238 'session' => $this->getContext()->exportSession()
239 ]
240 ) );
241 $result['result'] = 'Poll';
242 $result['stage'] = 'queued';
243 } else {
244 $status = $this->mUpload->concatenateChunks();
245 if ( !$status->isGood() ) {
246 UploadBase::setSessionStatus(
247 $this->getUser(),
248 $filekey,
249 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
250 );
251 $this->dieStatusWithCode( $status, 'stashfailed' );
252 }
253
254 // We can only get warnings like 'duplicate' after concatenating the chunks
255 $warnings = $this->getApiWarnings();
256 if ( $warnings ) {
257 $result['warnings'] = $warnings;
258 }
259
260 // The fully concatenated file has a new filekey. So remove
261 // the old filekey and fetch the new one.
262 UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
263 $this->mUpload->stash->removeFile( $filekey );
264 $filekey = $this->mUpload->getStashFile()->getFileKey();
265
266 $result['result'] = 'Success';
267 }
268 } else {
269 UploadBase::setSessionStatus(
270 $this->getUser(),
271 $filekey,
272 [
273 'result' => 'Continue',
274 'stage' => 'uploading',
275 'offset' => $totalSoFar,
276 'status' => Status::newGood(),
277 ]
278 );
279 $result['result'] = 'Continue';
280 $result['offset'] = $totalSoFar;
281 }
282
283 $result['filekey'] = $filekey;
284
285 return $result;
286 }
287
288 /**
289 * Stash the file and add the file key, or error information if it fails, to the data.
290 *
291 * @param string $failureMode What to do on failure to stash:
292 * - When 'critical', use dieStatus() to produce an error response and throw an exception.
293 * Use this when stashing the file was the primary purpose of the API request.
294 * - When 'optional', only add a 'stashfailed' key to the data and return null.
295 * Use this when some error happened for a non-stash upload and we're stashing the file
296 * only to save the client the trouble of re-uploading it.
297 * @param array &$data API result to which to add the information
298 * @return string|null File key
299 */
300 private function performStash( $failureMode, &$data = null ) {
301 $isPartial = (bool)$this->mParams['chunk'];
302 try {
303 $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
304
305 if ( $status->isGood() && !$status->getValue() ) {
306 // Not actually a 'good' status...
307 $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
308 }
309 } catch ( Exception $e ) {
310 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
311 wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
312 $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
313 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
314 ) );
315 }
316
317 if ( $status->isGood() ) {
318 $stashFile = $status->getValue();
319 $data['filekey'] = $stashFile->getFileKey();
320 // Backwards compatibility
321 $data['sessionkey'] = $data['filekey'];
322 return $data['filekey'];
323 }
324
325 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
326 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
327 // Statuses for it. Just extract the exception details and parse them ourselves.
328 list( $exceptionType, $message ) = $status->getMessage()->getParams();
329 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
330 wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
331 }
332
333 // Bad status
334 if ( $failureMode !== 'optional' ) {
335 $this->dieStatus( $status );
336 } else {
337 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
338 return null;
339 }
340 }
341
342 /**
343 * Throw an error that the user can recover from by providing a better
344 * value for $parameter
345 *
346 * @param array $errors Array of Message objects, message keys, key+param
347 * arrays, or StatusValue::getErrors()-style arrays
348 * @param string|null $parameter Parameter that needs revising
349 * @throws ApiUsageException
350 */
351 private function dieRecoverableError( $errors, $parameter = null ) {
352 $this->performStash( 'optional', $data );
353
354 if ( $parameter ) {
355 $data['invalidparameter'] = $parameter;
356 }
357
358 $sv = StatusValue::newGood();
359 foreach ( $errors as $error ) {
360 $msg = ApiMessage::create( $error );
361 $msg->setApiData( $msg->getApiData() + $data );
362 $sv->fatal( $msg );
363 }
364 $this->dieStatus( $sv );
365 }
366
367 /**
368 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
369 * IApiMessage.
370 *
371 * @param Status $status
372 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
373 * @param array|null $moreExtraData
374 * @throws ApiUsageException
375 */
376 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
377 $sv = StatusValue::newGood();
378 foreach ( $status->getErrors() as $error ) {
379 $msg = ApiMessage::create( $error, $overrideCode );
380 if ( $moreExtraData ) {
381 $msg->setApiData( $msg->getApiData() + $moreExtraData );
382 }
383 $sv->fatal( $msg );
384 }
385 $this->dieStatus( $sv );
386 }
387
388 /**
389 * Select an upload module and set it to mUpload. Dies on failure. If the
390 * request was a status request and not a true upload, returns false;
391 * otherwise true
392 *
393 * @return bool
394 */
395 protected function selectUploadModule() {
396 $request = $this->getMain()->getRequest();
397
398 // chunk or one and only one of the following parameters is needed
399 if ( !$this->mParams['chunk'] ) {
400 $this->requireOnlyOneParameter( $this->mParams,
401 'filekey', 'file', 'url' );
402 }
403
404 // Status report for "upload to stash"/"upload from stash"
405 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
406 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
407 if ( !$progress ) {
408 $this->dieWithError( 'apierror-upload-missingresult', 'missingresult' );
409 } elseif ( !$progress['status']->isGood() ) {
410 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
411 }
412 if ( isset( $progress['status']->value['verification'] ) ) {
413 $this->checkVerification( $progress['status']->value['verification'] );
414 }
415 if ( isset( $progress['status']->value['warnings'] ) ) {
416 $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
417 if ( $warnings ) {
418 $progress['warnings'] = $warnings;
419 }
420 }
421 unset( $progress['status'] ); // remove Status object
422 $imageinfo = null;
423 if ( isset( $progress['imageinfo'] ) ) {
424 $imageinfo = $progress['imageinfo'];
425 unset( $progress['imageinfo'] );
426 }
427
428 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
429 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
430 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
431 if ( $imageinfo ) {
432 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
433 }
434
435 return false;
436 }
437
438 // The following modules all require the filename parameter to be set
439 if ( is_null( $this->mParams['filename'] ) ) {
440 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
441 }
442
443 if ( $this->mParams['chunk'] ) {
444 // Chunk upload
445 $this->mUpload = new UploadFromChunks( $this->getUser() );
446 if ( isset( $this->mParams['filekey'] ) ) {
447 if ( $this->mParams['offset'] === 0 ) {
448 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
449 }
450
451 // handle new chunk
452 $this->mUpload->continueChunks(
453 $this->mParams['filename'],
454 $this->mParams['filekey'],
455 $request->getUpload( 'chunk' )
456 );
457 } else {
458 if ( $this->mParams['offset'] !== 0 ) {
459 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
460 }
461
462 // handle first chunk
463 $this->mUpload->initialize(
464 $this->mParams['filename'],
465 $request->getUpload( 'chunk' )
466 );
467 }
468 } elseif ( isset( $this->mParams['filekey'] ) ) {
469 // Upload stashed in a previous request
470 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
471 $this->dieWithError( 'apierror-invalid-file-key' );
472 }
473
474 $this->mUpload = new UploadFromStash( $this->getUser() );
475 // This will not download the temp file in initialize() in async mode.
476 // We still have enough information to call checkWarnings() and such.
477 $this->mUpload->initialize(
478 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
479 );
480 } elseif ( isset( $this->mParams['file'] ) ) {
481 // Can't async upload directly from a POSTed file, we'd have to
482 // stash the file and then queue the publish job. The user should
483 // just submit the two API queries to perform those two steps.
484 if ( $this->mParams['async'] ) {
485 $this->dieWithError( 'apierror-cannot-async-upload-file' );
486 }
487
488 $this->mUpload = new UploadFromFile();
489 $this->mUpload->initialize(
490 $this->mParams['filename'],
491 $request->getUpload( 'file' )
492 );
493 } elseif ( isset( $this->mParams['url'] ) ) {
494 // Make sure upload by URL is enabled:
495 if ( !UploadFromUrl::isEnabled() ) {
496 $this->dieWithError( 'copyuploaddisabled' );
497 }
498
499 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
500 $this->dieWithError( 'apierror-copyuploadbaddomain' );
501 }
502
503 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
504 $this->dieWithError( 'apierror-copyuploadbadurl' );
505 }
506
507 $this->mUpload = new UploadFromUrl;
508 $this->mUpload->initialize( $this->mParams['filename'],
509 $this->mParams['url'] );
510 }
511
512 return true;
513 }
514
515 /**
516 * Checks that the user has permissions to perform this upload.
517 * Dies with usage message on inadequate permissions.
518 * @param User $user The user to check.
519 */
520 protected function checkPermissions( $user ) {
521 // Check whether the user has the appropriate permissions to upload anyway
522 $permission = $this->mUpload->isAllowed( $user );
523
524 if ( $permission !== true ) {
525 if ( !$user->isLoggedIn() ) {
526 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
527 }
528
529 $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
530 }
531
532 // Check blocks
533 if ( $user->isBlockedFromUpload() ) {
534 $this->dieBlocked( $user->getBlock() );
535 }
536
537 // Global blocks
538 if ( $user->isBlockedGlobally() ) {
539 $this->dieBlocked( $user->getGlobalBlock() );
540 }
541 }
542
543 /**
544 * Performs file verification, dies on error.
545 */
546 protected function verifyUpload() {
547 $verification = $this->mUpload->verifyUpload();
548 if ( $verification['status'] === UploadBase::OK ) {
549 return;
550 }
551
552 $this->checkVerification( $verification );
553 }
554
555 /**
556 * Performs file verification, dies on error.
557 * @param array $verification
558 */
559 protected function checkVerification( array $verification ) {
560 switch ( $verification['status'] ) {
561 // Recoverable errors
562 case UploadBase::MIN_LENGTH_PARTNAME:
563 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
564 break;
565 case UploadBase::ILLEGAL_FILENAME:
566 $this->dieRecoverableError(
567 [ ApiMessage::create(
568 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
569 ) ], 'filename'
570 );
571 break;
572 case UploadBase::FILENAME_TOO_LONG:
573 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
574 break;
575 case UploadBase::FILETYPE_MISSING:
576 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
577 break;
578 case UploadBase::WINDOWS_NONASCII_FILENAME:
579 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
580 break;
581
582 // Unrecoverable errors
583 case UploadBase::EMPTY_FILE:
584 $this->dieWithError( 'empty-file' );
585 break;
586 case UploadBase::FILE_TOO_LARGE:
587 $this->dieWithError( 'file-too-large' );
588 break;
589
590 case UploadBase::FILETYPE_BADTYPE:
591 $extradata = [
592 'filetype' => $verification['finalExt'],
593 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
594 ];
595 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
596 $msg = [
597 'filetype-banned-type',
598 null, // filled in below
599 Message::listParam( $extensions, 'comma' ),
600 count( $extensions ),
601 null, // filled in below
602 ];
603 ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
604
605 if ( isset( $verification['blacklistedExt'] ) ) {
606 $msg[1] = Message::listParam( $verification['blacklistedExt'], 'comma' );
607 $msg[4] = count( $verification['blacklistedExt'] );
608 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
609 ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
610 } else {
611 $msg[1] = $verification['finalExt'];
612 $msg[4] = 1;
613 }
614
615 $this->dieWithError( $msg, 'filetype-banned', $extradata );
616 break;
617
618 case UploadBase::VERIFICATION_ERROR:
619 $msg = ApiMessage::create( $verification['details'], 'verification-error' );
620 if ( $verification['details'][0] instanceof MessageSpecifier ) {
621 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
622 } else {
623 $details = $verification['details'];
624 }
625 ApiResult::setIndexedTagName( $details, 'detail' );
626 $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
627 $this->dieWithError( $msg );
628 break;
629
630 case UploadBase::HOOK_ABORTED:
631 $msg = $verification['error'] === '' ? 'hookaborted' : $verification['error'];
632 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
633 break;
634 default:
635 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
636 [ 'details' => [ 'code' => $verification['status'] ] ] );
637 break;
638 }
639 }
640
641 /**
642 * Check warnings.
643 * Returns a suitable array for inclusion into API results if there were warnings
644 * Returns the empty array if there were no warnings
645 *
646 * @return array
647 */
648 protected function getApiWarnings() {
649 $warnings = $this->mUpload->checkWarnings();
650
651 return $this->transformWarnings( $warnings );
652 }
653
654 protected function transformWarnings( $warnings ) {
655 if ( $warnings ) {
656 // Add indices
657 ApiResult::setIndexedTagName( $warnings, 'warning' );
658
659 if ( isset( $warnings['duplicate'] ) ) {
660 $dupes = [];
661 /** @var File $dupe */
662 foreach ( $warnings['duplicate'] as $dupe ) {
663 $dupes[] = $dupe->getName();
664 }
665 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
666 $warnings['duplicate'] = $dupes;
667 }
668
669 if ( isset( $warnings['exists'] ) ) {
670 $warning = $warnings['exists'];
671 unset( $warnings['exists'] );
672 /** @var LocalFile $localFile */
673 $localFile = $warning['normalizedFile'] ?? $warning['file'];
674 $warnings[$warning['warning']] = $localFile->getName();
675 }
676
677 if ( isset( $warnings['no-change'] ) ) {
678 /** @var File $file */
679 $file = $warnings['no-change'];
680 unset( $warnings['no-change'] );
681
682 $warnings['nochange'] = [
683 'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
684 ];
685 }
686
687 if ( isset( $warnings['duplicate-version'] ) ) {
688 $dupes = [];
689 /** @var File $dupe */
690 foreach ( $warnings['duplicate-version'] as $dupe ) {
691 $dupes[] = [
692 'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
693 ];
694 }
695 unset( $warnings['duplicate-version'] );
696
697 ApiResult::setIndexedTagName( $dupes, 'ver' );
698 $warnings['duplicateversions'] = $dupes;
699 }
700 }
701
702 return $warnings;
703 }
704
705 /**
706 * Handles a stash exception, giving a useful error to the user.
707 * @todo Internationalize the exceptions then get rid of this
708 * @param Exception $e
709 * @return StatusValue
710 */
711 protected function handleStashException( $e ) {
712 switch ( get_class( $e ) ) {
713 case UploadStashFileNotFoundException::class:
714 $wrap = 'apierror-stashedfilenotfound';
715 break;
716 case UploadStashBadPathException::class:
717 $wrap = 'apierror-stashpathinvalid';
718 break;
719 case UploadStashFileException::class:
720 $wrap = 'apierror-stashfilestorage';
721 break;
722 case UploadStashZeroLengthFileException::class:
723 $wrap = 'apierror-stashzerolength';
724 break;
725 case UploadStashNotLoggedInException::class:
726 return StatusValue::newFatal( ApiMessage::create(
727 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
728 ) );
729 case UploadStashWrongOwnerException::class:
730 $wrap = 'apierror-stashwrongowner';
731 break;
732 case UploadStashNoSuchKeyException::class:
733 $wrap = 'apierror-stashnosuchfilekey';
734 break;
735 default:
736 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
737 break;
738 }
739 return StatusValue::newFatal(
740 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
741 );
742 }
743
744 /**
745 * Perform the actual upload. Returns a suitable result array on success;
746 * dies on failure.
747 *
748 * @param array $warnings Array of Api upload warnings
749 * @return array
750 */
751 protected function performUpload( $warnings ) {
752 // Use comment as initial page text by default
753 if ( is_null( $this->mParams['text'] ) ) {
754 $this->mParams['text'] = $this->mParams['comment'];
755 }
756
757 /** @var LocalFile $file */
758 $file = $this->mUpload->getLocalFile();
759
760 // For preferences mode, we want to watch if 'watchdefault' is set,
761 // or if the *file* doesn't exist, and either 'watchuploads' or
762 // 'watchcreations' is set. But getWatchlistValue()'s automatic
763 // handling checks if the *title* exists or not, so we need to check
764 // all three preferences manually.
765 $watch = $this->getWatchlistValue(
766 $this->mParams['watchlist'], $file->getTitle(), 'watchdefault'
767 );
768
769 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
770 $watch = (
771 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchuploads' ) ||
772 $this->getWatchlistValue( 'preferences', $file->getTitle(), 'watchcreations' )
773 );
774 }
775
776 // Deprecated parameters
777 if ( $this->mParams['watch'] ) {
778 $watch = true;
779 }
780
781 if ( $this->mParams['tags'] ) {
782 $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getUser() );
783 if ( !$status->isOK() ) {
784 $this->dieStatus( $status );
785 }
786 }
787
788 // No errors, no warnings: do the upload
789 if ( $this->mParams['async'] ) {
790 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
791 if ( $progress && $progress['result'] === 'Poll' ) {
792 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
793 }
794 UploadBase::setSessionStatus(
795 $this->getUser(),
796 $this->mParams['filekey'],
797 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
798 );
799 JobQueueGroup::singleton()->push( new PublishStashedFileJob(
800 Title::makeTitle( NS_FILE, $this->mParams['filename'] ),
801 [
802 'filename' => $this->mParams['filename'],
803 'filekey' => $this->mParams['filekey'],
804 'comment' => $this->mParams['comment'],
805 'tags' => $this->mParams['tags'],
806 'text' => $this->mParams['text'],
807 'watch' => $watch,
808 'session' => $this->getContext()->exportSession()
809 ]
810 ) );
811 $result['result'] = 'Poll';
812 $result['stage'] = 'queued';
813 } else {
814 /** @var Status $status */
815 $status = $this->mUpload->performUpload( $this->mParams['comment'],
816 $this->mParams['text'], $watch, $this->getUser(), $this->mParams['tags'] );
817
818 if ( !$status->isGood() ) {
819 $this->dieRecoverableError( $status->getErrors() );
820 }
821 $result['result'] = 'Success';
822 }
823
824 $result['filename'] = $file->getName();
825 if ( $warnings && count( $warnings ) > 0 ) {
826 $result['warnings'] = $warnings;
827 }
828
829 return $result;
830 }
831
832 public function mustBePosted() {
833 return true;
834 }
835
836 public function isWriteMode() {
837 return true;
838 }
839
840 public function getAllowedParams() {
841 $params = [
842 'filename' => [
843 ApiBase::PARAM_TYPE => 'string',
844 ],
845 'comment' => [
846 ApiBase::PARAM_DFLT => ''
847 ],
848 'tags' => [
849 ApiBase::PARAM_TYPE => 'tags',
850 ApiBase::PARAM_ISMULTI => true,
851 ],
852 'text' => [
853 ApiBase::PARAM_TYPE => 'text',
854 ],
855 'watch' => [
856 ApiBase::PARAM_DFLT => false,
857 ApiBase::PARAM_DEPRECATED => true,
858 ],
859 'watchlist' => [
860 ApiBase::PARAM_DFLT => 'preferences',
861 ApiBase::PARAM_TYPE => [
862 'watch',
863 'preferences',
864 'nochange'
865 ],
866 ],
867 'ignorewarnings' => false,
868 'file' => [
869 ApiBase::PARAM_TYPE => 'upload',
870 ],
871 'url' => null,
872 'filekey' => null,
873 'sessionkey' => [
874 ApiBase::PARAM_DEPRECATED => true,
875 ],
876 'stash' => false,
877
878 'filesize' => [
879 ApiBase::PARAM_TYPE => 'integer',
880 ApiBase::PARAM_MIN => 0,
881 ApiBase::PARAM_MAX => UploadBase::getMaxUploadSize(),
882 ],
883 'offset' => [
884 ApiBase::PARAM_TYPE => 'integer',
885 ApiBase::PARAM_MIN => 0,
886 ],
887 'chunk' => [
888 ApiBase::PARAM_TYPE => 'upload',
889 ],
890
891 'async' => false,
892 'checkstatus' => false,
893 ];
894
895 return $params;
896 }
897
898 public function needsToken() {
899 return 'csrf';
900 }
901
902 protected function getExamplesMessages() {
903 return [
904 'action=upload&filename=Wiki.png' .
905 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
906 => 'apihelp-upload-example-url',
907 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
908 => 'apihelp-upload-example-filekey',
909 ];
910 }
911
912 public function getHelpUrls() {
913 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
914 }
915 }