MediaWiki master
ApiUpload.php
Go to the documentation of this file.
1<?php
8
13
14namespace MediaWiki\Api;
15
16use Exception;
50use Psr\Log\LoggerInterface;
51use StatusValue;
52use Wikimedia\Message\MessageSpecifier;
53use Wikimedia\ParamValidator\ParamValidator;
54use Wikimedia\ParamValidator\TypeDef\IntegerDef;
55use Wikimedia\Timestamp\TimestampFormat as TS;
56
60class ApiUpload extends ApiBase {
61
63
65 protected $mUpload = null;
66
68 protected $mParams;
69
70 private readonly LocalRepo $localRepo;
71
72 private LoggerInterface $log;
73
74 public function __construct(
75 ApiMain $mainModule,
76 string $moduleName,
77 private readonly JobQueueGroup $jobQueueGroup,
78 WatchlistManager $watchlistManager,
79 WatchedItemStoreInterface $watchedItemStore,
80 UserOptionsLookup $userOptionsLookup,
81 RepoGroup $repoGroup,
82 ) {
83 parent::__construct( $mainModule, $moduleName );
84 $this->localRepo = $repoGroup->getLocalRepo();
85
86 // Variables needed in ApiWatchlistTrait trait
87 $this->watchlistExpiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
88 $this->watchlistMaxDuration =
90 $this->watchlistManager = $watchlistManager;
91 $this->watchedItemStore = $watchedItemStore;
92 $this->userOptionsLookup = $userOptionsLookup;
93 $this->log = LoggerFactory::getInstance( 'upload' );
94 }
95
96 public function execute() {
97 // Check whether upload is enabled
98 if ( !UploadBase::isEnabled() ) {
99 $this->dieWithError( 'uploaddisabled' );
100 }
101
102 $user = $this->getUser();
103 $config = $this->getConfig();
104
105 // Parameter handling
106 $this->mParams = $this->extractRequestParams();
107 // Check if async mode is actually supported (jobs done in cli mode)
108 $this->mParams['async'] = $this->mParams['async'] &&
109 $config->get( MainConfigNames::EnableAsyncUploads ) &&
110 ( !$this->mParams['url'] || $config->get( MainConfigNames::EnableAsyncUploadsByURL ) );
111
112 // Copy the session key to the file key, for backward compatibility.
113 if ( !$this->mParams['filekey'] && $this->mParams['sessionkey'] ) {
114 $this->mParams['filekey'] = $this->mParams['sessionkey'];
115 }
116
117 // 'text' is only used as the file page's text when actually
118 // publishing. A stash request never creates the page, so 'text' is
119 // ignored.
120 if ( $this->mParams['stash'] && $this->mParams['text'] !== null ) {
121 $this->addWarning( 'apiwarn-upload-textwithstash' );
122 }
123
124 // 'autotext' generates the file page's text when publishing. A stash
125 // request never creates the page, so 'autotext' is ignored.
126 if ( $this->mParams['stash'] && $this->mParams['autotext'] ) {
127 $this->addWarning( 'apiwarn-upload-autotextwithstash' );
128 }
129
130 if ( !$this->mParams['checkstatus'] ) {
132 }
133
134 // Select an upload module
135 try {
136 if ( !$this->selectUploadModule() ) {
137 // not a true upload, but a status request or similar
138 return;
139 } elseif ( !$this->mUpload ) {
140 self::dieDebug( __METHOD__, 'No upload module set' );
141 }
142 } catch ( UploadStashException $e ) {
143 // XXX: don't spam exception log
144 $this->dieStatus( $this->handleStashException( $e ) );
145 }
146
147 // First check permission to upload
148 $this->checkPermissions( $user );
149
150 // Fetch the file (usually a no-op)
151 // Skip for async upload from URL, where we just want to run checks.
153 if ( $this->mParams['async'] && $this->mParams['url'] ) {
154 $status = $this->mUpload->canFetchFile();
155 } else {
156 $status = $this->mUpload->fetchFile();
157 }
158
159 if ( !$status->isGood() ) {
160 $this->log->info( "Unable to fetch file {filename} for {user} because {status}",
161 [
162 'user' => $this->getUser()->getName(),
163 'status' => (string)$status,
164 'filename' => $this->mParams['filename'] ?? '-',
165 ]
166 );
167 $this->dieStatus( $status );
168 }
169
170 // Check the uploaded file
171 $this->verifyUpload();
172
173 // Check if the user has the rights to modify or overwrite the requested title
174 // (This check is irrelevant if stashing is already requested, since the errors
175 // can always be fixed by changing the title)
176 if ( !$this->mParams['stash'] ) {
177 $status = $this->mUpload->authorizeUpload( $user );
178 if ( !$status->isGood() ) {
179 $this->dieRecoverableError( $status->getMessages(), 'filename' );
180 }
181 }
182
183 // Get the result based on the current upload context:
184 try {
185 $result = $this->getContextResult();
186 } catch ( UploadStashException $e ) {
187 // XXX: don't spam exception log
188 $this->dieStatus( $this->handleStashException( $e ) );
189 }
190 $this->getResult()->addValue( null, $this->getModuleName(), $result );
191
192 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
193 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
194 if ( $result['result'] === 'Success' ) {
195 $imageinfo = $this->getUploadImageInfo( $this->mUpload );
196 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
197 }
198
199 // Cleanup any temporary mess
200 $this->mUpload->cleanupTempFile();
201 }
202
207 public static function getDummyInstance(): self {
208 wfDeprecated( __METHOD__, '1.46' );
209 $services = MediaWikiServices::getInstance();
210 return new ApiUpload(
211 // dummy object (XXX)
212 new ApiMain(),
213 'upload',
214 $services->getJobQueueGroup(),
215 $services->getWatchlistManager(),
216 $services->getWatchedItemStore(),
217 $services->getUserOptionsLookup(),
218 $services->getRepoGroup(),
219 );
220 }
221
234 public function getUploadImageInfo( UploadBase $upload ): array {
235 $stashFile = $upload->getStashFile();
236 if ( $stashFile ) {
237 $info = $this->getUploadImageInfoInternal( $stashFile, true );
238 } else {
239 $localFile = $upload->getLocalFile();
240 $info = $this->getUploadImageInfoInternal( $localFile, false );
241 }
242
243 return $info;
244 }
245
246 private function getUploadImageInfoInternal( File $file, bool $stashedImageInfos ): array {
247 $result = $this->getResult();
248 // Calling a different API module depending on whether the file was stashed is less than optimal.
249 // In fact, calling API modules here at all is less than optimal. Maybe it should be refactored.
250
251 // TODO: Reduce to what is needed
252 //
253 // Prior to May 2026 this used ApiQueryImageInfo::getPropertyNames to fetch "all" properties
254 // (except "uploadwarning"). It was frozen to avoid adding "thumburls" (T426246) and become
255 // more intentional. Figuring out what's needed is hard due to many levels of indirection,
256 // including mediawiki.Upload.js and mediawiki.Upload.BookletLayout (via API action=upload)
257 // and UploadBase::getSessionStatus (via getUploadImageInfo, UploadJobTrait, UploadFromUrlJob).
258 $iiprops = [
259 'timestamp',
260 'canonicaltitle',
261 'url',
262 'size',
263 'dimensions',
264 'sha1',
265 'mime',
266 'thumbmime',
267 'metadata',
268 'commonmetadata',
269 'extmetadata',
270 'bitdepth',
271 'badfile',
272 ];
273 if ( $stashedImageInfos ) {
274 $imParam = $iiprops;
275 $info = ApiQueryStashImageInfo::getInfo(
276 $file,
277 array_fill_keys( $imParam, true ),
278 $result
279 );
280 } else {
281 $imParam = [
282 ...$iiprops,
283 'user',
284 'userid',
285 'comment',
286 'parsedcomment',
287 'mediatype',
288 'archivename',
289 ];
290 $info = ApiQueryImageInfo::getInfo(
291 $file,
292 array_fill_keys( $imParam, true ),
293 $result
294 );
295 }
296
297 return $info;
298 }
299
304 private function getContextResult() {
305 $warnings = $this->getApiWarnings();
306 if ( $warnings && !$this->mParams['ignorewarnings'] ) {
307 // Get warnings formatted in result array format
308 return $this->getWarningsResult( $warnings );
309 } elseif ( $this->mParams['chunk'] ) {
310 // Add chunk, and get result
311 return $this->getChunkResult( $warnings );
312 } elseif ( $this->mParams['stash'] ) {
313 // Stash the file and get stash result
314 return $this->getStashResult( $warnings );
315 }
316
317 // This is the most common case -- a normal upload with no warnings
318 // performUpload will return a formatted properly for the API with status
319 return $this->performUpload( $warnings );
320 }
321
327 private function getStashResult( $warnings ) {
328 $result = [ 'result' => 'Success' ];
329 if ( $warnings && count( $warnings ) > 0 ) {
330 $result['warnings'] = $warnings;
331 }
332 // Some uploads can request they be stashed, so as not to publish them immediately.
333 // In this case, a failure to stash ought to be fatal
334 $this->performStash( 'critical', $result );
335
336 return $result;
337 }
338
344 private function getWarningsResult( $warnings ) {
345 $result = [
346 'result' => 'Warning',
347 'warnings' => $warnings,
348 ];
349
350 // in case the warnings can be fixed with some further user action, let's stash this upload
351 // and return a key they can use to restart it
352 $this->performStash( 'optional', $result );
353
354 return $result;
355 }
356
363 public static function getMinUploadChunkSize( Config $config ) {
364 $configured = $config->get( MainConfigNames::MinUploadChunkSize );
365
366 // Leave some room for other POST parameters
367 $postMax = (
369 ini_get( 'post_max_size' ),
370 PHP_INT_MAX
371 ) ?: PHP_INT_MAX
372 ) - 1024;
373
374 // Ensure the minimum chunk size is less than PHP upload limits
375 // or the maximum upload size.
376 return min(
377 $configured,
378 UploadBase::getMaxUploadSize( 'file' ),
379 UploadBase::getMaxPhpUploadSize(),
380 $postMax
381 );
382 }
383
389 private function getChunkResult( $warnings ) {
390 $result = [];
391
392 if ( $warnings && count( $warnings ) > 0 ) {
393 $result['warnings'] = $warnings;
394 }
395
396 $chunkUpload = $this->getMain()->getUpload( 'chunk' );
397 $chunkPath = $chunkUpload->getTempName();
398 $chunkSize = $chunkUpload->getSize();
399 $totalSoFar = $this->mParams['offset'] + $chunkSize;
400 $minChunkSize = self::getMinUploadChunkSize( $this->getConfig() );
401
402 // Double check sizing
403 if ( $totalSoFar > $this->mParams['filesize'] ) {
404 $this->dieWithError( 'apierror-invalid-chunk' );
405 }
406
407 // Enforce minimum chunk size
408 if ( $totalSoFar != $this->mParams['filesize'] && $chunkSize < $minChunkSize ) {
409 $this->dieWithError( [ 'apierror-chunk-too-small', Message::numParam( $minChunkSize ) ] );
410 }
411
412 if ( $this->mParams['offset'] == 0 ) {
413 $this->log->debug( "Started first chunk of chunked upload of {filename} for {user}",
414 [
415 'user' => $this->getUser()->getName(),
416 'filename' => $this->mParams['filename'] ?? '-',
417 'filesize' => $this->mParams['filesize'],
418 'chunkSize' => $chunkSize
419 ]
420 );
421 $filekey = $this->performStash( 'critical' );
422 } else {
423 $filekey = $this->mParams['filekey'];
424
425 // Don't allow further uploads to an already-completed session
426 $progress = UploadBase::getSessionStatus( $this->getUser(), $filekey );
427 if ( !$progress ) {
428 // Probably can't get here, but check anyway just in case
429 $this->log->info( "Stash failed due to no session for {user}",
430 [
431 'user' => $this->getUser()->getName(),
432 'filename' => $this->mParams['filename'] ?? '-',
433 'filekey' => $this->mParams['filekey'] ?? '-',
434 'filesize' => $this->mParams['filesize'],
435 'chunkSize' => $chunkSize
436 ]
437 );
438 $this->dieWithError( 'apierror-stashfailed-nosession', 'stashfailed' );
439 } elseif ( $progress['result'] !== 'Continue' || $progress['stage'] !== 'uploading' ) {
440 $this->dieWithError( 'apierror-stashfailed-complete', 'stashfailed' );
441 }
442
443 $status = $this->mUpload->addChunk(
444 $chunkPath, $chunkSize, $this->mParams['offset'] );
445 if ( !$status->isGood() ) {
446 $extradata = [
447 'offset' => $this->mUpload->getOffset(),
448 ];
449 $this->log->info( "Chunked upload stash failure {status} for {user}",
450 [
451 'status' => (string)$status,
452 'user' => $this->getUser()->getName(),
453 'filename' => $this->mParams['filename'] ?? '-',
454 'filekey' => $this->mParams['filekey'] ?? '-',
455 'filesize' => $this->mParams['filesize'],
456 'chunkSize' => $chunkSize,
457 'offset' => $this->mUpload->getOffset()
458 ]
459 );
460 $this->dieStatusWithCode( $status, 'stashfailed', $extradata );
461 } else {
462 $this->log->debug( "Got chunk for {filename} with offset {offset} for {user}",
463 [
464 'user' => $this->getUser()->getName(),
465 'filename' => $this->mParams['filename'] ?? '-',
466 'filekey' => $this->mParams['filekey'] ?? '-',
467 'filesize' => $this->mParams['filesize'],
468 'chunkSize' => $chunkSize,
469 'offset' => $this->mUpload->getOffset()
470 ]
471 );
472 }
473 }
474
475 // Check we added the last chunk:
476 if ( $totalSoFar == $this->mParams['filesize'] ) {
477 if ( $this->mParams['async'] ) {
478 UploadBase::setSessionStatus(
479 $this->getUser(),
480 $filekey,
481 [ 'result' => 'Poll',
482 'stage' => 'queued', 'status' => Status::newGood() ]
483 );
484 // It is important that this be lazyPush, as we do not want to insert
485 // into job queue until after the current transaction has completed since
486 // this depends on values in uploadstash table that were updated during
487 // the current transaction. (T350917)
488 $this->jobQueueGroup->lazyPush( new AssembleUploadChunksJob( [
489 'filename' => $this->mParams['filename'],
490 'filekey' => $filekey,
491 'filesize' => $this->mParams['filesize'],
492 'session' => $this->getContext()->exportSession()
493 ] ) );
494 $this->log->info( "Received final chunk of {filename} for {user}, queuing assemble job",
495 [
496 'user' => $this->getUser()->getName(),
497 'filename' => $this->mParams['filename'] ?? '-',
498 'filekey' => $this->mParams['filekey'] ?? '-',
499 'filesize' => $this->mParams['filesize'],
500 'chunkSize' => $chunkSize,
501 ]
502 );
503 $result['result'] = 'Poll';
504 $result['stage'] = 'queued';
505 } else {
506 $this->log->info( "Received final chunk of {filename} for {user}, assembling immediately",
507 [
508 'user' => $this->getUser()->getName(),
509 'filename' => $this->mParams['filename'] ?? '-',
510 'filekey' => $this->mParams['filekey'] ?? '-',
511 'filesize' => $this->mParams['filesize'],
512 'chunkSize' => $chunkSize,
513 ]
514 );
515 UploadBase::setSessionStatus(
516 $this->getUser(),
517 $filekey,
518 [ 'result' => 'Poll', 'stage' => 'assembling', 'status' => Status::newGood() ]
519 );
520
521 try {
522 $status = $this->mUpload->concatenateChunks();
523 if ( !$status->isGood() ) {
524 UploadBase::setSessionStatus(
525 $this->getUser(),
526 $filekey,
527 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
528 );
529 $this->log->info( "Non jobqueue assembly of {filename} failed because {status}",
530 [
531 'user' => $this->getUser()->getName(),
532 'filename' => $this->mParams['filename'] ?? '-',
533 'filekey' => $this->mParams['filekey'] ?? '-',
534 'filesize' => $this->mParams['filesize'],
535 'chunkSize' => $chunkSize,
536 'status' => (string)$status
537 ]
538 );
539 $this->dieStatusWithCode( $status, 'stashfailed' );
540 }
541
542 // We can only get warnings like 'duplicate' after concatenating the chunks
543 $warnings = $this->getApiWarnings();
544 if ( $warnings ) {
545 $result['warnings'] = $warnings;
546 }
547
548 // The fully concatenated file has a new filekey. So remove
549 // the old filekey and fetch the new one.
550 $this->mUpload->stash->removeFile( $filekey );
551 $uploadFilekey = $filekey;
552 $filekey = $this->mUpload->getStashFile()->getFileKey();
553
554 $result['result'] = 'Success';
555 UploadBase::setSessionStatus(
556 $this->getUser(),
557 $uploadFilekey,
558 [
559 'result' => 'Success',
560 'stage' => 'assembling',
561 'filekey' => $filekey,
562 'status' => $status
563 ]
564 );
565 } catch ( ApiUsageException $e ) {
566 // Forward from self::dieStatusWithCode
567 throw $e;
568 } catch ( Exception $e ) {
569 $this->log->info(
570 'Non jobqueue assembly of {filename} failed: ' . get_class( $e ) . ' ' . $e->getMessage(),
571 [
572 'user' => $this->getUser()->getName(),
573 'filename' => $this->mParams['filename'] ?? '-',
574 'filekey' => $this->mParams['filekey'] ?? '-',
575 'filesize' => $this->mParams['filesize'],
576 'chunkSize' => $chunkSize,
577 'exception' => $e,
578 ]
579 );
580
581 $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
582 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
583 ) );
584 UploadBase::setSessionStatus(
585 $this->getUser(),
586 $filekey,
587 [ 'result' => 'Failure', 'stage' => 'assembling', 'status' => $status ]
588 );
589 throw $e;
590 }
591 }
592 } else {
593 UploadBase::setSessionStatus(
594 $this->getUser(),
595 $filekey,
596 [
597 'result' => 'Continue',
598 'stage' => 'uploading',
599 'offset' => $totalSoFar,
600 'status' => Status::newGood(),
601 ]
602 );
603 $result['result'] = 'Continue';
604 $result['offset'] = $totalSoFar;
605 }
606
607 $result['filekey'] = $filekey;
608
609 return $result;
610 }
611
624 private function performStash( $failureMode, &$data = [] ) {
625 if ( $failureMode === 'optional' && $this->mUpload->skipStashFileAttempt() ) {
626 return null;
627 }
628
629 $isPartial = (bool)$this->mParams['chunk'];
630 try {
631 $status = $this->mUpload->tryStashFile( $this->getUser(), $isPartial );
632
633 if ( $status->isGood() && !$status->getValue() ) {
634 // Not actually a 'good' status...
635 $status->fatal( new ApiMessage( 'apierror-stashinvalidfile', 'stashfailed' ) );
636 }
637 } catch ( Exception $e ) {
638 $debugMessage = 'Stashing temporary file failed: ' . get_class( $e ) . ' ' . $e->getMessage();
639 $this->log->info( $debugMessage,
640 [
641 'user' => $this->getUser()->getName(),
642 'filename' => $this->mParams['filename'] ?? '-',
643 'filekey' => $this->mParams['filekey'] ?? '-'
644 ]
645 );
646
647 $status = Status::newFatal( $this->getErrorFormatter()->getMessageFromException(
648 $e, [ 'wrap' => new ApiMessage( 'apierror-stashexception', 'stashfailed' ) ]
649 ) );
650 }
651
652 if ( $status->isGood() ) {
653 $stashFile = $status->getValue();
654 $data['filekey'] = $stashFile->getFileKey();
655 // Backwards compatibility
656 $data['sessionkey'] = $data['filekey'];
657 return $data['filekey'];
658 }
659
660 if ( $status->getMessage()->getKey() === 'uploadstash-exception' ) {
661 // The exceptions thrown by upload stash code and pretty silly and UploadBase returns poor
662 // Statuses for it. Just extract the exception details and parse them ourselves.
663 [ $exceptionType, $message ] = $status->getMessage()->getParams();
664 $debugMessage = 'Stashing temporary file failed: ' . $exceptionType . ' ' . $message;
665 $this->log->info( $debugMessage,
666 [
667 'user' => $this->getUser()->getName(),
668 'filename' => $this->mParams['filename'] ?? '-',
669 'filekey' => $this->mParams['filekey'] ?? '-'
670 ]
671 );
672 }
673
674 $this->log->info( "Stash upload failure {status}",
675 [
676 'status' => (string)$status,
677 'user' => $this->getUser()->getName(),
678 'filename' => $this->mParams['filename'] ?? '-',
679 'filekey' => $this->mParams['filekey'] ?? '-'
680 ]
681 );
682 // Bad status
683 if ( $failureMode !== 'optional' ) {
684 $this->dieStatus( $status );
685 } else {
686 $data['stasherrors'] = $this->getErrorFormatter()->arrayFromStatus( $status );
687 return null;
688 }
689 }
690
700 private function dieRecoverableError( $errors, $parameter = null ): never {
701 $data = [];
702 $this->performStash( 'optional', $data );
703
704 if ( $parameter ) {
705 $data['invalidparameter'] = $parameter;
706 }
707
708 $sv = StatusValue::newGood();
709 foreach ( $errors as $error ) {
710 $msg = ApiMessage::create( $error );
711 $msg->setApiData( $msg->getApiData() + $data );
712 $sv->fatal( $msg );
713 }
714 $this->dieStatus( $sv );
715 }
716
727 public function dieStatusWithCode( $status, $overrideCode, $moreExtraData = null ): never {
728 $sv = StatusValue::newGood();
729 foreach ( $status->getMessages() as $error ) {
730 $msg = ApiMessage::create( $error, $overrideCode );
731 if ( $moreExtraData ) {
732 $msg->setApiData( $msg->getApiData() + $moreExtraData );
733 }
734 $sv->fatal( $msg );
735 }
736 $this->dieStatus( $sv );
737 }
738
746 protected function selectUploadModule() {
747 // chunk or one and only one of the following parameters is needed
748 if ( !$this->mParams['chunk'] ) {
749 $this->requireOnlyOneParameter( $this->mParams,
750 'filekey', 'file', 'url' );
751 }
752
753 // Status report for "upload to stash"/"upload from stash"/"upload by url"
754 if ( $this->mParams['checkstatus'] &&
755 ( $this->mParams['filekey'] || ( $this->mParams['url'] && $this->mParams['filename'] ) )
756 ) {
757 $statusKey = $this->mParams['filekey'] ?: UploadFromUrl::getCacheKey( $this->mParams );
758 $progress = UploadBase::getSessionStatus( $this->getUser(), $statusKey );
759 if ( !$progress ) {
760 $this->log->info( "Cannot check upload status due to missing upload session for {user}",
761 [
762 'user' => $this->getUser()->getName(),
763 'url' => $this->mParams['url'] ?? '-',
764 'filename' => $this->mParams['filename'] ?? '-',
765 'filekey' => $this->mParams['filekey'] ?? '-'
766 ]
767 );
768 $this->dieWithError( 'apierror-upload-missingresult', 'missingresult' );
769 } elseif ( !$progress['status']->isGood() ) {
770 $this->dieStatusWithCode( $progress['status'], 'stashfailed' );
771 }
772 if ( isset( $progress['status']->value['verification'] ) ) {
773 $this->checkVerification( $progress['status']->value['verification'] );
774 }
775 if ( isset( $progress['status']->value['warnings'] ) ) {
776 $warnings = $this->transformWarnings( $progress['status']->value['warnings'] );
777 if ( $warnings ) {
778 $progress['warnings'] = $warnings;
779 }
780 }
781 // remove Status object
782 unset( $progress['status'] );
783 $imageinfo = null;
784 if ( $progress['result'] === 'Success' ) {
785 if ( isset( $progress['filekey'] ) ) {
786 // assembled file, load stashed file from upload stash for imageinfo
787 try {
788 $file = $this->localRepo->getUploadStash( $this->getUser() )->getFile( $progress['filekey'] );
789 $imageinfo = $this->getUploadImageInfoInternal( $file, true );
791 // Stash already gone, but not die to get a valid response and report the "Success" result.
792 }
793 } elseif ( isset( $progress['filename'] ) && isset( $progress['timestamp'] ) ) {
794 // published file, load local file from local repo for imageinfo
795 $file = $this->localRepo->findFile(
796 $progress['filename'],
797 [ 'time' => $progress['timestamp'], 'latest' => true ]
798 );
799 if ( $file ) {
800 $imageinfo = $this->getUploadImageInfoInternal( $file, false );
801 }
802 }
803 }
804
805 $this->getResult()->addValue( null, $this->getModuleName(), $progress );
806 // Add 'imageinfo' in a separate addValue() call. File metadata can be unreasonably large,
807 // so otherwise when it exceeded $wgAPIMaxResultSize, no result would be returned (T143993).
808 if ( $imageinfo ) {
809 $this->getResult()->addValue( $this->getModuleName(), 'imageinfo', $imageinfo );
810 }
811
812 return false;
813 }
814
815 // The following modules all require the filename parameter to be set
816 if ( $this->mParams['filename'] === null ) {
817 $this->dieWithError( [ 'apierror-missingparam', 'filename' ] );
818 }
819
820 if ( $this->mParams['chunk'] ) {
821 // Chunk upload
822 $this->mUpload = new UploadFromChunks( $this->getUser() );
823 if ( isset( $this->mParams['filekey'] ) ) {
824 if ( $this->mParams['offset'] === 0 ) {
825 $this->dieWithError( 'apierror-upload-filekeynotallowed', 'filekeynotallowed' );
826 }
827
828 // handle new chunk
829 $this->mUpload->continueChunks(
830 $this->mParams['filename'],
831 $this->mParams['filekey'],
832 $this->getMain()->getUpload( 'chunk' )
833 );
834 } else {
835 if ( $this->mParams['offset'] !== 0 ) {
836 $this->dieWithError( 'apierror-upload-filekeyneeded', 'filekeyneeded' );
837 }
838
839 // handle first chunk
840 $this->mUpload->initialize(
841 $this->mParams['filename'],
842 $this->getMain()->getUpload( 'chunk' )
843 );
844 }
845 } elseif ( isset( $this->mParams['filekey'] ) ) {
846 // Upload stashed in a previous request
847 if ( !UploadFromStash::isValidKey( $this->mParams['filekey'] ) ) {
848 $this->dieWithError( 'apierror-invalid-file-key' );
849 }
850
851 $this->mUpload = new UploadFromStash( $this->getUser() );
852 // This will not download the temp file in initialize() in async mode.
853 // We still have enough information to call checkWarnings() and such.
854 $this->mUpload->initialize(
855 $this->mParams['filekey'], $this->mParams['filename'], !$this->mParams['async']
856 );
857 } elseif ( isset( $this->mParams['file'] ) ) {
858 // Can't async upload directly from a POSTed file, we'd have to
859 // stash the file and then queue the publish job. The user should
860 // just submit the two API queries to perform those two steps.
861 if ( $this->mParams['async'] ) {
862 $this->dieWithError( 'apierror-cannot-async-upload-file' );
863 }
864
865 $this->mUpload = new UploadFromFile();
866 $this->mUpload->initialize(
867 $this->mParams['filename'],
868 $this->getMain()->getUpload( 'file' )
869 );
870 } elseif ( isset( $this->mParams['url'] ) ) {
871 // Make sure upload by URL is enabled:
872 if ( !UploadFromUrl::isEnabled() ) {
873 $this->dieWithError( 'copyuploaddisabled' );
874 }
875
876 if ( !UploadFromUrl::isAllowedHost( $this->mParams['url'] ) ) {
877 $this->dieWithError( 'apierror-copyuploadbaddomain' );
878 }
879
880 if ( !UploadFromUrl::isAllowedUrl( $this->mParams['url'] ) ) {
881 $this->dieWithError( 'apierror-copyuploadbadurl' );
882 }
883
884 $this->mUpload = new UploadFromUrl;
885 // This will not create the temp file in initialize() in async mode.
886 // We still have enough information to call checkWarnings() and such.
887 $this->mUpload->initialize( $this->mParams['filename'],
888 $this->mParams['url'], !$this->mParams['async'] );
889 }
890
891 return true;
892 }
893
899 protected function checkPermissions( $user ) {
900 // Check whether the user has the appropriate permissions to upload anyway
901 $permission = $this->mUpload->isAllowed( $user );
902
903 if ( $permission !== true ) {
904 if ( !$user->isNamed() ) {
905 $this->dieWithError( [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ] );
906 }
907
908 $this->dieStatus( User::newFatalPermissionDeniedStatus( $permission ) );
909 }
910
911 // Check blocks
912 if ( $user->isBlockedFromUpload() ) {
913 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Block is checked and not null
914 $this->dieBlocked( $user->getBlock() );
915 }
916 }
917
921 protected function verifyUpload() {
922 if ( $this->mParams['chunk'] ) {
923 $maxSize = UploadBase::getMaxUploadSize( 'file' );
924 if ( $this->mParams['filesize'] > $maxSize ) {
925 $this->dieWithError( 'file-too-large' );
926 }
927 if ( !$this->mUpload->getTitle() ) {
928 $this->dieWithError( 'illegal-filename' );
929 }
930 // file will be assembled after having uploaded the last chunk,
931 // so we can only validate the name at this point
932 $verification = $this->mUpload->validateName();
933 if ( $verification === true ) {
934 return;
935 }
936 } elseif ( $this->mParams['async'] && ( $this->mParams['filekey'] || $this->mParams['url'] ) ) {
937 // file will be assembled/downloaded in a background process, so we
938 // can only validate the name at this point
939 // file verification will happen in background process
940 $verification = $this->mUpload->validateName();
941 if ( $verification === true ) {
942 return;
943 }
944 } else {
945 wfDebug( __METHOD__ . " about to verify" );
946
947 $verification = $this->mUpload->verifyUpload();
948
949 if ( $verification['status'] === UploadBase::OK ) {
950 return;
951 } else {
952 $this->log->info( "File verification of {filename} failed for {user} because {result}",
953 [
954 'user' => $this->getUser()->getName(),
955 'resultCode' => $verification['status'],
956 'result' => $this->mUpload->getVerificationErrorCode( $verification['status'] ),
957 'filename' => $this->mParams['filename'] ?? '-',
958 'details' => $verification['details'] ?? ''
959 ]
960 );
961 }
962 }
963
964 $this->checkVerification( $verification );
965 }
966
972 protected function checkVerification( array $verification ): never {
973 $status = $this->mUpload->convertVerifyErrorToStatus( $verification );
974 if ( $status->isRecoverableError() ) {
975 $this->dieRecoverableError( [ $status->asApiMessage() ], $status->getInvalidParameter() );
976 // dieRecoverableError prevents continuation
977 }
978 $this->dieWithError( $status->asApiMessage() );
979 // dieWithError prevents continuation
980 }
981
989 protected function getApiWarnings() {
990 $warnings = UploadBase::makeWarningsSerializable(
991 $this->mUpload->checkWarnings( $this->getUser() )
992 );
993
994 return $this->transformWarnings( $warnings );
995 }
996
997 protected function transformWarnings( array $warnings ): array {
998 if ( $warnings ) {
999 // Add indices
1000 ApiResult::setIndexedTagName( $warnings, 'warning' );
1001
1002 if ( isset( $warnings['duplicate'] ) ) {
1003 $dupes = array_column( $warnings['duplicate'], 'fileName' );
1004 ApiResult::setIndexedTagName( $dupes, 'duplicate' );
1005 $warnings['duplicate'] = $dupes;
1006 }
1007
1008 if ( isset( $warnings['exists'] ) ) {
1009 $warning = $warnings['exists'];
1010 unset( $warnings['exists'] );
1011 $localFile = $warning['normalizedFile'] ?? $warning['file'];
1012 $warnings[$warning['warning']] = $localFile['fileName'];
1013 }
1014
1015 if ( isset( $warnings['no-change'] ) ) {
1016 $file = $warnings['no-change'];
1017 unset( $warnings['no-change'] );
1018
1019 $warnings['nochange'] = [
1020 'timestamp' => wfTimestamp( TS::ISO_8601, $file['timestamp'] )
1021 ];
1022 }
1023
1024 if ( isset( $warnings['duplicate-version'] ) ) {
1025 $dupes = [];
1026 foreach ( $warnings['duplicate-version'] as $dupe ) {
1027 $dupes[] = [
1028 'timestamp' => wfTimestamp( TS::ISO_8601, $dupe['timestamp'] )
1029 ];
1030 }
1031 unset( $warnings['duplicate-version'] );
1032
1033 ApiResult::setIndexedTagName( $dupes, 'ver' );
1034 $warnings['duplicateversions'] = $dupes;
1035 }
1036 }
1037
1038 return $warnings;
1039 }
1040
1047 protected function handleStashException( $e ) {
1048 $this->log->info( "Upload stashing of {filename} failed for {user} because {error}",
1049 [
1050 'user' => $this->getUser()->getName(),
1051 'error' => get_class( $e ),
1052 'filename' => $this->mParams['filename'] ?? '-',
1053 'filekey' => $this->mParams['filekey'] ?? '-'
1054 ]
1055 );
1056
1057 switch ( get_class( $e ) ) {
1058 case UploadStashFileNotFoundException::class:
1059 $wrap = 'apierror-stashedfilenotfound';
1060 break;
1061 case UploadStashBadPathException::class:
1062 $wrap = 'apierror-stashpathinvalid';
1063 break;
1064 case UploadStashFileException::class:
1065 $wrap = 'apierror-stashfilestorage';
1066 break;
1067 case UploadStashZeroLengthFileException::class:
1068 $wrap = 'apierror-stashzerolength';
1069 break;
1070 case UploadStashNotLoggedInException::class:
1071 return StatusValue::newFatal( ApiMessage::create(
1072 [ 'apierror-mustbeloggedin', $this->msg( 'action-upload' ) ], 'stashnotloggedin'
1073 ) );
1074 case UploadStashWrongOwnerException::class:
1075 $wrap = 'apierror-stashwrongowner';
1076 break;
1077 case UploadStashNoSuchKeyException::class:
1078 $wrap = 'apierror-stashnosuchfilekey';
1079 break;
1080 default:
1081 $wrap = [ 'uploadstash-exception', get_class( $e ) ];
1082 break;
1083 }
1084 return StatusValue::newFatal(
1085 $this->getErrorFormatter()->getMessageFromException( $e, [ 'wrap' => $wrap ] )
1086 );
1087 }
1088
1096 protected function performUpload( $warnings ) {
1097 if ( $this->mParams['autotext'] ) {
1098 // Generate the file page wikitext server-side from the provided
1099 // parameters, overriding any client-supplied 'text'. Extensions
1100 // may alter this text via the UploadForm:getInitialPageText hook,
1101 // just like Special:Upload does.
1102 $this->mParams['text'] = SpecialUpload::getInitialPageText(
1103 $this->mParams['comment'],
1104 $this->mParams['license'],
1105 $this->mParams['copystatus'],
1106 $this->mParams['source'],
1107 $this->getConfig()
1108 );
1109 } else {
1110 // Use comment as initial page text by default
1111 $this->mParams['text'] ??= $this->mParams['comment'];
1112 }
1113
1115 $file = $this->mUpload->getLocalFile();
1116 $user = $this->getUser();
1117 $title = $file->getTitle();
1118
1119 // for preferences mode, we want to watch if 'watchdefault' is set,
1120 // or if the *file* doesn't exist, and either 'watchuploads' or
1121 // 'watchcreations' is set. But getWatchlistValue()'s automatic
1122 // handling checks if the *title* exists or not, so we need to check
1123 // all three preferences manually.
1124 $watch = $this->getWatchlistValue(
1125 $this->mParams['watchlist'], $title, $user, 'watchdefault'
1126 );
1127
1128 if ( !$watch && $this->mParams['watchlist'] == 'preferences' && !$file->exists() ) {
1129 $watch = (
1130 $this->getWatchlistValue( 'preferences', $title, $user, 'watchuploads' ) ||
1131 $this->getWatchlistValue( 'preferences', $title, $user, 'watchcreations' )
1132 );
1133 }
1134 $expiryOption = $file->exists() ? 'watchdefault-expiry' : 'watchcreations-expiry';
1135 $watchlistExpiry = $this->getExpiryFromParams( $this->mParams, $title, $user, $expiryOption );
1136
1137 // Deprecated parameters
1138 if ( $this->mParams['watch'] ) {
1139 $watch = true;
1140 }
1141
1142 if ( $this->mParams['tags'] ) {
1143 $status = ChangeTags::canAddTagsAccompanyingChange( $this->mParams['tags'], $this->getAuthority() );
1144 if ( !$status->isOK() ) {
1145 $this->dieStatus( $status );
1146 }
1147 }
1148
1149 // No errors, no warnings: do the upload
1150 $result = [];
1151 if ( $this->mParams['async'] ) {
1152 // Only stash uploads and copy uploads support async
1153 if ( $this->mParams['filekey'] ) {
1155 [
1156 'filename' => $this->mParams['filename'],
1157 'filekey' => $this->mParams['filekey'],
1158 'comment' => $this->mParams['comment'],
1159 'tags' => $this->mParams['tags'] ?? [],
1160 'text' => $this->mParams['text'],
1161 'watch' => $watch,
1162 'watchlistexpiry' => $watchlistExpiry,
1163 'session' => $this->getContext()->exportSession(),
1164 'ignorewarnings' => $this->mParams['ignorewarnings']
1165 ]
1166 );
1167 } elseif ( $this->mParams['url'] ) {
1168 $job = new UploadFromUrlJob(
1169 [
1170 'filename' => $this->mParams['filename'],
1171 'url' => $this->mParams['url'],
1172 'comment' => $this->mParams['comment'],
1173 'tags' => $this->mParams['tags'] ?? [],
1174 'text' => $this->mParams['text'],
1175 'watch' => $watch,
1176 'watchlistexpiry' => $watchlistExpiry,
1177 'session' => $this->getContext()->exportSession(),
1178 'ignorewarnings' => $this->mParams['ignorewarnings']
1179 ]
1180 );
1181 } else {
1182 $this->dieWithError( 'apierror-no-async-support', 'publishfailed' );
1183 // We will never reach this, but it's here to help phan figure out
1184 // $job is never null
1185 // @phan-suppress-next-line PhanPluginUnreachableCode On purpose
1186 return [];
1187 }
1188 $cacheKey = $job->getCacheKey();
1189 // Check if an upload is already in progress.
1190 // the result can be Poll / Failure / Success
1191 $progress = UploadBase::getSessionStatus( $this->getUser(), $cacheKey );
1192 if ( $progress && $progress['result'] === 'Poll' ) {
1193 $this->dieWithError( 'apierror-upload-inprogress', 'publishfailed' );
1194 }
1195 UploadBase::setSessionStatus(
1196 $this->getUser(),
1197 $cacheKey,
1198 [ 'result' => 'Poll', 'stage' => 'queued', 'status' => Status::newGood() ]
1199 );
1200
1201 $this->jobQueueGroup->push( $job );
1202 $this->log->info( "Sending publish job of {filename} for {user}",
1203 [
1204 'user' => $this->getUser()->getName(),
1205 'filename' => $this->mParams['filename'] ?? '-'
1206 ]
1207 );
1208 $result['result'] = 'Poll';
1209 $result['stage'] = 'queued';
1210 } else {
1211 $status = $this->mUpload->performUpload(
1212 $this->mParams['comment'],
1213 $this->mParams['text'],
1214 $watch,
1215 $this->getUser(),
1216 $this->mParams['tags'] ?? [],
1217 $watchlistExpiry
1218 );
1219
1220 if ( !$status->isGood() ) {
1221 $this->log->info( "Non-async API upload publish failed for {user} because {status}",
1222 [
1223 'user' => $this->getUser()->getName(),
1224 'filename' => $this->mParams['filename'] ?? '-',
1225 'filekey' => $this->mParams['filekey'] ?? '-',
1226 'status' => (string)$status
1227 ]
1228 );
1229 $this->dieRecoverableError( $status->getMessages() );
1230 }
1231 $result['result'] = 'Success';
1232 }
1233
1234 $result['filename'] = $file->getName();
1235 if ( $warnings && count( $warnings ) > 0 ) {
1236 $result['warnings'] = $warnings;
1237 }
1238
1239 return $result;
1240 }
1241
1243 public function mustBePosted() {
1244 return true;
1245 }
1246
1248 public function isWriteMode() {
1249 return true;
1250 }
1251
1253 public function getAllowedParams() {
1254 $params = [
1255 'filename' => [
1256 ParamValidator::PARAM_TYPE => 'string',
1257 ],
1258 'comment' => [
1259 ParamValidator::PARAM_DEFAULT => ''
1260 ],
1261 'tags' => [
1262 ParamValidator::PARAM_TYPE => 'tags',
1263 ParamValidator::PARAM_ISMULTI => true,
1264 ],
1265 'text' => [
1266 ParamValidator::PARAM_TYPE => 'text',
1267 ],
1268 'watch' => [
1269 ParamValidator::PARAM_DEFAULT => false,
1270 ParamValidator::PARAM_DEPRECATED => true,
1271 ],
1272 ];
1273
1274 // Params appear in the docs in the order they are defined,
1275 // which is why this is here and not at the bottom.
1276 $params += $this->getWatchlistParams( [
1277 'watch',
1278 'preferences',
1279 'nochange',
1280 ] );
1281
1282 $params += [
1283 'ignorewarnings' => false,
1284 'file' => [
1285 ParamValidator::PARAM_TYPE => 'upload',
1286 ],
1287 'url' => null,
1288 'filekey' => null,
1289 'sessionkey' => [
1290 ParamValidator::PARAM_DEPRECATED => true,
1291 ],
1292 'stash' => false,
1293
1294 'filesize' => [
1295 ParamValidator::PARAM_TYPE => 'integer',
1296 IntegerDef::PARAM_MIN => 0,
1297 IntegerDef::PARAM_MAX => UploadBase::getMaxUploadSize( 'file' ),
1298 ],
1299 'offset' => [
1300 ParamValidator::PARAM_TYPE => 'integer',
1301 IntegerDef::PARAM_MIN => 0,
1302 ],
1303 'chunk' => [
1304 ParamValidator::PARAM_TYPE => 'upload',
1305 ],
1306
1307 'async' => false,
1308 'checkstatus' => false,
1309
1310 'autotext' => [
1311 ParamValidator::PARAM_TYPE => 'boolean',
1312 ParamValidator::PARAM_DEFAULT => false,
1313 ],
1314 'license' => [
1315 ParamValidator::PARAM_TYPE => 'string',
1316 ParamValidator::PARAM_DEFAULT => ''
1317 ],
1318 ];
1319
1320 if ( $this->getConfig()->get( MainConfigNames::UseCopyrightUpload ) ) {
1321 $params += [
1322 'copystatus' => [
1323 ParamValidator::PARAM_TYPE => 'string',
1324 ParamValidator::PARAM_DEFAULT => ''
1325 ],
1326 'source' => [
1327 ParamValidator::PARAM_TYPE => 'string',
1328 ParamValidator::PARAM_DEFAULT => ''
1329 ],
1330 ];
1331 }
1332
1333 return $params;
1334 }
1335
1337 public function needsToken() {
1338 return 'csrf';
1339 }
1340
1342 protected function getExamplesMessages() {
1343 return [
1344 'action=upload&filename=Wiki.png' .
1345 '&url=http%3A//upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png&token=123ABC'
1346 => 'apihelp-upload-example-url',
1347 'action=upload&filename=Wiki.png&filekey=filekey&ignorewarnings=1&token=123ABC'
1348 => 'apihelp-upload-example-filekey',
1349 ];
1350 }
1351
1353 public function getHelpUrls() {
1354 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Upload';
1355 }
1356}
1357
1359class_alias( ApiUpload::class, 'ApiUpload' );
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfShorthandToInteger(?string $string='', int $default=-1)
Converts shorthand byte notation to integer form.
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:72
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:59
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition ApiBase.php:1482
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:556
getMain()
Get the main module.
Definition ApiBase.php:574
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition ApiBase.php:1329
getResult()
Get the result object.
Definition ApiBase.php:695
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1399
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition ApiBase.php:1719
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
Definition ApiBase.php:1510
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition ApiBase.php:1533
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:830
requireOnlyOneParameter( $params,... $required)
Die if 0 or more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:968
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:66
static create( $msg, $code=null, ?array $data=null)
Create an IApiMessage for the message.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
checkVerification(array $verification)
Performs file verification, dies on error.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
handleStashException( $e)
Handles a stash exception, giving a useful error to the user.
checkPermissions( $user)
Checks that the user has permissions to perform this upload.
selectUploadModule()
Select an upload module and set it to mUpload.
transformWarnings(array $warnings)
dieStatusWithCode( $status, $overrideCode, $moreExtraData=null)
Like dieStatus(), but always uses $overrideCode for the error code, unless the code comes from IApiMe...
static getMinUploadChunkSize(Config $config)
verifyUpload()
Performs file verification, dies on error.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiUpload.php:96
getUploadImageInfo(UploadBase $upload)
Gets image info about the file just uploaded.
getApiWarnings()
Check warnings.
needsToken()
Returns the token type this module requires in order to execute.Modules are strongly encouraged to us...
__construct(ApiMain $mainModule, string $moduleName, private readonly JobQueueGroup $jobQueueGroup, WatchlistManager $watchlistManager, WatchedItemStoreInterface $watchedItemStore, UserOptionsLookup $userOptionsLookup, RepoGroup $repoGroup,)
Definition ApiUpload.php:74
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
UploadBase UploadFromChunks null $mUpload
Definition ApiUpload.php:65
performUpload( $warnings)
Perform the actual upload.
getHelpUrls()
Return links to more detailed help pages about the module.1.25, returning boolean false is deprecated...
mustBePosted()
Indicates whether this module must be called with a POST request.Implementations of this method must ...
isWriteMode()
Indicates whether this module requires write access to the wiki.API modules must override this method...
Recent changes tagging.
exportSession()
Export the resolved user IP, HTTP headers, user ID, and session ID.
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage().
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:80
Local file in the wiki's own database.
Definition LocalFile.php:80
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:43
Prioritized list of file repositories.
Definition RepoGroup.php:30
getLocalRepo()
Get the local repository, i.e.
Handle enqueueing of background jobs.
Assemble the segments of a chunked upload.
Upload a file from the upload stash into the local file repo.
Upload a file by URL, via the jobqueue.
Create PSR-3 logger objects.
A class containing constants representing the names of configuration variables.
const EnableAsyncUploads
Name constant for the EnableAsyncUploads setting, for use with Config\get().
const WatchlistExpiry
Name constant for the WatchlistExpiry setting, for use with Config\get().
const MinUploadChunkSize
Name constant for the MinUploadChunkSize setting, for use with Config\get().
const UseCopyrightUpload
Name constant for the UseCopyrightUpload setting, for use with Config\get().
const EnableAsyncUploadsByURL
Name constant for the EnableAsyncUploadsByURL setting, for use with Config\get().
const WatchlistExpiryMaxDuration
Name constant for the WatchlistExpiryMaxDuration setting, for use with Config\get().
Service locator for MediaWiki core services.
static getInstance()
Returns the global default instance of the top level service locator.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:144
Form for uploading media files.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
UploadBase and subclasses are the backend of MediaWiki's file uploads.
getLocalFile()
Return the local file and initializes if necessary.
Implements uploading from chunks.
Implements regular file uploads.
Implements uploading from previously stored file.
Implements uploading from a HTTP resource.
initialize( $name, $url, $initTempFile=true)
Entry point for API upload.
Provides access to user options.
User class for the MediaWiki software.
Definition User.php:129
static newGood( $value=null)
Factory function for good results.
trait ApiWatchlistTrait
An ApiWatchlistTrait adds class properties and convenience methods for APIs that allow you to watch a...
Interface for configuration instances.
Definition Config.php:18
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
getWatchlistValue(string $watchlist, PageIdentity $page, User $user, ?string $userOption=null)
Return true if we're to watch the page, false if not.
getWatchlistParams(array $watchOptions=[])
Get additional allow params specific to watchlisting.
getExpiryFromParams(array $params, ?PageIdentity $page=null, ?UserIdentity $user=null, string $userOption='watchdefault-expiry')
Get formatted expiry from the given parameters.
if(count( $args)< 1) $job