MediaWiki master
SpecialUpload.php
Go to the documentation of this file.
1<?php
25namespace MediaWiki\Specials;
26
28use ChangeTags;
32use LocalFile;
33use LocalRepo;
52use Psr\Log\LoggerInterface;
53use RepoGroup;
54use UnexpectedValueException;
55use UploadBase;
56use UploadForm;
59use WikiFilePage;
60
68
69 private LocalRepo $localRepo;
70 private UserOptionsLookup $userOptionsLookup;
71 private NamespaceInfo $nsInfo;
72 private WatchlistManager $watchlistManager;
74 public bool $allowAsync;
75 private JobQueueGroup $jobQueueGroup;
76 private LoggerInterface $log;
77
84 public function __construct(
85 RepoGroup $repoGroup = null,
86 UserOptionsLookup $userOptionsLookup = null,
87 NamespaceInfo $nsInfo = null,
88 WatchlistManager $watchlistManager = null
89 ) {
90 parent::__construct( 'Upload', 'upload' );
91 // This class is extended and therefor fallback to global state - T265300
93 $this->jobQueueGroup = $services->getJobQueueGroup();
94 $repoGroup ??= $services->getRepoGroup();
95 $this->localRepo = $repoGroup->getLocalRepo();
96 $this->userOptionsLookup = $userOptionsLookup ?? $services->getUserOptionsLookup();
97 $this->nsInfo = $nsInfo ?? $services->getNamespaceInfo();
98 $this->watchlistManager = $watchlistManager ?? $services->getWatchlistManager();
99 $this->allowAsync = (
102 );
103 $this->log = LoggerFactory::getInstance( 'SpecialUpload' );
104 }
105
106 public function doesWrites() {
107 return true;
108 }
109
110 // Misc variables
111
113 public $mRequest;
115
118
120 public $mUpload;
121
125
126 // User input variables from the "description" section
127
130 public $mComment;
131 public $mLicense;
132
133 // User input variables from the root section
134
135 // phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.WrongStyle
140
141 // Hidden variables
142
143 // phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.WrongStyle
145
148
151 public $mTokenOk;
152
154 public $mUploadSuccessful = false;
155
160
164 protected function loadRequest() {
165 $this->mRequest = $request = $this->getRequest();
166 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
167 $this->mUpload = UploadBase::createFromRequest( $request );
168 $this->mUploadClicked = $request->wasPosted()
169 && ( $request->getCheck( 'wpUpload' )
170 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
171
172 // Guess the desired name from the filename if not provided
173 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
174 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
175 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
176 }
177 $this->mLicense = $request->getText( 'wpLicense' );
178
179 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
180 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
181 || $request->getCheck( 'wpUploadIgnoreWarning' );
182 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isRegistered();
183 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
184 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
185
186 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
187
188 $commentDefault = '';
189 $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
190 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
191 $commentDefault = $commentMsg->plain();
192 }
193 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
194
195 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
196 || $request->getCheck( 'wpReUpload' ); // b/w compat
197
198 // If it was posted check for the token (no remote POST'ing with user credentials)
199 $token = $request->getVal( 'wpEditToken' );
200 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
201
202 // If this is an upload from Url and we're allowing async processing,
203 // check for the presence of the cache key parameter, or compute it. Else, it should be empty.
204 if ( $this->isAsyncUpload() ) {
205 $this->mCacheKey = \UploadFromUrl::getCacheKeyFromRequest( $request );
206 } else {
207 $this->mCacheKey = '';
208 }
209
210 $this->uploadFormTextTop = '';
211 $this->uploadFormTextAfterSummary = '';
212 }
213
219 protected function isAsyncUpload() {
220 return ( $this->mSourceType === 'url' && $this->allowAsync );
221 }
222
231 public function userCanExecute( User $user ) {
232 return UploadBase::isEnabled() && parent::userCanExecute( $user );
233 }
234
238 public function execute( $par ) {
240
241 $this->setHeaders();
242 $this->outputHeader();
243
244 # Check uploading enabled
245 if ( !UploadBase::isEnabled() ) {
246 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
247 }
248
249 $this->addHelpLink( 'Help:Managing files' );
250
251 # Check permissions
252 $user = $this->getUser();
253 $permissionRequired = UploadBase::isAllowed( $user );
254 if ( $permissionRequired !== true ) {
255 throw new PermissionsError( $permissionRequired );
256 }
257
258 # Check blocks
259 if ( $user->isBlockedFromUpload() ) {
260 throw new UserBlockedError(
261 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable Block is checked and not null
262 $user->getBlock(),
263 $user,
264 $this->getLanguage(),
265 $this->getRequest()->getIP()
266 );
267 }
268
269 # Check whether we actually want to allow changing stuff
270 $this->checkReadOnly();
271
272 $this->loadRequest();
273
274 # Unsave the temporary file in case this was a cancelled upload
275 if ( $this->mCancelUpload && !$this->unsaveUploadedFile() ) {
276 # Something went wrong, so unsaveUploadedFile showed a warning
277 return;
278 }
279
280 # If we have a cache key, show the upload status.
281 if ( $this->mTokenOk && $this->mCacheKey !== '' ) {
282 if ( $this->mUpload && $this->mUploadClicked && !$this->mCancelUpload ) {
283 # If the user clicked the upload button, we need to process the upload
284 $this->processAsyncUpload();
285 } else {
286 # Show the upload status
287 $this->showUploadStatus( $user );
288 }
289 } elseif (
290 # Process upload or show a form
291 $this->mTokenOk && !$this->mCancelUpload &&
292 ( $this->mUpload && $this->mUploadClicked )
293 ) {
294 $this->processUpload();
295 } else {
296 # Backwards compatibility hook
297 if ( !$this->getHookRunner()->onUploadForm_initial( $this ) ) {
298 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
299
300 return;
301 }
302 $this->showUploadForm( $this->getUploadForm() );
303 }
304
305 # Cleanup
306 if ( $this->mUpload ) {
307 $this->mUpload->cleanupTempFile();
308 }
309 }
310
316 protected function showUploadStatus( $user ) {
317 // first, let's fetch the status from the main stash
318 $progress = UploadBase::getSessionStatus( $user, $this->mCacheKey );
319 if ( $progress == false ) {
320 $progress = [ 'status' => Status::newFatal( 'invalid-cache-key' ) ];
321 }
322 $this->log->debug( 'Upload status: stage {stage}, result {result}', $progress );
323
324 $status = $progress['status'] ?? Status::newFatal( 'invalid-cache-key' );
325 $stage = $progress['stage'] ?? 'unknown';
326 $result = $progress['result'] ?? 'unknown';
327 switch ( $stage ) {
328 case 'publish':
329 switch ( $result ) {
330 case 'Success':
331 // The upload is done. Check the result and either show the form with the error
332 // occurred, or redirect to the file itself
333 // Success, redirect to description page
334 $this->mUploadSuccessful = true;
335 $this->getHookRunner()->onSpecialUploadComplete( $this );
336 // Redirect to the destination URL, but purge the cache of the file description page first
337 // TODO: understand why this is needed
338 $title = Title::makeTitleSafe( NS_FILE, $this->mRequest->getText( 'wpDestFile' ) );
339 if ( $title ) {
340 $this->log->debug( 'Purging page', [ 'title' => $title->getText() ] );
341 $page = new WikiFilePage( $title );
342 $page->doPurge();
343 }
344 $this->getOutput()->redirect( $this->mRequest->getText( 'wpDestUrl' ) );
345 break;
346 case 'Warning':
347 $this->showUploadWarning( UploadBase::unserializeWarnings( $progress['warnings'] ) );
348 break;
349 case 'Failure':
350 $details = $status->getValue();
351 // Verification failed.
352 if ( is_array( $details ) && isset( $details['verification'] ) ) {
353 $this->processVerificationError( $details['verification'] );
354 } else {
355 $this->showUploadError( $this->getOutput()->parseAsInterface(
356 $status->getWikiText( false, false, $this->getLanguage() ) )
357 );
358 }
359 break;
360 case 'Poll':
361 $this->showUploadProgress(
362 [ 'active' => true, 'msg' => 'upload-progress-processing' ]
363 );
364 break;
365 }
366 break;
367 case 'queued':
368 // show stalled progress bar
369 $this->showUploadProgress( [ 'active' => false, 'msg' => 'upload-progress-queued' ] );
370 break;
371 case 'fetching':
372 switch ( $result ) {
373 case 'Success':
374 // The file is being downloaded from a URL
375 // TODO: show active progress bar saying we're downloading the file
376 $this->showUploadProgress( [ 'active' => true, 'msg' => 'upload-progress-downloading' ] );
377 break;
378 case 'Failure':
379 // downloading failed
380 $this->showUploadError( $this->getOutput()->parseAsInterface(
381 $status->getWikiText( false, false, $this->getLanguage() ) )
382 );
383 break;
384 }
385 break;
386 default:
387 // unknown status, just show a generic error
388 if ( $status->isOK() ) {
389 $status = Status::newFatal( 'upload-progress-unknown' );
390 }
391 $statusmsg = $this->getOutput()->parseAsInterface(
392 $status->getWikiText( false, false, $this->getLanguage() )
393 );
394 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . '</h2>' . HTML::errorBox( $statusmsg );
395 $this->showUploadForm( $this->getUploadForm( $message ) );
396 break;
397 }
398 }
399
410 private function showUploadProgress( $options ) {
411 // $isActive = $options['active'] ?? false;
412 //$progressBarProperty = $isActive ? '' : 'disabled';
413 $message = $this->msg( $options['msg'] )->escaped();
414 $destUrl = $this->mRequest->getText( 'wpDestUrl', '' );
415 if ( !$destUrl && $this->mUpload ) {
416 if ( !$this->mLocalFile ) {
417 $this->mLocalFile = $this->mUpload->getLocalFile();
418 }
419 // This probably means the title is bad, so we can't get the URL
420 // but we need to wait for the job to execute.
421 if ( $this->mLocalFile === null ) {
422 $destUrl = '';
423 } else {
424 $destUrl = $this->mLocalFile->getTitle()->getFullURL();
425 }
426 }
427
428 $destName = $this->mDesiredDestName;
429 if ( !$destName ) {
430 $destName = $this->mRequest->getText( 'wpDestFile' );
431 }
432
433 // Needed if we have warnings to show
434 $sourceURL = $this->mRequest->getText( 'wpUploadFileURL' );
435
436 $form = new HTMLForm( [
437 'CacheKey' => [
438 'type' => 'hidden',
439 'default' => $this->mCacheKey,
440 ],
441 'SourceType' => [
442 'type' => 'hidden',
443 'default' => $this->mSourceType,
444 ],
445 'DestUrl' => [
446 'type' => 'hidden',
447 'default' => $destUrl,
448 ],
449 'DestFile' => [
450 'type' => 'hidden',
451 'default' => $destName,
452 ],
453 'UploadFileURL' => [
454 'type' => 'hidden',
455 'default' => $sourceURL,
456 ],
457 ], $this->getContext(), 'uploadProgress' );
458 $form->setSubmitText( $this->msg( 'upload-refresh' )->escaped() );
459 // TODO: use codex, add a progress bar
460 //$preHtml = "<cdx-progress-bar aria--label='upload progressbar' $progressBarProperty />";
461 $preHtml = "<div id='upload-progress-message'>$message</div>";
462 $form->addPreHtml( $preHtml );
463 $form->setSubmitCallback(
464 static function ( $formData ) {
465 return true;
466 }
467 );
468 $form->prepareForm();
469 $this->getOutput()->addHTML( $form->getHTML( false ) );
470 }
471
477 protected function showUploadForm( $form ) {
478 if ( $form instanceof HTMLForm ) {
479 $form->show();
480 } else {
481 $this->getOutput()->addHTML( $form );
482 }
483 }
484
493 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
494 # Initialize form
495 $form = new UploadForm(
496 [
497 'watch' => $this->getWatchCheck(),
498 'forreupload' => $this->mForReUpload,
499 'sessionkey' => $sessionKey,
500 'hideignorewarning' => $hideIgnoreWarning,
501 'destwarningack' => (bool)$this->mDestWarningAck,
502
503 'description' => $this->mComment,
504 'texttop' => $this->uploadFormTextTop,
505 'textaftersummary' => $this->uploadFormTextAfterSummary,
506 'destfile' => $this->mDesiredDestName,
507 ],
508 $this->getContext(),
509 $this->getLinkRenderer(),
510 $this->localRepo,
511 $this->getContentLanguage(),
512 $this->nsInfo,
513 $this->getHookContainer()
514 );
515 $form->setTitle( $this->getPageTitle() ); // Remove subpage
516
517 # Check the token, but only if necessary
518 if (
519 !$this->mTokenOk && !$this->mCancelUpload &&
520 ( $this->mUpload && $this->mUploadClicked )
521 ) {
522 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
523 }
524
525 # Give a notice if the user is uploading a file that has been deleted or moved
526 # Note that this is independent from the message 'filewasdeleted'
527 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
528 $delNotice = ''; // empty by default
529 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
530 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
531 $desiredTitleObj,
532 '', [ 'lim' => 10,
533 'conds' => [ $this->localRepo->getReplicaDB()->expr( 'log_action', '!=', 'revision' ) ],
534 'showIfEmpty' => false,
535 'msgKey' => [ 'upload-recreate-warning' ] ]
536 );
537 }
538 $form->addPreText( $delNotice );
539
540 # Add text to form
541 $form->addPreText( '<div id="uploadtext">' .
542 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
543 '</div>' );
544 # Add upload error message
545 $form->addPreText( $message );
546
547 # Add footer to form
548 $uploadFooter = $this->msg( 'uploadfooter' );
549 if ( !$uploadFooter->isDisabled() ) {
550 $form->addPostText( '<div id="mw-upload-footer-message">'
551 . $uploadFooter->parseAsBlock() . "</div>\n" );
552 }
553
554 return $form;
555 }
556
568 protected function showRecoverableUploadError( $message ) {
569 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
570 if ( $stashStatus->isGood() ) {
571 $sessionKey = $stashStatus->getValue()->getFileKey();
572 $uploadWarning = 'upload-tryagain';
573 } else {
574 $sessionKey = null;
575 $uploadWarning = 'upload-tryagain-nostash';
576 }
577 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . '</h2>' .
578 Html::errorBox( $message );
579
580 $form = $this->getUploadForm( $message, $sessionKey );
581 $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
582 $this->showUploadForm( $form );
583 }
584
593 protected function showUploadWarning( $warnings ) {
594 # If there are no warnings, or warnings we can ignore, return early.
595 # mDestWarningAck is set when some javascript has shown the warning
596 # to the user. mForReUpload is set when the user clicks the "upload a
597 # new version" link.
598 if ( !$warnings || ( count( $warnings ) == 1
599 && isset( $warnings['exists'] )
600 && ( $this->mDestWarningAck || $this->mForReUpload ) )
601 ) {
602 return false;
603 }
604
605 if ( $this->mUpload ) {
606 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
607 if ( $stashStatus->isGood() ) {
608 $sessionKey = $stashStatus->getValue()->getFileKey();
609 $uploadWarning = 'uploadwarning-text';
610 } else {
611 $sessionKey = null;
612 $uploadWarning = 'uploadwarning-text-nostash';
613 }
614 } else {
615 $sessionKey = null;
616 $uploadWarning = 'uploadwarning-text-nostash';
617 }
618
619 // Add styles for the warning, reused from the live preview
620 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
621
622 $linkRenderer = $this->getLinkRenderer();
623 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
624 . '<div class="mw-destfile-warning"><ul>';
625 foreach ( $warnings as $warning => $args ) {
626 if ( $warning == 'badfilename' ) {
627 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
628 }
629 if ( $warning == 'exists' ) {
630 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
631 } elseif ( $warning == 'no-change' ) {
632 $file = $args;
633 $filename = $file->getTitle()->getPrefixedText();
634 $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
635 } elseif ( $warning == 'duplicate-version' ) {
636 $file = $args[0];
637 $count = count( $args );
638 $filename = $file->getTitle()->getPrefixedText();
639 $message = $this->msg( 'fileexists-duplicate-version' )
640 ->params( $filename )
641 ->numParams( $count );
642 $msg = "\t<li>" . $message->parse() . "</li>\n";
643 } elseif ( $warning == 'was-deleted' ) {
644 # If the file existed before and was deleted, warn the user of this
645 $ltitle = SpecialPage::getTitleFor( 'Log' );
646 $llink = $linkRenderer->makeKnownLink(
647 $ltitle,
648 $this->msg( 'deletionlog' )->text(),
649 [],
650 [
651 'type' => 'delete',
652 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
653 ]
654 );
655 $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
656 } elseif ( $warning == 'duplicate' ) {
657 $msg = $this->getDupeWarning( $args );
658 } elseif ( $warning == 'duplicate-archive' ) {
659 if ( $args === '' ) {
660 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
661 . "</li>\n";
662 } else {
663 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
664 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
665 . "</li>\n";
666 }
667 } else {
668 if ( $args === true ) {
669 $args = [];
670 } elseif ( !is_array( $args ) ) {
671 $args = [ $args ];
672 }
673 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
674 }
675 $warningHtml .= $msg;
676 }
677 $warningHtml .= "</ul></div>\n";
678 $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
679
680 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
681 $form->setSubmitTextMsg( 'upload-tryagain' );
682 $form->addButton( [
683 'name' => 'wpUploadIgnoreWarning',
684 'value' => $this->msg( 'ignorewarning' )->text()
685 ] );
686 $form->addButton( [
687 'name' => 'wpCancelUpload',
688 'value' => $this->msg( 'reuploaddesc' )->text()
689 ] );
690
691 $this->showUploadForm( $form );
692
693 # Indicate that we showed a form
694 return true;
695 }
696
702 protected function showUploadError( $message ) {
703 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . '</h2>' .
704 Html::errorBox( $message );
705 $this->showUploadForm( $this->getUploadForm( $message ) );
706 }
707
714 protected function performUploadChecks( $fetchFileStatus ): bool {
715 if ( !$fetchFileStatus->isOK() ) {
716 $this->showUploadError( $this->getOutput()->parseAsInterface(
717 $fetchFileStatus->getWikiText( false, false, $this->getLanguage() )
718 ) );
719
720 return false;
721 }
722 if ( !$this->getHookRunner()->onUploadForm_BeforeProcessing( $this ) ) {
723 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
724 // This code path is deprecated. If you want to break upload processing
725 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
726 // and UploadBase::verifyFile.
727 // If you use this hook to break uploading, the user will be returned
728 // an empty form with no error message whatsoever.
729 return false;
730 }
731
732 // Upload verification
733 // If this is an asynchronous upload-by-url, skip the verification
734 if ( $this->isAsyncUpload() ) {
735 return true;
736 }
737 $details = $this->mUpload->verifyUpload();
738 if ( $details['status'] != UploadBase::OK ) {
739 $this->processVerificationError( $details );
740
741 return false;
742 }
743
744 // Verify permissions for this title
745 $user = $this->getUser();
746 $permErrors = $this->mUpload->verifyTitlePermissions( $user );
747 if ( $permErrors !== true ) {
748 $code = array_shift( $permErrors[0] );
749 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
750
751 return false;
752 }
753
754 $this->mLocalFile = $this->mUpload->getLocalFile();
755
756 // Check warnings if necessary
757 if ( !$this->mIgnoreWarning ) {
758 $warnings = $this->mUpload->checkWarnings( $user );
759 if ( $this->showUploadWarning( $warnings ) ) {
760 return false;
761 }
762 }
763
764 return true;
765 }
766
772 protected function getPageTextAndTags() {
773 // Get the page text if this is not a reupload
774 if ( !$this->mForReUpload ) {
775 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
776 $this->mCopyrightStatus, $this->mCopyrightSource,
777 $this->getConfig() );
778 } else {
779 $pageText = false;
780 }
781 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
782 if ( $changeTags === null || $changeTags === '' ) {
783 $changeTags = [];
784 } else {
785 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
786 }
787 if ( $changeTags ) {
789 $changeTags, $this->getUser() );
790 if ( !$changeTagsStatus->isOK() ) {
791 $this->showUploadError( $this->getOutput()->parseAsInterface(
792 $changeTagsStatus->getWikiText( false, false, $this->getLanguage() )
793 ) );
794
795 return null;
796 }
797 }
798 return [ $pageText, $changeTags ];
799 }
800
805 protected function processUpload() {
806 // Fetch the file if required
807 $status = $this->mUpload->fetchFile();
808 if ( !$this->performUploadChecks( $status ) ) {
809 return;
810 }
811 $user = $this->getUser();
812 $pageAndTags = $this->getPageTextAndTags();
813 if ( $pageAndTags === null ) {
814 return;
815 }
816 [ $pageText, $changeTags ] = $pageAndTags;
817
818 $status = $this->mUpload->performUpload(
819 $this->mComment,
820 $pageText,
821 $this->mWatchthis,
822 $user,
823 $changeTags
824 );
825
826 if ( !$status->isGood() ) {
827 $this->showRecoverableUploadError(
828 $this->getOutput()->parseAsInterface(
829 $status->getWikiText( false, false, $this->getLanguage() )
830 )
831 );
832
833 return;
834 }
835
836 // Success, redirect to description page
837 $this->mUploadSuccessful = true;
838 $this->getHookRunner()->onSpecialUploadComplete( $this );
839 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
840 }
841
845 protected function processAsyncUpload() {
846 // Ensure the upload we're dealing with is an UploadFromUrl
847 if ( !$this->mUpload instanceof \UploadFromUrl ) {
848 $this->showUploadError( $this->msg( 'uploaderror' )->escaped() );
849
850 return;
851 }
852 // check we can fetch the file
853 $status = $this->mUpload->canFetchFile();
854 if ( !$this->performUploadChecks( $status ) ) {
855 $this->log->debug( 'Upload failed verification: {error}', [ 'error' => $status ] );
856 return;
857 }
858
859 $pageAndTags = $this->getPageTextAndTags();
860 if ( $pageAndTags === null ) {
861 return;
862 }
863 [ $pageText, $changeTags ] = $pageAndTags;
864
865 // Create a new job to process the upload from url
866 $job = new \UploadFromUrlJob(
867 [
868 'filename' => $this->mUpload->getDesiredDestName(),
869 'url' => $this->mUpload->getUrl(),
870 'comment' => $this->mComment,
871 'tags' => $changeTags,
872 'text' => $pageText,
873 'watch' => $this->mWatchthis,
874 'watchlistexpiry' => null,
875 'session' => $this->getContext()->exportSession(),
876 'reupload' => $this->mForReUpload,
877 'ignorewarnings' => $this->mIgnoreWarning,
878 ]
879 );
880 // Save the session status
881 $cacheKey = $job->getCacheKey();
882 UploadBase::setSessionStatus( $this->getUser(), $cacheKey, [
883 'status' => Status::newGood(),
884 'stage' => 'queued',
885 'result' => 'Poll'
886 ] );
887 $this->log->info( "Submitting UploadFromUrlJob for {filename}",
888 [ 'filename' => $this->mUpload->getDesiredDestName() ]
889 );
890 // Submit the job
891 $this->jobQueueGroup->push( $job );
892 // Show the upload status
893 $this->showUploadStatus( $this->getUser() );
894 }
895
905 public static function getInitialPageText( $comment = '', $license = '',
906 $copyStatus = '', $source = '', Config $config = null
907 ) {
908 if ( $config === null ) {
909 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
910 $config = MediaWikiServices::getInstance()->getMainConfig();
911 }
912
913 $msg = [];
914 $forceUIMsgAsContentMsg = (array)$config->get( MainConfigNames::ForceUIMsgAsContentMsg );
915 /* These messages are transcluded into the actual text of the description page.
916 * Thus, forcing them as content messages makes the upload to produce an int: template
917 * instead of hardcoding it there in the uploader language.
918 */
919 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
920 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
921 $msg[$msgName] = "{{int:$msgName}}";
922 } else {
923 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
924 }
925 }
926
927 $licenseText = '';
928 if ( $license !== '' ) {
929 $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
930 }
931
932 $pageText = $comment . "\n";
933 $headerText = '== ' . $msg['filedesc'] . ' ==';
934 if ( $comment !== '' && !str_contains( $comment, $headerText ) ) {
935 // prepend header to page text unless it's already there (or there is no content)
936 $pageText = $headerText . "\n" . $pageText;
937 }
938
939 if ( $config->get( MainConfigNames::UseCopyrightUpload ) ) {
940 $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
941 $pageText .= $licenseText;
942 $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
943 } else {
944 $pageText .= $licenseText;
945 }
946
947 // allow extensions to modify the content
948 ( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
949 ->onUploadForm_getInitialPageText( $pageText, $msg, $config );
950
951 return $pageText;
952 }
953
966 protected function getWatchCheck() {
967 $user = $this->getUser();
968 if ( $this->userOptionsLookup->getBoolOption( $user, 'watchdefault' ) ) {
969 // Watch all edits!
970 return true;
971 }
972
973 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
974 if ( $desiredTitleObj instanceof Title &&
975 $this->watchlistManager->isWatched( $user, $desiredTitleObj ) ) {
976 // Already watched, don't change that
977 return true;
978 }
979
980 $local = $this->localRepo->newFile( $this->mDesiredDestName );
981 if ( $local && $local->exists() ) {
982 // We're uploading a new version of an existing file.
983 // No creation, so don't watch it if we're not already.
984 return false;
985 } else {
986 // New page should get watched if that's our option.
987 return $this->userOptionsLookup->getBoolOption( $user, 'watchcreations' ) ||
988 $this->userOptionsLookup->getBoolOption( $user, 'watchuploads' );
989 }
990 }
991
997 protected function processVerificationError( $details ) {
998 switch ( $details['status'] ) {
1000 case UploadBase::MIN_LENGTH_PARTNAME:
1001 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
1002 break;
1003 case UploadBase::ILLEGAL_FILENAME:
1004 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
1005 $details['filtered'] )->parse() );
1006 break;
1007 case UploadBase::FILENAME_TOO_LONG:
1008 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
1009 break;
1010 case UploadBase::FILETYPE_MISSING:
1011 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
1012 break;
1013 case UploadBase::WINDOWS_NONASCII_FILENAME:
1014 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
1015 break;
1016
1018 case UploadBase::EMPTY_FILE:
1019 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
1020 break;
1021 case UploadBase::FILE_TOO_LARGE:
1022 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
1023 break;
1024 case UploadBase::FILETYPE_BADTYPE:
1025 $msg = $this->msg( 'filetype-banned-type' );
1026 if ( isset( $details['blacklistedExt'] ) ) {
1027 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
1028 } else {
1029 $msg->params( $details['finalExt'] );
1030 }
1031 $extensions =
1032 array_unique( $this->getConfig()->get( MainConfigNames::FileExtensions ) );
1033 $msg->params( $this->getLanguage()->commaList( $extensions ),
1034 count( $extensions ) );
1035
1036 // Add PLURAL support for the first parameter. This results
1037 // in a bit unlogical parameter sequence, but does not break
1038 // old translations
1039 if ( isset( $details['blacklistedExt'] ) ) {
1040 $msg->params( count( $details['blacklistedExt'] ) );
1041 } else {
1042 $msg->params( 1 );
1043 }
1044
1045 $this->showUploadError( $msg->parse() );
1046 break;
1047 case UploadBase::VERIFICATION_ERROR:
1048 unset( $details['status'] );
1049 $code = array_shift( $details['details'] );
1050 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
1051 break;
1052 case UploadBase::HOOK_ABORTED:
1053 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
1054 $args = $details['error'];
1055 $error = array_shift( $args );
1056 } else {
1057 $error = $details['error'];
1058 $args = null;
1059 }
1060
1061 $this->showUploadError( $this->msg( $error, $args )->parse() );
1062 break;
1063 default:
1064 throw new UnexpectedValueException( __METHOD__ . ": Unknown value `{$details['status']}`" );
1065 }
1066 }
1067
1073 protected function unsaveUploadedFile() {
1074 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
1075 return true;
1076 }
1077 $success = $this->mUpload->unsaveUploadedFile();
1078 if ( !$success ) {
1079 $this->getOutput()->showFatalError(
1080 $this->msg( 'filedeleteerror' )
1081 ->params( $this->mUpload->getTempPath() )
1082 ->escaped()
1083 );
1084
1085 return false;
1086 } else {
1087 return true;
1088 }
1089 }
1090
1100 public static function getExistsWarning( $exists ) {
1101 if ( !$exists ) {
1102 return '';
1103 }
1104
1105 $file = $exists['file'];
1106 $filename = $file->getTitle()->getPrefixedText();
1107 $warnMsg = null;
1108
1109 if ( $exists['warning'] == 'exists' ) {
1110 // Exact match
1111 $warnMsg = wfMessage( 'fileexists', $filename );
1112 } elseif ( $exists['warning'] == 'page-exists' ) {
1113 // Page exists but file does not
1114 $warnMsg = wfMessage( 'filepageexists', $filename );
1115 } elseif ( $exists['warning'] == 'exists-normalized' ) {
1116 $warnMsg = wfMessage( 'fileexists-extension', $filename,
1117 $exists['normalizedFile']->getTitle()->getPrefixedText() );
1118 } elseif ( $exists['warning'] == 'thumb' ) {
1119 // Swapped argument order compared with other messages for backwards compatibility
1120 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
1121 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
1122 } elseif ( $exists['warning'] == 'thumb-name' ) {
1123 // Image w/o '180px-' does not exists, but we do not like these filenames
1124 $name = $file->getName();
1125 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
1126 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
1127 } elseif ( $exists['warning'] == 'bad-prefix' ) {
1128 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
1129 }
1130
1131 return $warnMsg ? $warnMsg->page( $file->getTitle() )->parse() : '';
1132 }
1133
1139 public function getDupeWarning( $dupes ) {
1140 if ( !$dupes ) {
1141 return '';
1142 }
1143
1144 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
1145 $gallery->setShowBytes( false );
1146 $gallery->setShowDimensions( false );
1147 foreach ( $dupes as $file ) {
1148 $gallery->add( $file->getTitle() );
1149 }
1150
1151 return '<li>' .
1152 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
1153 $gallery->toHTML() . "</li>\n";
1154 }
1155
1156 protected function getGroupName() {
1157 return 'media';
1158 }
1159
1168 public static function rotationEnabled() {
1169 $bitmapHandler = new BitmapHandler();
1170 return $bitmapHandler->autoRotateEnabled();
1171 }
1172}
1173
1178class_alias( SpecialUpload::class, 'SpecialUpload' );
getUser()
getRequest()
const NS_FILE
Definition Defines.php:70
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.
getContext()
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:81
Generic handler for bitmap images.
static canAddTagsAccompanyingChange(array $tags, Authority $performer=null, $checkBlock=true)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
An error page which can definitely be safely rendered using the OutputPage.
Handle enqueueing of background jobs.
Local file in the wiki's own database.
Definition LocalFile.php:68
Local repository that stores files in the local filesystem and registers them in the wiki's own datab...
Definition LocalRepo.php:49
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition HTMLForm.php:206
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:56
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.
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.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Form for handling uploads and special page.
bool $mForReUpload
The user followed an "overwrite this file" link.
doesWrites()
Indicates whether this special page may perform database writes.
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.
__construct(RepoGroup $repoGroup=null, UserOptionsLookup $userOptionsLookup=null, NamespaceInfo $nsInfo=null, WatchlistManager $watchlistManager=null)
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.
static getInitialPageText( $comment='', $license='', $copyStatus='', $source='', Config $config=null)
Get the initial image page text based on a comment and optional file status information.
showUploadForm( $form)
Show the main upload form.
bool bool $allowAsync
wether uploads by url should be asynchronous or not
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.
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.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition Status.php:54
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:78
exists( $flags=0)
Check if page exists.
Definition Title.php:3201
Provides access to user options.
internal since 1.36
Definition User.php:93
Show an error when a user tries to do something they do not have the necessary permissions for.
Prioritized list of file repositories.
Definition RepoGroup.php:30
UploadBase and subclasses are the backend of MediaWiki's file uploads.
Sub class of HTMLForm that provides the form section of SpecialUpload.
Implements uploading from previously stored file.
Implements uploading from a HTTP resource.
Show an error when the user tries to do something whilst blocked.
Special handling for representing file pages.
Interface for configuration instances.
Definition Config.php:32
$source
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
if(count( $args)< 1) $job