more specific error message, using WikiError, if user trys to create account with...
[mediawiki.git] / includes / specials / SpecialUserrights.php
blobd3c9a31aa125e8653b716495e279096a4343941d
1 <?php
2 /**
3 * Special page to allow managing user group membership
5 * @file
6 * @ingroup SpecialPage
7 */
9 /**
10 * A class to manage user levels rights.
11 * @ingroup SpecialPage
13 class UserrightsPage extends SpecialPage {
14 # The target of the local right-adjuster's interest. Can be gotten from
15 # either a GET parameter or a subpage-style parameter, so have a member
16 # variable for it.
17 protected $mTarget;
18 protected $isself = false;
20 public function __construct() {
21 parent::__construct( 'Userrights' );
24 public function isRestricted() {
25 return true;
28 public function userCanExecute( $user ) {
29 return $this->userCanChangeRights( $user, false );
32 public function userCanChangeRights( $user, $checkIfSelf = true ) {
33 $available = $this->changeableGroups();
34 return !empty( $available['add'] )
35 or !empty( $available['remove'] )
36 or ( ( $this->isself || !$checkIfSelf ) and
37 ( !empty( $available['add-self'] )
38 or !empty( $available['remove-self'] ) ) );
41 /**
42 * Manage forms to be shown according to posted data.
43 * Depending on the submit button used, call a form or a save function.
45 * @param $par Mixed: string if any subpage provided, else null
47 public function execute( $par ) {
48 // If the visitor doesn't have permissions to assign or remove
49 // any groups, it's a bit silly to give them the user search prompt.
50 global $wgUser, $wgRequest, $wgOut;
52 if( $par ) {
53 $this->mTarget = $par;
54 } else {
55 $this->mTarget = $wgRequest->getVal( 'user' );
59 * If the user is blocked and they only have "partial" access
60 * (e.g. they don't have the userrights permission), then don't
61 * allow them to use Special:UserRights.
63 if( $wgUser->isBlocked() && !$wgUser->isAllowed( 'userrights' ) ) {
64 $wgOut->blockedPage();
65 return;
68 if ( !$this->mTarget ) {
70 * If the user specified no target, and they can only
71 * edit their own groups, automatically set them as the
72 * target.
74 $available = $this->changeableGroups();
75 if ( empty( $available['add'] ) && empty( $available['remove'] ) )
76 $this->mTarget = $wgUser->getName();
79 if ( $this->mTarget == $wgUser->getName() )
80 $this->isself = true;
82 if( !$this->userCanChangeRights( $wgUser, true ) ) {
83 // fixme... there may be intermediate groups we can mention.
84 global $wgOut;
85 $wgOut->showPermissionsErrorPage( array( array(
86 $wgUser->isAnon()
87 ? 'userrights-nologin'
88 : 'userrights-notallowed' ) ) );
89 return;
92 if ( wfReadOnly() ) {
93 global $wgOut;
94 $wgOut->readOnlyPage();
95 return;
98 $this->outputHeader();
100 $this->setHeaders();
102 // show the general form
103 $this->switchForm();
105 if( $wgRequest->wasPosted() ) {
106 // save settings
107 if( $wgRequest->getCheck( 'saveusergroups' ) ) {
108 $reason = $wgRequest->getVal( 'user-reason' );
109 $tok = $wgRequest->getVal( 'wpEditToken' );
110 if( $wgUser->matchEditToken( $tok, $this->mTarget ) ) {
111 $this->saveUserGroups(
112 $this->mTarget,
113 $reason
116 global $wgOut;
118 $url = $this->getSuccessURL();
119 $wgOut->redirect( $url );
120 return;
125 // show some more forms
126 if( $this->mTarget ) {
127 $this->editUserGroupsForm( $this->mTarget );
131 function getSuccessURL() {
132 return $this->getTitle( $this->mTarget )->getFullURL();
136 * Save user groups changes in the database.
137 * Data comes from the editUserGroupsForm() form function
139 * @param $username String: username to apply changes to.
140 * @param $reason String: reason for group change
141 * @return null
143 function saveUserGroups( $username, $reason = '' ) {
144 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
146 $user = $this->fetchUser( $username );
147 if( $user instanceof WikiErrorMsg ) {
148 $wgOut->addWikiMsgArray( $user->getMessageKey(), $user->getMessageArgs() );
149 return;
152 $allgroups = $this->getAllGroups();
153 $addgroup = array();
154 $removegroup = array();
156 // This could possibly create a highly unlikely race condition if permissions are changed between
157 // when the form is loaded and when the form is saved. Ignoring it for the moment.
158 foreach ( $allgroups as $group ) {
159 // We'll tell it to remove all unchecked groups, and add all checked groups.
160 // Later on, this gets filtered for what can actually be removed
161 if ( $wgRequest->getCheck( "wpGroup-$group" ) ) {
162 $addgroup[] = $group;
163 } else {
164 $removegroup[] = $group;
168 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
172 * Save user groups changes in the database.
174 * @param $user User object
175 * @param $add Array of groups to add
176 * @param $remove Array of groups to remove
177 * @param $reason String: reason for group change
178 * @return Array: Tuple of added, then removed groups
180 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
181 global $wgUser;
183 // Validate input set...
184 $isself = ( $user->getName() == $wgUser->getName() );
185 $groups = $user->getGroups();
186 $changeable = $this->changeableGroups();
187 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
188 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
190 $remove = array_unique(
191 array_intersect( (array)$remove, $removable, $groups ) );
192 $add = array_unique( array_diff(
193 array_intersect( (array)$add, $addable ),
194 $groups )
197 $oldGroups = $user->getGroups();
198 $newGroups = $oldGroups;
200 // remove then add groups
201 if( $remove ) {
202 $newGroups = array_diff( $newGroups, $remove );
203 foreach( $remove as $group ) {
204 $user->removeGroup( $group );
207 if( $add ) {
208 $newGroups = array_merge( $newGroups, $add );
209 foreach( $add as $group ) {
210 $user->addGroup( $group );
213 $newGroups = array_unique( $newGroups );
215 // Ensure that caches are cleared
216 $user->invalidateCache();
218 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
219 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
220 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
222 if( $newGroups != $oldGroups ) {
223 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
225 return array( $add, $remove );
230 * Add a rights log entry for an action.
232 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
233 $log = new LogPage( 'rights' );
235 $log->addEntry( 'rights',
236 $user->getUserPage(),
237 $reason,
238 array(
239 $this->makeGroupNameListForLog( $oldGroups ),
240 $this->makeGroupNameListForLog( $newGroups )
246 * Edit user groups membership
247 * @param $username String: name of the user.
249 function editUserGroupsForm( $username ) {
250 global $wgOut;
252 $user = $this->fetchUser( $username );
253 if( $user instanceof WikiErrorMsg ) {
254 $wgOut->addWikiMsgArray( $user->getMessageKey(), $user->getMessageArgs() );
255 return;
258 $groups = $user->getGroups();
260 $this->showEditUserGroupsForm( $user, $groups );
262 // This isn't really ideal logging behavior, but let's not hide the
263 // interwiki logs if we're using them as is.
264 $this->showLogFragment( $user, $wgOut );
268 * Normalize the input username, which may be local or remote, and
269 * return a user (or proxy) object for manipulating it.
271 * Side effects: error output for invalid access
272 * @return mixed User, UserRightsProxy, or WikiErrorMsg
274 public function fetchUser( $username ) {
275 global $wgUser, $wgUserrightsInterwikiDelimiter;
277 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
278 if( count( $parts ) < 2 ) {
279 $name = trim( $username );
280 $database = '';
281 } else {
282 list( $name, $database ) = array_map( 'trim', $parts );
284 if( $database == wfWikiID() ) {
285 $database = '';
286 } else {
287 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
288 return new WikiErrorMsg( 'userrights-no-interwiki' );
290 if( !UserRightsProxy::validDatabase( $database ) ) {
291 return new WikiErrorMsg( 'userrights-nodatabase', $database );
296 if( $name == '' ) {
297 return new WikiErrorMsg( 'nouserspecified' );
300 if( $name{0} == '#' ) {
301 // Numeric ID can be specified...
302 // We'll do a lookup for the name internally.
303 $id = intval( substr( $name, 1 ) );
305 if( $database == '' ) {
306 $name = User::whoIs( $id );
307 } else {
308 $name = UserRightsProxy::whoIs( $database, $id );
311 if( !$name ) {
312 return new WikiErrorMsg( 'noname' );
314 } else {
315 $name = User::getCanonicalName( $name );
316 if( !$name ) {
317 // invalid name
318 return new WikiErrorMsg( 'nosuchusershort', $username );
322 if( $database == '' ) {
323 $user = User::newFromName( $name );
324 } else {
325 $user = UserRightsProxy::newFromName( $database, $name );
328 if( !$user || $user->isAnon() ) {
329 return new WikiErrorMsg( 'nosuchusershort', $username );
332 return $user;
335 function makeGroupNameList( $ids ) {
336 if( empty( $ids ) ) {
337 return wfMsgForContent( 'rightsnone' );
338 } else {
339 return implode( ', ', $ids );
343 function makeGroupNameListForLog( $ids ) {
344 if( empty( $ids ) ) {
345 return '';
346 } else {
347 return $this->makeGroupNameList( $ids );
352 * Output a form to allow searching for a user
354 function switchForm() {
355 global $wgOut, $wgScript;
356 $wgOut->addHTML(
357 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
358 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
359 Xml::openElement( 'fieldset' ) .
360 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
361 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
362 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
363 Xml::closeElement( 'fieldset' ) .
364 Xml::closeElement( 'form' ) . "\n"
369 * Go through used and available groups and return the ones that this
370 * form will be able to manipulate based on the current user's system
371 * permissions.
373 * @param $groups Array: list of groups the given user is in
374 * @return Array: Tuple of addable, then removable groups
376 protected function splitGroups( $groups ) {
377 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
379 $removable = array_intersect(
380 array_merge( $this->isself ? $removeself : array(), $removable ),
381 $groups
382 ); // Can't remove groups the user doesn't have
383 $addable = array_diff(
384 array_merge( $this->isself ? $addself : array(), $addable ),
385 $groups
386 ); // Can't add groups the user does have
388 return array( $addable, $removable );
392 * Show the form to edit group memberships.
394 * @param $user User or UserRightsProxy you're editing
395 * @param $groups Array: Array of groups the user is in
397 protected function showEditUserGroupsForm( $user, $groups ) {
398 global $wgOut, $wgUser, $wgLang;
400 $list = array();
401 foreach( $groups as $group )
402 $list[] = self::buildGroupLink( $group );
404 $grouplist = '';
405 if( count( $list ) > 0 ) {
406 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
407 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . '</p>';
409 $wgOut->addHTML(
410 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
411 Xml::hidden( 'user', $this->mTarget ) .
412 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
413 Xml::openElement( 'fieldset' ) .
414 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
415 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
416 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
417 $grouplist .
418 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
419 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
420 "<tr>
421 <td class='mw-label'>" .
422 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
423 "</td>
424 <td class='mw-input'>" .
425 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
426 "</td>
427 </tr>
428 <tr>
429 <td></td>
430 <td class='mw-submit'>" .
431 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
432 "</td>
433 </tr>" .
434 Xml::closeElement( 'table' ) . "\n" .
435 Xml::closeElement( 'fieldset' ) .
436 Xml::closeElement( 'form' ) . "\n"
441 * Format a link to a group description page
443 * @param $group string
444 * @return string
446 private static function buildGroupLink( $group ) {
447 static $cache = array();
448 if( !isset( $cache[$group] ) )
449 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
450 return $cache[$group];
454 * Returns an array of all groups that may be edited
455 * @return array Array of groups that may be edited.
457 protected static function getAllGroups() {
458 return User::getAllGroups();
462 * Adds a table with checkboxes where you can select what groups to add/remove
464 * @param $usergroups Array: groups the user belongs to
465 * @return string XHTML table element with checkboxes
467 private function groupCheckboxes( $usergroups ) {
468 $allgroups = $this->getAllGroups();
469 $ret = '';
471 # Put all column info into an associative array so that extensions can
472 # more easily manage it.
473 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
475 foreach( $allgroups as $group ) {
476 $set = in_array( $group, $usergroups );
477 # Should the checkbox be disabled?
478 $disabled = !(
479 ( $set && $this->canRemove( $group ) ) ||
480 ( !$set && $this->canAdd( $group ) ) );
481 # Do we need to point out that this action is irreversible?
482 $irreversible = !$disabled && (
483 ( $set && !$this->canAdd( $group ) ) ||
484 ( !$set && !$this->canRemove( $group ) ) );
486 $checkbox = array(
487 'set' => $set,
488 'disabled' => $disabled,
489 'irreversible' => $irreversible
492 if( $disabled ) {
493 $columns['unchangeable'][$group] = $checkbox;
494 } else {
495 $columns['changeable'][$group] = $checkbox;
499 # Build the HTML table
500 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
501 "<tr>\n";
502 foreach( $columns as $name => $column ) {
503 if( $column === array() )
504 continue;
505 $ret .= xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
507 $ret.= "</tr>\n<tr>\n";
508 foreach( $columns as $column ) {
509 if( $column === array() )
510 continue;
511 $ret .= "\t<td style='vertical-align:top;'>\n";
512 foreach( $column as $group => $checkbox ) {
513 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
515 if ( $checkbox['irreversible'] ) {
516 $text = htmlspecialchars( wfMsg( 'userrights-irreversible-marker',
517 User::getGroupMember( $group ) ) );
518 } else {
519 $text = htmlspecialchars( User::getGroupMember( $group ) );
521 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
522 "wpGroup-" . $group, $checkbox['set'], $attr );
523 $ret .= "\t\t" . ( $checkbox['disabled']
524 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
525 : $checkboxHtml
526 ) . "<br />\n";
528 $ret .= "\t</td>\n";
530 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
532 return $ret;
536 * @param $group String: the name of the group to check
537 * @return bool Can we remove the group?
539 private function canRemove( $group ) {
540 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
541 // PHP.
542 $groups = $this->changeableGroups();
543 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
547 * @param $group string: the name of the group to check
548 * @return bool Can we add the group?
550 private function canAdd( $group ) {
551 $groups = $this->changeableGroups();
552 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
556 * Returns $wgUser->changeableGroups()
558 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
560 function changeableGroups() {
561 global $wgUser;
562 return $wgUser->changeableGroups();
566 * Show a rights log fragment for the specified user
568 * @param $user User to show log for
569 * @param $output OutputPage to use
571 protected function showLogFragment( $user, $output ) {
572 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
573 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );