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->mBlock
);
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 if ( wfReadOnly() ) {
109 throw new ReadOnlyError
;
113 $this->outputHeader();
115 $out = $this->getOutput();
116 $out->addModuleStyles( 'mediawiki.special' );
118 // show the general form
119 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
123 if( $request->wasPosted() ) {
125 if( $request->getCheck( 'saveusergroups' ) ) {
126 $reason = $request->getVal( 'user-reason' );
127 $tok = $request->getVal( 'wpEditToken' );
128 if( $user->matchEditToken( $tok, $this->mTarget
) ) {
129 $this->saveUserGroups(
134 $out->redirect( $this->getSuccessURL() );
140 // show some more forms
141 if( $this->mTarget
!== null ) {
142 $this->editUserGroupsForm( $this->mTarget
);
146 function getSuccessURL() {
147 return $this->getTitle( $this->mTarget
)->getFullURL();
151 * Save user groups changes in the database.
152 * Data comes from the editUserGroupsForm() form function
154 * @param $username String: username to apply changes to.
155 * @param $reason String: reason for group change
158 function saveUserGroups( $username, $reason = '' ) {
159 $status = $this->fetchUser( $username );
160 if( !$status->isOK() ) {
161 $this->getOutput()->addWikiText( $status->getWikiText() );
164 $user = $status->value
;
167 $allgroups = $this->getAllGroups();
169 $removegroup = array();
171 // This could possibly create a highly unlikely race condition if permissions are changed between
172 // when the form is loaded and when the form is saved. Ignoring it for the moment.
173 foreach ( $allgroups as $group ) {
174 // We'll tell it to remove all unchecked groups, and add all checked groups.
175 // Later on, this gets filtered for what can actually be removed
176 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
177 $addgroup[] = $group;
179 $removegroup[] = $group;
183 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
187 * Save user groups changes in the database.
189 * @param $user User object
190 * @param $add Array of groups to add
191 * @param $remove Array of groups to remove
192 * @param $reason String: reason for group change
193 * @return Array: Tuple of added, then removed groups
195 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
196 // Validate input set...
197 $isself = ( $user->getName() == $this->getUser()->getName() );
198 $groups = $user->getGroups();
199 $changeable = $this->changeableGroups();
200 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
201 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
203 $remove = array_unique(
204 array_intersect( (array)$remove, $removable, $groups ) );
205 $add = array_unique( array_diff(
206 array_intersect( (array)$add, $addable ),
210 $oldGroups = $user->getGroups();
211 $newGroups = $oldGroups;
213 // remove then add groups
215 $newGroups = array_diff( $newGroups, $remove );
216 foreach( $remove as $group ) {
217 $user->removeGroup( $group );
221 $newGroups = array_merge( $newGroups, $add );
222 foreach( $add as $group ) {
223 $user->addGroup( $group );
226 $newGroups = array_unique( $newGroups );
228 // Ensure that caches are cleared
229 $user->invalidateCache();
231 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
232 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
233 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
235 if( $newGroups != $oldGroups ) {
236 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
238 return array( $add, $remove );
243 * Add a rights log entry for an action.
245 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
246 $log = new LogPage( 'rights' );
248 $log->addEntry( 'rights',
249 $user->getUserPage(),
252 $this->makeGroupNameListForLog( $oldGroups ),
253 $this->makeGroupNameListForLog( $newGroups )
259 * Edit user groups membership
260 * @param $username String: name of the user.
262 function editUserGroupsForm( $username ) {
263 $status = $this->fetchUser( $username );
264 if( !$status->isOK() ) {
265 $this->getOutput()->addWikiText( $status->getWikiText() );
268 $user = $status->value
;
271 $groups = $user->getGroups();
273 $this->showEditUserGroupsForm( $user, $groups );
275 // This isn't really ideal logging behavior, but let's not hide the
276 // interwiki logs if we're using them as is.
277 $this->showLogFragment( $user, $this->getOutput() );
281 * Normalize the input username, which may be local or remote, and
282 * return a user (or proxy) object for manipulating it.
284 * Side effects: error output for invalid access
285 * @return Status object
287 public function fetchUser( $username ) {
288 global $wgUserrightsInterwikiDelimiter;
290 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
291 if( count( $parts ) < 2 ) {
292 $name = trim( $username );
295 list( $name, $database ) = array_map( 'trim', $parts );
297 if( $database == wfWikiID() ) {
300 if( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
301 return Status
::newFatal( 'userrights-no-interwiki' );
303 if( !UserRightsProxy
::validDatabase( $database ) ) {
304 return Status
::newFatal( 'userrights-nodatabase', $database );
310 return Status
::newFatal( 'nouserspecified' );
313 if( $name[0] == '#' ) {
314 // Numeric ID can be specified...
315 // We'll do a lookup for the name internally.
316 $id = intval( substr( $name, 1 ) );
318 if( $database == '' ) {
319 $name = User
::whoIs( $id );
321 $name = UserRightsProxy
::whoIs( $database, $id );
325 return Status
::newFatal( 'noname' );
328 $name = User
::getCanonicalName( $name );
329 if( $name === false ) {
331 return Status
::newFatal( 'nosuchusershort', $username );
335 if( $database == '' ) {
336 $user = User
::newFromName( $name );
338 $user = UserRightsProxy
::newFromName( $database, $name );
341 if( !$user ||
$user->isAnon() ) {
342 return Status
::newFatal( 'nosuchusershort', $username );
345 return Status
::newGood( $user );
348 function makeGroupNameList( $ids ) {
349 if( empty( $ids ) ) {
350 return wfMsgForContent( 'rightsnone' );
352 return implode( ', ', $ids );
356 function makeGroupNameListForLog( $ids ) {
357 if( empty( $ids ) ) {
360 return $this->makeGroupNameList( $ids );
365 * Output a form to allow searching for a user
367 function switchForm() {
369 $this->getOutput()->addHTML(
370 Html
::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
371 Html
::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
372 Xml
::fieldset( wfMsg( 'userrights-lookup-user' ) ) .
373 Xml
::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget
) ) . ' ' .
374 Xml
::submitButton( wfMsg( 'editusergroup' ) ) .
375 Html
::closeElement( 'fieldset' ) .
376 Html
::closeElement( 'form' ) . "\n"
381 * Go through used and available groups and return the ones that this
382 * form will be able to manipulate based on the current user's system
385 * @param $groups Array: list of groups the given user is in
386 * @return Array: Tuple of addable, then removable groups
388 protected function splitGroups( $groups ) {
389 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
391 $removable = array_intersect(
392 array_merge( $this->isself ?
$removeself : array(), $removable ),
394 ); // Can't remove groups the user doesn't have
395 $addable = array_diff(
396 array_merge( $this->isself ?
$addself : array(), $addable ),
398 ); // Can't add groups the user does have
400 return array( $addable, $removable );
404 * Show the form to edit group memberships.
406 * @param $user User or UserRightsProxy you're editing
407 * @param $groups Array: Array of groups the user is in
409 protected function showEditUserGroupsForm( $user, $groups ) {
411 foreach( $groups as $group ) {
412 $list[] = self
::buildGroupLink( $group );
416 if ( $user instanceof User
) {
417 foreach( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
418 $autolist[] = self
::buildGroupLink( $group );
423 $count = count( $list );
425 $grouplist = wfMessage( 'userrights-groupsmember', $count)->parse();
426 $grouplist = '<p>' . $grouplist . ' ' . $this->getLang()->listToText( $list ) . "</p>\n";
428 $count = count( $autolist );
430 $autogrouplistintro = wfMessage( 'userrights-groupsmember-auto', $count)->parse();
431 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $this->getLang()->listToText( $autolist ) . "</p>\n";
434 $userToolLinks = Linker
::userToolLinks(
437 false, /* default for redContribsWhenNoEdits */
438 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
441 $this->getOutput()->addHTML(
442 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
443 Html
::hidden( 'user', $this->mTarget
) .
444 Html
::hidden( 'wpEditToken', $this->getUser()->editToken( $this->mTarget
) ) .
445 Xml
::openElement( 'fieldset' ) .
446 Xml
::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
447 wfMessage( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )->rawParams( $userToolLinks )->parse() .
448 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
450 Xml
::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
451 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
453 <td class='mw-label'>" .
454 Xml
::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
456 <td class='mw-input'>" .
457 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
458 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
463 <td class='mw-submit'>" .
464 Xml
::submitButton( wfMsg( 'saveusergroups' ),
465 array( 'name' => 'saveusergroups' ) + Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' ) ) .
468 Xml
::closeElement( 'table' ) . "\n" .
469 Xml
::closeElement( 'fieldset' ) .
470 Xml
::closeElement( 'form' ) . "\n"
475 * Format a link to a group description page
477 * @param $group string
480 private static function buildGroupLink( $group ) {
481 static $cache = array();
482 if( !isset( $cache[$group] ) )
483 $cache[$group] = User
::makeGroupLinkHtml( $group, htmlspecialchars( User
::getGroupName( $group ) ) );
484 return $cache[$group];
488 * Returns an array of all groups that may be edited
489 * @return array Array of groups that may be edited.
491 protected static function getAllGroups() {
492 return User
::getAllGroups();
496 * Adds a table with checkboxes where you can select what groups to add/remove
498 * @param $usergroups Array: groups the user belongs to
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, wfMessage( '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 = wfMessage( '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() );