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
25 * Special page to allow managing user group membership
27 * @ingroup SpecialPage
29 class UserrightsPage
extends SpecialPage
{
30 # The target of the local right-adjuster's interest. Can be gotten from
31 # either a GET parameter or a subpage-style parameter, so have a member
35 * @var null|User $mFetchedUser The user object of the target username or null.
37 protected $mFetchedUser = null;
38 protected $isself = false;
40 public function __construct() {
41 parent
::__construct( 'Userrights' );
44 public function doesWrites() {
48 public function isRestricted() {
52 public function userCanExecute( User
$user ) {
53 return $this->userCanChangeRights( $user, false );
58 * @param bool $checkIfSelf
61 public function userCanChangeRights( $user, $checkIfSelf = true ) {
62 $available = $this->changeableGroups();
63 if ( $user->getId() == 0 ) {
67 return !empty( $available['add'] )
68 ||
!empty( $available['remove'] )
69 ||
( ( $this->isself ||
!$checkIfSelf ) &&
70 ( !empty( $available['add-self'] )
71 ||
!empty( $available['remove-self'] ) ) );
75 * Manage forms to be shown according to posted data.
76 * Depending on the submit button used, call a form or a save function.
78 * @param string|null $par String if any subpage provided, else null
79 * @throws UserBlockedError|PermissionsError
81 public function execute( $par ) {
82 // If the visitor doesn't have permissions to assign or remove
83 // any groups, it's a bit silly to give them the user search prompt.
85 $user = $this->getUser();
86 $request = $this->getRequest();
87 $out = $this->getOutput();
90 * If the user is blocked and they only have "partial" access
91 * (e.g. they don't have the userrights permission), then don't
92 * allow them to use Special:UserRights.
94 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
95 throw new UserBlockedError( $user->getBlock() );
98 if ( $par !== null ) {
99 $this->mTarget
= $par;
101 $this->mTarget
= $request->getVal( 'user' );
104 $available = $this->changeableGroups();
106 if ( $this->mTarget
=== null ) {
108 * If the user specified no target, and they can only
109 * edit their own groups, automatically set them as the
112 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
113 $this->mTarget
= $user->getName();
117 if ( $this->mTarget
!== null && User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
118 $this->isself
= true;
121 $fetchedStatus = $this->fetchUser( $this->mTarget
);
122 if ( $fetchedStatus->isOK() ) {
123 $this->mFetchedUser
= $fetchedStatus->value
;
124 if ( $this->mFetchedUser
instanceof User
) {
125 // Set the 'relevant user' in the skin, so it displays links like Contributions,
126 // User logs, UserRights, etc.
127 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
131 if ( !$this->userCanChangeRights( $user, true ) ) {
132 if ( $this->isself
&& $request->getCheck( 'success' ) ) {
133 // bug 48609: if the user just removed its own rights, this would
134 // leads it in a "permissions error" page. In that case, show a
135 // message that it can't anymore use this page instead of an error
137 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
138 $out->returnToMain();
143 // @todo FIXME: There may be intermediate groups we can mention.
144 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
145 throw new PermissionsError( null, [ [ $msg ] ] );
148 // show a successbox, if the user rights was saved successfully
149 if ( $request->getCheck( 'success' ) && $this->mFetchedUser
!== null ) {
150 $out->addModules( [ 'mediawiki.special.userrights' ] );
151 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
156 'class' => 'mw-notify-success successbox',
157 'id' => 'mw-preferences-success',
158 'data-mw-autohide' => 'false',
163 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
169 $this->checkReadOnly();
172 $this->outputHeader();
174 $out->addModuleStyles( 'mediawiki.special' );
175 $this->addHelpLink( 'Help:Assigning permissions' );
177 // show the general form
178 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
183 $request->wasPosted() &&
184 $request->getCheck( 'saveusergroups' ) &&
185 $this->mTarget
!== null &&
186 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
189 if ( !$fetchedStatus->isOK() ) {
190 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
195 $targetUser = $this->mFetchedUser
;
196 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
197 $targetUser->clearInstanceCache(); // bug 38989
200 if ( $request->getVal( 'conflictcheck-originalgroups' )
201 !== implode( ',', $targetUser->getGroups() )
203 $out->addWikiMsg( 'userrights-conflict' );
205 $this->saveUserGroups(
207 $request->getVal( 'user-reason' ),
211 $out->redirect( $this->getSuccessURL() );
217 // show some more forms
218 if ( $this->mTarget
!== null ) {
219 $this->editUserGroupsForm( $this->mTarget
);
223 function getSuccessURL() {
224 return $this->getPageTitle( $this->mTarget
)->getFullURL( [ 'success' => 1 ] );
228 * Save user groups changes in the database.
229 * Data comes from the editUserGroupsForm() form function
231 * @param string $username Username to apply changes to.
232 * @param string $reason Reason for group change
233 * @param User|UserRightsProxy $user Target user object.
236 function saveUserGroups( $username, $reason, $user ) {
237 $allgroups = $this->getAllGroups();
241 // This could possibly create a highly unlikely race condition if permissions are changed between
242 // when the form is loaded and when the form is saved. Ignoring it for the moment.
243 foreach ( $allgroups as $group ) {
244 // We'll tell it to remove all unchecked groups, and add all checked groups.
245 // Later on, this gets filtered for what can actually be removed
246 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
247 $addgroup[] = $group;
249 $removegroup[] = $group;
253 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
257 * Save user groups changes in the database.
259 * @param User|UserRightsProxy $user
260 * @param array $add Array of groups to add
261 * @param array $remove Array of groups to remove
262 * @param string $reason Reason for group change
263 * @return array Tuple of added, then removed groups
265 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
266 // Validate input set...
267 $isself = $user->getName() == $this->getUser()->getName();
268 $groups = $user->getGroups();
269 $changeable = $this->changeableGroups();
270 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
271 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
273 $remove = array_unique(
274 array_intersect( (array)$remove, $removable, $groups ) );
275 $add = array_unique( array_diff(
276 array_intersect( (array)$add, $addable ),
280 $oldGroups = $user->getGroups();
281 $newGroups = $oldGroups;
283 // Remove then add groups
285 foreach ( $remove as $index => $group ) {
286 if ( !$user->removeGroup( $group ) ) {
287 unset( $remove[$index] );
290 $newGroups = array_diff( $newGroups, $remove );
293 foreach ( $add as $index => $group ) {
294 if ( !$user->addGroup( $group ) ) {
295 unset( $add[$index] );
298 $newGroups = array_merge( $newGroups, $add );
300 $newGroups = array_unique( $newGroups );
302 // Ensure that caches are cleared
303 $user->invalidateCache();
305 // update groups in external authentication database
306 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
307 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin(
308 'updateExternalDBGroups', [ $user, $add, $remove ]
311 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
312 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
313 // Deprecated in favor of UserGroupsChanged hook
314 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
316 if ( $newGroups != $oldGroups ) {
317 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
320 return [ $add, $remove ];
324 * Add a rights log entry for an action.
326 * @param array $oldGroups
327 * @param array $newGroups
328 * @param array $reason
330 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
331 $logEntry = new ManualLogEntry( 'rights', 'rights' );
332 $logEntry->setPerformer( $this->getUser() );
333 $logEntry->setTarget( $user->getUserPage() );
334 $logEntry->setComment( $reason );
335 $logEntry->setParameters( [
336 '4::oldgroups' => $oldGroups,
337 '5::newgroups' => $newGroups,
339 $logid = $logEntry->insert();
340 $logEntry->publish( $logid );
344 * Edit user groups membership
345 * @param string $username Name of the user.
347 function editUserGroupsForm( $username ) {
348 $status = $this->fetchUser( $username );
349 if ( !$status->isOK() ) {
350 $this->getOutput()->addWikiText( $status->getWikiText() );
354 $user = $status->value
;
357 $groups = $user->getGroups();
359 $this->showEditUserGroupsForm( $user, $groups );
361 // This isn't really ideal logging behavior, but let's not hide the
362 // interwiki logs if we're using them as is.
363 $this->showLogFragment( $user, $this->getOutput() );
367 * Normalize the input username, which may be local or remote, and
368 * return a user (or proxy) object for manipulating it.
370 * Side effects: error output for invalid access
371 * @param string $username
374 public function fetchUser( $username ) {
375 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
376 if ( count( $parts ) < 2 ) {
377 $name = trim( $username );
380 list( $name, $database ) = array_map( 'trim', $parts );
382 if ( $database == wfWikiID() ) {
385 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
386 return Status
::newFatal( 'userrights-no-interwiki' );
388 if ( !UserRightsProxy
::validDatabase( $database ) ) {
389 return Status
::newFatal( 'userrights-nodatabase', $database );
394 if ( $name === '' ) {
395 return Status
::newFatal( 'nouserspecified' );
398 if ( $name[0] == '#' ) {
399 // Numeric ID can be specified...
400 // We'll do a lookup for the name internally.
401 $id = intval( substr( $name, 1 ) );
403 if ( $database == '' ) {
404 $name = User
::whoIs( $id );
406 $name = UserRightsProxy
::whoIs( $database, $id );
410 return Status
::newFatal( 'noname' );
413 $name = User
::getCanonicalName( $name );
414 if ( $name === false ) {
416 return Status
::newFatal( 'nosuchusershort', $username );
420 if ( $database == '' ) {
421 $user = User
::newFromName( $name );
423 $user = UserRightsProxy
::newFromName( $database, $name );
426 if ( !$user ||
$user->isAnon() ) {
427 return Status
::newFatal( 'nosuchusershort', $username );
430 return Status
::newGood( $user );
440 public function makeGroupNameList( $ids ) {
441 if ( empty( $ids ) ) {
442 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
444 return implode( ', ', $ids );
449 * Output a form to allow searching for a user
451 function switchForm() {
452 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
454 $this->getOutput()->addHTML(
459 'action' => wfScript(),
461 'id' => 'mw-userrights-form1'
464 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
465 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
467 $this->msg( 'userrights-user-editname' )->text(),
471 str_replace( '_', ' ', $this->mTarget
),
473 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
475 // Set autofocus on blank input and error input
476 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
482 $this->mFetchedUser
=== null ?
'[]' : $this->mFetchedUser
->getName()
485 Html
::closeElement( 'fieldset' ) .
486 Html
::closeElement( 'form' ) . "\n"
491 * Go through used and available groups and return the ones that this
492 * form will be able to manipulate based on the current user's system
495 * @param array $groups List of groups the given user is in
496 * @return array Tuple of addable, then removable groups
498 protected function splitGroups( $groups ) {
499 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
501 $removable = array_intersect(
502 array_merge( $this->isself ?
$removeself : [], $removable ),
504 ); // Can't remove groups the user doesn't have
505 $addable = array_diff(
506 array_merge( $this->isself ?
$addself : [], $addable ),
508 ); // Can't add groups the user does have
510 return [ $addable, $removable ];
514 * Show the form to edit group memberships.
516 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
517 * @param array $groups Array of groups the user is in
519 protected function showEditUserGroupsForm( $user, $groups ) {
522 foreach ( $groups as $group ) {
523 $list[] = self
::buildGroupLink( $group );
524 $membersList[] = self
::buildGroupMemberLink( $group );
528 $autoMembersList = [];
529 if ( $user instanceof User
) {
530 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
531 $autoList[] = self
::buildGroupLink( $group );
532 $autoMembersList[] = self
::buildGroupMemberLink( $group );
536 $language = $this->getLanguage();
537 $displayedList = $this->msg( 'userrights-groupsmember-type' )
539 $language->listToText( $list ),
540 $language->listToText( $membersList )
542 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
544 $language->listToText( $autoList ),
545 $language->listToText( $autoMembersList )
549 $count = count( $list );
551 $grouplist = $this->msg( 'userrights-groupsmember' )
552 ->numParams( $count )
553 ->params( $user->getName() )
555 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
558 $count = count( $autoList );
560 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
561 ->numParams( $count )
562 ->params( $user->getName() )
564 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
567 $userToolLinks = Linker
::userToolLinks(
570 false, /* default for redContribsWhenNoEdits */
571 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
574 $this->getOutput()->addHTML(
579 'action' => $this->getPageTitle()->getLocalURL(),
580 'name' => 'editGroup',
581 'id' => 'mw-userrights-form2'
584 Html
::hidden( 'user', $this->mTarget
) .
585 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
587 'conflictcheck-originalgroups',
588 implode( ',', $user->getGroups() )
589 ) . // Conflict detection
590 Xml
::openElement( 'fieldset' ) .
594 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
596 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
597 ->rawParams( $userToolLinks )->parse() .
598 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
600 $this->groupCheckboxes( $groups, $user ) .
601 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
603 <td class='mw-label'>" .
604 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
606 <td class='mw-input'>" .
607 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
608 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
613 <td class='mw-submit'>" .
614 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
615 [ 'name' => 'saveusergroups' ] +
616 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
620 Xml
::closeElement( 'table' ) . "\n" .
621 Xml
::closeElement( 'fieldset' ) .
622 Xml
::closeElement( 'form' ) . "\n"
627 * Format a link to a group description page
629 * @param string $group
632 private static function buildGroupLink( $group ) {
633 return User
::makeGroupLinkHTML( $group, User
::getGroupName( $group ) );
637 * Format a link to a group member description page
639 * @param string $group
642 private static function buildGroupMemberLink( $group ) {
643 return User
::makeGroupLinkHTML( $group, User
::getGroupMember( $group ) );
647 * Returns an array of all groups that may be edited
648 * @return array Array of groups that may be edited.
650 protected static function getAllGroups() {
651 return User
::getAllGroups();
655 * Adds a table with checkboxes where you can select what groups to add/remove
657 * @todo Just pass the username string?
658 * @param array $usergroups Groups the user belongs to
660 * @return string XHTML table element with checkboxes
662 private function groupCheckboxes( $usergroups, $user ) {
663 $allgroups = $this->getAllGroups();
666 // Put all column info into an associative array so that extensions can
667 // more easily manage it.
668 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
670 foreach ( $allgroups as $group ) {
671 $set = in_array( $group, $usergroups );
672 // Should the checkbox be disabled?
674 ( $set && $this->canRemove( $group ) ) ||
675 ( !$set && $this->canAdd( $group ) ) );
676 // Do we need to point out that this action is irreversible?
677 $irreversible = !$disabled && (
678 ( $set && !$this->canAdd( $group ) ) ||
679 ( !$set && !$this->canRemove( $group ) ) );
683 'disabled' => $disabled,
684 'irreversible' => $irreversible
688 $columns['unchangeable'][$group] = $checkbox;
690 $columns['changeable'][$group] = $checkbox;
694 // Build the HTML table
695 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
697 foreach ( $columns as $name => $column ) {
698 if ( $column === [] ) {
701 // Messages: userrights-changeable-col, userrights-unchangeable-col
702 $ret .= Xml
::element(
705 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
709 $ret .= "</tr>\n<tr>\n";
710 foreach ( $columns as $column ) {
711 if ( $column === [] ) {
714 $ret .= "\t<td style='vertical-align:top;'>\n";
715 foreach ( $column as $group => $checkbox ) {
716 $attr = $checkbox['disabled'] ?
[ 'disabled' => 'disabled' ] : [];
718 $member = User
::getGroupMember( $group, $user->getName() );
719 if ( $checkbox['irreversible'] ) {
720 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
724 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
725 "wpGroup-" . $group, $checkbox['set'], $attr );
726 $ret .= "\t\t" . ( $checkbox['disabled']
727 ? Xml
::tags( 'span', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
733 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
739 * @param string $group The name of the group to check
740 * @return bool Can we remove the group?
742 private function canRemove( $group ) {
743 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
744 $groups = $this->changeableGroups();
748 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
753 * @param string $group The name of the group to check
754 * @return bool Can we add the group?
756 private function canAdd( $group ) {
757 $groups = $this->changeableGroups();
761 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
766 * Returns $this->getUser()->changeableGroups()
768 * @return array Array(
769 * 'add' => array( addablegroups ),
770 * 'remove' => array( removablegroups ),
771 * 'add-self' => array( addablegroups to self ),
772 * 'remove-self' => array( removable groups from self )
775 function changeableGroups() {
776 return $this->getUser()->changeableGroups();
780 * Show a rights log fragment for the specified user
782 * @param User $user User to show log for
783 * @param OutputPage $output OutputPage to use
785 protected function showLogFragment( $user, $output ) {
786 $rightsLogPage = new LogPage( 'rights' );
787 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
788 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
792 * Return an array of subpages beginning with $search that this special page will accept.
794 * @param string $search Prefix to search for
795 * @param int $limit Maximum number of results to return (usually 10)
796 * @param int $offset Number of results to skip (usually 0)
797 * @return string[] Matching subpages
799 public function prefixSearchSubpages( $search, $limit, $offset ) {
800 $user = User
::newFromName( $search );
802 // No prefix suggestion for invalid user
805 // Autocomplete subpage as user list - public to allow caching
806 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
809 protected function getGroupName() {