Merge "Use a fixed marker prefix string in the Parser and MWTidy"
[mediawiki.git] / includes / specials / SpecialUserrights.php
blob758e3c05a36e57e3ea06bd9671ca4d37cfd1f988
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' );
138 $this->addHelpLink( 'Help:Assigning permissions' );
140 // show the general form
141 if ( count( $available['add'] ) || count( $available['remove'] ) ) {
142 $this->switchForm();
145 if (
146 $request->wasPosted() &&
147 $request->getCheck( 'saveusergroups' ) &&
148 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
150 // save settings
151 $status = $this->fetchUser( $this->mTarget );
152 if ( !$status->isOK() ) {
153 $this->getOutput()->addWikiText( $status->getWikiText() );
155 return;
158 $targetUser = $status->value;
159 if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (bug 61252)
160 $targetUser->clearInstanceCache(); // bug 38989
163 if ( $request->getVal( 'conflictcheck-originalgroups' )
164 !== implode( ',', $targetUser->getGroups() )
166 $out->addWikiMsg( 'userrights-conflict' );
167 } else {
168 $this->saveUserGroups(
169 $this->mTarget,
170 $request->getVal( 'user-reason' ),
171 $targetUser
174 $out->redirect( $this->getSuccessURL() );
176 return;
180 // show some more forms
181 if ( $this->mTarget !== null ) {
182 $this->editUserGroupsForm( $this->mTarget );
186 function getSuccessURL() {
187 return $this->getPageTitle( $this->mTarget )->getFullURL( array( 'success' => 1 ) );
191 * Save user groups changes in the database.
192 * Data comes from the editUserGroupsForm() form function
194 * @param string $username Username to apply changes to.
195 * @param string $reason Reason for group change
196 * @param User|UserRightsProxy $user Target user object.
197 * @return null
199 function saveUserGroups( $username, $reason, $user ) {
200 $allgroups = $this->getAllGroups();
201 $addgroup = array();
202 $removegroup = array();
204 // This could possibly create a highly unlikely race condition if permissions are changed between
205 // when the form is loaded and when the form is saved. Ignoring it for the moment.
206 foreach ( $allgroups as $group ) {
207 // We'll tell it to remove all unchecked groups, and add all checked groups.
208 // Later on, this gets filtered for what can actually be removed
209 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
210 $addgroup[] = $group;
211 } else {
212 $removegroup[] = $group;
216 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
220 * Save user groups changes in the database.
222 * @param User|UserRightsProxy $user
223 * @param array $add Array of groups to add
224 * @param array $remove Array of groups to remove
225 * @param string $reason Reason for group change
226 * @return array Tuple of added, then removed groups
228 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
229 global $wgAuth;
231 // Validate input set...
232 $isself = $user->getName() == $this->getUser()->getName();
233 $groups = $user->getGroups();
234 $changeable = $this->changeableGroups();
235 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
236 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
238 $remove = array_unique(
239 array_intersect( (array)$remove, $removable, $groups ) );
240 $add = array_unique( array_diff(
241 array_intersect( (array)$add, $addable ),
242 $groups )
245 $oldGroups = $user->getGroups();
246 $newGroups = $oldGroups;
248 // Remove then add groups
249 if ( $remove ) {
250 foreach ( $remove as $index => $group ) {
251 if ( !$user->removeGroup( $group ) ) {
252 unset($remove[$index]);
255 $newGroups = array_diff( $newGroups, $remove );
257 if ( $add ) {
258 foreach ( $add as $index => $group ) {
259 if ( !$user->addGroup( $group ) ) {
260 unset($add[$index]);
263 $newGroups = array_merge( $newGroups, $add );
265 $newGroups = array_unique( $newGroups );
267 // Ensure that caches are cleared
268 $user->invalidateCache();
270 // update groups in external authentication database
271 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
273 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
274 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
275 Hooks::run( 'UserRights', array( &$user, $add, $remove ) );
277 if ( $newGroups != $oldGroups ) {
278 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
281 return array( $add, $remove );
285 * Add a rights log entry for an action.
286 * @param User $user
287 * @param array $oldGroups
288 * @param array $newGroups
289 * @param array $reason
291 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
292 $logEntry = new ManualLogEntry( 'rights', 'rights' );
293 $logEntry->setPerformer( $this->getUser() );
294 $logEntry->setTarget( $user->getUserPage() );
295 $logEntry->setComment( $reason );
296 $logEntry->setParameters( array(
297 '4::oldgroups' => $oldGroups,
298 '5::newgroups' => $newGroups,
299 ) );
300 $logid = $logEntry->insert();
301 $logEntry->publish( $logid );
305 * Edit user groups membership
306 * @param string $username Name of the user.
308 function editUserGroupsForm( $username ) {
309 $status = $this->fetchUser( $username );
310 if ( !$status->isOK() ) {
311 $this->getOutput()->addWikiText( $status->getWikiText() );
313 return;
314 } else {
315 $user = $status->value;
318 $groups = $user->getGroups();
320 $this->showEditUserGroupsForm( $user, $groups );
322 // This isn't really ideal logging behavior, but let's not hide the
323 // interwiki logs if we're using them as is.
324 $this->showLogFragment( $user, $this->getOutput() );
328 * Normalize the input username, which may be local or remote, and
329 * return a user (or proxy) object for manipulating it.
331 * Side effects: error output for invalid access
332 * @param string $username
333 * @return Status
335 public function fetchUser( $username ) {
336 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
337 if ( count( $parts ) < 2 ) {
338 $name = trim( $username );
339 $database = '';
340 } else {
341 list( $name, $database ) = array_map( 'trim', $parts );
343 if ( $database == wfWikiID() ) {
344 $database = '';
345 } else {
346 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
347 return Status::newFatal( 'userrights-no-interwiki' );
349 if ( !UserRightsProxy::validDatabase( $database ) ) {
350 return Status::newFatal( 'userrights-nodatabase', $database );
355 if ( $name === '' ) {
356 return Status::newFatal( 'nouserspecified' );
359 if ( $name[0] == '#' ) {
360 // Numeric ID can be specified...
361 // We'll do a lookup for the name internally.
362 $id = intval( substr( $name, 1 ) );
364 if ( $database == '' ) {
365 $name = User::whoIs( $id );
366 } else {
367 $name = UserRightsProxy::whoIs( $database, $id );
370 if ( !$name ) {
371 return Status::newFatal( 'noname' );
373 } else {
374 $name = User::getCanonicalName( $name );
375 if ( $name === false ) {
376 // invalid name
377 return Status::newFatal( 'nosuchusershort', $username );
381 if ( $database == '' ) {
382 $user = User::newFromName( $name );
383 } else {
384 $user = UserRightsProxy::newFromName( $database, $name );
387 if ( !$user || $user->isAnon() ) {
388 return Status::newFatal( 'nosuchusershort', $username );
391 return Status::newGood( $user );
394 function makeGroupNameList( $ids ) {
395 if ( empty( $ids ) ) {
396 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
397 } else {
398 return implode( ', ', $ids );
403 * Make a list of group names to be stored as parameter for log entries
405 * @deprecated since 1.21; use LogFormatter instead.
406 * @param array $ids
407 * @return string
409 function makeGroupNameListForLog( $ids ) {
410 wfDeprecated( __METHOD__, '1.21' );
412 if ( empty( $ids ) ) {
413 return '';
414 } else {
415 return $this->makeGroupNameList( $ids );
420 * Output a form to allow searching for a user
422 function switchForm() {
423 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
425 $this->getOutput()->addHTML(
426 Html::openElement(
427 'form',
428 array(
429 'method' => 'get',
430 'action' => wfScript(),
431 'name' => 'uluser',
432 'id' => 'mw-userrights-form1'
435 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
436 Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
437 Xml::inputLabel(
438 $this->msg( 'userrights-user-editname' )->text(),
439 'user',
440 'username',
442 str_replace( '_', ' ', $this->mTarget ),
443 array(
444 'autofocus' => '',
445 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
447 ) . ' ' .
448 Xml::submitButton( $this->msg( 'editusergroup' )->text() ) .
449 Html::closeElement( 'fieldset' ) .
450 Html::closeElement( 'form' ) . "\n"
455 * Go through used and available groups and return the ones that this
456 * form will be able to manipulate based on the current user's system
457 * permissions.
459 * @param array $groups List of groups the given user is in
460 * @return array Tuple of addable, then removable groups
462 protected function splitGroups( $groups ) {
463 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
465 $removable = array_intersect(
466 array_merge( $this->isself ? $removeself : array(), $removable ),
467 $groups
468 ); // Can't remove groups the user doesn't have
469 $addable = array_diff(
470 array_merge( $this->isself ? $addself : array(), $addable ),
471 $groups
472 ); // Can't add groups the user does have
474 return array( $addable, $removable );
478 * Show the form to edit group memberships.
480 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
481 * @param array $groups Array of groups the user is in
483 protected function showEditUserGroupsForm( $user, $groups ) {
484 $list = array();
485 $membersList = array();
486 foreach ( $groups as $group ) {
487 $list[] = self::buildGroupLink( $group );
488 $membersList[] = self::buildGroupMemberLink( $group );
491 $autoList = array();
492 $autoMembersList = array();
493 if ( $user instanceof User ) {
494 foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
495 $autoList[] = self::buildGroupLink( $group );
496 $autoMembersList[] = self::buildGroupMemberLink( $group );
500 $language = $this->getLanguage();
501 $displayedList = $this->msg( 'userrights-groupsmember-type' )
502 ->rawParams(
503 $language->listToText( $list ),
504 $language->listToText( $membersList )
505 )->escaped();
506 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
507 ->rawParams(
508 $language->listToText( $autoList ),
509 $language->listToText( $autoMembersList )
510 )->escaped();
512 $grouplist = '';
513 $count = count( $list );
514 if ( $count > 0 ) {
515 $grouplist = $this->msg( 'userrights-groupsmember' )
516 ->numParams( $count )
517 ->params( $user->getName() )
518 ->parse();
519 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
522 $count = count( $autoList );
523 if ( $count > 0 ) {
524 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
525 ->numParams( $count )
526 ->params( $user->getName() )
527 ->parse();
528 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
531 $userToolLinks = Linker::userToolLinks(
532 $user->getId(),
533 $user->getName(),
534 false, /* default for redContribsWhenNoEdits */
535 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
538 $this->getOutput()->addHTML(
539 Xml::openElement(
540 'form',
541 array(
542 'method' => 'post',
543 'action' => $this->getPageTitle()->getLocalURL(),
544 'name' => 'editGroup',
545 'id' => 'mw-userrights-form2'
548 Html::hidden( 'user', $this->mTarget ) .
549 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
550 Html::hidden(
551 'conflictcheck-originalgroups',
552 implode( ',', $user->getGroups() )
553 ) . // Conflict detection
554 Xml::openElement( 'fieldset' ) .
555 Xml::element(
556 'legend',
557 array(),
558 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
560 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
561 ->rawParams( $userToolLinks )->parse() .
562 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
563 $grouplist .
564 $this->groupCheckboxes( $groups, $user ) .
565 Xml::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
566 "<tr>
567 <td class='mw-label'>" .
568 Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
569 "</td>
570 <td class='mw-input'>" .
571 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
572 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
573 "</td>
574 </tr>
575 <tr>
576 <td></td>
577 <td class='mw-submit'>" .
578 Xml::submitButton( $this->msg( 'saveusergroups' )->text(),
579 array( 'name' => 'saveusergroups' ) +
580 Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
582 "</td>
583 </tr>" .
584 Xml::closeElement( 'table' ) . "\n" .
585 Xml::closeElement( 'fieldset' ) .
586 Xml::closeElement( 'form' ) . "\n"
591 * Format a link to a group description page
593 * @param string $group
594 * @return string
596 private static function buildGroupLink( $group ) {
597 return User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
601 * Format a link to a group member description page
603 * @param string $group
604 * @return string
606 private static function buildGroupMemberLink( $group ) {
607 return User::makeGroupLinkHtml( $group, User::getGroupMember( $group ) );
611 * Returns an array of all groups that may be edited
612 * @return array Array of groups that may be edited.
614 protected static function getAllGroups() {
615 return User::getAllGroups();
619 * Adds a table with checkboxes where you can select what groups to add/remove
621 * @todo Just pass the username string?
622 * @param array $usergroups Groups the user belongs to
623 * @param User $user
624 * @return string XHTML table element with checkboxes
626 private function groupCheckboxes( $usergroups, $user ) {
627 $allgroups = $this->getAllGroups();
628 $ret = '';
630 // Put all column info into an associative array so that extensions can
631 // more easily manage it.
632 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
634 foreach ( $allgroups as $group ) {
635 $set = in_array( $group, $usergroups );
636 // Should the checkbox be disabled?
637 $disabled = !(
638 ( $set && $this->canRemove( $group ) ) ||
639 ( !$set && $this->canAdd( $group ) ) );
640 // Do we need to point out that this action is irreversible?
641 $irreversible = !$disabled && (
642 ( $set && !$this->canAdd( $group ) ) ||
643 ( !$set && !$this->canRemove( $group ) ) );
645 $checkbox = array(
646 'set' => $set,
647 'disabled' => $disabled,
648 'irreversible' => $irreversible
651 if ( $disabled ) {
652 $columns['unchangeable'][$group] = $checkbox;
653 } else {
654 $columns['changeable'][$group] = $checkbox;
658 // Build the HTML table
659 $ret .= Xml::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
660 "<tr>\n";
661 foreach ( $columns as $name => $column ) {
662 if ( $column === array() ) {
663 continue;
665 // Messages: userrights-changeable-col, userrights-unchangeable-col
666 $ret .= Xml::element(
667 'th',
668 null,
669 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
673 $ret .= "</tr>\n<tr>\n";
674 foreach ( $columns as $column ) {
675 if ( $column === array() ) {
676 continue;
678 $ret .= "\t<td style='vertical-align:top;'>\n";
679 foreach ( $column as $group => $checkbox ) {
680 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
682 $member = User::getGroupMember( $group, $user->getName() );
683 if ( $checkbox['irreversible'] ) {
684 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
685 } else {
686 $text = $member;
688 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
689 "wpGroup-" . $group, $checkbox['set'], $attr );
690 $ret .= "\t\t" . ( $checkbox['disabled']
691 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
692 : $checkboxHtml
693 ) . "<br />\n";
695 $ret .= "\t</td>\n";
697 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
699 return $ret;
703 * @param string $group The name of the group to check
704 * @return bool Can we remove the group?
706 private function canRemove( $group ) {
707 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
708 $groups = $this->changeableGroups();
710 return in_array(
711 $group,
712 $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
717 * @param string $group The name of the group to check
718 * @return bool Can we add the group?
720 private function canAdd( $group ) {
721 $groups = $this->changeableGroups();
723 return in_array(
724 $group,
725 $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
730 * Returns $this->getUser()->changeableGroups()
732 * @return array Array(
733 * 'add' => array( addablegroups ),
734 * 'remove' => array( removablegroups ),
735 * 'add-self' => array( addablegroups to self ),
736 * 'remove-self' => array( removable groups from self )
739 function changeableGroups() {
740 return $this->getUser()->changeableGroups();
744 * Show a rights log fragment for the specified user
746 * @param User $user User to show log for
747 * @param OutputPage $output OutputPage to use
749 protected function showLogFragment( $user, $output ) {
750 $rightsLogPage = new LogPage( 'rights' );
751 $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
752 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
755 protected function getGroupName() {
756 return 'users';