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 );
48 public function userCanChangeRights( $user, $checkIfSelf = true ) {
49 $available = $this->changeableGroups();
50 if ( $user->getId() == 0 ) {
53 return !empty( $available['add'] )
54 ||
!empty( $available['remove'] )
55 ||
( ( $this->isself ||
!$checkIfSelf ) &&
56 ( !empty( $available['add-self'] )
57 ||
!empty( $available['remove-self'] ) ) );
61 * Manage forms to be shown according to posted data.
62 * Depending on the submit button used, call a form or a save function.
64 * @param $par Mixed: string if any subpage provided, else null
65 * @throws UserBlockedError|PermissionsError
67 public function execute( $par ) {
68 // If the visitor doesn't have permissions to assign or remove
69 // any groups, it's a bit silly to give them the user search prompt.
71 $user = $this->getUser();
74 * If the user is blocked and they only have "partial" access
75 * (e.g. they don't have the userrights permission), then don't
76 * allow them to use Special:UserRights.
78 if( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
79 throw new UserBlockedError( $user->getBlock() );
82 $request = $this->getRequest();
85 $this->mTarget
= $par;
87 $this->mTarget
= $request->getVal( 'user' );
90 $available = $this->changeableGroups();
92 if ( $this->mTarget
=== null ) {
94 * If the user specified no target, and they can only
95 * edit their own groups, automatically set them as the
98 if ( !count( $available['add'] ) && !count( $available['remove'] ) )
99 $this->mTarget
= $user->getName();
102 if ( User
::getCanonicalName( $this->mTarget
) == $user->getName() ) {
103 $this->isself
= true;
106 if( !$this->userCanChangeRights( $user, true ) ) {
107 // @todo FIXME: There may be intermediate groups we can mention.
108 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
109 throw new PermissionsError( null, array( array( $msg ) ) );
112 $this->checkReadOnly();
115 $this->outputHeader();
117 $out = $this->getOutput();
118 $out->addModuleStyles( 'mediawiki.special' );
120 // show the general form
121 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
125 if( $request->wasPosted() ) {
127 if( $request->getCheck( 'saveusergroups' ) ) {
128 $reason = $request->getVal( 'user-reason' );
129 $tok = $request->getVal( 'wpEditToken' );
130 if( $user->matchEditToken( $tok, $this->mTarget
) ) {
131 $this->saveUserGroups(
136 $out->redirect( $this->getSuccessURL() );
142 // show some more forms
143 if( $this->mTarget
!== null ) {
144 $this->editUserGroupsForm( $this->mTarget
);
148 function getSuccessURL() {
149 return $this->getTitle( $this->mTarget
)->getFullURL();
153 * Save user groups changes in the database.
154 * Data comes from the editUserGroupsForm() form function
156 * @param $username String: username to apply changes to.
157 * @param $reason String: reason for group change
160 function saveUserGroups( $username, $reason = '' ) {
161 $status = $this->fetchUser( $username );
162 if( !$status->isOK() ) {
163 $this->getOutput()->addWikiText( $status->getWikiText() );
166 $user = $status->value
;
169 $allgroups = $this->getAllGroups();
171 $removegroup = array();
173 // This could possibly create a highly unlikely race condition if permissions are changed between
174 // when the form is loaded and when the form is saved. Ignoring it for the moment.
175 foreach ( $allgroups as $group ) {
176 // We'll tell it to remove all unchecked groups, and add all checked groups.
177 // Later on, this gets filtered for what can actually be removed
178 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
179 $addgroup[] = $group;
181 $removegroup[] = $group;
185 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
189 * Save user groups changes in the database.
191 * @param $user User object
192 * @param $add Array of groups to add
193 * @param $remove Array of groups to remove
194 * @param $reason String: reason for group change
195 * @return Array: Tuple of added, then removed groups
197 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
198 // Validate input set...
199 $isself = ( $user->getName() == $this->getUser()->getName() );
200 $groups = $user->getGroups();
201 $changeable = $this->changeableGroups();
202 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
203 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
205 $remove = array_unique(
206 array_intersect( (array)$remove, $removable, $groups ) );
207 $add = array_unique( array_diff(
208 array_intersect( (array)$add, $addable ),
212 $oldGroups = $user->getGroups();
213 $newGroups = $oldGroups;
215 // remove then add groups
217 $newGroups = array_diff( $newGroups, $remove );
218 foreach( $remove as $group ) {
219 $user->removeGroup( $group );
223 $newGroups = array_merge( $newGroups, $add );
224 foreach( $add as $group ) {
225 $user->addGroup( $group );
228 $newGroups = array_unique( $newGroups );
230 // Ensure that caches are cleared
231 $user->invalidateCache();
233 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
234 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
235 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
237 if( $newGroups != $oldGroups ) {
238 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
240 return array( $add, $remove );
245 * Add a rights log entry for an action.
247 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
248 $log = new LogPage( 'rights' );
250 $log->addEntry( 'rights',
251 $user->getUserPage(),
254 $this->makeGroupNameListForLog( $oldGroups ),
255 $this->makeGroupNameListForLog( $newGroups )
261 * Edit user groups membership
262 * @param $username String: name of the user.
264 function editUserGroupsForm( $username ) {
265 $status = $this->fetchUser( $username );
266 if( !$status->isOK() ) {
267 $this->getOutput()->addWikiText( $status->getWikiText() );
270 $user = $status->value
;
273 $groups = $user->getGroups();
275 $this->showEditUserGroupsForm( $user, $groups );
277 // This isn't really ideal logging behavior, but let's not hide the
278 // interwiki logs if we're using them as is.
279 $this->showLogFragment( $user, $this->getOutput() );
283 * Normalize the input username, which may be local or remote, and
284 * return a user (or proxy) object for manipulating it.
286 * Side effects: error output for invalid access
287 * @return Status object
289 public function fetchUser( $username ) {
290 global $wgUserrightsInterwikiDelimiter;
292 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
293 if( count( $parts ) < 2 ) {
294 $name = trim( $username );
297 list( $name, $database ) = array_map( 'trim', $parts );
299 if( $database == wfWikiID() ) {
302 if( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
303 return Status
::newFatal( 'userrights-no-interwiki' );
305 if( !UserRightsProxy
::validDatabase( $database ) ) {
306 return Status
::newFatal( 'userrights-nodatabase', $database );
312 return Status
::newFatal( 'nouserspecified' );
315 if( $name[0] == '#' ) {
316 // Numeric ID can be specified...
317 // We'll do a lookup for the name internally.
318 $id = intval( substr( $name, 1 ) );
320 if( $database == '' ) {
321 $name = User
::whoIs( $id );
323 $name = UserRightsProxy
::whoIs( $database, $id );
327 return Status
::newFatal( 'noname' );
330 $name = User
::getCanonicalName( $name );
331 if( $name === false ) {
333 return Status
::newFatal( 'nosuchusershort', $username );
337 if( $database == '' ) {
338 $user = User
::newFromName( $name );
340 $user = UserRightsProxy
::newFromName( $database, $name );
343 if( !$user ||
$user->isAnon() ) {
344 return Status
::newFatal( 'nosuchusershort', $username );
347 return Status
::newGood( $user );
350 function makeGroupNameList( $ids ) {
351 if( empty( $ids ) ) {
352 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
354 return implode( ', ', $ids );
358 function makeGroupNameListForLog( $ids ) {
359 if( empty( $ids ) ) {
362 return $this->makeGroupNameList( $ids );
367 * Output a form to allow searching for a user
369 function switchForm() {
371 $this->getOutput()->addHTML(
372 Html
::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
373 Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
374 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
375 Xml
::inputLabel( $this->msg( 'userrights-user-editname' )->text(), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget
) ) . ' ' .
376 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
377 Html
::closeElement( 'fieldset' ) .
378 Html
::closeElement( 'form' ) . "\n"
383 * Go through used and available groups and return the ones that this
384 * form will be able to manipulate based on the current user's system
387 * @param $groups Array: list of groups the given user is in
388 * @return Array: Tuple of addable, then removable groups
390 protected function splitGroups( $groups ) {
391 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
393 $removable = array_intersect(
394 array_merge( $this->isself ?
$removeself : array(), $removable ),
396 ); // Can't remove groups the user doesn't have
397 $addable = array_diff(
398 array_merge( $this->isself ?
$addself : array(), $addable ),
400 ); // Can't add groups the user does have
402 return array( $addable, $removable );
406 * Show the form to edit group memberships.
408 * @param $user User or UserRightsProxy you're editing
409 * @param $groups Array: Array of groups the user is in
411 protected function showEditUserGroupsForm( $user, $groups ) {
413 foreach( $groups as $group ) {
414 $list[] = self
::buildGroupLink( $group );
418 if ( $user instanceof User
) {
419 foreach( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
420 $autolist[] = self
::buildGroupLink( $group );
425 $count = count( $list );
427 $grouplist = $this->msg( 'userrights-groupsmember', $count, $user->getName() )->parse();
428 $grouplist = '<p>' . $grouplist . ' ' . $this->getLanguage()->listToText( $list ) . "</p>\n";
430 $count = count( $autolist );
432 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto', $count, $user->getName() )->parse();
433 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $this->getLanguage()->listToText( $autolist ) . "</p>\n";
436 $userToolLinks = Linker
::userToolLinks(
439 false, /* default for redContribsWhenNoEdits */
440 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
443 $this->getOutput()->addHTML(
444 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
445 Html
::hidden( 'user', $this->mTarget
) .
446 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
447 Xml
::openElement( 'fieldset' ) .
448 Xml
::element( 'legend', array(), $this->msg( 'userrights-editusergroup', $user->getName() )->text() ) .
449 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )->rawParams( $userToolLinks )->parse() .
450 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
452 Xml
::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
453 Xml
::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
455 <td class='mw-label'>" .
456 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
458 <td class='mw-input'>" .
459 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
460 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
465 <td class='mw-submit'>" .
466 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
467 array( 'name' => 'saveusergroups' ) + Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' ) ) .
470 Xml
::closeElement( 'table' ) . "\n" .
471 Xml
::closeElement( 'fieldset' ) .
472 Xml
::closeElement( 'form' ) . "\n"
477 * Format a link to a group description page
479 * @param $group string
482 private static function buildGroupLink( $group ) {
483 static $cache = array();
484 if( !isset( $cache[$group] ) )
485 $cache[$group] = User
::makeGroupLinkHtml( $group, htmlspecialchars( User
::getGroupName( $group ) ) );
486 return $cache[$group];
490 * Returns an array of all groups that may be edited
491 * @return array Array of groups that may be edited.
493 protected static function getAllGroups() {
494 return User
::getAllGroups();
498 * Adds a table with checkboxes where you can select what groups to add/remove
500 * @todo Just pass the username string?
501 * @param $usergroups Array: groups the user belongs to
502 * @param $user User a user object
503 * @return string XHTML table element with checkboxes
505 private function groupCheckboxes( $usergroups, $user ) {
506 $allgroups = $this->getAllGroups();
509 # Put all column info into an associative array so that extensions can
510 # more easily manage it.
511 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
513 foreach( $allgroups as $group ) {
514 $set = in_array( $group, $usergroups );
515 # Should the checkbox be disabled?
517 ( $set && $this->canRemove( $group ) ) ||
518 ( !$set && $this->canAdd( $group ) ) );
519 # Do we need to point out that this action is irreversible?
520 $irreversible = !$disabled && (
521 ( $set && !$this->canAdd( $group ) ) ||
522 ( !$set && !$this->canRemove( $group ) ) );
526 'disabled' => $disabled,
527 'irreversible' => $irreversible
531 $columns['unchangeable'][$group] = $checkbox;
533 $columns['changeable'][$group] = $checkbox;
537 # Build the HTML table
538 $ret .= Xml
::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
540 foreach( $columns as $name => $column ) {
541 if( $column === array() )
543 $ret .= Xml
::element( 'th', null, $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text() );
545 $ret.= "</tr>\n<tr>\n";
546 foreach( $columns as $column ) {
547 if( $column === array() )
549 $ret .= "\t<td style='vertical-align:top;'>\n";
550 foreach( $column as $group => $checkbox ) {
551 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
553 $member = User
::getGroupMember( $group, $user->getName() );
554 if ( $checkbox['irreversible'] ) {
555 $text = $this->msg( 'userrights-irreversible-marker', $member )->escaped();
557 $text = htmlspecialchars( $member );
559 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
560 "wpGroup-" . $group, $checkbox['set'], $attr );
561 $ret .= "\t\t" . ( $checkbox['disabled']
562 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
568 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
574 * @param $group String: the name of the group to check
575 * @return bool Can we remove the group?
577 private function canRemove( $group ) {
578 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
580 $groups = $this->changeableGroups();
581 return in_array( $group, $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] ) );
585 * @param $group string: the name of the group to check
586 * @return bool Can we add the group?
588 private function canAdd( $group ) {
589 $groups = $this->changeableGroups();
590 return in_array( $group, $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] ) );
594 * Returns $this->getUser()->changeableGroups()
596 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
598 function changeableGroups() {
599 return $this->getUser()->changeableGroups();
603 * Show a rights log fragment for the specified user
605 * @param $user User to show log for
606 * @param $output OutputPage to use
608 protected function showLogFragment( $user, $output ) {
609 $rightsLogPage = new LogPage( 'rights' );
610 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
611 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );