MediaWiki REL1_34
ProtectionForm.php
Go to the documentation of this file.
1<?php
26
32 protected $mRestrictions = [];
33
35 protected $mReason = '';
36
38 protected $mReasonSelection = '';
39
41 protected $mCascade = false;
42
44 protected $mExpiry = [];
45
50 protected $mExpirySelection = [];
51
53 protected $mPermErrors = [];
54
56 protected $mApplicableTypes = [];
57
59 protected $mExistingExpiry = [];
60
62 protected $mArticle;
63
65 protected $mTitle;
66
68 protected $disabled;
69
71 protected $disabledAttrib;
72
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
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
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
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
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
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
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(
337 $status->getWikiText( false, false, $this->mContext->getLanguage() )
338 ) );
339 return false;
340 }
341
348 $errorMsg = '';
349 if ( !Hooks::run( 'ProtectionForm::save', [ $this->mArticle, &$errorMsg, $reasonstr ] ) ) {
350 if ( $errorMsg == '' ) {
351 $errorMsg = [ 'hookaborted' ];
352 }
353 }
354 if ( $errorMsg != '' ) {
355 $this->show( $errorMsg );
356 return false;
357 }
358
359 WatchAction::doWatchOrUnwatch( $request->getCheck( 'mwProtectWatch' ), $this->mTitle, $user );
360
361 return true;
362 }
363
369 function buildForm() {
371 $user = $context->getUser();
372 $output = $context->getOutput();
373 $lang = $context->getLanguage();
374 $out = '';
375 if ( !$this->disabled ) {
376 $output->addModules( 'mediawiki.legacy.protect' );
377 $out .= Xml::openElement( 'form', [ 'method' => 'post',
378 'action' => $this->mTitle->getLocalURL( 'action=protect' ),
379 'id' => 'mw-Protect-Form' ] );
380 }
381
382 $out .= Xml::openElement( 'fieldset' ) .
383 Xml::element( 'legend', null, $context->msg( 'protect-legend' )->text() ) .
384 Xml::openElement( 'table', [ 'id' => 'mwProtectSet' ] ) .
385 Xml::openElement( 'tbody' );
386
387 $scExpiryOptions = wfMessage( 'protect-expiry-options' )->inContentLanguage()->text();
388 $showProtectOptions = $scExpiryOptions !== '-' && !$this->disabled;
389
390 // Not all languages have V_x <-> N_x relation
391 foreach ( $this->mRestrictions as $action => $selected ) {
392 // Messages:
393 // restriction-edit, restriction-move, restriction-create, restriction-upload
394 $msg = $context->msg( 'restriction-' . $action );
395 $out .= "<tr><td>" .
396 Xml::openElement( 'fieldset' ) .
397 Xml::element( 'legend', null, $msg->exists() ? $msg->text() : $action ) .
398 Xml::openElement( 'table', [ 'id' => "mw-protect-table-$action" ] ) .
399 "<tr><td>" . $this->buildSelector( $action, $selected ) . "</td></tr><tr><td>";
400
401 $mProtectexpiry = Xml::label(
402 $context->msg( 'protectexpiry' )->text(),
403 "mwProtectExpirySelection-$action"
404 );
405 $mProtectother = Xml::label(
406 $context->msg( 'protect-othertime' )->text(),
407 "mwProtect-$action-expires"
408 );
409
410 $expiryFormOptions = new XmlSelect(
411 "wpProtectExpirySelection-$action",
412 "mwProtectExpirySelection-$action",
413 $this->mExpirySelection[$action]
414 );
415 $expiryFormOptions->setAttribute( 'tabindex', '2' );
416 if ( $this->disabled ) {
417 $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
418 }
419
420 if ( $this->mExistingExpiry[$action] ) {
421 if ( $this->mExistingExpiry[$action] == 'infinity' ) {
422 $existingExpiryMessage = $context->msg( 'protect-existing-expiry-infinity' );
423 } else {
424 $timestamp = $lang->userTimeAndDate( $this->mExistingExpiry[$action], $user );
425 $d = $lang->userDate( $this->mExistingExpiry[$action], $user );
426 $t = $lang->userTime( $this->mExistingExpiry[$action], $user );
427 $existingExpiryMessage = $context->msg(
428 'protect-existing-expiry',
429 $timestamp,
430 $d,
431 $t
432 );
433 }
434 $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
435 }
436
437 $expiryFormOptions->addOption(
438 $context->msg( 'protect-othertime-op' )->text(),
439 'othertime'
440 );
441 foreach ( explode( ',', $scExpiryOptions ) as $option ) {
442 if ( strpos( $option, ":" ) === false ) {
443 $show = $value = $option;
444 } else {
445 list( $show, $value ) = explode( ":", $option );
446 }
447 $expiryFormOptions->addOption( $show, htmlspecialchars( $value ) );
448 }
449 # Add expiry dropdown
450 if ( $showProtectOptions && !$this->disabled ) {
451 $out .= "
452 <table><tr>
453 <td class='mw-label'>
454 {$mProtectexpiry}
455 </td>
456 <td class='mw-input'>" .
457 $expiryFormOptions->getHTML() .
458 "</td>
459 </tr></table>";
460 }
461 # Add custom expiry field
462 $attribs = [ 'id' => "mwProtect-$action-expires" ] + $this->disabledAttrib;
463 $out .= "<table><tr>
464 <td class='mw-label'>" .
465 $mProtectother .
466 '</td>
467 <td class="mw-input">' .
468 Xml::input( "mwProtect-expiry-$action", 50, $this->mExpiry[$action], $attribs ) .
469 '</td>
470 </tr></table>';
471 $out .= "</td></tr>" .
472 Xml::closeElement( 'table' ) .
473 Xml::closeElement( 'fieldset' ) .
474 "</td></tr>";
475 }
476 # Give extensions a chance to add items to the form
477 Hooks::run( 'ProtectionForm::buildForm', [ $this->mArticle, &$out ] );
478
479 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
480
481 // JavaScript will add another row with a value-chaining checkbox
482 if ( $this->mTitle->exists() ) {
483 $out .= Xml::openElement( 'table', [ 'id' => 'mw-protect-table2' ] ) .
484 Xml::openElement( 'tbody' );
485 $out .= '<tr>
486 <td></td>
487 <td class="mw-input">' .
488 Xml::checkLabel(
489 $context->msg( 'protect-cascade' )->text(),
490 'mwProtect-cascade',
491 'mwProtect-cascade',
492 $this->mCascade, $this->disabledAttrib
493 ) .
494 "</td>
495 </tr>\n";
496 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
497 }
498
499 # Add manual and custom reason field/selects as well as submit
500 if ( !$this->disabled ) {
501 $mProtectreasonother = Xml::label(
502 $context->msg( 'protectcomment' )->text(),
503 'wpProtectReasonSelection'
504 );
505
506 $mProtectreason = Xml::label(
507 $context->msg( 'protect-otherreason' )->text(),
508 'mwProtect-reason'
509 );
510
511 $reasonDropDown = Xml::listDropDown( 'wpProtectReasonSelection',
512 wfMessage( 'protect-dropdown' )->inContentLanguage()->text(),
513 wfMessage( 'protect-otherreason-op' )->inContentLanguage()->text(),
514 $this->mReasonSelection,
515 'mwProtect-reason', 4 );
516
517 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
518 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
519 // Unicode codepoints.
520 // Subtract arbitrary 75 to leave some space for the autogenerated null edit's summary
521 // and other texts chosen by dropdown menus on this page.
522 $maxlength = CommentStore::COMMENT_CHARACTER_LIMIT - 75;
523
524 $out .= Xml::openElement( 'table', [ 'id' => 'mw-protect-table3' ] ) .
525 Xml::openElement( 'tbody' );
526 $out .= "
527 <tr>
528 <td class='mw-label'>
529 {$mProtectreasonother}
530 </td>
531 <td class='mw-input'>
532 {$reasonDropDown}
533 </td>
534 </tr>
535 <tr>
536 <td class='mw-label'>
537 {$mProtectreason}
538 </td>
539 <td class='mw-input'>" .
540 Xml::input( 'mwProtect-reason', 60, $this->mReason, [ 'type' => 'text',
541 'id' => 'mwProtect-reason', 'maxlength' => $maxlength ] ) .
542 "</td>
543 </tr>";
544 # Disallow watching is user is not logged in
545 if ( $user->isLoggedIn() ) {
546 $out .= "
547 <tr>
548 <td></td>
549 <td class='mw-input'>" .
550 Xml::checkLabel( $context->msg( 'watchthis' )->text(),
551 'mwProtectWatch', 'mwProtectWatch',
552 $user->isWatched( $this->mTitle ) || $user->getOption( 'watchdefault' ) ) .
553 "</td>
554 </tr>";
555 }
556 $out .= "
557 <tr>
558 <td></td>
559 <td class='mw-submit'>" .
560 Xml::submitButton(
561 $context->msg( 'confirm' )->text(),
562 [ 'id' => 'mw-Protect-submit' ]
563 ) .
564 "</td>
565 </tr>\n";
566 $out .= Xml::closeElement( 'tbody' ) . Xml::closeElement( 'table' );
567 }
568 $out .= Xml::closeElement( 'fieldset' );
569
570 if ( MediaWikiServices::getInstance()->getPermissionManager()
571 ->userHasRight( $user, 'editinterface' ) ) {
572 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
573 $link = $linkRenderer->makeKnownLink(
574 $context->msg( 'protect-dropdown' )->inContentLanguage()->getTitle(),
575 $context->msg( 'protect-edit-reasonlist' )->text(),
576 [],
577 [ 'action' => 'edit' ]
578 );
579 $out .= '<p class="mw-protect-editreasons">' . $link . '</p>';
580 }
581
582 if ( !$this->disabled ) {
583 $out .= Html::hidden(
584 'wpEditToken',
585 $user->getEditToken( [ 'protect', $this->mTitle->getPrefixedDBkey() ] )
586 );
587 $out .= Xml::closeElement( 'form' );
588 }
589
590 return $out;
591 }
592
600 function buildSelector( $action, $selected ) {
601 // If the form is disabled, display all relevant levels. Otherwise,
602 // just show the ones this user can use.
603 $levels = MediaWikiServices::getInstance()
604 ->getPermissionManager()
605 ->getNamespaceRestrictionLevels(
606 $this->mTitle->getNamespace(),
607 $this->disabled ? null : $this->mContext->getUser()
608 );
609
610 $id = 'mwProtect-level-' . $action;
611
612 $select = new XmlSelect( $id, $id, $selected );
613 $select->setAttribute( 'size', count( $levels ) );
614 if ( $this->disabled ) {
615 $select->setAttribute( 'disabled', 'disabled' );
616 }
617
618 foreach ( $levels as $key ) {
619 $select->addOption( $this->getOptionLabel( $key ), $key );
620 }
621
622 return $select->getHTML();
623 }
624
631 private function getOptionLabel( $permission ) {
632 if ( $permission == '' ) {
633 return $this->mContext->msg( 'protect-default' )->text();
634 } else {
635 // Messages: protect-level-autoconfirmed, protect-level-sysop
636 $msg = $this->mContext->msg( "protect-level-{$permission}" );
637 if ( $msg->exists() ) {
638 return $msg->text();
639 }
640 return $this->mContext->msg( 'protect-fallback', $permission )->text();
641 }
642 }
643
649 private function showLogExtract( OutputPage $out ) {
650 # Show relevant lines from the protection log:
651 $protectLogPage = new LogPage( 'protect' );
652 $out->addHTML( Xml::element( 'h2', null, $protectLogPage->getName()->text() ) );
653 LogEventsList::showLogExtract( $out, 'protect', $this->mTitle );
654 # Let extensions add other relevant log extracts
655 Hooks::run( 'ProtectionForm::showLogExtract', [ $this->mArticle, $out ] );
656 }
657}
getPermissionManager()
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfIsInfinity( $str)
Determine input string is represents as infinity.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Class for viewing MediaWiki article and history.
Definition Article.php:38
getContext()
Gets the context this Article is executed in.
Definition Article.php:2267
getTitle()
Get the title object of the article.
Definition Article.php:221
An error page which can definitely be safely rendered using the OutputPage.
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Class to simplify the use of log pages.
Definition LogPage.php:33
MediaWikiServices is the service locator for the application scope of MediaWiki.
This is one of the Core classes and should be read at least once by any new developers.
addHTML( $text)
Append $text to the body HTML.
Handles the page protection UI and backend.
__construct(Article $article)
execute()
Main entry point for action=protect and action=unprotect.
loadData()
Loads the current state of protection into the object.
buildSelector( $action, $selected)
Build protection level selector.
getOptionLabel( $permission)
Prepare the label for a protection selector option.
array $mApplicableTypes
Types (i.e.
array $mRestrictions
A map of action to restriction level, from request or default.
array $mExistingExpiry
Map of action to the expiry time of the existing protection.
string $mReasonSelection
The reason selected from the list, blank for other/additional.
bool $mCascade
True if the restrictions are cascading, from request or existing protection.
array $mExpirySelection
Map of action to value selected in expiry drop-down list.
IContextSource $mContext
buildForm()
Build the input form.
string $mReason
The custom/additional protection reason.
show( $err=null)
Show the input form with optional error message.
array $mExpiry
Map of action to "other" expiry time.
save()
Save submitted protection form.
showLogExtract(OutputPage $out)
Show protection long extracts for this page.
array $mPermErrors
Permissions errors for the protect action.
getExpiry( $action)
Get the expiry time for a given action, by combining the relevant inputs.
Represents a title within MediaWiki.
Definition Title.php:42
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
Class for generating HTML <select> or <datalist> elements.
Definition XmlSelect.php:26
Interface for objects which can provide a MediaWiki context on request.
$context
Definition load.php:45
if(!isset( $args[0])) $lang