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 return !empty( $available['add'] )
51 ||
!empty( $available['remove'] )
52 ||
( ( $this->isself ||
!$checkIfSelf ) &&
53 ( !empty( $available['add-self'] )
54 ||
!empty( $available['remove-self'] ) ) );
58 * Manage forms to be shown according to posted data.
59 * Depending on the submit button used, call a form or a save function.
61 * @param $par Mixed: string if any subpage provided, else null
63 public function execute( $par ) {
64 // If the visitor doesn't have permissions to assign or remove
65 // any groups, it's a bit silly to give them the user search prompt.
67 $user = $this->getUser();
70 * If the user is blocked and they only have "partial" access
71 * (e.g. they don't have the userrights permission), then don't
72 * allow them to use Special:UserRights.
74 if( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
75 throw new UserBlockedError( $user->getBlock() );
78 $request = $this->getRequest();
81 $this->mTarget
= $par;
83 $this->mTarget
= $request->getVal( 'user' );
86 $available = $this->changeableGroups();
88 if ( $this->mTarget
=== null ) {
90 * If the user specified no target, and they can only
91 * edit their own groups, automatically set them as the
94 if ( !count( $available['add'] ) && !count( $available['remove'] ) )
95 $this->mTarget
= $user->getName();
98 if ( User
::getCanonicalName( $this->mTarget
) == $user->getName() ) {
102 if( !$this->userCanChangeRights( $user, true ) ) {
103 // @todo FIXME: There may be intermediate groups we can mention.
104 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
105 throw new PermissionsError( null, array( array( $msg ) ) );
108 $this->checkReadOnly();
111 $this->outputHeader();
113 $out = $this->getOutput();
114 $out->addModuleStyles( 'mediawiki.special' );
116 // show the general form
117 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
121 if( $request->wasPosted() ) {
123 if( $request->getCheck( 'saveusergroups' ) ) {
124 $reason = $request->getVal( 'user-reason' );
125 $tok = $request->getVal( 'wpEditToken' );
126 if( $user->matchEditToken( $tok, $this->mTarget
) ) {
127 $this->saveUserGroups(
132 $out->redirect( $this->getSuccessURL() );
138 // show some more forms
139 if( $this->mTarget
!== null ) {
140 $this->editUserGroupsForm( $this->mTarget
);
144 function getSuccessURL() {
145 return $this->getTitle( $this->mTarget
)->getFullURL();
149 * Save user groups changes in the database.
150 * Data comes from the editUserGroupsForm() form function
152 * @param $username String: username to apply changes to.
153 * @param $reason String: reason for group change
156 function saveUserGroups( $username, $reason = '' ) {
157 $status = $this->fetchUser( $username );
158 if( !$status->isOK() ) {
159 $this->getOutput()->addWikiText( $status->getWikiText() );
162 $user = $status->value
;
165 $allgroups = $this->getAllGroups();
167 $removegroup = array();
169 // This could possibly create a highly unlikely race condition if permissions are changed between
170 // when the form is loaded and when the form is saved. Ignoring it for the moment.
171 foreach ( $allgroups as $group ) {
172 // We'll tell it to remove all unchecked groups, and add all checked groups.
173 // Later on, this gets filtered for what can actually be removed
174 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
175 $addgroup[] = $group;
177 $removegroup[] = $group;
181 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
185 * Save user groups changes in the database.
187 * @param $user User object
188 * @param $add Array of groups to add
189 * @param $remove Array of groups to remove
190 * @param $reason String: reason for group change
191 * @return Array: Tuple of added, then removed groups
193 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
194 // Validate input set...
195 $isself = ( $user->getName() == $this->getUser()->getName() );
196 $groups = $user->getGroups();
197 $changeable = $this->changeableGroups();
198 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
199 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
201 $remove = array_unique(
202 array_intersect( (array)$remove, $removable, $groups ) );
203 $add = array_unique( array_diff(
204 array_intersect( (array)$add, $addable ),
208 $oldGroups = $user->getGroups();
209 $newGroups = $oldGroups;
211 // remove then add groups
213 $newGroups = array_diff( $newGroups, $remove );
214 foreach( $remove as $group ) {
215 $user->removeGroup( $group );
219 $newGroups = array_merge( $newGroups, $add );
220 foreach( $add as $group ) {
221 $user->addGroup( $group );
224 $newGroups = array_unique( $newGroups );
226 // Ensure that caches are cleared
227 $user->invalidateCache();
229 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
230 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
231 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
233 if( $newGroups != $oldGroups ) {
234 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
236 return array( $add, $remove );
241 * Add a rights log entry for an action.
243 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
244 $log = new LogPage( 'rights' );
246 $log->addEntry( 'rights',
247 $user->getUserPage(),
250 $this->makeGroupNameListForLog( $oldGroups ),
251 $this->makeGroupNameListForLog( $newGroups )
257 * Edit user groups membership
258 * @param $username String: name of the user.
260 function editUserGroupsForm( $username ) {
261 $status = $this->fetchUser( $username );
262 if( !$status->isOK() ) {
263 $this->getOutput()->addWikiText( $status->getWikiText() );
266 $user = $status->value
;
269 $groups = $user->getGroups();
271 $this->showEditUserGroupsForm( $user, $groups );
273 // This isn't really ideal logging behavior, but let's not hide the
274 // interwiki logs if we're using them as is.
275 $this->showLogFragment( $user, $this->getOutput() );
279 * Normalize the input username, which may be local or remote, and
280 * return a user (or proxy) object for manipulating it.
282 * Side effects: error output for invalid access
283 * @return Status object
285 public function fetchUser( $username ) {
286 global $wgUserrightsInterwikiDelimiter;
288 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
289 if( count( $parts ) < 2 ) {
290 $name = trim( $username );
293 list( $name, $database ) = array_map( 'trim', $parts );
295 if( $database == wfWikiID() ) {
298 if( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
299 return Status
::newFatal( 'userrights-no-interwiki' );
301 if( !UserRightsProxy
::validDatabase( $database ) ) {
302 return Status
::newFatal( 'userrights-nodatabase', $database );
308 return Status
::newFatal( 'nouserspecified' );
311 if( $name[0] == '#' ) {
312 // Numeric ID can be specified...
313 // We'll do a lookup for the name internally.
314 $id = intval( substr( $name, 1 ) );
316 if( $database == '' ) {
317 $name = User
::whoIs( $id );
319 $name = UserRightsProxy
::whoIs( $database, $id );
323 return Status
::newFatal( 'noname' );
326 $name = User
::getCanonicalName( $name );
327 if( $name === false ) {
329 return Status
::newFatal( 'nosuchusershort', $username );
333 if( $database == '' ) {
334 $user = User
::newFromName( $name );
336 $user = UserRightsProxy
::newFromName( $database, $name );
339 if( !$user ||
$user->isAnon() ) {
340 return Status
::newFatal( 'nosuchusershort', $username );
343 return Status
::newGood( $user );
346 function makeGroupNameList( $ids ) {
347 if( empty( $ids ) ) {
348 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
350 return implode( ', ', $ids );
354 function makeGroupNameListForLog( $ids ) {
355 if( empty( $ids ) ) {
358 return $this->makeGroupNameList( $ids );
363 * Output a form to allow searching for a user
365 function switchForm() {
367 $this->getOutput()->addHTML(
368 Html
::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
369 Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
370 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
371 Xml
::inputLabel( $this->msg( 'userrights-user-editname' )->text(), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget
) ) . ' ' .
372 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
373 Html
::closeElement( 'fieldset' ) .
374 Html
::closeElement( 'form' ) . "\n"
379 * Go through used and available groups and return the ones that this
380 * form will be able to manipulate based on the current user's system
383 * @param $groups Array: list of groups the given user is in
384 * @return Array: Tuple of addable, then removable groups
386 protected function splitGroups( $groups ) {
387 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
389 $removable = array_intersect(
390 array_merge( $this->isself ?
$removeself : array(), $removable ),
392 ); // Can't remove groups the user doesn't have
393 $addable = array_diff(
394 array_merge( $this->isself ?
$addself : array(), $addable ),
396 ); // Can't add groups the user does have
398 return array( $addable, $removable );
402 * Show the form to edit group memberships.
404 * @param $user User or UserRightsProxy you're editing
405 * @param $groups Array: Array of groups the user is in
407 protected function showEditUserGroupsForm( $user, $groups ) {
409 foreach( $groups as $group ) {
410 $list[] = self
::buildGroupLink( $group );
414 if ( $user instanceof User
) {
415 foreach( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
416 $autolist[] = self
::buildGroupLink( $group );
421 $count = count( $list );
423 $grouplist = $this->msg( 'userrights-groupsmember', $count )->parse();
424 $grouplist = '<p>' . $grouplist . ' ' . $this->getLanguage()->listToText( $list ) . "</p>\n";
426 $count = count( $autolist );
428 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto', $count )->parse();
429 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $this->getLanguage()->listToText( $autolist ) . "</p>\n";
432 $userToolLinks = Linker
::userToolLinks(
435 false, /* default for redContribsWhenNoEdits */
436 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
439 $this->getOutput()->addHTML(
440 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
441 Html
::hidden( 'user', $this->mTarget
) .
442 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
443 Xml
::openElement( 'fieldset' ) .
444 Xml
::element( 'legend', array(), $this->msg( 'userrights-editusergroup', $user->getName() )->text() ) .
445 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )->rawParams( $userToolLinks )->parse() .
446 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
448 Xml
::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
449 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
451 <td class='mw-label'>" .
452 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
454 <td class='mw-input'>" .
455 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
456 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
461 <td class='mw-submit'>" .
462 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
463 array( 'name' => 'saveusergroups' ) + Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' ) ) .
466 Xml
::closeElement( 'table' ) . "\n" .
467 Xml
::closeElement( 'fieldset' ) .
468 Xml
::closeElement( 'form' ) . "\n"
473 * Format a link to a group description page
475 * @param $group string
478 private static function buildGroupLink( $group ) {
479 static $cache = array();
480 if( !isset( $cache[$group] ) )
481 $cache[$group] = User
::makeGroupLinkHtml( $group, htmlspecialchars( User
::getGroupName( $group ) ) );
482 return $cache[$group];
486 * Returns an array of all groups that may be edited
487 * @return array Array of groups that may be edited.
489 protected static function getAllGroups() {
490 return User
::getAllGroups();
494 * Adds a table with checkboxes where you can select what groups to add/remove
496 * @todo Just pass the username string?
497 * @param $usergroups Array: groups the user belongs to
498 * @param $user User a user object
499 * @return string XHTML table element with checkboxes
501 private function groupCheckboxes( $usergroups, $user ) {
502 $allgroups = $this->getAllGroups();
505 # Put all column info into an associative array so that extensions can
506 # more easily manage it.
507 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
509 foreach( $allgroups as $group ) {
510 $set = in_array( $group, $usergroups );
511 # Should the checkbox be disabled?
513 ( $set && $this->canRemove( $group ) ) ||
514 ( !$set && $this->canAdd( $group ) ) );
515 # Do we need to point out that this action is irreversible?
516 $irreversible = !$disabled && (
517 ( $set && !$this->canAdd( $group ) ) ||
518 ( !$set && !$this->canRemove( $group ) ) );
522 'disabled' => $disabled,
523 'irreversible' => $irreversible
527 $columns['unchangeable'][$group] = $checkbox;
529 $columns['changeable'][$group] = $checkbox;
533 # Build the HTML table
534 $ret .= Xml
::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
536 foreach( $columns as $name => $column ) {
537 if( $column === array() )
539 $ret .= Xml
::element( 'th', null, $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text() );
541 $ret.= "</tr>\n<tr>\n";
542 foreach( $columns as $column ) {
543 if( $column === array() )
545 $ret .= "\t<td style='vertical-align:top;'>\n";
546 foreach( $column as $group => $checkbox ) {
547 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
549 $member = User
::getGroupMember( $group, $user->getName() );
550 if ( $checkbox['irreversible'] ) {
551 $text = $this->msg( 'userrights-irreversible-marker', $member )->escaped();
553 $text = htmlspecialchars( $member );
555 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
556 "wpGroup-" . $group, $checkbox['set'], $attr );
557 $ret .= "\t\t" . ( $checkbox['disabled']
558 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
564 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
570 * @param $group String: the name of the group to check
571 * @return bool Can we remove the group?
573 private function canRemove( $group ) {
574 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
576 $groups = $this->changeableGroups();
577 return in_array( $group, $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] ) );
581 * @param $group string: the name of the group to check
582 * @return bool Can we add the group?
584 private function canAdd( $group ) {
585 $groups = $this->changeableGroups();
586 return in_array( $group, $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] ) );
590 * Returns $this->getUser()->changeableGroups()
592 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
594 function changeableGroups() {
595 return $this->getUser()->changeableGroups();
599 * Show a rights log fragment for the specified user
601 * @param $user User to show log for
602 * @param $output OutputPage to use
604 protected function showLogFragment( $user, $output ) {
605 $output->addHTML( Xml
::element( 'h2', null, LogPage
::logName( 'rights' ) . "\n" ) );
606 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );