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