Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / specials / SpecialUserrights.php
bloba5edcb02caa2c6c005ba33cdf1ed0f4712c9ca39
1 <?php
2 /**
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
20 * @file
21 * @ingroup SpecialPage
24 /**
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
32 # variable for it.
33 protected $mTarget;
34 protected $isself = false;
36 public function __construct() {
37 parent::__construct( 'Userrights' );
40 public function isRestricted() {
41 return true;
44 public function userCanExecute( User $user ) {
45 return $this->userCanChangeRights( $user, false );
48 /**
49 * @param User $user
50 * @param bool $checkIfSelf
51 * @return bool
53 public function userCanChangeRights( $user, $checkIfSelf = true ) {
54 $available = $this->changeableGroups();
55 if ( $user->getId() == 0 ) {
56 return false;
59 return !empty( $available['add'] )
60 || !empty( $available['remove'] )
61 || ( ( $this->isself || !$checkIfSelf ) &&
62 ( !empty( $available['add-self'] )
63 || !empty( $available['remove-self'] ) ) );
66 /**
67 * Manage forms to be shown according to posted data.
68 * Depending on the submit button used, call a form or a save function.
70 * @param string|null $par String if any subpage provided, else null
71 * @throws UserBlockedError|PermissionsError
73 public function execute( $par ) {
74 // If the visitor doesn't have permissions to assign or remove
75 // any groups, it's a bit silly to give them the user search prompt.
77 $user = $this->getUser();
80 * If the user is blocked and they only have "partial" access
81 * (e.g. they don't have the userrights permission), then don't
82 * allow them to use Special:UserRights.
84 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
85 throw new UserBlockedError( $user->getBlock() );
88 $request = $this->getRequest();
90 if ( $par !== null ) {
91 $this->mTarget = $par;
92 } else {
93 $this->mTarget = $request->getVal( 'user' );
96 $available = $this->changeableGroups();
98 if ( $this->mTarget === null ) {
100 * If the user specified no target, and they can only
101 * edit their own groups, automatically set them as the
102 * target.
104 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
105 $this->mTarget = $user->getName();
109 if ( User::getCanonicalName( $this->mTarget ) === $user->getName() ) {
110 $this->isself = true;
113 if ( !$this->userCanChangeRights( $user, true ) ) {
114 if ( $this->isself && $request->getCheck( 'success' ) ) {
115 // bug 48609: if the user just removed its own rights, this would
116 // leads it in a "permissions error" page. In that case, show a
117 // message that it can't anymore use this page instead of an error
118 $this->setHeaders();
119 $out = $this->getOutput();
120 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
121 $out->returnToMain();
123 return;
126 // @todo FIXME: There may be intermediate groups we can mention.
127 $msg = $user->isAnon() ? 'userrights-nologin' : 'userrights-notallowed';
128 throw new PermissionsError( null, array( array( $msg ) ) );
131 $this->checkReadOnly();
133 $this->setHeaders();
134 $this->outputHeader();
136 $out = $this->getOutput();
137 $out->addModuleStyles( 'mediawiki.special' );
139 // show the general form
140 if ( count( $available['add'] ) || count( $available['remove'] ) ) {
141 $this->switchForm();
144 if (
145 $request->wasPosted() &&
146 $request->getCheck( 'saveusergroups' ) &&
147 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
149 // save settings
150 $status = $this->fetchUser( $this->mTarget );
151 if ( !$status->isOK() ) {
152 $this->getOutput()->addWikiText( $status->getWikiText() );
154 return;
157 $targetUser = $status->value;
158 if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (bug 61252)
159 $targetUser->clearInstanceCache(); // bug 38989
162 if ( $request->getVal( 'conflictcheck-originalgroups' )
163 !== implode( ',', $targetUser->getGroups() )
165 $out->addWikiMsg( 'userrights-conflict' );
166 } else {
167 $this->saveUserGroups(
168 $this->mTarget,
169 $request->getVal( 'user-reason' ),
170 $targetUser
173 $out->redirect( $this->getSuccessURL() );
175 return;
179 // show some more forms
180 if ( $this->mTarget !== null ) {
181 $this->editUserGroupsForm( $this->mTarget );
185 function getSuccessURL() {
186 return $this->getPageTitle( $this->mTarget )->getFullURL( array( 'success' => 1 ) );
190 * Save user groups changes in the database.
191 * Data comes from the editUserGroupsForm() form function
193 * @param string $username Username to apply changes to.
194 * @param string $reason Reason for group change
195 * @param User|UserRightsProxy $user Target user object.
196 * @return null
198 function saveUserGroups( $username, $reason, $user ) {
199 $allgroups = $this->getAllGroups();
200 $addgroup = array();
201 $removegroup = array();
203 // This could possibly create a highly unlikely race condition if permissions are changed between
204 // when the form is loaded and when the form is saved. Ignoring it for the moment.
205 foreach ( $allgroups as $group ) {
206 // We'll tell it to remove all unchecked groups, and add all checked groups.
207 // Later on, this gets filtered for what can actually be removed
208 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
209 $addgroup[] = $group;
210 } else {
211 $removegroup[] = $group;
215 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
219 * Save user groups changes in the database.
221 * @param User|UserRightsProxy $user
222 * @param array $add Array of groups to add
223 * @param array $remove Array of groups to remove
224 * @param string $reason Reason for group change
225 * @return array Tuple of added, then removed groups
227 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
228 global $wgAuth;
230 // Validate input set...
231 $isself = $user->getName() == $this->getUser()->getName();
232 $groups = $user->getGroups();
233 $changeable = $this->changeableGroups();
234 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
235 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
237 $remove = array_unique(
238 array_intersect( (array)$remove, $removable, $groups ) );
239 $add = array_unique( array_diff(
240 array_intersect( (array)$add, $addable ),
241 $groups )
244 $oldGroups = $user->getGroups();
245 $newGroups = $oldGroups;
247 // Remove then add groups
248 if ( $remove ) {
249 foreach ( $remove as $index => $group ) {
250 if ( !$user->removeGroup( $group ) ) {
251 unset($remove[$index]);
254 $newGroups = array_diff( $newGroups, $remove );
256 if ( $add ) {
257 foreach ( $add as $index => $group ) {
258 if ( !$user->addGroup( $group ) ) {
259 unset($add[$index]);
262 $newGroups = array_merge( $newGroups, $add );
264 $newGroups = array_unique( $newGroups );
266 // Ensure that caches are cleared
267 $user->invalidateCache();
269 // update groups in external authentication database
270 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
272 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
273 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
274 Hooks::run( 'UserRights', array( &$user, $add, $remove ) );
276 if ( $newGroups != $oldGroups ) {
277 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
280 return array( $add, $remove );
284 * Add a rights log entry for an action.
285 * @param User $user
286 * @param array $oldGroups
287 * @param array $newGroups
288 * @param array $reason
290 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
291 $logEntry = new ManualLogEntry( 'rights', 'rights' );
292 $logEntry->setPerformer( $this->getUser() );
293 $logEntry->setTarget( $user->getUserPage() );
294 $logEntry->setComment( $reason );
295 $logEntry->setParameters( array(
296 '4::oldgroups' => $oldGroups,
297 '5::newgroups' => $newGroups,
298 ) );
299 $logid = $logEntry->insert();
300 $logEntry->publish( $logid );
304 * Edit user groups membership
305 * @param string $username Name of the user.
307 function editUserGroupsForm( $username ) {
308 $status = $this->fetchUser( $username );
309 if ( !$status->isOK() ) {
310 $this->getOutput()->addWikiText( $status->getWikiText() );
312 return;
313 } else {
314 $user = $status->value;
317 $groups = $user->getGroups();
319 $this->showEditUserGroupsForm( $user, $groups );
321 // This isn't really ideal logging behavior, but let's not hide the
322 // interwiki logs if we're using them as is.
323 $this->showLogFragment( $user, $this->getOutput() );
327 * Normalize the input username, which may be local or remote, and
328 * return a user (or proxy) object for manipulating it.
330 * Side effects: error output for invalid access
331 * @param string $username
332 * @return Status
334 public function fetchUser( $username ) {
335 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
336 if ( count( $parts ) < 2 ) {
337 $name = trim( $username );
338 $database = '';
339 } else {
340 list( $name, $database ) = array_map( 'trim', $parts );
342 if ( $database == wfWikiID() ) {
343 $database = '';
344 } else {
345 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
346 return Status::newFatal( 'userrights-no-interwiki' );
348 if ( !UserRightsProxy::validDatabase( $database ) ) {
349 return Status::newFatal( 'userrights-nodatabase', $database );
354 if ( $name === '' ) {
355 return Status::newFatal( 'nouserspecified' );
358 if ( $name[0] == '#' ) {
359 // Numeric ID can be specified...
360 // We'll do a lookup for the name internally.
361 $id = intval( substr( $name, 1 ) );
363 if ( $database == '' ) {
364 $name = User::whoIs( $id );
365 } else {
366 $name = UserRightsProxy::whoIs( $database, $id );
369 if ( !$name ) {
370 return Status::newFatal( 'noname' );
372 } else {
373 $name = User::getCanonicalName( $name );
374 if ( $name === false ) {
375 // invalid name
376 return Status::newFatal( 'nosuchusershort', $username );
380 if ( $database == '' ) {
381 $user = User::newFromName( $name );
382 } else {
383 $user = UserRightsProxy::newFromName( $database, $name );
386 if ( !$user || $user->isAnon() ) {
387 return Status::newFatal( 'nosuchusershort', $username );
390 return Status::newGood( $user );
393 function makeGroupNameList( $ids ) {
394 if ( empty( $ids ) ) {
395 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
396 } else {
397 return implode( ', ', $ids );
402 * Make a list of group names to be stored as parameter for log entries
404 * @deprecated since 1.21; use LogFormatter instead.
405 * @param array $ids
406 * @return string
408 function makeGroupNameListForLog( $ids ) {
409 wfDeprecated( __METHOD__, '1.21' );
411 if ( empty( $ids ) ) {
412 return '';
413 } else {
414 return $this->makeGroupNameList( $ids );
419 * Output a form to allow searching for a user
421 function switchForm() {
422 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
424 $this->getOutput()->addHTML(
425 Html::openElement(
426 'form',
427 array(
428 'method' => 'get',
429 'action' => wfScript(),
430 'name' => 'uluser',
431 'id' => 'mw-userrights-form1'
434 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
435 Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
436 Xml::inputLabel(
437 $this->msg( 'userrights-user-editname' )->text(),
438 'user',
439 'username',
441 str_replace( '_', ' ', $this->mTarget ),
442 array(
443 'autofocus' => true,
444 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
446 ) . ' ' .
447 Xml::submitButton( $this->msg( 'editusergroup' )->text() ) .
448 Html::closeElement( 'fieldset' ) .
449 Html::closeElement( 'form' ) . "\n"
454 * Go through used and available groups and return the ones that this
455 * form will be able to manipulate based on the current user's system
456 * permissions.
458 * @param array $groups List of groups the given user is in
459 * @return array Tuple of addable, then removable groups
461 protected function splitGroups( $groups ) {
462 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
464 $removable = array_intersect(
465 array_merge( $this->isself ? $removeself : array(), $removable ),
466 $groups
467 ); // Can't remove groups the user doesn't have
468 $addable = array_diff(
469 array_merge( $this->isself ? $addself : array(), $addable ),
470 $groups
471 ); // Can't add groups the user does have
473 return array( $addable, $removable );
477 * Show the form to edit group memberships.
479 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
480 * @param array $groups Array of groups the user is in
482 protected function showEditUserGroupsForm( $user, $groups ) {
483 $list = array();
484 $membersList = array();
485 foreach ( $groups as $group ) {
486 $list[] = self::buildGroupLink( $group );
487 $membersList[] = self::buildGroupMemberLink( $group );
490 $autoList = array();
491 $autoMembersList = array();
492 if ( $user instanceof User ) {
493 foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
494 $autoList[] = self::buildGroupLink( $group );
495 $autoMembersList[] = self::buildGroupMemberLink( $group );
499 $language = $this->getLanguage();
500 $displayedList = $this->msg( 'userrights-groupsmember-type' )
501 ->rawParams(
502 $language->listToText( $list ),
503 $language->listToText( $membersList )
504 )->escaped();
505 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
506 ->rawParams(
507 $language->listToText( $autoList ),
508 $language->listToText( $autoMembersList )
509 )->escaped();
511 $grouplist = '';
512 $count = count( $list );
513 if ( $count > 0 ) {
514 $grouplist = $this->msg( 'userrights-groupsmember' )
515 ->numParams( $count )
516 ->params( $user->getName() )
517 ->parse();
518 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
521 $count = count( $autoList );
522 if ( $count > 0 ) {
523 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
524 ->numParams( $count )
525 ->params( $user->getName() )
526 ->parse();
527 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
530 $userToolLinks = Linker::userToolLinks(
531 $user->getId(),
532 $user->getName(),
533 false, /* default for redContribsWhenNoEdits */
534 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
537 $this->getOutput()->addHTML(
538 Xml::openElement(
539 'form',
540 array(
541 'method' => 'post',
542 'action' => $this->getPageTitle()->getLocalURL(),
543 'name' => 'editGroup',
544 'id' => 'mw-userrights-form2'
547 Html::hidden( 'user', $this->mTarget ) .
548 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
549 Html::hidden(
550 'conflictcheck-originalgroups',
551 implode( ',', $user->getGroups() )
552 ) . // Conflict detection
553 Xml::openElement( 'fieldset' ) .
554 Xml::element(
555 'legend',
556 array(),
557 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
559 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
560 ->rawParams( $userToolLinks )->parse() .
561 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
562 $grouplist .
563 $this->groupCheckboxes( $groups, $user ) .
564 Xml::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
565 "<tr>
566 <td class='mw-label'>" .
567 Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
568 "</td>
569 <td class='mw-input'>" .
570 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
571 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
572 "</td>
573 </tr>
574 <tr>
575 <td></td>
576 <td class='mw-submit'>" .
577 Xml::submitButton( $this->msg( 'saveusergroups' )->text(),
578 array( 'name' => 'saveusergroups' ) +
579 Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
581 "</td>
582 </tr>" .
583 Xml::closeElement( 'table' ) . "\n" .
584 Xml::closeElement( 'fieldset' ) .
585 Xml::closeElement( 'form' ) . "\n"
590 * Format a link to a group description page
592 * @param string $group
593 * @return string
595 private static function buildGroupLink( $group ) {
596 return User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
600 * Format a link to a group member description page
602 * @param string $group
603 * @return string
605 private static function buildGroupMemberLink( $group ) {
606 return User::makeGroupLinkHtml( $group, User::getGroupMember( $group ) );
610 * Returns an array of all groups that may be edited
611 * @return array Array of groups that may be edited.
613 protected static function getAllGroups() {
614 return User::getAllGroups();
618 * Adds a table with checkboxes where you can select what groups to add/remove
620 * @todo Just pass the username string?
621 * @param array $usergroups Groups the user belongs to
622 * @param User $user
623 * @return string XHTML table element with checkboxes
625 private function groupCheckboxes( $usergroups, $user ) {
626 $allgroups = $this->getAllGroups();
627 $ret = '';
629 // Put all column info into an associative array so that extensions can
630 // more easily manage it.
631 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
633 foreach ( $allgroups as $group ) {
634 $set = in_array( $group, $usergroups );
635 // Should the checkbox be disabled?
636 $disabled = !(
637 ( $set && $this->canRemove( $group ) ) ||
638 ( !$set && $this->canAdd( $group ) ) );
639 // Do we need to point out that this action is irreversible?
640 $irreversible = !$disabled && (
641 ( $set && !$this->canAdd( $group ) ) ||
642 ( !$set && !$this->canRemove( $group ) ) );
644 $checkbox = array(
645 'set' => $set,
646 'disabled' => $disabled,
647 'irreversible' => $irreversible
650 if ( $disabled ) {
651 $columns['unchangeable'][$group] = $checkbox;
652 } else {
653 $columns['changeable'][$group] = $checkbox;
657 // Build the HTML table
658 $ret .= Xml::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
659 "<tr>\n";
660 foreach ( $columns as $name => $column ) {
661 if ( $column === array() ) {
662 continue;
664 // Messages: userrights-changeable-col, userrights-unchangeable-col
665 $ret .= Xml::element(
666 'th',
667 null,
668 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
672 $ret .= "</tr>\n<tr>\n";
673 foreach ( $columns as $column ) {
674 if ( $column === array() ) {
675 continue;
677 $ret .= "\t<td style='vertical-align:top;'>\n";
678 foreach ( $column as $group => $checkbox ) {
679 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
681 $member = User::getGroupMember( $group, $user->getName() );
682 if ( $checkbox['irreversible'] ) {
683 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
684 } else {
685 $text = $member;
687 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
688 "wpGroup-" . $group, $checkbox['set'], $attr );
689 $ret .= "\t\t" . ( $checkbox['disabled']
690 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
691 : $checkboxHtml
692 ) . "<br />\n";
694 $ret .= "\t</td>\n";
696 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
698 return $ret;
702 * @param string $group The name of the group to check
703 * @return bool Can we remove the group?
705 private function canRemove( $group ) {
706 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
707 $groups = $this->changeableGroups();
709 return in_array(
710 $group,
711 $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
716 * @param string $group The name of the group to check
717 * @return bool Can we add the group?
719 private function canAdd( $group ) {
720 $groups = $this->changeableGroups();
722 return in_array(
723 $group,
724 $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
729 * Returns $this->getUser()->changeableGroups()
731 * @return array Array(
732 * 'add' => array( addablegroups ),
733 * 'remove' => array( removablegroups ),
734 * 'add-self' => array( addablegroups to self ),
735 * 'remove-self' => array( removable groups from self )
738 function changeableGroups() {
739 return $this->getUser()->changeableGroups();
743 * Show a rights log fragment for the specified user
745 * @param User $user User to show log for
746 * @param OutputPage $output OutputPage to use
748 protected function showLogFragment( $user, $output ) {
749 $rightsLogPage = new LogPage( 'rights' );
750 $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
751 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
754 protected function getGroupName() {
755 return 'users';