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
35 * @var null|User $mFetchedUser The user object of the target username or null.
37 protected $mFetchedUser = null;
38 protected $isself = false;
40 public function __construct() {
41 parent
::__construct( 'Userrights' );
44 public function isRestricted() {
48 public function userCanExecute( User
$user ) {
49 return $this->userCanChangeRights( $user, false );
54 * @param bool $checkIfSelf
57 public function userCanChangeRights( $user, $checkIfSelf = true ) {
58 $available = $this->changeableGroups();
59 if ( $user->getId() == 0 ) {
63 return !empty( $available['add'] )
64 ||
!empty( $available['remove'] )
65 ||
( ( $this->isself ||
!$checkIfSelf ) &&
66 ( !empty( $available['add-self'] )
67 ||
!empty( $available['remove-self'] ) ) );
71 * Manage forms to be shown according to posted data.
72 * Depending on the submit button used, call a form or a save function.
74 * @param string|null $par String if any subpage provided, else null
75 * @throws UserBlockedError|PermissionsError
77 public function execute( $par ) {
78 // If the visitor doesn't have permissions to assign or remove
79 // any groups, it's a bit silly to give them the user search prompt.
81 $user = $this->getUser();
82 $request = $this->getRequest();
83 $out = $this->getOutput();
86 * If the user is blocked and they only have "partial" access
87 * (e.g. they don't have the userrights permission), then don't
88 * allow them to use Special:UserRights.
90 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
91 throw new UserBlockedError( $user->getBlock() );
94 if ( $par !== null ) {
95 $this->mTarget
= $par;
97 $this->mTarget
= $request->getVal( 'user' );
100 $available = $this->changeableGroups();
102 if ( $this->mTarget
=== null ) {
104 * If the user specified no target, and they can only
105 * edit their own groups, automatically set them as the
108 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
109 $this->mTarget
= $user->getName();
113 if ( $this->mTarget
!== null && User
::getCanonicalName( $this->mTarget
) === $user->getName() ) {
114 $this->isself
= true;
117 $fetchedStatus = $this->fetchUser( $this->mTarget
);
118 if ( $fetchedStatus->isOk() ) {
119 $this->mFetchedUser
= $fetchedStatus->value
;
122 if ( !$this->userCanChangeRights( $user, true ) ) {
123 if ( $this->isself
&& $request->getCheck( 'success' ) ) {
124 // bug 48609: if the user just removed its own rights, this would
125 // leads it in a "permissions error" page. In that case, show a
126 // message that it can't anymore use this page instead of an error
128 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
129 $out->returnToMain();
134 // @todo FIXME: There may be intermediate groups we can mention.
135 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
136 throw new PermissionsError( null, array( array( $msg ) ) );
139 // show a successbox, if the user rights was saved successfully
140 if ( $request->getCheck( 'success' ) && $this->mFetchedUser
!== null ) {
142 "<div class=\"successbox\">\n$1\n</div>",
143 array( 'savedrights', $this->mFetchedUser
->getName() )
147 $this->checkReadOnly();
150 $this->outputHeader();
152 $out->addModuleStyles( 'mediawiki.special' );
153 $this->addHelpLink( 'Help:Assigning permissions' );
155 // show the general form
156 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
161 $request->wasPosted() &&
162 $request->getCheck( 'saveusergroups' ) &&
163 $this->mTarget
!== null &&
164 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
167 if ( !$fetchedStatus->isOK() ) {
168 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
173 $targetUser = $this->mFetchedUser
;
174 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
175 $targetUser->clearInstanceCache(); // bug 38989
178 if ( $request->getVal( 'conflictcheck-originalgroups' )
179 !== implode( ',', $targetUser->getGroups() )
181 $out->addWikiMsg( 'userrights-conflict' );
183 $this->saveUserGroups(
185 $request->getVal( 'user-reason' ),
189 $out->redirect( $this->getSuccessURL() );
195 // show some more forms
196 if ( $this->mTarget
!== null ) {
197 $this->editUserGroupsForm( $this->mTarget
);
201 function getSuccessURL() {
202 return $this->getPageTitle( $this->mTarget
)->getFullURL( array( 'success' => 1 ) );
206 * Save user groups changes in the database.
207 * Data comes from the editUserGroupsForm() form function
209 * @param string $username Username to apply changes to.
210 * @param string $reason Reason for group change
211 * @param User|UserRightsProxy $user Target user object.
214 function saveUserGroups( $username, $reason, $user ) {
215 $allgroups = $this->getAllGroups();
217 $removegroup = array();
219 // This could possibly create a highly unlikely race condition if permissions are changed between
220 // when the form is loaded and when the form is saved. Ignoring it for the moment.
221 foreach ( $allgroups as $group ) {
222 // We'll tell it to remove all unchecked groups, and add all checked groups.
223 // Later on, this gets filtered for what can actually be removed
224 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
225 $addgroup[] = $group;
227 $removegroup[] = $group;
231 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
235 * Save user groups changes in the database.
237 * @param User|UserRightsProxy $user
238 * @param array $add Array of groups to add
239 * @param array $remove Array of groups to remove
240 * @param string $reason Reason for group change
241 * @return array Tuple of added, then removed groups
243 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
246 // Validate input set...
247 $isself = $user->getName() == $this->getUser()->getName();
248 $groups = $user->getGroups();
249 $changeable = $this->changeableGroups();
250 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
251 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
253 $remove = array_unique(
254 array_intersect( (array)$remove, $removable, $groups ) );
255 $add = array_unique( array_diff(
256 array_intersect( (array)$add, $addable ),
260 $oldGroups = $user->getGroups();
261 $newGroups = $oldGroups;
263 // Remove then add groups
265 foreach ( $remove as $index => $group ) {
266 if ( !$user->removeGroup( $group ) ) {
267 unset( $remove[$index] );
270 $newGroups = array_diff( $newGroups, $remove );
273 foreach ( $add as $index => $group ) {
274 if ( !$user->addGroup( $group ) ) {
275 unset( $add[$index] );
278 $newGroups = array_merge( $newGroups, $add );
280 $newGroups = array_unique( $newGroups );
282 // Ensure that caches are cleared
283 $user->invalidateCache();
285 // update groups in external authentication database
286 Hooks
::run( 'UserGroupsChanged', array( $user, $add, $remove, $this->getUser() ) );
287 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
289 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
290 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
291 // Deprecated in favor of UserGroupsChanged hook
292 Hooks
::run( 'UserRights', array( &$user, $add, $remove ), '1.26' );
294 if ( $newGroups != $oldGroups ) {
295 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
298 return array( $add, $remove );
302 * Add a rights log entry for an action.
304 * @param array $oldGroups
305 * @param array $newGroups
306 * @param array $reason
308 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
309 $logEntry = new ManualLogEntry( 'rights', 'rights' );
310 $logEntry->setPerformer( $this->getUser() );
311 $logEntry->setTarget( $user->getUserPage() );
312 $logEntry->setComment( $reason );
313 $logEntry->setParameters( array(
314 '4::oldgroups' => $oldGroups,
315 '5::newgroups' => $newGroups,
317 $logid = $logEntry->insert();
318 $logEntry->publish( $logid );
322 * Edit user groups membership
323 * @param string $username Name of the user.
325 function editUserGroupsForm( $username ) {
326 $status = $this->fetchUser( $username );
327 if ( !$status->isOK() ) {
328 $this->getOutput()->addWikiText( $status->getWikiText() );
332 $user = $status->value
;
335 $groups = $user->getGroups();
337 $this->showEditUserGroupsForm( $user, $groups );
339 // This isn't really ideal logging behavior, but let's not hide the
340 // interwiki logs if we're using them as is.
341 $this->showLogFragment( $user, $this->getOutput() );
345 * Normalize the input username, which may be local or remote, and
346 * return a user (or proxy) object for manipulating it.
348 * Side effects: error output for invalid access
349 * @param string $username
352 public function fetchUser( $username ) {
353 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
354 if ( count( $parts ) < 2 ) {
355 $name = trim( $username );
358 list( $name, $database ) = array_map( 'trim', $parts );
360 if ( $database == wfWikiID() ) {
363 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
364 return Status
::newFatal( 'userrights-no-interwiki' );
366 if ( !UserRightsProxy
::validDatabase( $database ) ) {
367 return Status
::newFatal( 'userrights-nodatabase', $database );
372 if ( $name === '' ) {
373 return Status
::newFatal( 'nouserspecified' );
376 if ( $name[0] == '#' ) {
377 // Numeric ID can be specified...
378 // We'll do a lookup for the name internally.
379 $id = intval( substr( $name, 1 ) );
381 if ( $database == '' ) {
382 $name = User
::whoIs( $id );
384 $name = UserRightsProxy
::whoIs( $database, $id );
388 return Status
::newFatal( 'noname' );
391 $name = User
::getCanonicalName( $name );
392 if ( $name === false ) {
394 return Status
::newFatal( 'nosuchusershort', $username );
398 if ( $database == '' ) {
399 $user = User
::newFromName( $name );
401 $user = UserRightsProxy
::newFromName( $database, $name );
404 if ( !$user ||
$user->isAnon() ) {
405 return Status
::newFatal( 'nosuchusershort', $username );
408 return Status
::newGood( $user );
411 function makeGroupNameList( $ids ) {
412 if ( empty( $ids ) ) {
413 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
415 return implode( ', ', $ids );
420 * Make a list of group names to be stored as parameter for log entries
422 * @deprecated since 1.21; use LogFormatter instead.
426 function makeGroupNameListForLog( $ids ) {
427 wfDeprecated( __METHOD__
, '1.21' );
429 if ( empty( $ids ) ) {
432 return $this->makeGroupNameList( $ids );
437 * Output a form to allow searching for a user
439 function switchForm() {
440 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
442 $this->getOutput()->addHTML(
447 'action' => wfScript(),
449 'id' => 'mw-userrights-form1'
452 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
453 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
455 $this->msg( 'userrights-user-editname' )->text(),
459 str_replace( '_', ' ', $this->mTarget
),
462 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
465 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
466 Html
::closeElement( 'fieldset' ) .
467 Html
::closeElement( 'form' ) . "\n"
472 * Go through used and available groups and return the ones that this
473 * form will be able to manipulate based on the current user's system
476 * @param array $groups List of groups the given user is in
477 * @return array Tuple of addable, then removable groups
479 protected function splitGroups( $groups ) {
480 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
482 $removable = array_intersect(
483 array_merge( $this->isself ?
$removeself : array(), $removable ),
485 ); // Can't remove groups the user doesn't have
486 $addable = array_diff(
487 array_merge( $this->isself ?
$addself : array(), $addable ),
489 ); // Can't add groups the user does have
491 return array( $addable, $removable );
495 * Show the form to edit group memberships.
497 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
498 * @param array $groups Array of groups the user is in
500 protected function showEditUserGroupsForm( $user, $groups ) {
502 $membersList = array();
503 foreach ( $groups as $group ) {
504 $list[] = self
::buildGroupLink( $group );
505 $membersList[] = self
::buildGroupMemberLink( $group );
509 $autoMembersList = array();
510 if ( $user instanceof User
) {
511 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
512 $autoList[] = self
::buildGroupLink( $group );
513 $autoMembersList[] = self
::buildGroupMemberLink( $group );
517 $language = $this->getLanguage();
518 $displayedList = $this->msg( 'userrights-groupsmember-type' )
520 $language->listToText( $list ),
521 $language->listToText( $membersList )
523 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
525 $language->listToText( $autoList ),
526 $language->listToText( $autoMembersList )
530 $count = count( $list );
532 $grouplist = $this->msg( 'userrights-groupsmember' )
533 ->numParams( $count )
534 ->params( $user->getName() )
536 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
539 $count = count( $autoList );
541 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
542 ->numParams( $count )
543 ->params( $user->getName() )
545 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
548 $userToolLinks = Linker
::userToolLinks(
551 false, /* default for redContribsWhenNoEdits */
552 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
555 $this->getOutput()->addHTML(
560 'action' => $this->getPageTitle()->getLocalURL(),
561 'name' => 'editGroup',
562 'id' => 'mw-userrights-form2'
565 Html
::hidden( 'user', $this->mTarget
) .
566 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
568 'conflictcheck-originalgroups',
569 implode( ',', $user->getGroups() )
570 ) . // Conflict detection
571 Xml
::openElement( 'fieldset' ) .
575 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
577 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
578 ->rawParams( $userToolLinks )->parse() .
579 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
581 $this->groupCheckboxes( $groups, $user ) .
582 Xml
::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
584 <td class='mw-label'>" .
585 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
587 <td class='mw-input'>" .
588 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
589 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
594 <td class='mw-submit'>" .
595 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
596 array( 'name' => 'saveusergroups' ) +
597 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
601 Xml
::closeElement( 'table' ) . "\n" .
602 Xml
::closeElement( 'fieldset' ) .
603 Xml
::closeElement( 'form' ) . "\n"
608 * Format a link to a group description page
610 * @param string $group
613 private static function buildGroupLink( $group ) {
614 return User
::makeGroupLinkHtml( $group, User
::getGroupName( $group ) );
618 * Format a link to a group member description page
620 * @param string $group
623 private static function buildGroupMemberLink( $group ) {
624 return User
::makeGroupLinkHtml( $group, User
::getGroupMember( $group ) );
628 * Returns an array of all groups that may be edited
629 * @return array Array of groups that may be edited.
631 protected static function getAllGroups() {
632 return User
::getAllGroups();
636 * Adds a table with checkboxes where you can select what groups to add/remove
638 * @todo Just pass the username string?
639 * @param array $usergroups Groups the user belongs to
641 * @return string XHTML table element with checkboxes
643 private function groupCheckboxes( $usergroups, $user ) {
644 $allgroups = $this->getAllGroups();
647 // Put all column info into an associative array so that extensions can
648 // more easily manage it.
649 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
651 foreach ( $allgroups as $group ) {
652 $set = in_array( $group, $usergroups );
653 // Should the checkbox be disabled?
655 ( $set && $this->canRemove( $group ) ) ||
656 ( !$set && $this->canAdd( $group ) ) );
657 // Do we need to point out that this action is irreversible?
658 $irreversible = !$disabled && (
659 ( $set && !$this->canAdd( $group ) ) ||
660 ( !$set && !$this->canRemove( $group ) ) );
664 'disabled' => $disabled,
665 'irreversible' => $irreversible
669 $columns['unchangeable'][$group] = $checkbox;
671 $columns['changeable'][$group] = $checkbox;
675 // Build the HTML table
676 $ret .= Xml
::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
678 foreach ( $columns as $name => $column ) {
679 if ( $column === array() ) {
682 // Messages: userrights-changeable-col, userrights-unchangeable-col
683 $ret .= Xml
::element(
686 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
690 $ret .= "</tr>\n<tr>\n";
691 foreach ( $columns as $column ) {
692 if ( $column === array() ) {
695 $ret .= "\t<td style='vertical-align:top;'>\n";
696 foreach ( $column as $group => $checkbox ) {
697 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
699 $member = User
::getGroupMember( $group, $user->getName() );
700 if ( $checkbox['irreversible'] ) {
701 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
705 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
706 "wpGroup-" . $group, $checkbox['set'], $attr );
707 $ret .= "\t\t" . ( $checkbox['disabled']
708 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
714 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
720 * @param string $group The name of the group to check
721 * @return bool Can we remove the group?
723 private function canRemove( $group ) {
724 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
725 $groups = $this->changeableGroups();
729 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
734 * @param string $group The name of the group to check
735 * @return bool Can we add the group?
737 private function canAdd( $group ) {
738 $groups = $this->changeableGroups();
742 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
747 * Returns $this->getUser()->changeableGroups()
749 * @return array Array(
750 * 'add' => array( addablegroups ),
751 * 'remove' => array( removablegroups ),
752 * 'add-self' => array( addablegroups to self ),
753 * 'remove-self' => array( removable groups from self )
756 function changeableGroups() {
757 return $this->getUser()->changeableGroups();
761 * Show a rights log fragment for the specified user
763 * @param User $user User to show log for
764 * @param OutputPage $output OutputPage to use
766 protected function showLogFragment( $user, $output ) {
767 $rightsLogPage = new LogPage( 'rights' );
768 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
769 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
772 protected function getGroupName() {