Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / ProtectionForm.php
blobde5e9db8e71f31c8d9d279fa3f5c3ffde425e5ad
1 <?php
2 /**
3 * Page protection
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * http://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 /** A map of action to restriction level, from request or default */
31 var $mRestrictions = array();
33 /** The custom/additional protection reason */
34 var $mReason = '';
36 /** The reason selected from the list, blank for other/additional */
37 var $mReasonSelection = '';
39 /** True if the restrictions are cascading, from request or existing protection */
40 var $mCascade = false;
42 /** Map of action to "other" expiry time. Used in preference to mExpirySelection. */
43 var $mExpiry = array();
45 /**
46 * Map of action to value selected in expiry drop-down list.
47 * Will be set to 'othertime' whenever mExpiry is set.
49 var $mExpirySelection = array();
51 /** Permissions errors for the protect action */
52 var $mPermErrors = array();
54 /** Types (i.e. actions) for which levels can be selected */
55 var $mApplicableTypes = array();
57 /** Map of action to the expiry time of the existing protection */
58 var $mExistingExpiry = array();
60 function __construct( Page $article ) {
61 global $wgUser;
62 // Set instance variables.
63 $this->mArticle = $article;
64 $this->mTitle = $article->getTitle();
65 $this->mApplicableTypes = $this->mTitle->getRestrictionTypes();
67 // Check if the form should be disabled.
68 // If it is, the form will be available in read-only to show levels.
69 $this->mPermErrors = $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser );
70 if ( wfReadOnly() ) {
71 $this->mPermErrors[] = array( 'readonlytext', wfReadOnlyReason() );
73 $this->disabled = $this->mPermErrors != array();
74 $this->disabledAttrib = $this->disabled
75 ? array( 'disabled' => 'disabled' )
76 : array();
78 $this->loadData();
81 /**
82 * Loads the current state of protection into the object.
84 function loadData() {
85 global $wgRequest, $wgUser;
86 global $wgRestrictionLevels;
88 $this->mCascade = $this->mTitle->areRestrictionsCascading();
90 $this->mReason = $wgRequest->getText( 'mwProtect-reason' );
91 $this->mReasonSelection = $wgRequest->getText( 'wpProtectReasonSelection' );
92 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade', $this->mCascade );
94 foreach( $this->mApplicableTypes as $action ) {
95 // @todo FIXME: This form currently requires individual selections,
96 // but the db allows multiples separated by commas.
98 // Pull the actual restriction from the DB
99 $this->mRestrictions[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
101 if ( !$this->mRestrictions[$action] ) {
102 // No existing expiry
103 $existingExpiry = '';
104 } else {
105 $existingExpiry = $this->mTitle->getRestrictionExpiry( $action );
107 $this->mExistingExpiry[$action] = $existingExpiry;
109 $requestExpiry = $wgRequest->getText( "mwProtect-expiry-$action" );
110 $requestExpirySelection = $wgRequest->getVal( "wpProtectExpirySelection-$action" );
112 if ( $requestExpiry ) {
113 // Custom expiry takes precedence
114 $this->mExpiry[$action] = $requestExpiry;
115 $this->mExpirySelection[$action] = 'othertime';
116 } elseif ( $requestExpirySelection ) {
117 // Expiry selected from list
118 $this->mExpiry[$action] = '';
119 $this->mExpirySelection[$action] = $requestExpirySelection;
120 } elseif ( $existingExpiry == 'infinity' ) {
121 // Existing expiry is infinite, use "infinite" in drop-down
122 $this->mExpiry[$action] = '';
123 $this->mExpirySelection[$action] = 'infinite';
124 } elseif ( $existingExpiry ) {
125 // Use existing expiry in its own list item
126 $this->mExpiry[$action] = '';
127 $this->mExpirySelection[$action] = $existingExpiry;
128 } else {
129 // Final default: infinite
130 $this->mExpiry[$action] = '';
131 $this->mExpirySelection[$action] = 'infinite';
134 $val = $wgRequest->getVal( "mwProtect-level-$action" );
135 if( isset( $val ) && in_array( $val, $wgRestrictionLevels ) ) {
136 // Prevent users from setting levels that they cannot later unset
137 if( $val == 'sysop' ) {
138 // Special case, rewrite sysop to either protect and editprotected
139 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) )
140 continue;
141 } else {
142 if( !$wgUser->isAllowed( $val ) )
143 continue;
145 $this->mRestrictions[$action] = $val;
151 * Get the expiry time for a given action, by combining the relevant inputs.
153 * @param $action string
155 * @return string 14-char timestamp or "infinity", or false if the input was invalid
157 function getExpiry( $action ) {
158 if ( $this->mExpirySelection[$action] == 'existing' ) {
159 return $this->mExistingExpiry[$action];
160 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
161 $value = $this->mExpiry[$action];
162 } else {
163 $value = $this->mExpirySelection[$action];
165 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
166 $time = wfGetDB( DB_SLAVE )->getInfinity();
167 } else {
168 $unix = strtotime( $value );
170 if ( !$unix || $unix === -1 ) {
171 return false;
174 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
175 // and there isn't notice about it in the ui
176 $time = wfTimestamp( TS_MW, $unix );
178 return $time;
182 * Main entry point for action=protect and action=unprotect
184 function execute() {
185 global $wgRequest, $wgOut;
187 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
188 throw new ErrorPageError( 'protect-badnamespace-title', 'protect-badnamespace-text' );
191 if( $wgRequest->wasPosted() ) {
192 if( $this->save() ) {
193 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
194 $wgOut->redirect( $this->mTitle->getFullURL( $q ) );
196 } else {
197 $this->show();
202 * Show the input form with optional error message
204 * @param string $err error message or null if there's no error
206 function show( $err = null ) {
207 global $wgOut;
209 $wgOut->setRobotPolicy( 'noindex,nofollow' );
210 $wgOut->addBacklinkSubtitle( $this->mTitle );
212 if ( is_array( $err ) ) {
213 $wgOut->wrapWikiMsg( "<p class='error'>\n$1\n</p>\n", $err );
214 } elseif ( is_string( $err ) ) {
215 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
218 if ( $this->mTitle->getRestrictionTypes() === array() ) {
219 // No restriction types available for the current title
220 // this might happen if an extension alters the available types
221 $wgOut->setPageTitle( wfMessage( 'protect-norestrictiontypes-title', $this->mTitle->getPrefixedText() ) );
222 $wgOut->addWikiText( wfMessage( 'protect-norestrictiontypes-text' )->text() );
224 // Show the log in case protection was possible once
225 $this->showLogExtract( $wgOut );
226 // return as there isn't anything else we can do
227 return;
230 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
231 if ( $cascadeSources && count( $cascadeSources ) > 0 ) {
232 $titles = '';
234 foreach ( $cascadeSources as $title ) {
235 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
238 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count( $cascadeSources ) ) );
241 # Show an appropriate message if the user isn't allowed or able to change
242 # the protection settings at this time
243 if ( $this->disabled ) {
244 $wgOut->setPageTitle( wfMessage( 'protect-title-notallowed', $this->mTitle->getPrefixedText() ) );
245 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $this->mPermErrors, 'protect' ) );
246 } else {
247 $wgOut->setPageTitle( wfMessage( 'protect-title', $this->mTitle->getPrefixedText() ) );
248 $wgOut->addWikiMsg( 'protect-text',
249 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
252 $wgOut->addHTML( $this->buildForm() );
253 $this->showLogExtract( $wgOut );
257 * Save submitted protection form
259 * @return Boolean: success
261 function save() {
262 global $wgRequest, $wgUser, $wgOut;
264 # Permission check!
265 if ( $this->disabled ) {
266 $this->show();
267 return false;
270 $token = $wgRequest->getVal( 'wpEditToken' );
271 if ( !$wgUser->matchEditToken( $token, array( 'protect', $this->mTitle->getPrefixedDBkey() ) ) ) {
272 $this->show( array( 'sessionfailure' ) );
273 return false;
276 # Create reason string. Use list and/or custom string.
277 $reasonstr = $this->mReasonSelection;
278 if ( $reasonstr != 'other' && $this->mReason != '' ) {
279 // Entry from drop down menu + additional comment
280 $reasonstr .= wfMessage( 'colon-separator' )->text() . $this->mReason;
281 } elseif ( $reasonstr == 'other' ) {
282 $reasonstr = $this->mReason;
284 $expiry = array();
285 foreach( $this->mApplicableTypes as $action ) {
286 $expiry[$action] = $this->getExpiry( $action );
287 if( empty( $this->mRestrictions[$action] ) )
288 continue; // unprotected
289 if ( !$expiry[$action] ) {
290 $this->show( array( 'protect_expiry_invalid' ) );
291 return false;
293 if ( $expiry[$action] < wfTimestampNow() ) {
294 $this->show( array( 'protect_expiry_old' ) );
295 return false;
299 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
300 # to a semi-protected page.
301 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
302 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
303 if ( $this->mCascade && ($edit_restriction != 'protect') &&
304 !User::groupHasPermission( $edit_restriction, 'protect' ) )
305 $this->mCascade = false;
307 $status = $this->mArticle->doUpdateRestrictions( $this->mRestrictions, $expiry, $this->mCascade, $reasonstr, $wgUser );
309 if ( !$status->isOK() ) {
310 $this->show( $wgOut->parseInline( $status->getWikiText() ) );
311 return false;
315 * Give extensions a change to handle added form items
317 * @since 1.19 you can (and you should) return false to abort saving;
318 * you can also return an array of message name and its parameters
320 $errorMsg = '';
321 if( !wfRunHooks( 'ProtectionForm::save', array( $this->mArticle, &$errorMsg ) ) ) {
322 if ( $errorMsg == '' ) {
323 $errorMsg = array( 'hookaborted' );
326 if( $errorMsg != '' ) {
327 $this->show( $errorMsg );
328 return false;
331 if ( $wgUser->isLoggedIn() && $wgRequest->getCheck( 'mwProtectWatch' ) != $wgUser->isWatched( $this->mTitle ) ) {
332 if ( $wgRequest->getCheck( 'mwProtectWatch' ) ) {
333 WatchAction::doWatch( $this->mTitle, $wgUser );
334 } else {
335 WatchAction::doUnwatch( $this->mTitle, $wgUser );
338 return true;
342 * Build the input form
344 * @return String: HTML form
346 function buildForm() {
347 global $wgUser, $wgLang, $wgOut;
349 $mProtectreasonother = Xml::label(
350 wfMessage( 'protectcomment' )->text(),
351 'wpProtectReasonSelection'
353 $mProtectreason = Xml::label(
354 wfMessage( 'protect-otherreason' )->text(),
355 'mwProtect-reason'
358 $out = '';
359 if( !$this->disabled ) {
360 $wgOut->addModules( 'mediawiki.legacy.protect' );
361 $out .= Xml::openElement( 'form', array( 'method' => 'post',
362 'action' => $this->mTitle->getLocalURL( 'action=protect' ),
363 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
366 $out .= Xml::openElement( 'fieldset' ) .
367 Xml::element( 'legend', null, wfMessage( 'protect-legend' )->text() ) .
368 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
369 Xml::openElement( 'tbody' );
371 foreach( $this->mRestrictions as $action => $selected ) {
372 /* Not all languages have V_x <-> N_x relation */
373 $msg = wfMessage( 'restriction-' . $action );
374 $out .= "<tr><td>" .
375 Xml::openElement( 'fieldset' ) .
376 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
377 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
378 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
380 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
381 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
382 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
383 $this->mReasonSelection,
384 'mwProtect-reason', 4 );
385 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
387 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
389 $mProtectexpiry = Xml::label(
390 wfMessage( 'protectexpiry' )->text(),
391 "mwProtectExpirySelection-$action"
393 $mProtectother = Xml::label(
394 wfMessage( 'protect-othertime' )->text(),
395 "mwProtect-$action-expires"
398 $expiryFormOptions = '';
399 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
400 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action], true );
401 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
402 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
403 $expiryFormOptions .=
404 Xml::option(
405 wfMessage( 'protect-existing-expiry', $timestamp, $d, $t )->text(),
406 'existing',
407 $this->mExpirySelection[$action] == 'existing'
408 ) . "\n";
411 $expiryFormOptions .= Xml::option(
412 wfMessage( 'protect-othertime-op' )->text(),
413 "othertime"
414 ) . "\n";
415 foreach( explode( ',', $scExpiryOptions ) as $option ) {
416 if ( strpos( $option, ":" ) === false ) {
417 $show = $value = $option;
418 } else {
419 list( $show, $value ) = explode( ":", $option );
421 $show = htmlspecialchars( $show );
422 $value = htmlspecialchars( $value );
423 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
425 # Add expiry dropdown
426 if( $showProtectOptions && !$this->disabled ) {
427 $out .= "
428 <table><tr>
429 <td class='mw-label'>
430 {$mProtectexpiry}
431 </td>
432 <td class='mw-input'>" .
433 Xml::tags( 'select',
434 array(
435 'id' => "mwProtectExpirySelection-$action",
436 'name' => "wpProtectExpirySelection-$action",
437 'onchange' => "ProtectionForm.updateExpiryList(this)",
438 'tabindex' => '2' ) + $this->disabledAttrib,
439 $expiryFormOptions ) .
440 "</td>
441 </tr></table>";
443 # Add custom expiry field
444 $attribs = array( 'id' => "mwProtect-$action-expires",
445 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
446 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
447 $out .= "<table><tr>
448 <td class='mw-label'>" .
449 $mProtectother .
450 '</td>
451 <td class="mw-input">' .
452 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
453 '</td>
454 </tr></table>';
455 $out .= "</td></tr>" .
456 Xml::closeElement( 'table' ) .
457 Xml::closeElement( 'fieldset' ) .
458 "</td></tr>";
460 # Give extensions a chance to add items to the form
461 wfRunHooks( 'ProtectionForm::buildForm', array( $this->mArticle, &$out ) );
463 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
465 // JavaScript will add another row with a value-chaining checkbox
466 if( $this->mTitle->exists() ) {
467 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
468 Xml::openElement( 'tbody' );
469 $out .= '<tr>
470 <td></td>
471 <td class="mw-input">' .
472 Xml::checkLabel(
473 wfMessage( 'protect-cascade' )->text(),
474 'mwProtect-cascade',
475 'mwProtect-cascade',
476 $this->mCascade, $this->disabledAttrib
478 "</td>
479 </tr>\n";
480 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
483 # Add manual and custom reason field/selects as well as submit
484 if( !$this->disabled ) {
485 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
486 Xml::openElement( 'tbody' );
487 $out .= "
488 <tr>
489 <td class='mw-label'>
490 {$mProtectreasonother}
491 </td>
492 <td class='mw-input'>
493 {$reasonDropDown}
494 </td>
495 </tr>
496 <tr>
497 <td class='mw-label'>
498 {$mProtectreason}
499 </td>
500 <td class='mw-input'>" .
501 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
502 'id' => 'mwProtect-reason', 'maxlength' => 180 ) ) .
503 // Limited maxlength as the database trims at 255 bytes and other texts
504 // chosen by dropdown menus on this page are also included in this database field.
505 // The byte limit of 180 bytes is enforced in javascript
506 "</td>
507 </tr>";
508 # Disallow watching is user is not logged in
509 if( $wgUser->isLoggedIn() ) {
510 $out .= "
511 <tr>
512 <td></td>
513 <td class='mw-input'>" .
514 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
515 'mwProtectWatch', 'mwProtectWatch',
516 $wgUser->isWatched( $this->mTitle ) || $wgUser->getOption( 'watchdefault' ) ) .
517 "</td>
518 </tr>";
520 $out .= "
521 <tr>
522 <td></td>
523 <td class='mw-submit'>" .
524 Xml::submitButton(
525 wfMessage( 'confirm' )->text(),
526 array( 'id' => 'mw-Protect-submit' )
528 "</td>
529 </tr>\n";
530 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
532 $out .= Xml::closeElement( 'fieldset' );
534 if ( $wgUser->isAllowed( 'editinterface' ) ) {
535 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
536 $link = Linker::link(
537 $title,
538 wfMessage( 'protect-edit-reasonlist' )->escaped(),
539 array(),
540 array( 'action' => 'edit' )
542 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
545 if ( !$this->disabled ) {
546 $out .= Html::hidden( 'wpEditToken', $wgUser->getEditToken( array( 'protect', $this->mTitle->getPrefixedDBkey() ) ) );
547 $out .= Xml::closeElement( 'form' );
548 $wgOut->addScript( $this->buildCleanupScript() );
551 return $out;
555 * Build protection level selector
557 * @param string $action action to protect
558 * @param string $selected current protection level
559 * @return String: HTML fragment
561 function buildSelector( $action, $selected ) {
562 global $wgRestrictionLevels, $wgUser;
564 $levels = array();
565 foreach( $wgRestrictionLevels as $key ) {
566 //don't let them choose levels above their own (aka so they can still unprotect and edit the page). but only when the form isn't disabled
567 if( $key == 'sysop' ) {
568 //special case, rewrite sysop to protect and editprotected
569 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) && !$this->disabled )
570 continue;
571 } else {
572 if( !$wgUser->isAllowed( $key ) && !$this->disabled )
573 continue;
575 $levels[] = $key;
578 $id = 'mwProtect-level-' . $action;
579 $attribs = array(
580 'id' => $id,
581 'name' => $id,
582 'size' => count( $levels ),
583 'onchange' => 'ProtectionForm.updateLevels(this)',
584 ) + $this->disabledAttrib;
586 $out = Xml::openElement( 'select', $attribs );
587 foreach( $levels as $key ) {
588 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
590 $out .= Xml::closeElement( 'select' );
591 return $out;
595 * Prepare the label for a protection selector option
597 * @param string $permission permission required
598 * @return String
600 private function getOptionLabel( $permission ) {
601 if( $permission == '' ) {
602 return wfMessage( 'protect-default' )->text();
603 } else {
604 $msg = wfMessage( "protect-level-{$permission}" );
605 if( $msg->exists() ) {
606 return $msg->text();
608 return wfMessage( 'protect-fallback', $permission )->text();
612 function buildCleanupScript() {
613 global $wgRestrictionLevels, $wgOut;
615 $cascadeableLevels = array();
616 foreach( $wgRestrictionLevels as $key ) {
617 if ( User::groupHasPermission( $key, 'protect' )
618 || $key == 'protect'
620 $cascadeableLevels[] = $key;
623 $options = array(
624 'tableId' => 'mwProtectSet',
625 'labelText' => wfMessage( 'protect-unchain-permissions' )->plain(),
626 'numTypes' => count( $this->mApplicableTypes ),
627 'existingMatch' => count( array_unique( $this->mExistingExpiry ) ) === 1,
630 $wgOut->addJsConfigVars( 'wgCascadeableLevels', $cascadeableLevels );
631 $script = Xml::encodeJsCall( 'ProtectionForm.init', array( $options ) );
632 return Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) );
636 * Show protection long extracts for this page
638 * @param $out OutputPage
639 * @access private
641 function showLogExtract( &$out ) {
642 # Show relevant lines from the protection log:
643 $protectLogPage = new LogPage( 'protect' );
644 $out->addHTML( Xml::element( 'h2', null, $protectLogPage->getName()->text() ) );
645 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle );
646 # Let extensions add other relevant log extracts
647 wfRunHooks( 'ProtectionForm::showLogExtract', array( $this->mArticle, $out ) );