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
34 protected $isself = false;
36 public function __construct() {
37 parent
::__construct( 'Userrights' );
40 public function isRestricted() {
44 public function userCanExecute( User
$user ) {
45 return $this->userCanChangeRights( $user, false );
50 * @param bool $checkIfSelf
53 public function userCanChangeRights( $user, $checkIfSelf = true ) {
54 $available = $this->changeableGroups();
55 if ( $user->getId() == 0 ) {
59 return !empty( $available['add'] )
60 ||
!empty( $available['remove'] )
61 ||
( ( $this->isself ||
!$checkIfSelf ) &&
62 ( !empty( $available['add-self'] )
63 ||
!empty( $available['remove-self'] ) ) );
67 * Manage forms to be shown according to posted data.
68 * Depending on the submit button used, call a form or a save function.
70 * @param string|null $par String if any subpage provided, else null
71 * @throws UserBlockedError|PermissionsError
73 public function execute( $par ) {
74 // If the visitor doesn't have permissions to assign or remove
75 // any groups, it's a bit silly to give them the user search prompt.
77 $user = $this->getUser();
80 * If the user is blocked and they only have "partial" access
81 * (e.g. they don't have the userrights permission), then don't
82 * allow them to use Special:UserRights.
84 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
85 throw new UserBlockedError( $user->getBlock() );
88 $request = $this->getRequest();
90 if ( $par !== null ) {
91 $this->mTarget
= $par;
93 $this->mTarget
= $request->getVal( 'user' );
96 $available = $this->changeableGroups();
98 if ( $this->mTarget
=== null ) {
100 * If the user specified no target, and they can only
101 * edit their own groups, automatically set them as the
104 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
105 $this->mTarget
= $user->getName();
109 if ( User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
110 $this->isself
= true;
113 if ( !$this->userCanChangeRights( $user, true ) ) {
114 if ( $this->isself
&& $request->getCheck( 'success' ) ) {
115 // bug 48609: if the user just removed its own rights, this would
116 // leads it in a "permissions error" page. In that case, show a
117 // message that it can't anymore use this page instead of an error
119 $out = $this->getOutput();
120 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
121 $out->returnToMain();
126 // @todo FIXME: There may be intermediate groups we can mention.
127 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
128 throw new PermissionsError( null, array( array( $msg ) ) );
131 $this->checkReadOnly();
134 $this->outputHeader();
136 $out = $this->getOutput();
137 $out->addModuleStyles( 'mediawiki.special' );
138 $out->addHelpLink( 'Help:Assigning permissions' );
140 // show the general form
141 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
146 $request->wasPosted() &&
147 $request->getCheck( 'saveusergroups' ) &&
148 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
151 $status = $this->fetchUser( $this->mTarget
);
152 if ( !$status->isOK() ) {
153 $this->getOutput()->addWikiText( $status->getWikiText() );
158 $targetUser = $status->value
;
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( array( '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();
202 $removegroup = array();
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 = '' ) {
231 // Validate input set...
232 $isself = $user->getName() == $this->getUser()->getName();
233 $groups = $user->getGroups();
234 $changeable = $this->changeableGroups();
235 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
236 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
238 $remove = array_unique(
239 array_intersect( (array)$remove, $removable, $groups ) );
240 $add = array_unique( array_diff(
241 array_intersect( (array)$add, $addable ),
245 $oldGroups = $user->getGroups();
246 $newGroups = $oldGroups;
248 // Remove then add groups
250 foreach ( $remove as $index => $group ) {
251 if ( !$user->removeGroup( $group ) ) {
252 unset($remove[$index]);
255 $newGroups = array_diff( $newGroups, $remove );
258 foreach ( $add as $index => $group ) {
259 if ( !$user->addGroup( $group ) ) {
263 $newGroups = array_merge( $newGroups, $add );
265 $newGroups = array_unique( $newGroups );
267 // Ensure that caches are cleared
268 $user->invalidateCache();
270 // update groups in external authentication database
271 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
273 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
274 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
275 Hooks
::run( 'UserRights', array( &$user, $add, $remove ) );
277 if ( $newGroups != $oldGroups ) {
278 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
281 return array( $add, $remove );
285 * Add a rights log entry for an action.
287 * @param array $oldGroups
288 * @param array $newGroups
289 * @param array $reason
291 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
292 $logEntry = new ManualLogEntry( 'rights', 'rights' );
293 $logEntry->setPerformer( $this->getUser() );
294 $logEntry->setTarget( $user->getUserPage() );
295 $logEntry->setComment( $reason );
296 $logEntry->setParameters( array(
297 '4::oldgroups' => $oldGroups,
298 '5::newgroups' => $newGroups,
300 $logid = $logEntry->insert();
301 $logEntry->publish( $logid );
305 * Edit user groups membership
306 * @param string $username Name of the user.
308 function editUserGroupsForm( $username ) {
309 $status = $this->fetchUser( $username );
310 if ( !$status->isOK() ) {
311 $this->getOutput()->addWikiText( $status->getWikiText() );
315 $user = $status->value
;
318 $groups = $user->getGroups();
320 $this->showEditUserGroupsForm( $user, $groups );
322 // This isn't really ideal logging behavior, but let's not hide the
323 // interwiki logs if we're using them as is.
324 $this->showLogFragment( $user, $this->getOutput() );
328 * Normalize the input username, which may be local or remote, and
329 * return a user (or proxy) object for manipulating it.
331 * Side effects: error output for invalid access
332 * @param string $username
335 public function fetchUser( $username ) {
336 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
337 if ( count( $parts ) < 2 ) {
338 $name = trim( $username );
341 list( $name, $database ) = array_map( 'trim', $parts );
343 if ( $database == wfWikiID() ) {
346 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
347 return Status
::newFatal( 'userrights-no-interwiki' );
349 if ( !UserRightsProxy
::validDatabase( $database ) ) {
350 return Status
::newFatal( 'userrights-nodatabase', $database );
355 if ( $name === '' ) {
356 return Status
::newFatal( 'nouserspecified' );
359 if ( $name[0] == '#' ) {
360 // Numeric ID can be specified...
361 // We'll do a lookup for the name internally.
362 $id = intval( substr( $name, 1 ) );
364 if ( $database == '' ) {
365 $name = User
::whoIs( $id );
367 $name = UserRightsProxy
::whoIs( $database, $id );
371 return Status
::newFatal( 'noname' );
374 $name = User
::getCanonicalName( $name );
375 if ( $name === false ) {
377 return Status
::newFatal( 'nosuchusershort', $username );
381 if ( $database == '' ) {
382 $user = User
::newFromName( $name );
384 $user = UserRightsProxy
::newFromName( $database, $name );
387 if ( !$user ||
$user->isAnon() ) {
388 return Status
::newFatal( 'nosuchusershort', $username );
391 return Status
::newGood( $user );
394 function makeGroupNameList( $ids ) {
395 if ( empty( $ids ) ) {
396 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
398 return implode( ', ', $ids );
403 * Make a list of group names to be stored as parameter for log entries
405 * @deprecated since 1.21; use LogFormatter instead.
409 function makeGroupNameListForLog( $ids ) {
410 wfDeprecated( __METHOD__
, '1.21' );
412 if ( empty( $ids ) ) {
415 return $this->makeGroupNameList( $ids );
420 * Output a form to allow searching for a user
422 function switchForm() {
423 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
425 $this->getOutput()->addHTML(
430 'action' => wfScript(),
432 'id' => 'mw-userrights-form1'
435 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
436 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
438 $this->msg( 'userrights-user-editname' )->text(),
442 str_replace( '_', ' ', $this->mTarget
),
445 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
448 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
449 Html
::closeElement( 'fieldset' ) .
450 Html
::closeElement( 'form' ) . "\n"
455 * Go through used and available groups and return the ones that this
456 * form will be able to manipulate based on the current user's system
459 * @param array $groups List of groups the given user is in
460 * @return array Tuple of addable, then removable groups
462 protected function splitGroups( $groups ) {
463 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
465 $removable = array_intersect(
466 array_merge( $this->isself ?
$removeself : array(), $removable ),
468 ); // Can't remove groups the user doesn't have
469 $addable = array_diff(
470 array_merge( $this->isself ?
$addself : array(), $addable ),
472 ); // Can't add groups the user does have
474 return array( $addable, $removable );
478 * Show the form to edit group memberships.
480 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
481 * @param array $groups Array of groups the user is in
483 protected function showEditUserGroupsForm( $user, $groups ) {
485 $membersList = array();
486 foreach ( $groups as $group ) {
487 $list[] = self
::buildGroupLink( $group );
488 $membersList[] = self
::buildGroupMemberLink( $group );
492 $autoMembersList = array();
493 if ( $user instanceof User
) {
494 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
495 $autoList[] = self
::buildGroupLink( $group );
496 $autoMembersList[] = self
::buildGroupMemberLink( $group );
500 $language = $this->getLanguage();
501 $displayedList = $this->msg( 'userrights-groupsmember-type' )
503 $language->listToText( $list ),
504 $language->listToText( $membersList )
506 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
508 $language->listToText( $autoList ),
509 $language->listToText( $autoMembersList )
513 $count = count( $list );
515 $grouplist = $this->msg( 'userrights-groupsmember' )
516 ->numParams( $count )
517 ->params( $user->getName() )
519 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
522 $count = count( $autoList );
524 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
525 ->numParams( $count )
526 ->params( $user->getName() )
528 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
531 $userToolLinks = Linker
::userToolLinks(
534 false, /* default for redContribsWhenNoEdits */
535 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
538 $this->getOutput()->addHTML(
543 'action' => $this->getPageTitle()->getLocalURL(),
544 'name' => 'editGroup',
545 'id' => 'mw-userrights-form2'
548 Html
::hidden( 'user', $this->mTarget
) .
549 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
551 'conflictcheck-originalgroups',
552 implode( ',', $user->getGroups() )
553 ) . // Conflict detection
554 Xml
::openElement( 'fieldset' ) .
558 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
560 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
561 ->rawParams( $userToolLinks )->parse() .
562 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
564 $this->groupCheckboxes( $groups, $user ) .
565 Xml
::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
567 <td class='mw-label'>" .
568 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
570 <td class='mw-input'>" .
571 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
572 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
577 <td class='mw-submit'>" .
578 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
579 array( 'name' => 'saveusergroups' ) +
580 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
584 Xml
::closeElement( 'table' ) . "\n" .
585 Xml
::closeElement( 'fieldset' ) .
586 Xml
::closeElement( 'form' ) . "\n"
591 * Format a link to a group description page
593 * @param string $group
596 private static function buildGroupLink( $group ) {
597 return User
::makeGroupLinkHtml( $group, User
::getGroupName( $group ) );
601 * Format a link to a group member description page
603 * @param string $group
606 private static function buildGroupMemberLink( $group ) {
607 return User
::makeGroupLinkHtml( $group, User
::getGroupMember( $group ) );
611 * Returns an array of all groups that may be edited
612 * @return array Array of groups that may be edited.
614 protected static function getAllGroups() {
615 return User
::getAllGroups();
619 * Adds a table with checkboxes where you can select what groups to add/remove
621 * @todo Just pass the username string?
622 * @param array $usergroups Groups the user belongs to
624 * @return string XHTML table element with checkboxes
626 private function groupCheckboxes( $usergroups, $user ) {
627 $allgroups = $this->getAllGroups();
630 // Put all column info into an associative array so that extensions can
631 // more easily manage it.
632 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
634 foreach ( $allgroups as $group ) {
635 $set = in_array( $group, $usergroups );
636 // Should the checkbox be disabled?
638 ( $set && $this->canRemove( $group ) ) ||
639 ( !$set && $this->canAdd( $group ) ) );
640 // Do we need to point out that this action is irreversible?
641 $irreversible = !$disabled && (
642 ( $set && !$this->canAdd( $group ) ) ||
643 ( !$set && !$this->canRemove( $group ) ) );
647 'disabled' => $disabled,
648 'irreversible' => $irreversible
652 $columns['unchangeable'][$group] = $checkbox;
654 $columns['changeable'][$group] = $checkbox;
658 // Build the HTML table
659 $ret .= Xml
::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
661 foreach ( $columns as $name => $column ) {
662 if ( $column === array() ) {
665 // Messages: userrights-changeable-col, userrights-unchangeable-col
666 $ret .= Xml
::element(
669 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
673 $ret .= "</tr>\n<tr>\n";
674 foreach ( $columns as $column ) {
675 if ( $column === array() ) {
678 $ret .= "\t<td style='vertical-align:top;'>\n";
679 foreach ( $column as $group => $checkbox ) {
680 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
682 $member = User
::getGroupMember( $group, $user->getName() );
683 if ( $checkbox['irreversible'] ) {
684 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
688 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
689 "wpGroup-" . $group, $checkbox['set'], $attr );
690 $ret .= "\t\t" . ( $checkbox['disabled']
691 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
697 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
703 * @param string $group The name of the group to check
704 * @return bool Can we remove the group?
706 private function canRemove( $group ) {
707 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
708 $groups = $this->changeableGroups();
712 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
717 * @param string $group The name of the group to check
718 * @return bool Can we add the group?
720 private function canAdd( $group ) {
721 $groups = $this->changeableGroups();
725 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
730 * Returns $this->getUser()->changeableGroups()
732 * @return array Array(
733 * 'add' => array( addablegroups ),
734 * 'remove' => array( removablegroups ),
735 * 'add-self' => array( addablegroups to self ),
736 * 'remove-self' => array( removable groups from self )
739 function changeableGroups() {
740 return $this->getUser()->changeableGroups();
744 * Show a rights log fragment for the specified user
746 * @param User $user User to show log for
747 * @param OutputPage $output OutputPage to use
749 protected function showLogFragment( $user, $output ) {
750 $rightsLogPage = new LogPage( 'rights' );
751 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
752 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
755 protected function getGroupName() {