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
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
31 class SpecialUpload
extends SpecialPage
{
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param WebRequest $request Data posted.
37 public function __construct( $request = null ) {
38 parent
::__construct( 'Upload', 'upload' );
41 public function doesWrites() {
45 /** Misc variables **/
47 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
51 /** @var UploadBase */
56 public $mUploadClicked;
58 /** User input variables from the "description" section **/
60 /** @var string The requested target file name */
61 public $mDesiredDestName;
65 /** User input variables from the root section **/
67 public $mIgnoreWarning;
69 public $mCopyrightStatus;
70 public $mCopyrightSource;
72 /** Hidden variables **/
74 public $mDestWarningAck;
76 /** @var bool The user followed an "overwrite this file" link */
79 /** @var bool The user clicked "Cancel and return to upload form" button */
80 public $mCancelUpload;
83 /** @var bool Subclasses can use this to determine whether a file was uploaded */
84 public $mUploadSuccessful = false;
86 /** Text injection points for hooks not using HTMLForm **/
87 public $uploadFormTextTop;
88 public $uploadFormTextAfterSummary;
91 * Initialize instance variables from request and create an Upload handler
93 protected function loadRequest() {
94 $this->mRequest
= $request = $this->getRequest();
95 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
96 $this->mUpload
= UploadBase
::createFromRequest( $request );
97 $this->mUploadClicked
= $request->wasPosted()
98 && ( $request->getCheck( 'wpUpload' )
99 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
101 // Guess the desired name from the filename if not provided
102 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
103 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
104 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
106 $this->mLicense
= $request->getText( 'wpLicense' );
108 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
109 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
110 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
111 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
112 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
113 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
115 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
117 $commentDefault = '';
118 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
119 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
120 $commentDefault = $commentMsg->plain();
122 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
124 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
125 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
127 // If it was posted check for the token (no remote POST'ing with user credentials)
128 $token = $request->getVal( 'wpEditToken' );
129 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
131 $this->uploadFormTextTop
= '';
132 $this->uploadFormTextAfterSummary
= '';
136 * This page can be shown if uploading is enabled.
137 * Handle permission checking elsewhere in order to be able to show
138 * custom error messages.
143 public function userCanExecute( User
$user ) {
144 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
148 * Special page entry point
150 * @throws ErrorPageError
153 * @throws MWException
154 * @throws PermissionsError
155 * @throws ReadOnlyError
156 * @throws UserBlockedError
158 public function execute( $par ) {
159 $this->useTransactionalTimeLimit();
162 $this->outputHeader();
164 # Check uploading enabled
165 if ( !UploadBase
::isEnabled() ) {
166 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
169 $this->addHelpLink( 'Help:Managing files' );
172 $user = $this->getUser();
173 $permissionRequired = UploadBase
::isAllowed( $user );
174 if ( $permissionRequired !== true ) {
175 throw new PermissionsError( $permissionRequired );
179 if ( $user->isBlocked() ) {
180 throw new UserBlockedError( $user->getBlock() );
184 if ( $user->isBlockedGlobally() ) {
185 throw new UserBlockedError( $user->getGlobalBlock() );
188 # Check whether we actually want to allow changing stuff
189 $this->checkReadOnly();
191 $this->loadRequest();
193 # Unsave the temporary file in case this was a cancelled upload
194 if ( $this->mCancelUpload
) {
195 if ( !$this->unsaveUploadedFile() ) {
196 # Something went wrong, so unsaveUploadedFile showed a warning
201 # Process upload or show a form
203 $this->mTokenOk
&& !$this->mCancelUpload
&&
204 ( $this->mUpload
&& $this->mUploadClicked
)
206 $this->processUpload();
208 # Backwards compatibility hook
209 if ( !Hooks
::run( 'UploadForm:initial', [ &$this ] ) ) {
210 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
214 $this->showUploadForm( $this->getUploadForm() );
218 if ( $this->mUpload
) {
219 $this->mUpload
->cleanupTempFile();
224 * Show the main upload form
226 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
228 protected function showUploadForm( $form ) {
229 # Add links if file was previously deleted
230 if ( $this->mDesiredDestName
) {
231 $this->showViewDeletedLinks();
234 if ( $form instanceof HTMLForm
) {
237 $this->getOutput()->addHTML( $form );
242 * Get an UploadForm instance with title and text properly set.
244 * @param string $message HTML string to add to the form
245 * @param string $sessionKey Session key in case this is a stashed upload
246 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
249 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
251 $context = new DerivativeContext( $this->getContext() );
252 $context->setTitle( $this->getPageTitle() ); // Remove subpage
253 $form = new UploadForm( [
254 'watch' => $this->getWatchCheck(),
255 'forreupload' => $this->mForReUpload
,
256 'sessionkey' => $sessionKey,
257 'hideignorewarning' => $hideIgnoreWarning,
258 'destwarningack' => (bool)$this->mDestWarningAck
,
260 'description' => $this->mComment
,
261 'texttop' => $this->uploadFormTextTop
,
262 'textaftersummary' => $this->uploadFormTextAfterSummary
,
263 'destfile' => $this->mDesiredDestName
,
266 # Check the token, but only if necessary
268 !$this->mTokenOk
&& !$this->mCancelUpload
&&
269 ( $this->mUpload
&& $this->mUploadClicked
)
271 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
274 # Give a notice if the user is uploading a file that has been deleted or moved
275 # Note that this is independent from the message 'filewasdeleted'
276 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
277 $delNotice = ''; // empty by default
278 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
279 LogEventsList
::showLogExtract( $delNotice, [ 'delete', 'move' ],
282 'conds' => [ "log_action != 'revision'" ],
283 'showIfEmpty' => false,
284 'msgKey' => [ 'upload-recreate-warning' ] ]
287 $form->addPreText( $delNotice );
290 $form->addPreText( '<div id="uploadtext">' .
291 $this->msg( 'uploadtext', [ $this->mDesiredDestName
] )->parseAsBlock() .
293 # Add upload error message
294 $form->addPreText( $message );
297 $uploadFooter = $this->msg( 'uploadfooter' );
298 if ( !$uploadFooter->isDisabled() ) {
299 $form->addPostText( '<div id="mw-upload-footer-message">'
300 . $uploadFooter->parseAsBlock() . "</div>\n" );
307 * Shows the "view X deleted revivions link""
309 protected function showViewDeletedLinks() {
310 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
311 $user = $this->getUser();
312 // Show a subtitle link to deleted revisions (to sysops et al only)
313 if ( $title instanceof Title
) {
314 $count = $title->isDeleted();
315 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
316 $restorelink = Linker
::linkKnown(
317 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
318 $this->msg( 'restorelink' )->numParams( $count )->escaped()
320 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
321 ->rawParams( $restorelink )->parseAsBlock();
322 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
328 * Stashes the upload and shows the main upload form.
330 * Note: only errors that can be handled by changing the name or
331 * description should be redirected here. It should be assumed that the
332 * file itself is sane and has passed UploadBase::verifyFile. This
333 * essentially means that UploadBase::VERIFICATION_ERROR and
334 * UploadBase::EMPTY_FILE should not be passed here.
336 * @param string $message HTML message to be passed to mainUploadForm
338 protected function showRecoverableUploadError( $message ) {
339 $sessionKey = $this->mUpload
->stashSession();
340 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
341 '<div class="error">' . $message . "</div>\n";
343 $form = $this->getUploadForm( $message, $sessionKey );
344 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
345 $this->showUploadForm( $form );
349 * Stashes the upload, shows the main form, but adds a "continue anyway button".
350 * Also checks whether there are actually warnings to display.
352 * @param array $warnings
353 * @return bool True if warnings were displayed, false if there are no
354 * warnings and it should continue processing
356 protected function showUploadWarning( $warnings ) {
357 # If there are no warnings, or warnings we can ignore, return early.
358 # mDestWarningAck is set when some javascript has shown the warning
359 # to the user. mForReUpload is set when the user clicks the "upload a
361 if ( !$warnings ||
( count( $warnings ) == 1
362 && isset( $warnings['exists'] )
363 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
368 $sessionKey = $this->mUpload
->stashSession();
370 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
371 . '<div class="warningbox"><ul>';
372 foreach ( $warnings as $warning => $args ) {
373 if ( $warning == 'badfilename' ) {
374 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
376 if ( $warning == 'exists' ) {
377 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
378 } elseif ( $warning == 'was-deleted' ) {
379 # If the file existed before and was deleted, warn the user of this
380 $ltitle = SpecialPage
::getTitleFor( 'Log' );
381 $llink = Linker
::linkKnown(
383 wfMessage( 'deletionlog' )->escaped(),
387 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
390 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
391 } elseif ( $warning == 'duplicate' ) {
392 $msg = $this->getDupeWarning( $args );
393 } elseif ( $warning == 'duplicate-archive' ) {
394 if ( $args === '' ) {
395 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
398 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
399 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
403 if ( $args === true ) {
405 } elseif ( !is_array( $args ) ) {
408 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
410 $warningHtml .= $msg;
412 $warningHtml .= "</ul></div>\n";
413 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
415 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
416 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
418 'name' => 'wpUploadIgnoreWarning',
419 'value' => $this->msg( 'ignorewarning' )->text()
422 'name' => 'wpCancelUpload',
423 'value' => $this->msg( 'reuploaddesc' )->text()
426 $this->showUploadForm( $form );
428 # Indicate that we showed a form
433 * Show the upload form with error message, but do not stash the file.
435 * @param string $message HTML string
437 protected function showUploadError( $message ) {
438 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
439 '<div class="error">' . $message . "</div>\n";
440 $this->showUploadForm( $this->getUploadForm( $message ) );
445 * Checks are made in SpecialUpload::execute()
447 protected function processUpload() {
448 // Fetch the file if required
449 $status = $this->mUpload
->fetchFile();
450 if ( !$status->isOK() ) {
451 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
456 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', [ &$this ] ) ) {
457 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
458 // This code path is deprecated. If you want to break upload processing
459 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
460 // and UploadBase::verifyFile.
461 // If you use this hook to break uploading, the user will be returned
462 // an empty form with no error message whatsoever.
466 // Upload verification
467 $details = $this->mUpload
->verifyUpload();
468 if ( $details['status'] != UploadBase
::OK
) {
469 $this->processVerificationError( $details );
474 // Verify permissions for this title
475 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
476 if ( $permErrors !== true ) {
477 $code = array_shift( $permErrors[0] );
478 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
483 $this->mLocalFile
= $this->mUpload
->getLocalFile();
485 // Check warnings if necessary
486 if ( !$this->mIgnoreWarning
) {
487 $warnings = $this->mUpload
->checkWarnings();
488 if ( $this->showUploadWarning( $warnings ) ) {
493 // This is as late as we can throttle, after expected issues have been handled
494 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
495 $this->showRecoverableUploadError(
496 $this->msg( 'actionthrottledtext' )->escaped()
501 // Get the page text if this is not a reupload
502 if ( !$this->mForReUpload
) {
503 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
504 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
509 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
510 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
513 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
517 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
518 $changeTags, $this->getUser() );
519 if ( !$changeTagsStatus->isOK() ) {
520 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
526 $status = $this->mUpload
->performUpload(
534 if ( !$status->isGood() ) {
535 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
540 // Success, redirect to description page
541 $this->mUploadSuccessful
= true;
542 Hooks
::run( 'SpecialUploadComplete', [ &$this ] );
543 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
547 * Get the initial image page text based on a comment and optional file status information
548 * @param string $comment
549 * @param string $license
550 * @param string $copyStatus
551 * @param string $source
552 * @param Config $config Configuration object to load data from
555 public static function getInitialPageText( $comment = '', $license = '',
556 $copyStatus = '', $source = '', Config
$config = null
558 if ( $config === null ) {
559 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
560 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
564 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
565 /* These messages are transcluded into the actual text of the description page.
566 * Thus, forcing them as content messages makes the upload to produce an int: template
567 * instead of hardcoding it there in the uploader language.
569 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
570 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
571 $msg[$msgName] = "{{int:$msgName}}";
573 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
577 if ( $config->get( 'UseCopyrightUpload' ) ) {
579 if ( $license != '' ) {
580 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
582 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
583 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
585 '== ' . $msg['filesource'] . " ==\n" . $source;
587 if ( $license != '' ) {
588 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
589 $pageText = $filedesc .
590 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
592 $pageText = $comment;
600 * See if we should check the 'watch this page' checkbox on the form
601 * based on the user's preferences and whether we're being asked
602 * to create a new file or update an existing one.
604 * In the case where 'watch edits' is off but 'watch creations' is on,
605 * we'll leave the box unchecked.
607 * Note that the page target can be changed *on the form*, so our check
608 * state can get out of sync.
609 * @return bool|string
611 protected function getWatchCheck() {
612 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
617 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
618 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
619 // Already watched, don't change that
623 $local = wfLocalFile( $this->mDesiredDestName
);
624 if ( $local && $local->exists() ) {
625 // We're uploading a new version of an existing file.
626 // No creation, so don't watch it if we're not already.
629 // New page should get watched if that's our option.
630 return $this->getUser()->getOption( 'watchcreations' ) ||
631 $this->getUser()->getOption( 'watchuploads' );
636 * Provides output to the user for a result of UploadBase::verifyUpload
638 * @param array $details Result of UploadBase::verifyUpload
639 * @throws MWException
641 protected function processVerificationError( $details ) {
642 switch ( $details['status'] ) {
644 /** Statuses that only require name changing **/
645 case UploadBase
::MIN_LENGTH_PARTNAME
:
646 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
648 case UploadBase
::ILLEGAL_FILENAME
:
649 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
650 $details['filtered'] )->parse() );
652 case UploadBase
::FILENAME_TOO_LONG
:
653 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
655 case UploadBase
::FILETYPE_MISSING
:
656 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
658 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
659 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
662 /** Statuses that require reuploading **/
663 case UploadBase
::EMPTY_FILE
:
664 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
666 case UploadBase
::FILE_TOO_LARGE
:
667 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
669 case UploadBase
::FILETYPE_BADTYPE
:
670 $msg = $this->msg( 'filetype-banned-type' );
671 if ( isset( $details['blacklistedExt'] ) ) {
672 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
674 $msg->params( $details['finalExt'] );
676 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
677 $msg->params( $this->getLanguage()->commaList( $extensions ),
678 count( $extensions ) );
680 // Add PLURAL support for the first parameter. This results
681 // in a bit unlogical parameter sequence, but does not break
683 if ( isset( $details['blacklistedExt'] ) ) {
684 $msg->params( count( $details['blacklistedExt'] ) );
689 $this->showUploadError( $msg->parse() );
691 case UploadBase
::VERIFICATION_ERROR
:
692 unset( $details['status'] );
693 $code = array_shift( $details['details'] );
694 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
696 case UploadBase
::HOOK_ABORTED
:
697 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
698 $args = $details['error'];
699 $error = array_shift( $args );
701 $error = $details['error'];
705 $this->showUploadError( $this->msg( $error, $args )->parse() );
708 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
713 * Remove a temporarily kept file stashed by saveTempUploadedFile().
715 * @return bool Success
717 protected function unsaveUploadedFile() {
718 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
721 $success = $this->mUpload
->unsaveUploadedFile();
723 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
731 /*** Functions for formatting warnings ***/
734 * Formats a result of UploadBase::getExistsWarning as HTML
735 * This check is static and can be done pre-upload via AJAX
737 * @param array $exists The result of UploadBase::getExistsWarning
738 * @return string Empty string if there is no warning or an HTML fragment
740 public static function getExistsWarning( $exists ) {
745 $file = $exists['file'];
746 $filename = $file->getTitle()->getPrefixedText();
749 if ( $exists['warning'] == 'exists' ) {
751 $warning = wfMessage( 'fileexists', $filename )->parse();
752 } elseif ( $exists['warning'] == 'page-exists' ) {
753 // Page exists but file does not
754 $warning = wfMessage( 'filepageexists', $filename )->parse();
755 } elseif ( $exists['warning'] == 'exists-normalized' ) {
756 $warning = wfMessage( 'fileexists-extension', $filename,
757 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
758 } elseif ( $exists['warning'] == 'thumb' ) {
759 // Swapped argument order compared with other messages for backwards compatibility
760 $warning = wfMessage( 'fileexists-thumbnail-yes',
761 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
762 } elseif ( $exists['warning'] == 'thumb-name' ) {
763 // Image w/o '180px-' does not exists, but we do not like these filenames
764 $name = $file->getName();
765 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
766 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
767 } elseif ( $exists['warning'] == 'bad-prefix' ) {
768 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
775 * Construct a warning and a gallery from an array of duplicate files.
776 * @param array $dupes
779 public function getDupeWarning( $dupes ) {
784 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
785 $gallery->setShowBytes( false );
786 foreach ( $dupes as $file ) {
787 $gallery->add( $file->getTitle() );
791 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
792 $gallery->toHTML() . "</li>\n";
795 protected function getGroupName() {
800 * Should we rotate images in the preview on Special:Upload.
802 * This controls js: mw.config.get( 'wgFileCanRotate' )
804 * @todo What about non-BitmapHandler handled files?
806 public static function rotationEnabled() {
807 $bitmapHandler = new BitmapHandler();
808 return $bitmapHandler->autoRotateEnabled();
813 * Sub class of HTMLForm that provides the form section of SpecialUpload
815 class UploadForm
extends HTMLForm
{
817 protected $mForReUpload;
818 protected $mSessionKey;
819 protected $mHideIgnoreWarning;
820 protected $mDestWarningAck;
821 protected $mDestFile;
825 protected $mTextAfterSummary;
827 protected $mSourceIds;
829 protected $mMaxFileSize = [];
831 protected $mMaxUploadSize = [];
833 public function __construct( array $options = [], IContextSource
$context = null ) {
834 if ( $context instanceof IContextSource
) {
835 $this->setContext( $context );
838 $this->mWatch
= !empty( $options['watch'] );
839 $this->mForReUpload
= !empty( $options['forreupload'] );
840 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
841 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
842 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
843 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
845 $this->mComment
= isset( $options['description'] ) ?
846 $options['description'] : '';
848 $this->mTextTop
= isset( $options['texttop'] )
849 ?
$options['texttop'] : '';
851 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
852 ?
$options['textaftersummary'] : '';
854 $sourceDescriptor = $this->getSourceSection();
855 $descriptor = $sourceDescriptor
856 +
$this->getDescriptionSection()
857 +
$this->getOptionsSection();
859 Hooks
::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
860 parent
::__construct( $descriptor, $context, 'upload' );
862 # Add a link to edit MediaWik:Licenses
863 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
864 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
865 $licensesLink = Linker
::linkKnown(
866 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
867 $this->msg( 'licenses-edit' )->escaped(),
869 [ 'action' => 'edit' ]
871 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
872 $this->addFooterText( $editLicenses, 'description' );
875 # Set some form properties
876 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
877 $this->setSubmitName( 'wpUpload' );
878 # Used message keys: 'accesskey-upload', 'tooltip-upload'
879 $this->setSubmitTooltip( 'upload' );
880 $this->setId( 'mw-upload-form' );
882 # Build a list of IDs for javascript insertion
883 $this->mSourceIds
= [];
884 foreach ( $sourceDescriptor as $field ) {
885 if ( !empty( $field['id'] ) ) {
886 $this->mSourceIds
[] = $field['id'];
892 * Get the descriptor of the fieldset that contains the file source
893 * selection. The section is 'source'
895 * @return array Descriptor array
897 protected function getSourceSection() {
898 if ( $this->mSessionKey
) {
902 'default' => $this->mSessionKey
,
906 'default' => 'Stash',
911 $canUploadByUrl = UploadFromUrl
::isEnabled()
912 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
913 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
914 $radio = $canUploadByUrl;
915 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
918 if ( $this->mTextTop
) {
919 $descriptor['UploadFormTextTop'] = [
921 'section' => 'source',
922 'default' => $this->mTextTop
,
927 $this->mMaxUploadSize
['file'] = min(
928 UploadBase
::getMaxUploadSize( 'file' ),
929 UploadBase
::getMaxPhpUploadSize()
932 $help = $this->msg( 'upload-maxfilesize',
933 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
936 // If the user can also upload by URL, there are 2 different file size limits.
937 // This extra message helps stress which limit corresponds to what.
938 if ( $canUploadByUrl ) {
939 $help .= $this->msg( 'word-separator' )->escaped();
940 $help .= $this->msg( 'upload_source_file' )->parse();
943 $descriptor['UploadFile'] = [
944 'class' => 'UploadSourceField',
945 'section' => 'source',
947 'id' => 'wpUploadFile',
948 'radio-id' => 'wpSourceTypeFile',
949 'label-message' => 'sourcefilename',
950 'upload-type' => 'File',
953 'checked' => $selectedSourceType == 'file',
956 if ( $canUploadByUrl ) {
957 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
958 $descriptor['UploadFileURL'] = [
959 'class' => 'UploadSourceField',
960 'section' => 'source',
961 'id' => 'wpUploadFileURL',
962 'radio-id' => 'wpSourceTypeurl',
963 'label-message' => 'sourceurl',
964 'upload-type' => 'url',
966 'help' => $this->msg( 'upload-maxfilesize',
967 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
969 $this->msg( 'word-separator' )->escaped() .
970 $this->msg( 'upload_source_url' )->parse(),
971 'checked' => $selectedSourceType == 'url',
974 Hooks
::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
976 $descriptor['Extensions'] = [
978 'section' => 'source',
979 'default' => $this->getExtensionsMessage(),
987 * Get the messages indicating which extensions are preferred and prohibitted.
989 * @return string HTML string containing the message
991 protected function getExtensionsMessage() {
992 # Print a list of allowed file extensions, if so configured. We ignore
993 # MIME type here, it's incomprehensible to most people and too long.
994 $config = $this->getConfig();
996 if ( $config->get( 'CheckFileExtensions' ) ) {
997 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
998 if ( $config->get( 'StrictFileExtensions' ) ) {
999 # Everything not permitted is banned
1001 '<div id="mw-upload-permitted">' .
1002 $this->msg( 'upload-permitted' )
1003 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1004 ->numParams( count( $fileExtensions ) )
1008 # We have to list both preferred and prohibited
1009 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1011 '<div id="mw-upload-preferred">' .
1012 $this->msg( 'upload-preferred' )
1013 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1014 ->numParams( count( $fileExtensions ) )
1017 '<div id="mw-upload-prohibited">' .
1018 $this->msg( 'upload-prohibited' )
1019 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1020 ->numParams( count( $fileBlacklist ) )
1025 # Everything is permitted.
1026 $extensionsList = '';
1029 return $extensionsList;
1033 * Get the descriptor of the fieldset that contains the file description
1034 * input. The section is 'description'
1036 * @return array Descriptor array
1038 protected function getDescriptionSection() {
1039 $config = $this->getConfig();
1040 if ( $this->mSessionKey
) {
1041 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1043 $file = $stash->getFile( $this->mSessionKey
);
1044 } catch ( Exception
$e ) {
1050 $mto = $file->transform( [ 'width' => 120 ] );
1051 $this->addHeaderText(
1052 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1053 Html
::element( 'img', [
1054 'src' => $mto->getUrl(),
1055 'class' => 'thumbimage',
1056 ] ) . '</div>', 'description' );
1063 'section' => 'description',
1064 'id' => 'wpDestFile',
1065 'label-message' => 'destfilename',
1067 'default' => $this->mDestFile
,
1068 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1069 'nodata' => strval( $this->mDestFile
) !== '',
1071 'UploadDescription' => [
1072 'type' => 'textarea',
1073 'section' => 'description',
1074 'id' => 'wpUploadDescription',
1075 'label-message' => $this->mForReUpload
1076 ?
'filereuploadsummary'
1077 : 'fileuploadsummary',
1078 'default' => $this->mComment
,
1079 'cols' => $this->getUser()->getIntOption( 'cols' ),
1083 if ( $this->mTextAfterSummary
) {
1084 $descriptor['UploadFormTextAfterSummary'] = [
1086 'section' => 'description',
1087 'default' => $this->mTextAfterSummary
,
1094 'type' => 'edittools',
1095 'section' => 'description',
1096 'message' => 'edittools-upload',
1100 if ( $this->mForReUpload
) {
1101 $descriptor['DestFile']['readonly'] = true;
1103 $descriptor['License'] = [
1105 'class' => 'Licenses',
1106 'section' => 'description',
1107 'id' => 'wpLicense',
1108 'label-message' => 'license',
1112 if ( $config->get( 'UseCopyrightUpload' ) ) {
1113 $descriptor['UploadCopyStatus'] = [
1115 'section' => 'description',
1116 'id' => 'wpUploadCopyStatus',
1117 'label-message' => 'filestatus',
1119 $descriptor['UploadSource'] = [
1121 'section' => 'description',
1122 'id' => 'wpUploadSource',
1123 'label-message' => 'filesource',
1131 * Get the descriptor of the fieldset that contains the upload options,
1132 * such as "watch this file". The section is 'options'
1134 * @return array Descriptor array
1136 protected function getOptionsSection() {
1137 $user = $this->getUser();
1138 if ( $user->isLoggedIn() ) {
1142 'id' => 'wpWatchthis',
1143 'label-message' => 'watchthisupload',
1144 'section' => 'options',
1145 'default' => $this->mWatch
,
1149 if ( !$this->mHideIgnoreWarning
) {
1150 $descriptor['IgnoreWarning'] = [
1152 'id' => 'wpIgnoreWarning',
1153 'label-message' => 'ignorewarnings',
1154 'section' => 'options',
1158 $descriptor['DestFileWarningAck'] = [
1160 'id' => 'wpDestFileWarningAck',
1161 'default' => $this->mDestWarningAck ?
'1' : '',
1164 if ( $this->mForReUpload
) {
1165 $descriptor['ForReUpload'] = [
1167 'id' => 'wpForReUpload',
1176 * Add the upload JS and show the form.
1178 public function show() {
1179 $this->addUploadJS();
1184 * Add upload JS to the OutputPage
1186 protected function addUploadJS() {
1187 $config = $this->getConfig();
1189 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1190 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1191 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1192 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1195 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1196 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1197 'wgUploadAutoFill' => !$this->mForReUpload
&&
1198 // If we received mDestFile from the request, don't autofill
1199 // the wpDestFile textbox
1200 $this->mDestFile
=== '',
1201 'wgUploadSourceIds' => $this->mSourceIds
,
1202 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1203 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1204 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1205 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1206 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1207 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1210 $out = $this->getOutput();
1211 $out->addJsConfigVars( $scriptVars );
1214 'mediawiki.action.edit', // For <charinsert> support
1215 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1220 * Empty function; submission is handled elsewhere.
1222 * @return bool False
1224 function trySubmit() {
1230 * A form field that contains a radio box in the label
1232 class UploadSourceField
extends HTMLTextField
{
1235 * @param array $cellAttributes
1238 function getLabelHtml( $cellAttributes = [] ) {
1239 $id = $this->mParams
['id'];
1240 $label = Html
::rawElement( 'label', [ 'for' => $id ], $this->mLabel
);
1242 if ( !empty( $this->mParams
['radio'] ) ) {
1243 if ( isset( $this->mParams
['radio-id'] ) ) {
1244 $radioId = $this->mParams
['radio-id'];
1246 // Old way. For the benefit of extensions that do not define
1247 // the 'radio-id' key.
1248 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1252 'name' => 'wpSourceType',
1255 'value' => $this->mParams
['upload-type'],
1258 if ( !empty( $this->mParams
['checked'] ) ) {
1259 $attribs['checked'] = 'checked';
1262 $label .= Html
::element( 'input', $attribs );
1265 return Html
::rawElement( 'td', [ 'class' => 'mw-label' ] +
$cellAttributes, $label );
1271 function getSize() {
1272 return isset( $this->mParams
['size'] )
1273 ?
$this->mParams
['size']