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
;
120 if ( $this->mFetchedUser
instanceof User
) {
121 // Set the 'relevant user' in the skin, so it displays links like Contributions,
122 // User logs, UserRights, etc.
123 $this->getSkin()->setRelevantUser( $this->mFetchedUser
);
127 if ( !$this->userCanChangeRights( $user, true ) ) {
128 if ( $this->isself
&& $request->getCheck( 'success' ) ) {
129 // bug 48609: if the user just removed its own rights, this would
130 // leads it in a "permissions error" page. In that case, show a
131 // message that it can't anymore use this page instead of an error
133 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
134 $out->returnToMain();
139 // @todo FIXME: There may be intermediate groups we can mention.
140 $msg = $user->isAnon() ?
'userrights-nologin' : 'userrights-notallowed';
141 throw new PermissionsError( null, array( array( $msg ) ) );
144 // show a successbox, if the user rights was saved successfully
145 if ( $request->getCheck( 'success' ) && $this->mFetchedUser
!== null ) {
147 "<div class=\"successbox\">\n$1\n</div>",
148 array( 'savedrights', $this->mFetchedUser
->getName() )
152 $this->checkReadOnly();
155 $this->outputHeader();
157 $out->addModuleStyles( 'mediawiki.special' );
158 $this->addHelpLink( 'Help:Assigning permissions' );
160 // show the general form
161 if ( count( $available['add'] ) ||
count( $available['remove'] ) ) {
166 $request->wasPosted() &&
167 $request->getCheck( 'saveusergroups' ) &&
168 $this->mTarget
!== null &&
169 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget
)
172 if ( !$fetchedStatus->isOK() ) {
173 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
178 $targetUser = $this->mFetchedUser
;
179 if ( $targetUser instanceof User
) { // UserRightsProxy doesn't have this method (bug 61252)
180 $targetUser->clearInstanceCache(); // bug 38989
183 if ( $request->getVal( 'conflictcheck-originalgroups' )
184 !== implode( ',', $targetUser->getGroups() )
186 $out->addWikiMsg( 'userrights-conflict' );
188 $this->saveUserGroups(
190 $request->getVal( 'user-reason' ),
194 $out->redirect( $this->getSuccessURL() );
200 // show some more forms
201 if ( $this->mTarget
!== null ) {
202 $this->editUserGroupsForm( $this->mTarget
);
206 function getSuccessURL() {
207 return $this->getPageTitle( $this->mTarget
)->getFullURL( array( 'success' => 1 ) );
211 * Save user groups changes in the database.
212 * Data comes from the editUserGroupsForm() form function
214 * @param string $username Username to apply changes to.
215 * @param string $reason Reason for group change
216 * @param User|UserRightsProxy $user Target user object.
219 function saveUserGroups( $username, $reason, $user ) {
220 $allgroups = $this->getAllGroups();
222 $removegroup = array();
224 // This could possibly create a highly unlikely race condition if permissions are changed between
225 // when the form is loaded and when the form is saved. Ignoring it for the moment.
226 foreach ( $allgroups as $group ) {
227 // We'll tell it to remove all unchecked groups, and add all checked groups.
228 // Later on, this gets filtered for what can actually be removed
229 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
230 $addgroup[] = $group;
232 $removegroup[] = $group;
236 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
240 * Save user groups changes in the database.
242 * @param User|UserRightsProxy $user
243 * @param array $add Array of groups to add
244 * @param array $remove Array of groups to remove
245 * @param string $reason Reason for group change
246 * @return array Tuple of added, then removed groups
248 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
251 // Validate input set...
252 $isself = $user->getName() == $this->getUser()->getName();
253 $groups = $user->getGroups();
254 $changeable = $this->changeableGroups();
255 $addable = array_merge( $changeable['add'], $isself ?
$changeable['add-self'] : array() );
256 $removable = array_merge( $changeable['remove'], $isself ?
$changeable['remove-self'] : array() );
258 $remove = array_unique(
259 array_intersect( (array)$remove, $removable, $groups ) );
260 $add = array_unique( array_diff(
261 array_intersect( (array)$add, $addable ),
265 $oldGroups = $user->getGroups();
266 $newGroups = $oldGroups;
268 // Remove then add groups
270 foreach ( $remove as $index => $group ) {
271 if ( !$user->removeGroup( $group ) ) {
272 unset( $remove[$index] );
275 $newGroups = array_diff( $newGroups, $remove );
278 foreach ( $add as $index => $group ) {
279 if ( !$user->addGroup( $group ) ) {
280 unset( $add[$index] );
283 $newGroups = array_merge( $newGroups, $add );
285 $newGroups = array_unique( $newGroups );
287 // Ensure that caches are cleared
288 $user->invalidateCache();
290 // update groups in external authentication database
291 Hooks
::run( 'UserGroupsChanged', array( $user, $add, $remove, $this->getUser() ) );
292 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
294 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
295 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
296 // Deprecated in favor of UserGroupsChanged hook
297 Hooks
::run( 'UserRights', array( &$user, $add, $remove ), '1.26' );
299 if ( $newGroups != $oldGroups ) {
300 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
303 return array( $add, $remove );
307 * Add a rights log entry for an action.
309 * @param array $oldGroups
310 * @param array $newGroups
311 * @param array $reason
313 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
314 $logEntry = new ManualLogEntry( 'rights', 'rights' );
315 $logEntry->setPerformer( $this->getUser() );
316 $logEntry->setTarget( $user->getUserPage() );
317 $logEntry->setComment( $reason );
318 $logEntry->setParameters( array(
319 '4::oldgroups' => $oldGroups,
320 '5::newgroups' => $newGroups,
322 $logid = $logEntry->insert();
323 $logEntry->publish( $logid );
327 * Edit user groups membership
328 * @param string $username Name of the user.
330 function editUserGroupsForm( $username ) {
331 $status = $this->fetchUser( $username );
332 if ( !$status->isOK() ) {
333 $this->getOutput()->addWikiText( $status->getWikiText() );
337 $user = $status->value
;
340 $groups = $user->getGroups();
342 $this->showEditUserGroupsForm( $user, $groups );
344 // This isn't really ideal logging behavior, but let's not hide the
345 // interwiki logs if we're using them as is.
346 $this->showLogFragment( $user, $this->getOutput() );
350 * Normalize the input username, which may be local or remote, and
351 * return a user (or proxy) object for manipulating it.
353 * Side effects: error output for invalid access
354 * @param string $username
357 public function fetchUser( $username ) {
358 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
359 if ( count( $parts ) < 2 ) {
360 $name = trim( $username );
363 list( $name, $database ) = array_map( 'trim', $parts );
365 if ( $database == wfWikiID() ) {
368 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
369 return Status
::newFatal( 'userrights-no-interwiki' );
371 if ( !UserRightsProxy
::validDatabase( $database ) ) {
372 return Status
::newFatal( 'userrights-nodatabase', $database );
377 if ( $name === '' ) {
378 return Status
::newFatal( 'nouserspecified' );
381 if ( $name[0] == '#' ) {
382 // Numeric ID can be specified...
383 // We'll do a lookup for the name internally.
384 $id = intval( substr( $name, 1 ) );
386 if ( $database == '' ) {
387 $name = User
::whoIs( $id );
389 $name = UserRightsProxy
::whoIs( $database, $id );
393 return Status
::newFatal( 'noname' );
396 $name = User
::getCanonicalName( $name );
397 if ( $name === false ) {
399 return Status
::newFatal( 'nosuchusershort', $username );
403 if ( $database == '' ) {
404 $user = User
::newFromName( $name );
406 $user = UserRightsProxy
::newFromName( $database, $name );
409 if ( !$user ||
$user->isAnon() ) {
410 return Status
::newFatal( 'nosuchusershort', $username );
413 return Status
::newGood( $user );
416 function makeGroupNameList( $ids ) {
417 if ( empty( $ids ) ) {
418 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
420 return implode( ', ', $ids );
425 * Make a list of group names to be stored as parameter for log entries
427 * @deprecated since 1.21; use LogFormatter instead.
431 function makeGroupNameListForLog( $ids ) {
432 wfDeprecated( __METHOD__
, '1.21' );
434 if ( empty( $ids ) ) {
437 return $this->makeGroupNameList( $ids );
442 * Output a form to allow searching for a user
444 function switchForm() {
445 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
447 $this->getOutput()->addHTML(
452 'action' => wfScript(),
454 'id' => 'mw-userrights-form1'
457 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
458 Xml
::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
460 $this->msg( 'userrights-user-editname' )->text(),
464 str_replace( '_', ' ', $this->mTarget
),
466 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
468 // Set autofocus on blank input and error input
469 $this->mFetchedUser
=== null ?
array( 'autofocus' => '' ) : array()
472 Xml
::submitButton( $this->msg( 'editusergroup' )->text() ) .
473 Html
::closeElement( 'fieldset' ) .
474 Html
::closeElement( 'form' ) . "\n"
479 * Go through used and available groups and return the ones that this
480 * form will be able to manipulate based on the current user's system
483 * @param array $groups List of groups the given user is in
484 * @return array Tuple of addable, then removable groups
486 protected function splitGroups( $groups ) {
487 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
489 $removable = array_intersect(
490 array_merge( $this->isself ?
$removeself : array(), $removable ),
492 ); // Can't remove groups the user doesn't have
493 $addable = array_diff(
494 array_merge( $this->isself ?
$addself : array(), $addable ),
496 ); // Can't add groups the user does have
498 return array( $addable, $removable );
502 * Show the form to edit group memberships.
504 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
505 * @param array $groups Array of groups the user is in
507 protected function showEditUserGroupsForm( $user, $groups ) {
509 $membersList = array();
510 foreach ( $groups as $group ) {
511 $list[] = self
::buildGroupLink( $group );
512 $membersList[] = self
::buildGroupMemberLink( $group );
516 $autoMembersList = array();
517 if ( $user instanceof User
) {
518 foreach ( Autopromote
::getAutopromoteGroups( $user ) as $group ) {
519 $autoList[] = self
::buildGroupLink( $group );
520 $autoMembersList[] = self
::buildGroupMemberLink( $group );
524 $language = $this->getLanguage();
525 $displayedList = $this->msg( 'userrights-groupsmember-type' )
527 $language->listToText( $list ),
528 $language->listToText( $membersList )
530 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
532 $language->listToText( $autoList ),
533 $language->listToText( $autoMembersList )
537 $count = count( $list );
539 $grouplist = $this->msg( 'userrights-groupsmember' )
540 ->numParams( $count )
541 ->params( $user->getName() )
543 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
546 $count = count( $autoList );
548 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
549 ->numParams( $count )
550 ->params( $user->getName() )
552 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
555 $userToolLinks = Linker
::userToolLinks(
558 false, /* default for redContribsWhenNoEdits */
559 Linker
::TOOL_LINKS_EMAIL
/* Add "send e-mail" link */
562 $this->getOutput()->addHTML(
567 'action' => $this->getPageTitle()->getLocalURL(),
568 'name' => 'editGroup',
569 'id' => 'mw-userrights-form2'
572 Html
::hidden( 'user', $this->mTarget
) .
573 Html
::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget
) ) .
575 'conflictcheck-originalgroups',
576 implode( ',', $user->getGroups() )
577 ) . // Conflict detection
578 Xml
::openElement( 'fieldset' ) .
582 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
584 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
585 ->rawParams( $userToolLinks )->parse() .
586 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
588 $this->groupCheckboxes( $groups, $user ) .
589 Xml
::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
591 <td class='mw-label'>" .
592 Xml
::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
594 <td class='mw-input'>" .
595 Xml
::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
596 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
601 <td class='mw-submit'>" .
602 Xml
::submitButton( $this->msg( 'saveusergroups' )->text(),
603 array( 'name' => 'saveusergroups' ) +
604 Linker
::tooltipAndAccesskeyAttribs( 'userrights-set' )
608 Xml
::closeElement( 'table' ) . "\n" .
609 Xml
::closeElement( 'fieldset' ) .
610 Xml
::closeElement( 'form' ) . "\n"
615 * Format a link to a group description page
617 * @param string $group
620 private static function buildGroupLink( $group ) {
621 return User
::makeGroupLinkHtml( $group, User
::getGroupName( $group ) );
625 * Format a link to a group member description page
627 * @param string $group
630 private static function buildGroupMemberLink( $group ) {
631 return User
::makeGroupLinkHtml( $group, User
::getGroupMember( $group ) );
635 * Returns an array of all groups that may be edited
636 * @return array Array of groups that may be edited.
638 protected static function getAllGroups() {
639 return User
::getAllGroups();
643 * Adds a table with checkboxes where you can select what groups to add/remove
645 * @todo Just pass the username string?
646 * @param array $usergroups Groups the user belongs to
648 * @return string XHTML table element with checkboxes
650 private function groupCheckboxes( $usergroups, $user ) {
651 $allgroups = $this->getAllGroups();
654 // Put all column info into an associative array so that extensions can
655 // more easily manage it.
656 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
658 foreach ( $allgroups as $group ) {
659 $set = in_array( $group, $usergroups );
660 // Should the checkbox be disabled?
662 ( $set && $this->canRemove( $group ) ) ||
663 ( !$set && $this->canAdd( $group ) ) );
664 // Do we need to point out that this action is irreversible?
665 $irreversible = !$disabled && (
666 ( $set && !$this->canAdd( $group ) ) ||
667 ( !$set && !$this->canRemove( $group ) ) );
671 'disabled' => $disabled,
672 'irreversible' => $irreversible
676 $columns['unchangeable'][$group] = $checkbox;
678 $columns['changeable'][$group] = $checkbox;
682 // Build the HTML table
683 $ret .= Xml
::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
685 foreach ( $columns as $name => $column ) {
686 if ( $column === array() ) {
689 // Messages: userrights-changeable-col, userrights-unchangeable-col
690 $ret .= Xml
::element(
693 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
697 $ret .= "</tr>\n<tr>\n";
698 foreach ( $columns as $column ) {
699 if ( $column === array() ) {
702 $ret .= "\t<td style='vertical-align:top;'>\n";
703 foreach ( $column as $group => $checkbox ) {
704 $attr = $checkbox['disabled'] ?
array( 'disabled' => 'disabled' ) : array();
706 $member = User
::getGroupMember( $group, $user->getName() );
707 if ( $checkbox['irreversible'] ) {
708 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
712 $checkboxHtml = Xml
::checkLabel( $text, "wpGroup-" . $group,
713 "wpGroup-" . $group, $checkbox['set'], $attr );
714 $ret .= "\t\t" . ( $checkbox['disabled']
715 ? Xml
::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
721 $ret .= Xml
::closeElement( 'tr' ) . Xml
::closeElement( 'table' );
727 * @param string $group The name of the group to check
728 * @return bool Can we remove the group?
730 private function canRemove( $group ) {
731 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
732 $groups = $this->changeableGroups();
736 $groups['remove'] ) ||
( $this->isself
&& in_array( $group, $groups['remove-self'] )
741 * @param string $group The name of the group to check
742 * @return bool Can we add the group?
744 private function canAdd( $group ) {
745 $groups = $this->changeableGroups();
749 $groups['add'] ) ||
( $this->isself
&& in_array( $group, $groups['add-self'] )
754 * Returns $this->getUser()->changeableGroups()
756 * @return array Array(
757 * 'add' => array( addablegroups ),
758 * 'remove' => array( removablegroups ),
759 * 'add-self' => array( addablegroups to self ),
760 * 'remove-self' => array( removable groups from self )
763 function changeableGroups() {
764 return $this->getUser()->changeableGroups();
768 * Show a rights log fragment for the specified user
770 * @param User $user User to show log for
771 * @param OutputPage $output OutputPage to use
773 protected function showLogFragment( $user, $output ) {
774 $rightsLogPage = new LogPage( 'rights' );
775 $output->addHTML( Xml
::element( 'h2', null, $rightsLogPage->getName()->text() ) );
776 LogEventsList
::showLogExtract( $output, 'rights', $user->getUserPage() );
780 * Return an array of subpages beginning with $search that this special page will accept.
782 * @param string $search Prefix to search for
783 * @param int $limit Maximum number of results to return (usually 10)
784 * @param int $offset Number of results to skip (usually 0)
785 * @return string[] Matching subpages
787 public function prefixSearchSubpages( $search, $limit, $offset ) {
788 $user = User
::newFromName( $search );
790 // No prefix suggestion for invalid user
793 // Autocomplete subpage as user list - public to allow caching
794 return UserNamePrefixSearch
::search( 'public', $search, $limit, $offset );
797 protected function getGroupName() {