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 ) {
58 return !empty( $available['add'] )
59 ||
!empty( $available['remove'] )
60 ||
( ( $this->isself ||
!$checkIfSelf ) &&
61 ( !empty( $available['add-self'] )
62 ||
!empty( $available['remove-self'] ) ) );
66 * Manage forms to be shown according to posted data.
67 * Depending on the submit button used, call a form or a save function.
69 * @param $par Mixed: string if any subpage provided, else null
70 * @throws UserBlockedError|PermissionsError
72 public function execute( $par ) {
73 // If the visitor doesn't have permissions to assign or remove
74 // any groups, it's a bit silly to give them the user search prompt.
76 $user = $this->getUser();
79 * If the user is blocked and they only have "partial" access
80 * (e.g. they don't have the userrights permission), then don't
81 * allow them to use Special:UserRights.
83 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
84 throw new UserBlockedError( $user->getBlock() );
87 $request = $this->getRequest();
89 if ( $par !== null ) {
90 $this->mTarget
= $par;
92 $this->mTarget
= $request->getVal( 'user' );
95 $available = $this->changeableGroups();
97 if ( $this->mTarget
=== null ) {
99 * If the user specified no target, and they can only
100 * edit their own groups, automatically set them as the
103 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
104 $this->mTarget
= $user->getName();
108 if ( User
::getCanonicalName( $this->mTarget
) == $user->getName() ) {
109 $this->isself
= true;
112 if ( !$this->userCanChangeRights( $user, true ) ) {
113 if ( $this->isself
&& $request->getCheck( 'success' ) ) {
114 // bug 48609: if the user just removed its own rights, this would
115 // leads it in a "permissions error" page. In that case, show a
116 // message that it can't anymore use this page instead of an error
118 $out = $this->getOutput();
119 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
120 $out->returnToMain();
124 // @todo FIXME: There may be intermediate groups we can mention.
125 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
126 throw new PermissionsError( null, array( array( $msg ) ) );
129 $this->checkReadOnly();
132 $this->outputHeader();
134 $out = $this->getOutput();
135 $out->addModuleStyles( 'mediawiki.special' );
137 // show the general form
138 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
143 $request->wasPosted() &&
144 $request->getCheck( 'saveusergroups' ) &&
145 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
148 $status = $this->fetchUser( $this->mTarget
);
149 if ( !$status->isOK() ) {
150 $this->getOutput()->addWikiText( $status->getWikiText() );
154 $targetUser = $status->value
;
155 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
156 $targetUser->clearInstanceCache(); // bug 38989
159 if ( $request->getVal( 'conflictcheck-originalgroups' ) !== implode( ',', $targetUser->getGroups() ) ) {
160 $out->addWikiMsg( 'userrights-conflict' );
162 $this->saveUserGroups(
164 $request->getVal( 'user-reason' ),
168 $out->redirect( $this->getSuccessURL() );
173 // show some more forms
174 if ( $this->mTarget
!== null ) {
175 $this->editUserGroupsForm( $this->mTarget
);
179 function getSuccessURL() {
180 return $this->getPageTitle( $this->mTarget
)->getFullURL( array( 'success' => 1 ) );
184 * Save user groups changes in the database.
185 * Data comes from the editUserGroupsForm() form function
187 * @param string $username username to apply changes to.
188 * @param string $reason reason for group change
189 * @param User|UserRightsProxy $user Target user object.
192 function saveUserGroups( $username, $reason, $user ) {
193 $allgroups = $this->getAllGroups();
195 $removegroup = array();
197 // This could possibly create a highly unlikely race condition if permissions are changed between
198 // when the form is loaded and when the form is saved. Ignoring it for the moment.
199 foreach ( $allgroups as $group ) {
200 // We'll tell it to remove all unchecked groups, and add all checked groups.
201 // Later on, this gets filtered for what can actually be removed
202 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
203 $addgroup[] = $group;
205 $removegroup[] = $group;
209 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
213 * Save user groups changes in the database.
215 * @param $user User object
216 * @param array $add of groups to add
217 * @param array $remove of groups to remove
218 * @param string $reason reason for group change
219 * @return Array: Tuple of added, then removed groups
221 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
224 // Validate input set...
225 $isself = ( $user->getName() == $this->getUser()->getName() );
226 $groups = $user->getGroups();
227 $changeable = $this->changeableGroups();
228 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
229 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
231 $remove = array_unique(
232 array_intersect( (array)$remove, $removable, $groups ) );
233 $add = array_unique( array_diff(
234 array_intersect( (array)$add, $addable ),
238 $oldGroups = $user->getGroups();
239 $newGroups = $oldGroups;
241 // remove then add groups
243 $newGroups = array_diff( $newGroups, $remove );
244 foreach ( $remove as $group ) {
245 $user->removeGroup( $group );
249 $newGroups = array_merge( $newGroups, $add );
250 foreach ( $add as $group ) {
251 $user->addGroup( $group );
254 $newGroups = array_unique( $newGroups );
256 // Ensure that caches are cleared
257 $user->invalidateCache();
259 // update groups in external authentication database
260 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
262 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
263 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
264 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
266 if ( $newGroups != $oldGroups ) {
267 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
269 return array( $add, $remove );
273 * Add a rights log entry for an action.
275 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
276 $logEntry = new ManualLogEntry( 'rights', 'rights' );
277 $logEntry->setPerformer( $this->getUser() );
278 $logEntry->setTarget( $user->getUserPage() );
279 $logEntry->setComment( $reason );
280 $logEntry->setParameters( array(
281 '4::oldgroups' => $oldGroups,
282 '5::newgroups' => $newGroups,
284 $logid = $logEntry->insert();
285 $logEntry->publish( $logid );
289 * Edit user groups membership
290 * @param string $username name of the user.
292 function editUserGroupsForm( $username ) {
293 $status = $this->fetchUser( $username );
294 if ( !$status->isOK() ) {
295 $this->getOutput()->addWikiText( $status->getWikiText() );
298 $user = $status->value
;
301 $groups = $user->getGroups();
303 $this->showEditUserGroupsForm( $user, $groups );
305 // This isn't really ideal logging behavior, but let's not hide the
306 // interwiki logs if we're using them as is.
307 $this->showLogFragment( $user, $this->getOutput() );
311 * Normalize the input username, which may be local or remote, and
312 * return a user (or proxy) object for manipulating it.
314 * Side effects: error output for invalid access
315 * @param string $username
316 * @return Status object
318 public function fetchUser( $username ) {
319 global $wgUserrightsInterwikiDelimiter;
321 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
322 if ( count( $parts ) < 2 ) {
323 $name = trim( $username );
326 list( $name, $database ) = array_map( 'trim', $parts );
328 if ( $database == wfWikiID() ) {
331 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
332 return Status
::newFatal( 'userrights-no-interwiki' );
334 if ( !UserRightsProxy
::validDatabase( $database ) ) {
335 return Status
::newFatal( 'userrights-nodatabase', $database );
340 if ( $name === '' ) {
341 return Status
::newFatal( 'nouserspecified' );
344 if ( $name[0] == '#' ) {
345 // Numeric ID can be specified...
346 // We'll do a lookup for the name internally.
347 $id = intval( substr( $name, 1 ) );
349 if ( $database == '' ) {
350 $name = User
::whoIs( $id );
352 $name = UserRightsProxy
::whoIs( $database, $id );
356 return Status
::newFatal( 'noname' );
359 $name = User
::getCanonicalName( $name );
360 if ( $name === false ) {
362 return Status
::newFatal( 'nosuchusershort', $username );
366 if ( $database == '' ) {
367 $user = User
::newFromName( $name );
369 $user = UserRightsProxy
::newFromName( $database, $name );
372 if ( !$user ||
$user->isAnon() ) {
373 return Status
::newFatal( 'nosuchusershort', $username );
376 return Status
::newGood( $user );
379 function makeGroupNameList( $ids ) {
380 if ( empty( $ids ) ) {
381 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
383 return implode( ', ', $ids );
388 * Make a list of group names to be stored as parameter for log entries
390 * @deprecated in 1.21; use LogFormatter instead.
394 function makeGroupNameListForLog( $ids ) {
395 wfDeprecated( __METHOD__
, '1.21' );
397 if ( empty( $ids ) ) {
400 return $this->makeGroupNameList( $ids );
405 * Output a form to allow searching for a user
407 function switchForm() {
409 $this->getOutput()->addHTML(
410 Html
::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
411 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
412 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
413 Xml
::inputLabel( $this->msg( 'userrights-user-editname' )->text(), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget
), array( 'autofocus' => true ) ) . ' ' .
414 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
415 Html
::closeElement( 'fieldset' ) .
416 Html
::closeElement( 'form' ) . "\n"
421 * Go through used and available groups and return the ones that this
422 * form will be able to manipulate based on the current user's system
425 * @param array $groups list of groups the given user is in
426 * @return Array: Tuple of addable, then removable groups
428 protected function splitGroups( $groups ) {
429 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
431 $removable = array_intersect(
432 array_merge( $this->isself ?
$removeself : array(), $removable ),
434 ); // Can't remove groups the user doesn't have
435 $addable = array_diff(
436 array_merge( $this->isself ?
$addself : array(), $addable ),
438 ); // Can't add groups the user does have
440 return array( $addable, $removable );
444 * Show the form to edit group memberships.
446 * @param $user User or UserRightsProxy you're editing
447 * @param $groups Array: Array of groups the user is in
449 protected function showEditUserGroupsForm( $user, $groups ) {
451 $membersList = array();
452 foreach ( $groups as $group ) {
453 $list[] = self
::buildGroupLink( $group );
454 $membersList[] = self
::buildGroupMemberLink( $group );
458 $autoMembersList = array();
459 if ( $user instanceof User
) {
460 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
461 $autoList[] = self
::buildGroupLink( $group );
462 $autoMembersList[] = self
::buildGroupMemberLink( $group );
466 $language = $this->getLanguage();
467 $displayedList = $this->msg( 'userrights-groupsmember-type',
468 $language->listToText( $list ),
469 $language->listToText( $membersList )
471 $displayedAutolist = $this->msg( 'userrights-groupsmember-type',
472 $language->listToText( $autoList ),
473 $language->listToText( $autoMembersList )
477 $count = count( $list );
479 $grouplist = $this->msg( 'userrights-groupsmember', $count, $user->getName() )->parse();
480 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
482 $count = count( $autoList );
484 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto', $count, $user->getName() )->parse();
485 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
488 $userToolLinks = Linker
::userToolLinks(
491 false, /* default for redContribsWhenNoEdits */
492 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
495 $this->getOutput()->addHTML(
496 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $this->getPageTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
497 Html
::hidden( 'user', $this->mTarget
) .
498 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
499 Html
::hidden( 'conflictcheck-originalgroups', implode( ',', $user->getGroups() ) ) . // Conflict detection
500 Xml
::openElement( 'fieldset' ) .
501 Xml
::element( 'legend', array(), $this->msg( 'userrights-editusergroup', $user->getName() )->text() ) .
502 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )->rawParams( $userToolLinks )->parse() .
503 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
505 Xml
::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
506 Xml
::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
508 <td class='mw-label'>" .
509 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
511 <td class='mw-input'>" .
512 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
513 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
518 <td class='mw-submit'>" .
519 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
520 array( 'name' => 'saveusergroups' ) + Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' ) ) .
523 Xml
::closeElement( 'table' ) . "\n" .
524 Xml
::closeElement( 'fieldset' ) .
525 Xml
::closeElement( 'form' ) . "\n"
530 * Format a link to a group description page
532 * @param $group string
535 private static function buildGroupLink( $group ) {
536 return User
::makeGroupLinkHtml( $group, User
::getGroupName( $group ) );
540 * Format a link to a group member description page
542 * @param $group string
545 private static function buildGroupMemberLink( $group ) {
546 return User
::makeGroupLinkHtml( $group, User
::getGroupMember( $group ) );
550 * Returns an array of all groups that may be edited
551 * @return array Array of groups that may be edited.
553 protected static function getAllGroups() {
554 return User
::getAllGroups();
558 * Adds a table with checkboxes where you can select what groups to add/remove
560 * @todo Just pass the username string?
561 * @param array $usergroups groups the user belongs to
562 * @param $user User a user object
563 * @return string XHTML table element with checkboxes
565 private function groupCheckboxes( $usergroups, $user ) {
566 $allgroups = $this->getAllGroups();
569 // Put all column info into an associative array so that extensions can
570 // more easily manage it.
571 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
573 foreach ( $allgroups as $group ) {
574 $set = in_array( $group, $usergroups );
575 // Should the checkbox be disabled?
577 ( $set && $this->canRemove( $group ) ) ||
578 ( !$set && $this->canAdd( $group ) ) );
579 // Do we need to point out that this action is irreversible?
580 $irreversible = !$disabled && (
581 ( $set && !$this->canAdd( $group ) ) ||
582 ( !$set && !$this->canRemove( $group ) ) );
586 'disabled' => $disabled,
587 'irreversible' => $irreversible
591 $columns['unchangeable'][$group] = $checkbox;
593 $columns['changeable'][$group] = $checkbox;
597 // Build the HTML table
598 $ret .= Xml
::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
600 foreach ( $columns as $name => $column ) {
601 if ( $column === array() ) {
604 // Messages: userrights-changeable-col, userrights-unchangeable-col
605 $ret .= Xml
::element( 'th', null, $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text() );
607 $ret .= "</tr>\n<tr>\n";
608 foreach ( $columns as $column ) {
609 if ( $column === array() ) {
612 $ret .= "\t<td style='vertical-align:top;'>\n";
613 foreach ( $column as $group => $checkbox ) {
614 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
616 $member = User
::getGroupMember( $group, $user->getName() );
617 if ( $checkbox['irreversible'] ) {
618 $text = $this->msg( 'userrights-irreversible-marker', $member )->escaped();
620 $text = htmlspecialchars( $member );
622 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
623 "wpGroup-" . $group, $checkbox['set'], $attr );
624 $ret .= "\t\t" . ( $checkbox['disabled']
625 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
631 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
637 * @param $group String: the name of the group to check
638 * @return bool Can we remove the group?
640 private function canRemove( $group ) {
641 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
642 $groups = $this->changeableGroups();
643 return in_array( $group, $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] ) );
647 * @param string $group the name of the group to check
648 * @return bool Can we add the group?
650 private function canAdd( $group ) {
651 $groups = $this->changeableGroups();
652 return in_array( $group, $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] ) );
656 * Returns $this->getUser()->changeableGroups()
658 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ), 'add-self' => array( addablegroups to self ), 'remove-self' => array( removable groups from self ) )
660 function changeableGroups() {
661 return $this->getUser()->changeableGroups();
665 * Show a rights log fragment for the specified user
667 * @param $user User to show log for
668 * @param $output OutputPage to use
670 protected function showLogFragment( $user, $output ) {
671 $rightsLogPage = new LogPage( 'rights' );
672 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
673 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
676 protected function getGroupName() {