3 * Implements Special:Upload
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
25 use MediaWiki\Linker\LinkRenderer
;
26 use MediaWiki\MediaWikiServices
;
29 * Form for handling uploads and special page.
31 * @ingroup SpecialPage
34 class SpecialUpload
extends SpecialPage
{
36 * Constructor : initialise object
37 * Get data POSTed through the form and assign them to the object
38 * @param WebRequest $request Data posted.
40 public function __construct( $request = null ) {
41 parent
::__construct( 'Upload', 'upload' );
44 public function doesWrites() {
48 /** Misc variables **/
50 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
54 /** @var UploadBase */
59 public $mUploadClicked;
61 /** User input variables from the "description" section **/
63 /** @var string The requested target file name */
64 public $mDesiredDestName;
68 /** User input variables from the root section **/
70 public $mIgnoreWarning;
72 public $mCopyrightStatus;
73 public $mCopyrightSource;
75 /** Hidden variables **/
77 public $mDestWarningAck;
79 /** @var bool The user followed an "overwrite this file" link */
82 /** @var bool The user clicked "Cancel and return to upload form" button */
83 public $mCancelUpload;
86 /** @var bool Subclasses can use this to determine whether a file was uploaded */
87 public $mUploadSuccessful = false;
89 /** Text injection points for hooks not using HTMLForm **/
90 public $uploadFormTextTop;
91 public $uploadFormTextAfterSummary;
94 * Initialize instance variables from request and create an Upload handler
96 protected function loadRequest() {
97 $this->mRequest
= $request = $this->getRequest();
98 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
99 $this->mUpload
= UploadBase
::createFromRequest( $request );
100 $this->mUploadClicked
= $request->wasPosted()
101 && ( $request->getCheck( 'wpUpload' )
102 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
104 // Guess the desired name from the filename if not provided
105 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
106 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
107 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
109 $this->mLicense
= $request->getText( 'wpLicense' );
111 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
112 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
113 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
114 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
115 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
116 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
118 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
120 $commentDefault = '';
121 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
122 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
123 $commentDefault = $commentMsg->plain();
125 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
127 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
128 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
130 // If it was posted check for the token (no remote POST'ing with user credentials)
131 $token = $request->getVal( 'wpEditToken' );
132 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
134 $this->uploadFormTextTop
= '';
135 $this->uploadFormTextAfterSummary
= '';
139 * This page can be shown if uploading is enabled.
140 * Handle permission checking elsewhere in order to be able to show
141 * custom error messages.
146 public function userCanExecute( User
$user ) {
147 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
151 * Special page entry point
153 * @throws ErrorPageError
156 * @throws MWException
157 * @throws PermissionsError
158 * @throws ReadOnlyError
159 * @throws UserBlockedError
161 public function execute( $par ) {
162 $this->useTransactionalTimeLimit();
165 $this->outputHeader();
167 # Check uploading enabled
168 if ( !UploadBase
::isEnabled() ) {
169 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
172 $this->addHelpLink( 'Help:Managing files' );
175 $user = $this->getUser();
176 $permissionRequired = UploadBase
::isAllowed( $user );
177 if ( $permissionRequired !== true ) {
178 throw new PermissionsError( $permissionRequired );
182 if ( $user->isBlocked() ) {
183 throw new UserBlockedError( $user->getBlock() );
187 if ( $user->isBlockedGlobally() ) {
188 throw new UserBlockedError( $user->getGlobalBlock() );
191 # Check whether we actually want to allow changing stuff
192 $this->checkReadOnly();
194 $this->loadRequest();
196 # Unsave the temporary file in case this was a cancelled upload
197 if ( $this->mCancelUpload
) {
198 if ( !$this->unsaveUploadedFile() ) {
199 # Something went wrong, so unsaveUploadedFile showed a warning
204 # Process upload or show a form
206 $this->mTokenOk
&& !$this->mCancelUpload
&&
207 ( $this->mUpload
&& $this->mUploadClicked
)
209 $this->processUpload();
211 # Backwards compatibility hook
212 // Avoid PHP 7.1 warning of passing $this by reference
214 if ( !Hooks
::run( 'UploadForm:initial', [ &$upload ] ) ) {
215 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
219 $this->showUploadForm( $this->getUploadForm() );
223 if ( $this->mUpload
) {
224 $this->mUpload
->cleanupTempFile();
229 * Show the main upload form
231 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
233 protected function showUploadForm( $form ) {
234 # Add links if file was previously deleted
235 if ( $this->mDesiredDestName
) {
236 $this->showViewDeletedLinks();
239 if ( $form instanceof HTMLForm
) {
242 $this->getOutput()->addHTML( $form );
247 * Get an UploadForm instance with title and text properly set.
249 * @param string $message HTML string to add to the form
250 * @param string $sessionKey Session key in case this is a stashed upload
251 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
254 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
256 $context = new DerivativeContext( $this->getContext() );
257 $context->setTitle( $this->getPageTitle() ); // Remove subpage
258 $form = new UploadForm( [
259 'watch' => $this->getWatchCheck(),
260 'forreupload' => $this->mForReUpload
,
261 'sessionkey' => $sessionKey,
262 'hideignorewarning' => $hideIgnoreWarning,
263 'destwarningack' => (bool)$this->mDestWarningAck
,
265 'description' => $this->mComment
,
266 'texttop' => $this->uploadFormTextTop
,
267 'textaftersummary' => $this->uploadFormTextAfterSummary
,
268 'destfile' => $this->mDesiredDestName
,
269 ], $context, $this->getLinkRenderer() );
271 # Check the token, but only if necessary
273 !$this->mTokenOk
&& !$this->mCancelUpload
&&
274 ( $this->mUpload
&& $this->mUploadClicked
)
276 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
279 # Give a notice if the user is uploading a file that has been deleted or moved
280 # Note that this is independent from the message 'filewasdeleted'
281 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
282 $delNotice = ''; // empty by default
283 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
284 $dbr = wfGetDB( DB_REPLICA
);
286 LogEventsList
::showLogExtract( $delNotice, [ 'delete', 'move' ],
289 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
290 'showIfEmpty' => false,
291 'msgKey' => [ 'upload-recreate-warning' ] ]
294 $form->addPreText( $delNotice );
297 $form->addPreText( '<div id="uploadtext">' .
298 $this->msg( 'uploadtext', [ $this->mDesiredDestName
] )->parseAsBlock() .
300 # Add upload error message
301 $form->addPreText( $message );
304 $uploadFooter = $this->msg( 'uploadfooter' );
305 if ( !$uploadFooter->isDisabled() ) {
306 $form->addPostText( '<div id="mw-upload-footer-message">'
307 . $uploadFooter->parseAsBlock() . "</div>\n" );
314 * Shows the "view X deleted revivions link""
316 protected function showViewDeletedLinks() {
317 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
318 $user = $this->getUser();
319 // Show a subtitle link to deleted revisions (to sysops et al only)
320 if ( $title instanceof Title
) {
321 $count = $title->isDeleted();
322 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
323 $restorelink = $this->getLinkRenderer()->makeKnownLink(
324 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
325 $this->msg( 'restorelink' )->numParams( $count )->text()
327 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
328 ->rawParams( $restorelink )->parseAsBlock();
329 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
335 * Stashes the upload and shows the main upload form.
337 * Note: only errors that can be handled by changing the name or
338 * description should be redirected here. It should be assumed that the
339 * file itself is sane and has passed UploadBase::verifyFile. This
340 * essentially means that UploadBase::VERIFICATION_ERROR and
341 * UploadBase::EMPTY_FILE should not be passed here.
343 * @param string $message HTML message to be passed to mainUploadForm
345 protected function showRecoverableUploadError( $message ) {
346 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
347 if ( $stashStatus->isGood() ) {
348 $sessionKey = $stashStatus->getValue()->getFileKey();
351 // TODO Add a warning message about the failure to stash here?
353 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
354 '<div class="error">' . $message . "</div>\n";
356 $form = $this->getUploadForm( $message, $sessionKey );
357 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
358 $this->showUploadForm( $form );
362 * Stashes the upload, shows the main form, but adds a "continue anyway button".
363 * Also checks whether there are actually warnings to display.
365 * @param array $warnings
366 * @return bool True if warnings were displayed, false if there are no
367 * warnings and it should continue processing
369 protected function showUploadWarning( $warnings ) {
370 # If there are no warnings, or warnings we can ignore, return early.
371 # mDestWarningAck is set when some javascript has shown the warning
372 # to the user. mForReUpload is set when the user clicks the "upload a
374 if ( !$warnings ||
( count( $warnings ) == 1
375 && isset( $warnings['exists'] )
376 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
381 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
382 if ( $stashStatus->isGood() ) {
383 $sessionKey = $stashStatus->getValue()->getFileKey();
386 // TODO Add a warning message about the failure to stash here?
389 // Add styles for the warning, reused from the live preview
390 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
392 $linkRenderer = $this->getLinkRenderer();
393 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
394 . '<div class="mw-destfile-warning"><ul>';
395 foreach ( $warnings as $warning => $args ) {
396 if ( $warning == 'badfilename' ) {
397 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
399 if ( $warning == 'exists' ) {
400 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
401 } elseif ( $warning == 'no-change' ) {
403 $filename = $file->getTitle()->getPrefixedText();
404 $msg = "\t<li>" . wfMessage( 'fileexists-no-change', $filename )->parse() . "</li>\n";
405 } elseif ( $warning == 'duplicate-version' ) {
407 $count = count( $args );
408 $filename = $file->getTitle()->getPrefixedText();
409 $message = wfMessage( 'fileexists-duplicate-version' )
410 ->params( $filename )
411 ->numParams( $count );
412 $msg = "\t<li>" . $message->parse() . "</li>\n";
413 } elseif ( $warning == 'was-deleted' ) {
414 # If the file existed before and was deleted, warn the user of this
415 $ltitle = SpecialPage
::getTitleFor( 'Log' );
416 $llink = $linkRenderer->makeKnownLink(
418 wfMessage( 'deletionlog' )->text(),
422 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
425 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
426 } elseif ( $warning == 'duplicate' ) {
427 $msg = $this->getDupeWarning( $args );
428 } elseif ( $warning == 'duplicate-archive' ) {
429 if ( $args === '' ) {
430 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
433 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
434 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
438 if ( $args === true ) {
440 } elseif ( !is_array( $args ) ) {
443 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
445 $warningHtml .= $msg;
447 $warningHtml .= "</ul></div>\n";
448 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
450 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
451 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
453 'name' => 'wpUploadIgnoreWarning',
454 'value' => $this->msg( 'ignorewarning' )->text()
457 'name' => 'wpCancelUpload',
458 'value' => $this->msg( 'reuploaddesc' )->text()
461 $this->showUploadForm( $form );
463 # Indicate that we showed a form
468 * Show the upload form with error message, but do not stash the file.
470 * @param string $message HTML string
472 protected function showUploadError( $message ) {
473 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
474 '<div class="error">' . $message . "</div>\n";
475 $this->showUploadForm( $this->getUploadForm( $message ) );
480 * Checks are made in SpecialUpload::execute()
482 protected function processUpload() {
483 // Fetch the file if required
484 $status = $this->mUpload
->fetchFile();
485 if ( !$status->isOK() ) {
486 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
490 // Avoid PHP 7.1 warning of passing $this by reference
492 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
493 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
494 // This code path is deprecated. If you want to break upload processing
495 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
496 // and UploadBase::verifyFile.
497 // If you use this hook to break uploading, the user will be returned
498 // an empty form with no error message whatsoever.
502 // Upload verification
503 $details = $this->mUpload
->verifyUpload();
504 if ( $details['status'] != UploadBase
::OK
) {
505 $this->processVerificationError( $details );
510 // Verify permissions for this title
511 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
512 if ( $permErrors !== true ) {
513 $code = array_shift( $permErrors[0] );
514 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
519 $this->mLocalFile
= $this->mUpload
->getLocalFile();
521 // Check warnings if necessary
522 if ( !$this->mIgnoreWarning
) {
523 $warnings = $this->mUpload
->checkWarnings();
524 if ( $this->showUploadWarning( $warnings ) ) {
529 // This is as late as we can throttle, after expected issues have been handled
530 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
531 $this->showRecoverableUploadError(
532 $this->msg( 'actionthrottledtext' )->escaped()
537 // Get the page text if this is not a reupload
538 if ( !$this->mForReUpload
) {
539 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
540 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
545 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
546 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
549 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
553 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
554 $changeTags, $this->getUser() );
555 if ( !$changeTagsStatus->isOK() ) {
556 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
562 $status = $this->mUpload
->performUpload(
570 if ( !$status->isGood() ) {
571 $this->showRecoverableUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
576 // Success, redirect to description page
577 $this->mUploadSuccessful
= true;
578 // Avoid PHP 7.1 warning of passing $this by reference
580 Hooks
::run( 'SpecialUploadComplete', [ &$upload ] );
581 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
585 * Get the initial image page text based on a comment and optional file status information
586 * @param string $comment
587 * @param string $license
588 * @param string $copyStatus
589 * @param string $source
590 * @param Config $config Configuration object to load data from
593 public static function getInitialPageText( $comment = '', $license = '',
594 $copyStatus = '', $source = '', Config
$config = null
596 if ( $config === null ) {
597 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
598 $config = MediaWikiServices
::getInstance()->getMainConfig();
602 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
603 /* These messages are transcluded into the actual text of the description page.
604 * Thus, forcing them as content messages makes the upload to produce an int: template
605 * instead of hardcoding it there in the uploader language.
607 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
608 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
609 $msg[$msgName] = "{{int:$msgName}}";
611 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
615 if ( $config->get( 'UseCopyrightUpload' ) ) {
617 if ( $license != '' ) {
618 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
620 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
621 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
623 '== ' . $msg['filesource'] . " ==\n" . $source;
625 if ( $license != '' ) {
626 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
627 $pageText = $filedesc .
628 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
630 $pageText = $comment;
638 * See if we should check the 'watch this page' checkbox on the form
639 * based on the user's preferences and whether we're being asked
640 * to create a new file or update an existing one.
642 * In the case where 'watch edits' is off but 'watch creations' is on,
643 * we'll leave the box unchecked.
645 * Note that the page target can be changed *on the form*, so our check
646 * state can get out of sync.
647 * @return bool|string
649 protected function getWatchCheck() {
650 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
655 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
656 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
657 // Already watched, don't change that
661 $local = wfLocalFile( $this->mDesiredDestName
);
662 if ( $local && $local->exists() ) {
663 // We're uploading a new version of an existing file.
664 // No creation, so don't watch it if we're not already.
667 // New page should get watched if that's our option.
668 return $this->getUser()->getOption( 'watchcreations' ) ||
669 $this->getUser()->getOption( 'watchuploads' );
674 * Provides output to the user for a result of UploadBase::verifyUpload
676 * @param array $details Result of UploadBase::verifyUpload
677 * @throws MWException
679 protected function processVerificationError( $details ) {
680 switch ( $details['status'] ) {
681 /** Statuses that only require name changing **/
682 case UploadBase
::MIN_LENGTH_PARTNAME
:
683 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
685 case UploadBase
::ILLEGAL_FILENAME
:
686 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
687 $details['filtered'] )->parse() );
689 case UploadBase
::FILENAME_TOO_LONG
:
690 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
692 case UploadBase
::FILETYPE_MISSING
:
693 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
695 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
696 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
699 /** Statuses that require reuploading **/
700 case UploadBase
::EMPTY_FILE
:
701 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
703 case UploadBase
::FILE_TOO_LARGE
:
704 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
706 case UploadBase
::FILETYPE_BADTYPE
:
707 $msg = $this->msg( 'filetype-banned-type' );
708 if ( isset( $details['blacklistedExt'] ) ) {
709 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
711 $msg->params( $details['finalExt'] );
713 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
714 $msg->params( $this->getLanguage()->commaList( $extensions ),
715 count( $extensions ) );
717 // Add PLURAL support for the first parameter. This results
718 // in a bit unlogical parameter sequence, but does not break
720 if ( isset( $details['blacklistedExt'] ) ) {
721 $msg->params( count( $details['blacklistedExt'] ) );
726 $this->showUploadError( $msg->parse() );
728 case UploadBase
::VERIFICATION_ERROR
:
729 unset( $details['status'] );
730 $code = array_shift( $details['details'] );
731 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
733 case UploadBase
::HOOK_ABORTED
:
734 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
735 $args = $details['error'];
736 $error = array_shift( $args );
738 $error = $details['error'];
742 $this->showUploadError( $this->msg( $error, $args )->parse() );
745 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
750 * Remove a temporarily kept file stashed by saveTempUploadedFile().
752 * @return bool Success
754 protected function unsaveUploadedFile() {
755 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
758 $success = $this->mUpload
->unsaveUploadedFile();
760 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
768 /*** Functions for formatting warnings ***/
771 * Formats a result of UploadBase::getExistsWarning as HTML
772 * This check is static and can be done pre-upload via AJAX
774 * @param array $exists The result of UploadBase::getExistsWarning
775 * @return string Empty string if there is no warning or an HTML fragment
777 public static function getExistsWarning( $exists ) {
782 $file = $exists['file'];
783 $filename = $file->getTitle()->getPrefixedText();
786 if ( $exists['warning'] == 'exists' ) {
788 $warnMsg = wfMessage( 'fileexists', $filename );
789 } elseif ( $exists['warning'] == 'page-exists' ) {
790 // Page exists but file does not
791 $warnMsg = wfMessage( 'filepageexists', $filename );
792 } elseif ( $exists['warning'] == 'exists-normalized' ) {
793 $warnMsg = wfMessage( 'fileexists-extension', $filename,
794 $exists['normalizedFile']->getTitle()->getPrefixedText() );
795 } elseif ( $exists['warning'] == 'thumb' ) {
796 // Swapped argument order compared with other messages for backwards compatibility
797 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
798 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
799 } elseif ( $exists['warning'] == 'thumb-name' ) {
800 // Image w/o '180px-' does not exists, but we do not like these filenames
801 $name = $file->getName();
802 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
803 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
804 } elseif ( $exists['warning'] == 'bad-prefix' ) {
805 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
808 return $warnMsg ?
$warnMsg->title( $file->getTitle() )->parse() : '';
812 * Construct a warning and a gallery from an array of duplicate files.
813 * @param array $dupes
816 public function getDupeWarning( $dupes ) {
821 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
822 $gallery->setShowBytes( false );
823 $gallery->setShowDimensions( false );
824 foreach ( $dupes as $file ) {
825 $gallery->add( $file->getTitle() );
829 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
830 $gallery->toHTML() . "</li>\n";
833 protected function getGroupName() {
838 * Should we rotate images in the preview on Special:Upload.
840 * This controls js: mw.config.get( 'wgFileCanRotate' )
842 * @todo What about non-BitmapHandler handled files?
844 public static function rotationEnabled() {
845 $bitmapHandler = new BitmapHandler();
846 return $bitmapHandler->autoRotateEnabled();
851 * Sub class of HTMLForm that provides the form section of SpecialUpload
853 class UploadForm
extends HTMLForm
{
855 protected $mForReUpload;
856 protected $mSessionKey;
857 protected $mHideIgnoreWarning;
858 protected $mDestWarningAck;
859 protected $mDestFile;
863 protected $mTextAfterSummary;
865 protected $mSourceIds;
867 protected $mMaxFileSize = [];
869 protected $mMaxUploadSize = [];
871 public function __construct( array $options = [], IContextSource
$context = null,
872 LinkRenderer
$linkRenderer = null
874 if ( $context instanceof IContextSource
) {
875 $this->setContext( $context );
878 if ( !$linkRenderer ) {
879 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
882 $this->mWatch
= !empty( $options['watch'] );
883 $this->mForReUpload
= !empty( $options['forreupload'] );
884 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
885 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
886 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
887 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
889 $this->mComment
= isset( $options['description'] ) ?
890 $options['description'] : '';
892 $this->mTextTop
= isset( $options['texttop'] )
893 ?
$options['texttop'] : '';
895 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
896 ?
$options['textaftersummary'] : '';
898 $sourceDescriptor = $this->getSourceSection();
899 $descriptor = $sourceDescriptor
900 +
$this->getDescriptionSection()
901 +
$this->getOptionsSection();
903 Hooks
::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
904 parent
::__construct( $descriptor, $context, 'upload' );
906 # Add a link to edit MediaWiki:Licenses
907 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
908 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
909 $licensesLink = $linkRenderer->makeKnownLink(
910 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
911 $this->msg( 'licenses-edit' )->text(),
913 [ 'action' => 'edit' ]
915 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
916 $this->addFooterText( $editLicenses, 'description' );
919 # Set some form properties
920 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
921 $this->setSubmitName( 'wpUpload' );
922 # Used message keys: 'accesskey-upload', 'tooltip-upload'
923 $this->setSubmitTooltip( 'upload' );
924 $this->setId( 'mw-upload-form' );
926 # Build a list of IDs for javascript insertion
927 $this->mSourceIds
= [];
928 foreach ( $sourceDescriptor as $field ) {
929 if ( !empty( $field['id'] ) ) {
930 $this->mSourceIds
[] = $field['id'];
936 * Get the descriptor of the fieldset that contains the file source
937 * selection. The section is 'source'
939 * @return array Descriptor array
941 protected function getSourceSection() {
942 if ( $this->mSessionKey
) {
946 'default' => $this->mSessionKey
,
950 'default' => 'Stash',
955 $canUploadByUrl = UploadFromUrl
::isEnabled()
956 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
957 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
958 $radio = $canUploadByUrl;
959 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
962 if ( $this->mTextTop
) {
963 $descriptor['UploadFormTextTop'] = [
965 'section' => 'source',
966 'default' => $this->mTextTop
,
971 $this->mMaxUploadSize
['file'] = min(
972 UploadBase
::getMaxUploadSize( 'file' ),
973 UploadBase
::getMaxPhpUploadSize()
976 $help = $this->msg( 'upload-maxfilesize',
977 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
980 // If the user can also upload by URL, there are 2 different file size limits.
981 // This extra message helps stress which limit corresponds to what.
982 if ( $canUploadByUrl ) {
983 $help .= $this->msg( 'word-separator' )->escaped();
984 $help .= $this->msg( 'upload_source_file' )->parse();
987 $descriptor['UploadFile'] = [
988 'class' => 'UploadSourceField',
989 'section' => 'source',
991 'id' => 'wpUploadFile',
992 'radio-id' => 'wpSourceTypeFile',
993 'label-message' => 'sourcefilename',
994 'upload-type' => 'File',
997 'checked' => $selectedSourceType == 'file',
1000 if ( $canUploadByUrl ) {
1001 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
1002 $descriptor['UploadFileURL'] = [
1003 'class' => 'UploadSourceField',
1004 'section' => 'source',
1005 'id' => 'wpUploadFileURL',
1006 'radio-id' => 'wpSourceTypeurl',
1007 'label-message' => 'sourceurl',
1008 'upload-type' => 'url',
1010 'help' => $this->msg( 'upload-maxfilesize',
1011 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
1013 $this->msg( 'word-separator' )->escaped() .
1014 $this->msg( 'upload_source_url' )->parse(),
1015 'checked' => $selectedSourceType == 'url',
1018 Hooks
::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
1020 $descriptor['Extensions'] = [
1022 'section' => 'source',
1023 'default' => $this->getExtensionsMessage(),
1031 * Get the messages indicating which extensions are preferred and prohibitted.
1033 * @return string HTML string containing the message
1035 protected function getExtensionsMessage() {
1036 # Print a list of allowed file extensions, if so configured. We ignore
1037 # MIME type here, it's incomprehensible to most people and too long.
1038 $config = $this->getConfig();
1040 if ( $config->get( 'CheckFileExtensions' ) ) {
1041 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
1042 if ( $config->get( 'StrictFileExtensions' ) ) {
1043 # Everything not permitted is banned
1045 '<div id="mw-upload-permitted">' .
1046 $this->msg( 'upload-permitted' )
1047 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1048 ->numParams( count( $fileExtensions ) )
1052 # We have to list both preferred and prohibited
1053 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1055 '<div id="mw-upload-preferred">' .
1056 $this->msg( 'upload-preferred' )
1057 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1058 ->numParams( count( $fileExtensions ) )
1061 '<div id="mw-upload-prohibited">' .
1062 $this->msg( 'upload-prohibited' )
1063 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1064 ->numParams( count( $fileBlacklist ) )
1069 # Everything is permitted.
1070 $extensionsList = '';
1073 return $extensionsList;
1077 * Get the descriptor of the fieldset that contains the file description
1078 * input. The section is 'description'
1080 * @return array Descriptor array
1082 protected function getDescriptionSection() {
1083 $config = $this->getConfig();
1084 if ( $this->mSessionKey
) {
1085 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1087 $file = $stash->getFile( $this->mSessionKey
);
1088 } catch ( Exception
$e ) {
1094 $mto = $file->transform( [ 'width' => 120 ] );
1096 $this->addHeaderText(
1097 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1098 Html
::element( 'img', [
1099 'src' => $mto->getUrl(),
1100 'class' => 'thumbimage',
1101 ] ) . '</div>', 'description' );
1109 'section' => 'description',
1110 'id' => 'wpDestFile',
1111 'label-message' => 'destfilename',
1113 'default' => $this->mDestFile
,
1114 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1115 'nodata' => strval( $this->mDestFile
) !== '',
1117 'UploadDescription' => [
1118 'type' => 'textarea',
1119 'section' => 'description',
1120 'id' => 'wpUploadDescription',
1121 'label-message' => $this->mForReUpload
1122 ?
'filereuploadsummary'
1123 : 'fileuploadsummary',
1124 'default' => $this->mComment
,
1129 if ( $this->mTextAfterSummary
) {
1130 $descriptor['UploadFormTextAfterSummary'] = [
1132 'section' => 'description',
1133 'default' => $this->mTextAfterSummary
,
1140 'type' => 'edittools',
1141 'section' => 'description',
1142 'message' => 'edittools-upload',
1146 if ( $this->mForReUpload
) {
1147 $descriptor['DestFile']['readonly'] = true;
1149 $descriptor['License'] = [
1151 'class' => 'Licenses',
1152 'section' => 'description',
1153 'id' => 'wpLicense',
1154 'label-message' => 'license',
1158 if ( $config->get( 'UseCopyrightUpload' ) ) {
1159 $descriptor['UploadCopyStatus'] = [
1161 'section' => 'description',
1162 'id' => 'wpUploadCopyStatus',
1163 'label-message' => 'filestatus',
1165 $descriptor['UploadSource'] = [
1167 'section' => 'description',
1168 'id' => 'wpUploadSource',
1169 'label-message' => 'filesource',
1177 * Get the descriptor of the fieldset that contains the upload options,
1178 * such as "watch this file". The section is 'options'
1180 * @return array Descriptor array
1182 protected function getOptionsSection() {
1183 $user = $this->getUser();
1184 if ( $user->isLoggedIn() ) {
1188 'id' => 'wpWatchthis',
1189 'label-message' => 'watchthisupload',
1190 'section' => 'options',
1191 'default' => $this->mWatch
,
1195 if ( !$this->mHideIgnoreWarning
) {
1196 $descriptor['IgnoreWarning'] = [
1198 'id' => 'wpIgnoreWarning',
1199 'label-message' => 'ignorewarnings',
1200 'section' => 'options',
1204 $descriptor['DestFileWarningAck'] = [
1206 'id' => 'wpDestFileWarningAck',
1207 'default' => $this->mDestWarningAck ?
'1' : '',
1210 if ( $this->mForReUpload
) {
1211 $descriptor['ForReUpload'] = [
1213 'id' => 'wpForReUpload',
1222 * Add the upload JS and show the form.
1224 public function show() {
1225 $this->addUploadJS();
1230 * Add upload JS to the OutputPage
1232 protected function addUploadJS() {
1233 $config = $this->getConfig();
1235 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1236 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1237 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1238 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1241 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1242 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1243 'wgUploadAutoFill' => !$this->mForReUpload
&&
1244 // If we received mDestFile from the request, don't autofill
1245 // the wpDestFile textbox
1246 $this->mDestFile
=== '',
1247 'wgUploadSourceIds' => $this->mSourceIds
,
1248 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1249 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1250 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1251 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1252 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1253 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1256 $out = $this->getOutput();
1257 $out->addJsConfigVars( $scriptVars );
1260 'mediawiki.action.edit', // For <charinsert> support
1261 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1266 * Empty function; submission is handled elsewhere.
1268 * @return bool False
1270 function trySubmit() {
1276 * A form field that contains a radio box in the label
1278 class UploadSourceField
extends HTMLTextField
{
1281 * @param array $cellAttributes
1284 function getLabelHtml( $cellAttributes = [] ) {
1285 $id = $this->mParams
['id'];
1286 $label = Html
::rawElement( 'label', [ 'for' => $id ], $this->mLabel
);
1288 if ( !empty( $this->mParams
['radio'] ) ) {
1289 if ( isset( $this->mParams
['radio-id'] ) ) {
1290 $radioId = $this->mParams
['radio-id'];
1292 // Old way. For the benefit of extensions that do not define
1293 // the 'radio-id' key.
1294 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1298 'name' => 'wpSourceType',
1301 'value' => $this->mParams
['upload-type'],
1304 if ( !empty( $this->mParams
['checked'] ) ) {
1305 $attribs['checked'] = 'checked';
1308 $label .= Html
::element( 'input', $attribs );
1311 return Html
::rawElement( 'td', [ 'class' => 'mw-label' ] +
$cellAttributes, $label );
1317 function getSize() {
1318 return isset( $this->mParams
['size'] )
1319 ?
$this->mParams
['size']