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
{
31 * The target of the local right-adjuster's interest. Can be gotten from
32 * either a GET parameter or a subpage-style parameter, so have a member
34 * @var null|string $mTarget
38 * @var null|User $mFetchedUser The user object of the target username or null.
40 protected $mFetchedUser = null;
41 protected $isself = false;
43 public function __construct() {
44 parent
::__construct( 'Userrights' );
47 public function doesWrites() {
52 * Check whether the current user (from context) can change the target user's rights.
54 * @param User $targetUser User whose rights are being changed
55 * @param bool $checkIfSelf If false, assume that the current user can add/remove groups defined
56 * in $wgGroupsAddToSelf / $wgGroupsRemoveFromSelf, without checking if it's the same as target
60 public function userCanChangeRights( $targetUser, $checkIfSelf = true ) {
61 $isself = $this->getUser()->equals( $targetUser );
63 $available = $this->changeableGroups();
64 if ( $targetUser->getId() == 0 ) {
68 return !empty( $available['add'] )
69 ||
!empty( $available['remove'] )
70 ||
( ( $isself ||
!$checkIfSelf ) &&
71 ( !empty( $available['add-self'] )
72 ||
!empty( $available['remove-self'] ) ) );
76 * Manage forms to be shown according to posted data.
77 * Depending on the submit button used, call a form or a save function.
79 * @param string|null $par String if any subpage provided, else null
80 * @throws UserBlockedError|PermissionsError
82 public function execute( $par ) {
83 $user = $this->getUser();
84 $request = $this->getRequest();
85 $session = $request->getSession();
86 $out = $this->getOutput();
88 if ( $par !== null ) {
89 $this->mTarget
= $par;
91 $this->mTarget
= $request->getVal( 'user' );
94 if ( is_string( $this->mTarget
) ) {
95 $this->mTarget
= trim( $this->mTarget
);
98 if ( $this->mTarget
!== null && User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
102 $fetchedStatus = $this->fetchUser( $this->mTarget
, true );
103 if ( $fetchedStatus->isOK() ) {
104 $this->mFetchedUser
= $fetchedStatus->value
;
105 if ( $this->mFetchedUser
instanceof User
) {
106 // Set the 'relevant user' in the skin, so it displays links like Contributions,
107 // User logs, UserRights, etc.
108 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
112 // show a successbox, if the user rights was saved successfully
114 $session->get( 'specialUserrightsSaveSuccess' ) &&
115 $this->mFetchedUser
!== null
117 // Remove session data for the success message
118 $session->remove( 'specialUserrightsSaveSuccess' );
120 $out->addModules( [ 'mediawiki.special.userrights' ] );
121 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
126 'class' => 'mw-notify-success successbox',
127 'id' => 'mw-preferences-success',
128 'data-mw-autohide' => 'false',
133 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
140 $this->outputHeader();
142 $out->addModuleStyles( 'mediawiki.special' );
143 $this->addHelpLink( 'Help:Assigning permissions' );
148 $request->wasPosted() &&
149 $request->getCheck( 'saveusergroups' ) &&
150 $this->mTarget
!== null &&
151 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
154 * If the user is blocked and they only have "partial" access
155 * (e.g. they don't have the userrights permission), then don't
156 * allow them to change any user rights.
158 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
159 throw new UserBlockedError( $user->getBlock() );
162 $this->checkReadOnly();
165 if ( !$fetchedStatus->isOK() ) {
166 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
171 $targetUser = $this->mFetchedUser
;
172 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
173 $targetUser->clearInstanceCache(); // bug 38989
176 if ( $request->getVal( 'conflictcheck-originalgroups' )
177 !== implode( ',', $targetUser->getGroups() )
179 $out->addWikiMsg( 'userrights-conflict' );
181 $this->saveUserGroups(
183 $request->getVal( 'user-reason' ),
187 // Set session data for the success message
188 $session->set( 'specialUserrightsSaveSuccess', 1 );
190 $out->redirect( $this->getSuccessURL() );
196 // show some more forms
197 if ( $this->mTarget
!== null ) {
198 $this->editUserGroupsForm( $this->mTarget
);
202 function getSuccessURL() {
203 return $this->getPageTitle( $this->mTarget
)->getFullURL();
207 * Save user groups changes in the database.
208 * Data comes from the editUserGroupsForm() form function
210 * @param string $username Username to apply changes to.
211 * @param string $reason Reason for group change
212 * @param User|UserRightsProxy $user Target user object.
215 function saveUserGroups( $username, $reason, $user ) {
216 $allgroups = $this->getAllGroups();
220 // This could possibly create a highly unlikely race condition if permissions are changed between
221 // when the form is loaded and when the form is saved. Ignoring it for the moment.
222 foreach ( $allgroups as $group ) {
223 // We'll tell it to remove all unchecked groups, and add all checked groups.
224 // Later on, this gets filtered for what can actually be removed
225 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
226 $addgroup[] = $group;
228 $removegroup[] = $group;
232 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
236 * Save user groups changes in the database.
238 * @param User|UserRightsProxy $user
239 * @param array $add Array of groups to add
240 * @param array $remove Array of groups to remove
241 * @param string $reason Reason for group change
242 * @param array $tags Array of change tags to add to the log entry
243 * @return array Tuple of added, then removed groups
245 function doSaveUserGroups( $user, $add, $remove, $reason = '', $tags = [] ) {
246 // Validate input set...
247 $isself = $user->getName() == $this->getUser()->getName();
248 $groups = $user->getGroups();
249 $changeable = $this->changeableGroups();
250 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
251 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
253 $remove = array_unique(
254 array_intersect( (array)$remove, $removable, $groups ) );
255 $add = array_unique( array_diff(
256 array_intersect( (array)$add, $addable ),
260 Hooks
::run( 'ChangeUserGroups', [ $this->getUser(), $user, &$add, &$remove ] );
262 $oldGroups = $user->getGroups();
263 $newGroups = $oldGroups;
265 // Remove then add groups
267 foreach ( $remove as $index => $group ) {
268 if ( !$user->removeGroup( $group ) ) {
269 unset( $remove[$index] );
272 $newGroups = array_diff( $newGroups, $remove );
275 foreach ( $add as $index => $group ) {
276 if ( !$user->addGroup( $group ) ) {
277 unset( $add[$index] );
280 $newGroups = array_merge( $newGroups, $add );
282 $newGroups = array_unique( $newGroups );
284 // Ensure that caches are cleared
285 $user->invalidateCache();
287 // update groups in external authentication database
288 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
289 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin(
290 'updateExternalDBGroups', [ $user, $add, $remove ]
293 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
294 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
295 // Deprecated in favor of UserGroupsChanged hook
296 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
298 if ( $newGroups != $oldGroups ) {
299 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags );
302 return [ $add, $remove ];
306 * Add a rights log entry for an action.
308 * @param array $oldGroups
309 * @param array $newGroups
310 * @param array $reason
313 function addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags ) {
314 $logEntry = new ManualLogEntry( 'rights', 'rights' );
315 $logEntry->setPerformer( $this->getUser() );
316 $logEntry->setTarget( $user->getUserPage() );
317 $logEntry->setComment( $reason );
318 $logEntry->setParameters( [
319 '4::oldgroups' => $oldGroups,
320 '5::newgroups' => $newGroups,
322 $logid = $logEntry->insert();
323 if ( count( $tags ) ) {
324 $logEntry->setTags( $tags );
326 $logEntry->publish( $logid );
330 * Edit user groups membership
331 * @param string $username Name of the user.
333 function editUserGroupsForm( $username ) {
334 $status = $this->fetchUser( $username, true );
335 if ( !$status->isOK() ) {
336 $this->getOutput()->addWikiText( $status->getWikiText() );
340 $user = $status->value
;
343 $groups = $user->getGroups();
345 $this->showEditUserGroupsForm( $user, $groups );
347 // This isn't really ideal logging behavior, but let's not hide the
348 // interwiki logs if we're using them as is.
349 $this->showLogFragment( $user, $this->getOutput() );
353 * Normalize the input username, which may be local or remote, and
354 * return a user (or proxy) object for manipulating it.
356 * Side effects: error output for invalid access
357 * @param string $username
358 * @param bool $writing
361 public function fetchUser( $username, $writing = true ) {
362 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
363 if ( count( $parts ) < 2 ) {
364 $name = trim( $username );
367 list( $name, $database ) = array_map( 'trim', $parts );
369 if ( $database == wfWikiID() ) {
372 if ( $writing && !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
373 return Status
::newFatal( 'userrights-no-interwiki' );
375 if ( !UserRightsProxy
::validDatabase( $database ) ) {
376 return Status
::newFatal( 'userrights-nodatabase', $database );
381 if ( $name === '' ) {
382 return Status
::newFatal( 'nouserspecified' );
385 if ( $name[0] == '#' ) {
386 // Numeric ID can be specified...
387 // We'll do a lookup for the name internally.
388 $id = intval( substr( $name, 1 ) );
390 if ( $database == '' ) {
391 $name = User
::whoIs( $id );
393 $name = UserRightsProxy
::whoIs( $database, $id );
397 return Status
::newFatal( 'noname' );
400 $name = User
::getCanonicalName( $name );
401 if ( $name === false ) {
403 return Status
::newFatal( 'nosuchusershort', $username );
407 if ( $database == '' ) {
408 $user = User
::newFromName( $name );
410 $user = UserRightsProxy
::newFromName( $database, $name );
413 if ( !$user ||
$user->isAnon() ) {
414 return Status
::newFatal( 'nosuchusershort', $username );
417 return Status
::newGood( $user );
427 public function makeGroupNameList( $ids ) {
428 if ( empty( $ids ) ) {
429 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
431 return implode( ', ', $ids );
436 * Output a form to allow searching for a user
438 function switchForm() {
439 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
441 $this->getOutput()->addHTML(
446 'action' => wfScript(),
448 'id' => 'mw-userrights-form1'
451 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
452 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
454 $this->msg( 'userrights-user-editname' )->text(),
458 str_replace( '_', ' ', $this->mTarget
),
460 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
462 // Set autofocus on blank input and error input
463 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
467 $this->msg( 'editusergroup' )->text()
469 Html
::closeElement( 'fieldset' ) .
470 Html
::closeElement( 'form' ) . "\n"
475 * Show the form to edit group memberships.
477 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
478 * @param array $groups Array of groups the user is in
480 protected function showEditUserGroupsForm( $user, $groups ) {
483 foreach ( $groups as $group ) {
484 $list[] = self
::buildGroupLink( $group );
485 $membersList[] = self
::buildGroupMemberLink( $group );
489 $autoMembersList = [];
490 if ( $user instanceof User
) {
491 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
492 $autoList[] = self
::buildGroupLink( $group );
493 $autoMembersList[] = self
::buildGroupMemberLink( $group );
497 $language = $this->getLanguage();
498 $displayedList = $this->msg( 'userrights-groupsmember-type' )
500 $language->listToText( $list ),
501 $language->listToText( $membersList )
503 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
505 $language->listToText( $autoList ),
506 $language->listToText( $autoMembersList )
510 $count = count( $list );
512 $grouplist = $this->msg( 'userrights-groupsmember' )
513 ->numParams( $count )
514 ->params( $user->getName() )
516 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
519 $count = count( $autoList );
521 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
522 ->numParams( $count )
523 ->params( $user->getName() )
525 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
528 $userToolLinks = Linker
::userToolLinks(
531 false, /* default for redContribsWhenNoEdits */
532 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
535 list( $groupCheckboxes, $canChangeAny ) = $this->groupCheckboxes( $groups, $user );
536 $this->getOutput()->addHTML(
541 'action' => $this->getPageTitle()->getLocalURL(),
542 'name' => 'editGroup',
543 'id' => 'mw-userrights-form2'
546 Html
::hidden( 'user', $this->mTarget
) .
547 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
549 'conflictcheck-originalgroups',
550 implode( ',', $user->getGroups() )
551 ) . // Conflict detection
552 Xml
::openElement( 'fieldset' ) .
557 $canChangeAny ?
'userrights-editusergroup' : 'userrights-viewusergroup',
562 $canChangeAny ?
'editinguser' : 'viewinguserrights'
563 )->params( wfEscapeWikiText( $user->getName() ) )
564 ->rawParams( $userToolLinks )->parse()
566 if ( $canChangeAny ) {
567 $this->getOutput()->addHTML(
568 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
571 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
573 <td class='mw-label'>" .
574 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
576 <td class='mw-input'>" .
577 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
578 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
583 <td class='mw-submit'>" .
584 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
585 [ 'name' => 'saveusergroups' ] +
586 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
590 Xml
::closeElement( 'table' ) . "\n"
593 $this->getOutput()->addHTML( $grouplist );
595 $this->getOutput()->addHTML(
596 Xml
::closeElement( 'fieldset' ) .
597 Xml
::closeElement( 'form' ) . "\n"
602 * Format a link to a group description page
604 * @param string $group
607 private static function buildGroupLink( $group ) {
608 return User
::makeGroupLinkHTML( $group, User
::getGroupName( $group ) );
612 * Format a link to a group member description page
614 * @param string $group
617 private static function buildGroupMemberLink( $group ) {
618 return User
::makeGroupLinkHTML( $group, User
::getGroupMember( $group ) );
622 * Returns an array of all groups that may be edited
623 * @return array Array of groups that may be edited.
625 protected static function getAllGroups() {
626 return User
::getAllGroups();
630 * Adds a table with checkboxes where you can select what groups to add/remove
632 * @todo Just pass the username string?
633 * @param array $usergroups Groups the user belongs to
635 * @return Array with 2 elements: the XHTML table element with checkxboes, and
636 * whether any groups are changeable
638 private function groupCheckboxes( $usergroups, $user ) {
639 $allgroups = $this->getAllGroups();
642 // Put all column info into an associative array so that extensions can
643 // more easily manage it.
644 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
646 foreach ( $allgroups as $group ) {
647 $set = in_array( $group, $usergroups );
648 // Should the checkbox be disabled?
650 ( $set && $this->canRemove( $group ) ) ||
651 ( !$set && $this->canAdd( $group ) ) );
652 // Do we need to point out that this action is irreversible?
653 $irreversible = !$disabled && (
654 ( $set && !$this->canAdd( $group ) ) ||
655 ( !$set && !$this->canRemove( $group ) ) );
659 'disabled' => $disabled,
660 'irreversible' => $irreversible
664 $columns['unchangeable'][$group] = $checkbox;
666 $columns['changeable'][$group] = $checkbox;
670 // Build the HTML table
671 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
673 foreach ( $columns as $name => $column ) {
674 if ( $column === [] ) {
677 // Messages: userrights-changeable-col, userrights-unchangeable-col
678 $ret .= Xml
::element(
681 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
685 $ret .= "</tr>\n<tr>\n";
686 foreach ( $columns as $column ) {
687 if ( $column === [] ) {
690 $ret .= "\t<td style='vertical-align:top;'>\n";
691 foreach ( $column as $group => $checkbox ) {
692 $attr = $checkbox['disabled'] ?
[ 'disabled' => 'disabled' ] : [];
694 $member = User
::getGroupMember( $group, $user->getName() );
695 if ( $checkbox['irreversible'] ) {
696 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
700 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
701 "wpGroup-" . $group, $checkbox['set'], $attr );
702 $ret .= "\t\t" . ( $checkbox['disabled']
703 ? Xml
::tags( 'span', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
709 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
711 return [ $ret, (bool)$columns['changeable'] ];
715 * @param string $group The name of the group to check
716 * @return bool Can we remove the group?
718 private function canRemove( $group ) {
719 $groups = $this->changeableGroups();
723 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
728 * @param string $group The name of the group to check
729 * @return bool Can we add the group?
731 private function canAdd( $group ) {
732 $groups = $this->changeableGroups();
736 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
741 * Returns $this->getUser()->changeableGroups()
743 * @return array Array(
744 * 'add' => array( addablegroups ),
745 * 'remove' => array( removablegroups ),
746 * 'add-self' => array( addablegroups to self ),
747 * 'remove-self' => array( removable groups from self )
750 function changeableGroups() {
751 return $this->getUser()->changeableGroups();
755 * Show a rights log fragment for the specified user
757 * @param User $user User to show log for
758 * @param OutputPage $output OutputPage to use
760 protected function showLogFragment( $user, $output ) {
761 $rightsLogPage = new LogPage( 'rights' );
762 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
763 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
767 * Return an array of subpages beginning with $search that this special page will accept.
769 * @param string $search Prefix to search for
770 * @param int $limit Maximum number of results to return (usually 10)
771 * @param int $offset Number of results to skip (usually 0)
772 * @return string[] Matching subpages
774 public function prefixSearchSubpages( $search, $limit, $offset ) {
775 $user = User
::newFromName( $search );
777 // No prefix suggestion for invalid user
780 // Autocomplete subpage as user list - public to allow caching
781 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
784 protected function getGroupName() {