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 if ( $this->mTarget
!== null && User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
95 $fetchedStatus = $this->fetchUser( $this->mTarget
, true );
96 if ( $fetchedStatus->isOK() ) {
97 $this->mFetchedUser
= $fetchedStatus->value
;
98 if ( $this->mFetchedUser
instanceof User
) {
99 // Set the 'relevant user' in the skin, so it displays links like Contributions,
100 // User logs, UserRights, etc.
101 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
105 // show a successbox, if the user rights was saved successfully
106 if ( $request->getCheck( 'success' ) && $this->mFetchedUser
!== null ) {
107 $out->addModules( [ 'mediawiki.special.userrights' ] );
108 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
113 'class' => 'mw-notify-success successbox',
114 'id' => 'mw-preferences-success',
115 'data-mw-autohide' => 'false',
120 $this->msg( 'savedrights', $this->mFetchedUser
->getName() )->text()
127 $this->outputHeader();
129 $out->addModuleStyles( 'mediawiki.special' );
130 $this->addHelpLink( 'Help:Assigning permissions' );
135 $request->wasPosted() &&
136 $request->getCheck( 'saveusergroups' ) &&
137 $this->mTarget
!== null &&
138 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
141 * If the user is blocked and they only have "partial" access
142 * (e.g. they don't have the userrights permission), then don't
143 * allow them to change any user rights.
145 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
146 throw new UserBlockedError( $user->getBlock() );
149 $this->checkReadOnly();
152 if ( !$fetchedStatus->isOK() ) {
153 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
158 $targetUser = $this->mFetchedUser
;
159 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
160 $targetUser->clearInstanceCache(); // bug 38989
163 if ( $request->getVal( 'conflictcheck-originalgroups' )
164 !== implode( ',', $targetUser->getGroups() )
166 $out->addWikiMsg( 'userrights-conflict' );
168 $this->saveUserGroups(
170 $request->getVal( 'user-reason' ),
174 $out->redirect( $this->getSuccessURL() );
180 // show some more forms
181 if ( $this->mTarget
!== null ) {
182 $this->editUserGroupsForm( $this->mTarget
);
186 function getSuccessURL() {
187 return $this->getPageTitle( $this->mTarget
)->getFullURL( [ 'success' => 1 ] );
191 * Save user groups changes in the database.
192 * Data comes from the editUserGroupsForm() form function
194 * @param string $username Username to apply changes to.
195 * @param string $reason Reason for group change
196 * @param User|UserRightsProxy $user Target user object.
199 function saveUserGroups( $username, $reason, $user ) {
200 $allgroups = $this->getAllGroups();
204 // This could possibly create a highly unlikely race condition if permissions are changed between
205 // when the form is loaded and when the form is saved. Ignoring it for the moment.
206 foreach ( $allgroups as $group ) {
207 // We'll tell it to remove all unchecked groups, and add all checked groups.
208 // Later on, this gets filtered for what can actually be removed
209 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
210 $addgroup[] = $group;
212 $removegroup[] = $group;
216 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
220 * Save user groups changes in the database.
222 * @param User|UserRightsProxy $user
223 * @param array $add Array of groups to add
224 * @param array $remove Array of groups to remove
225 * @param string $reason Reason for group change
226 * @return array Tuple of added, then removed groups
228 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
229 // Validate input set...
230 $isself = $user->getName() == $this->getUser()->getName();
231 $groups = $user->getGroups();
232 $changeable = $this->changeableGroups();
233 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
234 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
236 $remove = array_unique(
237 array_intersect( (array)$remove, $removable, $groups ) );
238 $add = array_unique( array_diff(
239 array_intersect( (array)$add, $addable ),
243 $oldGroups = $user->getGroups();
244 $newGroups = $oldGroups;
246 // Remove then add groups
248 foreach ( $remove as $index => $group ) {
249 if ( !$user->removeGroup( $group ) ) {
250 unset( $remove[$index] );
253 $newGroups = array_diff( $newGroups, $remove );
256 foreach ( $add as $index => $group ) {
257 if ( !$user->addGroup( $group ) ) {
258 unset( $add[$index] );
261 $newGroups = array_merge( $newGroups, $add );
263 $newGroups = array_unique( $newGroups );
265 // Ensure that caches are cleared
266 $user->invalidateCache();
268 // update groups in external authentication database
269 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
270 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin(
271 'updateExternalDBGroups', [ $user, $add, $remove ]
274 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
275 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
276 // Deprecated in favor of UserGroupsChanged hook
277 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
279 if ( $newGroups != $oldGroups ) {
280 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
283 return [ $add, $remove ];
287 * Add a rights log entry for an action.
289 * @param array $oldGroups
290 * @param array $newGroups
291 * @param array $reason
293 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
294 $logEntry = new ManualLogEntry( 'rights', 'rights' );
295 $logEntry->setPerformer( $this->getUser() );
296 $logEntry->setTarget( $user->getUserPage() );
297 $logEntry->setComment( $reason );
298 $logEntry->setParameters( [
299 '4::oldgroups' => $oldGroups,
300 '5::newgroups' => $newGroups,
302 $logid = $logEntry->insert();
303 $logEntry->publish( $logid );
307 * Edit user groups membership
308 * @param string $username Name of the user.
310 function editUserGroupsForm( $username ) {
311 $status = $this->fetchUser( $username, true );
312 if ( !$status->isOK() ) {
313 $this->getOutput()->addWikiText( $status->getWikiText() );
317 $user = $status->value
;
320 $groups = $user->getGroups();
322 $this->showEditUserGroupsForm( $user, $groups );
324 // This isn't really ideal logging behavior, but let's not hide the
325 // interwiki logs if we're using them as is.
326 $this->showLogFragment( $user, $this->getOutput() );
330 * Normalize the input username, which may be local or remote, and
331 * return a user (or proxy) object for manipulating it.
333 * Side effects: error output for invalid access
334 * @param string $username
335 * @param bool $writing
338 public function fetchUser( $username, $writing = true ) {
339 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
340 if ( count( $parts ) < 2 ) {
341 $name = trim( $username );
344 list( $name, $database ) = array_map( 'trim', $parts );
346 if ( $database == wfWikiID() ) {
349 if ( $writing && !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
350 return Status
::newFatal( 'userrights-no-interwiki' );
352 if ( !UserRightsProxy
::validDatabase( $database ) ) {
353 return Status
::newFatal( 'userrights-nodatabase', $database );
358 if ( $name === '' ) {
359 return Status
::newFatal( 'nouserspecified' );
362 if ( $name[0] == '#' ) {
363 // Numeric ID can be specified...
364 // We'll do a lookup for the name internally.
365 $id = intval( substr( $name, 1 ) );
367 if ( $database == '' ) {
368 $name = User
::whoIs( $id );
370 $name = UserRightsProxy
::whoIs( $database, $id );
374 return Status
::newFatal( 'noname' );
377 $name = User
::getCanonicalName( $name );
378 if ( $name === false ) {
380 return Status
::newFatal( 'nosuchusershort', $username );
384 if ( $database == '' ) {
385 $user = User
::newFromName( $name );
387 $user = UserRightsProxy
::newFromName( $database, $name );
390 if ( !$user ||
$user->isAnon() ) {
391 return Status
::newFatal( 'nosuchusershort', $username );
394 return Status
::newGood( $user );
404 public function makeGroupNameList( $ids ) {
405 if ( empty( $ids ) ) {
406 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
408 return implode( ', ', $ids );
413 * Output a form to allow searching for a user
415 function switchForm() {
416 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
418 $this->getOutput()->addHTML(
423 'action' => wfScript(),
425 'id' => 'mw-userrights-form1'
428 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
429 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
431 $this->msg( 'userrights-user-editname' )->text(),
435 str_replace( '_', ' ', $this->mTarget
),
437 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
439 // Set autofocus on blank input and error input
440 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
444 $this->msg( 'editusergroup' )->text()
446 Html
::closeElement( 'fieldset' ) .
447 Html
::closeElement( 'form' ) . "\n"
452 * Go through used and available groups and return the ones that this
453 * form will be able to manipulate based on the current user's system
456 * @param array $groups List of groups the given user is in
457 * @return array Tuple of addable, then removable groups
459 protected function splitGroups( $groups ) {
460 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
462 $removable = array_intersect(
463 array_merge( $this->isself ?
$removeself : [], $removable ),
465 ); // Can't remove groups the user doesn't have
466 $addable = array_diff(
467 array_merge( $this->isself ?
$addself : [], $addable ),
469 ); // Can't add groups the user does have
471 return [ $addable, $removable ];
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() {