Merge "Add CollationFa"
[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 ApiRawMessage( 'Invalid stashed file', '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( new ApiRawMessage( $e->getMessage(), 'stashfailed' ) );
329 }
330
331 if ( $status->isGood() ) {
332 $stashFile = $status->getValue();
333 $data['filekey'] = $stashFile->getFileKey();
334 // Backwards compatibility
335 $data['sessionkey'] = $data['filekey'];
336 return $data['filekey'];
337 }
338
339 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
340 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
341 // Statuses for it. Just extract the exception details and parse them ourselves.
342 list( $exceptionType, $message ) = $status->getMessage()->getParams();
343 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
344 wfDebug( __METHOD__ . ' ' . $debugMessage . "\n" );
345 }
346
347 // Bad status
348 if ( $failureMode !== 'optional' ) {
349 $this->dieStatus( $status );
350 } else {
351 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
352 return null;
353 }
354 }
355
356 /**
357 * Throw an error that the user can recover from by providing a better
358 * value for $parameter
359 *
360 * @param array $errors Array of Message objects, message keys, key+param
361 * arrays, or StatusValue::getErrors()-style arrays
362 * @param string|null $parameter Parameter that needs revising
363 * @throws ApiUsageException
364 */
365 private function dieRecoverableError( $errors, $parameter = null ) {
366 $this->performStash( 'optional', $data );
367
368 if ( $parameter ) {
369 $data['invalidparameter'] = $parameter;
370 }
371
372 $sv = StatusValue::newGood();
373 foreach ( $errors as $error ) {
374 $msg = ApiMessage::create( $error );
375 $msg->setApiData( $msg->getApiData() + $data );
376 $sv->fatal( $msg );
377 }
378 $this->dieStatus( $sv );
379 }
380
381 /**
382 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
383 * IApiMessage.
384 *
385 * @param Status $status
386 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
387 * @param array|null $moreExtraData
388 * @throws ApiUsageException
389 */
390 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
391 $sv = StatusValue::newGood();
392 foreach ( $status->getErrors() as $error ) {
393 $msg = ApiMessage::create( $error, $overrideCode );
394 if ( $moreExtraData ) {
395 $msg->setApiData( $msg->getApiData() + $moreExtraData );
396 }
397 $sv->fatal( $msg );
398 }
399 $this->dieStatus( $sv );
400 }
401
402 /**
403 * Select an upload module and set it to mUpload. Dies on failure. If the
404 * request was a status request and not a true upload, returns false;
405 * otherwise true
406 *
407 * @return bool
408 */
409 protected function selectUploadModule() {
410 $request = $this->getMain()->getRequest();
411
412 // chunk or one and only one of the following parameters is needed
413 if ( !$this->mParams['chunk'] ) {
414 $this->requireOnlyOneParameter( $this->mParams,
415 'filekey', 'file', 'url' );
416 }
417
418 // Status report for "upload to stash"/"upload from stash"
419 if ( $this->mParams['filekey'] && $this->mParams['checkstatus'] ) {
420 $progress = UploadBase::getSessionStatus( $this->getUser(), $this->mParams['filekey'] );
421 if ( !$progress ) {
422 $this->dieWithError( 'api-upload-missingresult', 'missingresult' );
423 } elseif ( !$progress['status']->isGood() ) {
424 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
425 }
426 if ( isset( $progress['status']->value['verification'] ) ) {
427 $this->checkVerification( $progress['status']->value['verification'] );
428 }
429 if ( isset( $progress['status']->value['warnings'] ) ) {
430 $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
431 if ( $warnings ) {
432 $progress['warnings'] = $warnings;
433 }
434 }
435 unset( $progress['status'] ); // remove Status object
436 $imageinfo = null;
437 if ( isset( $progress['imageinfo'] ) ) {
438 $imageinfo = $progress['imageinfo'];
439 unset( $progress['imageinfo'] );
440 }
441
442 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
443 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
444 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
445 if ( $imageinfo ) {
446 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
447 }
448
449 return false;
450 }
451
452 // The following modules all require the filename parameter to be set
453 if ( is_null( $this->mParams['filename'] ) ) {
454 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
455 }
456
457 if ( $this->mParams['chunk'] ) {
458 // Chunk upload
459 $this->mUpload = new UploadFromChunks( $this->getUser() );
460 if ( isset( $this->mParams['filekey'] ) ) {
461 if ( $this->mParams['offset'] === 0 ) {
462 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
463 }
464
465 // handle new chunk
466 $this->mUpload->continueChunks(
467 $this->mParams['filename'],
468 $this->mParams['filekey'],
469 $request->getUpload( 'chunk' )
470 );
471 } else {
472 if ( $this->mParams['offset'] !== 0 ) {
473 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
474 }
475
476 // handle first chunk
477 $this->mUpload->initialize(
478 $this->mParams['filename'],
479 $request->getUpload( 'chunk' )
480 );
481 }
482 } elseif ( isset( $this->mParams['filekey'] ) ) {
483 // Upload stashed in a previous request
484 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
485 $this->dieWithError( 'apierror-invalid-file-key' );
486 }
487
488 $this->mUpload = new UploadFromStash( $this->getUser() );
489 // This will not download the temp file in initialize() in async mode.
490 // We still have enough information to call checkWarnings() and such.
491 $this->mUpload->initialize(
492 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
493 );
494 } elseif ( isset( $this->mParams['file'] ) ) {
495 $this->mUpload = new UploadFromFile();
496 $this->mUpload->initialize(
497 $this->mParams['filename'],
498 $request->getUpload( 'file' )
499 );
500 } elseif ( isset( $this->mParams['url'] ) ) {
501 // Make sure upload by URL is enabled:
502 if ( !UploadFromUrl::isEnabled() ) {
503 $this->dieWithError( 'copyuploaddisabled' );
504 }
505
506 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
507 $this->dieWithError( 'apierror-copyuploadbaddomain' );
508 }
509
510 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
511 $this->dieWithError( 'apierror-copyuploadbadurl' );
512 }
513
514 $this->mUpload = new UploadFromUrl;
515 $this->mUpload->initialize( $this->mParams['filename'],
516 $this->mParams['url'] );
517 }
518
519 return true;
520 }
521
522 /**
523 * Checks that the user has permissions to perform this upload.
524 * Dies with usage message on inadequate permissions.
525 * @param User $user The user to check.
526 */
527 protected function checkPermissions( $user ) {
528 // Check whether the user has the appropriate permissions to upload anyway
529 $permission = $this->mUpload->isAllowed( $user );
530
531 if ( $permission !== true ) {
532 if ( !$user->isLoggedIn() ) {
533 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
534 }
535
536 $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
537 }
538
539 // Check blocks
540 if ( $user->isBlocked() ) {
541 $this->dieBlocked( $user->getBlock() );
542 }
543
544 // Global blocks
545 if ( $user->isBlockedGlobally() ) {
546 $this->dieBlocked( $user->getGlobalBlock() );
547 }
548 }
549
550 /**
551 * Performs file verification, dies on error.
552 */
553 protected function verifyUpload() {
554 $verification = $this->mUpload->verifyUpload();
555 if ( $verification['status'] === UploadBase::OK ) {
556 return;
557 }
558
559 $this->checkVerification( $verification );
560 }
561
562 /**
563 * Performs file verification, dies on error.
564 * @param array $verification
565 */
566 protected function checkVerification( array $verification ) {
567 // @todo Move them to ApiBase's message map
568 switch ( $verification['status'] ) {
569 // Recoverable errors
570 case UploadBase::MIN_LENGTH_PARTNAME:
571 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
572 break;
573 case UploadBase::ILLEGAL_FILENAME:
574 $this->dieRecoverableError(
575 [ ApiMessage::create(
576 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
577 ) ], 'filename'
578 );
579 break;
580 case UploadBase::FILENAME_TOO_LONG:
581 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
582 break;
583 case UploadBase::FILETYPE_MISSING:
584 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
585 break;
586 case UploadBase::WINDOWS_NONASCII_FILENAME:
587 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
588 break;
589
590 // Unrecoverable errors
591 case UploadBase::EMPTY_FILE:
592 $this->dieWithError( 'empty-file' );
593 break;
594 case UploadBase::FILE_TOO_LARGE:
595 $this->dieWithError( 'file-too-large' );
596 break;
597
598 case UploadBase::FILETYPE_BADTYPE:
599 $extradata = [
600 'filetype' => $verification['finalExt'],
601 'allowed' => array_values( array_unique( $this->getConfig()->get( 'FileExtensions' ) ) )
602 ];
603 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
604 $msg = [
605 'filetype-banned-type',
606 null, // filled in below
607 Message::listParam( $extensions, 'comma' ),
608 count( $extensions ),
609 null, // filled in below
610 ];
611 ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
612
613 if ( isset( $verification['blacklistedExt'] ) ) {
614 $msg[1] = Message::listParam( $verification['blacklistedExt'], 'comma' );
615 $msg[4] = count( $verification['blacklistedExt'] );
616 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
617 ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
618 } else {
619 $msg[1] = $verification['finalExt'];
620 $msg[4] = 1;
621 }
622
623 $this->dieWithError( $msg, 'filetype-banned', $extradata );
624 break;
625
626 case UploadBase::VERIFICATION_ERROR:
627 $msg = ApiMessage::create( $verification['details'], 'verification-error' );
628 if ( $verification['details'][0] instanceof MessageSpecifier ) {
629 $details = array_merge( [ $msg->getKey() ], $msg->getParams() );
630 } else {
631 $details = $verification['details'];
632 }
633 ApiResult::setIndexedTagName( $details, 'detail' );
634 $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
635 $this->dieWithError( $msg );
636 break;
637
638 case UploadBase::HOOK_ABORTED:
639 $this->dieWithError( $params, 'hookaborted', [ 'details' => $verification['error'] ] );
640 break;
641 default:
642 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
643 [ 'details' => [ 'code' => $verification['status'] ] ] );
644 break;
645 }
646 }
647
648 /**
649 * Check warnings.
650 * Returns a suitable array for inclusion into API results if there were warnings
651 * Returns the empty array if there were no warnings
652 *
653 * @return array
654 */
655 protected function getApiWarnings() {
656 $warnings = $this->mUpload->checkWarnings();
657
658 return $this->transformWarnings( $warnings );
659 }
660
661 protected function transformWarnings( $warnings ) {
662 if ( $warnings ) {
663 // Add indices
664 ApiResult::setIndexedTagName( $warnings, 'warning' );
665
666 if ( isset( $warnings['duplicate'] ) ) {
667 $dupes = [];
668 /** @var File $dupe */
669 foreach ( $warnings['duplicate'] as $dupe ) {
670 $dupes[] = $dupe->getName();
671 }
672 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
673 $warnings['duplicate'] = $dupes;
674 }
675
676 if ( isset( $warnings['exists'] ) ) {
677 $warning = $warnings['exists'];
678 unset( $warnings['exists'] );
679 /** @var LocalFile $localFile */
680 $localFile = isset( $warning['normalizedFile'] )
681 ? $warning['normalizedFile']
682 : $warning['file'];
683 $warnings[$warning['warning']] = $localFile->getName();
684 }
685
686 if ( isset( $warnings['no-change'] ) ) {
687 /** @var File $file */
688 $file = $warnings['no-change'];
689 unset( $warnings['no-change'] );
690
691 $warnings['nochange'] = [
692 'timestamp' => wfTimestamp( TS_ISO_8601, $file->getTimestamp() )
693 ];
694 }
695
696 if ( isset( $warnings['duplicate-version'] ) ) {
697 $dupes = [];
698 /** @var File $dupe */
699 foreach ( $warnings['duplicate-version'] as $dupe ) {
700 $dupes[] = [
701 'timestamp' => wfTimestamp( TS_ISO_8601, $dupe->getTimestamp() )
702 ];
703 }
704 unset( $warnings['duplicate-version'] );
705
706 ApiResult::setIndexedTagName( $dupes, 'ver' );
707 $warnings['duplicateversions'] = $dupes;
708 }
709 }
710
711 return $warnings;
712 }
713
714 /**
715 * Handles a stash exception, giving a useful error to the user.
716 * @todo Internationalize the exceptions
717 * @param Exception $e
718 * @return StatusValue
719 */
720 protected function handleStashException( $e ) {
721 $err = wfEscapeWikiText( $e->getMessage() );
722 switch ( get_class( $exception ) ) {
723 case 'UploadStashFileNotFoundException':
724 return StatusValue::newFatal( 'apierror-stashedfilenotfound', $err );
725 case 'UploadStashBadPathException':
726 return StatusValue::newFatal( 'apierror-stashpathinvalid', $err );
727 case 'UploadStashFileException':
728 return StatusValue::newFatal( 'apierror-stashfilestorage', $err );
729 case 'UploadStashZeroLengthFileException':
730 return StatusValue::newFatal( 'apierror-stashzerolength', $err );
731 case 'UploadStashNotLoggedInException':
732 return StatusValue::newFatal( ApiMessage::create(
733 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
734 ) );
735 case 'UploadStashWrongOwnerException':
736 return StatusValue::newFatal( 'apierror-stashwrongowner', $err );
737 case 'UploadStashNoSuchKeyException':
738 return StatusValue::newFatal( 'apierror-stashnosuchfilekey', $err );
739 default:
740 return StatusValue::newFatal( 'uploadstash-exception', get_class( $e ), $err );
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 $file LocalFile */
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/API:Upload';
914 }
915 }