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 $out = $this->getOutput();
81 if ( $par !== null ) {
82 $this->mTarget
= $par;
84 $this->mTarget
= $request->getVal( 'user' );
87 if ( is_string( $this->mTarget
) ) {
88 $this->mTarget
= trim( $this->mTarget
);
91 $fetchedStatus = $this->fetchUser( $this->mTarget
, true );
92 if ( $fetchedStatus->isOK() ) {
93 $this->mFetchedUser
= $fetchedStatus->value
;
94 if ( $this->mFetchedUser
instanceof User
) {
95 // Set the 'relevant user' in the skin, so it displays links like Contributions,
96 // User logs, UserRights, etc.
97 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
101 // show a successbox, if the user rights was saved successfully
102 if ( $request->getCheck( 'success' ) && $this->mFetchedUser
!== null ) {
103 $out->addModules( [ 'mediawiki.special.userrights' ] );
104 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
109 'class' => 'mw-notify-success successbox',
110 'id' => 'mw-preferences-success',
111 'data-mw-autohide' => 'false',
116 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
123 $this->outputHeader();
125 $out->addModuleStyles( 'mediawiki.special' );
126 $this->addHelpLink( 'Help:Assigning permissions' );
131 $request->wasPosted() &&
132 $request->getCheck( 'saveusergroups' ) &&
133 $this->mTarget
!== null &&
134 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
137 * If the user is blocked and they only have "partial" access
138 * (e.g. they don't have the userrights permission), then don't
139 * allow them to change any user rights.
141 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
142 throw new UserBlockedError( $user->getBlock() );
145 $this->checkReadOnly();
148 if ( !$fetchedStatus->isOK() ) {
149 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
154 $targetUser = $this->mFetchedUser
;
155 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
156 $targetUser->clearInstanceCache(); // bug 38989
159 if ( $request->getVal( 'conflictcheck-originalgroups' )
160 !== implode( ',', $targetUser->getGroups() )
162 $out->addWikiMsg( 'userrights-conflict' );
164 $this->saveUserGroups(
166 $request->getVal( 'user-reason' ),
170 $out->redirect( $this->getSuccessURL() );
176 // show some more forms
177 if ( $this->mTarget
!== null ) {
178 $this->editUserGroupsForm( $this->mTarget
);
182 function getSuccessURL() {
183 return $this->getPageTitle( $this->mTarget
)->getFullURL( [ 'success' => 1 ] );
187 * Save user groups changes in the database.
188 * Data comes from the editUserGroupsForm() form function
190 * @param string $username Username to apply changes to.
191 * @param string $reason Reason for group change
192 * @param User|UserRightsProxy $user Target user object.
195 function saveUserGroups( $username, $reason, $user ) {
196 $allgroups = $this->getAllGroups();
200 // This could possibly create a highly unlikely race condition if permissions are changed between
201 // when the form is loaded and when the form is saved. Ignoring it for the moment.
202 foreach ( $allgroups as $group ) {
203 // We'll tell it to remove all unchecked groups, and add all checked groups.
204 // Later on, this gets filtered for what can actually be removed
205 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
206 $addgroup[] = $group;
208 $removegroup[] = $group;
212 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
216 * Save user groups changes in the database.
218 * @param User|UserRightsProxy $user
219 * @param array $add Array of groups to add
220 * @param array $remove Array of groups to remove
221 * @param string $reason Reason for group change
222 * @return array Tuple of added, then removed groups
224 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
225 // Validate input set...
226 $isself = $user->getName() == $this->getUser()->getName();
227 $groups = $user->getGroups();
228 $changeable = $this->changeableGroups();
229 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
230 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
232 $remove = array_unique(
233 array_intersect( (array)$remove, $removable, $groups ) );
234 $add = array_unique( array_diff(
235 array_intersect( (array)$add, $addable ),
239 $oldGroups = $user->getGroups();
240 $newGroups = $oldGroups;
242 // Remove then add groups
244 foreach ( $remove as $index => $group ) {
245 if ( !$user->removeGroup( $group ) ) {
246 unset( $remove[$index] );
249 $newGroups = array_diff( $newGroups, $remove );
252 foreach ( $add as $index => $group ) {
253 if ( !$user->addGroup( $group ) ) {
254 unset( $add[$index] );
257 $newGroups = array_merge( $newGroups, $add );
259 $newGroups = array_unique( $newGroups );
261 // Ensure that caches are cleared
262 $user->invalidateCache();
264 // update groups in external authentication database
265 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
266 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin(
267 'updateExternalDBGroups', [ $user, $add, $remove ]
270 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
271 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
272 // Deprecated in favor of UserGroupsChanged hook
273 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
275 if ( $newGroups != $oldGroups ) {
276 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
279 return [ $add, $remove ];
283 * Add a rights log entry for an action.
285 * @param array $oldGroups
286 * @param array $newGroups
287 * @param array $reason
289 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
290 $logEntry = new ManualLogEntry( 'rights', 'rights' );
291 $logEntry->setPerformer( $this->getUser() );
292 $logEntry->setTarget( $user->getUserPage() );
293 $logEntry->setComment( $reason );
294 $logEntry->setParameters( [
295 '4::oldgroups' => $oldGroups,
296 '5::newgroups' => $newGroups,
298 $logid = $logEntry->insert();
299 $logEntry->publish( $logid );
303 * Edit user groups membership
304 * @param string $username Name of the user.
306 function editUserGroupsForm( $username ) {
307 $status = $this->fetchUser( $username, true );
308 if ( !$status->isOK() ) {
309 $this->getOutput()->addWikiText( $status->getWikiText() );
313 $user = $status->value
;
316 $groups = $user->getGroups();
318 $this->showEditUserGroupsForm( $user, $groups );
320 // This isn't really ideal logging behavior, but let's not hide the
321 // interwiki logs if we're using them as is.
322 $this->showLogFragment( $user, $this->getOutput() );
326 * Normalize the input username, which may be local or remote, and
327 * return a user (or proxy) object for manipulating it.
329 * Side effects: error output for invalid access
330 * @param string $username
331 * @param bool $writing
334 public function fetchUser( $username, $writing = true ) {
335 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
336 if ( count( $parts ) < 2 ) {
337 $name = trim( $username );
340 list( $name, $database ) = array_map( 'trim', $parts );
342 if ( $database == wfWikiID() ) {
345 if ( $writing && !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
346 return Status
::newFatal( 'userrights-no-interwiki' );
348 if ( !UserRightsProxy
::validDatabase( $database ) ) {
349 return Status
::newFatal( 'userrights-nodatabase', $database );
354 if ( $name === '' ) {
355 return Status
::newFatal( 'nouserspecified' );
358 if ( $name[0] == '#' ) {
359 // Numeric ID can be specified...
360 // We'll do a lookup for the name internally.
361 $id = intval( substr( $name, 1 ) );
363 if ( $database == '' ) {
364 $name = User
::whoIs( $id );
366 $name = UserRightsProxy
::whoIs( $database, $id );
370 return Status
::newFatal( 'noname' );
373 $name = User
::getCanonicalName( $name );
374 if ( $name === false ) {
376 return Status
::newFatal( 'nosuchusershort', $username );
380 if ( $database == '' ) {
381 $user = User
::newFromName( $name );
383 $user = UserRightsProxy
::newFromName( $database, $name );
386 if ( !$user ||
$user->isAnon() ) {
387 return Status
::newFatal( 'nosuchusershort', $username );
390 return Status
::newGood( $user );
400 public function makeGroupNameList( $ids ) {
401 if ( empty( $ids ) ) {
402 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
404 return implode( ', ', $ids );
409 * Output a form to allow searching for a user
411 function switchForm() {
412 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
414 $this->getOutput()->addHTML(
419 'action' => wfScript(),
421 'id' => 'mw-userrights-form1'
424 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
425 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
427 $this->msg( 'userrights-user-editname' )->text(),
431 str_replace( '_', ' ', $this->mTarget
),
433 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
435 // Set autofocus on blank input and error input
436 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
440 $this->msg( 'editusergroup' )->text()
442 Html
::closeElement( 'fieldset' ) .
443 Html
::closeElement( 'form' ) . "\n"
448 * Go through used and available groups and return the ones that this
449 * form will be able to manipulate based on the current user's system
452 * @param array $groups List of groups the given user is in
453 * @return array Tuple of addable, then removable groups
455 protected function splitGroups( $groups ) {
456 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
458 $removable = array_intersect(
459 array_merge( $this->isself ?
$removeself : [], $removable ),
461 ); // Can't remove groups the user doesn't have
462 $addable = array_diff(
463 array_merge( $this->isself ?
$addself : [], $addable ),
465 ); // Can't add groups the user does have
467 return [ $addable, $removable ];
471 * Show the form to edit group memberships.
473 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
474 * @param array $groups Array of groups the user is in
476 protected function showEditUserGroupsForm( $user, $groups ) {
479 foreach ( $groups as $group ) {
480 $list[] = self
::buildGroupLink( $group );
481 $membersList[] = self
::buildGroupMemberLink( $group );
485 $autoMembersList = [];
486 if ( $user instanceof User
) {
487 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
488 $autoList[] = self
::buildGroupLink( $group );
489 $autoMembersList[] = self
::buildGroupMemberLink( $group );
493 $language = $this->getLanguage();
494 $displayedList = $this->msg( 'userrights-groupsmember-type' )
496 $language->listToText( $list ),
497 $language->listToText( $membersList )
499 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
501 $language->listToText( $autoList ),
502 $language->listToText( $autoMembersList )
506 $count = count( $list );
508 $grouplist = $this->msg( 'userrights-groupsmember' )
509 ->numParams( $count )
510 ->params( $user->getName() )
512 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
515 $count = count( $autoList );
517 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
518 ->numParams( $count )
519 ->params( $user->getName() )
521 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
524 $userToolLinks = Linker
::userToolLinks(
527 false, /* default for redContribsWhenNoEdits */
528 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
531 list( $groupCheckboxes, $canChangeAny ) = $this->groupCheckboxes( $groups, $user );
532 $this->getOutput()->addHTML(
537 'action' => $this->getPageTitle()->getLocalURL(),
538 'name' => 'editGroup',
539 'id' => 'mw-userrights-form2'
542 Html
::hidden( 'user', $this->mTarget
) .
543 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
545 'conflictcheck-originalgroups',
546 implode( ',', $user->getGroups() )
547 ) . // Conflict detection
548 Xml
::openElement( 'fieldset' ) .
553 $canChangeAny ?
'userrights-editusergroup' : 'userrights-viewusergroup',
558 $canChangeAny ?
'editinguser' : 'viewinguserrights'
559 )->params( wfEscapeWikiText( $user->getName() ) )
560 ->rawParams( $userToolLinks )->parse()
562 if ( $canChangeAny ) {
563 $this->getOutput()->addHTML(
564 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
567 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
569 <td class='mw-label'>" .
570 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
572 <td class='mw-input'>" .
573 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
574 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
579 <td class='mw-submit'>" .
580 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
581 [ 'name' => 'saveusergroups' ] +
582 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
586 Xml
::closeElement( 'table' ) . "\n"
589 $this->getOutput()->addHTML( $grouplist );
591 $this->getOutput()->addHTML(
592 Xml
::closeElement( 'fieldset' ) .
593 Xml
::closeElement( 'form' ) . "\n"
598 * Format a link to a group description page
600 * @param string $group
603 private static function buildGroupLink( $group ) {
604 return User
::makeGroupLinkHTML( $group, User
::getGroupName( $group ) );
608 * Format a link to a group member description page
610 * @param string $group
613 private static function buildGroupMemberLink( $group ) {
614 return User
::makeGroupLinkHTML( $group, User
::getGroupMember( $group ) );
618 * Returns an array of all groups that may be edited
619 * @return array Array of groups that may be edited.
621 protected static function getAllGroups() {
622 return User
::getAllGroups();
626 * Adds a table with checkboxes where you can select what groups to add/remove
628 * @todo Just pass the username string?
629 * @param array $usergroups Groups the user belongs to
631 * @return Array with 2 elements: the XHTML table element with checkxboes, and
632 * whether any groups are changeable
634 private function groupCheckboxes( $usergroups, $user ) {
635 $allgroups = $this->getAllGroups();
638 // Put all column info into an associative array so that extensions can
639 // more easily manage it.
640 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
642 foreach ( $allgroups as $group ) {
643 $set = in_array( $group, $usergroups );
644 // Should the checkbox be disabled?
646 ( $set && $this->canRemove( $group ) ) ||
647 ( !$set && $this->canAdd( $group ) ) );
648 // Do we need to point out that this action is irreversible?
649 $irreversible = !$disabled && (
650 ( $set && !$this->canAdd( $group ) ) ||
651 ( !$set && !$this->canRemove( $group ) ) );
655 'disabled' => $disabled,
656 'irreversible' => $irreversible
660 $columns['unchangeable'][$group] = $checkbox;
662 $columns['changeable'][$group] = $checkbox;
666 // Build the HTML table
667 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
669 foreach ( $columns as $name => $column ) {
670 if ( $column === [] ) {
673 // Messages: userrights-changeable-col, userrights-unchangeable-col
674 $ret .= Xml
::element(
677 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
681 $ret .= "</tr>\n<tr>\n";
682 foreach ( $columns as $column ) {
683 if ( $column === [] ) {
686 $ret .= "\t<td style='vertical-align:top;'>\n";
687 foreach ( $column as $group => $checkbox ) {
688 $attr = $checkbox['disabled'] ?
[ 'disabled' => 'disabled' ] : [];
690 $member = User
::getGroupMember( $group, $user->getName() );
691 if ( $checkbox['irreversible'] ) {
692 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
696 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
697 "wpGroup-" . $group, $checkbox['set'], $attr );
698 $ret .= "\t\t" . ( $checkbox['disabled']
699 ? Xml
::tags( 'span', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
705 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
707 return [ $ret, (bool)$columns['changeable'] ];
711 * @param string $group The name of the group to check
712 * @return bool Can we remove the group?
714 private function canRemove( $group ) {
715 $groups = $this->changeableGroups();
719 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
724 * @param string $group The name of the group to check
725 * @return bool Can we add the group?
727 private function canAdd( $group ) {
728 $groups = $this->changeableGroups();
732 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
737 * Returns $this->getUser()->changeableGroups()
739 * @return array Array(
740 * 'add' => array( addablegroups ),
741 * 'remove' => array( removablegroups ),
742 * 'add-self' => array( addablegroups to self ),
743 * 'remove-self' => array( removable groups from self )
746 function changeableGroups() {
747 return $this->getUser()->changeableGroups();
751 * Show a rights log fragment for the specified user
753 * @param User $user User to show log for
754 * @param OutputPage $output OutputPage to use
756 protected function showLogFragment( $user, $output ) {
757 $rightsLogPage = new LogPage( 'rights' );
758 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
759 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
763 * Return an array of subpages beginning with $search that this special page will accept.
765 * @param string $search Prefix to search for
766 * @param int $limit Maximum number of results to return (usually 10)
767 * @param int $offset Number of results to skip (usually 0)
768 * @return string[] Matching subpages
770 public function prefixSearchSubpages( $search, $limit, $offset ) {
771 $user = User
::newFromName( $search );
773 // No prefix suggestion for invalid user
776 // Autocomplete subpage as user list - public to allow caching
777 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
780 protected function getGroupName() {