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