(bug 18533) Add readonly reason to readonly exception
[mediawiki.git] / includes / specials / SpecialUserrights.php
blob22929b17f33ffb8226a453b53feffd5ed6a58a61
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 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;
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(
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 ) );
196 $oldGroups = $user->getGroups();
197 $newGroups = $oldGroups;
199 // remove then add groups
200 if( $remove ) {
201 $newGroups = array_diff($newGroups, $remove);
202 foreach( $remove as $group ) {
203 $user->removeGroup( $group );
206 if( $add ) {
207 $newGroups = array_merge($newGroups, $add);
208 foreach( $add as $group ) {
209 $user->addGroup( $group );
212 $newGroups = array_unique( $newGroups );
214 // Ensure that caches are cleared
215 $user->invalidateCache();
217 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
218 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
219 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
221 if( $newGroups != $oldGroups ) {
222 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
224 return array( $add, $remove );
229 * Add a rights log entry for an action.
231 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
232 $log = new LogPage( 'rights' );
234 $log->addEntry( 'rights',
235 $user->getUserPage(),
236 $reason,
237 array(
238 $this->makeGroupNameListForLog( $oldGroups ),
239 $this->makeGroupNameListForLog( $newGroups )
245 * Edit user groups membership
246 * @param $username String: name of the user.
248 function editUserGroupsForm( $username ) {
249 global $wgOut;
251 $user = $this->fetchUser( $username );
252 if( $user instanceof WikiErrorMsg ) {
253 $wgOut->addWikiMsgArray($user->getMessageKey(), $user->getMessageArgs());
254 return;
257 $groups = $user->getGroups();
259 $this->showEditUserGroupsForm( $user, $groups );
261 // This isn't really ideal logging behavior, but let's not hide the
262 // interwiki logs if we're using them as is.
263 $this->showLogFragment( $user, $wgOut );
267 * Normalize the input username, which may be local or remote, and
268 * return a user (or proxy) object for manipulating it.
270 * Side effects: error output for invalid access
271 * @return mixed User, UserRightsProxy, or WikiErrorMsg
273 function fetchUser( $username ) {
274 global $wgUser, $wgUserrightsInterwikiDelimiter;
276 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
277 if( count( $parts ) < 2 ) {
278 $name = trim( $username );
279 $database = '';
280 } else {
281 list( $name, $database ) = array_map( 'trim', $parts );
283 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
284 return new WikiErrorMsg( 'userrights-no-interwiki' );
286 if( !UserRightsProxy::validDatabase( $database ) ) {
287 return new WikiErrorMsg( 'userrights-nodatabase', $database );
291 if( $name == '' ) {
292 return new WikiErrorMsg( 'nouserspecified' );
295 if( $name{0} == '#' ) {
296 // Numeric ID can be specified...
297 // We'll do a lookup for the name internally.
298 $id = intval( substr( $name, 1 ) );
300 if( $database == '' ) {
301 $name = User::whoIs( $id );
302 } else {
303 $name = UserRightsProxy::whoIs( $database, $id );
306 if( !$name ) {
307 return new WikiErrorMsg( 'noname' );
311 if( $database == '' ) {
312 $user = User::newFromName( $name );
313 } else {
314 $user = UserRightsProxy::newFromName( $database, $name );
317 if( !$user || $user->isAnon() ) {
318 return new WikiErrorMsg( 'nosuchusershort', $username );
321 return $user;
324 function makeGroupNameList( $ids ) {
325 if( empty( $ids ) ) {
326 return wfMsgForContent( 'rightsnone' );
327 } else {
328 return implode( ', ', $ids );
332 function makeGroupNameListForLog( $ids ) {
333 if( empty( $ids ) ) {
334 return '';
335 } else {
336 return $this->makeGroupNameList( $ids );
341 * Output a form to allow searching for a user
343 function switchForm() {
344 global $wgOut, $wgScript;
345 $wgOut->addHTML(
346 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
347 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
348 Xml::openElement( 'fieldset' ) .
349 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
350 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
351 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
352 Xml::closeElement( 'fieldset' ) .
353 Xml::closeElement( 'form' ) . "\n"
358 * Go through used and available groups and return the ones that this
359 * form will be able to manipulate based on the current user's system
360 * permissions.
362 * @param $groups Array: list of groups the given user is in
363 * @return Array: Tuple of addable, then removable groups
365 protected function splitGroups( $groups ) {
366 list($addable, $removable, $addself, $removeself) = array_values( $this->changeableGroups() );
368 $removable = array_intersect(
369 array_merge( $this->isself ? $removeself : array(), $removable ),
370 $groups ); // Can't remove groups the user doesn't have
371 $addable = array_diff(
372 array_merge( $this->isself ? $addself : array(), $addable ),
373 $groups ); // Can't add groups the user does have
375 return array( $addable, $removable );
379 * Show the form to edit group memberships.
381 * @param $user User or UserRightsProxy you're editing
382 * @param $groups Array: Array of groups the user is in
384 protected function showEditUserGroupsForm( $user, $groups ) {
385 global $wgOut, $wgUser, $wgLang;
387 $list = array();
388 foreach( $groups as $group )
389 $list[] = self::buildGroupLink( $group );
391 $grouplist = '';
392 if( count( $list ) > 0 ) {
393 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
394 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . '</p>';
396 $wgOut->addHTML(
397 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
398 Xml::hidden( 'user', $this->mTarget ) .
399 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
400 Xml::openElement( 'fieldset' ) .
401 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
402 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
403 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
404 $grouplist .
405 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
406 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
407 "<tr>
408 <td class='mw-label'>" .
409 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
410 "</td>
411 <td class='mw-input'>" .
412 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
413 "</td>
414 </tr>
415 <tr>
416 <td></td>
417 <td class='mw-submit'>" .
418 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
419 "</td>
420 </tr>" .
421 Xml::closeElement( 'table' ) . "\n" .
422 Xml::closeElement( 'fieldset' ) .
423 Xml::closeElement( 'form' ) . "\n"
428 * Format a link to a group description page
430 * @param $group string
431 * @return string
433 private static function buildGroupLink( $group ) {
434 static $cache = array();
435 if( !isset( $cache[$group] ) )
436 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
437 return $cache[$group];
441 * Returns an array of all groups that may be edited
442 * @return array Array of groups that may be edited.
444 protected static function getAllGroups() {
445 return User::getAllGroups();
449 * Adds a table with checkboxes where you can select what groups to add/remove
451 * @param $usergroups Array: groups the user belongs to
452 * @return string XHTML table element with checkboxes
454 private function groupCheckboxes( $usergroups ) {
455 $allgroups = $this->getAllGroups();
456 $ret = '';
458 # Put all column info into an associative array so that extensions can
459 # more easily manage it.
460 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
462 foreach( $allgroups as $group ) {
463 $set = in_array( $group, $usergroups );
464 # Should the checkbox be disabled?
465 $disabled = !(
466 ( $set && $this->canRemove( $group ) ) ||
467 ( !$set && $this->canAdd( $group ) ) );
468 # Do we need to point out that this action is irreversible?
469 $irreversible = !$disabled && (
470 ($set && !$this->canAdd( $group )) ||
471 (!$set && !$this->canRemove( $group ) ) );
473 $checkbox = array(
474 'set' => $set,
475 'disabled' => $disabled,
476 'irreversible' => $irreversible
479 if( $disabled ) {
480 $columns['unchangeable'][$group] = $checkbox;
481 } else {
482 $columns['changeable'][$group] = $checkbox;
486 # Build the HTML table
487 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
488 "<tr>\n";
489 foreach( $columns as $name => $column ) {
490 if( $column === array() )
491 continue;
492 $ret .= xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
494 $ret.= "</tr>\n<tr>\n";
495 foreach( $columns as $column ) {
496 if( $column === array() )
497 continue;
498 $ret .= "\t<td style='vertical-align:top;'>\n";
499 foreach( $column as $group => $checkbox ) {
500 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
501 $text = $checkbox['irreversible']
502 ? wfMsgHtml( 'userrights-irreversible-marker', User::getGroupMember( $group ) )
503 : User::getGroupMember( $group );
504 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
505 "wpGroup-" . $group, $checkbox['set'], $attr );
506 $ret .= "\t\t" . ( $checkbox['disabled']
507 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
508 : $checkboxHtml
509 ) . "<br />\n";
511 $ret .= "\t</td>\n";
513 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
515 return $ret;
519 * @param $group String: the name of the group to check
520 * @return bool Can we remove the group?
522 private function canRemove( $group ) {
523 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
524 // PHP.
525 $groups = $this->changeableGroups();
526 return in_array( $group, $groups['remove'] ) || ($this->isself && in_array( $group, $groups['remove-self'] ));
530 * @param $group string: the name of the group to check
531 * @return bool Can we add the group?
533 private function canAdd( $group ) {
534 $groups = $this->changeableGroups();
535 return in_array( $group, $groups['add'] ) || ($this->isself && in_array( $group, $groups['add-self'] ));
539 * Returns $wgUser->changeableGroups()
541 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
543 function changeableGroups() {
544 global $wgUser;
545 return $wgUser->changeableGroups();
549 * Show a rights log fragment for the specified user
551 * @param $user User to show log for
552 * @param $output OutputPage to use
554 protected function showLogFragment( $user, $output ) {
555 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
556 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );