Fix syntax terror from r79884
[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->isAllowed('protect') && !$wgUser->isAllowed('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 = Block::infinity();
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->addWikiText( $wgOut->formatPermissionsErrorMessage( $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 = wfMsg( 'restriction-' . $action );
355 if( wfEmptyMsg( 'restriction-' . $action, $msg ) ) {
356 $msg = $action;
357 }
358 $out .= "<tr><td>".
359 Xml::openElement( 'fieldset' ) .
360 Xml::element( 'legend', null, $msg ) .
361 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
362 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
363
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' );
370
371 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
372
373 $mProtectexpiry = Xml::label( wfMsg( 'protectexpiry' ), "mwProtectExpirySelection-$action" );
374 $mProtectother = Xml::label( wfMsg( 'protect-othertime' ), "mwProtect-$action-expires" );
375
376 $expiryFormOptions = '';
377 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
378 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action] );
379 $d = $wgLang->date( $this->mExistingExpiry[$action] );
380 $t = $wgLang->time( $this->mExistingExpiry[$action] );
381 $expiryFormOptions .=
382 Xml::option(
383 wfMsg( 'protect-existing-expiry', $timestamp, $d, $t ),
384 'existing',
385 $this->mExpirySelection[$action] == 'existing'
386 ) . "\n";
387 }
388
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);
395 }
396 $show = htmlspecialchars($show);
397 $value = htmlspecialchars($value);
398 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
399 }
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>";
417 }
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>";
434 }
435 # Give extensions a chance to add items to the form
436 wfRunHooks( 'ProtectionForm::buildForm', array($this->mArticle,&$out) );
437
438 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
439
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' );
452 }
453
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' => 255 ) ) .
474 "</td>
475 </tr>";
476 # Disallow watching is user is not logged in
477 if( $wgUser->isLoggedIn() ) {
478 $out .= "
479 <tr>
480 <td></td>
481 <td class='mw-input'>" .
482 Xml::checkLabel( wfMsg( 'watchthis' ),
483 'mwProtectWatch', 'mwProtectWatch',
484 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
485 "</td>
486 </tr>";
487 }
488 $out .= "
489 <tr>
490 <td></td>
491 <td class='mw-submit'>" .
492 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
493 "</td>
494 </tr>\n";
495 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
496 }
497 $out .= Xml::closeElement( 'fieldset' );
498
499 if ( $wgUser->isAllowed( 'editinterface' ) ) {
500 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
501 $link = $wgUser->getSkin()->link(
502 $title,
503 wfMsgHtml( 'protect-edit-reasonlist' ),
504 array(),
505 array( 'action' => 'edit' )
506 );
507 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
508 }
509
510 if ( !$this->disabled ) {
511 $out .= Xml::closeElement( 'form' );
512 $wgOut->addScript( $this->buildCleanupScript() );
513 }
514
515 return $out;
516 }
517
518 /**
519 * Build protection level selector
520 *
521 * @param $action String: action to protect
522 * @param $selected String: current protection level
523 * @return String: HTML fragment
524 */
525 function buildSelector( $action, $selected ) {
526 global $wgRestrictionLevels, $wgUser;
527
528 $levels = array();
529 foreach( $wgRestrictionLevels as $key ) {
530 //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
531 if( $key == 'sysop' ) {
532 //special case, rewrite sysop to protect and editprotected
533 if( !$wgUser->isAllowed('protect') && !$wgUser->isAllowed('editprotected') && !$this->disabled )
534 continue;
535 } else {
536 if( !$wgUser->isAllowed($key) && !$this->disabled )
537 continue;
538 }
539 $levels[] = $key;
540 }
541
542 $id = 'mwProtect-level-' . $action;
543 $attribs = array(
544 'id' => $id,
545 'name' => $id,
546 'size' => count( $levels ),
547 'onchange' => 'ProtectionForm.updateLevels(this)',
548 ) + $this->disabledAttrib;
549
550 $out = Xml::openElement( 'select', $attribs );
551 foreach( $levels as $key ) {
552 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
553 }
554 $out .= Xml::closeElement( 'select' );
555 return $out;
556 }
557
558 /**
559 * Prepare the label for a protection selector option
560 *
561 * @param $permission String: permission required
562 * @return String
563 */
564 private function getOptionLabel( $permission ) {
565 if( $permission == '' ) {
566 return wfMsg( 'protect-default' );
567 } else {
568 $key = "protect-level-{$permission}";
569 $msg = wfMsg( $key );
570 if( wfEmptyMsg( $key, $msg ) )
571 $msg = wfMsg( 'protect-fallback', $permission );
572 return $msg;
573 }
574 }
575
576 function buildCleanupScript() {
577 global $wgRestrictionLevels, $wgGroupPermissions;
578 $script = 'var wgCascadeableLevels=';
579 $CascadeableLevels = array();
580 foreach( $wgRestrictionLevels as $key ) {
581 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
582 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
583 }
584 }
585 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
586 $options = (object)array(
587 'tableId' => 'mwProtectSet',
588 'labelText' => wfMsg( 'protect-unchain-permissions' ),
589 'numTypes' => count($this->mApplicableTypes),
590 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
591 );
592 $encOptions = Xml::encodeJsVar( $options );
593
594 $script .= "ProtectionForm.init($encOptions)";
595 return Html::inlineScript( "if ( window.mediaWiki ) { $script }" );
596 }
597
598 /**
599 * Show protection long extracts for this page
600 *
601 * @param $out OutputPage
602 * @access private
603 */
604 function showLogExtract( &$out ) {
605 # Show relevant lines from the protection log:
606 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
607 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
608 # Let extensions add other relevant log extracts
609 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );
610 }
611 }