Debian Codegraph @

includes/api/ApiUpload.php

raw symbols SCIP
1 <?php
2 /**
3 * Copyright © 2008 - 2010 Bryan Tong Minh <[email protected]>
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 * @todo: create a UploadCommandFactory and UploadComand classes to share logic with Special:Upload
25 * @todo: split the different cases of upload in subclasses or submethods.
26 */
27
28 namespace MediaWiki\Api;
29
30 use AssembleUploadChunksJob;
31 use ChangeTags;
32 use Exception;
33 use JobQueueGroup;
34 use MediaWiki\Config\Config;
35 use MediaWiki\Logger\LoggerFactory;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Message\Message;
39 use MediaWiki\Status\Status;
40 use MediaWiki\User\Options\UserOptionsLookup;
41 use MediaWiki\User\User;
42 use MediaWiki\Watchlist\WatchlistManager;
43 use Psr\Log\LoggerInterface;
44 use PublishStashedFileJob;
45 use StatusValue;
46 use UploadBase;
47 use UploadFromChunks;
48 use UploadFromFile;
49 use UploadFromStash;
50 use UploadFromUrl;
51 use UploadFromUrlJob;
52 use UploadStashBadPathException;
53 use UploadStashException;
54 use UploadStashFileException;
55 use UploadStashFileNotFoundException;
56 use UploadStashNoSuchKeyException;
57 use UploadStashNotLoggedInException;
58 use UploadStashWrongOwnerException;
59 use UploadStashZeroLengthFileException;
60 use Wikimedia\Message\MessageSpecifier;
61 use Wikimedia\ParamValidator\ParamValidator;
62 use Wikimedia\ParamValidator\TypeDef\IntegerDef;
63
64 /**
65 * @ingroup API
66 */
67 class ApiUpload extends ApiBase {
68
69 use ApiWatchlistTrait;
70
71 /** @var UploadBase|UploadFromChunks */
72 protected $mUpload = null;
73
74 /** @var array */
75 protected $mParams;
76
77 private JobQueueGroup $jobQueueGroup;
78
79 private LoggerInterface $log;
80
81 public function __construct(
82 ApiMain $mainModule,
83 string $moduleName,
84 JobQueueGroup $jobQueueGroup,
85 WatchlistManager $watchlistManager,
86 UserOptionsLookup $userOptionsLookup
87 ) {
88 parent::__construct( $mainModule, $moduleName );
89 $this->jobQueueGroup = $jobQueueGroup;
90
91 // Variables needed in ApiWatchlistTrait trait
92 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
93 $this->watchlistMaxDuration =
94 $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
95 $this->watchlistManager = $watchlistManager;
96 $this->userOptionsLookup = $userOptionsLookup;
97 $this->log = LoggerFactory::getInstance( 'upload' );
98 }
99
100 public function execute() {
101 // Check whether upload is enabled
102 if ( !UploadBase::isEnabled() ) {
103 $this->dieWithError( 'uploaddisabled' );
104 }
105
106 $user = $this->getUser();
107
108 // Parameter handling
109 $this->mParams = $this->extractRequestParams();
110 // Check if async mode is actually supported (jobs done in cli mode)
111 $this->mParams['async'] = ( $this->mParams['async'] &&
112 $this->getConfig()->get( MainConfigNames::EnableAsyncUploads ) );
113
114 // Copy the session key to the file key, for backward compatibility.
115 if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
116 $this->mParams['filekey'] = $this->mParams['sessionkey'];
117 }
118
119 if ( !$this->mParams['checkstatus'] ) {
120 $this->useTransactionalTimeLimit();
121 }
122
123 // Select an upload module
124 try {
125 if ( !$this->selectUploadModule() ) {
126 return; // not a true upload, but a status request or similar
127 } elseif ( !isset( $this->mUpload ) ) {
128 $this->dieDebug( __METHOD__, 'No upload module set' );
129 }
130 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
131 $this->dieStatus( $this->handleStashException( $e ) );
132 }
133
134 // First check permission to upload
135 $this->checkPermissions( $user );
136
137 // Fetch the file (usually a no-op)
138 // Skip for async upload from URL, where we just want to run checks.
139 /** @var Status $status */
140 if ( $this->mParams['async'] && $this->mParams['url'] ) {
141 $status = $this->mUpload->canFetchFile();
142 } else {
143 $status = $this->mUpload->fetchFile();
144 }
145
146 if ( !$status->isGood() ) {
147 $this->log->info( "Unable to fetch file {filename} for {user} because {status}",
148 [
149 'user' => $this->getUser()->getName(),
150 'status' => (string)$status,
151 'filename' => $this->mParams['filename'] ?? '-',
152 ]
153 );
154 $this->dieStatus( $status );
155 }
156
157 // Check the uploaded file
158 $this->verifyUpload();
159
160 // Check if the user has the rights to modify or overwrite the requested title
161 // (This check is irrelevant if stashing is already requested, since the errors
162 // can always be fixed by changing the title)
163 if ( !$this->mParams['stash'] ) {
164 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
165 if ( $permErrors !== true ) {
166 $this->dieRecoverableError( $permErrors, 'filename' );
167 }
168 }
169
170 // Get the result based on the current upload context:
171 try {
172 $result = $this->getContextResult();
173 } catch ( UploadStashException $e ) { // XXX: don't spam exception log
174 $this->dieStatus( $this->handleStashException( $e ) );
175 }
176 $this->getResult()->addValue( null, $this->getModuleName(), $result );
177
178 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
179 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
180 // @phan-suppress-next-line PhanTypeArraySuspiciousNullable False positive
181 if ( $result['result'] === 'Success' ) {
182 $imageinfo = $this->getUploadImageInfo( $this->mUpload );
183 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
184 }
185
186 // Cleanup any temporary mess
187 $this->mUpload->cleanupTempFile();
188 }
189
190 public static function getDummyInstance(): self {
191 $services = MediaWikiServices::getInstance();
192 $apiMain = new ApiMain(); // dummy object (XXX)
193 $apiUpload = new ApiUpload(
194 $apiMain,
195 'upload',
196 $services->getJobQueueGroup(),
197 $services->getWatchlistManager(),
198 $services->getUserOptionsLookup()
199 );
200
201 return $apiUpload;
202 }
203
204 /**
205 * Gets image info about the file just uploaded.
206 *
207 * Also has the effect of setting metadata to be an 'indexed tag name' in
208 * returned API result if 'metadata' was requested. Oddly, we have to pass
209 * the "result" object down just so it can do that with the appropriate
210 * format, presumably.
211 *
212 * @internal For use in upload jobs and a deprecated method on UploadBase.
213 * @todo Extract the logic actually needed by the jobs, and separate it
214 * from the structure used in API responses.
215 *
216 * @return array Image info
217 */
218 public function getUploadImageInfo( UploadBase $upload ): array {
219 $result = $this->getResult();
220 $stashFile = $upload->getStashFile();
221
222 // Calling a different API module depending on whether the file was stashed is less than optimal.
223 // In fact, calling API modules here at all is less than optimal. Maybe it should be refactored.
224 if ( $stashFile ) {
225 $imParam = ApiQueryStashImageInfo::getPropertyNames();
226 $info = ApiQueryStashImageInfo::getInfo(
227 $stashFile,
228 array_fill_keys( $imParam, true ),
229 $result
230 );
231 } else {
232 $localFile = $upload->getLocalFile();
233 $imParam = ApiQueryImageInfo::getPropertyNames();
234 $info = ApiQueryImageInfo::getInfo(
235 $localFile,
236 array_fill_keys( $imParam, true ),
237 $result
238 );
239 }
240
241 return $info;
242 }
243
244 /**
245 * Get an upload result based on upload context
246 * @return array
247 */
248 private function getContextResult() {
249 $warnings = $this->getApiWarnings();
250 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
251 // Get warnings formatted in result array format
252 return $this->getWarningsResult( $warnings );
253 } elseif ( $this->mParams['chunk'] ) {
254 // Add chunk, and get result
255 return $this->getChunkResult( $warnings );
256 } elseif ( $this->mParams['stash'] ) {
257 // Stash the file and get stash result
258 return $this->getStashResult( $warnings );
259 }
260
261 // This is the most common case -- a normal upload with no warnings
262 // performUpload will return a formatted properly for the API with status
263 return $this->performUpload( $warnings );
264 }
265
266 /**
267 * Get Stash Result, throws an exception if the file could not be stashed.
268 * @param array $warnings Array of Api upload warnings
269 * @return array
270 */
271 private function getStashResult( $warnings ) {
272 $result = [];
273 $result['result'] = 'Success';
274 if ( $warnings && count( $warnings ) > 0 ) {
275 $result['warnings'] = $warnings;
276 }
277 // Some uploads can request they be stashed, so as not to publish them immediately.
278 // In this case, a failure to stash ought to be fatal
279 $this->performStash( 'critical', $result );
280
281 return $result;
282 }
283
284 /**
285 * Get Warnings Result
286 * @param array $warnings Array of Api upload warnings
287 * @return array
288 */
289 private function getWarningsResult( $warnings ) {
290 $result = [];
291 $result['result'] = 'Warning';
292 $result['warnings'] = $warnings;
293 // in case the warnings can be fixed with some further user action, let's stash this upload
294 // and return a key they can use to restart it
295 $this->performStash( 'optional', $result );
296
297 return $result;
298 }
299
300 /**
301 * @since 1.35
302 * @see $wgMinUploadChunkSize
303 * @param Config $config Site configuration for MinUploadChunkSize
304 * @return int
305 */
306 public static function getMinUploadChunkSize( Config $config ) {
307 $configured = $config->get( MainConfigNames::MinUploadChunkSize );
308
309 // Leave some room for other POST parameters
310 $postMax = (
311 wfShorthandToInteger(
312 ini_get( 'post_max_size' ),
313 PHP_INT_MAX
314 ) ?: PHP_INT_MAX
315 ) - 1024;
316
317 // Ensure the minimum chunk size is less than PHP upload limits
318 // or the maximum upload size.
319 return min(
320 $configured,
321 UploadBase::getMaxUploadSize( 'file' ),
322 UploadBase::getMaxPhpUploadSize(),
323 $postMax
324 );
325 }
326
327 /**
328 * Get the result of a chunk upload.
329 * @param array $warnings Array of Api upload warnings
330 * @return array
331 */
332 private function getChunkResult( $warnings ) {
333 $result = [];
334
335 if ( $warnings && count( $warnings ) > 0 ) {
336 $result['warnings'] = $warnings;
337 }
338
339 $chunkUpload = $this->getMain()->getUpload( 'chunk' );
340 $chunkPath = $chunkUpload->getTempName();
341 $chunkSize = $chunkUpload->getSize();
342 $totalSoFar = $this->mParams['offset'] + $chunkSize;
343 $minChunkSize = self::getMinUploadChunkSize( $this->getConfig() );
344
345 // Double check sizing
346 if ( $totalSoFar > $this->mParams['filesize'] ) {
347 $this->dieWithError( 'apierror-invalid-chunk' );
348 }
349
350 // Enforce minimum chunk size
351 if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
352 $this->dieWithError( [ 'apierror-chunk-too-small', Message::numParam( $minChunkSize ) ] );
353 }
354
355 if ( $this->mParams['offset'] == 0 ) {
356 $this->log->debug( "Started first chunk of chunked upload of {filename} for {user}",
357 [
358 'user' => $this->getUser()->getName(),
359 'filename' => $this->mParams['filename'] ?? '-',
360 'filesize' => $this->mParams['filesize'],
361 'chunkSize' => $chunkSize
362 ]
363 );
364 $filekey = $this->performStash( 'critical' );
365 } else {
366 $filekey = $this->mParams['filekey'];
367
368 // Don't allow further uploads to an already-completed session
369 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
370 if ( !$progress ) {
371 // Probably can't get here, but check anyway just in case
372 $this->log->info( "Stash failed due to no session for {user}",
373 [
374 'user' => $this->getUser()->getName(),
375 'filename' => $this->mParams['filename'] ?? '-',
376 'filekey' => $this->mParams['filekey'] ?? '-',
377 'filesize' => $this->mParams['filesize'],
378 'chunkSize' => $chunkSize
379 ]
380 );
381 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
382 } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
383 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
384 }
385
386 $status = $this->mUpload->addChunk(
387 $chunkPath, $chunkSize, $this->mParams['offset'] );
388 if ( !$status->isGood() ) {
389 $extradata = [
390 'offset' => $this->mUpload->getOffset(),
391 ];
392 $this->log->info( "Chunked upload stash failure {status} for {user}",
393 [
394 'status' => (string)$status,
395 'user' => $this->getUser()->getName(),
396 'filename' => $this->mParams['filename'] ?? '-',
397 'filekey' => $this->mParams['filekey'] ?? '-',
398 'filesize' => $this->mParams['filesize'],
399 'chunkSize' => $chunkSize,
400 'offset' => $this->mUpload->getOffset()
401 ]
402 );
403 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
404 } else {
405 $this->log->debug( "Got chunk for {filename} with offset {offset} for {user}",
406 [
407 'user' => $this->getUser()->getName(),
408 'filename' => $this->mParams['filename'] ?? '-',
409 'filekey' => $this->mParams['filekey'] ?? '-',
410 'filesize' => $this->mParams['filesize'],
411 'chunkSize' => $chunkSize,
412 'offset' => $this->mUpload->getOffset()
413 ]
414 );
415 }
416 }
417
418 // Check we added the last chunk:
419 if ( $totalSoFar == $this->mParams['filesize'] ) {
420 if ( $this->mParams['async'] ) {
421 UploadBase::setSessionStatus(
422 $this->getUser(),
423 $filekey,
424 [ 'result' => 'Poll',
425 'stage' => 'queued', 'status' => Status::newGood() ]
426 );
427 // It is important that this be lazyPush, as we do not want to insert
428 // into job queue until after the current transaction has completed since
429 // this depends on values in uploadstash table that were updated during
430 // the current transaction. (T350917)
431 $this->jobQueueGroup->lazyPush( new AssembleUploadChunksJob( [
432 'filename' => $this->mParams['filename'],
433 'filekey' => $filekey,
434 'filesize' => $this->mParams['filesize'],
435 'session' => $this->getContext()->exportSession()
436 ] ) );
437 $this->log->info( "Received final chunk of {filename} for {user}, queuing assemble job",
438 [
439 'user' => $this->getUser()->getName(),
440 'filename' => $this->mParams['filename'] ?? '-',
441 'filekey' => $this->mParams['filekey'] ?? '-',
442 'filesize' => $this->mParams['filesize'],
443 'chunkSize' => $chunkSize,
444 ]
445 );
446 $result['result'] = 'Poll';
447 $result['stage'] = 'queued';
448 } else {
449 $this->log->info( "Received final chunk of {filename} for {user}, assembling immediately",
450 [
451 'user' => $this->getUser()->getName(),
452 'filename' => $this->mParams['filename'] ?? '-',
453 'filekey' => $this->mParams['filekey'] ?? '-',
454 'filesize' => $this->mParams['filesize'],
455 'chunkSize' => $chunkSize,
456 ]
457 );
458
459 $status = $this->mUpload->concatenateChunks();
460 if ( !$status->isGood() ) {
461 UploadBase::setSessionStatus(
462 $this->getUser(),
463 $filekey,
464 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
465 );
466 $this->log->info( "Non jobqueue assembly of {filename} failed because {status}",
467 [
468 'user' => $this->getUser()->getName(),
469 'filename' => $this->mParams['filename'] ?? '-',
470 'filekey' => $this->mParams['filekey'] ?? '-',
471 'filesize' => $this->mParams['filesize'],
472 'chunkSize' => $chunkSize,
473 'status' => (string)$status
474 ]
475 );
476 $this->dieStatusWithCode( $status, 'stashfailed' );
477 }
478
479 // We can only get warnings like 'duplicate' after concatenating the chunks
480 $warnings = $this->getApiWarnings();
481 if ( $warnings ) {
482 $result['warnings'] = $warnings;
483 }
484
485 // The fully concatenated file has a new filekey. So remove
486 // the old filekey and fetch the new one.
487 UploadBase::setSessionStatus( $this->getUser(), $filekey, false );
488 $this->mUpload->stash->removeFile( $filekey );
489 $filekey = $this->mUpload->getStashFile()->getFileKey();
490
491 $result['result'] = 'Success';
492 }
493 } else {
494 UploadBase::setSessionStatus(
495 $this->getUser(),
496 $filekey,
497 [
498 'result' => 'Continue',
499 'stage' => 'uploading',
500 'offset' => $totalSoFar,
501 'status' => Status::newGood(),
502 ]
503 );
504 $result['result'] = 'Continue';
505 $result['offset'] = $totalSoFar;
506 }
507
508 $result['filekey'] = $filekey;
509
510 return $result;
511 }
512
513 /**
514 * Stash the file and add the file key, or error information if it fails, to the data.
515 *
516 * @param string $failureMode What to do on failure to stash:
517 * - When 'critical', use dieStatus() to produce an error response and throw an exception.
518 * Use this when stashing the file was the primary purpose of the API request.
519 * - When 'optional', only add a 'stashfailed' key to the data and return null.
520 * Use this when some error happened for a non-stash upload and we're stashing the file
521 * only to save the client the trouble of re-uploading it.
522 * @param array &$data API result to which to add the information
523 * @return string|null File key
524 */
525 private function performStash( $failureMode, &$data = [] ) {
526 $isPartial = (bool)$this->mParams['chunk'];
527 try {
528 $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
529
530 if ( $status->isGood() && !$status->getValue() ) {
531 // Not actually a 'good' status...
532 $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
533 }
534 } catch ( Exception $e ) {
535 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
536 $this->log->info( $debugMessage,
537 [
538 'user' => $this->getUser()->getName(),
539 'filename' => $this->mParams['filename'] ?? '-',
540 'filekey' => $this->mParams['filekey'] ?? '-'
541 ]
542 );
543
544 $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
545 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
546 ) );
547 }
548
549 if ( $status->isGood() ) {
550 $stashFile = $status->getValue();
551 $data['filekey'] = $stashFile->getFileKey();
552 // Backwards compatibility
553 $data['sessionkey'] = $data['filekey'];
554 return $data['filekey'];
555 }
556
557 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
558 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
559 // Statuses for it. Just extract the exception details and parse them ourselves.
560 [ $exceptionType, $message ] = $status->getMessage()->getParams();
561 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
562 $this->log->info( $debugMessage,
563 [
564 'user' => $this->getUser()->getName(),
565 'filename' => $this->mParams['filename'] ?? '-',
566 'filekey' => $this->mParams['filekey'] ?? '-'
567 ]
568 );
569 }
570
571 $this->log->info( "Stash upload failure {status}",
572 [
573 'status' => (string)$status,
574 'user' => $this->getUser()->getName(),
575 'filename' => $this->mParams['filename'] ?? '-',
576 'filekey' => $this->mParams['filekey'] ?? '-'
577 ]
578 );
579 // Bad status
580 if ( $failureMode !== 'optional' ) {
581 $this->dieStatus( $status );
582 } else {
583 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
584 return null;
585 }
586 }
587
588 /**
589 * Throw an error that the user can recover from by providing a better
590 * value for $parameter
591 *
592 * @param array $errors Array of Message objects, message keys, key+param
593 * arrays, or StatusValue::getErrors()-style arrays
594 * @param string|null $parameter Parameter that needs revising
595 * @throws ApiUsageException
596 * @return never
597 */
598 private function dieRecoverableError( $errors, $parameter = null ) {
599 $data = [];
600 $this->performStash( 'optional', $data );
601
602 if ( $parameter ) {
603 $data['invalidparameter'] = $parameter;
604 }
605
606 $sv = StatusValue::newGood();
607 foreach ( $errors as $error ) {
608 $msg = ApiMessage::create( $error );
609 $msg->setApiData( $msg->getApiData() + $data );
610 $sv->fatal( $msg );
611 }
612 $this->dieStatus( $sv );
613 }
614
615 /**
616 * Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from
617 * IApiMessage.
618 *
619 * @param Status $status
620 * @param string $overrideCode Error code to use if there isn't one from IApiMessage
621 * @param array|null $moreExtraData
622 * @throws ApiUsageException
623 * @return never
624 */
625 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ) {
626 $sv = StatusValue::newGood();
627 foreach ( $status->getMessages() as $error ) {
628 $msg = ApiMessage::create( $error, $overrideCode );
629 if ( $moreExtraData ) {
630 $msg->setApiData( $msg->getApiData() + $moreExtraData );
631 }
632 $sv->fatal( $msg );
633 }
634 $this->dieStatus( $sv );
635 }
636
637 /**
638 * Select an upload module and set it to mUpload. Dies on failure. If the
639 * request was a status request and not a true upload, returns false;
640 * otherwise true
641 *
642 * @return bool
643 */
644 protected function selectUploadModule() {
645 // chunk or one and only one of the following parameters is needed
646 if ( !$this->mParams['chunk'] ) {
647 $this->requireOnlyOneParameter( $this->mParams,
648 'filekey', 'file', 'url' );
649 }
650
651 // Status report for "upload to stash"/"upload from stash"/"upload by url"
652 if ( $this->mParams['checkstatus'] && ( $this->mParams['filekey'] || $this->mParams['url'] ) ) {
653 $statusKey = $this->mParams['filekey'] ?: UploadFromUrl::getCacheKey( $this->mParams );
654 $progress = UploadBase::getSessionStatus( $this->getUser(), $statusKey );
655 if ( !$progress ) {
656 $this->log->info( "Cannot check upload status due to missing upload session for {user}",
657 [
658 'user' => $this->getUser()->getName(),
659 'filename' => $this->mParams['filename'] ?? '-',
660 'filekey' => $this->mParams['filekey'] ?? '-'
661 ]
662 );
663 $this->dieWithError( 'apierror-upload-missingresult', 'missingresult' );
664 } elseif ( !$progress['status']->isGood() ) {
665 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
666 }
667 if ( isset( $progress['status']->value['verification'] ) ) {
668 $this->checkVerification( $progress['status']->value['verification'] );
669 }
670 if ( isset( $progress['status']->value['warnings'] ) ) {
671 $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
672 if ( $warnings ) {
673 $progress['warnings'] = $warnings;
674 }
675 }
676 unset( $progress['status'] ); // remove Status object
677 $imageinfo = null;
678 if ( isset( $progress['imageinfo'] ) ) {
679 $imageinfo = $progress['imageinfo'];
680 unset( $progress['imageinfo'] );
681 }
682
683 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
684 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
685 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
686 if ( $imageinfo ) {
687 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
688 }
689
690 return false;
691 }
692
693 // The following modules all require the filename parameter to be set
694 if ( $this->mParams['filename'] === null ) {
695 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
696 }
697
698 if ( $this->mParams['chunk'] ) {
699 // Chunk upload
700 $this->mUpload = new UploadFromChunks( $this->getUser() );
701 if ( isset( $this->mParams['filekey'] ) ) {
702 if ( $this->mParams['offset'] === 0 ) {
703 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
704 }
705
706 // handle new chunk
707 $this->mUpload->continueChunks(
708 $this->mParams['filename'],
709 $this->mParams['filekey'],
710 $this->getMain()->getUpload( 'chunk' )
711 );
712 } else {
713 if ( $this->mParams['offset'] !== 0 ) {
714 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
715 }
716
717 // handle first chunk
718 $this->mUpload->initialize(
719 $this->mParams['filename'],
720 $this->getMain()->getUpload( 'chunk' )
721 );
722 }
723 } elseif ( isset( $this->mParams['filekey'] ) ) {
724 // Upload stashed in a previous request
725 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
726 $this->dieWithError( 'apierror-invalid-file-key' );
727 }
728
729 $this->mUpload = new UploadFromStash( $this->getUser() );
730 // This will not download the temp file in initialize() in async mode.
731 // We still have enough information to call checkWarnings() and such.
732 $this->mUpload->initialize(
733 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
734 );
735 } elseif ( isset( $this->mParams['file'] ) ) {
736 // Can't async upload directly from a POSTed file, we'd have to
737 // stash the file and then queue the publish job. The user should
738 // just submit the two API queries to perform those two steps.
739 if ( $this->mParams['async'] ) {
740 $this->dieWithError( 'apierror-cannot-async-upload-file' );
741 }
742
743 $this->mUpload = new UploadFromFile();
744 $this->mUpload->initialize(
745 $this->mParams['filename'],
746 $this->getMain()->getUpload( 'file' )
747 );
748 } elseif ( isset( $this->mParams['url'] ) ) {
749 // Make sure upload by URL is enabled:
750 if ( !UploadFromUrl::isEnabled() ) {
751 $this->dieWithError( 'copyuploaddisabled' );
752 }
753
754 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
755 $this->dieWithError( 'apierror-copyuploadbaddomain' );
756 }
757
758 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
759 $this->dieWithError( 'apierror-copyuploadbadurl' );
760 }
761
762 $this->mUpload = new UploadFromUrl;
763 $this->mUpload->initialize( $this->mParams['filename'],
764 $this->mParams['url'] );
765 }
766
767 return true;
768 }
769
770 /**
771 * Checks that the user has permissions to perform this upload.
772 * Dies with usage message on inadequate permissions.
773 * @param User $user The user to check.
774 */
775 protected function checkPermissions( $user ) {
776 // Check whether the user has the appropriate permissions to upload anyway
777 $permission = $this->mUpload->isAllowed( $user );
778
779 if ( $permission !== true ) {
780 if ( !$user->isNamed() ) {
781 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
782 }
783
784 $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
785 }
786
787 // Check blocks
788 if ( $user->isBlockedFromUpload() ) {
789 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Block is checked and not null
790 $this->dieBlocked( $user->getBlock() );
791 }
792 }
793
794 /**
795 * Performs file verification, dies on error.
796 */
797 protected function verifyUpload() {
798 if ( $this->mParams['chunk'] ) {
799 $maxSize = UploadBase::getMaxUploadSize();
800 if ( $this->mParams['filesize'] > $maxSize ) {
801 $this->dieWithError( 'file-too-large' );
802 }
803 if ( !$this->mUpload->getTitle() ) {
804 $this->dieWithError( 'illegal-filename' );
805 }
806 // file will be assembled after having uploaded the last chunk,
807 // so we can only validate the name at this point
808 $verification = $this->mUpload->validateName();
809 if ( $verification === true ) {
810 return;
811 }
812 } elseif ( $this->mParams['async'] && ( $this->mParams['filekey'] || $this->mParams['url'] ) ) {
813 // file will be assembled/downloaded in a background process, so we
814 // can only validate the name at this point
815 // file verification will happen in background process
816 $verification = $this->mUpload->validateName();
817 if ( $verification === true ) {
818 return;
819 }
820 } else {
821 wfDebug( __METHOD__ . " about to verify" );
822
823 $verification = $this->mUpload->verifyUpload();
824
825 if ( $verification['status'] === UploadBase::OK ) {
826 return;
827 } else {
828 $this->log->info( "File verification of {filename} failed for {user} because {result}",
829 [
830 'user' => $this->getUser()->getName(),
831 'resultCode' => $verification['status'],
832 'result' => $this->mUpload->getVerificationErrorCode( $verification['status'] ),
833 'filename' => $this->mParams['filename'] ?? '-',
834 'details' => $verification['details'] ?? ''
835 ]
836 );
837 }
838 }
839
840 $this->checkVerification( $verification );
841 }
842
843 /**
844 * Performs file verification, dies on error.
845 * @param array $verification
846 * @return never
847 */
848 protected function checkVerification( array $verification ) {
849 switch ( $verification['status'] ) {
850 // Recoverable errors
851 case UploadBase::MIN_LENGTH_PARTNAME:
852 $this->dieRecoverableError( [ 'filename-tooshort' ], 'filename' );
853 // dieRecoverableError prevents continuation
854 case UploadBase::ILLEGAL_FILENAME:
855 $this->dieRecoverableError(
856 [ ApiMessage::create(
857 'illegal-filename', null, [ 'filename' => $verification['filtered'] ]
858 ) ], 'filename'
859 );
860 // dieRecoverableError prevents continuation
861 case UploadBase::FILENAME_TOO_LONG:
862 $this->dieRecoverableError( [ 'filename-toolong' ], 'filename' );
863 // dieRecoverableError prevents continuation
864 case UploadBase::FILETYPE_MISSING:
865 $this->dieRecoverableError( [ 'filetype-missing' ], 'filename' );
866 // dieRecoverableError prevents continuation
867 case UploadBase::WINDOWS_NONASCII_FILENAME:
868 $this->dieRecoverableError( [ 'windows-nonascii-filename' ], 'filename' );
869
870 // Unrecoverable errors
871 case UploadBase::EMPTY_FILE:
872 $this->dieWithError( 'empty-file' );
873 // dieWithError prevents continuation
874 case UploadBase::FILE_TOO_LARGE:
875 $this->dieWithError( 'file-too-large' );
876 // dieWithError prevents continuation
877
878 case UploadBase::FILETYPE_BADTYPE:
879 $extradata = [
880 'filetype' => $verification['finalExt'],
881 'allowed' => array_values( array_unique(
882 $this->getConfig()->get( MainConfigNames::FileExtensions ) ) )
883 ];
884 $extensions =
885 array_unique( $this->getConfig()->get( MainConfigNames::FileExtensions ) );
886 $msg = [
887 'filetype-banned-type',
888 null, // filled in below
889 Message::listParam( $extensions, 'comma' ),
890 count( $extensions ),
891 null, // filled in below
892 ];
893 ApiResult::setIndexedTagName( $extradata['allowed'], 'ext' );
894
895 if ( isset( $verification['blacklistedExt'] ) ) {
896 $msg[1] = Message::listParam( $verification['blacklistedExt'], 'comma' );
897 $msg[4] = count( $verification['blacklistedExt'] );
898 $extradata['blacklisted'] = array_values( $verification['blacklistedExt'] );
899 ApiResult::setIndexedTagName( $extradata['blacklisted'], 'ext' );
900 } else {
901 $msg[1] = $verification['finalExt'];
902 $msg[4] = 1;
903 }
904
905 $this->dieWithError( $msg, 'filetype-banned', $extradata );
906 // dieWithError prevents continuation
907
908 case UploadBase::VERIFICATION_ERROR:
909 $msg = ApiMessage::create( $verification['details'], 'verification-error' );
910 if ( $verification['details'][0] instanceof MessageSpecifier ) {
911 $details = [ $msg->getKey(), ...$msg->getParams() ];
912 } else {
913 $details = $verification['details'];
914 }
915 ApiResult::setIndexedTagName( $details, 'detail' );
916 $msg->setApiData( $msg->getApiData() + [ 'details' => $details ] );
917 $this->dieWithError( $msg );
918 // dieWithError prevents continuation
919
920 case UploadBase::HOOK_ABORTED:
921 $msg = $verification['error'] === '' ? 'hookaborted' : $verification['error'];
922 $this->dieWithError( $msg, 'hookaborted', [ 'details' => $verification['error'] ] );
923 // dieWithError prevents continuation
924 default:
925 $this->dieWithError( 'apierror-unknownerror-nocode', 'unknown-error',
926 [ 'details' => [ 'code' => $verification['status'] ] ] );
927 }
928 }
929
930 /**
931 * Check warnings.
932 * Returns a suitable array for inclusion into API results if there were warnings
933 * Returns the empty array if there were no warnings
934 *
935 * @return array
936 */
937 protected function getApiWarnings() {
938 $warnings = UploadBase::makeWarningsSerializable(
939 $this->mUpload->checkWarnings( $this->getUser() )
940 );
941
942 return $this->transformWarnings( $warnings );
943 }
944
945 protected function transformWarnings( $warnings ) {
946 if ( $warnings ) {
947 // Add indices
948 ApiResult::setIndexedTagName( $warnings, 'warning' );
949
950 if ( isset( $warnings['duplicate'] ) ) {
951 $dupes = array_column( $warnings['duplicate'], 'fileName' );
952 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
953 $warnings['duplicate'] = $dupes;
954 }
955
956 if ( isset( $warnings['exists'] ) ) {
957 $warning = $warnings['exists'];
958 unset( $warnings['exists'] );
959 $localFile = $warning['normalizedFile'] ?? $warning['file'];
960 $warnings[$warning['warning']] = $localFile['fileName'];
961 }
962
963 if ( isset( $warnings['no-change'] ) ) {
964 $file = $warnings['no-change'];
965 unset( $warnings['no-change'] );
966
967 $warnings['nochange'] = [
968 'timestamp' => wfTimestamp( TS_ISO_8601, $file['timestamp'] )
969 ];
970 }
971
972 if ( isset( $warnings['duplicate-version'] ) ) {
973 $dupes = [];
974 foreach ( $warnings['duplicate-version'] as $dupe ) {
975 $dupes[] = [
976 'timestamp' => wfTimestamp( TS_ISO_8601, $dupe['timestamp'] )
977 ];
978 }
979 unset( $warnings['duplicate-version'] );
980
981 ApiResult::setIndexedTagName( $dupes, 'ver' );
982 $warnings['duplicateversions'] = $dupes;
983 }
984 // We haven't downloaded the file, so this will result in an empty file warning
985 if ( $this->mParams['async'] && $this->mParams['url'] ) {
986 unset( $warnings['empty-file'] );
987 }
988 }
989
990 return $warnings;
991 }
992
993 /**
994 * Handles a stash exception, giving a useful error to the user.
995 * @todo Internationalize the exceptions then get rid of this
996 * @param Exception $e
997 * @return StatusValue
998 */
999 protected function handleStashException( $e ) {
1000 $this->log->info( "Upload stashing of {filename} failed for {user} because {error}",
1001 [
1002 'user' => $this->getUser()->getName(),
1003 'error' => get_class( $e ),
1004 'filename' => $this->mParams['filename'] ?? '-',
1005 'filekey' => $this->mParams['filekey'] ?? '-'
1006 ]
1007 );
1008
1009 switch ( get_class( $e ) ) {
1010 case UploadStashFileNotFoundException::class:
1011 $wrap = 'apierror-stashedfilenotfound';
1012 break;
1013 case UploadStashBadPathException::class:
1014 $wrap = 'apierror-stashpathinvalid';
1015 break;
1016 case UploadStashFileException::class:
1017 $wrap = 'apierror-stashfilestorage';
1018 break;
1019 case UploadStashZeroLengthFileException::class:
1020 $wrap = 'apierror-stashzerolength';
1021 break;
1022 case UploadStashNotLoggedInException::class:
1023 return StatusValue::newFatal( ApiMessage::create(
1024 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
1025 ) );
1026 case UploadStashWrongOwnerException::class:
1027 $wrap = 'apierror-stashwrongowner';
1028 break;
1029 case UploadStashNoSuchKeyException::class:
1030 $wrap = 'apierror-stashnosuchfilekey';
1031 break;
1032 default:
1033 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
1034 break;
1035 }
1036 return StatusValue::newFatal(
1037 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
1038 );
1039 }
1040
1041 /**
1042 * Perform the actual upload. Returns a suitable result array on success;
1043 * dies on failure.
1044 *
1045 * @param array $warnings Array of Api upload warnings
1046 * @return array
1047 */
1048 protected function performUpload( $warnings ) {
1049 // Use comment as initial page text by default
1050 $this->mParams['text'] ??= $this->mParams['comment'];
1051
1052 /** @var LocalFile $file */
1053 $file = $this->mUpload->getLocalFile();
1054 $user = $this->getUser();
1055 $title = $file->getTitle();
1056
1057 // for preferences mode, we want to watch if 'watchdefault' is set,
1058 // or if the *file* doesn't exist, and either 'watchuploads' or
1059 // 'watchcreations' is set. But getWatchlistValue()'s automatic
1060 // handling checks if the *title* exists or not, so we need to check
1061 // all three preferences manually.
1062 $watch = $this->getWatchlistValue(
1063 $this->mParams['watchlist'], $title, $user, 'watchdefault'
1064 );
1065
1066 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
1067 $watch = (
1068 $this->getWatchlistValue( 'preferences', $title, $user, 'watchuploads' ) ||
1069 $this->getWatchlistValue( 'preferences', $title, $user, 'watchcreations' )
1070 );
1071 }
1072 $watchlistExpiry = $this->getExpiryFromParams( $this->mParams );
1073
1074 // Deprecated parameters
1075 if ( $this->mParams['watch'] ) {
1076 $watch = true;
1077 }
1078
1079 if ( $this->mParams['tags'] ) {
1080 $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getAuthority() );
1081 if ( !$status->isOK() ) {
1082 $this->dieStatus( $status );
1083 }
1084 }
1085
1086 // No errors, no warnings: do the upload
1087 $result = [];
1088 if ( $this->mParams['async'] ) {
1089 // Only stash uploads and copy uploads support async
1090 if ( $this->mParams['filekey'] ) {
1091 $job = new PublishStashedFileJob(
1092 [
1093 'filename' => $this->mParams['filename'],
1094 'filekey' => $this->mParams['filekey'],
1095 'comment' => $this->mParams['comment'],
1096 'tags' => $this->mParams['tags'] ?? [],
1097 'text' => $this->mParams['text'],
1098 'watch' => $watch,
1099 'watchlistexpiry' => $watchlistExpiry,
1100 'session' => $this->getContext()->exportSession(),
1101 'ignorewarnings' => $this->mParams['ignorewarnings']
1102 ]
1103 );
1104 } elseif ( $this->mParams['url'] ) {
1105 $job = new UploadFromUrlJob(
1106 [
1107 'filename' => $this->mParams['filename'],
1108 'url' => $this->mParams['url'],
1109 'comment' => $this->mParams['comment'],
1110 'tags' => $this->mParams['tags'] ?? [],
1111 'text' => $this->mParams['text'],
1112 'watch' => $watch,
1113 'watchlistexpiry' => $watchlistExpiry,
1114 'session' => $this->getContext()->exportSession(),
1115 'ignorewarnings' => $this->mParams['ignorewarnings']
1116 ]
1117 );
1118 } else {
1119 $this->dieWithError( 'apierror-no-async-support', 'publishfailed' );
1120 // We will never reach this, but it's here to help phan figure out
1121 // $job is never null
1122 // @phan-suppress-next-line PhanPluginUnreachableCode On purpose
1123 return [];
1124 }
1125 $cacheKey = $job->getCacheKey();
1126 // Check if an upload is already in progress.
1127 // the result can be Poll / Failure / Success
1128 $progress = UploadBase::getSessionStatus( $this->getUser(), $cacheKey );
1129 if ( $progress && $progress['result'] === 'Poll' ) {
1130 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
1131 }
1132 UploadBase::setSessionStatus(
1133 $this->getUser(),
1134 $cacheKey,
1135 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
1136 );
1137
1138 $this->jobQueueGroup->push( $job );
1139 $this->log->info( "Sending publish job of {filename} for {user}",
1140 [
1141 'user' => $this->getUser()->getName(),
1142 'filename' => $this->mParams['filename'] ?? '-'
1143 ]
1144 );
1145 $result['result'] = 'Poll';
1146 $result['stage'] = 'queued';
1147 } else {
1148 /** @var Status $status */
1149 $status = $this->mUpload->performUpload(
1150 $this->mParams['comment'],
1151 $this->mParams['text'],
1152 $watch,
1153 $this->getUser(),
1154 $this->mParams['tags'] ?? [],
1155 $watchlistExpiry
1156 );
1157
1158 if ( !$status->isGood() ) {
1159 $this->log->info( "Non-async API upload publish failed for {user} because {status}",
1160 [
1161 'user' => $this->getUser()->getName(),
1162 'filename' => $this->mParams['filename'] ?? '-',
1163 'filekey' => $this->mParams['filekey'] ?? '-',
1164 'status' => (string)$status
1165 ]
1166 );
1167 $this->dieRecoverableError( $status->getMessages() );
1168 }
1169 $result['result'] = 'Success';
1170 }
1171
1172 $result['filename'] = $file->getName();
1173 if ( $warnings && count( $warnings ) > 0 ) {
1174 $result['warnings'] = $warnings;
1175 }
1176
1177 return $result;
1178 }
1179
1180 public function mustBePosted() {
1181 return true;
1182 }
1183
1184 public function isWriteMode() {
1185 return true;
1186 }
1187
1188 public function getAllowedParams() {
1189 $params = [
1190 'filename' => [
1191 ParamValidator::PARAM_TYPE => 'string',
1192 ],
1193 'comment' => [
1194 ParamValidator::PARAM_DEFAULT => ''
1195 ],
1196 'tags' => [
1197 ParamValidator::PARAM_TYPE => 'tags',
1198 ParamValidator::PARAM_ISMULTI => true,
1199 ],
1200 'text' => [
1201 ParamValidator::PARAM_TYPE => 'text',
1202 ],
1203 'watch' => [
1204 ParamValidator::PARAM_DEFAULT => false,
1205 ParamValidator::PARAM_DEPRECATED => true,
1206 ],
1207 ];
1208
1209 // Params appear in the docs in the order they are defined,
1210 // which is why this is here and not at the bottom.
1211 $params += $this->getWatchlistParams( [
1212 'watch',
1213 'preferences',
1214 'nochange',
1215 ] );
1216
1217 $params += [
1218 'ignorewarnings' => false,
1219 'file' => [
1220 ParamValidator::PARAM_TYPE => 'upload',
1221 ],
1222 'url' => null,
1223 'filekey' => null,
1224 'sessionkey' => [
1225 ParamValidator::PARAM_DEPRECATED => true,
1226 ],
1227 'stash' => false,
1228
1229 'filesize' => [
1230 ParamValidator::PARAM_TYPE => 'integer',
1231 IntegerDef::PARAM_MIN => 0,
1232 IntegerDef::PARAM_MAX => UploadBase::getMaxUploadSize(),
1233 ],
1234 'offset' => [
1235 ParamValidator::PARAM_TYPE => 'integer',
1236 IntegerDef::PARAM_MIN => 0,
1237 ],
1238 'chunk' => [
1239 ParamValidator::PARAM_TYPE => 'upload',
1240 ],
1241
1242 'async' => false,
1243 'checkstatus' => false,
1244 ];
1245
1246 return $params;
1247 }
1248
1249 public function needsToken() {
1250 return 'csrf';
1251 }
1252
1253 protected function getExamplesMessages() {
1254 return [
1255 'action=upload&filename=Wiki.png' .
1256 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
1257 => 'apihelp-upload-example-url',
1258 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
1259 => 'apihelp-upload-example-filekey',
1260 ];
1261 }
1262
1263 public function getHelpUrls() {
1264 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
1265 }
1266 }
1267
1268 /** @deprecated class alias since 1.43 */
1269 class_alias( ApiUpload::class, 'ApiUpload' );