3 * Implements Special:Userrights
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
24 use MediaWiki\MediaWikiServices
;
27 * Special page to allow managing user group membership
29 * @ingroup SpecialPage
31 class UserrightsPage
extends SpecialPage
{
33 * The target of the local right-adjuster's interest. Can be gotten from
34 * either a GET parameter or a subpage-style parameter, so have a member
36 * @var null|string $mTarget
40 * @var null|User $mFetchedUser The user object of the target username or null.
42 protected $mFetchedUser = null;
43 protected $isself = false;
45 public function __construct() {
46 parent
::__construct( 'Userrights' );
49 public function doesWrites() {
54 * Check whether the current user (from context) can change the target user's rights.
56 * @param User $targetUser User whose rights are being changed
57 * @param bool $checkIfSelf If false, assume that the current user can add/remove groups defined
58 * in $wgGroupsAddToSelf / $wgGroupsRemoveFromSelf, without checking if it's the same as target
62 public function userCanChangeRights( $targetUser, $checkIfSelf = true ) {
63 $isself = $this->getUser()->equals( $targetUser );
65 $available = $this->changeableGroups();
66 if ( $targetUser->getId() === 0 ) {
70 if ( $available['add'] ||
$available['remove'] ) {
71 // can change some rights for any user
75 if ( ( $available['add-self'] ||
$available['remove-self'] )
76 && ( $isself ||
!$checkIfSelf )
78 // can change some rights for self
86 * Manage forms to be shown according to posted data.
87 * Depending on the submit button used, call a form or a save function.
89 * @param string|null $par String if any subpage provided, else null
90 * @throws UserBlockedError|PermissionsError
91 * @suppress PhanUndeclaredMethod
93 public function execute( $par ) {
94 $user = $this->getUser();
95 $request = $this->getRequest();
96 $session = $request->getSession();
97 $out = $this->getOutput();
99 $out->addModules( [ 'mediawiki.special.userrights' ] );
101 $this->mTarget
= $par ??
$request->getVal( 'user' );
103 if ( is_string( $this->mTarget
) ) {
104 $this->mTarget
= trim( $this->mTarget
);
107 if ( $this->mTarget
!== null && User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
108 $this->isself
= true;
111 $fetchedStatus = $this->fetchUser( $this->mTarget
, true );
112 if ( $fetchedStatus->isOK() ) {
113 $this->mFetchedUser
= $fetchedStatus->value
;
114 if ( $this->mFetchedUser
instanceof User
) {
115 // Set the 'relevant user' in the skin, so it displays links like Contributions,
116 // User logs, UserRights, etc.
117 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
121 // show a successbox, if the user rights was saved successfully
123 $session->get( 'specialUserrightsSaveSuccess' ) &&
124 $this->mFetchedUser
!== null
126 // Remove session data for the success message
127 $session->remove( 'specialUserrightsSaveSuccess' );
129 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
134 'class' => 'mw-notify-success successbox',
135 'id' => 'mw-preferences-success',
136 'data-mw-autohide' => 'false',
141 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
148 $this->outputHeader();
150 $out->addModuleStyles( 'mediawiki.special' );
151 $this->addHelpLink( 'Help:Assigning permissions' );
156 $request->wasPosted() &&
157 $request->getCheck( 'saveusergroups' ) &&
158 $this->mTarget
!== null &&
159 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
162 * If the user is blocked and they only have "partial" access
163 * (e.g. they don't have the userrights permission), then don't
164 * allow them to change any user rights.
166 if ( !MediaWikiServices
::getInstance()
167 ->getPermissionManager()
168 ->userHasRight( $user, 'userrights' )
170 $block = $user->getBlock();
171 if ( $block && $block->isSitewide() ) {
172 throw new UserBlockedError( $block );
176 $this->checkReadOnly();
179 if ( !$fetchedStatus->isOK() ) {
180 $this->getOutput()->addWikiTextAsInterface(
181 $fetchedStatus->getWikiText( false, false, $this->getLanguage() )
187 $targetUser = $this->mFetchedUser
;
188 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (T63252)
189 $targetUser->clearInstanceCache(); // T40989
192 $conflictCheck = $request->getVal( 'conflictcheck-originalgroups' );
193 $conflictCheck = ( $conflictCheck === '' ) ?
[] : explode( ',', $conflictCheck );
194 $userGroups = $targetUser->getGroups();
196 if ( $userGroups !== $conflictCheck ) {
197 $out->wrapWikiMsg( '<span class="error">$1</span>', 'userrights-conflict' );
199 $status = $this->saveUserGroups(
201 $request->getVal( 'user-reason' ),
205 if ( $status->isOK() ) {
206 // Set session data for the success message
207 $session->set( 'specialUserrightsSaveSuccess', 1 );
209 $out->redirect( $this->getSuccessURL() );
212 // Print an error message and redisplay the form
213 $out->wrapWikiTextAsInterface(
214 'error', $status->getWikiText( false, false, $this->getLanguage() )
220 // show some more forms
221 if ( $this->mTarget
!== null ) {
222 $this->editUserGroupsForm( $this->mTarget
);
226 function getSuccessURL() {
227 return $this->getPageTitle( $this->mTarget
)->getFullURL();
231 * Returns true if this user rights form can set and change user group expiries.
232 * Subclasses may wish to override this to return false.
236 public function canProcessExpiries() {
241 * Converts a user group membership expiry string into a timestamp. Words like
242 * 'existing' or 'other' should have been filtered out before calling this
245 * @param string $expiry
246 * @return string|null|false A string containing a valid timestamp, or null
247 * if the expiry is infinite, or false if the timestamp is not valid
249 public static function expiryToTimestamp( $expiry ) {
250 if ( wfIsInfinity( $expiry ) ) {
254 $unix = strtotime( $expiry );
256 if ( !$unix ||
$unix === -1 ) {
260 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
261 // and there isn't notice about it in the ui (see ProtectionForm::getExpiry)
262 return wfTimestamp( TS_MW
, $unix );
266 * Save user groups changes in the database.
267 * Data comes from the editUserGroupsForm() form function
269 * @param string $username Username to apply changes to.
270 * @param string $reason Reason for group change
271 * @param User|UserRightsProxy $user Target user object.
274 protected function saveUserGroups( $username, $reason, $user ) {
275 $allgroups = $this->getAllGroups();
277 $groupExpiries = []; // associative array of (group name => expiry)
279 $existingUGMs = $user->getGroupMemberships();
281 // This could possibly create a highly unlikely race condition if permissions are changed between
282 // when the form is loaded and when the form is saved. Ignoring it for the moment.
283 foreach ( $allgroups as $group ) {
284 // We'll tell it to remove all unchecked groups, and add all checked groups.
285 // Later on, this gets filtered for what can actually be removed
286 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
287 $addgroup[] = $group;
289 if ( $this->canProcessExpiries() ) {
290 // read the expiry information from the request
291 $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" );
292 if ( $expiryDropdown === 'existing' ) {
296 if ( $expiryDropdown === 'other' ) {
297 $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" );
299 $expiryValue = $expiryDropdown;
302 // validate the expiry
303 $groupExpiries[$group] = self
::expiryToTimestamp( $expiryValue );
305 if ( $groupExpiries[$group] === false ) {
306 return Status
::newFatal( 'userrights-invalid-expiry', $group );
309 // not allowed to have things expiring in the past
310 if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) {
311 return Status
::newFatal( 'userrights-expiry-in-past', $group );
314 // if the user can only add this group (not remove it), the expiry time
315 // cannot be brought forward (T156784)
316 if ( !$this->canRemove( $group ) &&
317 isset( $existingUGMs[$group] ) &&
318 ( $existingUGMs[$group]->getExpiry() ?
: 'infinity' ) >
319 ( $groupExpiries[$group] ?
: 'infinity' )
321 return Status
::newFatal( 'userrights-cannot-shorten-expiry', $group );
325 $removegroup[] = $group;
329 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries );
331 return Status
::newGood();
335 * Save user groups changes in the database. This function does not throw errors;
336 * instead, it ignores groups that the performer does not have permission to set.
338 * @param User|UserRightsProxy $user
339 * @param array $add Array of groups to add
340 * @param array $remove Array of groups to remove
341 * @param string $reason Reason for group change
342 * @param array $tags Array of change tags to add to the log entry
343 * @param array $groupExpiries Associative array of (group name => expiry),
344 * containing only those groups that are to have new expiry values set
345 * @return array Tuple of added, then removed groups
347 function doSaveUserGroups( $user, array $add, array $remove, $reason = '',
348 array $tags = [], array $groupExpiries = []
350 // Validate input set...
351 $isself = $user->getName() == $this->getUser()->getName();
352 $groups = $user->getGroups();
353 $ugms = $user->getGroupMemberships();
354 $changeable = $this->changeableGroups();
355 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
356 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
358 $remove = array_unique(
359 array_intersect( (array)$remove, $removable, $groups ) );
360 $add = array_intersect( (array)$add, $addable );
362 // add only groups that are not already present or that need their expiry updated,
363 // UNLESS the user can only add this group (not remove it) and the expiry time
364 // is being brought forward (T156784)
365 $add = array_filter( $add,
366 function ( $group ) use ( $groups, $groupExpiries, $removable, $ugms ) {
367 if ( isset( $groupExpiries[$group] ) &&
368 !in_array( $group, $removable ) &&
369 isset( $ugms[$group] ) &&
370 ( $ugms[$group]->getExpiry() ?
: 'infinity' ) >
371 ( $groupExpiries[$group] ?
: 'infinity' )
375 return !in_array( $group, $groups ) ||
array_key_exists( $group, $groupExpiries );
378 Hooks
::run( 'ChangeUserGroups', [ $this->getUser(), $user, &$add, &$remove ] );
380 $oldGroups = $groups;
381 $oldUGMs = $user->getGroupMemberships();
382 $newGroups = $oldGroups;
384 // Remove groups, then add new ones/update expiries of existing ones
386 foreach ( $remove as $index => $group ) {
387 if ( !$user->removeGroup( $group ) ) {
388 unset( $remove[$index] );
391 $newGroups = array_diff( $newGroups, $remove );
394 foreach ( $add as $index => $group ) {
395 $expiry = $groupExpiries[$group] ??
null;
396 if ( !$user->addGroup( $group, $expiry ) ) {
397 unset( $add[$index] );
400 $newGroups = array_merge( $newGroups, $add );
402 $newGroups = array_unique( $newGroups );
403 $newUGMs = $user->getGroupMemberships();
405 // Ensure that caches are cleared
406 $user->invalidateCache();
408 // update groups in external authentication database
409 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(),
410 $reason, $oldUGMs, $newUGMs ] );
412 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
413 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
414 wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) . "\n" );
415 wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) . "\n" );
417 // Only add a log entry if something actually changed
418 if ( $newGroups != $oldGroups ||
$newUGMs != $oldUGMs ) {
419 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs );
422 return [ $add, $remove ];
426 * Serialise a UserGroupMembership object for storage in the log_params section
427 * of the logging table. Only keeps essential data, removing redundant fields.
429 * @param UserGroupMembership|null $ugm May be null if things get borked
432 protected static function serialiseUgmForLog( $ugm ) {
433 if ( !$ugm instanceof UserGroupMembership
) {
436 return [ 'expiry' => $ugm->getExpiry() ];
440 * Add a rights log entry for an action.
441 * @param User|UserRightsProxy $user
442 * @param array $oldGroups
443 * @param array $newGroups
444 * @param string $reason
445 * @param array $tags Change tags for the log entry
446 * @param array $oldUGMs Associative array of (group name => UserGroupMembership)
447 * @param array $newUGMs Associative array of (group name => UserGroupMembership)
449 protected function addLogEntry( $user, array $oldGroups, array $newGroups, $reason,
450 array $tags, array $oldUGMs, array $newUGMs
452 // make sure $oldUGMs and $newUGMs are in the same order, and serialise
453 // each UGM object to a simplified array
454 $oldUGMs = array_map( function ( $group ) use ( $oldUGMs ) {
455 return isset( $oldUGMs[$group] ) ?
456 self
::serialiseUgmForLog( $oldUGMs[$group] ) :
459 $newUGMs = array_map( function ( $group ) use ( $newUGMs ) {
460 return isset( $newUGMs[$group] ) ?
461 self
::serialiseUgmForLog( $newUGMs[$group] ) :
465 $logEntry = new ManualLogEntry( 'rights', 'rights' );
466 $logEntry->setPerformer( $this->getUser() );
467 $logEntry->setTarget( $user->getUserPage() );
468 $logEntry->setComment( $reason );
469 $logEntry->setParameters( [
470 '4::oldgroups' => $oldGroups,
471 '5::newgroups' => $newGroups,
472 'oldmetadata' => $oldUGMs,
473 'newmetadata' => $newUGMs,
475 $logid = $logEntry->insert();
476 if ( count( $tags ) ) {
477 $logEntry->addTags( $tags );
479 $logEntry->publish( $logid );
483 * Edit user groups membership
484 * @param string $username Name of the user.
486 function editUserGroupsForm( $username ) {
487 $status = $this->fetchUser( $username, true );
488 if ( !$status->isOK() ) {
489 $this->getOutput()->addWikiTextAsInterface(
490 $status->getWikiText( false, false, $this->getLanguage() )
496 /** @var User $user */
497 $user = $status->value
;
498 '@phan-var User $user';
500 $groups = $user->getGroups();
501 $groupMemberships = $user->getGroupMemberships();
502 $this->showEditUserGroupsForm( $user, $groups, $groupMemberships );
504 // This isn't really ideal logging behavior, but let's not hide the
505 // interwiki logs if we're using them as is.
506 $this->showLogFragment( $user, $this->getOutput() );
510 * Normalize the input username, which may be local or remote, and
511 * return a user (or proxy) object for manipulating it.
513 * Side effects: error output for invalid access
514 * @param string $username
515 * @param bool $writing
518 public function fetchUser( $username, $writing = true ) {
519 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
520 if ( count( $parts ) < 2 ) {
521 $name = trim( $username );
524 list( $name, $dbDomain ) = array_map( 'trim', $parts );
526 if ( WikiMap
::isCurrentWikiId( $dbDomain ) ) {
529 if ( $writing && !MediaWikiServices
::getInstance()
530 ->getPermissionManager()
531 ->userHasRight( $this->getUser(), 'userrights-interwiki' )
533 return Status
::newFatal( 'userrights-no-interwiki' );
535 if ( !UserRightsProxy
::validDatabase( $dbDomain ) ) {
536 return Status
::newFatal( 'userrights-nodatabase', $dbDomain );
541 if ( $name === '' ) {
542 return Status
::newFatal( 'nouserspecified' );
545 if ( $name[0] == '#' ) {
546 // Numeric ID can be specified...
547 // We'll do a lookup for the name internally.
548 $id = intval( substr( $name, 1 ) );
550 if ( $dbDomain == '' ) {
551 $name = User
::whoIs( $id );
553 $name = UserRightsProxy
::whoIs( $dbDomain, $id );
557 return Status
::newFatal( 'noname' );
560 $name = User
::getCanonicalName( $name );
561 if ( $name === false ) {
563 return Status
::newFatal( 'nosuchusershort', $username );
567 if ( $dbDomain == '' ) {
568 $user = User
::newFromName( $name );
570 $user = UserRightsProxy
::newFromName( $dbDomain, $name );
573 if ( !$user ||
$user->isAnon() ) {
574 return Status
::newFatal( 'nosuchusershort', $username );
577 return Status
::newGood( $user );
587 public function makeGroupNameList( $ids ) {
588 if ( empty( $ids ) ) {
589 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
591 return implode( ', ', $ids );
596 * Output a form to allow searching for a user
598 function switchForm() {
599 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
601 $this->getOutput()->addHTML(
606 'action' => wfScript(),
608 'id' => 'mw-userrights-form1'
611 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
612 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
614 $this->msg( 'userrights-user-editname' )->text(),
618 str_replace( '_', ' ', $this->mTarget
),
620 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
622 // Set autofocus on blank input and error input
623 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
627 $this->msg( 'editusergroup' )->text()
629 Html
::closeElement( 'fieldset' ) .
630 Html
::closeElement( 'form' ) . "\n"
635 * Show the form to edit group memberships.
637 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
638 * @param array $groups Array of groups the user is in. Not used by this implementation
639 * anymore, but kept for backward compatibility with subclasses
640 * @param array $groupMemberships Associative array of (group name => UserGroupMembership
641 * object) containing the groups the user is in
643 protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) {
644 $list = $membersList = $tempList = $tempMembersList = [];
645 foreach ( $groupMemberships as $ugm ) {
646 $linkG = UserGroupMembership
::getLink( $ugm, $this->getContext(), 'html' );
647 $linkM = UserGroupMembership
::getLink( $ugm, $this->getContext(), 'html',
649 if ( $ugm->getExpiry() ) {
650 $tempList[] = $linkG;
651 $tempMembersList[] = $linkM;
654 $membersList[] = $linkM;
660 $autoMembersList = [];
661 if ( $user instanceof User
) {
662 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
663 $autoList[] = UserGroupMembership
::getLink( $group, $this->getContext(), 'html' );
664 $autoMembersList[] = UserGroupMembership
::getLink( $group, $this->getContext(),
665 'html', $user->getName() );
669 $language = $this->getLanguage();
670 $displayedList = $this->msg( 'userrights-groupsmember-type' )
672 $language->commaList( array_merge( $tempList, $list ) ),
673 $language->commaList( array_merge( $tempMembersList, $membersList ) )
675 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
677 $language->commaList( $autoList ),
678 $language->commaList( $autoMembersList )
682 $count = count( $list ) +
count( $tempList );
684 $grouplist = $this->msg( 'userrights-groupsmember' )
685 ->numParams( $count )
686 ->params( $user->getName() )
688 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
691 $count = count( $autoList );
693 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
694 ->numParams( $count )
695 ->params( $user->getName() )
697 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
700 $userToolLinks = Linker
::userToolLinks(
703 false, /* default for redContribsWhenNoEdits */
704 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
707 list( $groupCheckboxes, $canChangeAny ) =
708 $this->groupCheckboxes( $groupMemberships, $user );
709 $this->getOutput()->addHTML(
714 'action' => $this->getPageTitle()->getLocalURL(),
715 'name' => 'editGroup',
716 'id' => 'mw-userrights-form2'
719 Html
::hidden( 'user', $this->mTarget
) .
720 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
722 'conflictcheck-originalgroups',
723 implode( ',', $user->getGroups() )
724 ) . // Conflict detection
725 Xml
::openElement( 'fieldset' ) .
730 $canChangeAny ?
'userrights-editusergroup' : 'userrights-viewusergroup',
735 $canChangeAny ?
'editinguser' : 'viewinguserrights'
736 )->params( wfEscapeWikiText( $user->getName() ) )
737 ->rawParams( $userToolLinks )->parse()
739 if ( $canChangeAny ) {
740 $this->getOutput()->addHTML(
741 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
744 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
746 <td class='mw-label'>" .
747 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
749 <td class='mw-input'>" .
750 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ), [
752 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
753 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
754 // Unicode codepoints.
755 'maxlength' => CommentStore
::COMMENT_CHARACTER_LIMIT
,
761 <td class='mw-submit'>" .
762 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
763 [ 'name' => 'saveusergroups' ] +
764 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
768 Xml
::closeElement( 'table' ) . "\n"
771 $this->getOutput()->addHTML( $grouplist );
773 $this->getOutput()->addHTML(
774 Xml
::closeElement( 'fieldset' ) .
775 Xml
::closeElement( 'form' ) . "\n"
780 * Returns an array of all groups that may be edited
781 * @return array Array of groups that may be edited.
783 protected static function getAllGroups() {
784 return User
::getAllGroups();
788 * Adds a table with checkboxes where you can select what groups to add/remove
790 * @param UserGroupMembership[] $usergroups Associative array of (group name as string =>
791 * UserGroupMembership object) for groups the user belongs to
793 * @return array Array with 2 elements: the XHTML table element with checkxboes, and
794 * whether any groups are changeable
796 private function groupCheckboxes( $usergroups, $user ) {
797 $allgroups = $this->getAllGroups();
800 // Get the list of preset expiry times from the system message
801 $expiryOptionsMsg = $this->msg( 'userrights-expiry-options' )->inContentLanguage();
802 $expiryOptions = $expiryOptionsMsg->isDisabled() ?
804 explode( ',', $expiryOptionsMsg->text() );
806 // Put all column info into an associative array so that extensions can
807 // more easily manage it.
808 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
810 foreach ( $allgroups as $group ) {
811 $set = isset( $usergroups[$group] );
812 // Users who can add the group, but not remove it, can only lengthen
813 // expiries, not shorten them. So they should only see the expiry
814 // dropdown if the group currently has a finite expiry
815 $canOnlyLengthenExpiry = ( $set && $this->canAdd( $group ) &&
816 !$this->canRemove( $group ) && $usergroups[$group]->getExpiry() );
817 // Should the checkbox be disabled?
818 $disabledCheckbox = !(
819 ( $set && $this->canRemove( $group ) ) ||
820 ( !$set && $this->canAdd( $group ) ) );
821 // Should the expiry elements be disabled?
822 $disabledExpiry = $disabledCheckbox && !$canOnlyLengthenExpiry;
823 // Do we need to point out that this action is irreversible?
824 $irreversible = !$disabledCheckbox && (
825 ( $set && !$this->canAdd( $group ) ) ||
826 ( !$set && !$this->canRemove( $group ) ) );
830 'disabled' => $disabledCheckbox,
831 'disabled-expiry' => $disabledExpiry,
832 'irreversible' => $irreversible
835 if ( $disabledCheckbox && $disabledExpiry ) {
836 $columns['unchangeable'][$group] = $checkbox;
838 $columns['changeable'][$group] = $checkbox;
842 // Build the HTML table
843 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
845 foreach ( $columns as $name => $column ) {
846 if ( $column === [] ) {
849 // Messages: userrights-changeable-col, userrights-unchangeable-col
850 $ret .= Xml
::element(
853 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
857 $ret .= "</tr>\n<tr>\n";
858 foreach ( $columns as $column ) {
859 if ( $column === [] ) {
862 $ret .= "\t<td style='vertical-align:top;'>\n";
863 foreach ( $column as $group => $checkbox ) {
864 $attr = [ 'class' => 'mw-userrights-groupcheckbox' ];
865 if ( $checkbox['disabled'] ) {
866 $attr['disabled'] = 'disabled';
869 $member = UserGroupMembership
::getGroupMemberName( $group, $user->getName() );
870 if ( $checkbox['irreversible'] ) {
871 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
872 } elseif ( $checkbox['disabled'] && !$checkbox['disabled-expiry'] ) {
873 $text = $this->msg( 'userrights-no-shorten-expiry-marker', $member )->text();
877 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
878 "wpGroup-" . $group, $checkbox['set'], $attr );
880 if ( $this->canProcessExpiries() ) {
881 $uiUser = $this->getUser();
882 $uiLanguage = $this->getLanguage();
884 $currentExpiry = isset( $usergroups[$group] ) ?
885 $usergroups[$group]->getExpiry() :
888 // If the user can't modify the expiry, print the current expiry below
889 // it in plain text. Otherwise provide UI to set/change the expiry
890 if ( $checkbox['set'] &&
891 ( $checkbox['irreversible'] ||
$checkbox['disabled-expiry'] )
893 if ( $currentExpiry ) {
894 $expiryFormatted = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
895 $expiryFormattedD = $uiLanguage->userDate( $currentExpiry, $uiUser );
896 $expiryFormattedT = $uiLanguage->userTime( $currentExpiry, $uiUser );
897 $expiryHtml = $this->msg( 'userrights-expiry-current' )->params(
898 $expiryFormatted, $expiryFormattedD, $expiryFormattedT )->text();
900 $expiryHtml = $this->msg( 'userrights-expiry-none' )->text();
902 // T171345: Add a hidden form element so that other groups can still be manipulated,
903 // otherwise saving errors out with an invalid expiry time for this group.
904 $expiryHtml .= Html
::hidden( "wpExpiry-$group",
905 $currentExpiry ?
'existing' : 'infinite' );
906 $expiryHtml .= "<br />\n";
908 $expiryHtml = Xml
::element( 'span', null,
909 $this->msg( 'userrights-expiry' )->text() );
910 $expiryHtml .= Xml
::openElement( 'span' );
912 // add a form element to set the expiry date
913 $expiryFormOptions = new XmlSelect(
915 "mw-input-wpExpiry-$group", // forward compatibility with HTMLForm
916 $currentExpiry ?
'existing' : 'infinite'
918 if ( $checkbox['disabled-expiry'] ) {
919 $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
922 if ( $currentExpiry ) {
923 $timestamp = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
924 $d = $uiLanguage->userDate( $currentExpiry, $uiUser );
925 $t = $uiLanguage->userTime( $currentExpiry, $uiUser );
926 $existingExpiryMessage = $this->msg( 'userrights-expiry-existing',
927 $timestamp, $d, $t );
928 $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
931 $expiryFormOptions->addOption(
932 $this->msg( 'userrights-expiry-none' )->text(),
935 $expiryFormOptions->addOption(
936 $this->msg( 'userrights-expiry-othertime' )->text(),
939 foreach ( $expiryOptions as $option ) {
940 if ( strpos( $option, ":" ) === false ) {
941 $displayText = $value = $option;
943 list( $displayText, $value ) = explode( ":", $option );
945 $expiryFormOptions->addOption( $displayText, htmlspecialchars( $value ) );
948 // Add expiry dropdown
949 $expiryHtml .= $expiryFormOptions->getHTML() . '<br />';
951 // Add custom expiry field
953 'id' => "mw-input-wpExpiry-$group-other",
954 'class' => 'mw-userrights-expiryfield',
956 if ( $checkbox['disabled-expiry'] ) {
957 $attribs['disabled'] = 'disabled';
959 $expiryHtml .= Xml
::input( "wpExpiry-$group-other", 30, '', $attribs );
961 // If the user group is set but the checkbox is disabled, mimic a
962 // checked checkbox in the form submission
963 if ( $checkbox['set'] && $checkbox['disabled'] ) {
964 $expiryHtml .= Html
::hidden( "wpGroup-$group", 1 );
967 $expiryHtml .= Xml
::closeElement( 'span' );
971 'id' => "mw-userrights-nested-wpGroup-$group",
972 'class' => 'mw-userrights-nested',
974 $checkboxHtml .= "\t\t\t" . Xml
::tags( 'div', $divAttribs, $expiryHtml ) . "\n";
976 $ret .= "\t\t" . ( ( $checkbox['disabled'] && $checkbox['disabled-expiry'] )
977 ? Xml
::tags( 'div', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
978 : Xml
::tags( 'div', [], $checkboxHtml )
983 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
985 return [ $ret, (bool)$columns['changeable'] ];
989 * @param string $group The name of the group to check
990 * @return bool Can we remove the group?
992 private function canRemove( $group ) {
993 $groups = $this->changeableGroups();
997 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
1002 * @param string $group The name of the group to check
1003 * @return bool Can we add the group?
1005 private function canAdd( $group ) {
1006 $groups = $this->changeableGroups();
1010 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
1015 * Returns $this->getUser()->changeableGroups()
1018 * 'add' => [ addablegroups ],
1019 * 'remove' => [ removablegroups ],
1020 * 'add-self' => [ addablegroups to self ],
1021 * 'remove-self' => [ removable groups from self ]
1024 function changeableGroups() {
1025 return $this->getUser()->changeableGroups();
1029 * Show a rights log fragment for the specified user
1031 * @param User $user User to show log for
1032 * @param OutputPage $output OutputPage to use
1034 protected function showLogFragment( $user, $output ) {
1035 $rightsLogPage = new LogPage( 'rights' );
1036 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
1037 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
1041 * Return an array of subpages beginning with $search that this special page will accept.
1043 * @param string $search Prefix to search for
1044 * @param int $limit Maximum number of results to return (usually 10)
1045 * @param int $offset Number of results to skip (usually 0)
1046 * @return string[] Matching subpages
1048 public function prefixSearchSubpages( $search, $limit, $offset ) {
1049 $user = User
::newFromName( $search );
1051 // No prefix suggestion for invalid user
1054 // Autocomplete subpage as user list - public to allow caching
1055 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
1058 protected function getGroupName() {