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