Fux PHP Notice: Undefined property: ContribsPager::$showSizeDiff in /www/w/includes...
[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( Page $article ) {
61 global $wgUser;
62 // Set instance variables.
63 $this->mArticle = $article;
64 $this->mTitle = $article->getTitle();
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 // @todo 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 * @param $action string
151 *
152 * @return string 14-char timestamp or "infinity", or false if the input was invalid
153 */
154 function getExpiry( $action ) {
155 if ( $this->mExpirySelection[$action] == 'existing' ) {
156 return $this->mExistingExpiry[$action];
157 } elseif ( $this->mExpirySelection[$action] == 'othertime' ) {
158 $value = $this->mExpiry[$action];
159 } else {
160 $value = $this->mExpirySelection[$action];
161 }
162 if ( $value == 'infinite' || $value == 'indefinite' || $value == 'infinity' ) {
163 $time = wfGetDB( DB_SLAVE )->getInfinity();
164 } else {
165 $unix = strtotime( $value );
166
167 if ( !$unix || $unix === -1 ) {
168 return false;
169 }
170
171 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
172 // and there isn't notice about it in the ui
173 $time = wfTimestamp( TS_MW, $unix );
174 }
175 return $time;
176 }
177
178 /**
179 * Main entry point for action=protect and action=unprotect
180 */
181 function execute() {
182 global $wgRequest, $wgOut;
183 if( $wgRequest->wasPosted() ) {
184 if( $this->save() ) {
185 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
186 $wgOut->redirect( $this->mTitle->getFullUrl( $q ) );
187 }
188 } else {
189 $this->show();
190 }
191 }
192
193 /**
194 * Show the input form with optional error message
195 *
196 * @param $err String: error message or null if there's no error
197 */
198 function show( $err = null ) {
199 global $wgOut, $wgUser;
200
201 $wgOut->setRobotPolicy( 'noindex,nofollow' );
202
203 if( is_null( $this->mTitle ) ||
204 $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
205 $wgOut->showFatalError( wfMsg( 'badarticleerror' ) );
206 return;
207 }
208
209 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
210
211 if ( $err != "" ) {
212 $wgOut->setSubtitle( wfMsgHtml( 'formerror' ) );
213 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
214 }
215
216 if ( $cascadeSources && count($cascadeSources) > 0 ) {
217 $titles = '';
218
219 foreach ( $cascadeSources as $title ) {
220 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
221 }
222
223 $wgOut->wrapWikiMsg( "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>", array( 'protect-cascadeon', count($cascadeSources) ) );
224 }
225
226 $sk = $wgUser->getSkin();
227 $titleLink = $sk->link( $this->mTitle );
228 $wgOut->setPageTitle( wfMsg( 'protect-title', $this->mTitle->getPrefixedText() ) );
229 $wgOut->setSubtitle( wfMsg( 'protect-backlink', $titleLink ) );
230
231 # Show an appropriate message if the user isn't allowed or able to change
232 # the protection settings at this time
233 if( $this->disabled ) {
234 if( wfReadOnly() ) {
235 $wgOut->readOnlyPage();
236 } elseif( $this->mPermErrors ) {
237 $wgOut->showPermissionsErrorPage( $this->mPermErrors );
238 }
239 } else {
240 $wgOut->addWikiMsg( 'protect-text',
241 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
242 }
243
244 $wgOut->addHTML( $this->buildForm() );
245
246 $this->showLogExtract( $wgOut );
247 }
248
249 /**
250 * Save submitted protection form
251 *
252 * @return Boolean: success
253 */
254 function save() {
255 global $wgRequest, $wgUser;
256
257 # Permission check!
258 if ( $this->disabled ) {
259 $this->show();
260 return false;
261 }
262
263 $token = $wgRequest->getVal( 'wpEditToken' );
264 if ( !$wgUser->matchEditToken( $token ) ) {
265 $this->show( wfMsg( 'sessionfailure' ) );
266 return false;
267 }
268
269 # Create reason string. Use list and/or custom string.
270 $reasonstr = $this->mReasonSelection;
271 if ( $reasonstr != 'other' && $this->mReason != '' ) {
272 // Entry from drop down menu + additional comment
273 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->mReason;
274 } elseif ( $reasonstr == 'other' ) {
275 $reasonstr = $this->mReason;
276 }
277 $expiry = array();
278 foreach( $this->mApplicableTypes as $action ) {
279 $expiry[$action] = $this->getExpiry( $action );
280 if( empty($this->mRestrictions[$action]) )
281 continue; // unprotected
282 if ( !$expiry[$action] ) {
283 $this->show( wfMsg( 'protect_expiry_invalid' ) );
284 return false;
285 }
286 if ( $expiry[$action] < wfTimestampNow() ) {
287 $this->show( wfMsg( 'protect_expiry_old' ) );
288 return false;
289 }
290 }
291
292 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
293 # to a semi-protected page.
294 global $wgGroupPermissions;
295
296 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
297 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
298 if ($this->mCascade && ($edit_restriction != 'protect') &&
299 !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'] ) )
300 $this->mCascade = false;
301
302 if ($this->mTitle->exists()) {
303 $ok = $this->mArticle->updateRestrictions( $this->mRestrictions, $reasonstr, $this->mCascade, $expiry );
304 } else {
305 $ok = $this->mTitle->updateTitleProtection( $this->mRestrictions['create'], $reasonstr, $expiry['create'] );
306 }
307
308 if( !$ok ) {
309 throw new FatalError( "Unknown error at restriction save time." );
310 }
311
312 $errorMsg = '';
313 # Give extensions a change to handle added form items
314 if( !wfRunHooks( 'ProtectionForm::save', array($this->mArticle,&$errorMsg) ) ) {
315 throw new FatalError( "Unknown hook error at restriction save time." );
316 }
317 if( $errorMsg != '' ) {
318 $this->show( $errorMsg );
319 return false;
320 }
321
322 if ( $wgRequest->getCheck( 'mwProtectWatch' ) && $wgUser->isLoggedIn() ) {
323 WatchAction::doWatch( $this->mTitle, $wgUser );
324 } elseif ( $this->mTitle->userIsWatching() ) {
325 WatchAction::doUnwatch( $this->mTitle, $wgUser );
326 }
327 return $ok;
328 }
329
330 /**
331 * Build the input form
332 *
333 * @return String: HTML form
334 */
335 function buildForm() {
336 global $wgUser, $wgLang, $wgOut;
337
338 $mProtectreasonother = Xml::label( wfMsg( 'protectcomment' ), 'wpProtectReasonSelection' );
339 $mProtectreason = Xml::label( wfMsg( 'protect-otherreason' ), 'mwProtect-reason' );
340
341 $out = '';
342 if( !$this->disabled ) {
343 $wgOut->addModules( 'mediawiki.legacy.protect' );
344 $out .= Xml::openElement( 'form', array( 'method' => 'post',
345 'action' => $this->mTitle->getLocalUrl( 'action=protect' ),
346 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
347 $out .= Html::hidden( 'wpEditToken',$wgUser->editToken() );
348 }
349
350 $out .= Xml::openElement( 'fieldset' ) .
351 Xml::element( 'legend', null, wfMsg( 'protect-legend' ) ) .
352 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
353 Xml::openElement( 'tbody' );
354
355 foreach( $this->mRestrictions as $action => $selected ) {
356 /* Not all languages have V_x <-> N_x relation */
357 $msg = wfMessage( 'restriction-' . $action );
358 $out .= "<tr><td>".
359 Xml::openElement( 'fieldset' ) .
360 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
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], true );
379 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
380 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
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' => 180 ) ) .
474 // Limited maxlength as the database trims at 255 bytes and other texts
475 // chosen by dropdown menus on this page are also included in this database field.
476 // The byte limit of 180 bytes is enforced in javascript
477 "</td>
478 </tr>";
479 # Disallow watching is user is not logged in
480 if( $wgUser->isLoggedIn() ) {
481 $out .= "
482 <tr>
483 <td></td>
484 <td class='mw-input'>" .
485 Xml::checkLabel( wfMsg( 'watchthis' ),
486 'mwProtectWatch', 'mwProtectWatch',
487 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
488 "</td>
489 </tr>";
490 }
491 $out .= "
492 <tr>
493 <td></td>
494 <td class='mw-submit'>" .
495 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
496 "</td>
497 </tr>\n";
498 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
499 }
500 $out .= Xml::closeElement( 'fieldset' );
501
502 if ( $wgUser->isAllowed( 'editinterface' ) ) {
503 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
504 $link = $wgUser->getSkin()->link(
505 $title,
506 wfMsgHtml( 'protect-edit-reasonlist' ),
507 array(),
508 array( 'action' => 'edit' )
509 );
510 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
511 }
512
513 if ( !$this->disabled ) {
514 $out .= Xml::closeElement( 'form' );
515 $wgOut->addScript( $this->buildCleanupScript() );
516 }
517
518 return $out;
519 }
520
521 /**
522 * Build protection level selector
523 *
524 * @param $action String: action to protect
525 * @param $selected String: current protection level
526 * @return String: HTML fragment
527 */
528 function buildSelector( $action, $selected ) {
529 global $wgRestrictionLevels, $wgUser;
530
531 $levels = array();
532 foreach( $wgRestrictionLevels as $key ) {
533 //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
534 if( $key == 'sysop' ) {
535 //special case, rewrite sysop to protect and editprotected
536 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) && !$this->disabled )
537 continue;
538 } else {
539 if( !$wgUser->isAllowed($key) && !$this->disabled )
540 continue;
541 }
542 $levels[] = $key;
543 }
544
545 $id = 'mwProtect-level-' . $action;
546 $attribs = array(
547 'id' => $id,
548 'name' => $id,
549 'size' => count( $levels ),
550 'onchange' => 'ProtectionForm.updateLevels(this)',
551 ) + $this->disabledAttrib;
552
553 $out = Xml::openElement( 'select', $attribs );
554 foreach( $levels as $key ) {
555 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
556 }
557 $out .= Xml::closeElement( 'select' );
558 return $out;
559 }
560
561 /**
562 * Prepare the label for a protection selector option
563 *
564 * @param $permission String: permission required
565 * @return String
566 */
567 private function getOptionLabel( $permission ) {
568 if( $permission == '' ) {
569 return wfMsg( 'protect-default' );
570 } else {
571 $msg = wfMessage( "protect-level-{$permission}" );
572 if( $msg->exists() ) {
573 return $msg->text();
574 }
575 return wfMsg( 'protect-fallback', $permission );
576 }
577 }
578
579 function buildCleanupScript() {
580 global $wgRestrictionLevels, $wgGroupPermissions;
581 $script = 'var wgCascadeableLevels=';
582 $CascadeableLevels = array();
583 foreach( $wgRestrictionLevels as $key ) {
584 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
585 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
586 }
587 }
588 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
589 $options = (object)array(
590 'tableId' => 'mwProtectSet',
591 'labelText' => wfMsg( 'protect-unchain-permissions' ),
592 'numTypes' => count($this->mApplicableTypes),
593 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
594 );
595 $encOptions = Xml::encodeJsVar( $options );
596
597 $script .= "ProtectionForm.init($encOptions)";
598 return Html::inlineScript( "if ( window.mediaWiki ) { $script }" );
599 }
600
601 /**
602 * Show protection long extracts for this page
603 *
604 * @param $out OutputPage
605 * @access private
606 */
607 function showLogExtract( &$out ) {
608 # Show relevant lines from the protection log:
609 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
610 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
611 # Let extensions add other relevant log extracts
612 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );
613 }
614 }