Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / ProtectionForm.php
blobbcf4dda98ade783c1a1d24bfa58dbf636c8af57e
1 <?php
2 /**
3 * Page protection
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
23 * @file
26 /**
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 = [];
45 /**
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 */
61 private $mContext;
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(
73 'protect',
74 $this->mContext->getUser(),
75 $this->mContext->getRequest()->wasPosted() ? 'secure' : 'full' // T92357
77 if ( wfReadOnly() ) {
78 $this->mPermErrors[] = [ 'readonlytext', wfReadOnlyReason() ];
80 $this->disabled = $this->mPermErrors != [];
81 $this->disabledAttrib = $this->disabled
82 ? [ 'disabled' => 'disabled' ]
83 : [];
85 $this->loadData();
88 /**
89 * Loads the current state of protection into the object.
91 function loadData() {
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 = '';
112 } else {
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;
132 } else {
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];
158 } else {
159 $value = $this->mExpirySelection[$action];
161 if ( wfIsInfinity( $value ) ) {
162 $time = 'infinity';
163 } else {
164 $unix = strtotime( $value );
166 if ( !$unix || $unix === -1 ) {
167 return false;
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 );
174 return $time;
178 * Main entry point for action=protect and action=unprotect
180 function execute() {
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 $reasonsList = Xml::getArrayFromWikiTextList(
188 wfMessage( 'protect-dropdown' )->inContentLanguage()->text()
190 $out->addModules( 'mediawiki.reasonSuggest' );
191 $out->addJsConfigVars( [
192 'reasons' => $reasonsList
193 ] );
196 if ( $this->mContext->getRequest()->wasPosted() ) {
197 if ( $this->save() ) {
198 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
199 $out->redirect( $this->mTitle->getFullURL( $q ) );
201 } else {
202 $this->show();
207 * Show the input form with optional error message
209 * @param string $err Error message or null if there's no error
211 function show( $err = null ) {
212 $out = $this->mContext->getOutput();
213 $out->setRobotPolicy( 'noindex,nofollow' );
214 $out->addBacklinkSubtitle( $this->mTitle );
216 if ( is_array( $err ) ) {
217 $out->wrapWikiMsg( "<p class='error'>\n$1\n</p>\n", $err );
218 } elseif ( is_string( $err ) ) {
219 $out->addHTML( "<p class='error'>{$err}</p>\n" );
222 if ( $this->mTitle->getRestrictionTypes() === [] ) {
223 // No restriction types available for the current title
224 // this might happen if an extension alters the available types
225 $out->setPageTitle( $this->mContext->msg(
226 'protect-norestrictiontypes-title',
227 $this->mTitle->getPrefixedText()
228 ) );
229 $out->addWikiText( $this->mContext->msg( 'protect-norestrictiontypes-text' )->plain() );
231 // Show the log in case protection was possible once
232 $this->showLogExtract( $out );
233 // return as there isn't anything else we can do
234 return;
237 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
238 if ( $cascadeSources && count( $cascadeSources ) > 0 ) {
239 $titles = '';
241 foreach ( $cascadeSources as $title ) {
242 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
245 /** @todo FIXME: i18n issue, should use formatted number. */
246 $out->wrapWikiMsg(
247 "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>",
248 [ 'protect-cascadeon', count( $cascadeSources ) ]
252 # Show an appropriate message if the user isn't allowed or able to change
253 # the protection settings at this time
254 if ( $this->disabled ) {
255 $out->setPageTitle(
256 $this->mContext->msg( 'protect-title-notallowed',
257 $this->mTitle->getPrefixedText() )
259 $out->addWikiText( $out->formatPermissionsErrorMessage( $this->mPermErrors, 'protect' ) );
260 } else {
261 $out->setPageTitle( $this->mContext->msg( 'protect-title', $this->mTitle->getPrefixedText() ) );
262 $out->addWikiMsg( 'protect-text',
263 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
266 $out->addHTML( $this->buildForm() );
267 $this->showLogExtract( $out );
271 * Save submitted protection form
273 * @return bool Success
275 function save() {
276 # Permission check!
277 if ( $this->disabled ) {
278 $this->show();
279 return false;
282 $request = $this->mContext->getRequest();
283 $user = $this->mContext->getUser();
284 $out = $this->mContext->getOutput();
285 $token = $request->getVal( 'wpEditToken' );
286 if ( !$user->matchEditToken( $token, [ 'protect', $this->mTitle->getPrefixedDBkey() ] ) ) {
287 $this->show( [ 'sessionfailure' ] );
288 return false;
291 # Create reason string. Use list and/or custom string.
292 $reasonstr = $this->mReasonSelection;
293 if ( $reasonstr != 'other' && $this->mReason != '' ) {
294 // Entry from drop down menu + additional comment
295 $reasonstr .= $this->mContext->msg( 'colon-separator' )->text() . $this->mReason;
296 } elseif ( $reasonstr == 'other' ) {
297 $reasonstr = $this->mReason;
299 $expiry = [];
300 foreach ( $this->mApplicableTypes as $action ) {
301 $expiry[$action] = $this->getExpiry( $action );
302 if ( empty( $this->mRestrictions[$action] ) ) {
303 continue; // unprotected
305 if ( !$expiry[$action] ) {
306 $this->show( [ 'protect_expiry_invalid' ] );
307 return false;
309 if ( $expiry[$action] < wfTimestampNow() ) {
310 $this->show( [ 'protect_expiry_old' ] );
311 return false;
315 $this->mCascade = $request->getBool( 'mwProtect-cascade' );
317 $status = $this->mArticle->doUpdateRestrictions(
318 $this->mRestrictions,
319 $expiry,
320 $this->mCascade,
321 $reasonstr,
322 $user
325 if ( !$status->isOK() ) {
326 $this->show( $out->parseInline( $status->getWikiText() ) );
327 return false;
331 * Give extensions a change to handle added form items
333 * @since 1.19 you can (and you should) return false to abort saving;
334 * you can also return an array of message name and its parameters
336 $errorMsg = '';
337 if ( !Hooks::run( 'ProtectionForm::save', [ $this->mArticle, &$errorMsg, $reasonstr ] ) ) {
338 if ( $errorMsg == '' ) {
339 $errorMsg = [ 'hookaborted' ];
342 if ( $errorMsg != '' ) {
343 $this->show( $errorMsg );
344 return false;
347 WatchAction::doWatchOrUnwatch( $request->getCheck( 'mwProtectWatch' ), $this->mTitle, $user );
349 return true;
353 * Build the input form
355 * @return string HTML form
357 function buildForm() {
358 $context = $this->mContext;
359 $user = $context->getUser();
360 $output = $context->getOutput();
361 $lang = $context->getLanguage();
362 $cascadingRestrictionLevels = $context->getConfig()->get( 'CascadingRestrictionLevels' );
363 $out = '';
364 if ( !$this->disabled ) {
365 $output->addModules( 'mediawiki.legacy.protect' );
366 $output->addJsConfigVars( 'wgCascadeableLevels', $cascadingRestrictionLevels );
367 $out .= Xml::openElement( 'form', [ 'method' => 'post',
368 'action' => $this->mTitle->getLocalURL( 'action=protect' ),
369 'id' => 'mw-Protect-Form' ] );
372 $out .= Xml::openElement( 'fieldset' ) .
373 Xml::element( 'legend', null, $context->msg( 'protect-legend' )->text() ) .
374 Xml::openElement( 'table', [ 'id' => 'mwProtectSet' ] ) .
375 Xml::openElement( 'tbody' );
377 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
378 $showProtectOptions = $scExpiryOptions !== '-' && !$this->disabled;
380 // Not all languages have V_x <-> N_x relation
381 foreach ( $this->mRestrictions as $action => $selected ) {
382 // Messages:
383 // restriction-edit, restriction-move, restriction-create, restriction-upload
384 $msg = $context->msg( 'restriction-' . $action );
385 $out .= "<tr><td>" .
386 Xml::openElement( 'fieldset' ) .
387 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
388 Xml::openElement( 'table', [ 'id' => "mw-protect-table-$action" ] ) .
389 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
391 $mProtectexpiry = Xml::label(
392 $context->msg( 'protectexpiry' )->text(),
393 "mwProtectExpirySelection-$action"
395 $mProtectother = Xml::label(
396 $context->msg( 'protect-othertime' )->text(),
397 "mwProtect-$action-expires"
400 $expiryFormOptions = new XmlSelect(
401 "wpProtectExpirySelection-$action",
402 "mwProtectExpirySelection-$action",
403 $this->mExpirySelection[$action]
405 $expiryFormOptions->setAttribute( 'tabindex', '2' );
406 if ( $this->disabled ) {
407 $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
410 if ( $this->mExistingExpiry[$action] ) {
411 if ( $this->mExistingExpiry[$action] == 'infinity' ) {
412 $existingExpiryMessage = $context->msg( 'protect-existing-expiry-infinity' );
413 } else {
414 $timestamp = $lang->userTimeAndDate( $this->mExistingExpiry[$action], $user );
415 $d = $lang->userDate( $this->mExistingExpiry[$action], $user );
416 $t = $lang->userTime( $this->mExistingExpiry[$action], $user );
417 $existingExpiryMessage = $context->msg(
418 'protect-existing-expiry',
419 $timestamp,
424 $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
427 $expiryFormOptions->addOption(
428 $context->msg( 'protect-othertime-op' )->text(),
429 'othertime'
431 foreach ( explode( ',', $scExpiryOptions ) as $option ) {
432 if ( strpos( $option, ":" ) === false ) {
433 $show = $value = $option;
434 } else {
435 list( $show, $value ) = explode( ":", $option );
437 $expiryFormOptions->addOption( $show, htmlspecialchars( $value ) );
439 # Add expiry dropdown
440 if ( $showProtectOptions && !$this->disabled ) {
441 $out .= "
442 <table><tr>
443 <td class='mw-label'>
444 {$mProtectexpiry}
445 </td>
446 <td class='mw-input'>" .
447 $expiryFormOptions->getHTML() .
448 "</td>
449 </tr></table>";
451 # Add custom expiry field
452 $attribs = [ 'id' => "mwProtect-$action-expires" ] + $this->disabledAttrib;
453 $out .= "<table><tr>
454 <td class='mw-label'>" .
455 $mProtectother .
456 '</td>
457 <td class="mw-input">' .
458 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
459 '</td>
460 </tr></table>';
461 $out .= "</td></tr>" .
462 Xml::closeElement( 'table' ) .
463 Xml::closeElement( 'fieldset' ) .
464 "</td></tr>";
466 # Give extensions a chance to add items to the form
467 Hooks::run( 'ProtectionForm::buildForm', [ $this->mArticle, &$out ] );
469 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
471 // JavaScript will add another row with a value-chaining checkbox
472 if ( $this->mTitle->exists() ) {
473 $out .= Xml::openElement( 'table', [ 'id' => 'mw-protect-table2' ] ) .
474 Xml::openElement( 'tbody' );
475 $out .= '<tr>
476 <td></td>
477 <td class="mw-input">' .
478 Xml::checkLabel(
479 $context->msg( 'protect-cascade' )->text(),
480 'mwProtect-cascade',
481 'mwProtect-cascade',
482 $this->mCascade, $this->disabledAttrib
484 "</td>
485 </tr>\n";
486 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
489 # Add manual and custom reason field/selects as well as submit
490 if ( !$this->disabled ) {
491 $mProtectreasonother = Xml::label(
492 $context->msg( 'protectcomment' )->text(),
493 'wpProtectReasonSelection'
496 $mProtectreason = Xml::label(
497 $context->msg( 'protect-otherreason' )->text(),
498 'mwProtect-reason'
501 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
502 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
503 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
504 $this->mReasonSelection,
505 'mwProtect-reason', 4 );
507 $out .= Xml::openElement( 'table', [ 'id' => 'mw-protect-table3' ] ) .
508 Xml::openElement( 'tbody' );
509 $out .= "
510 <tr>
511 <td class='mw-label'>
512 {$mProtectreasonother}
513 </td>
514 <td class='mw-input'>
515 {$reasonDropDown}
516 </td>
517 </tr>
518 <tr>
519 <td class='mw-label'>
520 {$mProtectreason}
521 </td>
522 <td class='mw-input'>" .
523 Xml::input( 'mwProtect-reason', 60, $this->mReason, [ 'type' => 'text',
524 'id' => 'mwProtect-reason', 'maxlength' => 180 ] ) .
525 // Limited maxlength as the database trims at 255 bytes and other texts
526 // chosen by dropdown menus on this page are also included in this database field.
527 // The byte limit of 180 bytes is enforced in javascript
528 "</td>
529 </tr>";
530 # Disallow watching is user is not logged in
531 if ( $user->isLoggedIn() ) {
532 $out .= "
533 <tr>
534 <td></td>
535 <td class='mw-input'>" .
536 Xml::checkLabel( $context->msg( 'watchthis' )->text(),
537 'mwProtectWatch', 'mwProtectWatch',
538 $user->isWatched( $this->mTitle ) || $user->getOption( 'watchdefault' ) ) .
539 "</td>
540 </tr>";
542 $out .= "
543 <tr>
544 <td></td>
545 <td class='mw-submit'>" .
546 Xml::submitButton(
547 $context->msg( 'confirm' )->text(),
548 [ 'id' => 'mw-Protect-submit' ]
550 "</td>
551 </tr>\n";
552 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
554 $out .= Xml::closeElement( 'fieldset' );
556 if ( $user->isAllowed( 'editinterface' ) ) {
557 $link = Linker::linkKnown(
558 $context->msg( 'protect-dropdown' )->inContentLanguage()->getTitle(),
559 $context->msg( 'protect-edit-reasonlist' )->escaped(),
561 [ 'action' => 'edit' ]
563 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
566 if ( !$this->disabled ) {
567 $out .= Html::hidden(
568 'wpEditToken',
569 $user->getEditToken( [ 'protect', $this->mTitle->getPrefixedDBkey() ] )
571 $out .= Xml::closeElement( 'form' );
574 return $out;
578 * Build protection level selector
580 * @param string $action Action to protect
581 * @param string $selected Current protection level
582 * @return string HTML fragment
584 function buildSelector( $action, $selected ) {
585 // If the form is disabled, display all relevant levels. Otherwise,
586 // just show the ones this user can use.
587 $levels = MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace(),
588 $this->disabled ? null : $this->mContext->getUser()
591 $id = 'mwProtect-level-' . $action;
593 $select = new XmlSelect( $id, $id, $selected );
594 $select->setAttribute( 'size', count( $levels ) );
595 if ( $this->disabled ) {
596 $select->setAttribute( 'disabled', 'disabled' );
599 foreach ( $levels as $key ) {
600 $select->addOption( $this->getOptionLabel( $key ), $key );
603 return $select->getHTML();
607 * Prepare the label for a protection selector option
609 * @param string $permission Permission required
610 * @return string
612 private function getOptionLabel( $permission ) {
613 if ( $permission == '' ) {
614 return $this->mContext->msg( 'protect-default' )->text();
615 } else {
616 // Messages: protect-level-autoconfirmed, protect-level-sysop
617 $msg = $this->mContext->msg( "protect-level-{$permission}" );
618 if ( $msg->exists() ) {
619 return $msg->text();
621 return $this->mContext->msg( 'protect-fallback', $permission )->text();
626 * Show protection long extracts for this page
628 * @param OutputPage $out
629 * @access private
631 function showLogExtract( &$out ) {
632 # Show relevant lines from the protection log:
633 $protectLogPage = new LogPage( 'protect' );
634 $out->addHTML( Xml::element( 'h2', null, $protectLogPage->getName()->text() ) );
635 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle );
636 # Let extensions add other relevant log extracts
637 Hooks::run( 'ProtectionForm::showLogExtract', [ $this->mArticle, $out ] );