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 if ( !Hooks
::run( 'UploadForm:initial', [ &$this ] ) ) {
213 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
217 $this->showUploadForm( $this->getUploadForm() );
221 if ( $this->mUpload
) {
222 $this->mUpload
->cleanupTempFile();
227 * Show the main upload form
229 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
231 protected function showUploadForm( $form ) {
232 # Add links if file was previously deleted
233 if ( $this->mDesiredDestName
) {
234 $this->showViewDeletedLinks();
237 if ( $form instanceof HTMLForm
) {
240 $this->getOutput()->addHTML( $form );
245 * Get an UploadForm instance with title and text properly set.
247 * @param string $message HTML string to add to the form
248 * @param string $sessionKey Session key in case this is a stashed upload
249 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
252 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
254 $context = new DerivativeContext( $this->getContext() );
255 $context->setTitle( $this->getPageTitle() ); // Remove subpage
256 $form = new UploadForm( [
257 'watch' => $this->getWatchCheck(),
258 'forreupload' => $this->mForReUpload
,
259 'sessionkey' => $sessionKey,
260 'hideignorewarning' => $hideIgnoreWarning,
261 'destwarningack' => (bool)$this->mDestWarningAck
,
263 'description' => $this->mComment
,
264 'texttop' => $this->uploadFormTextTop
,
265 'textaftersummary' => $this->uploadFormTextAfterSummary
,
266 'destfile' => $this->mDesiredDestName
,
267 ], $context, $this->getLinkRenderer() );
269 # Check the token, but only if necessary
271 !$this->mTokenOk
&& !$this->mCancelUpload
&&
272 ( $this->mUpload
&& $this->mUploadClicked
)
274 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
277 # Give a notice if the user is uploading a file that has been deleted or moved
278 # Note that this is independent from the message 'filewasdeleted'
279 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
280 $delNotice = ''; // empty by default
281 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
282 LogEventsList
::showLogExtract( $delNotice, [ 'delete', 'move' ],
285 'conds' => [ "log_action != 'revision'" ],
286 'showIfEmpty' => false,
287 'msgKey' => [ 'upload-recreate-warning' ] ]
290 $form->addPreText( $delNotice );
293 $form->addPreText( '<div id="uploadtext">' .
294 $this->msg( 'uploadtext', [ $this->mDesiredDestName
] )->parseAsBlock() .
296 # Add upload error message
297 $form->addPreText( $message );
300 $uploadFooter = $this->msg( 'uploadfooter' );
301 if ( !$uploadFooter->isDisabled() ) {
302 $form->addPostText( '<div id="mw-upload-footer-message">'
303 . $uploadFooter->parseAsBlock() . "</div>\n" );
310 * Shows the "view X deleted revivions link""
312 protected function showViewDeletedLinks() {
313 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
314 $user = $this->getUser();
315 // Show a subtitle link to deleted revisions (to sysops et al only)
316 if ( $title instanceof Title
) {
317 $count = $title->isDeleted();
318 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
319 $restorelink = $this->getLinkRenderer()->makeKnownLink(
320 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
321 $this->msg( 'restorelink' )->numParams( $count )->text()
323 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
324 ->rawParams( $restorelink )->parseAsBlock();
325 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
331 * Stashes the upload and shows the main upload form.
333 * Note: only errors that can be handled by changing the name or
334 * description should be redirected here. It should be assumed that the
335 * file itself is sane and has passed UploadBase::verifyFile. This
336 * essentially means that UploadBase::VERIFICATION_ERROR and
337 * UploadBase::EMPTY_FILE should not be passed here.
339 * @param string $message HTML message to be passed to mainUploadForm
341 protected function showRecoverableUploadError( $message ) {
342 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
343 if ( $stashStatus->isGood() ) {
344 $sessionKey = $stashStatus->getValue()->getFileKey();
347 // TODO Add a warning message about the failure to stash here?
349 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
350 '<div class="error">' . $message . "</div>\n";
352 $form = $this->getUploadForm( $message, $sessionKey );
353 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
354 $this->showUploadForm( $form );
358 * Stashes the upload, shows the main form, but adds a "continue anyway button".
359 * Also checks whether there are actually warnings to display.
361 * @param array $warnings
362 * @return bool True if warnings were displayed, false if there are no
363 * warnings and it should continue processing
365 protected function showUploadWarning( $warnings ) {
366 # If there are no warnings, or warnings we can ignore, return early.
367 # mDestWarningAck is set when some javascript has shown the warning
368 # to the user. mForReUpload is set when the user clicks the "upload a
370 if ( !$warnings ||
( count( $warnings ) == 1
371 && isset( $warnings['exists'] )
372 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
377 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
378 if ( $stashStatus->isGood() ) {
379 $sessionKey = $stashStatus->getValue()->getFileKey();
382 // TODO Add a warning message about the failure to stash here?
385 // Add styles for the warning, reused from the live preview
386 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
388 $linkRenderer = $this->getLinkRenderer();
389 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
390 . '<div class="mw-destfile-warning"><ul>';
391 foreach ( $warnings as $warning => $args ) {
392 if ( $warning == 'badfilename' ) {
393 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
395 if ( $warning == 'exists' ) {
396 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
397 } elseif ( $warning == 'was-deleted' ) {
398 # If the file existed before and was deleted, warn the user of this
399 $ltitle = SpecialPage
::getTitleFor( 'Log' );
400 $llink = $linkRenderer->makeKnownLink(
402 wfMessage( 'deletionlog' )->text(),
406 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
409 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
410 } elseif ( $warning == 'duplicate' ) {
411 $msg = $this->getDupeWarning( $args );
412 } elseif ( $warning == 'duplicate-archive' ) {
413 if ( $args === '' ) {
414 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
417 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
418 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
422 if ( $args === true ) {
424 } elseif ( !is_array( $args ) ) {
427 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
429 $warningHtml .= $msg;
431 $warningHtml .= "</ul></div>\n";
432 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
434 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
435 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
437 'name' => 'wpUploadIgnoreWarning',
438 'value' => $this->msg( 'ignorewarning' )->text()
441 'name' => 'wpCancelUpload',
442 'value' => $this->msg( 'reuploaddesc' )->text()
445 $this->showUploadForm( $form );
447 # Indicate that we showed a form
452 * Show the upload form with error message, but do not stash the file.
454 * @param string $message HTML string
456 protected function showUploadError( $message ) {
457 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
458 '<div class="error">' . $message . "</div>\n";
459 $this->showUploadForm( $this->getUploadForm( $message ) );
464 * Checks are made in SpecialUpload::execute()
466 protected function processUpload() {
467 // Fetch the file if required
468 $status = $this->mUpload
->fetchFile();
469 if ( !$status->isOK() ) {
470 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
475 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', [ &$this ] ) ) {
476 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
477 // This code path is deprecated. If you want to break upload processing
478 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
479 // and UploadBase::verifyFile.
480 // If you use this hook to break uploading, the user will be returned
481 // an empty form with no error message whatsoever.
485 // Upload verification
486 $details = $this->mUpload
->verifyUpload();
487 if ( $details['status'] != UploadBase
::OK
) {
488 $this->processVerificationError( $details );
493 // Verify permissions for this title
494 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
495 if ( $permErrors !== true ) {
496 $code = array_shift( $permErrors[0] );
497 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
502 $this->mLocalFile
= $this->mUpload
->getLocalFile();
504 // Check warnings if necessary
505 if ( !$this->mIgnoreWarning
) {
506 $warnings = $this->mUpload
->checkWarnings();
507 if ( $this->showUploadWarning( $warnings ) ) {
512 // This is as late as we can throttle, after expected issues have been handled
513 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
514 $this->showRecoverableUploadError(
515 $this->msg( 'actionthrottledtext' )->escaped()
520 // Get the page text if this is not a reupload
521 if ( !$this->mForReUpload
) {
522 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
523 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
528 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
529 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
532 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
536 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
537 $changeTags, $this->getUser() );
538 if ( !$changeTagsStatus->isOK() ) {
539 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
545 $status = $this->mUpload
->performUpload(
553 if ( !$status->isGood() ) {
554 $this->showRecoverableUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
559 // Success, redirect to description page
560 $this->mUploadSuccessful
= true;
561 Hooks
::run( 'SpecialUploadComplete', [ &$this ] );
562 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
566 * Get the initial image page text based on a comment and optional file status information
567 * @param string $comment
568 * @param string $license
569 * @param string $copyStatus
570 * @param string $source
571 * @param Config $config Configuration object to load data from
574 public static function getInitialPageText( $comment = '', $license = '',
575 $copyStatus = '', $source = '', Config
$config = null
577 if ( $config === null ) {
578 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
579 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
583 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
584 /* These messages are transcluded into the actual text of the description page.
585 * Thus, forcing them as content messages makes the upload to produce an int: template
586 * instead of hardcoding it there in the uploader language.
588 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
589 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
590 $msg[$msgName] = "{{int:$msgName}}";
592 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
596 if ( $config->get( 'UseCopyrightUpload' ) ) {
598 if ( $license != '' ) {
599 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
601 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
602 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
604 '== ' . $msg['filesource'] . " ==\n" . $source;
606 if ( $license != '' ) {
607 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
608 $pageText = $filedesc .
609 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
611 $pageText = $comment;
619 * See if we should check the 'watch this page' checkbox on the form
620 * based on the user's preferences and whether we're being asked
621 * to create a new file or update an existing one.
623 * In the case where 'watch edits' is off but 'watch creations' is on,
624 * we'll leave the box unchecked.
626 * Note that the page target can be changed *on the form*, so our check
627 * state can get out of sync.
628 * @return bool|string
630 protected function getWatchCheck() {
631 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
636 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
637 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
638 // Already watched, don't change that
642 $local = wfLocalFile( $this->mDesiredDestName
);
643 if ( $local && $local->exists() ) {
644 // We're uploading a new version of an existing file.
645 // No creation, so don't watch it if we're not already.
648 // New page should get watched if that's our option.
649 return $this->getUser()->getOption( 'watchcreations' ) ||
650 $this->getUser()->getOption( 'watchuploads' );
655 * Provides output to the user for a result of UploadBase::verifyUpload
657 * @param array $details Result of UploadBase::verifyUpload
658 * @throws MWException
660 protected function processVerificationError( $details ) {
661 switch ( $details['status'] ) {
663 /** Statuses that only require name changing **/
664 case UploadBase
::MIN_LENGTH_PARTNAME
:
665 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
667 case UploadBase
::ILLEGAL_FILENAME
:
668 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
669 $details['filtered'] )->parse() );
671 case UploadBase
::FILENAME_TOO_LONG
:
672 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
674 case UploadBase
::FILETYPE_MISSING
:
675 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
677 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
678 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
681 /** Statuses that require reuploading **/
682 case UploadBase
::EMPTY_FILE
:
683 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
685 case UploadBase
::FILE_TOO_LARGE
:
686 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
688 case UploadBase
::FILETYPE_BADTYPE
:
689 $msg = $this->msg( 'filetype-banned-type' );
690 if ( isset( $details['blacklistedExt'] ) ) {
691 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
693 $msg->params( $details['finalExt'] );
695 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
696 $msg->params( $this->getLanguage()->commaList( $extensions ),
697 count( $extensions ) );
699 // Add PLURAL support for the first parameter. This results
700 // in a bit unlogical parameter sequence, but does not break
702 if ( isset( $details['blacklistedExt'] ) ) {
703 $msg->params( count( $details['blacklistedExt'] ) );
708 $this->showUploadError( $msg->parse() );
710 case UploadBase
::VERIFICATION_ERROR
:
711 unset( $details['status'] );
712 $code = array_shift( $details['details'] );
713 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
715 case UploadBase
::HOOK_ABORTED
:
716 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
717 $args = $details['error'];
718 $error = array_shift( $args );
720 $error = $details['error'];
724 $this->showUploadError( $this->msg( $error, $args )->parse() );
727 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
732 * Remove a temporarily kept file stashed by saveTempUploadedFile().
734 * @return bool Success
736 protected function unsaveUploadedFile() {
737 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
740 $success = $this->mUpload
->unsaveUploadedFile();
742 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
750 /*** Functions for formatting warnings ***/
753 * Formats a result of UploadBase::getExistsWarning as HTML
754 * This check is static and can be done pre-upload via AJAX
756 * @param array $exists The result of UploadBase::getExistsWarning
757 * @return string Empty string if there is no warning or an HTML fragment
759 public static function getExistsWarning( $exists ) {
764 $file = $exists['file'];
765 $filename = $file->getTitle()->getPrefixedText();
768 if ( $exists['warning'] == 'exists' ) {
770 $warning = wfMessage( 'fileexists', $filename )->parse();
771 } elseif ( $exists['warning'] == 'page-exists' ) {
772 // Page exists but file does not
773 $warning = wfMessage( 'filepageexists', $filename )->parse();
774 } elseif ( $exists['warning'] == 'exists-normalized' ) {
775 $warning = wfMessage( 'fileexists-extension', $filename,
776 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
777 } elseif ( $exists['warning'] == 'thumb' ) {
778 // Swapped argument order compared with other messages for backwards compatibility
779 $warning = wfMessage( 'fileexists-thumbnail-yes',
780 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
781 } elseif ( $exists['warning'] == 'thumb-name' ) {
782 // Image w/o '180px-' does not exists, but we do not like these filenames
783 $name = $file->getName();
784 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
785 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
786 } elseif ( $exists['warning'] == 'bad-prefix' ) {
787 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
794 * Construct a warning and a gallery from an array of duplicate files.
795 * @param array $dupes
798 public function getDupeWarning( $dupes ) {
803 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
804 $gallery->setShowBytes( false );
805 foreach ( $dupes as $file ) {
806 $gallery->add( $file->getTitle() );
810 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
811 $gallery->toHTML() . "</li>\n";
814 protected function getGroupName() {
819 * Should we rotate images in the preview on Special:Upload.
821 * This controls js: mw.config.get( 'wgFileCanRotate' )
823 * @todo What about non-BitmapHandler handled files?
825 public static function rotationEnabled() {
826 $bitmapHandler = new BitmapHandler();
827 return $bitmapHandler->autoRotateEnabled();
832 * Sub class of HTMLForm that provides the form section of SpecialUpload
834 class UploadForm
extends HTMLForm
{
836 protected $mForReUpload;
837 protected $mSessionKey;
838 protected $mHideIgnoreWarning;
839 protected $mDestWarningAck;
840 protected $mDestFile;
844 protected $mTextAfterSummary;
846 protected $mSourceIds;
848 protected $mMaxFileSize = [];
850 protected $mMaxUploadSize = [];
852 public function __construct( array $options = [], IContextSource
$context = null,
853 LinkRenderer
$linkRenderer = null
855 if ( $context instanceof IContextSource
) {
856 $this->setContext( $context );
859 if ( !$linkRenderer ) {
860 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
863 $this->mWatch
= !empty( $options['watch'] );
864 $this->mForReUpload
= !empty( $options['forreupload'] );
865 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
866 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
867 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
868 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
870 $this->mComment
= isset( $options['description'] ) ?
871 $options['description'] : '';
873 $this->mTextTop
= isset( $options['texttop'] )
874 ?
$options['texttop'] : '';
876 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
877 ?
$options['textaftersummary'] : '';
879 $sourceDescriptor = $this->getSourceSection();
880 $descriptor = $sourceDescriptor
881 +
$this->getDescriptionSection()
882 +
$this->getOptionsSection();
884 Hooks
::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
885 parent
::__construct( $descriptor, $context, 'upload' );
887 # Add a link to edit MediaWiki:Licenses
888 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
889 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
890 $licensesLink = $linkRenderer->makeKnownLink(
891 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
892 $this->msg( 'licenses-edit' )->text(),
894 [ 'action' => 'edit' ]
896 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
897 $this->addFooterText( $editLicenses, 'description' );
900 # Set some form properties
901 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
902 $this->setSubmitName( 'wpUpload' );
903 # Used message keys: 'accesskey-upload', 'tooltip-upload'
904 $this->setSubmitTooltip( 'upload' );
905 $this->setId( 'mw-upload-form' );
907 # Build a list of IDs for javascript insertion
908 $this->mSourceIds
= [];
909 foreach ( $sourceDescriptor as $field ) {
910 if ( !empty( $field['id'] ) ) {
911 $this->mSourceIds
[] = $field['id'];
917 * Get the descriptor of the fieldset that contains the file source
918 * selection. The section is 'source'
920 * @return array Descriptor array
922 protected function getSourceSection() {
923 if ( $this->mSessionKey
) {
927 'default' => $this->mSessionKey
,
931 'default' => 'Stash',
936 $canUploadByUrl = UploadFromUrl
::isEnabled()
937 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
938 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
939 $radio = $canUploadByUrl;
940 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
943 if ( $this->mTextTop
) {
944 $descriptor['UploadFormTextTop'] = [
946 'section' => 'source',
947 'default' => $this->mTextTop
,
952 $this->mMaxUploadSize
['file'] = min(
953 UploadBase
::getMaxUploadSize( 'file' ),
954 UploadBase
::getMaxPhpUploadSize()
957 $help = $this->msg( 'upload-maxfilesize',
958 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
961 // If the user can also upload by URL, there are 2 different file size limits.
962 // This extra message helps stress which limit corresponds to what.
963 if ( $canUploadByUrl ) {
964 $help .= $this->msg( 'word-separator' )->escaped();
965 $help .= $this->msg( 'upload_source_file' )->parse();
968 $descriptor['UploadFile'] = [
969 'class' => 'UploadSourceField',
970 'section' => 'source',
972 'id' => 'wpUploadFile',
973 'radio-id' => 'wpSourceTypeFile',
974 'label-message' => 'sourcefilename',
975 'upload-type' => 'File',
978 'checked' => $selectedSourceType == 'file',
981 if ( $canUploadByUrl ) {
982 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
983 $descriptor['UploadFileURL'] = [
984 'class' => 'UploadSourceField',
985 'section' => 'source',
986 'id' => 'wpUploadFileURL',
987 'radio-id' => 'wpSourceTypeurl',
988 'label-message' => 'sourceurl',
989 'upload-type' => 'url',
991 'help' => $this->msg( 'upload-maxfilesize',
992 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
994 $this->msg( 'word-separator' )->escaped() .
995 $this->msg( 'upload_source_url' )->parse(),
996 'checked' => $selectedSourceType == 'url',
999 Hooks
::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
1001 $descriptor['Extensions'] = [
1003 'section' => 'source',
1004 'default' => $this->getExtensionsMessage(),
1012 * Get the messages indicating which extensions are preferred and prohibitted.
1014 * @return string HTML string containing the message
1016 protected function getExtensionsMessage() {
1017 # Print a list of allowed file extensions, if so configured. We ignore
1018 # MIME type here, it's incomprehensible to most people and too long.
1019 $config = $this->getConfig();
1021 if ( $config->get( 'CheckFileExtensions' ) ) {
1022 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
1023 if ( $config->get( 'StrictFileExtensions' ) ) {
1024 # Everything not permitted is banned
1026 '<div id="mw-upload-permitted">' .
1027 $this->msg( 'upload-permitted' )
1028 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1029 ->numParams( count( $fileExtensions ) )
1033 # We have to list both preferred and prohibited
1034 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1036 '<div id="mw-upload-preferred">' .
1037 $this->msg( 'upload-preferred' )
1038 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1039 ->numParams( count( $fileExtensions ) )
1042 '<div id="mw-upload-prohibited">' .
1043 $this->msg( 'upload-prohibited' )
1044 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1045 ->numParams( count( $fileBlacklist ) )
1050 # Everything is permitted.
1051 $extensionsList = '';
1054 return $extensionsList;
1058 * Get the descriptor of the fieldset that contains the file description
1059 * input. The section is 'description'
1061 * @return array Descriptor array
1063 protected function getDescriptionSection() {
1064 $config = $this->getConfig();
1065 if ( $this->mSessionKey
) {
1066 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1068 $file = $stash->getFile( $this->mSessionKey
);
1069 } catch ( Exception
$e ) {
1075 $mto = $file->transform( [ 'width' => 120 ] );
1076 $this->addHeaderText(
1077 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1078 Html
::element( 'img', [
1079 'src' => $mto->getUrl(),
1080 'class' => 'thumbimage',
1081 ] ) . '</div>', 'description' );
1088 'section' => 'description',
1089 'id' => 'wpDestFile',
1090 'label-message' => 'destfilename',
1092 'default' => $this->mDestFile
,
1093 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1094 'nodata' => strval( $this->mDestFile
) !== '',
1096 'UploadDescription' => [
1097 'type' => 'textarea',
1098 'section' => 'description',
1099 'id' => 'wpUploadDescription',
1100 'label-message' => $this->mForReUpload
1101 ?
'filereuploadsummary'
1102 : 'fileuploadsummary',
1103 'default' => $this->mComment
,
1104 'cols' => $this->getUser()->getIntOption( 'cols' ),
1108 if ( $this->mTextAfterSummary
) {
1109 $descriptor['UploadFormTextAfterSummary'] = [
1111 'section' => 'description',
1112 'default' => $this->mTextAfterSummary
,
1119 'type' => 'edittools',
1120 'section' => 'description',
1121 'message' => 'edittools-upload',
1125 if ( $this->mForReUpload
) {
1126 $descriptor['DestFile']['readonly'] = true;
1128 $descriptor['License'] = [
1130 'class' => 'Licenses',
1131 'section' => 'description',
1132 'id' => 'wpLicense',
1133 'label-message' => 'license',
1137 if ( $config->get( 'UseCopyrightUpload' ) ) {
1138 $descriptor['UploadCopyStatus'] = [
1140 'section' => 'description',
1141 'id' => 'wpUploadCopyStatus',
1142 'label-message' => 'filestatus',
1144 $descriptor['UploadSource'] = [
1146 'section' => 'description',
1147 'id' => 'wpUploadSource',
1148 'label-message' => 'filesource',
1156 * Get the descriptor of the fieldset that contains the upload options,
1157 * such as "watch this file". The section is 'options'
1159 * @return array Descriptor array
1161 protected function getOptionsSection() {
1162 $user = $this->getUser();
1163 if ( $user->isLoggedIn() ) {
1167 'id' => 'wpWatchthis',
1168 'label-message' => 'watchthisupload',
1169 'section' => 'options',
1170 'default' => $this->mWatch
,
1174 if ( !$this->mHideIgnoreWarning
) {
1175 $descriptor['IgnoreWarning'] = [
1177 'id' => 'wpIgnoreWarning',
1178 'label-message' => 'ignorewarnings',
1179 'section' => 'options',
1183 $descriptor['DestFileWarningAck'] = [
1185 'id' => 'wpDestFileWarningAck',
1186 'default' => $this->mDestWarningAck ?
'1' : '',
1189 if ( $this->mForReUpload
) {
1190 $descriptor['ForReUpload'] = [
1192 'id' => 'wpForReUpload',
1201 * Add the upload JS and show the form.
1203 public function show() {
1204 $this->addUploadJS();
1209 * Add upload JS to the OutputPage
1211 protected function addUploadJS() {
1212 $config = $this->getConfig();
1214 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1215 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1216 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1217 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1220 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1221 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1222 'wgUploadAutoFill' => !$this->mForReUpload
&&
1223 // If we received mDestFile from the request, don't autofill
1224 // the wpDestFile textbox
1225 $this->mDestFile
=== '',
1226 'wgUploadSourceIds' => $this->mSourceIds
,
1227 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1228 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1229 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1230 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1231 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1232 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1235 $out = $this->getOutput();
1236 $out->addJsConfigVars( $scriptVars );
1239 'mediawiki.action.edit', // For <charinsert> support
1240 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1245 * Empty function; submission is handled elsewhere.
1247 * @return bool False
1249 function trySubmit() {
1255 * A form field that contains a radio box in the label
1257 class UploadSourceField
extends HTMLTextField
{
1260 * @param array $cellAttributes
1263 function getLabelHtml( $cellAttributes = [] ) {
1264 $id = $this->mParams
['id'];
1265 $label = Html
::rawElement( 'label', [ 'for' => $id ], $this->mLabel
);
1267 if ( !empty( $this->mParams
['radio'] ) ) {
1268 if ( isset( $this->mParams
['radio-id'] ) ) {
1269 $radioId = $this->mParams
['radio-id'];
1271 // Old way. For the benefit of extensions that do not define
1272 // the 'radio-id' key.
1273 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1277 'name' => 'wpSourceType',
1280 'value' => $this->mParams
['upload-type'],
1283 if ( !empty( $this->mParams
['checked'] ) ) {
1284 $attribs['checked'] = 'checked';
1287 $label .= Html
::element( 'input', $attribs );
1290 return Html
::rawElement( 'td', [ 'class' => 'mw-label' ] +
$cellAttributes, $label );
1296 function getSize() {
1297 return isset( $this->mParams
['size'] )
1298 ?
$this->mParams
['size']