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 ) {
151 "<div class=\"successbox\">\n$1\n</div>",
152 [ 'savedrights', $this->mFetchedUser
->getName() ]
156 $this->checkReadOnly();
159 $this->outputHeader();
161 $out->addModuleStyles( 'mediawiki.special' );
162 $this->addHelpLink( 'Help:Assigning permissions' );
164 // show the general form
165 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
170 $request->wasPosted() &&
171 $request->getCheck( 'saveusergroups' ) &&
172 $this->mTarget
!== null &&
173 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
176 if ( !$fetchedStatus->isOK() ) {
177 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
182 $targetUser = $this->mFetchedUser
;
183 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
184 $targetUser->clearInstanceCache(); // bug 38989
187 if ( $request->getVal( 'conflictcheck-originalgroups' )
188 !== implode( ',', $targetUser->getGroups() )
190 $out->addWikiMsg( 'userrights-conflict' );
192 $this->saveUserGroups(
194 $request->getVal( 'user-reason' ),
198 $out->redirect( $this->getSuccessURL() );
204 // show some more forms
205 if ( $this->mTarget
!== null ) {
206 $this->editUserGroupsForm( $this->mTarget
);
210 function getSuccessURL() {
211 return $this->getPageTitle( $this->mTarget
)->getFullURL( [ 'success' => 1 ] );
215 * Save user groups changes in the database.
216 * Data comes from the editUserGroupsForm() form function
218 * @param string $username Username to apply changes to.
219 * @param string $reason Reason for group change
220 * @param User|UserRightsProxy $user Target user object.
223 function saveUserGroups( $username, $reason, $user ) {
224 $allgroups = $this->getAllGroups();
228 // This could possibly create a highly unlikely race condition if permissions are changed between
229 // when the form is loaded and when the form is saved. Ignoring it for the moment.
230 foreach ( $allgroups as $group ) {
231 // We'll tell it to remove all unchecked groups, and add all checked groups.
232 // Later on, this gets filtered for what can actually be removed
233 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
234 $addgroup[] = $group;
236 $removegroup[] = $group;
240 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
244 * Save user groups changes in the database.
246 * @param User|UserRightsProxy $user
247 * @param array $add Array of groups to add
248 * @param array $remove Array of groups to remove
249 * @param string $reason Reason for group change
250 * @return array Tuple of added, then removed groups
252 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
255 // Validate input set...
256 $isself = $user->getName() == $this->getUser()->getName();
257 $groups = $user->getGroups();
258 $changeable = $this->changeableGroups();
259 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : [] );
260 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : [] );
262 $remove = array_unique(
263 array_intersect( (array)$remove, $removable, $groups ) );
264 $add = array_unique( array_diff(
265 array_intersect( (array)$add, $addable ),
269 $oldGroups = $user->getGroups();
270 $newGroups = $oldGroups;
272 // Remove then add groups
274 foreach ( $remove as $index => $group ) {
275 if ( !$user->removeGroup( $group ) ) {
276 unset( $remove[$index] );
279 $newGroups = array_diff( $newGroups, $remove );
282 foreach ( $add as $index => $group ) {
283 if ( !$user->addGroup( $group ) ) {
284 unset( $add[$index] );
287 $newGroups = array_merge( $newGroups, $add );
289 $newGroups = array_unique( $newGroups );
291 // Ensure that caches are cleared
292 $user->invalidateCache();
294 // update groups in external authentication database
295 Hooks
::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
296 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
298 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
299 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
300 // Deprecated in favor of UserGroupsChanged hook
301 Hooks
::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
303 if ( $newGroups != $oldGroups ) {
304 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
307 return [ $add, $remove ];
311 * Add a rights log entry for an action.
313 * @param array $oldGroups
314 * @param array $newGroups
315 * @param array $reason
317 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
318 $logEntry = new ManualLogEntry( 'rights', 'rights' );
319 $logEntry->setPerformer( $this->getUser() );
320 $logEntry->setTarget( $user->getUserPage() );
321 $logEntry->setComment( $reason );
322 $logEntry->setParameters( [
323 '4::oldgroups' => $oldGroups,
324 '5::newgroups' => $newGroups,
326 $logid = $logEntry->insert();
327 $logEntry->publish( $logid );
331 * Edit user groups membership
332 * @param string $username Name of the user.
334 function editUserGroupsForm( $username ) {
335 $status = $this->fetchUser( $username );
336 if ( !$status->isOK() ) {
337 $this->getOutput()->addWikiText( $status->getWikiText() );
341 $user = $status->value
;
344 $groups = $user->getGroups();
346 $this->showEditUserGroupsForm( $user, $groups );
348 // This isn't really ideal logging behavior, but let's not hide the
349 // interwiki logs if we're using them as is.
350 $this->showLogFragment( $user, $this->getOutput() );
354 * Normalize the input username, which may be local or remote, and
355 * return a user (or proxy) object for manipulating it.
357 * Side effects: error output for invalid access
358 * @param string $username
361 public function fetchUser( $username ) {
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 ( !$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 );
420 function makeGroupNameList( $ids ) {
421 if ( empty( $ids ) ) {
422 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
424 return implode( ', ', $ids );
429 * Output a form to allow searching for a user
431 function switchForm() {
432 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
434 $this->getOutput()->addHTML(
439 'action' => wfScript(),
441 'id' => 'mw-userrights-form1'
444 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
445 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
447 $this->msg( 'userrights-user-editname' )->text(),
451 str_replace( '_', ' ', $this->mTarget
),
453 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
455 // Set autofocus on blank input and error input
456 $this->mFetchedUser
=== null ?
[ 'autofocus' => '' ] : []
462 $this->mFetchedUser
=== null ?
'[]' : $this->mFetchedUser
->getName()
465 Html
::closeElement( 'fieldset' ) .
466 Html
::closeElement( 'form' ) . "\n"
471 * Go through used and available groups and return the ones that this
472 * form will be able to manipulate based on the current user's system
475 * @param array $groups List of groups the given user is in
476 * @return array Tuple of addable, then removable groups
478 protected function splitGroups( $groups ) {
479 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
481 $removable = array_intersect(
482 array_merge( $this->isself ?
$removeself : [], $removable ),
484 ); // Can't remove groups the user doesn't have
485 $addable = array_diff(
486 array_merge( $this->isself ?
$addself : [], $addable ),
488 ); // Can't add groups the user does have
490 return [ $addable, $removable ];
494 * Show the form to edit group memberships.
496 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
497 * @param array $groups Array of groups the user is in
499 protected function showEditUserGroupsForm( $user, $groups ) {
502 foreach ( $groups as $group ) {
503 $list[] = self
::buildGroupLink( $group );
504 $membersList[] = self
::buildGroupMemberLink( $group );
508 $autoMembersList = [];
509 if ( $user instanceof User
) {
510 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
511 $autoList[] = self
::buildGroupLink( $group );
512 $autoMembersList[] = self
::buildGroupMemberLink( $group );
516 $language = $this->getLanguage();
517 $displayedList = $this->msg( 'userrights-groupsmember-type' )
519 $language->listToText( $list ),
520 $language->listToText( $membersList )
522 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
524 $language->listToText( $autoList ),
525 $language->listToText( $autoMembersList )
529 $count = count( $list );
531 $grouplist = $this->msg( 'userrights-groupsmember' )
532 ->numParams( $count )
533 ->params( $user->getName() )
535 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
538 $count = count( $autoList );
540 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
541 ->numParams( $count )
542 ->params( $user->getName() )
544 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
547 $userToolLinks = Linker
::userToolLinks(
550 false, /* default for redContribsWhenNoEdits */
551 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
554 $this->getOutput()->addHTML(
559 'action' => $this->getPageTitle()->getLocalURL(),
560 'name' => 'editGroup',
561 'id' => 'mw-userrights-form2'
564 Html
::hidden( 'user', $this->mTarget
) .
565 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
567 'conflictcheck-originalgroups',
568 implode( ',', $user->getGroups() )
569 ) . // Conflict detection
570 Xml
::openElement( 'fieldset' ) .
574 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
576 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
577 ->rawParams( $userToolLinks )->parse() .
578 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
580 $this->groupCheckboxes( $groups, $user ) .
581 Xml
::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
583 <td class='mw-label'>" .
584 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
586 <td class='mw-input'>" .
587 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
588 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
593 <td class='mw-submit'>" .
594 Xml
::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
595 [ 'name' => 'saveusergroups' ] +
596 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
600 Xml
::closeElement( 'table' ) . "\n" .
601 Xml
::closeElement( 'fieldset' ) .
602 Xml
::closeElement( 'form' ) . "\n"
607 * Format a link to a group description page
609 * @param string $group
612 private static function buildGroupLink( $group ) {
613 return User
::makeGroupLinkHtml( $group, User
::getGroupName( $group ) );
617 * Format a link to a group member description page
619 * @param string $group
622 private static function buildGroupMemberLink( $group ) {
623 return User
::makeGroupLinkHtml( $group, User
::getGroupMember( $group ) );
627 * Returns an array of all groups that may be edited
628 * @return array Array of groups that may be edited.
630 protected static function getAllGroups() {
631 return User
::getAllGroups();
635 * Adds a table with checkboxes where you can select what groups to add/remove
637 * @todo Just pass the username string?
638 * @param array $usergroups Groups the user belongs to
640 * @return string XHTML table element with checkboxes
642 private function groupCheckboxes( $usergroups, $user ) {
643 $allgroups = $this->getAllGroups();
646 // Put all column info into an associative array so that extensions can
647 // more easily manage it.
648 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
650 foreach ( $allgroups as $group ) {
651 $set = in_array( $group, $usergroups );
652 // Should the checkbox be disabled?
654 ( $set && $this->canRemove( $group ) ) ||
655 ( !$set && $this->canAdd( $group ) ) );
656 // Do we need to point out that this action is irreversible?
657 $irreversible = !$disabled && (
658 ( $set && !$this->canAdd( $group ) ) ||
659 ( !$set && !$this->canRemove( $group ) ) );
663 'disabled' => $disabled,
664 'irreversible' => $irreversible
668 $columns['unchangeable'][$group] = $checkbox;
670 $columns['changeable'][$group] = $checkbox;
674 // Build the HTML table
675 $ret .= Xml
::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
677 foreach ( $columns as $name => $column ) {
678 if ( $column === [] ) {
681 // Messages: userrights-changeable-col, userrights-unchangeable-col
682 $ret .= Xml
::element(
685 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
689 $ret .= "</tr>\n<tr>\n";
690 foreach ( $columns as $column ) {
691 if ( $column === [] ) {
694 $ret .= "\t<td style='vertical-align:top;'>\n";
695 foreach ( $column as $group => $checkbox ) {
696 $attr = $checkbox['disabled'] ?
[ 'disabled' => 'disabled' ] : [];
698 $member = User
::getGroupMember( $group, $user->getName() );
699 if ( $checkbox['irreversible'] ) {
700 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
704 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
705 "wpGroup-" . $group, $checkbox['set'], $attr );
706 $ret .= "\t\t" . ( $checkbox['disabled']
707 ? Xml
::tags( 'span', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
713 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
719 * @param string $group The name of the group to check
720 * @return bool Can we remove the group?
722 private function canRemove( $group ) {
723 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
724 $groups = $this->changeableGroups();
728 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
733 * @param string $group The name of the group to check
734 * @return bool Can we add the group?
736 private function canAdd( $group ) {
737 $groups = $this->changeableGroups();
741 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
746 * Returns $this->getUser()->changeableGroups()
748 * @return array Array(
749 * 'add' => array( addablegroups ),
750 * 'remove' => array( removablegroups ),
751 * 'add-self' => array( addablegroups to self ),
752 * 'remove-self' => array( removable groups from self )
755 function changeableGroups() {
756 return $this->getUser()->changeableGroups();
760 * Show a rights log fragment for the specified user
762 * @param User $user User to show log for
763 * @param OutputPage $output OutputPage to use
765 protected function showLogFragment( $user, $output ) {
766 $rightsLogPage = new LogPage( 'rights' );
767 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
768 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
772 * Return an array of subpages beginning with $search that this special page will accept.
774 * @param string $search Prefix to search for
775 * @param int $limit Maximum number of results to return (usually 10)
776 * @param int $offset Number of results to skip (usually 0)
777 * @return string[] Matching subpages
779 public function prefixSearchSubpages( $search, $limit, $offset ) {
780 $user = User
::newFromName( $search );
782 // No prefix suggestion for invalid user
785 // Autocomplete subpage as user list - public to allow caching
786 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
789 protected function getGroupName() {