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