Remove useless comments from search output
[mediawiki.git] / includes / ProtectionForm.php
blobbcb88e9fa76061b4bb489ac9276895a1d7a472e0
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 /** 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;
87 $levels = MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace(), $wgUser );
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, $levels ) ) {
136 $this->mRestrictions[$action] = $val;
142 * Get the expiry time for a given action, by combining the relevant inputs.
144 * @param $action string
146 * @return string 14-char timestamp or "infinity", or false if the input was invalid
148 function getExpiry( $action ) {
149 if ( $this->mExpirySelection[$action] == 'existing' ) {
150 return $this->mExistingExpiry[$action];
151 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
152 $value = $this->mExpiry[$action];
153 } else {
154 $value = $this->mExpirySelection[$action];
156 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
157 $time = wfGetDB( DB_SLAVE )->getInfinity();
158 } else {
159 $unix = strtotime( $value );
161 if ( !$unix || $unix === -1 ) {
162 return false;
165 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
166 // and there isn't notice about it in the ui
167 $time = wfTimestamp( TS_MW, $unix );
169 return $time;
173 * Main entry point for action=protect and action=unprotect
175 function execute() {
176 global $wgRequest, $wgOut;
178 if ( MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) === array( '' ) ) {
179 throw new ErrorPageError( 'protect-badnamespace-title', 'protect-badnamespace-text' );
182 if ( $wgRequest->wasPosted() ) {
183 if ( $this->save() ) {
184 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
185 $wgOut->redirect( $this->mTitle->getFullURL( $q ) );
187 } else {
188 $this->show();
193 * Show the input form with optional error message
195 * @param string $err error message or null if there's no error
197 function show( $err = null ) {
198 global $wgOut;
200 $wgOut->setRobotPolicy( 'noindex,nofollow' );
201 $wgOut->addBacklinkSubtitle( $this->mTitle );
203 if ( is_array( $err ) ) {
204 $wgOut->wrapWikiMsg( "<p class='error'>\n$1\n</p>\n", $err );
205 } elseif ( is_string( $err ) ) {
206 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
209 if ( $this->mTitle->getRestrictionTypes() === array() ) {
210 // No restriction types available for the current title
211 // this might happen if an extension alters the available types
212 $wgOut->setPageTitle( wfMessage( 'protect-norestrictiontypes-title', $this->mTitle->getPrefixedText() ) );
213 $wgOut->addWikiText( wfMessage( 'protect-norestrictiontypes-text' )->text() );
215 // Show the log in case protection was possible once
216 $this->showLogExtract( $wgOut );
217 // return as there isn't anything else we can do
218 return;
221 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
222 if ( $cascadeSources && count( $cascadeSources ) > 0 ) {
223 $titles = '';
225 foreach ( $cascadeSources as $title ) {
226 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
229 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count( $cascadeSources ) ) );
232 # Show an appropriate message if the user isn't allowed or able to change
233 # the protection settings at this time
234 if ( $this->disabled ) {
235 $wgOut->setPageTitle( wfMessage( 'protect-title-notallowed', $this->mTitle->getPrefixedText() ) );
236 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $this->mPermErrors, 'protect' ) );
237 } else {
238 $wgOut->setPageTitle( wfMessage( 'protect-title', $this->mTitle->getPrefixedText() ) );
239 $wgOut->addWikiMsg( 'protect-text',
240 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
243 $wgOut->addHTML( $this->buildForm() );
244 $this->showLogExtract( $wgOut );
248 * Save submitted protection form
250 * @return Boolean: success
252 function save() {
253 global $wgRequest, $wgUser, $wgOut;
255 # Permission check!
256 if ( $this->disabled ) {
257 $this->show();
258 return false;
261 $token = $wgRequest->getVal( 'wpEditToken' );
262 if ( !$wgUser->matchEditToken( $token, array( 'protect', $this->mTitle->getPrefixedDBkey() ) ) ) {
263 $this->show( array( 'sessionfailure' ) );
264 return false;
267 # Create reason string. Use list and/or custom string.
268 $reasonstr = $this->mReasonSelection;
269 if ( $reasonstr != 'other' && $this->mReason != '' ) {
270 // Entry from drop down menu + additional comment
271 $reasonstr .= wfMessage( 'colon-separator' )->text() . $this->mReason;
272 } elseif ( $reasonstr == 'other' ) {
273 $reasonstr = $this->mReason;
275 $expiry = array();
276 foreach ( $this->mApplicableTypes as $action ) {
277 $expiry[$action] = $this->getExpiry( $action );
278 if ( empty( $this->mRestrictions[$action] ) ) {
279 continue; // unprotected
281 if ( !$expiry[$action] ) {
282 $this->show( array( 'protect_expiry_invalid' ) );
283 return false;
285 if ( $expiry[$action] < wfTimestampNow() ) {
286 $this->show( array( 'protect_expiry_old' ) );
287 return false;
291 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
293 $status = $this->mArticle->doUpdateRestrictions( $this->mRestrictions, $expiry, $this->mCascade, $reasonstr, $wgUser );
295 if ( !$status->isOK() ) {
296 $this->show( $wgOut->parseInline( $status->getWikiText() ) );
297 return false;
301 * Give extensions a change to handle added form items
303 * @since 1.19 you can (and you should) return false to abort saving;
304 * you can also return an array of message name and its parameters
306 $errorMsg = '';
307 if ( !wfRunHooks( 'ProtectionForm::save', array( $this->mArticle, &$errorMsg, $reasonstr ) ) ) {
308 if ( $errorMsg == '' ) {
309 $errorMsg = array( 'hookaborted' );
312 if ( $errorMsg != '' ) {
313 $this->show( $errorMsg );
314 return false;
317 WatchAction::doWatchOrUnwatch( $wgRequest->getCheck( 'mwProtectWatch' ), $this->mTitle, $wgUser );
319 return true;
323 * Build the input form
325 * @return String: HTML form
327 function buildForm() {
328 global $wgUser, $wgLang, $wgOut;
330 $mProtectreasonother = Xml::label(
331 wfMessage( 'protectcomment' )->text(),
332 'wpProtectReasonSelection'
334 $mProtectreason = Xml::label(
335 wfMessage( 'protect-otherreason' )->text(),
336 'mwProtect-reason'
339 $out = '';
340 if ( !$this->disabled ) {
341 $wgOut->addModules( 'mediawiki.legacy.protect' );
342 $out .= Xml::openElement( 'form', array( 'method' => 'post',
343 'action' => $this->mTitle->getLocalURL( 'action=protect' ),
344 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
347 $out .= Xml::openElement( 'fieldset' ) .
348 Xml::element( 'legend', null, wfMessage( 'protect-legend' )->text() ) .
349 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
350 Xml::openElement( 'tbody' );
352 // Not all languages have V_x <-> N_x relation
353 foreach ( $this->mRestrictions as $action => $selected ) {
354 // Messages:
355 // restriction-edit, restriction-move, restriction-create, restriction-upload
356 $msg = wfMessage( 'restriction-' . $action );
357 $out .= "<tr><td>" .
358 Xml::openElement( 'fieldset' ) .
359 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
360 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
361 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
363 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
364 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
365 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
366 $this->mReasonSelection,
367 'mwProtect-reason', 4 );
368 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
370 $showProtectOptions = $scExpiryOptions !== '-' && !$this->disabled;
372 $mProtectexpiry = Xml::label(
373 wfMessage( 'protectexpiry' )->text(),
374 "mwProtectExpirySelection-$action"
376 $mProtectother = Xml::label(
377 wfMessage( 'protect-othertime' )->text(),
378 "mwProtect-$action-expires"
381 $expiryFormOptions = '';
382 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
383 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action], true );
384 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
385 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
386 $expiryFormOptions .=
387 Xml::option(
388 wfMessage( 'protect-existing-expiry', $timestamp, $d, $t )->text(),
389 'existing',
390 $this->mExpirySelection[$action] == 'existing'
391 ) . "\n";
394 $expiryFormOptions .= Xml::option(
395 wfMessage( 'protect-othertime-op' )->text(),
396 "othertime"
397 ) . "\n";
398 foreach ( explode( ',', $scExpiryOptions ) as $option ) {
399 if ( strpos( $option, ":" ) === false ) {
400 $show = $value = $option;
401 } else {
402 list( $show, $value ) = explode( ":", $option );
404 $show = htmlspecialchars( $show );
405 $value = htmlspecialchars( $value );
406 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
408 # Add expiry dropdown
409 if ( $showProtectOptions && !$this->disabled ) {
410 $out .= "
411 <table><tr>
412 <td class='mw-label'>
413 {$mProtectexpiry}
414 </td>
415 <td class='mw-input'>" .
416 Xml::tags( 'select',
417 array(
418 'id' => "mwProtectExpirySelection-$action",
419 'name' => "wpProtectExpirySelection-$action",
420 'onchange' => "ProtectionForm.updateExpiryList(this)",
421 'tabindex' => '2' ) + $this->disabledAttrib,
422 $expiryFormOptions ) .
423 "</td>
424 </tr></table>";
426 # Add custom expiry field
427 $attribs = array( 'id' => "mwProtect-$action-expires",
428 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
429 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
430 $out .= "<table><tr>
431 <td class='mw-label'>" .
432 $mProtectother .
433 '</td>
434 <td class="mw-input">' .
435 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
436 '</td>
437 </tr></table>';
438 $out .= "</td></tr>" .
439 Xml::closeElement( 'table' ) .
440 Xml::closeElement( 'fieldset' ) .
441 "</td></tr>";
443 # Give extensions a chance to add items to the form
444 wfRunHooks( 'ProtectionForm::buildForm', array( $this->mArticle, &$out ) );
446 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
448 // JavaScript will add another row with a value-chaining checkbox
449 if ( $this->mTitle->exists() ) {
450 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
451 Xml::openElement( 'tbody' );
452 $out .= '<tr>
453 <td></td>
454 <td class="mw-input">' .
455 Xml::checkLabel(
456 wfMessage( 'protect-cascade' )->text(),
457 'mwProtect-cascade',
458 'mwProtect-cascade',
459 $this->mCascade, $this->disabledAttrib
461 "</td>
462 </tr>\n";
463 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
466 # Add manual and custom reason field/selects as well as submit
467 if ( !$this->disabled ) {
468 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
469 Xml::openElement( 'tbody' );
470 $out .= "
471 <tr>
472 <td class='mw-label'>
473 {$mProtectreasonother}
474 </td>
475 <td class='mw-input'>
476 {$reasonDropDown}
477 </td>
478 </tr>
479 <tr>
480 <td class='mw-label'>
481 {$mProtectreason}
482 </td>
483 <td class='mw-input'>" .
484 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
485 'id' => 'mwProtect-reason', 'maxlength' => 180 ) ) .
486 // Limited maxlength as the database trims at 255 bytes and other texts
487 // chosen by dropdown menus on this page are also included in this database field.
488 // The byte limit of 180 bytes is enforced in javascript
489 "</td>
490 </tr>";
491 # Disallow watching is user is not logged in
492 if ( $wgUser->isLoggedIn() ) {
493 $out .= "
494 <tr>
495 <td></td>
496 <td class='mw-input'>" .
497 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
498 'mwProtectWatch', 'mwProtectWatch',
499 $wgUser->isWatched( $this->mTitle ) || $wgUser->getOption( 'watchdefault' ) ) .
500 "</td>
501 </tr>";
503 $out .= "
504 <tr>
505 <td></td>
506 <td class='mw-submit'>" .
507 Xml::submitButton(
508 wfMessage( 'confirm' )->text(),
509 array( 'id' => 'mw-Protect-submit' )
511 "</td>
512 </tr>\n";
513 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
515 $out .= Xml::closeElement( 'fieldset' );
517 if ( $wgUser->isAllowed( 'editinterface' ) ) {
518 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
519 $link = Linker::link(
520 $title,
521 wfMessage( 'protect-edit-reasonlist' )->escaped(),
522 array(),
523 array( 'action' => 'edit' )
525 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
528 if ( !$this->disabled ) {
529 $out .= Html::hidden( 'wpEditToken', $wgUser->getEditToken( array( 'protect', $this->mTitle->getPrefixedDBkey() ) ) );
530 $out .= Xml::closeElement( 'form' );
531 $wgOut->addScript( $this->buildCleanupScript() );
534 return $out;
538 * Build protection level selector
540 * @param string $action action to protect
541 * @param string $selected current protection level
542 * @return String: HTML fragment
544 function buildSelector( $action, $selected ) {
545 global $wgUser;
547 // If the form is disabled, display all relevant levels. Otherwise,
548 // just show the ones this user can use.
549 $levels = MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace(),
550 $this->disabled ? null : $wgUser
553 $id = 'mwProtect-level-' . $action;
554 $attribs = array(
555 'id' => $id,
556 'name' => $id,
557 'size' => count( $levels ),
558 'onchange' => 'ProtectionForm.updateLevels(this)',
559 ) + $this->disabledAttrib;
561 $out = Xml::openElement( 'select', $attribs );
562 foreach ( $levels as $key ) {
563 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
565 $out .= Xml::closeElement( 'select' );
566 return $out;
570 * Prepare the label for a protection selector option
572 * @param string $permission permission required
573 * @return String
575 private function getOptionLabel( $permission ) {
576 if ( $permission == '' ) {
577 return wfMessage( 'protect-default' )->text();
578 } else {
579 // Messages: protect-level-autoconfirmed, protect-level-sysop
580 $msg = wfMessage( "protect-level-{$permission}" );
581 if ( $msg->exists() ) {
582 return $msg->text();
584 return wfMessage( 'protect-fallback', $permission )->text();
588 function buildCleanupScript() {
589 global $wgCascadingRestrictionLevels, $wgOut;
591 $cascadeableLevels = $wgCascadingRestrictionLevels;
592 $options = array(
593 'tableId' => 'mwProtectSet',
594 'labelText' => wfMessage( 'protect-unchain-permissions' )->plain(),
595 'numTypes' => count( $this->mApplicableTypes ),
596 'existingMatch' => count( array_unique( $this->mExistingExpiry ) ) === 1,
599 $wgOut->addJsConfigVars( 'wgCascadeableLevels', $cascadeableLevels );
600 $script = Xml::encodeJsCall( 'ProtectionForm.init', array( $options ) );
601 return Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) );
605 * Show protection long extracts for this page
607 * @param $out OutputPage
608 * @access private
610 function showLogExtract( &$out ) {
611 # Show relevant lines from the protection log:
612 $protectLogPage = new LogPage( 'protect' );
613 $out->addHTML( Xml::element( 'h2', null, $protectLogPage->getName()->text() ) );
614 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle );
615 # Let extensions add other relevant log extracts
616 wfRunHooks( 'ProtectionForm::showLogExtract', array( $this->mArticle, $out ) );