Add support for Number grouping(commafy) based on CLDR number grouping patterns like...
[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;
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 $titleLink = Linker::link( $this->mTitle );
227 $wgOut->setPageTitle( wfMsg( 'protect-title', $this->mTitle->getPrefixedText() ) );
228 $wgOut->setSubtitle( wfMsg( 'protect-backlink', $titleLink ) );
229
230 # Show an appropriate message if the user isn't allowed or able to change
231 # the protection settings at this time
232 if( $this->disabled ) {
233 if( wfReadOnly() ) {
234 $wgOut->readOnlyPage();
235 } elseif( $this->mPermErrors ) {
236 $wgOut->showPermissionsErrorPage( $this->mPermErrors );
237 }
238 } else {
239 $wgOut->addWikiMsg( 'protect-text',
240 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
241 }
242
243 $wgOut->addHTML( $this->buildForm() );
244
245 $this->showLogExtract( $wgOut );
246 }
247
248 /**
249 * Save submitted protection form
250 *
251 * @return Boolean: success
252 */
253 function save() {
254 global $wgRequest, $wgUser;
255
256 # Permission check!
257 if ( $this->disabled ) {
258 $this->show();
259 return false;
260 }
261
262 $token = $wgRequest->getVal( 'wpEditToken' );
263 if ( !$wgUser->matchEditToken( $token ) ) {
264 $this->show( wfMsg( 'sessionfailure' ) );
265 return false;
266 }
267
268 # Create reason string. Use list and/or custom string.
269 $reasonstr = $this->mReasonSelection;
270 if ( $reasonstr != 'other' && $this->mReason != '' ) {
271 // Entry from drop down menu + additional comment
272 $reasonstr .= wfMsgForContent( 'colon-separator' ) . $this->mReason;
273 } elseif ( $reasonstr == 'other' ) {
274 $reasonstr = $this->mReason;
275 }
276 $expiry = array();
277 foreach( $this->mApplicableTypes as $action ) {
278 $expiry[$action] = $this->getExpiry( $action );
279 if( empty($this->mRestrictions[$action]) )
280 continue; // unprotected
281 if ( !$expiry[$action] ) {
282 $this->show( wfMsg( 'protect_expiry_invalid' ) );
283 return false;
284 }
285 if ( $expiry[$action] < wfTimestampNow() ) {
286 $this->show( wfMsg( 'protect_expiry_old' ) );
287 return false;
288 }
289 }
290
291 # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
292 # to a semi-protected page.
293 global $wgGroupPermissions;
294
295 $edit_restriction = isset( $this->mRestrictions['edit'] ) ? $this->mRestrictions['edit'] : '';
296 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
297 if ($this->mCascade && ($edit_restriction != 'protect') &&
298 !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'] ) )
299 $this->mCascade = false;
300
301 if ($this->mTitle->exists()) {
302 $ok = $this->mArticle->updateRestrictions( $this->mRestrictions, $reasonstr, $this->mCascade, $expiry );
303 } else {
304 $ok = $this->mTitle->updateTitleProtection( $this->mRestrictions['create'], $reasonstr, $expiry['create'] );
305 }
306
307 if( !$ok ) {
308 throw new FatalError( "Unknown error at restriction save time." );
309 }
310
311 $errorMsg = '';
312 # Give extensions a change to handle added form items
313 if( !wfRunHooks( 'ProtectionForm::save', array($this->mArticle,&$errorMsg) ) ) {
314 throw new FatalError( "Unknown hook error at restriction save time." );
315 }
316 if( $errorMsg != '' ) {
317 $this->show( $errorMsg );
318 return false;
319 }
320
321 if ( $wgRequest->getCheck( 'mwProtectWatch' ) && $wgUser->isLoggedIn() ) {
322 WatchAction::doWatch( $this->mTitle, $wgUser );
323 } elseif ( $this->mTitle->userIsWatching() ) {
324 WatchAction::doUnwatch( $this->mTitle, $wgUser );
325 }
326 return $ok;
327 }
328
329 /**
330 * Build the input form
331 *
332 * @return String: HTML form
333 */
334 function buildForm() {
335 global $wgUser, $wgLang, $wgOut;
336
337 $mProtectreasonother = Xml::label( wfMsg( 'protectcomment' ), 'wpProtectReasonSelection' );
338 $mProtectreason = Xml::label( wfMsg( 'protect-otherreason' ), 'mwProtect-reason' );
339
340 $out = '';
341 if( !$this->disabled ) {
342 $wgOut->addModules( 'mediawiki.legacy.protect' );
343 $out .= Xml::openElement( 'form', array( 'method' => 'post',
344 'action' => $this->mTitle->getLocalUrl( 'action=protect' ),
345 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
346 $out .= Html::hidden( 'wpEditToken',$wgUser->editToken() );
347 }
348
349 $out .= Xml::openElement( 'fieldset' ) .
350 Xml::element( 'legend', null, wfMsg( 'protect-legend' ) ) .
351 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
352 Xml::openElement( 'tbody' );
353
354 foreach( $this->mRestrictions as $action => $selected ) {
355 /* Not all languages have V_x <-> N_x relation */
356 $msg = wfMessage( 'restriction-' . $action );
357 $out .= "<tr><td>".
358 Xml::openElement( 'fieldset' ) .
359 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
360 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
361 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
362
363 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
364 wfMsgForContent( 'protect-dropdown' ),
365 wfMsgForContent( 'protect-otherreason-op' ),
366 $this->mReasonSelection,
367 'mwProtect-reason', 4 );
368 $scExpiryOptions = wfMsgForContent( 'protect-expiry-options' );
369
370 $showProtectOptions = ($scExpiryOptions !== '-' && !$this->disabled);
371
372 $mProtectexpiry = Xml::label( wfMsg( 'protectexpiry' ), "mwProtectExpirySelection-$action" );
373 $mProtectother = Xml::label( wfMsg( 'protect-othertime' ), "mwProtect-$action-expires" );
374
375 $expiryFormOptions = '';
376 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
377 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action], true );
378 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
379 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
380 $expiryFormOptions .=
381 Xml::option(
382 wfMsg( 'protect-existing-expiry', $timestamp, $d, $t ),
383 'existing',
384 $this->mExpirySelection[$action] == 'existing'
385 ) . "\n";
386 }
387
388 $expiryFormOptions .= Xml::option( wfMsg( 'protect-othertime-op' ), "othertime" ) . "\n";
389 foreach( explode(',', $scExpiryOptions) as $option ) {
390 if ( strpos($option, ":") === false ) {
391 $show = $value = $option;
392 } else {
393 list($show, $value) = explode(":", $option);
394 }
395 $show = htmlspecialchars($show);
396 $value = htmlspecialchars($value);
397 $expiryFormOptions .= Xml::option( $show, $value, $this->mExpirySelection[$action] === $value ) . "\n";
398 }
399 # Add expiry dropdown
400 if( $showProtectOptions && !$this->disabled ) {
401 $out .= "
402 <table><tr>
403 <td class='mw-label'>
404 {$mProtectexpiry}
405 </td>
406 <td class='mw-input'>" .
407 Xml::tags( 'select',
408 array(
409 'id' => "mwProtectExpirySelection-$action",
410 'name' => "wpProtectExpirySelection-$action",
411 'onchange' => "ProtectionForm.updateExpiryList(this)",
412 'tabindex' => '2' ) + $this->disabledAttrib,
413 $expiryFormOptions ) .
414 "</td>
415 </tr></table>";
416 }
417 # Add custom expiry field
418 $attribs = array( 'id' => "mwProtect-$action-expires",
419 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
420 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
421 $out .= "<table><tr>
422 <td class='mw-label'>" .
423 $mProtectother .
424 '</td>
425 <td class="mw-input">' .
426 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
427 '</td>
428 </tr></table>';
429 $out .= "</td></tr>" .
430 Xml::closeElement( 'table' ) .
431 Xml::closeElement( 'fieldset' ) .
432 "</td></tr>";
433 }
434 # Give extensions a chance to add items to the form
435 wfRunHooks( 'ProtectionForm::buildForm', array($this->mArticle,&$out) );
436
437 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
438
439 // JavaScript will add another row with a value-chaining checkbox
440 if( $this->mTitle->exists() ) {
441 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
442 Xml::openElement( 'tbody' );
443 $out .= '<tr>
444 <td></td>
445 <td class="mw-input">' .
446 Xml::checkLabel( wfMsg( 'protect-cascade' ), 'mwProtect-cascade', 'mwProtect-cascade',
447 $this->mCascade, $this->disabledAttrib ) .
448 "</td>
449 </tr>\n";
450 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
451 }
452
453 # Add manual and custom reason field/selects as well as submit
454 if( !$this->disabled ) {
455 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
456 Xml::openElement( 'tbody' );
457 $out .= "
458 <tr>
459 <td class='mw-label'>
460 {$mProtectreasonother}
461 </td>
462 <td class='mw-input'>
463 {$reasonDropDown}
464 </td>
465 </tr>
466 <tr>
467 <td class='mw-label'>
468 {$mProtectreason}
469 </td>
470 <td class='mw-input'>" .
471 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
472 'id' => 'mwProtect-reason', 'maxlength' => 180 ) ) .
473 // Limited maxlength as the database trims at 255 bytes and other texts
474 // chosen by dropdown menus on this page are also included in this database field.
475 // The byte limit of 180 bytes is enforced in javascript
476 "</td>
477 </tr>";
478 # Disallow watching is user is not logged in
479 if( $wgUser->isLoggedIn() ) {
480 $out .= "
481 <tr>
482 <td></td>
483 <td class='mw-input'>" .
484 Xml::checkLabel( wfMsg( 'watchthis' ),
485 'mwProtectWatch', 'mwProtectWatch',
486 $this->mTitle->userIsWatching() || $wgUser->getOption( 'watchdefault' ) ) .
487 "</td>
488 </tr>";
489 }
490 $out .= "
491 <tr>
492 <td></td>
493 <td class='mw-submit'>" .
494 Xml::submitButton( wfMsg( 'confirm' ), array( 'id' => 'mw-Protect-submit' ) ) .
495 "</td>
496 </tr>\n";
497 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
498 }
499 $out .= Xml::closeElement( 'fieldset' );
500
501 if ( $wgUser->isAllowed( 'editinterface' ) ) {
502 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
503 $link = Linker::link(
504 $title,
505 wfMsgHtml( 'protect-edit-reasonlist' ),
506 array(),
507 array( 'action' => 'edit' )
508 );
509 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
510 }
511
512 if ( !$this->disabled ) {
513 $out .= Xml::closeElement( 'form' );
514 $wgOut->addScript( $this->buildCleanupScript() );
515 }
516
517 return $out;
518 }
519
520 /**
521 * Build protection level selector
522 *
523 * @param $action String: action to protect
524 * @param $selected String: current protection level
525 * @return String: HTML fragment
526 */
527 function buildSelector( $action, $selected ) {
528 global $wgRestrictionLevels, $wgUser;
529
530 $levels = array();
531 foreach( $wgRestrictionLevels as $key ) {
532 //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
533 if( $key == 'sysop' ) {
534 //special case, rewrite sysop to protect and editprotected
535 if( !$wgUser->isAllowedAny( 'protect', 'editprotected' ) && !$this->disabled )
536 continue;
537 } else {
538 if( !$wgUser->isAllowed($key) && !$this->disabled )
539 continue;
540 }
541 $levels[] = $key;
542 }
543
544 $id = 'mwProtect-level-' . $action;
545 $attribs = array(
546 'id' => $id,
547 'name' => $id,
548 'size' => count( $levels ),
549 'onchange' => 'ProtectionForm.updateLevels(this)',
550 ) + $this->disabledAttrib;
551
552 $out = Xml::openElement( 'select', $attribs );
553 foreach( $levels as $key ) {
554 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
555 }
556 $out .= Xml::closeElement( 'select' );
557 return $out;
558 }
559
560 /**
561 * Prepare the label for a protection selector option
562 *
563 * @param $permission String: permission required
564 * @return String
565 */
566 private function getOptionLabel( $permission ) {
567 if( $permission == '' ) {
568 return wfMsg( 'protect-default' );
569 } else {
570 $msg = wfMessage( "protect-level-{$permission}" );
571 if( $msg->exists() ) {
572 return $msg->text();
573 }
574 return wfMsg( 'protect-fallback', $permission );
575 }
576 }
577
578 function buildCleanupScript() {
579 global $wgRestrictionLevels, $wgGroupPermissions;
580 $script = 'var wgCascadeableLevels=';
581 $CascadeableLevels = array();
582 foreach( $wgRestrictionLevels as $key ) {
583 if ( (isset($wgGroupPermissions[$key]['protect']) && $wgGroupPermissions[$key]['protect']) || $key == 'protect' ) {
584 $CascadeableLevels[] = "'" . Xml::escapeJsString( $key ) . "'";
585 }
586 }
587 $script .= "[" . implode(',',$CascadeableLevels) . "];\n";
588 $options = (object)array(
589 'tableId' => 'mwProtectSet',
590 'labelText' => wfMsg( 'protect-unchain-permissions' ),
591 'numTypes' => count($this->mApplicableTypes),
592 'existingMatch' => 1 == count( array_unique( $this->mExistingExpiry ) ),
593 );
594 $encOptions = Xml::encodeJsVar( $options );
595
596 $script .= "ProtectionForm.init($encOptions)";
597 return Html::inlineScript( "if ( window.mediaWiki ) { $script }" );
598 }
599
600 /**
601 * Show protection long extracts for this page
602 *
603 * @param $out OutputPage
604 * @access private
605 */
606 function showLogExtract( &$out ) {
607 # Show relevant lines from the protection log:
608 $out->addHTML( Xml::element( 'h2', null, LogPage::logName( 'protect' ) ) );
609 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle->getPrefixedText() );
610 # Let extensions add other relevant log extracts
611 wfRunHooks( 'ProtectionForm::showLogExtract', array($this->mArticle,$out) );
612 }
613 }