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