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() );
183 # Check whether we actually want to allow changing stuff
184 $this->checkReadOnly();
186 $this->loadRequest();
188 # Unsave the temporary file in case this was a cancelled upload
189 if ( $this->mCancelUpload
) {
190 if ( !$this->unsaveUploadedFile() ) {
191 # Something went wrong, so unsaveUploadedFile showed a warning
196 # Process upload or show a form
198 $this->mTokenOk
&& !$this->mCancelUpload
&&
199 ( $this->mUpload
&& $this->mUploadClicked
)
201 $this->processUpload();
203 # Backwards compatibility hook
204 if ( !Hooks
::run( 'UploadForm:initial', [ &$this ] ) ) {
205 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
209 $this->showUploadForm( $this->getUploadForm() );
213 if ( $this->mUpload
) {
214 $this->mUpload
->cleanupTempFile();
219 * Show the main upload form
221 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
223 protected function showUploadForm( $form ) {
224 # Add links if file was previously deleted
225 if ( $this->mDesiredDestName
) {
226 $this->showViewDeletedLinks();
229 if ( $form instanceof HTMLForm
) {
232 $this->getOutput()->addHTML( $form );
237 * Get an UploadForm instance with title and text properly set.
239 * @param string $message HTML string to add to the form
240 * @param string $sessionKey Session key in case this is a stashed upload
241 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
244 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
246 $context = new DerivativeContext( $this->getContext() );
247 $context->setTitle( $this->getPageTitle() ); // Remove subpage
248 $form = new UploadForm( [
249 'watch' => $this->getWatchCheck(),
250 'forreupload' => $this->mForReUpload
,
251 'sessionkey' => $sessionKey,
252 'hideignorewarning' => $hideIgnoreWarning,
253 'destwarningack' => (bool)$this->mDestWarningAck
,
255 'description' => $this->mComment
,
256 'texttop' => $this->uploadFormTextTop
,
257 'textaftersummary' => $this->uploadFormTextAfterSummary
,
258 'destfile' => $this->mDesiredDestName
,
261 # Check the token, but only if necessary
263 !$this->mTokenOk
&& !$this->mCancelUpload
&&
264 ( $this->mUpload
&& $this->mUploadClicked
)
266 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
269 # Give a notice if the user is uploading a file that has been deleted or moved
270 # Note that this is independent from the message 'filewasdeleted'
271 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
272 $delNotice = ''; // empty by default
273 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
274 LogEventsList
::showLogExtract( $delNotice, [ 'delete', 'move' ],
277 'conds' => [ "log_action != 'revision'" ],
278 'showIfEmpty' => false,
279 'msgKey' => [ 'upload-recreate-warning' ] ]
282 $form->addPreText( $delNotice );
285 $form->addPreText( '<div id="uploadtext">' .
286 $this->msg( 'uploadtext', [ $this->mDesiredDestName
] )->parseAsBlock() .
288 # Add upload error message
289 $form->addPreText( $message );
292 $uploadFooter = $this->msg( 'uploadfooter' );
293 if ( !$uploadFooter->isDisabled() ) {
294 $form->addPostText( '<div id="mw-upload-footer-message">'
295 . $uploadFooter->parseAsBlock() . "</div>\n" );
302 * Shows the "view X deleted revivions link""
304 protected function showViewDeletedLinks() {
305 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
306 $user = $this->getUser();
307 // Show a subtitle link to deleted revisions (to sysops et al only)
308 if ( $title instanceof Title
) {
309 $count = $title->isDeleted();
310 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
311 $restorelink = Linker
::linkKnown(
312 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
313 $this->msg( 'restorelink' )->numParams( $count )->escaped()
315 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
316 ->rawParams( $restorelink )->parseAsBlock();
317 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
323 * Stashes the upload and shows the main upload form.
325 * Note: only errors that can be handled by changing the name or
326 * description should be redirected here. It should be assumed that the
327 * file itself is sane and has passed UploadBase::verifyFile. This
328 * essentially means that UploadBase::VERIFICATION_ERROR and
329 * UploadBase::EMPTY_FILE should not be passed here.
331 * @param string $message HTML message to be passed to mainUploadForm
333 protected function showRecoverableUploadError( $message ) {
334 $sessionKey = $this->mUpload
->stashSession();
335 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
336 '<div class="error">' . $message . "</div>\n";
338 $form = $this->getUploadForm( $message, $sessionKey );
339 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
340 $this->showUploadForm( $form );
344 * Stashes the upload, shows the main form, but adds a "continue anyway button".
345 * Also checks whether there are actually warnings to display.
347 * @param array $warnings
348 * @return bool True if warnings were displayed, false if there are no
349 * warnings and it should continue processing
351 protected function showUploadWarning( $warnings ) {
352 # If there are no warnings, or warnings we can ignore, return early.
353 # mDestWarningAck is set when some javascript has shown the warning
354 # to the user. mForReUpload is set when the user clicks the "upload a
356 if ( !$warnings ||
( count( $warnings ) == 1
357 && isset( $warnings['exists'] )
358 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
363 $sessionKey = $this->mUpload
->stashSession();
365 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
366 . '<div class="warningbox"><ul>';
367 foreach ( $warnings as $warning => $args ) {
368 if ( $warning == 'badfilename' ) {
369 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
371 if ( $warning == 'exists' ) {
372 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
373 } elseif ( $warning == 'was-deleted' ) {
374 # If the file existed before and was deleted, warn the user of this
375 $ltitle = SpecialPage
::getTitleFor( 'Log' );
376 $llink = Linker
::linkKnown(
378 wfMessage( 'deletionlog' )->escaped(),
382 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
385 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
386 } elseif ( $warning == 'duplicate' ) {
387 $msg = $this->getDupeWarning( $args );
388 } elseif ( $warning == 'duplicate-archive' ) {
389 if ( $args === '' ) {
390 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
393 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
394 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
398 if ( $args === true ) {
400 } elseif ( !is_array( $args ) ) {
403 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
405 $warningHtml .= $msg;
407 $warningHtml .= "</ul></div>\n";
408 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
410 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
411 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
413 'name' => 'wpUploadIgnoreWarning',
414 'value' => $this->msg( 'ignorewarning' )->text()
417 'name' => 'wpCancelUpload',
418 'value' => $this->msg( 'reuploaddesc' )->text()
421 $this->showUploadForm( $form );
423 # Indicate that we showed a form
428 * Show the upload form with error message, but do not stash the file.
430 * @param string $message HTML string
432 protected function showUploadError( $message ) {
433 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
434 '<div class="error">' . $message . "</div>\n";
435 $this->showUploadForm( $this->getUploadForm( $message ) );
440 * Checks are made in SpecialUpload::execute()
442 protected function processUpload() {
443 // Fetch the file if required
444 $status = $this->mUpload
->fetchFile();
445 if ( !$status->isOK() ) {
446 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
451 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', [ &$this ] ) ) {
452 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
453 // This code path is deprecated. If you want to break upload processing
454 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
455 // and UploadBase::verifyFile.
456 // If you use this hook to break uploading, the user will be returned
457 // an empty form with no error message whatsoever.
461 // Upload verification
462 $details = $this->mUpload
->verifyUpload();
463 if ( $details['status'] != UploadBase
::OK
) {
464 $this->processVerificationError( $details );
469 // Verify permissions for this title
470 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
471 if ( $permErrors !== true ) {
472 $code = array_shift( $permErrors[0] );
473 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
478 $this->mLocalFile
= $this->mUpload
->getLocalFile();
480 // Check warnings if necessary
481 if ( !$this->mIgnoreWarning
) {
482 $warnings = $this->mUpload
->checkWarnings();
483 if ( $this->showUploadWarning( $warnings ) ) {
488 // This is as late as we can throttle, after expected issues have been handled
489 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
490 $this->showRecoverableUploadError(
491 $this->msg( 'actionthrottledtext' )->escaped()
496 // Get the page text if this is not a reupload
497 if ( !$this->mForReUpload
) {
498 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
499 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
504 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
505 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
508 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
512 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
513 $changeTags, $this->getUser() );
514 if ( !$changeTagsStatus->isOK() ) {
515 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
521 $status = $this->mUpload
->performUpload(
529 if ( !$status->isGood() ) {
530 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
535 // Success, redirect to description page
536 $this->mUploadSuccessful
= true;
537 Hooks
::run( 'SpecialUploadComplete', [ &$this ] );
538 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
542 * Get the initial image page text based on a comment and optional file status information
543 * @param string $comment
544 * @param string $license
545 * @param string $copyStatus
546 * @param string $source
547 * @param Config $config Configuration object to load data from
550 public static function getInitialPageText( $comment = '', $license = '',
551 $copyStatus = '', $source = '', Config
$config = null
553 if ( $config === null ) {
554 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
555 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
559 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
560 /* These messages are transcluded into the actual text of the description page.
561 * Thus, forcing them as content messages makes the upload to produce an int: template
562 * instead of hardcoding it there in the uploader language.
564 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
565 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
566 $msg[$msgName] = "{{int:$msgName}}";
568 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
572 if ( $config->get( 'UseCopyrightUpload' ) ) {
574 if ( $license != '' ) {
575 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
577 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
578 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
580 '== ' . $msg['filesource'] . " ==\n" . $source;
582 if ( $license != '' ) {
583 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
584 $pageText = $filedesc .
585 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
587 $pageText = $comment;
595 * See if we should check the 'watch this page' checkbox on the form
596 * based on the user's preferences and whether we're being asked
597 * to create a new file or update an existing one.
599 * In the case where 'watch edits' is off but 'watch creations' is on,
600 * we'll leave the box unchecked.
602 * Note that the page target can be changed *on the form*, so our check
603 * state can get out of sync.
604 * @return bool|string
606 protected function getWatchCheck() {
607 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
612 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
613 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
614 // Already watched, don't change that
618 $local = wfLocalFile( $this->mDesiredDestName
);
619 if ( $local && $local->exists() ) {
620 // We're uploading a new version of an existing file.
621 // No creation, so don't watch it if we're not already.
624 // New page should get watched if that's our option.
625 return $this->getUser()->getOption( 'watchcreations' );
630 * Provides output to the user for a result of UploadBase::verifyUpload
632 * @param array $details Result of UploadBase::verifyUpload
633 * @throws MWException
635 protected function processVerificationError( $details ) {
636 switch ( $details['status'] ) {
638 /** Statuses that only require name changing **/
639 case UploadBase
::MIN_LENGTH_PARTNAME
:
640 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
642 case UploadBase
::ILLEGAL_FILENAME
:
643 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
644 $details['filtered'] )->parse() );
646 case UploadBase
::FILENAME_TOO_LONG
:
647 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
649 case UploadBase
::FILETYPE_MISSING
:
650 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
652 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
653 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
656 /** Statuses that require reuploading **/
657 case UploadBase
::EMPTY_FILE
:
658 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
660 case UploadBase
::FILE_TOO_LARGE
:
661 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
663 case UploadBase
::FILETYPE_BADTYPE
:
664 $msg = $this->msg( 'filetype-banned-type' );
665 if ( isset( $details['blacklistedExt'] ) ) {
666 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
668 $msg->params( $details['finalExt'] );
670 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
671 $msg->params( $this->getLanguage()->commaList( $extensions ),
672 count( $extensions ) );
674 // Add PLURAL support for the first parameter. This results
675 // in a bit unlogical parameter sequence, but does not break
677 if ( isset( $details['blacklistedExt'] ) ) {
678 $msg->params( count( $details['blacklistedExt'] ) );
683 $this->showUploadError( $msg->parse() );
685 case UploadBase
::VERIFICATION_ERROR
:
686 unset( $details['status'] );
687 $code = array_shift( $details['details'] );
688 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
690 case UploadBase
::HOOK_ABORTED
:
691 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
692 $args = $details['error'];
693 $error = array_shift( $args );
695 $error = $details['error'];
699 $this->showUploadError( $this->msg( $error, $args )->parse() );
702 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
707 * Remove a temporarily kept file stashed by saveTempUploadedFile().
709 * @return bool Success
711 protected function unsaveUploadedFile() {
712 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
715 $success = $this->mUpload
->unsaveUploadedFile();
717 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
725 /*** Functions for formatting warnings ***/
728 * Formats a result of UploadBase::getExistsWarning as HTML
729 * This check is static and can be done pre-upload via AJAX
731 * @param array $exists The result of UploadBase::getExistsWarning
732 * @return string Empty string if there is no warning or an HTML fragment
734 public static function getExistsWarning( $exists ) {
739 $file = $exists['file'];
740 $filename = $file->getTitle()->getPrefixedText();
743 if ( $exists['warning'] == 'exists' ) {
745 $warning = wfMessage( 'fileexists', $filename )->parse();
746 } elseif ( $exists['warning'] == 'page-exists' ) {
747 // Page exists but file does not
748 $warning = wfMessage( 'filepageexists', $filename )->parse();
749 } elseif ( $exists['warning'] == 'exists-normalized' ) {
750 $warning = wfMessage( 'fileexists-extension', $filename,
751 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
752 } elseif ( $exists['warning'] == 'thumb' ) {
753 // Swapped argument order compared with other messages for backwards compatibility
754 $warning = wfMessage( 'fileexists-thumbnail-yes',
755 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
756 } elseif ( $exists['warning'] == 'thumb-name' ) {
757 // Image w/o '180px-' does not exists, but we do not like these filenames
758 $name = $file->getName();
759 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
760 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
761 } elseif ( $exists['warning'] == 'bad-prefix' ) {
762 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
769 * Construct a warning and a gallery from an array of duplicate files.
770 * @param array $dupes
773 public function getDupeWarning( $dupes ) {
778 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
779 $gallery->setShowBytes( false );
780 foreach ( $dupes as $file ) {
781 $gallery->add( $file->getTitle() );
785 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
786 $gallery->toHTML() . "</li>\n";
789 protected function getGroupName() {
794 * Should we rotate images in the preview on Special:Upload.
796 * This controls js: mw.config.get( 'wgFileCanRotate' )
798 * @todo What about non-BitmapHandler handled files?
800 public static function rotationEnabled() {
801 $bitmapHandler = new BitmapHandler();
802 return $bitmapHandler->autoRotateEnabled();
807 * Sub class of HTMLForm that provides the form section of SpecialUpload
809 class UploadForm
extends HTMLForm
{
811 protected $mForReUpload;
812 protected $mSessionKey;
813 protected $mHideIgnoreWarning;
814 protected $mDestWarningAck;
815 protected $mDestFile;
819 protected $mTextAfterSummary;
821 protected $mSourceIds;
823 protected $mMaxFileSize = [];
825 protected $mMaxUploadSize = [];
827 public function __construct( array $options = [], IContextSource
$context = null ) {
828 if ( $context instanceof IContextSource
) {
829 $this->setContext( $context );
832 $this->mWatch
= !empty( $options['watch'] );
833 $this->mForReUpload
= !empty( $options['forreupload'] );
834 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
835 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
836 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
837 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
839 $this->mComment
= isset( $options['description'] ) ?
840 $options['description'] : '';
842 $this->mTextTop
= isset( $options['texttop'] )
843 ?
$options['texttop'] : '';
845 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
846 ?
$options['textaftersummary'] : '';
848 $sourceDescriptor = $this->getSourceSection();
849 $descriptor = $sourceDescriptor
850 +
$this->getDescriptionSection()
851 +
$this->getOptionsSection();
853 Hooks
::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
854 parent
::__construct( $descriptor, $context, 'upload' );
856 # Add a link to edit MediaWik:Licenses
857 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
858 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
859 $licensesLink = Linker
::linkKnown(
860 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
861 $this->msg( 'licenses-edit' )->escaped(),
863 [ 'action' => 'edit' ]
865 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
866 $this->addFooterText( $editLicenses, 'description' );
869 # Set some form properties
870 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
871 $this->setSubmitName( 'wpUpload' );
872 # Used message keys: 'accesskey-upload', 'tooltip-upload'
873 $this->setSubmitTooltip( 'upload' );
874 $this->setId( 'mw-upload-form' );
876 # Build a list of IDs for javascript insertion
877 $this->mSourceIds
= [];
878 foreach ( $sourceDescriptor as $field ) {
879 if ( !empty( $field['id'] ) ) {
880 $this->mSourceIds
[] = $field['id'];
886 * Get the descriptor of the fieldset that contains the file source
887 * selection. The section is 'source'
889 * @return array Descriptor array
891 protected function getSourceSection() {
892 if ( $this->mSessionKey
) {
896 'default' => $this->mSessionKey
,
900 'default' => 'Stash',
905 $canUploadByUrl = UploadFromUrl
::isEnabled()
906 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
907 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
908 $radio = $canUploadByUrl;
909 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
912 if ( $this->mTextTop
) {
913 $descriptor['UploadFormTextTop'] = [
915 'section' => 'source',
916 'default' => $this->mTextTop
,
921 $this->mMaxUploadSize
['file'] = min(
922 UploadBase
::getMaxUploadSize( 'file' ),
923 UploadBase
::getMaxPhpUploadSize()
926 $help = $this->msg( 'upload-maxfilesize',
927 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
930 // If the user can also upload by URL, there are 2 different file size limits.
931 // This extra message helps stress which limit corresponds to what.
932 if ( $canUploadByUrl ) {
933 $help .= $this->msg( 'word-separator' )->escaped();
934 $help .= $this->msg( 'upload_source_file' )->parse();
937 $descriptor['UploadFile'] = [
938 'class' => 'UploadSourceField',
939 'section' => 'source',
941 'id' => 'wpUploadFile',
942 'radio-id' => 'wpSourceTypeFile',
943 'label-message' => 'sourcefilename',
944 'upload-type' => 'File',
947 'checked' => $selectedSourceType == 'file',
950 if ( $canUploadByUrl ) {
951 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
952 $descriptor['UploadFileURL'] = [
953 'class' => 'UploadSourceField',
954 'section' => 'source',
955 'id' => 'wpUploadFileURL',
956 'radio-id' => 'wpSourceTypeurl',
957 'label-message' => 'sourceurl',
958 'upload-type' => 'url',
960 'help' => $this->msg( 'upload-maxfilesize',
961 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
963 $this->msg( 'word-separator' )->escaped() .
964 $this->msg( 'upload_source_url' )->parse(),
965 'checked' => $selectedSourceType == 'url',
968 Hooks
::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
970 $descriptor['Extensions'] = [
972 'section' => 'source',
973 'default' => $this->getExtensionsMessage(),
981 * Get the messages indicating which extensions are preferred and prohibitted.
983 * @return string HTML string containing the message
985 protected function getExtensionsMessage() {
986 # Print a list of allowed file extensions, if so configured. We ignore
987 # MIME type here, it's incomprehensible to most people and too long.
988 $config = $this->getConfig();
990 if ( $config->get( 'CheckFileExtensions' ) ) {
991 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
992 if ( $config->get( 'StrictFileExtensions' ) ) {
993 # Everything not permitted is banned
995 '<div id="mw-upload-permitted">' .
996 $this->msg( 'upload-permitted' )
997 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
998 ->numParams( count( $fileExtensions ) )
1002 # We have to list both preferred and prohibited
1003 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1005 '<div id="mw-upload-preferred">' .
1006 $this->msg( 'upload-preferred' )
1007 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1008 ->numParams( count( $fileExtensions ) )
1011 '<div id="mw-upload-prohibited">' .
1012 $this->msg( 'upload-prohibited' )
1013 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1014 ->numParams( count( $fileBlacklist ) )
1019 # Everything is permitted.
1020 $extensionsList = '';
1023 return $extensionsList;
1027 * Get the descriptor of the fieldset that contains the file description
1028 * input. The section is 'description'
1030 * @return array Descriptor array
1032 protected function getDescriptionSection() {
1033 $config = $this->getConfig();
1034 if ( $this->mSessionKey
) {
1035 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1037 $file = $stash->getFile( $this->mSessionKey
);
1038 } catch ( Exception
$e ) {
1044 $mto = $file->transform( [ 'width' => 120 ] );
1045 $this->addHeaderText(
1046 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1047 Html
::element( 'img', [
1048 'src' => $mto->getUrl(),
1049 'class' => 'thumbimage',
1050 ] ) . '</div>', 'description' );
1057 'section' => 'description',
1058 'id' => 'wpDestFile',
1059 'label-message' => 'destfilename',
1061 'default' => $this->mDestFile
,
1062 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1063 'nodata' => strval( $this->mDestFile
) !== '',
1065 'UploadDescription' => [
1066 'type' => 'textarea',
1067 'section' => 'description',
1068 'id' => 'wpUploadDescription',
1069 'label-message' => $this->mForReUpload
1070 ?
'filereuploadsummary'
1071 : 'fileuploadsummary',
1072 'default' => $this->mComment
,
1073 'cols' => $this->getUser()->getIntOption( 'cols' ),
1077 if ( $this->mTextAfterSummary
) {
1078 $descriptor['UploadFormTextAfterSummary'] = [
1080 'section' => 'description',
1081 'default' => $this->mTextAfterSummary
,
1088 'type' => 'edittools',
1089 'section' => 'description',
1090 'message' => 'edittools-upload',
1094 if ( $this->mForReUpload
) {
1095 $descriptor['DestFile']['readonly'] = true;
1097 $descriptor['License'] = [
1099 'class' => 'Licenses',
1100 'section' => 'description',
1101 'id' => 'wpLicense',
1102 'label-message' => 'license',
1106 if ( $config->get( 'UseCopyrightUpload' ) ) {
1107 $descriptor['UploadCopyStatus'] = [
1109 'section' => 'description',
1110 'id' => 'wpUploadCopyStatus',
1111 'label-message' => 'filestatus',
1113 $descriptor['UploadSource'] = [
1115 'section' => 'description',
1116 'id' => 'wpUploadSource',
1117 'label-message' => 'filesource',
1125 * Get the descriptor of the fieldset that contains the upload options,
1126 * such as "watch this file". The section is 'options'
1128 * @return array Descriptor array
1130 protected function getOptionsSection() {
1131 $user = $this->getUser();
1132 if ( $user->isLoggedIn() ) {
1136 'id' => 'wpWatchthis',
1137 'label-message' => 'watchthisupload',
1138 'section' => 'options',
1139 'default' => $this->mWatch
,
1143 if ( !$this->mHideIgnoreWarning
) {
1144 $descriptor['IgnoreWarning'] = [
1146 'id' => 'wpIgnoreWarning',
1147 'label-message' => 'ignorewarnings',
1148 'section' => 'options',
1152 $descriptor['DestFileWarningAck'] = [
1154 'id' => 'wpDestFileWarningAck',
1155 'default' => $this->mDestWarningAck ?
'1' : '',
1158 if ( $this->mForReUpload
) {
1159 $descriptor['ForReUpload'] = [
1161 'id' => 'wpForReUpload',
1170 * Add the upload JS and show the form.
1172 public function show() {
1173 $this->addUploadJS();
1178 * Add upload JS to the OutputPage
1180 protected function addUploadJS() {
1181 $config = $this->getConfig();
1183 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1184 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1185 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1186 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1189 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1190 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1191 'wgUploadAutoFill' => !$this->mForReUpload
&&
1192 // If we received mDestFile from the request, don't autofill
1193 // the wpDestFile textbox
1194 $this->mDestFile
=== '',
1195 'wgUploadSourceIds' => $this->mSourceIds
,
1196 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1197 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1198 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1199 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1200 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1201 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1204 $out = $this->getOutput();
1205 $out->addJsConfigVars( $scriptVars );
1208 'mediawiki.action.edit', // For <charinsert> support
1209 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1214 * Empty function; submission is handled elsewhere.
1216 * @return bool False
1218 function trySubmit() {
1224 * A form field that contains a radio box in the label
1226 class UploadSourceField
extends HTMLTextField
{
1229 * @param array $cellAttributes
1232 function getLabelHtml( $cellAttributes = [] ) {
1233 $id = $this->mParams
['id'];
1234 $label = Html
::rawElement( 'label', [ 'for' => $id ], $this->mLabel
);
1236 if ( !empty( $this->mParams
['radio'] ) ) {
1237 if ( isset( $this->mParams
['radio-id'] ) ) {
1238 $radioId = $this->mParams
['radio-id'];
1240 // Old way. For the benefit of extensions that do not define
1241 // the 'radio-id' key.
1242 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1246 'name' => 'wpSourceType',
1249 'value' => $this->mParams
['upload-type'],
1252 if ( !empty( $this->mParams
['checked'] ) ) {
1253 $attribs['checked'] = 'checked';
1256 $label .= Html
::element( 'input', $attribs );
1259 return Html
::rawElement( 'td', [ 'class' => 'mw-label' ] +
$cellAttributes, $label );
1265 function getSize() {
1266 return isset( $this->mParams
['size'] )
1267 ?
$this->mParams
['size']