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() {
53 * @param bool $checkIfSelf
56 public function userCanChangeRights( $user, $checkIfSelf = true ) {
57 $available = $this->changeableGroups();
58 if ( $user->getId() == 0 ) {
62 return !empty( $available['add'] )
63 ||
!empty( $available['remove'] )
64 ||
( ( $this->isself ||
!$checkIfSelf ) &&
65 ( !empty( $available['add-self'] )
66 ||
!empty( $available['remove-self'] ) ) );
70 * Manage forms to be shown according to posted data.
71 * Depending on the submit button used, call a form or a save function.
73 * @param string|null $par String if any subpage provided, else null
74 * @throws UserBlockedError|PermissionsError
76 public function execute( $par ) {
77 $user = $this->getUser();
78 $request = $this->getRequest();
79 $session = $request->getSession();
80 $out = $this->getOutput();
82 if ( $par !== null ) {
83 $this->mTarget
= $par;
85 $this->mTarget
= $request->getVal( 'user' );
88 if ( is_string( $this->mTarget
) ) {
89 $this->mTarget
= trim( $this->mTarget
);
92 $fetchedStatus = $this->fetchUser( $this->mTarget
, true );
93 if ( $fetchedStatus->isOK() ) {
94 $this->mFetchedUser
= $fetchedStatus->value
;
95 if ( $this->mFetchedUser
instanceof User
) {
96 // Set the 'relevant user' in the skin, so it displays links like Contributions,
97 // User logs, UserRights, etc.
98 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
102 // show a successbox, if the user rights was saved successfully
104 $session->get( 'specialUserrightsSaveSuccess' ) &&
105 $this->mFetchedUser
!== null
107 // Remove session data for the success message
108 $session->remove( 'specialUserrightsSaveSuccess' );
110 $out->addModules( [ 'mediawiki.special.userrights' ] );
111 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
116 'class' => 'mw-notify-success successbox',
117 'id' => 'mw-preferences-success',
118 'data-mw-autohide' => 'false',
123 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
130 $this->outputHeader();
132 $out->addModuleStyles( 'mediawiki.special' );
133 $this->addHelpLink( 'Help:Assigning permissions' );
138 $request->wasPosted() &&
139 $request->getCheck( 'saveusergroups' ) &&
140 $this->mTarget
!== null &&
141 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
144 * If the user is blocked and they only have "partial" access
145 * (e.g. they don't have the userrights permission), then don't
146 * allow them to change any user rights.
148 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
149 throw new UserBlockedError( $user->getBlock() );
152 $this->checkReadOnly();
155 if ( !$fetchedStatus->isOK() ) {
156 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
161 $targetUser = $this->mFetchedUser
;
162 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
163 $targetUser->clearInstanceCache(); // bug 38989
166 if ( $request->getVal( 'conflictcheck-originalgroups' )
167 !== implode( ',', $targetUser->getGroups() )
169 $out->addWikiMsg( 'userrights-conflict' );
171 $this->saveUserGroups(
173 $request->getVal( 'user-reason' ),
177 // Set session data for the success message
178 $session->set( 'specialUserrightsSaveSuccess', 1 );
180 $out->redirect( $this->getSuccessURL() );
186 // show some more forms
187 if ( $this->mTarget
!== null ) {
188 $this->editUserGroupsForm( $this->mTarget
);
192 function getSuccessURL() {
193 return $this->getPageTitle( $this->mTarget
)->getFullURL();
197 * Save user groups changes in the database.
198 * Data comes from the editUserGroupsForm() form function
200 * @param string $username Username to apply changes to.
201 * @param string $reason Reason for group change
202 * @param User|UserRightsProxy $user Target user object.
205 function saveUserGroups( $username, $reason, $user ) {
206 $allgroups = $this->getAllGroups();
210 // This could possibly create a highly unlikely race condition if permissions are changed between
211 // when the form is loaded and when the form is saved. Ignoring it for the moment.
212 foreach ( $allgroups as $group ) {
213 // We'll tell it to remove all unchecked groups, and add all checked groups.
214 // Later on, this gets filtered for what can actually be removed
215 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
216 $addgroup[] = $group;
218 $removegroup[] = $group;
222 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
226 * Save user groups changes in the database.
228 * @param User|UserRightsProxy $user
229 * @param array $add Array of groups to add
230 * @param array $remove Array of groups to remove
231 * @param string $reason Reason for group change
232 * @return array Tuple of added, then removed groups
234 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
235 // Validate input set...
236 $isself = $user->getName() == $this->getUser()->getName();
237 $groups = $user->getGroups();
238 $changeable = $this->changeableGroups();
239 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
240 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
242 $remove = array_unique(
243 array_intersect( (array)$remove, $removable, $groups ) );
244 $add = array_unique( array_diff(
245 array_intersect( (array)$add, $addable ),
249 $oldGroups = $user->getGroups();
250 $newGroups = $oldGroups;
252 // Remove then add groups
254 foreach ( $remove as $index => $group ) {
255 if ( !$user->removeGroup( $group ) ) {
256 unset( $remove[$index] );
259 $newGroups = array_diff( $newGroups, $remove );
262 foreach ( $add as $index => $group ) {
263 if ( !$user->addGroup( $group ) ) {
264 unset( $add[$index] );
267 $newGroups = array_merge( $newGroups, $add );
269 $newGroups = array_unique( $newGroups );
271 // Ensure that caches are cleared
272 $user->invalidateCache();
274 // update groups in external authentication database
275 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
276 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin(
277 'updateExternalDBGroups', [ $user, $add, $remove ]
280 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
281 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
282 // Deprecated in favor of UserGroupsChanged hook
283 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
285 if ( $newGroups != $oldGroups ) {
286 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
289 return [ $add, $remove ];
293 * Add a rights log entry for an action.
295 * @param array $oldGroups
296 * @param array $newGroups
297 * @param array $reason
299 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
300 $logEntry = new ManualLogEntry( 'rights', 'rights' );
301 $logEntry->setPerformer( $this->getUser() );
302 $logEntry->setTarget( $user->getUserPage() );
303 $logEntry->setComment( $reason );
304 $logEntry->setParameters( [
305 '4::oldgroups' => $oldGroups,
306 '5::newgroups' => $newGroups,
308 $logid = $logEntry->insert();
309 $logEntry->publish( $logid );
313 * Edit user groups membership
314 * @param string $username Name of the user.
316 function editUserGroupsForm( $username ) {
317 $status = $this->fetchUser( $username, true );
318 if ( !$status->isOK() ) {
319 $this->getOutput()->addWikiText( $status->getWikiText() );
323 $user = $status->value
;
326 $groups = $user->getGroups();
328 $this->showEditUserGroupsForm( $user, $groups );
330 // This isn't really ideal logging behavior, but let's not hide the
331 // interwiki logs if we're using them as is.
332 $this->showLogFragment( $user, $this->getOutput() );
336 * Normalize the input username, which may be local or remote, and
337 * return a user (or proxy) object for manipulating it.
339 * Side effects: error output for invalid access
340 * @param string $username
341 * @param bool $writing
344 public function fetchUser( $username, $writing ) {
345 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
346 if ( count( $parts ) < 2 ) {
347 $name = trim( $username );
350 list( $name, $database ) = array_map( 'trim', $parts );
352 if ( $database == wfWikiID() ) {
355 if ( $writing && !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
356 return Status
::newFatal( 'userrights-no-interwiki' );
358 if ( !UserRightsProxy
::validDatabase( $database ) ) {
359 return Status
::newFatal( 'userrights-nodatabase', $database );
364 if ( $name === '' ) {
365 return Status
::newFatal( 'nouserspecified' );
368 if ( $name[0] == '#' ) {
369 // Numeric ID can be specified...
370 // We'll do a lookup for the name internally.
371 $id = intval( substr( $name, 1 ) );
373 if ( $database == '' ) {
374 $name = User
::whoIs( $id );
376 $name = UserRightsProxy
::whoIs( $database, $id );
380 return Status
::newFatal( 'noname' );
383 $name = User
::getCanonicalName( $name );
384 if ( $name === false ) {
386 return Status
::newFatal( 'nosuchusershort', $username );
390 if ( $database == '' ) {
391 $user = User
::newFromName( $name );
393 $user = UserRightsProxy
::newFromName( $database, $name );
396 if ( !$user ||
$user->isAnon() ) {
397 return Status
::newFatal( 'nosuchusershort', $username );
400 return Status
::newGood( $user );
410 public function makeGroupNameList( $ids ) {
411 if ( empty( $ids ) ) {
412 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
414 return implode( ', ', $ids );
419 * Output a form to allow searching for a user
421 function switchForm() {
422 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
424 $this->getOutput()->addHTML(
429 'action' => wfScript(),
431 'id' => 'mw-userrights-form1'
434 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
435 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
437 $this->msg( 'userrights-user-editname' )->text(),
441 str_replace( '_', ' ', $this->mTarget
),
443 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
445 // Set autofocus on blank input and error input
446 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
450 $this->msg( 'editusergroup' )->text()
452 Html
::closeElement( 'fieldset' ) .
453 Html
::closeElement( 'form' ) . "\n"
458 * Go through used and available groups and return the ones that this
459 * form will be able to manipulate based on the current user's system
462 * @param array $groups List of groups the given user is in
463 * @return array Tuple of addable, then removable groups
465 protected function splitGroups( $groups ) {
466 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
468 $removable = array_intersect(
469 array_merge( $this->isself ?
$removeself : [], $removable ),
471 ); // Can't remove groups the user doesn't have
472 $addable = array_diff(
473 array_merge( $this->isself ?
$addself : [], $addable ),
475 ); // Can't add groups the user does have
477 return [ $addable, $removable ];
481 * Show the form to edit group memberships.
483 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
484 * @param array $groups Array of groups the user is in
486 protected function showEditUserGroupsForm( $user, $groups ) {
489 foreach ( $groups as $group ) {
490 $list[] = self
::buildGroupLink( $group );
491 $membersList[] = self
::buildGroupMemberLink( $group );
495 $autoMembersList = [];
496 if ( $user instanceof User
) {
497 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
498 $autoList[] = self
::buildGroupLink( $group );
499 $autoMembersList[] = self
::buildGroupMemberLink( $group );
503 $language = $this->getLanguage();
504 $displayedList = $this->msg( 'userrights-groupsmember-type' )
506 $language->listToText( $list ),
507 $language->listToText( $membersList )
509 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
511 $language->listToText( $autoList ),
512 $language->listToText( $autoMembersList )
516 $count = count( $list );
518 $grouplist = $this->msg( 'userrights-groupsmember' )
519 ->numParams( $count )
520 ->params( $user->getName() )
522 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
525 $count = count( $autoList );
527 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
528 ->numParams( $count )
529 ->params( $user->getName() )
531 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
534 $userToolLinks = Linker
::userToolLinks(
537 false, /* default for redContribsWhenNoEdits */
538 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
541 list( $groupCheckboxes, $canChangeAny ) = $this->groupCheckboxes( $groups, $user );
542 $this->getOutput()->addHTML(
547 'action' => $this->getPageTitle()->getLocalURL(),
548 'name' => 'editGroup',
549 'id' => 'mw-userrights-form2'
552 Html
::hidden( 'user', $this->mTarget
) .
553 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
555 'conflictcheck-originalgroups',
556 implode( ',', $user->getGroups() )
557 ) . // Conflict detection
558 Xml
::openElement( 'fieldset' ) .
562 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
564 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
565 ->rawParams( $userToolLinks )->parse()
567 if ( $canChangeAny ) {
568 $this->getOutput()->addHTML(
569 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
572 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
574 <td class='mw-label'>" .
575 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
577 <td class='mw-input'>" .
578 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
579 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
584 <td class='mw-submit'>" .
585 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
586 [ 'name' => 'saveusergroups' ] +
587 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
591 Xml
::closeElement( 'table' ) . "\n"
594 $this->getOutput()->addHTML( $grouplist );
596 $this->getOutput()->addHTML(
597 Xml
::closeElement( 'fieldset' ) .
598 Xml
::closeElement( 'form' ) . "\n"
603 * Format a link to a group description page
605 * @param string $group
608 private static function buildGroupLink( $group ) {
609 return User
::makeGroupLinkHTML( $group, User
::getGroupName( $group ) );
613 * Format a link to a group member description page
615 * @param string $group
618 private static function buildGroupMemberLink( $group ) {
619 return User
::makeGroupLinkHTML( $group, User
::getGroupMember( $group ) );
623 * Returns an array of all groups that may be edited
624 * @return array Array of groups that may be edited.
626 protected static function getAllGroups() {
627 return User
::getAllGroups();
631 * Adds a table with checkboxes where you can select what groups to add/remove
633 * @todo Just pass the username string?
634 * @param array $usergroups Groups the user belongs to
636 * @return Array with 2 elements: the XHTML table element with checkxboes, and
637 * whether any groups are changeable
639 private function groupCheckboxes( $usergroups, $user ) {
640 $allgroups = $this->getAllGroups();
643 // Put all column info into an associative array so that extensions can
644 // more easily manage it.
645 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
647 foreach ( $allgroups as $group ) {
648 $set = in_array( $group, $usergroups );
649 // Should the checkbox be disabled?
651 ( $set && $this->canRemove( $group ) ) ||
652 ( !$set && $this->canAdd( $group ) ) );
653 // Do we need to point out that this action is irreversible?
654 $irreversible = !$disabled && (
655 ( $set && !$this->canAdd( $group ) ) ||
656 ( !$set && !$this->canRemove( $group ) ) );
660 'disabled' => $disabled,
661 'irreversible' => $irreversible
665 $columns['unchangeable'][$group] = $checkbox;
667 $columns['changeable'][$group] = $checkbox;
671 // Build the HTML table
672 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
674 foreach ( $columns as $name => $column ) {
675 if ( $column === [] ) {
678 // Messages: userrights-changeable-col, userrights-unchangeable-col
679 $ret .= Xml
::element(
682 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
686 $ret .= "</tr>\n<tr>\n";
687 foreach ( $columns as $column ) {
688 if ( $column === [] ) {
691 $ret .= "\t<td style='vertical-align:top;'>\n";
692 foreach ( $column as $group => $checkbox ) {
693 $attr = $checkbox['disabled'] ?
[ 'disabled' => 'disabled' ] : [];
695 $member = User
::getGroupMember( $group, $user->getName() );
696 if ( $checkbox['irreversible'] ) {
697 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
701 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
702 "wpGroup-" . $group, $checkbox['set'], $attr );
703 $ret .= "\t\t" . ( $checkbox['disabled']
704 ? Xml
::tags( 'span', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
710 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
712 return [ $ret, (bool)$columns['changeable'] ];
716 * @param string $group The name of the group to check
717 * @return bool Can we remove the group?
719 private function canRemove( $group ) {
720 $groups = $this->changeableGroups();
724 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
729 * @param string $group The name of the group to check
730 * @return bool Can we add the group?
732 private function canAdd( $group ) {
733 $groups = $this->changeableGroups();
737 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
742 * Returns $this->getUser()->changeableGroups()
744 * @return array Array(
745 * 'add' => array( addablegroups ),
746 * 'remove' => array( removablegroups ),
747 * 'add-self' => array( addablegroups to self ),
748 * 'remove-self' => array( removable groups from self )
751 function changeableGroups() {
752 return $this->getUser()->changeableGroups();
756 * Show a rights log fragment for the specified user
758 * @param User $user User to show log for
759 * @param OutputPage $output OutputPage to use
761 protected function showLogFragment( $user, $output ) {
762 $rightsLogPage = new LogPage( 'rights' );
763 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
764 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
768 * Return an array of subpages beginning with $search that this special page will accept.
770 * @param string $search Prefix to search for
771 * @param int $limit Maximum number of results to return (usually 10)
772 * @param int $offset Number of results to skip (usually 0)
773 * @return string[] Matching subpages
775 public function prefixSearchSubpages( $search, $limit, $offset ) {
776 $user = User
::newFromName( $search );
778 // No prefix suggestion for invalid user
781 // Autocomplete subpage as user list - public to allow caching
782 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
785 protected function getGroupName() {