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