5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
27 * Handles the page protection UI and backend
29 class ProtectionForm
{
30 /** @var array A map of action to restriction level, from request or default */
31 protected $mRestrictions = [];
33 /** @var string The custom/additional protection reason */
34 protected $mReason = '';
36 /** @var string The reason selected from the list, blank for other/additional */
37 protected $mReasonSelection = '';
39 /** @var bool True if the restrictions are cascading, from request or existing protection */
40 protected $mCascade = false;
42 /** @var array Map of action to "other" expiry time. Used in preference to mExpirySelection. */
43 protected $mExpiry = [];
46 * @var array Map of action to value selected in expiry drop-down list.
47 * Will be set to 'othertime' whenever mExpiry is set.
49 protected $mExpirySelection = [];
51 /** @var array Permissions errors for the protect action */
52 protected $mPermErrors = [];
54 /** @var array Types (i.e. actions) for which levels can be selected */
55 protected $mApplicableTypes = [];
57 /** @var array Map of action to the expiry time of the existing protection */
58 protected $mExistingExpiry = [];
60 /** @var IContextSource */
63 function __construct( Article
$article ) {
64 // Set instance variables.
65 $this->mArticle
= $article;
66 $this->mTitle
= $article->getTitle();
67 $this->mApplicableTypes
= $this->mTitle
->getRestrictionTypes();
68 $this->mContext
= $article->getContext();
70 // Check if the form should be disabled.
71 // If it is, the form will be available in read-only to show levels.
72 $this->mPermErrors
= $this->mTitle
->getUserPermissionsErrors(
74 $this->mContext
->getUser(),
75 $this->mContext
->getRequest()->wasPosted() ?
'secure' : 'full' // T92357
78 $this->mPermErrors
[] = [ 'readonlytext', wfReadOnlyReason() ];
80 $this->disabled
= $this->mPermErrors
!= [];
81 $this->disabledAttrib
= $this->disabled
82 ?
[ 'disabled' => 'disabled' ]
89 * Loads the current state of protection into the object.
92 $levels = MWNamespace
::getRestrictionLevels(
93 $this->mTitle
->getNamespace(), $this->mContext
->getUser()
95 $this->mCascade
= $this->mTitle
->areRestrictionsCascading();
97 $request = $this->mContext
->getRequest();
98 $this->mReason
= $request->getText( 'mwProtect-reason' );
99 $this->mReasonSelection
= $request->getText( 'wpProtectReasonSelection' );
100 $this->mCascade
= $request->getBool( 'mwProtect-cascade', $this->mCascade
);
102 foreach ( $this->mApplicableTypes
as $action ) {
103 // @todo FIXME: This form currently requires individual selections,
104 // but the db allows multiples separated by commas.
106 // Pull the actual restriction from the DB
107 $this->mRestrictions
[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
109 if ( !$this->mRestrictions
[$action] ) {
110 // No existing expiry
111 $existingExpiry = '';
113 $existingExpiry = $this->mTitle
->getRestrictionExpiry( $action );
115 $this->mExistingExpiry
[$action] = $existingExpiry;
117 $requestExpiry = $request->getText( "mwProtect-expiry-$action" );
118 $requestExpirySelection = $request->getVal( "wpProtectExpirySelection-$action" );
120 if ( $requestExpiry ) {
121 // Custom expiry takes precedence
122 $this->mExpiry
[$action] = $requestExpiry;
123 $this->mExpirySelection
[$action] = 'othertime';
124 } elseif ( $requestExpirySelection ) {
125 // Expiry selected from list
126 $this->mExpiry
[$action] = '';
127 $this->mExpirySelection
[$action] = $requestExpirySelection;
128 } elseif ( $existingExpiry ) {
129 // Use existing expiry in its own list item
130 $this->mExpiry
[$action] = '';
131 $this->mExpirySelection
[$action] = $existingExpiry;
133 // Catches 'infinity' - Existing expiry is infinite, use "infinite" in drop-down
134 // Final default: infinite
135 $this->mExpiry
[$action] = '';
136 $this->mExpirySelection
[$action] = 'infinite';
139 $val = $request->getVal( "mwProtect-level-$action" );
140 if ( isset( $val ) && in_array( $val, $levels ) ) {
141 $this->mRestrictions
[$action] = $val;
147 * Get the expiry time for a given action, by combining the relevant inputs.
149 * @param string $action
151 * @return string|false 14-char timestamp or "infinity", or false if the input was invalid
153 function getExpiry( $action ) {
154 if ( $this->mExpirySelection
[$action] == 'existing' ) {
155 return $this->mExistingExpiry
[$action];
156 } elseif ( $this->mExpirySelection
[$action] == 'othertime' ) {
157 $value = $this->mExpiry
[$action];
159 $value = $this->mExpirySelection
[$action];
161 if ( wfIsInfinity( $value ) ) {
164 $unix = strtotime( $value );
166 if ( !$unix ||
$unix === -1 ) {
170 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
171 // and there isn't notice about it in the ui
172 $time = wfTimestamp( TS_MW
, $unix );
178 * Main entry point for action=protect and action=unprotect
181 if ( MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace() ) === [ '' ] ) {
182 throw new ErrorPageError( 'protect-badnamespace-title', 'protect-badnamespace-text' );
185 $out = $this->mContext
->getOutput();
186 if ( !wfMessage( 'protect-dropdown' )->inContentLanguage()->isDisabled() ) {
187 $out->addModules( 'mediawiki.reasonSuggest' );
188 $out->addJsConfigVars( [
189 'reasons' => 'protect-dropdown'
193 if ( $this->mContext
->getRequest()->wasPosted() ) {
194 if ( $this->save() ) {
195 $q = $this->mArticle
->isRedirect() ?
'redirect=no' : '';
196 $out->redirect( $this->mTitle
->getFullURL( $q ) );
204 * Show the input form with optional error message
206 * @param string $err Error message or null if there's no error
208 function show( $err = null ) {
209 $out = $this->mContext
->getOutput();
210 $out->setRobotPolicy( 'noindex,nofollow' );
211 $out->addBacklinkSubtitle( $this->mTitle
);
213 if ( is_array( $err ) ) {
214 $out->wrapWikiMsg( "<p class='error'>\n$1\n</p>\n", $err );
215 } elseif ( is_string( $err ) ) {
216 $out->addHTML( "<p class='error'>{$err}</p>\n" );
219 if ( $this->mTitle
->getRestrictionTypes() === [] ) {
220 // No restriction types available for the current title
221 // this might happen if an extension alters the available types
222 $out->setPageTitle( $this->mContext
->msg(
223 'protect-norestrictiontypes-title',
224 $this->mTitle
->getPrefixedText()
226 $out->addWikiText( $this->mContext
->msg( 'protect-norestrictiontypes-text' )->plain() );
228 // Show the log in case protection was possible once
229 $this->showLogExtract( $out );
230 // return as there isn't anything else we can do
234 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle
->getCascadeProtectionSources();
235 if ( $cascadeSources && count( $cascadeSources ) > 0 ) {
238 foreach ( $cascadeSources as $title ) {
239 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
242 /** @todo FIXME: i18n issue, should use formatted number. */
244 "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>",
245 [ 'protect-cascadeon', count( $cascadeSources ) ]
249 # Show an appropriate message if the user isn't allowed or able to change
250 # the protection settings at this time
251 if ( $this->disabled
) {
253 $this->mContext
->msg( 'protect-title-notallowed',
254 $this->mTitle
->getPrefixedText() )
256 $out->addWikiText( $out->formatPermissionsErrorMessage( $this->mPermErrors
, 'protect' ) );
258 $out->setPageTitle( $this->mContext
->msg( 'protect-title', $this->mTitle
->getPrefixedText() ) );
259 $out->addWikiMsg( 'protect-text',
260 wfEscapeWikiText( $this->mTitle
->getPrefixedText() ) );
263 $out->addHTML( $this->buildForm() );
264 $this->showLogExtract( $out );
268 * Save submitted protection form
270 * @return bool Success
274 if ( $this->disabled
) {
279 $request = $this->mContext
->getRequest();
280 $user = $this->mContext
->getUser();
281 $out = $this->mContext
->getOutput();
282 $token = $request->getVal( 'wpEditToken' );
283 if ( !$user->matchEditToken( $token, [ 'protect', $this->mTitle
->getPrefixedDBkey() ] ) ) {
284 $this->show( [ 'sessionfailure' ] );
288 # Create reason string. Use list and/or custom string.
289 $reasonstr = $this->mReasonSelection
;
290 if ( $reasonstr != 'other' && $this->mReason
!= '' ) {
291 // Entry from drop down menu + additional comment
292 $reasonstr .= $this->mContext
->msg( 'colon-separator' )->text() . $this->mReason
;
293 } elseif ( $reasonstr == 'other' ) {
294 $reasonstr = $this->mReason
;
297 foreach ( $this->mApplicableTypes
as $action ) {
298 $expiry[$action] = $this->getExpiry( $action );
299 if ( empty( $this->mRestrictions
[$action] ) ) {
300 continue; // unprotected
302 if ( !$expiry[$action] ) {
303 $this->show( [ 'protect_expiry_invalid' ] );
306 if ( $expiry[$action] < wfTimestampNow() ) {
307 $this->show( [ 'protect_expiry_old' ] );
312 $this->mCascade
= $request->getBool( 'mwProtect-cascade' );
314 $status = $this->mArticle
->doUpdateRestrictions(
315 $this->mRestrictions
,
322 if ( !$status->isOK() ) {
323 $this->show( $out->parseInline( $status->getWikiText() ) );
328 * Give extensions a change to handle added form items
330 * @since 1.19 you can (and you should) return false to abort saving;
331 * you can also return an array of message name and its parameters
334 if ( !Hooks
::run( 'ProtectionForm::save', [ $this->mArticle
, &$errorMsg, $reasonstr ] ) ) {
335 if ( $errorMsg == '' ) {
336 $errorMsg = [ 'hookaborted' ];
339 if ( $errorMsg != '' ) {
340 $this->show( $errorMsg );
344 WatchAction
::doWatchOrUnwatch( $request->getCheck( 'mwProtectWatch' ), $this->mTitle
, $user );
350 * Build the input form
352 * @return string HTML form
354 function buildForm() {
355 $context = $this->mContext
;
356 $user = $context->getUser();
357 $output = $context->getOutput();
358 $lang = $context->getLanguage();
359 $cascadingRestrictionLevels = $context->getConfig()->get( 'CascadingRestrictionLevels' );
361 if ( !$this->disabled
) {
362 $output->addModules( 'mediawiki.legacy.protect' );
363 $output->addJsConfigVars( 'wgCascadeableLevels', $cascadingRestrictionLevels );
364 $out .= Xml
::openElement( 'form', [ 'method' => 'post',
365 'action' => $this->mTitle
->getLocalURL( 'action=protect' ),
366 'id' => 'mw-Protect-Form' ] );
369 $out .= Xml
::openElement( 'fieldset' ) .
370 Xml
::element( 'legend', null, $context->msg( 'protect-legend' )->text() ) .
371 Xml
::openElement( 'table', [ 'id' => 'mwProtectSet' ] ) .
372 Xml
::openElement( 'tbody' );
374 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
375 $showProtectOptions = $scExpiryOptions !== '-' && !$this->disabled
;
377 // Not all languages have V_x <-> N_x relation
378 foreach ( $this->mRestrictions
as $action => $selected ) {
380 // restriction-edit, restriction-move, restriction-create, restriction-upload
381 $msg = $context->msg( 'restriction-' . $action );
383 Xml
::openElement( 'fieldset' ) .
384 Xml
::element( 'legend', null, $msg->exists() ?
$msg->text() : $action ) .
385 Xml
::openElement( 'table', [ 'id' => "mw-protect-table-$action" ] ) .
386 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
388 $mProtectexpiry = Xml
::label(
389 $context->msg( 'protectexpiry' )->text(),
390 "mwProtectExpirySelection-$action"
392 $mProtectother = Xml
::label(
393 $context->msg( 'protect-othertime' )->text(),
394 "mwProtect-$action-expires"
397 $expiryFormOptions = new XmlSelect(
398 "wpProtectExpirySelection-$action",
399 "mwProtectExpirySelection-$action",
400 $this->mExpirySelection
[$action]
402 $expiryFormOptions->setAttribute( 'tabindex', '2' );
403 if ( $this->disabled
) {
404 $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
407 if ( $this->mExistingExpiry
[$action] ) {
408 if ( $this->mExistingExpiry
[$action] == 'infinity' ) {
409 $existingExpiryMessage = $context->msg( 'protect-existing-expiry-infinity' );
411 $timestamp = $lang->userTimeAndDate( $this->mExistingExpiry
[$action], $user );
412 $d = $lang->userDate( $this->mExistingExpiry
[$action], $user );
413 $t = $lang->userTime( $this->mExistingExpiry
[$action], $user );
414 $existingExpiryMessage = $context->msg(
415 'protect-existing-expiry',
421 $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
424 $expiryFormOptions->addOption(
425 $context->msg( 'protect-othertime-op' )->text(),
428 foreach ( explode( ',', $scExpiryOptions ) as $option ) {
429 if ( strpos( $option, ":" ) === false ) {
430 $show = $value = $option;
432 list( $show, $value ) = explode( ":", $option );
434 $expiryFormOptions->addOption( $show, htmlspecialchars( $value ) );
436 # Add expiry dropdown
437 if ( $showProtectOptions && !$this->disabled
) {
440 <td class='mw-label'>
443 <td class='mw-input'>" .
444 $expiryFormOptions->getHTML() .
448 # Add custom expiry field
449 $attribs = [ 'id' => "mwProtect-$action-expires" ] +
$this->disabledAttrib
;
451 <td class='mw-label'>" .
454 <td class="mw-input">' .
455 Xml
::input( "mwProtect-expiry-$action", 50, $this->mExpiry
[$action], $attribs ) .
458 $out .= "</td></tr>" .
459 Xml
::closeElement( 'table' ) .
460 Xml
::closeElement( 'fieldset' ) .
463 # Give extensions a chance to add items to the form
464 Hooks
::run( 'ProtectionForm::buildForm', [ $this->mArticle
, &$out ] );
466 $out .= Xml
::closeElement( 'tbody' ) . Xml
::closeElement( 'table' );
468 // JavaScript will add another row with a value-chaining checkbox
469 if ( $this->mTitle
->exists() ) {
470 $out .= Xml
::openElement( 'table', [ 'id' => 'mw-protect-table2' ] ) .
471 Xml
::openElement( 'tbody' );
474 <td class="mw-input">' .
476 $context->msg( 'protect-cascade' )->text(),
479 $this->mCascade
, $this->disabledAttrib
483 $out .= Xml
::closeElement( 'tbody' ) . Xml
::closeElement( 'table' );
486 # Add manual and custom reason field/selects as well as submit
487 if ( !$this->disabled
) {
488 $mProtectreasonother = Xml
::label(
489 $context->msg( 'protectcomment' )->text(),
490 'wpProtectReasonSelection'
493 $mProtectreason = Xml
::label(
494 $context->msg( 'protect-otherreason' )->text(),
498 $reasonDropDown = Xml
::listDropDown( 'wpProtectReasonSelection',
499 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
500 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
501 $this->mReasonSelection
,
502 'mwProtect-reason', 4 );
504 $out .= Xml
::openElement( 'table', [ 'id' => 'mw-protect-table3' ] ) .
505 Xml
::openElement( 'tbody' );
508 <td class='mw-label'>
509 {$mProtectreasonother}
511 <td class='mw-input'>
516 <td class='mw-label'>
519 <td class='mw-input'>" .
520 Xml
::input( 'mwProtect-reason', 60, $this->mReason
, [ 'type' => 'text',
521 'id' => 'mwProtect-reason', 'maxlength' => 180 ] ) .
522 // Limited maxlength as the database trims at 255 bytes and other texts
523 // chosen by dropdown menus on this page are also included in this database field.
524 // The byte limit of 180 bytes is enforced in javascript
527 # Disallow watching is user is not logged in
528 if ( $user->isLoggedIn() ) {
532 <td class='mw-input'>" .
533 Xml
::checkLabel( $context->msg( 'watchthis' )->text(),
534 'mwProtectWatch', 'mwProtectWatch',
535 $user->isWatched( $this->mTitle
) ||
$user->getOption( 'watchdefault' ) ) .
542 <td class='mw-submit'>" .
544 $context->msg( 'confirm' )->text(),
545 [ 'id' => 'mw-Protect-submit' ]
549 $out .= Xml
::closeElement( 'tbody' ) . Xml
::closeElement( 'table' );
551 $out .= Xml
::closeElement( 'fieldset' );
553 if ( $user->isAllowed( 'editinterface' ) ) {
554 $link = Linker
::linkKnown(
555 $context->msg( 'protect-dropdown' )->inContentLanguage()->getTitle(),
556 $context->msg( 'protect-edit-reasonlist' )->escaped(),
558 [ 'action' => 'edit' ]
560 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
563 if ( !$this->disabled
) {
564 $out .= Html
::hidden(
566 $user->getEditToken( [ 'protect', $this->mTitle
->getPrefixedDBkey() ] )
568 $out .= Xml
::closeElement( 'form' );
575 * Build protection level selector
577 * @param string $action Action to protect
578 * @param string $selected Current protection level
579 * @return string HTML fragment
581 function buildSelector( $action, $selected ) {
582 // If the form is disabled, display all relevant levels. Otherwise,
583 // just show the ones this user can use.
584 $levels = MWNamespace
::getRestrictionLevels( $this->mTitle
->getNamespace(),
585 $this->disabled ?
null : $this->mContext
->getUser()
588 $id = 'mwProtect-level-' . $action;
590 $select = new XmlSelect( $id, $id, $selected );
591 $select->setAttribute( 'size', count( $levels ) );
592 if ( $this->disabled
) {
593 $select->setAttribute( 'disabled', 'disabled' );
596 foreach ( $levels as $key ) {
597 $select->addOption( $this->getOptionLabel( $key ), $key );
600 return $select->getHTML();
604 * Prepare the label for a protection selector option
606 * @param string $permission Permission required
609 private function getOptionLabel( $permission ) {
610 if ( $permission == '' ) {
611 return $this->mContext
->msg( 'protect-default' )->text();
613 // Messages: protect-level-autoconfirmed, protect-level-sysop
614 $msg = $this->mContext
->msg( "protect-level-{$permission}" );
615 if ( $msg->exists() ) {
618 return $this->mContext
->msg( 'protect-fallback', $permission )->text();
623 * Show protection long extracts for this page
625 * @param OutputPage $out
628 function showLogExtract( &$out ) {
629 # Show relevant lines from the protection log:
630 $protectLogPage = new LogPage( 'protect' );
631 $out->addHTML( Xml
::element( 'h2', null, $protectLogPage->getName()->text() ) );
632 LogEventsList
::showLogExtract( $out, 'protect', $this->mTitle
);
633 # Let extensions add other relevant log extracts
634 Hooks
::run( 'ProtectionForm::showLogExtract', [ $this->mArticle
, $out ] );