MediaWiki master
SpecialUpload.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Specials;
8
41use Psr\Log\LoggerInterface;
42use UnexpectedValueException;
43use UploadForm;
45
53
54 private LocalRepo $localRepo;
55 private UserOptionsLookup $userOptionsLookup;
56 private NamespaceInfo $nsInfo;
57 private WatchlistManager $watchlistManager;
58 private JobQueueGroup $jobQueueGroup;
59 private LoggerInterface $log;
60
61 public function __construct(
62 ?RepoGroup $repoGroup = null,
63 ?UserOptionsLookup $userOptionsLookup = null,
64 ?NamespaceInfo $nsInfo = null,
65 ?WatchlistManager $watchlistManager = null
66 ) {
67 parent::__construct( 'Upload', 'upload' );
68 // This class is extended and therefor fallback to global state - T265300
70 $this->jobQueueGroup = $services->getJobQueueGroup();
71 $repoGroup ??= $services->getRepoGroup();
72 $this->localRepo = $repoGroup->getLocalRepo();
73 $this->userOptionsLookup = $userOptionsLookup ?? $services->getUserOptionsLookup();
74 $this->nsInfo = $nsInfo ?? $services->getNamespaceInfo();
75 $this->watchlistManager = $watchlistManager ?? $services->getWatchlistManager();
76 $this->log = LoggerFactory::getInstance( 'SpecialUpload' );
77 }
78
79 private function addMessageBoxStyling() {
80 $this->getOutput()->addModuleStyles( 'mediawiki.codex.messagebox.styles' );
81 }
82
84 public function doesWrites() {
85 return true;
86 }
87
88 // Misc variables
89
91 public $mRequest;
94
96 public $mCacheKey;
97
99 public $mUpload;
100
105
106 // User input variables from the "description" section
107
111 public $mComment;
113 public $mLicense;
114
115 // User input variables from the root section
116
125
126 // Hidden variables
127
130
133
137 public $mTokenOk;
138
140 public $mUploadSuccessful = false;
141
146
150 protected function loadRequest() {
151 $this->mRequest = $request = $this->getRequest();
152 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
153 $this->mUpload = UploadBase::createFromRequest( $request );
154 $this->mUploadClicked = $request->wasPosted()
155 && ( $request->getCheck( 'wpUpload' )
156 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
157
158 // Guess the desired name from the filename if not provided
159 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
160 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
161 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
162 }
163 $this->mLicense = $request->getText( 'wpLicense' );
164
165 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
166 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
167 || $request->getCheck( 'wpUploadIgnoreWarning' );
168 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isRegistered();
169 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
170 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
171
172 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
173
174 $commentDefault = '';
175 $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
176 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
177 $commentDefault = $commentMsg->plain();
178 }
179 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
180
181 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
182 || $request->getCheck( 'wpReUpload' ); // b/w compat
183
184 // If it was posted check for the token (no remote POST'ing with user credentials)
185 $token = $request->getVal( 'wpEditToken' );
186 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
187
188 // If this is an upload from Url and we're allowing async processing,
189 // check for the presence of the cache key parameter, or compute it. Else, it should be empty.
190 if ( $this->isAsyncUpload() ) {
191 $this->mCacheKey = \MediaWiki\Upload\UploadFromUrl::getCacheKeyFromRequest( $request );
192 } else {
193 $this->mCacheKey = '';
194 }
195
196 $this->uploadFormTextTop = '';
197 $this->uploadFormTextAfterSummary = '';
198 }
199
205 protected function isAsyncUpload() {
206 return $this->mSourceType === 'url'
209 }
210
219 public function userCanExecute( User $user ) {
220 return UploadBase::isEnabled() && parent::userCanExecute( $user );
221 }
222
226 public function execute( $par ) {
228
229 $this->setHeaders();
230 $this->outputHeader();
231
232 # Check uploading enabled
233 if ( !UploadBase::isEnabled() ) {
234 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
235 }
236
237 $this->addHelpLink( 'Help:Managing files' );
238
239 # Check permissions
240 $user = $this->getUser();
241 $permissionRequired = UploadBase::isAllowed( $user );
242 if ( $permissionRequired !== true ) {
243 throw new PermissionsError( $permissionRequired );
244 }
245
246 # Check blocks
247 if ( $user->isBlockedFromUpload() ) {
248 throw new UserBlockedError(
249 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Block is checked and not null
250 $user->getBlock(),
251 $user,
252 $this->getLanguage(),
253 $this->getRequest()->getIP()
254 );
255 }
256
257 # Check whether we actually want to allow changing stuff
258 $this->checkReadOnly();
259
260 try {
261 $this->loadRequest();
262 } catch ( UploadStashException $e ) {
263 $this->showUploadError( $this->msg( 'upload-stash-error', $e->getMessageObject() )->escaped() );
264 return;
265 }
266
267 # Unsave the temporary file in case this was a cancelled upload
268 if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
269 # Something went wrong, so unsaveUploadedFile showed a warning
270 return;
271 }
272
273 # If we have a cache key, show the upload status.
274 if ( $this->mTokenOk && $this->mCacheKey !== '' ) {
275 if ( $this->mUpload && $this->mUploadClicked && !$this->mCancelUpload ) {
276 # If the user clicked the upload button, we need to process the upload
277 $this->processAsyncUpload();
278 } else {
279 # Show the upload status
280 $this->showUploadStatus( $user );
281 }
282 } elseif (
283 # Process upload or show a form
284 $this->mTokenOk && !$this->mCancelUpload &&
285 ( $this->mUpload && $this->mUploadClicked )
286 ) {
287 $this->processUpload();
288 } else {
289 # Backwards compatibility hook
290 if ( !$this->getHookRunner()->onUploadForm_initial( $this ) ) {
291 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
292
293 return;
294 }
295 $this->showUploadForm( $this->getUploadForm( '', $this->mUpload?->getStashFile()?->getFileKey() ) );
296 }
297
298 # Cleanup
299 if ( $this->mUpload ) {
300 $this->mUpload->cleanupTempFile();
301 }
302 }
303
309 protected function showUploadStatus( $user ) {
310 // first, let's fetch the status from the main stash
311 $progress = UploadBase::getSessionStatus( $user, $this->mCacheKey );
312 if ( !$progress ) {
313 $progress = [ 'status' => Status::newFatal( 'invalid-cache-key' ) ];
314 }
315 $this->log->debug( 'Upload status: stage {stage}, result {result}', $progress );
316
317 $status = $progress['status'] ?? Status::newFatal( 'invalid-cache-key' );
318 $stage = $progress['stage'] ?? 'unknown';
319 $result = $progress['result'] ?? 'unknown';
320 switch ( $stage ) {
321 case 'publish':
322 switch ( $result ) {
323 case 'Success':
324 // The upload is done. Check the result and either show the form with the error
325 // occurred, or redirect to the file itself
326 // Success, redirect to description page
327 $this->mUploadSuccessful = true;
328 $this->getHookRunner()->onSpecialUploadComplete( $this );
329 // Redirect to the destination URL, but purge the cache of the file description page first
330 // TODO: understand why this is needed
331 $title = Title::makeTitleSafe( NS_FILE, $this->mRequest->getText( 'wpDestFile' ) );
332 if ( $title ) {
333 $this->log->debug( 'Purging page', [ 'title' => $title->getText() ] );
334 $page = new WikiFilePage( $title );
335 $page->doPurge();
336 }
337 $this->getOutput()->redirect( $this->mRequest->getText( 'wpDestUrl' ) );
338 break;
339 case 'Warning':
340 $this->showUploadWarning( UploadBase::unserializeWarnings( $progress['warnings'] ) );
341 break;
342 case 'Failure':
343 $details = $status->getValue();
344 // Verification failed.
345 if ( is_array( $details ) && isset( $details['verification'] ) ) {
346 $this->processVerificationError( $details['verification'] );
347 } else {
348 $this->showUploadError( $this->getOutput()->parseAsInterface(
349 $status->getWikiText( false, false, $this->getLanguage() ) )
350 );
351 }
352 break;
353 case 'Poll':
354 $this->showUploadProgress(
355 [ 'active' => true, 'msg' => 'upload-progress-processing' ]
356 );
357 break;
358 default:
359 // unknown result, just show a generic error
360 $this->showUploadError( $this->getOutput()->parseAsInterface(
361 $status->getWikiText( false, false, $this->getLanguage() ) )
362 );
363 break;
364 }
365 break;
366 case 'queued':
367 // show stalled progress bar
368 $this->showUploadProgress( [ 'active' => false, 'msg' => 'upload-progress-queued' ] );
369 break;
370 case 'fetching':
371 switch ( $result ) {
372 case 'Success':
373 // The file is being downloaded from a URL
374 // TODO: show active progress bar saying we're downloading the file
375 $this->showUploadProgress( [ 'active' => true, 'msg' => 'upload-progress-downloading' ] );
376 break;
377 case 'Failure':
378 // downloading failed
379 $this->showUploadError( $this->getOutput()->parseAsInterface(
380 $status->getWikiText( false, false, $this->getLanguage() ) )
381 );
382 break;
383 default:
384 // unknown result, just show a generic error
385 $this->showUploadError( $this->getOutput()->parseAsInterface(
386 $status->getWikiText( false, false, $this->getLanguage() ) )
387 );
388 break;
389 }
390 break;
391 default:
392 // unknown status, just show a generic error
393 if ( $status->isOK() ) {
394 $status = Status::newFatal( 'upload-progress-unknown' );
395 }
396 $statusmsg = $this->getOutput()->parseAsInterface(
397 $status->getWikiText( false, false, $this->getLanguage() )
398 );
399 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . '</h2>' . Html::errorBox( $statusmsg );
400 $this->addMessageBoxStyling();
401 $this->showUploadForm( $this->getUploadForm( $message ) );
402 break;
403 }
404 }
405
416 private function showUploadProgress( $options ) {
417 // $isActive = $options['active'] ?? false;
418 //$progressBarProperty = $isActive ? '' : 'disabled';
419 $message = $this->msg( $options['msg'] )->escaped();
420 $destUrl = $this->mRequest->getText( 'wpDestUrl', '' );
421 if ( !$destUrl && $this->mUpload ) {
422 if ( !$this->mLocalFile ) {
423 $this->mLocalFile = $this->mUpload->getLocalFile();
424 }
425 // This probably means the title is bad, so we can't get the URL
426 // but we need to wait for the job to execute.
427 if ( $this->mLocalFile === null ) {
428 $destUrl = '';
429 } else {
430 $destUrl = $this->mLocalFile->getTitle()->getFullURL();
431 }
432 }
433
434 $destName = $this->mDesiredDestName;
435 if ( !$destName ) {
436 $destName = $this->mRequest->getText( 'wpDestFile' );
437 }
438
439 // Needed if we have warnings to show
440 $sourceURL = $this->mRequest->getText( 'wpUploadFileURL' );
441
442 $form = new HTMLForm( [
443 'CacheKey' => [
444 'type' => 'hidden',
445 'default' => $this->mCacheKey,
446 ],
447 'SourceType' => [
448 'type' => 'hidden',
449 'default' => $this->mSourceType,
450 ],
451 'DestUrl' => [
452 'type' => 'hidden',
453 'default' => $destUrl,
454 ],
455 'DestFile' => [
456 'type' => 'hidden',
457 'default' => $destName,
458 ],
459 'UploadFileURL' => [
460 'type' => 'hidden',
461 'default' => $sourceURL,
462 ],
463 ], $this->getContext(), 'uploadProgress' );
464 $form->setSubmitText( $this->msg( 'upload-refresh' )->escaped() );
465 // TODO: use codex, add a progress bar
466 //$preHtml = "<cdx-progress-bar aria--label='upload progressbar' $progressBarProperty />";
467 $preHtml = "<div id='upload-progress-message'>$message</div>";
468 $form->addPreHtml( $preHtml );
469 $form->setSubmitCallback(
470 static function ( $formData ) {
471 return true;
472 }
473 );
474 $form->prepareForm();
475 $this->getOutput()->addHTML( $form->getHTML( false ) );
476 }
477
483 protected function showUploadForm( $form ) {
484 if ( $form instanceof HTMLForm ) {
485 $form->show();
486 } else {
487 $this->getOutput()->addHTML( $form );
488 }
489 }
490
499 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
500 # Initialize form
501 $form = new UploadForm(
502 [
503 'watch' => $this->getWatchCheck(),
504 'forreupload' => $this->mForReUpload,
505 'sessionkey' => $sessionKey,
506 'hideignorewarning' => $hideIgnoreWarning,
507 'destwarningack' => (bool)$this->mDestWarningAck,
508
509 'description' => $this->mComment,
510 'texttop' => $this->uploadFormTextTop,
511 'textaftersummary' => $this->uploadFormTextAfterSummary,
512 'destfile' => $this->mDesiredDestName,
513 ],
514 $this->getContext(),
515 $this->getLinkRenderer(),
516 $this->localRepo,
517 $this->getContentLanguage(),
518 $this->nsInfo,
519 $this->getHookContainer()
520 );
521 $form->setTitle( $this->getPageTitle() ); // Remove subpage
522
523 # Check the token, but only if necessary
524 if (
525 !$this->mTokenOk && !$this->mCancelUpload &&
526 ( $this->mUpload && $this->mUploadClicked )
527 ) {
528 $form->addPreHtml( $this->msg( 'session_fail_preview' )->parse() );
529 }
530
531 # Give a notice if the user is uploading a file that has been deleted or moved
532 # Note that this is independent from the message 'filewasdeleted'
533 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
534 $delNotice = ''; // empty by default
535 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
536 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
537 $desiredTitleObj,
538 '', [ 'lim' => 10,
539 'conds' => [ $this->localRepo->getReplicaDB()->expr( 'log_action', '!=', 'revision' ) ],
540 'showIfEmpty' => false,
541 'msgKey' => [ 'upload-recreate-warning' ] ]
542 );
543 }
544 $form->addPreHtml( $delNotice );
545
546 # Add text to form
547 $form->addPreHtml( '<div id="uploadtext">' .
548 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
549 '</div>' );
550 # Add upload error message
551 $form->addPreHtml( $message );
552
553 # Add footer to form
554 $uploadFooter = $this->msg( 'uploadfooter' );
555 if ( !$uploadFooter->isDisabled() ) {
556 $form->addPostHtml( '<div id="mw-upload-footer-message">'
557 . $uploadFooter->parseAsBlock() . "</div>\n" );
558 }
559
560 return $form;
561 }
562
574 protected function showRecoverableUploadError( $message ) {
575 $stashFile = $this->mUpload->getStashFile();
576 if ( !$stashFile ) {
577 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
578 if ( $stashStatus->isGood() ) {
579 $stashFile = $stashStatus->getValue();
580 }
581 }
582 if ( $stashFile ) {
583 $sessionKey = $stashFile->getFileKey();
584 $uploadWarning = 'upload-tryagain';
585 } else {
586 $sessionKey = null;
587 $uploadWarning = 'upload-tryagain-nostash';
588 }
589 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . '</h2>' .
590 Html::errorBox( $message );
591
592 $this->addMessageBoxStyling();
593 $form = $this->getUploadForm( $message, $sessionKey );
594 $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
595 $this->showUploadForm( $form );
596 }
597
606 protected function showUploadWarning( $warnings ) {
607 # If there are no warnings, or warnings we can ignore, return early.
608 # mDestWarningAck is set when some javascript has shown the warning
609 # to the user. mForReUpload is set when the user clicks the "upload a
610 # new version" link.
611 if ( !$warnings || ( count( $warnings ) == 1
612 && isset( $warnings['exists'] )
613 && ( $this->mDestWarningAck || $this->mForReUpload ) )
614 ) {
615 return false;
616 }
617
618 if ( $this->mUpload ) {
619 $stashFile = $this->mUpload->getStashFile();
620 if ( !$stashFile ) {
621 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
622 if ( $stashStatus->isGood() ) {
623 $stashFile = $stashStatus->getValue();
624 }
625 }
626 if ( $stashFile ) {
627 $sessionKey = $stashFile->getFileKey();
628 $uploadWarning = 'uploadwarning-text';
629 } else {
630 $sessionKey = null;
631 $uploadWarning = 'uploadwarning-text-nostash';
632 }
633 } else {
634 $sessionKey = null;
635 $uploadWarning = 'uploadwarning-text-nostash';
636 }
637
638 // Add styles for the warning, reused from the live preview
639 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
640
641 $linkRenderer = $this->getLinkRenderer();
642 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
643 . '<div class="mw-destfile-warning"><ul>';
644 foreach ( $warnings as $warning => $args ) {
645 if ( $warning == 'badfilename' ) {
646 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
647 }
648 if ( $warning == 'exists' ) {
649 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
650 } elseif ( $warning == 'no-change' ) {
651 $file = $args;
652 $filename = $file->getTitle()->getPrefixedText();
653 $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
654 } elseif ( $warning == 'duplicate-version' ) {
655 $file = $args[0];
656 $count = count( $args );
657 $filename = $file->getTitle()->getPrefixedText();
658 $message = $this->msg( 'fileexists-duplicate-version' )
659 ->params( $filename )
660 ->numParams( $count );
661 $msg = "\t<li>" . $message->parse() . "</li>\n";
662 } elseif ( $warning == 'was-deleted' ) {
663 # If the file existed before and was deleted, warn the user of this
664 $ltitle = SpecialPage::getTitleFor( 'Log' );
665 $llink = $linkRenderer->makeKnownLink(
666 $ltitle,
667 $this->msg( 'deletionlog' )->text(),
668 [],
669 [
670 'type' => 'delete',
671 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
672 ]
673 );
674 $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
675 } elseif ( $warning == 'duplicate' ) {
676 $msg = $this->getDupeWarning( $args );
677 } elseif ( $warning == 'duplicate-archive' ) {
678 if ( $args === '' ) {
679 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
680 . "</li>\n";
681 } else {
682 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
683 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
684 . "</li>\n";
685 }
686 } else {
687 if ( $args === true ) {
688 $args = [];
689 } elseif ( !is_array( $args ) ) {
690 $args = [ $args ];
691 }
692 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
693 }
694 $warningHtml .= $msg;
695 }
696 $warningHtml .= "</ul></div>\n";
697 $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
698
699 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
700 $form->setSubmitTextMsg( 'upload-tryagain' );
701 $form->addButton( [
702 'name' => 'wpUploadIgnoreWarning',
703 'value' => $this->msg( 'ignorewarning' )->text()
704 ] );
705 $form->addButton( [
706 'name' => 'wpCancelUpload',
707 'value' => $this->msg( 'reuploaddesc' )->text()
708 ] );
709
710 $this->showUploadForm( $form );
711
712 # Indicate that we showed a form
713 return true;
714 }
715
721 protected function showUploadError( $message ) {
722 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . '</h2>' .
723 Html::errorBox( $message );
724 $this->showUploadForm( $this->getUploadForm( $message ) );
725 $this->addMessageBoxStyling();
726 }
727
734 protected function performUploadChecks( $fetchFileStatus ): bool {
735 if ( !$fetchFileStatus->isOK() ) {
736 $this->showUploadError( $this->getOutput()->parseAsInterface(
737 $fetchFileStatus->getWikiText( false, false, $this->getLanguage() )
738 ) );
739
740 return false;
741 }
742 if ( !$this->getHookRunner()->onUploadForm_BeforeProcessing( $this ) ) {
743 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
744 // This code path is deprecated. If you want to break upload processing
745 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
746 // and UploadBase::verifyFile.
747 // If you use this hook to break uploading, the user will be returned
748 // an empty form with no error message whatsoever.
749 return false;
750 }
751
752 // Upload verification
753 // If this is an asynchronous upload-by-url, skip the verification
754 if ( $this->isAsyncUpload() ) {
755 return true;
756 }
757 $details = $this->mUpload->verifyUpload();
758 if ( $details['status'] != UploadBase::OK ) {
759 $this->processVerificationError( $details );
760
761 return false;
762 }
763
764 // Verify permissions for this title
765 $user = $this->getUser();
766 $status = $this->mUpload->authorizeUpload( $user );
767 if ( !$status->isGood() ) {
769 $this->getOutput()->parseAsInterface(
770 Status::wrap( $status )->getWikiText( false, false, $this->getLanguage() )
771 )
772 );
773
774 return false;
775 }
776
777 $this->mLocalFile = $this->mUpload->getLocalFile();
778
779 // Check warnings if necessary
780 if ( !$this->mIgnoreWarning ) {
781 $warnings = $this->mUpload->checkWarnings( $user );
782 if ( $this->showUploadWarning( $warnings ) ) {
783 return false;
784 }
785 }
786
787 return true;
788 }
789
795 protected function getPageTextAndTags() {
796 // Get the page text if this is not a reupload
797 if ( !$this->mForReUpload ) {
798 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
799 $this->mCopyrightStatus, $this->mCopyrightSource,
800 $this->getConfig() );
801 } else {
802 $pageText = false;
803 }
804 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
805 if ( $changeTags === null || $changeTags === '' ) {
806 $changeTags = [];
807 } else {
808 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
809 }
810 if ( $changeTags ) {
811 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
812 $changeTags, $this->getUser() );
813 if ( !$changeTagsStatus->isOK() ) {
814 $this->showUploadError( $this->getOutput()->parseAsInterface(
815 $changeTagsStatus->getWikiText( false, false, $this->getLanguage() )
816 ) );
817
818 return null;
819 }
820 }
821 return [ $pageText, $changeTags ];
822 }
823
828 protected function processUpload() {
829 // Fetch the file if required
830 $status = $this->mUpload->fetchFile();
831 if ( !$this->performUploadChecks( $status ) ) {
832 return;
833 }
834 $user = $this->getUser();
835 $pageAndTags = $this->getPageTextAndTags();
836 if ( $pageAndTags === null ) {
837 return;
838 }
839 [ $pageText, $changeTags ] = $pageAndTags;
840
841 $status = $this->mUpload->performUpload(
842 $this->mComment,
843 $pageText,
844 $this->mWatchthis,
845 $user,
846 $changeTags
847 );
848
849 if ( !$status->isGood() ) {
850 $this->showRecoverableUploadError(
851 $this->getOutput()->parseAsInterface(
852 $status->getWikiText( false, false, $this->getLanguage() )
853 )
854 );
855
856 return;
857 }
858
859 // Success, redirect to description page
860 $this->mUploadSuccessful = true;
861 $this->getHookRunner()->onSpecialUploadComplete( $this );
862 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
863 }
864
868 protected function processAsyncUpload() {
869 // Ensure the upload we're dealing with is an UploadFromUrl
870 if ( !$this->mUpload instanceof \MediaWiki\Upload\UploadFromUrl ) {
871 $this->showUploadError( $this->msg( 'uploaderror' )->escaped() );
872
873 return;
874 }
875 // check we can fetch the file
876 $status = $this->mUpload->canFetchFile();
877 if ( !$this->performUploadChecks( $status ) ) {
878 $this->log->debug( 'Upload failed verification: {error}', [ 'error' => $status ] );
879 return;
880 }
881
882 $pageAndTags = $this->getPageTextAndTags();
883 if ( $pageAndTags === null ) {
884 return;
885 }
886 [ $pageText, $changeTags ] = $pageAndTags;
887
888 // Create a new job to process the upload from url
890 [
891 'filename' => $this->mUpload->getDesiredDestName(),
892 'url' => $this->mUpload->getUrl(),
893 'comment' => $this->mComment,
894 'tags' => $changeTags,
895 'text' => $pageText,
896 'watch' => $this->mWatchthis,
897 'watchlistexpiry' => null,
898 'session' => $this->getContext()->exportSession(),
899 'reupload' => $this->mForReUpload,
900 'ignorewarnings' => $this->mIgnoreWarning,
901 ]
902 );
903 // Save the session status
904 $cacheKey = $job->getCacheKey();
905 UploadBase::setSessionStatus( $this->getUser(), $cacheKey, [
906 'status' => Status::newGood(),
907 'stage' => 'queued',
908 'result' => 'Poll'
909 ] );
910 $this->log->info( "Submitting UploadFromUrlJob for {filename}",
911 [ 'filename' => $this->mUpload->getDesiredDestName() ]
912 );
913 // Submit the job
914 $this->jobQueueGroup->push( $job );
915 // Show the upload status
916 $this->showUploadStatus( $this->getUser() );
917 }
918
928 public static function getInitialPageText( $comment = '', $license = '',
929 $copyStatus = '', $source = '', ?Config $config = null
930 ) {
931 if ( $config === null ) {
932 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
933 $config = MediaWikiServices::getInstance()->getMainConfig();
934 }
935
936 $msg = [];
937 $forceUIMsgAsContentMsg = (array)$config->get( MainConfigNames::ForceUIMsgAsContentMsg );
938 /* These messages are transcluded into the actual text of the description page.
939 * Thus, forcing them as content messages makes the upload to produce an int: template
940 * instead of hardcoding it there in the uploader language.
941 */
942 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
943 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
944 $msg[$msgName] = "{{int:$msgName}}";
945 } else {
946 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
947 }
948 }
949
950 $licenseText = '';
951 if ( $license !== '' ) {
952 $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
953 }
954
955 $pageText = $comment . "\n";
956 $headerText = '== ' . $msg['filedesc'] . ' ==';
957 if ( $comment !== '' && !str_contains( $comment, $headerText ) ) {
958 // prepend header to page text unless it's already there (or there is no content)
959 $pageText = $headerText . "\n" . $pageText;
960 }
961
962 if ( $config->get( MainConfigNames::UseCopyrightUpload ) ) {
963 $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
964 $pageText .= $licenseText;
965 $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
966 } else {
967 $pageText .= $licenseText;
968 }
969
970 // allow extensions to modify the content
971 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
972 ->onUploadForm_getInitialPageText( $pageText, $msg, $config );
973
974 return $pageText;
975 }
976
989 protected function getWatchCheck() {
990 $user = $this->getUser();
991 if ( $this->userOptionsLookup->getBoolOption( $user, 'watchdefault' ) ) {
992 // Watch all edits!
993 return true;
994 }
995
996 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
997 if ( $desiredTitleObj instanceof Title &&
998 $this->watchlistManager->isWatched( $user, $desiredTitleObj ) ) {
999 // Already watched, don't change that
1000 return true;
1001 }
1002
1003 $local = $this->localRepo->newFile( $this->mDesiredDestName );
1004 if ( $local && $local->exists() ) {
1005 // We're uploading a new version of an existing file.
1006 // No creation, so don't watch it if we're not already.
1007 return false;
1008 } else {
1009 // New page should get watched if that's our option.
1010 return $this->userOptionsLookup->getBoolOption( $user, 'watchcreations' ) ||
1011 $this->userOptionsLookup->getBoolOption( $user, 'watchuploads' );
1012 }
1013 }
1014
1020 protected function processVerificationError( $details ) {
1021 switch ( $details['status'] ) {
1023 case UploadBase::MIN_LENGTH_PARTNAME:
1024 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
1025 break;
1026 case UploadBase::ILLEGAL_FILENAME:
1027 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
1028 $details['filtered'] )->parse() );
1029 break;
1030 case UploadBase::FILENAME_TOO_LONG:
1031 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
1032 break;
1033 case UploadBase::FILETYPE_MISSING:
1034 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
1035 break;
1036 case UploadBase::WINDOWS_NONASCII_FILENAME:
1037 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
1038 break;
1039
1041 case UploadBase::EMPTY_FILE:
1042 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
1043 break;
1044 case UploadBase::FILE_TOO_LARGE:
1045 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
1046 break;
1047 case UploadBase::FILETYPE_BADTYPE:
1048 $msg = $this->msg( 'filetype-banned-type' );
1049 if ( isset( $details['blacklistedExt'] ) ) {
1050 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
1051 } else {
1052 $msg->params( $details['finalExt'] );
1053 }
1054 $extensions =
1055 array_unique( $this->getConfig()->get( MainConfigNames::FileExtensions ) );
1056 $msg->params( $this->getLanguage()->commaList( $extensions ),
1057 count( $extensions ) );
1058
1059 // Add PLURAL support for the first parameter. This results
1060 // in a bit unlogical parameter sequence, but does not break
1061 // old translations
1062 if ( isset( $details['blacklistedExt'] ) ) {
1063 $msg->params( count( $details['blacklistedExt'] ) );
1064 } else {
1065 $msg->params( 1 );
1066 }
1067
1068 $this->showUploadError( $msg->parse() );
1069 break;
1070 case UploadBase::VERIFICATION_ERROR:
1071 unset( $details['status'] );
1072 $code = array_shift( $details['details'] );
1073 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
1074 break;
1075 default:
1076 throw new UnexpectedValueException( __METHOD__ . ": Unknown value `{$details['status']}`" );
1077 }
1078 }
1079
1085 protected function unsaveUploadedFile() {
1086 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
1087 return true;
1088 }
1089 $success = $this->mUpload->unsaveUploadedFile();
1090 if ( !$success ) {
1091 $this->getOutput()->showErrorPage(
1092 'internalerror',
1093 'filedeleteerror',
1094 [ $this->mUpload->getTempPath() ]
1095 );
1096
1097 return false;
1098 } else {
1099 return true;
1100 }
1101 }
1102
1112 public static function getExistsWarning( $exists ) {
1113 if ( !$exists ) {
1114 return '';
1115 }
1116
1117 $file = $exists['file'];
1118 if ( !$file instanceof File ) {
1119 // File deleted while showing entry from cache for async-url-upload
1120 // Or serialize error, see T409830
1121 return '';
1122 }
1123
1124 $filename = $file->getTitle()->getPrefixedText();
1125 $warnMsg = null;
1126
1127 if ( $exists['warning'] == 'exists' ) {
1128 // Exact match
1129 $warnMsg = wfMessage( 'fileexists', $filename );
1130 } elseif ( $exists['warning'] == 'page-exists' ) {
1131 // Page exists but file does not
1132 $warnMsg = wfMessage( 'filepageexists', $filename );
1133 } elseif ( $exists['warning'] == 'exists-normalized' ) {
1134 $warnMsg = wfMessage( 'fileexists-extension', $filename,
1135 $exists['normalizedFile']->getTitle()->getPrefixedText() );
1136 } elseif ( $exists['warning'] == 'thumb' ) {
1137 // Swapped argument order compared with other messages for backwards compatibility
1138 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
1139 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
1140 } elseif ( $exists['warning'] == 'thumb-name' ) {
1141 // Image w/o '180px-' does not exists, but we do not like these filenames
1142 $name = $file->getName();
1143 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
1144 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
1145 } elseif ( $exists['warning'] == 'bad-prefix' ) {
1146 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
1147 }
1148
1149 return $warnMsg ? $warnMsg->page( $file->getTitle() )->parse() : '';
1150 }
1151
1157 public function getDupeWarning( $dupes ) {
1158 if ( !$dupes ) {
1159 return '';
1160 }
1161
1162 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
1163 $gallery->setShowBytes( false );
1164 $gallery->setShowDimensions( false );
1165 foreach ( $dupes as $file ) {
1166 $gallery->add( $file->getTitle() );
1167 }
1168
1169 return '<li>' .
1170 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
1171 $gallery->toHTML() . "</li>\n";
1172 }
1173
1175 protected function getGroupName() {
1176 return 'media';
1177 }
1178
1187 public static function rotationEnabled() {
1188 $bitmapHandler = new BitmapHandler();
1189 return $bitmapHandler->autoRotateEnabled();
1190 }
1191}
1192
1197class_alias( SpecialUpload::class, 'SpecialUpload' );
const NS_FILE
Definition Defines.php:57
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:68
Generic handler for bitmap images.
Recent changes tagging.
makeTitle( $linkId)
Convert a link ID to a Title.to override Title
An error page which can definitely be safely rendered using the OutputPage.
Show an error when a user tries to do something they do not have the necessary permissions for.
Show an error when the user tries to do something whilst blocked.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition File.php:79
Local file in the wiki's own database.
Definition LocalFile.php:79
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:45
Prioritized list of file repositories.
Definition RepoGroup.php:29
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:195
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
This class is a collection of static functions that serve two purposes:
Definition Html.php:43
Handle enqueueing of background jobs.
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 ForceUIMsgAsContentMsg
Name constant for the ForceUIMsgAsContentMsg setting, for use with Config::get()
const UseCopyrightUpload
Name constant for the UseCopyrightUpload setting, for use with Config::get()
const FileExtensions
Name constant for the FileExtensions setting, for use with Config::get()
const EnableAsyncUploadsByURL
Name constant for the EnableAsyncUploadsByURL 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.
Special handling for representing file pages.
WebRequest clone which takes values from a provided array.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Parent class for all special pages.
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
getUser()
Shortcut to get the User executing this instance.
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
getPageTitle( $subpage=false)
Get a self-referential title object.
checkReadOnly()
If the wiki is currently in readonly mode, throws a ReadOnlyError.
getConfig()
Shortcut to get main config object.
getContext()
Gets the context this SpecialPage is executed in.
getRequest()
Get the WebRequest being used for this instance.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
getOutput()
Get the OutputPage being used for this instance.
getContentLanguage()
Shortcut to get content language.
getLanguage()
Shortcut to get user's language.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages By default the message key is the canonical name of...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Form for uploading media files.
bool $mForReUpload
The user followed an "overwrite this file" link.
doesWrites()
Indicates whether POST requests to this special page require write access to the wiki....
bool $mCancelUpload
The user clicked "Cancel and return to upload form" button.
getWatchCheck()
See if we should check the 'watch this page' checkbox on the form based on the user's preferences and...
bool $mUploadSuccessful
Subclasses can use this to determine whether a file was uploaded.
static rotationEnabled()
Should we rotate images in the preview on Special:Upload.
unsaveUploadedFile()
Remove a temporarily kept file stashed by saveTempUploadedFile().
string $mDesiredDestName
The requested target file name.
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
string $uploadFormTextTop
Raw html injection point for hooks not using HTMLForm.
showUploadForm( $form)
Show the main upload form.
performUploadChecks( $fetchFileStatus)
Common steps for processing uploads.
showUploadError( $message)
Show the upload form with error message, but do not stash the file.
processVerificationError( $details)
Provides output to the user for a result of UploadBase::verifyUpload.
string $uploadFormTextAfterSummary
Raw html injection point for hooks not using HTMLForm.
static getExistsWarning( $exists)
Functions for formatting warnings.
showUploadWarning( $warnings)
Stashes the upload, shows the main form, but adds a "continue anyway button".
userCanExecute(User $user)
This page can be shown if uploading is enabled.
processAsyncUpload()
Process an asynchronous upload.
getDupeWarning( $dupes)
Construct a warning and a gallery from an array of duplicate files.
getUploadForm( $message='', $sessionKey='', $hideIgnoreWarning=false)
Get an UploadForm instance with title and text properly set.
loadRequest()
Initialize instance variables from request and create an Upload handler.
string $mCacheKey
The cache key to use to retreive the status of your async upload.
showRecoverableUploadError( $message)
Stashes the upload and shows the main upload form.
getPageTextAndTags()
Get the page text and tags for the upload.
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', ?Config $config=null)
Get the initial image page text based on a comment and optional file status information.
showUploadStatus( $user)
Show the upload status.
isAsyncUpload()
Check if the current request is an async upload by url request.
WebRequest FauxRequest $mRequest
The request this form is supposed to handle.
__construct(?RepoGroup $repoGroup=null, ?UserOptionsLookup $userOptionsLookup=null, ?NamespaceInfo $nsInfo=null, ?WatchlistManager $watchlistManager=null)
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:44
This is a utility class for dealing with namespaces that encodes all the "magic" behaviors of them ba...
Represents a title within MediaWiki.
Definition Title.php:69
exists( $flags=0)
Check if page exists.
Definition Title.php:3129
UploadBase and subclasses are the backend of MediaWiki's file uploads.
Implements uploading from previously stored file.
Provides access to user options.
User class for the MediaWiki software.
Definition User.php:109
Sub class of HTMLForm that provides the form section of SpecialUpload.
getMessageObject()
Return a Message object for this exception.Message
Interface for configuration instances.
Definition Config.php:18
$source
Helper trait for implementations \DAO.
if(count( $args)< 1) $job