* Follow-up r84610: don't assume a Parser object is attached
[lhc/web/wiklou.git] / includes / ProtectionForm.php
1 <?php
2 /**
3 * Page protection
4 *
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * http://www.mediawiki.org/
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 */
25
26 /**
27 * Handles the page protection UI and backend
28 */
29 class ProtectionForm {
30 /** A map of action to restriction level, from request or default */
31 var $mRestrictions = array();
32
33 /** The custom/additional protection reason */
34 var $mReason = '';
35
36 /** The reason selected from the list, blank for other/additional */
37 var $mReasonSelection = '';
38
39 /** True if the restrictions are cascading, from request or existing protection */
40 var $mCascade = false;
41
42 /** Map of action to "other" expiry time. Used in preference to mExpirySelection. */
43 var $mExpiry = array();
44
45 /**
46 * Map of action to value selected in expiry drop-down list.
47 * Will be set to 'othertime' whenever mExpiry is set.
48 */
49 var $mExpirySelection = array();
50
51 /** Permissions errors for the protect action */
52 var $mPermErrors = array();
53
54 /** Types (i.e. actions) for which levels can be selected */
55 var $mApplicableTypes = array();
56
57 /** Map of action to the expiry time of the existing protection */
58 var $mExistingExpiry = array();
59
60 function __construct( Article $article ) {
61 global $wgUser;
62 // Set instance variables.
63 $this->mArticle = $article;
64 $this->mTitle = $article->mTitle;
65 $this->mApplicableTypes = $this->mTitle->getRestrictionTypes();
66
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();
74
75 $this->loadData();
76 }
77
78 /**
79 * Loads the current state of protection into the object.
80 */
81 function loadData() {
82 global $wgRequest, $wgUser;
83 global $wgRestrictionLevels;
84
85 $this->mCascade = $this->mTitle->areRestrictionsCascading();
86
87 $this->mReason = $wgRequest->getText( 'mwProtect-reason' );
88 $this->mReasonSelection = $wgRequest->getText( 'wpProtectReasonSelection' );
89 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade', $this->mCascade );
90
91 foreach( $this->mApplicableTypes as $action ) {
92 // Fixme: this form currently requires individual selections,
93 // but the db allows multiples separated by commas.
94
95 // Pull the actual restriction from the DB
96 $this->mRestrictions[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
97
98 if ( !$this->mRestrictions[$action] ) {
99 // No existing expiry
100 $existingExpiry = '';
101 } else {
102 $existingExpiry = $this->mTitle->getRestrictionExpiry( $action );
103 }
104 $this->mExistingExpiry[$action] = $existingExpiry;
105
106 $requestExpiry = $wgRequest->getText( "mwProtect-expiry-$action" );
107 $requestExpirySelection = $wgRequest->getVal( "wpProtectExpirySelection-$action" );
108
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';
129 }
130
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;
141 }
142 $this->mRestrictions[$action] = $val;
143 }
144 }
145 }
146
147 /**
148 * Get the expiry time for a given action, by combining the relevant inputs.
149 *
150 * @return 14-char timestamp or "infinity", or false if the input was invalid
151 */
152 function getExpiry( $action ) {
153 if ( $this->mExpirySelection[$action] == 'existing' ) {
154 return $this->mExistingExpiry[$action];
155 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
156 $value = $this->mExpiry[$action];
157 } else {
158 $value = $this->mExpirySelection[$action];
159 }
160 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
161 $time = wfGetDB( DB_SLAVE )->getInfinity();
162 } else {
163 $unix = strtotime( $value );
164
165 if ( !$unix || $unix === -1 ) {
166 return false;
167 }
168
169 // Fixme: non-qualified absolute times are not in users specified timezone
170 // and there isn't notice about it in the ui
171 $time = wfTimestamp( TS_MW, $unix );
172 }
173 return $time;
174 }
175
176 /**
177 * Main entry point for action=protect and action=unprotect
178 */
179 function execute() {
180 global $wgRequest, $wgOut;
181 if( $wgRequest->wasPosted() ) {
182 if( $this->save() ) {
183 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
184 $wgOut->redirect( $this->mTitle->getFullUrl( $q ) );
185 }
186 } else {
187 $this->show();
188 }
189 }
190
191 /**
192 * Show the input form with optional error message
193 *
194 * @param $err String: error message or null if there's no error
195 */
196 function show( $err = null ) {
197 global $wgOut, $wgUser;
198
199 $wgOut->setRobotPolicy( 'noindex,nofollow' );
200
201 if( is_null( $this->mTitle ) ||
202 $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
203 $wgOut->showFatalError( wfMsg( 'badarticleerror' ) );
204 return;
205 }
206
207 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
208
209 if ( $err != "" ) {
210 $wgOut->setSubtitle( wfMsgHtml( 'formerror' ) );
211 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
212 }
213
214 if ( $cascadeSources && count($cascadeSources) > 0 ) {
215 $titles = '';
216
217 foreach ( $cascadeSources as $title ) {
218 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
219 }
220
221 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count($cascadeSources) ) );
222 }
223
224 $sk = $wgUser->getSkin();
225 $titleLink = $sk->link( $this->mTitle );
226 $wgOut->setPageTitle( wfMsg( 'protect-title', $this->mTitle->getPrefixedText() ) );
227 $wgOut->setSubtitle( wfMsg( 'protect-backlink', $titleLink ) );
228
229 # Show an appropriate message if the user isn't allowed or able to change
230 # the protection settings at this time
231 if( $this->disabled ) {
232 if( wfReadOnly() ) {
233 $wgOut->readOnlyPage();
234 } elseif( $this->mPermErrors ) {
235 $wgOut->showPermissionsErrorPage( $this->mPermErrors );
236 }
237 } else {
238 $wgOut->addWikiMsg( 'protect-text', $this->mTitle->getPrefixedText() );
239 }
240
241 $wgOut->addHTML( $this->buildForm() );
242
243 $this->showLogExtract( $wgOut );
244 }
245
246 /**
247 * Save submitted protection form
248 *
249 * @return Boolean: success
250 */
251 function save() {
252 global $wgRequest, $wgUser;
253
254 # Permission check!
255 if ( $this->disabled ) {
256 $this->show();
257 return false;
258 }
259
260 $token = $wgRequest->getVal( 'wpEditToken' );
261 if ( !$wgUser->matchEditToken( $token ) ) {
262 $this->show( wfMsg( 'sessionfailure' ) );
263 return false;
264 }
265
266 # Create reason string. Use list and/or custom string.
267 $reasonstr = $this->mReasonSelection;
268 if ( $reasonstr != 'other' && $this->mReason != '' ) {
269 // Entry from drop down menu + additional comment
270 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->mReason;
271 } elseif ( $reasonstr == 'other' ) {
272 $reasonstr = $this->mReason;
273 }
274 $expiry = array();
275 foreach( $this->mApplicableTypes as $action ) {
276 $expiry[$action] = $this->getExpiry( $action );
277 if( empty($this->mRestrictions[$action]) )
278 continue; // unprotected
279 if ( !$expiry[$action] ) {
280 $this->show( wfMsg( 'protect_expiry_invalid' ) );
281 return false;
282 }
283 if ( $expiry[$action] < wfTimestampNow() ) {
284 $this->show( wfMsg( 'protect_expiry_old' ) );
285 return false;
286 }
287 }
288
289 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
290 # to a semi-protected page.
291 global $wgGroupPermissions;
292
293 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
294 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
295 if ($this->mCascade && ($edit_restriction != 'protect') &&
296 !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'] ) )
297 $this->mCascade = false;
298
299 if ($this->mTitle->exists()) {
300 $ok = $this->mArticle->updateRestrictions( $this->mRestrictions, $reasonstr, $this->mCascade, $expiry );
301 } else {
302 $ok = $this->mTitle->updateTitleProtection( $this->mRestrictions['create'], $reasonstr, $expiry['create'] );
303 }
304
305 if( !$ok ) {
306 throw new FatalError( "Unknown error at restriction save time." );
307 }
308
309 $errorMsg = '';
310 # Give extensions a change to handle added form items
311 if( !wfRunHooks( 'ProtectionForm::save', array($this->mArticle,&$errorMsg) ) ) {
312 throw new FatalError( "Unknown hook error at restriction save time." );
313 }
314 if( $errorMsg != '' ) {
315 $this->show( $errorMsg );
316 return false;
317 }
318
319 if( $wgRequest->getCheck( 'mwProtectWatch' ) && $wgUser->isLoggedIn() ) {
320 $this->mArticle->doWatch();
321 } elseif( $this->mTitle->userIsWatching() ) {
322 $this->mArticle->doUnwatch();
323 }
324 return $ok;
325 }
326
327 /**
328 * Build the input form
329 *
330 * @return String: HTML form
331 */
332 function buildForm() {
333 global $wgUser, $wgLang, $wgOut;
334
335 $mProtectreasonother = Xml::label( wfMsg( 'protectcomment' ), 'wpProtectReasonSelection' );
336 $mProtectreason = Xml::label( wfMsg( 'protect-otherreason' ), 'mwProtect-reason' );
337
338 $out = '';
339 if( !$this->disabled ) {
340 $wgOut->addModules( 'mediawiki.legacy.protect' );
341 $out .= Xml::openElement( 'form', array( 'method' => 'post',
342 'action' => $this->mTitle->getLocalUrl( 'action=protect' ),
343 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
344 $out .= Html::hidden( 'wpEditToken',$wgUser->editToken() );
345 }
346
347 $out .= Xml::openElement( 'fieldset' ) .
348 Xml::element( 'legend', null, wfMsg( 'protect-legend' ) ) .
349 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
350 Xml::openElement( 'tbody' );
351
352 foreach( $this->mRestrictions as $action => $selected ) {
353 /* Not all languages have V_x <-> N_x relation */
354 $msg = wfMessage( 'restriction-' . $action );
355 $out .= "<tr><td>".
356 Xml::openElement( 'fieldset' ) .
357 Xml::element( 'legend', null, $msg->exists() ? $action : $msg->text() ) .
358 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
359 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
360
361 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
362 wfMsgForContent( 'protect-dropdown' ),
363 wfMsgForContent( 'protect-otherreason-op' ),
364 $this->mReasonSelection,
365 'mwProtect-reason', 4 );
366 $scExpiryOptions = wfMsgForContent( 'protect-expiry-options' );
367
368 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
369
370 $mProtectexpiry = Xml::label( wfMsg( 'protectexpiry' ), "mwProtectExpirySelection-$action" );
371 $mProtectother = Xml::label( wfMsg( 'protect-othertime' ), "mwProtect-$action-expires" );
372
373 $expiryFormOptions = '';
374 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
375 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action] );
376 $d = $wgLang->date( $this->mExistingExpiry[$action] );
377 $t = $wgLang->time( $this->mExistingExpiry[$action] );
378 $expiryFormOptions .=
379 Xml::option(
380 wfMsg( 'protect-existing-expiry', $timestamp, $d, $t ),
381 'existing',
382 $this->mExpirySelection[$action] == 'existing'
383 ) . "\n";
384 }
385
386 $expiryFormOptions .= Xml::option( wfMsg( 'protect-othertime-op' ), "othertime" ) . "\n";
387 foreach( explode(',', $scExpiryOptions) as $option ) {
388 if ( strpos($option, ":") === false ) {
389 $show = $value = $option;
390 } else {
391 list($show, $value) = explode(":", $option);
392 }
393 $show = htmlspecialchars($show);
394 $value = htmlspecialchars($value);
395 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
396 }
397 # Add expiry dropdown
398 if( $showProtectOptions && !$this->disabled ) {
399 $out .= "
400 <table><tr>
401 <td class='mw-label'>
402 {$mProtectexpiry}
403 </td>
404 <td class='mw-input'>" .
405 Xml::tags( 'select',
406 array(
407 'id' => "mwProtectExpirySelection-$action",
408 'name' => "wpProtectExpirySelection-$action",
409 'onchange' => "ProtectionForm.updateExpiryList(this)",
410 'tabindex' => '2' ) + $this->disabledAttrib,
411 $expiryFormOptions ) .
412 "</td>
413 </tr></table>";
414 }
415 # Add custom expiry field
416 $attribs = array( 'id' => "mwProtect-$action-expires",
417 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
418 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
419 $out .= "<table><tr>
420 <td class='mw-label'>" .
421 $mProtectother .
422 '</td>
423 <td class="mw-input">' .
424 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
425 '</td>
426 </tr></table>';
427 $out .= "</td></tr>" .
428 Xml::closeElement( 'table' ) .
429 Xml::closeElement( 'fieldset' ) .
430 "</td></tr>";
431 }
432 # Give extensions a chance to add items to the form
433 wfRunHooks( 'ProtectionForm::buildForm', array($this->mArticle,&$out) );
434
435 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
436
437 // JavaScript will add another row with a value-chaining checkbox
438 if( $this->mTitle->exists() ) {
439 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
440 Xml::openElement( 'tbody' );
441 $out .= '<tr>
442 <td></td>
443 <td class="mw-input">' .
444 Xml::checkLabel( wfMsg( 'protect-cascade' ), 'mwProtect-cascade', 'mwProtect-cascade',
445 $this->mCascade, $this->disabledAttrib ) .
446 "</td>
447 </tr>\n";
448 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
449 }
450
451 # Add manual and custom reason field/selects as well as submit
452 if( !$this->disabled ) {
453 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
454 Xml::openElement( 'tbody' );
455 $out .= "
456 <tr>
457 <td class='mw-label'>
458 {$mProtectreasonother}
459 </td>
460 <td class='mw-input'>
461 {$reasonDropDown}
462 </td>
463 </tr>
464 <tr>
465 <td class='mw-label'>
466 {$mProtectreason}
467 </td>
468 <td class='mw-input'>" .
469 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
470 'id' => 'mwProtect-reason', 'maxlength' => 255 ) ) .
471 "</td>
472 </tr>";
473 # Disallow watching is user is not logged in
474 if( $wgUser->isLoggedIn() ) {
475 $out .= "
476 <tr>
477 <td></td>
478 <td class='mw-input'>" .
479 Xml::checkLabel( wfMsg( 'watchthis' ),
480 'mwProtectWatch', 'mwProtectWatch',
481 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
482 "</td>
483 </tr>";
484 }
485 $out .= "
486 <tr>
487 <td></td>
488 <td class='mw-submit'>" .
489 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
490 "</td>
491 </tr>\n";
492 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
493 }
494 $out .= Xml::closeElement( 'fieldset' );
495
496 if ( $wgUser->isAllowed( 'editinterface' ) ) {
497 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
498 $link = $wgUser->getSkin()->link(
499 $title,
500 wfMsgHtml( 'protect-edit-reasonlist' ),
501 array(),
502 array( 'action' => 'edit' )
503 );
504 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
505 }
506
507 if ( !$this->disabled ) {
508 $out .= Xml::closeElement( 'form' );
509 $wgOut->addScript( $this->buildCleanupScript() );
510 }
511
512 return $out;
513 }
514
515 /**
516 * Build protection level selector
517 *
518 * @param $action String: action to protect
519 * @param $selected String: current protection level
520 * @return String: HTML fragment
521 */
522 function buildSelector( $action, $selected ) {
523 global $wgRestrictionLevels, $wgUser;
524
525 $levels = array();
526 foreach( $wgRestrictionLevels as $key ) {
527 //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
528 if( $key == 'sysop' ) {
529 //special case, rewrite sysop to protect and editprotected
530 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) && !$this->disabled )
531 continue;
532 } else {
533 if( !$wgUser->isAllowed($key) && !$this->disabled )
534 continue;
535 }
536 $levels[] = $key;
537 }
538
539 $id = 'mwProtect-level-' . $action;
540 $attribs = array(
541 'id' => $id,
542 'name' => $id,
543 'size' => count( $levels ),
544 'onchange' => 'ProtectionForm.updateLevels(this)',
545 ) + $this->disabledAttrib;
546
547 $out = Xml::openElement( 'select', $attribs );
548 foreach( $levels as $key ) {
549 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
550 }
551 $out .= Xml::closeElement( 'select' );
552 return $out;
553 }
554
555 /**
556 * Prepare the label for a protection selector option
557 *
558 * @param $permission String: permission required
559 * @return String
560 */
561 private function getOptionLabel( $permission ) {
562 if( $permission == '' ) {
563 return wfMsg( 'protect-default' );
564 } else {
565 $msg = wfMessage( "protect-level-{$permission}" );
566 if( !$msg->exists() ) {
567 return $msg->text();
568 }
569 return wfMsg( 'protect-fallback', $permission );
570 }
571 }
572
573 function buildCleanupScript() {
574 global $wgRestrictionLevels, $wgGroupPermissions;
575 $script = 'var wgCascadeableLevels=';
576 $CascadeableLevels = array();
577 foreach( $wgRestrictionLevels as $key ) {
578 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
579 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
580 }
581 }
582 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
583 $options = (object)array(
584 'tableId' => 'mwProtectSet',
585 'labelText' => wfMsg( 'protect-unchain-permissions' ),
586 'numTypes' => count($this->mApplicableTypes),
587 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
588 );
589 $encOptions = Xml::encodeJsVar( $options );
590
591 $script .= "ProtectionForm.init($encOptions)";
592 return Html::inlineScript( "if ( window.mediaWiki ) { $script }" );
593 }
594
595 /**
596 * Show protection long extracts for this page
597 *
598 * @param $out OutputPage
599 * @access private
600 */
601 function showLogExtract( &$out ) {
602 # Show relevant lines from the protection log:
603 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
604 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
605 # Let extensions add other relevant log extracts
606 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );
607 }
608 }