Change default value for format property of mw.message object from 'parse' to 'plain...
[mediawiki.git] / includes / ProtectionForm.php
blobcac302558aaf8a240bbc96a210e8ec6a948e198d
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 $this->disabled = wfReadOnly() || $this->mPermErrors != array();
71 $this->disabledAttrib = $this->disabled
72 ? array( 'disabled' => 'disabled' )
73 : array();
75 $this->loadData();
78 /**
79 * Loads the current state of protection into the object.
81 function loadData() {
82 global $wgRequest, $wgUser;
83 global $wgRestrictionLevels;
85 $this->mCascade = $this->mTitle->areRestrictionsCascading();
87 $this->mReason = $wgRequest->getText( 'mwProtect-reason' );
88 $this->mReasonSelection = $wgRequest->getText( 'wpProtectReasonSelection' );
89 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade', $this->mCascade );
91 foreach( $this->mApplicableTypes as $action ) {
92 // @todo FIXME: This form currently requires individual selections,
93 // but the db allows multiples separated by commas.
95 // Pull the actual restriction from the DB
96 $this->mRestrictions[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
98 if ( !$this->mRestrictions[$action] ) {
99 // No existing expiry
100 $existingExpiry = '';
101 } else {
102 $existingExpiry = $this->mTitle->getRestrictionExpiry( $action );
104 $this->mExistingExpiry[$action] = $existingExpiry;
106 $requestExpiry = $wgRequest->getText( "mwProtect-expiry-$action" );
107 $requestExpirySelection = $wgRequest->getVal( "wpProtectExpirySelection-$action" );
109 if ( $requestExpiry ) {
110 // Custom expiry takes precedence
111 $this->mExpiry[$action] = $requestExpiry;
112 $this->mExpirySelection[$action] = 'othertime';
113 } elseif ( $requestExpirySelection ) {
114 // Expiry selected from list
115 $this->mExpiry[$action] = '';
116 $this->mExpirySelection[$action] = $requestExpirySelection;
117 } elseif ( $existingExpiry == 'infinity' ) {
118 // Existing expiry is infinite, use "infinite" in drop-down
119 $this->mExpiry[$action] = '';
120 $this->mExpirySelection[$action] = 'infinite';
121 } elseif ( $existingExpiry ) {
122 // Use existing expiry in its own list item
123 $this->mExpiry[$action] = '';
124 $this->mExpirySelection[$action] = $existingExpiry;
125 } else {
126 // Final default: infinite
127 $this->mExpiry[$action] = '';
128 $this->mExpirySelection[$action] = 'infinite';
131 $val = $wgRequest->getVal( "mwProtect-level-$action" );
132 if( isset( $val ) && in_array( $val, $wgRestrictionLevels ) ) {
133 // Prevent users from setting levels that they cannot later unset
134 if( $val == 'sysop' ) {
135 // Special case, rewrite sysop to either protect and editprotected
136 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) )
137 continue;
138 } else {
139 if( !$wgUser->isAllowed($val) )
140 continue;
142 $this->mRestrictions[$action] = $val;
148 * Get the expiry time for a given action, by combining the relevant inputs.
150 * @param $action string
152 * @return string 14-char timestamp or "infinity", or false if the input was invalid
154 function getExpiry( $action ) {
155 if ( $this->mExpirySelection[$action] == 'existing' ) {
156 return $this->mExistingExpiry[$action];
157 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
158 $value = $this->mExpiry[$action];
159 } else {
160 $value = $this->mExpirySelection[$action];
162 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
163 $time = wfGetDB( DB_SLAVE )->getInfinity();
164 } else {
165 $unix = strtotime( $value );
167 if ( !$unix || $unix === -1 ) {
168 return false;
171 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
172 // and there isn't notice about it in the ui
173 $time = wfTimestamp( TS_MW, $unix );
175 return $time;
179 * Main entry point for action=protect and action=unprotect
181 function execute() {
182 global $wgRequest, $wgOut;
183 if( $wgRequest->wasPosted() ) {
184 if( $this->save() ) {
185 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
186 $wgOut->redirect( $this->mTitle->getFullUrl( $q ) );
188 } else {
189 $this->show();
194 * Show the input form with optional error message
196 * @param $err String: error message or null if there's no error
198 function show( $err = null ) {
199 global $wgOut, $wgUser;
201 $wgOut->setRobotPolicy( 'noindex,nofollow' );
203 if( is_null( $this->mTitle ) ||
204 $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
205 $wgOut->showFatalError( wfMsg( 'badarticleerror' ) );
206 return;
209 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
211 if ( $err != "" ) {
212 $wgOut->setSubtitle( wfMsgHtml( 'formerror' ) );
213 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
216 if ( $cascadeSources && count($cascadeSources) > 0 ) {
217 $titles = '';
219 foreach ( $cascadeSources as $title ) {
220 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
223 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count($cascadeSources) ) );
226 $sk = $wgUser->getSkin();
227 $titleLink = $sk->link( $this->mTitle );
228 $wgOut->setPageTitle( wfMsg( 'protect-title', $this->mTitle->getPrefixedText() ) );
229 $wgOut->setSubtitle( wfMsg( 'protect-backlink', $titleLink ) );
231 # Show an appropriate message if the user isn't allowed or able to change
232 # the protection settings at this time
233 if( $this->disabled ) {
234 if( wfReadOnly() ) {
235 $wgOut->readOnlyPage();
236 } elseif( $this->mPermErrors ) {
237 $wgOut->showPermissionsErrorPage( $this->mPermErrors );
239 } else {
240 $wgOut->addWikiMsg( 'protect-text',
241 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
244 $wgOut->addHTML( $this->buildForm() );
246 $this->showLogExtract( $wgOut );
250 * Save submitted protection form
252 * @return Boolean: success
254 function save() {
255 global $wgRequest, $wgUser;
257 # Permission check!
258 if ( $this->disabled ) {
259 $this->show();
260 return false;
263 $token = $wgRequest->getVal( 'wpEditToken' );
264 if ( !$wgUser->matchEditToken( $token ) ) {
265 $this->show( wfMsg( 'sessionfailure' ) );
266 return false;
269 # Create reason string. Use list and/or custom string.
270 $reasonstr = $this->mReasonSelection;
271 if ( $reasonstr != 'other' && $this->mReason != '' ) {
272 // Entry from drop down menu + additional comment
273 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->mReason;
274 } elseif ( $reasonstr == 'other' ) {
275 $reasonstr = $this->mReason;
277 $expiry = array();
278 foreach( $this->mApplicableTypes as $action ) {
279 $expiry[$action] = $this->getExpiry( $action );
280 if( empty($this->mRestrictions[$action]) )
281 continue; // unprotected
282 if ( !$expiry[$action] ) {
283 $this->show( wfMsg( 'protect_expiry_invalid' ) );
284 return false;
286 if ( $expiry[$action] < wfTimestampNow() ) {
287 $this->show( wfMsg( 'protect_expiry_old' ) );
288 return false;
292 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
293 # to a semi-protected page.
294 global $wgGroupPermissions;
296 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
297 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
298 if ($this->mCascade && ($edit_restriction != 'protect') &&
299 !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'] ) )
300 $this->mCascade = false;
302 if ($this->mTitle->exists()) {
303 $ok = $this->mArticle->updateRestrictions( $this->mRestrictions, $reasonstr, $this->mCascade, $expiry );
304 } else {
305 $ok = $this->mTitle->updateTitleProtection( $this->mRestrictions['create'], $reasonstr, $expiry['create'] );
308 if( !$ok ) {
309 throw new FatalError( "Unknown error at restriction save time." );
312 $errorMsg = '';
313 # Give extensions a change to handle added form items
314 if( !wfRunHooks( 'ProtectionForm::save', array($this->mArticle,&$errorMsg) ) ) {
315 throw new FatalError( "Unknown hook error at restriction save time." );
317 if( $errorMsg != '' ) {
318 $this->show( $errorMsg );
319 return false;
322 if ( $wgRequest->getCheck( 'mwProtectWatch' ) && $wgUser->isLoggedIn() ) {
323 WatchAction::doWatch( $this->mTitle, $wgUser );
324 } elseif ( $this->mTitle->userIsWatching() ) {
325 WatchAction::doUnwatch( $this->mTitle, $wgUser );
327 return $ok;
331 * Build the input form
333 * @return String: HTML form
335 function buildForm() {
336 global $wgUser, $wgLang, $wgOut;
338 $mProtectreasonother = Xml::label( wfMsg( 'protectcomment' ), 'wpProtectReasonSelection' );
339 $mProtectreason = Xml::label( wfMsg( 'protect-otherreason' ), 'mwProtect-reason' );
341 $out = '';
342 if( !$this->disabled ) {
343 $wgOut->addModules( 'mediawiki.legacy.protect' );
344 $out .= Xml::openElement( 'form', array( 'method' => 'post',
345 'action' => $this->mTitle->getLocalUrl( 'action=protect' ),
346 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
347 $out .= Html::hidden( 'wpEditToken',$wgUser->editToken() );
350 $out .= Xml::openElement( 'fieldset' ) .
351 Xml::element( 'legend', null, wfMsg( 'protect-legend' ) ) .
352 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
353 Xml::openElement( 'tbody' );
355 foreach( $this->mRestrictions as $action => $selected ) {
356 /* Not all languages have V_x <-> N_x relation */
357 $msg = wfMessage( 'restriction-' . $action );
358 $out .= "<tr><td>".
359 Xml::openElement( 'fieldset' ) .
360 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
361 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
362 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
364 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
365 wfMsgForContent( 'protect-dropdown' ),
366 wfMsgForContent( 'protect-otherreason-op' ),
367 $this->mReasonSelection,
368 'mwProtect-reason', 4 );
369 $scExpiryOptions = wfMsgForContent( 'protect-expiry-options' );
371 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
373 $mProtectexpiry = Xml::label( wfMsg( 'protectexpiry' ), "mwProtectExpirySelection-$action" );
374 $mProtectother = Xml::label( wfMsg( 'protect-othertime' ), "mwProtect-$action-expires" );
376 $expiryFormOptions = '';
377 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
378 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action], true );
379 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
380 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
381 $expiryFormOptions .=
382 Xml::option(
383 wfMsg( 'protect-existing-expiry', $timestamp, $d, $t ),
384 'existing',
385 $this->mExpirySelection[$action] == 'existing'
386 ) . "\n";
389 $expiryFormOptions .= Xml::option( wfMsg( 'protect-othertime-op' ), "othertime" ) . "\n";
390 foreach( explode(',', $scExpiryOptions) as $option ) {
391 if ( strpos($option, ":") === false ) {
392 $show = $value = $option;
393 } else {
394 list($show, $value) = explode(":", $option);
396 $show = htmlspecialchars($show);
397 $value = htmlspecialchars($value);
398 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
400 # Add expiry dropdown
401 if( $showProtectOptions && !$this->disabled ) {
402 $out .= "
403 <table><tr>
404 <td class='mw-label'>
405 {$mProtectexpiry}
406 </td>
407 <td class='mw-input'>" .
408 Xml::tags( 'select',
409 array(
410 'id' => "mwProtectExpirySelection-$action",
411 'name' => "wpProtectExpirySelection-$action",
412 'onchange' => "ProtectionForm.updateExpiryList(this)",
413 'tabindex' => '2' ) + $this->disabledAttrib,
414 $expiryFormOptions ) .
415 "</td>
416 </tr></table>";
418 # Add custom expiry field
419 $attribs = array( 'id' => "mwProtect-$action-expires",
420 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
421 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
422 $out .= "<table><tr>
423 <td class='mw-label'>" .
424 $mProtectother .
425 '</td>
426 <td class="mw-input">' .
427 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
428 '</td>
429 </tr></table>';
430 $out .= "</td></tr>" .
431 Xml::closeElement( 'table' ) .
432 Xml::closeElement( 'fieldset' ) .
433 "</td></tr>";
435 # Give extensions a chance to add items to the form
436 wfRunHooks( 'ProtectionForm::buildForm', array($this->mArticle,&$out) );
438 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
440 // JavaScript will add another row with a value-chaining checkbox
441 if( $this->mTitle->exists() ) {
442 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
443 Xml::openElement( 'tbody' );
444 $out .= '<tr>
445 <td></td>
446 <td class="mw-input">' .
447 Xml::checkLabel( wfMsg( 'protect-cascade' ), 'mwProtect-cascade', 'mwProtect-cascade',
448 $this->mCascade, $this->disabledAttrib ) .
449 "</td>
450 </tr>\n";
451 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
454 # Add manual and custom reason field/selects as well as submit
455 if( !$this->disabled ) {
456 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
457 Xml::openElement( 'tbody' );
458 $out .= "
459 <tr>
460 <td class='mw-label'>
461 {$mProtectreasonother}
462 </td>
463 <td class='mw-input'>
464 {$reasonDropDown}
465 </td>
466 </tr>
467 <tr>
468 <td class='mw-label'>
469 {$mProtectreason}
470 </td>
471 <td class='mw-input'>" .
472 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
473 'id' => 'mwProtect-reason', 'maxlength' => 180 ) ) .
474 // Limited maxlength as the database trims at 255 bytes and other texts
475 // chosen by dropdown menus on this page are also included in this database field.
476 // The byte limit of 180 bytes is enforced in javascript
477 "</td>
478 </tr>";
479 # Disallow watching is user is not logged in
480 if( $wgUser->isLoggedIn() ) {
481 $out .= "
482 <tr>
483 <td></td>
484 <td class='mw-input'>" .
485 Xml::checkLabel( wfMsg( 'watchthis' ),
486 'mwProtectWatch', 'mwProtectWatch',
487 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
488 "</td>
489 </tr>";
491 $out .= "
492 <tr>
493 <td></td>
494 <td class='mw-submit'>" .
495 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
496 "</td>
497 </tr>\n";
498 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
500 $out .= Xml::closeElement( 'fieldset' );
502 if ( $wgUser->isAllowed( 'editinterface' ) ) {
503 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
504 $link = $wgUser->getSkin()->link(
505 $title,
506 wfMsgHtml( 'protect-edit-reasonlist' ),
507 array(),
508 array( 'action' => 'edit' )
510 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
513 if ( !$this->disabled ) {
514 $out .= Xml::closeElement( 'form' );
515 $wgOut->addScript( $this->buildCleanupScript() );
518 return $out;
522 * Build protection level selector
524 * @param $action String: action to protect
525 * @param $selected String: current protection level
526 * @return String: HTML fragment
528 function buildSelector( $action, $selected ) {
529 global $wgRestrictionLevels, $wgUser;
531 $levels = array();
532 foreach( $wgRestrictionLevels as $key ) {
533 //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
534 if( $key == 'sysop' ) {
535 //special case, rewrite sysop to protect and editprotected
536 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) && !$this->disabled )
537 continue;
538 } else {
539 if( !$wgUser->isAllowed($key) && !$this->disabled )
540 continue;
542 $levels[] = $key;
545 $id = 'mwProtect-level-' . $action;
546 $attribs = array(
547 'id' => $id,
548 'name' => $id,
549 'size' => count( $levels ),
550 'onchange' => 'ProtectionForm.updateLevels(this)',
551 ) + $this->disabledAttrib;
553 $out = Xml::openElement( 'select', $attribs );
554 foreach( $levels as $key ) {
555 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
557 $out .= Xml::closeElement( 'select' );
558 return $out;
562 * Prepare the label for a protection selector option
564 * @param $permission String: permission required
565 * @return String
567 private function getOptionLabel( $permission ) {
568 if( $permission == '' ) {
569 return wfMsg( 'protect-default' );
570 } else {
571 $msg = wfMessage( "protect-level-{$permission}" );
572 if( $msg->exists() ) {
573 return $msg->text();
575 return wfMsg( 'protect-fallback', $permission );
579 function buildCleanupScript() {
580 global $wgRestrictionLevels, $wgGroupPermissions;
581 $script = 'var wgCascadeableLevels=';
582 $CascadeableLevels = array();
583 foreach( $wgRestrictionLevels as $key ) {
584 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
585 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
588 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
589 $options = (object)array(
590 'tableId' => 'mwProtectSet',
591 'labelText' => wfMsg( 'protect-unchain-permissions' ),
592 'numTypes' => count($this->mApplicableTypes),
593 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
595 $encOptions = Xml::encodeJsVar( $options );
597 $script .= "ProtectionForm.init($encOptions)";
598 return Html::inlineScript( "if ( window.mediaWiki ) { $script }" );
602 * Show protection long extracts for this page
604 * @param $out OutputPage
605 * @access private
607 function showLogExtract( &$out ) {
608 # Show relevant lines from the protection log:
609 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
610 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
611 # Let extensions add other relevant log extracts
612 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );