Collapse duplicate $existingExpiry == 'infinity' case into else
[lhc/web/wiklou.git] / includes / ProtectionForm.php
1 <?php
2 /**
3 * Page protection
4 *
5 * Copyright © 2005 Brion Vibber <brion@pobox.com>
6 * https://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 /** @var array A map of action to restriction level, from request or default */
31 protected $mRestrictions = array();
32
33 /** @var string The custom/additional protection reason */
34 protected $mReason = '';
35
36 /** @var string The reason selected from the list, blank for other/additional */
37 protected $mReasonSelection = '';
38
39 /** @var bool True if the restrictions are cascading, from request or existing protection */
40 protected $mCascade = false;
41
42 /** @var array Map of action to "other" expiry time. Used in preference to mExpirySelection. */
43 protected $mExpiry = array();
44
45 /**
46 * @var array Map of action to value selected in expiry drop-down list.
47 * Will be set to 'othertime' whenever mExpiry is set.
48 */
49 protected $mExpirySelection = array();
50
51 /** @var array Permissions errors for the protect action */
52 protected $mPermErrors = array();
53
54 /** @var array Types (i.e. actions) for which levels can be selected */
55 protected $mApplicableTypes = array();
56
57 /** @var array Map of action to the expiry time of the existing protection */
58 protected $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 if ( wfReadOnly() ) {
71 $this->mPermErrors[] = array( 'readonlytext', wfReadOnlyReason() );
72 }
73 $this->disabled = $this->mPermErrors != array();
74 $this->disabledAttrib = $this->disabled
75 ? array( 'disabled' => 'disabled' )
76 : array();
77
78 $this->loadData();
79 }
80
81 /**
82 * Loads the current state of protection into the object.
83 */
84 function loadData() {
85 global $wgRequest, $wgUser;
86
87 $levels = MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace(), $wgUser );
88 $this->mCascade = $this->mTitle->areRestrictionsCascading();
89
90 $this->mReason = $wgRequest->getText( 'mwProtect-reason' );
91 $this->mReasonSelection = $wgRequest->getText( 'wpProtectReasonSelection' );
92 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade', $this->mCascade );
93
94 foreach ( $this->mApplicableTypes as $action ) {
95 // @todo FIXME: This form currently requires individual selections,
96 // but the db allows multiples separated by commas.
97
98 // Pull the actual restriction from the DB
99 $this->mRestrictions[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
100
101 if ( !$this->mRestrictions[$action] ) {
102 // No existing expiry
103 $existingExpiry = '';
104 } else {
105 $existingExpiry = $this->mTitle->getRestrictionExpiry( $action );
106 }
107 $this->mExistingExpiry[$action] = $existingExpiry;
108
109 $requestExpiry = $wgRequest->getText( "mwProtect-expiry-$action" );
110 $requestExpirySelection = $wgRequest->getVal( "wpProtectExpirySelection-$action" );
111
112 if ( $requestExpiry ) {
113 // Custom expiry takes precedence
114 $this->mExpiry[$action] = $requestExpiry;
115 $this->mExpirySelection[$action] = 'othertime';
116 } elseif ( $requestExpirySelection ) {
117 // Expiry selected from list
118 $this->mExpiry[$action] = '';
119 $this->mExpirySelection[$action] = $requestExpirySelection;
120 } elseif ( $existingExpiry ) {
121 // Use existing expiry in its own list item
122 $this->mExpiry[$action] = '';
123 $this->mExpirySelection[$action] = $existingExpiry;
124 } else {
125 // Catches 'infinity' - Existing expiry is infinite, use "infinite" in drop-down
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, $levels ) ) {
133 $this->mRestrictions[$action] = $val;
134 }
135 }
136 }
137
138 /**
139 * Get the expiry time for a given action, by combining the relevant inputs.
140 *
141 * @param string $action
142 *
143 * @return string 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 = wfGetDB( DB_SLAVE )->getInfinity();
155 } else {
156 $unix = strtotime( $value );
157
158 if ( !$unix || $unix === -1 ) {
159 return false;
160 }
161
162 // @todo 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 /**
170 * Main entry point for action=protect and action=unprotect
171 */
172 function execute() {
173 global $wgRequest, $wgOut;
174
175 if ( MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace() ) === array( '' ) ) {
176 throw new ErrorPageError( 'protect-badnamespace-title', 'protect-badnamespace-text' );
177 }
178
179 if ( $wgRequest->wasPosted() ) {
180 if ( $this->save() ) {
181 $q = $this->mArticle->isRedirect() ? 'redirect=no' : '';
182 $wgOut->redirect( $this->mTitle->getFullURL( $q ) );
183 }
184 } else {
185 $this->show();
186 }
187 }
188
189 /**
190 * Show the input form with optional error message
191 *
192 * @param string $err Error message or null if there's no error
193 */
194 function show( $err = null ) {
195 global $wgOut;
196
197 $wgOut->setRobotPolicy( 'noindex,nofollow' );
198 $wgOut->addBacklinkSubtitle( $this->mTitle );
199
200 if ( is_array( $err ) ) {
201 $wgOut->wrapWikiMsg( "<p class='error'>\n$1\n</p>\n", $err );
202 } elseif ( is_string( $err ) ) {
203 $wgOut->addHTML( "<p class='error'>{$err}</p>\n" );
204 }
205
206 if ( $this->mTitle->getRestrictionTypes() === array() ) {
207 // No restriction types available for the current title
208 // this might happen if an extension alters the available types
209 $wgOut->setPageTitle( wfMessage(
210 'protect-norestrictiontypes-title',
211 $this->mTitle->getPrefixedText()
212 ) );
213 $wgOut->addWikiText( wfMessage( 'protect-norestrictiontypes-text' )->text() );
214
215 // Show the log in case protection was possible once
216 $this->showLogExtract( $wgOut );
217 // return as there isn't anything else we can do
218 return;
219 }
220
221 list( $cascadeSources, /* $restrictions */ ) = $this->mTitle->getCascadeProtectionSources();
222 if ( $cascadeSources && count( $cascadeSources ) > 0 ) {
223 $titles = '';
224
225 foreach ( $cascadeSources as $title ) {
226 $titles .= '* [[:' . $title->getPrefixedText() . "]]\n";
227 }
228
229 /** @todo FIXME: i18n issue, should use formatted number. */
230 $wgOut->wrapWikiMsg(
231 "<div id=\"mw-protect-cascadeon\">\n$1\n" . $titles . "</div>",
232 array( 'protect-cascadeon', count( $cascadeSources ) )
233 );
234 }
235
236 # Show an appropriate message if the user isn't allowed or able to change
237 # the protection settings at this time
238 if ( $this->disabled ) {
239 $wgOut->setPageTitle(
240 wfMessage( 'protect-title-notallowed',
241 $this->mTitle->getPrefixedText() )
242 );
243 $wgOut->addWikiText( $wgOut->formatPermissionsErrorMessage( $this->mPermErrors, 'protect' ) );
244 } else {
245 $wgOut->setPageTitle( wfMessage( 'protect-title', $this->mTitle->getPrefixedText() ) );
246 $wgOut->addWikiMsg( 'protect-text',
247 wfEscapeWikiText( $this->mTitle->getPrefixedText() ) );
248 }
249
250 $wgOut->addHTML( $this->buildForm() );
251 $this->showLogExtract( $wgOut );
252 }
253
254 /**
255 * Save submitted protection form
256 *
257 * @return bool Success
258 */
259 function save() {
260 global $wgRequest, $wgUser, $wgOut;
261
262 # Permission check!
263 if ( $this->disabled ) {
264 $this->show();
265 return false;
266 }
267
268 $token = $wgRequest->getVal( 'wpEditToken' );
269 if ( !$wgUser->matchEditToken( $token, array( 'protect', $this->mTitle->getPrefixedDBkey() ) ) ) {
270 $this->show( array( 'sessionfailure' ) );
271 return false;
272 }
273
274 # Create reason string. Use list and/or custom string.
275 $reasonstr = $this->mReasonSelection;
276 if ( $reasonstr != 'other' && $this->mReason != '' ) {
277 // Entry from drop down menu + additional comment
278 $reasonstr .= wfMessage( 'colon-separator' )->text() . $this->mReason;
279 } elseif ( $reasonstr == 'other' ) {
280 $reasonstr = $this->mReason;
281 }
282 $expiry = array();
283 foreach ( $this->mApplicableTypes as $action ) {
284 $expiry[$action] = $this->getExpiry( $action );
285 if ( empty( $this->mRestrictions[$action] ) ) {
286 continue; // unprotected
287 }
288 if ( !$expiry[$action] ) {
289 $this->show( array( 'protect_expiry_invalid' ) );
290 return false;
291 }
292 if ( $expiry[$action] < wfTimestampNow() ) {
293 $this->show( array( 'protect_expiry_old' ) );
294 return false;
295 }
296 }
297
298 $this->mCascade = $wgRequest->getBool( 'mwProtect-cascade' );
299
300 $status = $this->mArticle->doUpdateRestrictions(
301 $this->mRestrictions,
302 $expiry,
303 $this->mCascade,
304 $reasonstr,
305 $wgUser
306 );
307
308 if ( !$status->isOK() ) {
309 $this->show( $wgOut->parseInline( $status->getWikiText() ) );
310 return false;
311 }
312
313 /**
314 * Give extensions a change to handle added form items
315 *
316 * @since 1.19 you can (and you should) return false to abort saving;
317 * you can also return an array of message name and its parameters
318 */
319 $errorMsg = '';
320 if ( !wfRunHooks( 'ProtectionForm::save', array( $this->mArticle, &$errorMsg, $reasonstr ) ) ) {
321 if ( $errorMsg == '' ) {
322 $errorMsg = array( 'hookaborted' );
323 }
324 }
325 if ( $errorMsg != '' ) {
326 $this->show( $errorMsg );
327 return false;
328 }
329
330 WatchAction::doWatchOrUnwatch( $wgRequest->getCheck( 'mwProtectWatch' ), $this->mTitle, $wgUser );
331
332 return true;
333 }
334
335 /**
336 * Build the input form
337 *
338 * @return string HTML form
339 */
340 function buildForm() {
341 global $wgUser, $wgLang, $wgOut;
342
343 $mProtectreasonother = Xml::label(
344 wfMessage( 'protectcomment' )->text(),
345 'wpProtectReasonSelection'
346 );
347 $mProtectreason = Xml::label(
348 wfMessage( 'protect-otherreason' )->text(),
349 'mwProtect-reason'
350 );
351
352 $out = '';
353 if ( !$this->disabled ) {
354 $wgOut->addModules( 'mediawiki.legacy.protect' );
355 $out .= Xml::openElement( 'form', array( 'method' => 'post',
356 'action' => $this->mTitle->getLocalURL( 'action=protect' ),
357 'id' => 'mw-Protect-Form', 'onsubmit' => 'ProtectionForm.enableUnchainedInputs(true)' ) );
358 }
359
360 $out .= Xml::openElement( 'fieldset' ) .
361 Xml::element( 'legend', null, wfMessage( 'protect-legend' )->text() ) .
362 Xml::openElement( 'table', array( 'id' => 'mwProtectSet' ) ) .
363 Xml::openElement( 'tbody' );
364
365 // Not all languages have V_x <-> N_x relation
366 foreach ( $this->mRestrictions as $action => $selected ) {
367 // Messages:
368 // restriction-edit, restriction-move, restriction-create, restriction-upload
369 $msg = wfMessage( 'restriction-' . $action );
370 $out .= "<tr><td>" .
371 Xml::openElement( 'fieldset' ) .
372 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
373 Xml::openElement( 'table', array( 'id' => "mw-protect-table-$action" ) ) .
374 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
375
376 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
377 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
378 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
379 $this->mReasonSelection,
380 'mwProtect-reason', 4 );
381 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
382
383 $showProtectOptions = $scExpiryOptions !== '-' && !$this->disabled;
384
385 $mProtectexpiry = Xml::label(
386 wfMessage( 'protectexpiry' )->text(),
387 "mwProtectExpirySelection-$action"
388 );
389 $mProtectother = Xml::label(
390 wfMessage( 'protect-othertime' )->text(),
391 "mwProtect-$action-expires"
392 );
393
394 $expiryFormOptions = '';
395 if ( $this->mExistingExpiry[$action] && $this->mExistingExpiry[$action] != 'infinity' ) {
396 $timestamp = $wgLang->timeanddate( $this->mExistingExpiry[$action], true );
397 $d = $wgLang->date( $this->mExistingExpiry[$action], true );
398 $t = $wgLang->time( $this->mExistingExpiry[$action], true );
399 $expiryFormOptions .=
400 Xml::option(
401 wfMessage( 'protect-existing-expiry', $timestamp, $d, $t )->text(),
402 'existing',
403 $this->mExpirySelection[$action] == 'existing'
404 ) . "\n";
405 }
406
407 $expiryFormOptions .= Xml::option(
408 wfMessage( 'protect-othertime-op' )->text(),
409 "othertime"
410 ) . "\n";
411 foreach ( explode( ',', $scExpiryOptions ) as $option ) {
412 if ( strpos( $option, ":" ) === false ) {
413 $show = $value = $option;
414 } else {
415 list( $show, $value ) = explode( ":", $option );
416 }
417 $show = htmlspecialchars( $show );
418 $value = htmlspecialchars( $value );
419 $expiryFormOptions .= Xml::option(
420 $show,
421 $value,
422 $this->mExpirySelection[$action] === $value
423 ) . "\n";
424 }
425 # Add expiry dropdown
426 if ( $showProtectOptions && !$this->disabled ) {
427 $out .= "
428 <table><tr>
429 <td class='mw-label'>
430 {$mProtectexpiry}
431 </td>
432 <td class='mw-input'>" .
433 Xml::tags( 'select',
434 array(
435 'id' => "mwProtectExpirySelection-$action",
436 'name' => "wpProtectExpirySelection-$action",
437 'onchange' => "ProtectionForm.updateExpiryList(this)",
438 'tabindex' => '2' ) + $this->disabledAttrib,
439 $expiryFormOptions ) .
440 "</td>
441 </tr></table>";
442 }
443 # Add custom expiry field
444 $attribs = array( 'id' => "mwProtect-$action-expires",
445 'onkeyup' => 'ProtectionForm.updateExpiry(this)',
446 'onchange' => 'ProtectionForm.updateExpiry(this)' ) + $this->disabledAttrib;
447 $out .= "<table><tr>
448 <td class='mw-label'>" .
449 $mProtectother .
450 '</td>
451 <td class="mw-input">' .
452 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
453 '</td>
454 </tr></table>';
455 $out .= "</td></tr>" .
456 Xml::closeElement( 'table' ) .
457 Xml::closeElement( 'fieldset' ) .
458 "</td></tr>";
459 }
460 # Give extensions a chance to add items to the form
461 wfRunHooks( 'ProtectionForm::buildForm', array( $this->mArticle, &$out ) );
462
463 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
464
465 // JavaScript will add another row with a value-chaining checkbox
466 if ( $this->mTitle->exists() ) {
467 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table2' ) ) .
468 Xml::openElement( 'tbody' );
469 $out .= '<tr>
470 <td></td>
471 <td class="mw-input">' .
472 Xml::checkLabel(
473 wfMessage( 'protect-cascade' )->text(),
474 'mwProtect-cascade',
475 'mwProtect-cascade',
476 $this->mCascade, $this->disabledAttrib
477 ) .
478 "</td>
479 </tr>\n";
480 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
481 }
482
483 # Add manual and custom reason field/selects as well as submit
484 if ( !$this->disabled ) {
485 $out .= Xml::openElement( 'table', array( 'id' => 'mw-protect-table3' ) ) .
486 Xml::openElement( 'tbody' );
487 $out .= "
488 <tr>
489 <td class='mw-label'>
490 {$mProtectreasonother}
491 </td>
492 <td class='mw-input'>
493 {$reasonDropDown}
494 </td>
495 </tr>
496 <tr>
497 <td class='mw-label'>
498 {$mProtectreason}
499 </td>
500 <td class='mw-input'>" .
501 Xml::input( 'mwProtect-reason', 60, $this->mReason, array( 'type' => 'text',
502 'id' => 'mwProtect-reason', 'maxlength' => 180 ) ) .
503 // Limited maxlength as the database trims at 255 bytes and other texts
504 // chosen by dropdown menus on this page are also included in this database field.
505 // The byte limit of 180 bytes is enforced in javascript
506 "</td>
507 </tr>";
508 # Disallow watching is user is not logged in
509 if ( $wgUser->isLoggedIn() ) {
510 $out .= "
511 <tr>
512 <td></td>
513 <td class='mw-input'>" .
514 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
515 'mwProtectWatch', 'mwProtectWatch',
516 $wgUser->isWatched( $this->mTitle ) || $wgUser->getOption( 'watchdefault' ) ) .
517 "</td>
518 </tr>";
519 }
520 $out .= "
521 <tr>
522 <td></td>
523 <td class='mw-submit'>" .
524 Xml::submitButton(
525 wfMessage( 'confirm' )->text(),
526 array( 'id' => 'mw-Protect-submit' )
527 ) .
528 "</td>
529 </tr>\n";
530 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
531 }
532 $out .= Xml::closeElement( 'fieldset' );
533
534 if ( $wgUser->isAllowed( 'editinterface' ) ) {
535 $title = Title::makeTitle( NS_MEDIAWIKI, 'Protect-dropdown' );
536 $link = Linker::link(
537 $title,
538 wfMessage( 'protect-edit-reasonlist' )->escaped(),
539 array(),
540 array( 'action' => 'edit' )
541 );
542 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
543 }
544
545 if ( !$this->disabled ) {
546 $out .= Html::hidden(
547 'wpEditToken',
548 $wgUser->getEditToken( array( 'protect', $this->mTitle->getPrefixedDBkey() ) )
549 );
550 $out .= Xml::closeElement( 'form' );
551 $wgOut->addScript( $this->buildCleanupScript() );
552 }
553
554 return $out;
555 }
556
557 /**
558 * Build protection level selector
559 *
560 * @param string $action Action to protect
561 * @param string $selected Current protection level
562 * @return string HTML fragment
563 */
564 function buildSelector( $action, $selected ) {
565 global $wgUser;
566
567 // If the form is disabled, display all relevant levels. Otherwise,
568 // just show the ones this user can use.
569 $levels = MWNamespace::getRestrictionLevels( $this->mTitle->getNamespace(),
570 $this->disabled ? null : $wgUser
571 );
572
573 $id = 'mwProtect-level-' . $action;
574 $attribs = array(
575 'id' => $id,
576 'name' => $id,
577 'size' => count( $levels ),
578 'onchange' => 'ProtectionForm.updateLevels(this)',
579 ) + $this->disabledAttrib;
580
581 $out = Xml::openElement( 'select', $attribs );
582 foreach ( $levels as $key ) {
583 $out .= Xml::option( $this->getOptionLabel( $key ), $key, $key == $selected );
584 }
585 $out .= Xml::closeElement( 'select' );
586 return $out;
587 }
588
589 /**
590 * Prepare the label for a protection selector option
591 *
592 * @param string $permission Permission required
593 * @return string
594 */
595 private function getOptionLabel( $permission ) {
596 if ( $permission == '' ) {
597 return wfMessage( 'protect-default' )->text();
598 } else {
599 // Messages: protect-level-autoconfirmed, protect-level-sysop
600 $msg = wfMessage( "protect-level-{$permission}" );
601 if ( $msg->exists() ) {
602 return $msg->text();
603 }
604 return wfMessage( 'protect-fallback', $permission )->text();
605 }
606 }
607
608 function buildCleanupScript() {
609 global $wgCascadingRestrictionLevels, $wgOut;
610
611 $cascadeableLevels = $wgCascadingRestrictionLevels;
612 $options = array(
613 'tableId' => 'mwProtectSet',
614 'labelText' => wfMessage( 'protect-unchain-permissions' )->plain(),
615 'numTypes' => count( $this->mApplicableTypes ),
616 'existingMatch' => count( array_unique( $this->mExistingExpiry ) ) === 1,
617 );
618
619 $wgOut->addJsConfigVars( 'wgCascadeableLevels', $cascadeableLevels );
620 $script = Xml::encodeJsCall( 'ProtectionForm.init', array( $options ) );
621 return Html::inlineScript( ResourceLoader::makeLoaderConditionalScript( $script ) );
622 }
623
624 /**
625 * Show protection long extracts for this page
626 *
627 * @param OutputPage $out
628 * @access private
629 */
630 function showLogExtract( &$out ) {
631 # Show relevant lines from the protection log:
632 $protectLogPage = new LogPage( 'protect' );
633 $out->addHTML( Xml::element( 'h2', null, $protectLogPage->getName()->text() ) );
634 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle );
635 # Let extensions add other relevant log extracts
636 wfRunHooks( 'ProtectionForm::showLogExtract', array( $this->mArticle, $out ) );
637 }
638 }