* (bug 21518) Special:UserRights no longer displays the user name box for users that...
[lhc/web/wiklou.git] / includes / specials / SpecialUserrights.php
1 <?php
2 /**
3 * Special page to allow managing user group membership
4 *
5 * @file
6 * @ingroup SpecialPage
7 */
8
9 /**
10 * A class to manage user levels rights.
11 * @ingroup SpecialPage
12 */
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;
19
20 public function __construct() {
21 parent::__construct( 'Userrights' );
22 }
23
24 public function isRestricted() {
25 return true;
26 }
27
28 public function userCanExecute( $user ) {
29 return $this->userCanChangeRights( $user, false );
30 }
31
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'] ) ) );
39 }
40
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.
44 *
45 * @param $par Mixed: string if any subpage provided, else null
46 */
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;
51
52 if( $par ) {
53 $this->mTarget = $par;
54 } else {
55 $this->mTarget = $wgRequest->getVal( 'user' );
56 }
57
58 /*
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.
62 */
63 if( $wgUser->isBlocked() && !$wgUser->isAllowed( 'userrights' ) ) {
64 $wgOut->blockedPage();
65 return;
66 }
67
68 $available = $this->changeableGroups();
69
70 if ( !$this->mTarget ) {
71 /*
72 * If the user specified no target, and they can only
73 * edit their own groups, automatically set them as the
74 * target.
75 */
76 if ( !count( $available['add'] ) && !count( $available['remove'] ) )
77 $this->mTarget = $wgUser->getName();
78 }
79
80 if ( $this->mTarget == $wgUser->getName() )
81 $this->isself = true;
82
83 if( !$this->userCanChangeRights( $wgUser, true ) ) {
84 // fixme... there may be intermediate groups we can mention.
85 global $wgOut;
86 $wgOut->showPermissionsErrorPage( array( array(
87 $wgUser->isAnon()
88 ? 'userrights-nologin'
89 : 'userrights-notallowed' ) ) );
90 return;
91 }
92
93 if ( wfReadOnly() ) {
94 global $wgOut;
95 $wgOut->readOnlyPage();
96 return;
97 }
98
99 $this->outputHeader();
100
101 $this->setHeaders();
102
103 // show the general form
104 if ( count( $available['add'] ) || count( $available['remove'] ) )
105 $this->switchForm();
106
107 if( $wgRequest->wasPosted() ) {
108 // save settings
109 if( $wgRequest->getCheck( 'saveusergroups' ) ) {
110 $reason = $wgRequest->getVal( 'user-reason' );
111 $tok = $wgRequest->getVal( 'wpEditToken' );
112 if( $wgUser->matchEditToken( $tok, $this->mTarget ) ) {
113 $this->saveUserGroups(
114 $this->mTarget,
115 $reason
116 );
117
118 global $wgOut;
119
120 $url = $this->getSuccessURL();
121 $wgOut->redirect( $url );
122 return;
123 }
124 }
125 }
126
127 // show some more forms
128 if( $this->mTarget ) {
129 $this->editUserGroupsForm( $this->mTarget );
130 }
131 }
132
133 function getSuccessURL() {
134 return $this->getTitle( $this->mTarget )->getFullURL();
135 }
136
137 /**
138 * Save user groups changes in the database.
139 * Data comes from the editUserGroupsForm() form function
140 *
141 * @param $username String: username to apply changes to.
142 * @param $reason String: reason for group change
143 * @return null
144 */
145 function saveUserGroups( $username, $reason = '' ) {
146 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
147
148 $user = $this->fetchUser( $username );
149 if( $user instanceof WikiErrorMsg ) {
150 $wgOut->addWikiMsgArray( $user->getMessageKey(), $user->getMessageArgs() );
151 return;
152 }
153
154 $allgroups = $this->getAllGroups();
155 $addgroup = array();
156 $removegroup = array();
157
158 // This could possibly create a highly unlikely race condition if permissions are changed between
159 // when the form is loaded and when the form is saved. Ignoring it for the moment.
160 foreach ( $allgroups as $group ) {
161 // We'll tell it to remove all unchecked groups, and add all checked groups.
162 // Later on, this gets filtered for what can actually be removed
163 if ( $wgRequest->getCheck( "wpGroup-$group" ) ) {
164 $addgroup[] = $group;
165 } else {
166 $removegroup[] = $group;
167 }
168 }
169
170 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
171 }
172
173 /**
174 * Save user groups changes in the database.
175 *
176 * @param $user User object
177 * @param $add Array of groups to add
178 * @param $remove Array of groups to remove
179 * @param $reason String: reason for group change
180 * @return Array: Tuple of added, then removed groups
181 */
182 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
183 global $wgUser;
184
185 // Validate input set...
186 $isself = ( $user->getName() == $wgUser->getName() );
187 $groups = $user->getGroups();
188 $changeable = $this->changeableGroups();
189 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
190 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
191
192 $remove = array_unique(
193 array_intersect( (array)$remove, $removable, $groups ) );
194 $add = array_unique( array_diff(
195 array_intersect( (array)$add, $addable ),
196 $groups )
197 );
198
199 $oldGroups = $user->getGroups();
200 $newGroups = $oldGroups;
201
202 // remove then add groups
203 if( $remove ) {
204 $newGroups = array_diff( $newGroups, $remove );
205 foreach( $remove as $group ) {
206 $user->removeGroup( $group );
207 }
208 }
209 if( $add ) {
210 $newGroups = array_merge( $newGroups, $add );
211 foreach( $add as $group ) {
212 $user->addGroup( $group );
213 }
214 }
215 $newGroups = array_unique( $newGroups );
216
217 // Ensure that caches are cleared
218 $user->invalidateCache();
219
220 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
221 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
222 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
223
224 if( $newGroups != $oldGroups ) {
225 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
226 }
227 return array( $add, $remove );
228 }
229
230
231 /**
232 * Add a rights log entry for an action.
233 */
234 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
235 $log = new LogPage( 'rights' );
236
237 $log->addEntry( 'rights',
238 $user->getUserPage(),
239 $reason,
240 array(
241 $this->makeGroupNameListForLog( $oldGroups ),
242 $this->makeGroupNameListForLog( $newGroups )
243 )
244 );
245 }
246
247 /**
248 * Edit user groups membership
249 * @param $username String: name of the user.
250 */
251 function editUserGroupsForm( $username ) {
252 global $wgOut;
253
254 $user = $this->fetchUser( $username );
255 if( $user instanceof WikiErrorMsg ) {
256 $wgOut->addWikiMsgArray( $user->getMessageKey(), $user->getMessageArgs() );
257 return;
258 }
259
260 $groups = $user->getGroups();
261
262 $this->showEditUserGroupsForm( $user, $groups );
263
264 // This isn't really ideal logging behavior, but let's not hide the
265 // interwiki logs if we're using them as is.
266 $this->showLogFragment( $user, $wgOut );
267 }
268
269 /**
270 * Normalize the input username, which may be local or remote, and
271 * return a user (or proxy) object for manipulating it.
272 *
273 * Side effects: error output for invalid access
274 * @return mixed User, UserRightsProxy, or WikiErrorMsg
275 */
276 public function fetchUser( $username ) {
277 global $wgUser, $wgUserrightsInterwikiDelimiter;
278
279 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
280 if( count( $parts ) < 2 ) {
281 $name = trim( $username );
282 $database = '';
283 } else {
284 list( $name, $database ) = array_map( 'trim', $parts );
285
286 if( $database == wfWikiID() ) {
287 $database = '';
288 } else {
289 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
290 return new WikiErrorMsg( 'userrights-no-interwiki' );
291 }
292 if( !UserRightsProxy::validDatabase( $database ) ) {
293 return new WikiErrorMsg( 'userrights-nodatabase', $database );
294 }
295 }
296 }
297
298 if( $name == '' ) {
299 return new WikiErrorMsg( 'nouserspecified' );
300 }
301
302 if( $name{0} == '#' ) {
303 // Numeric ID can be specified...
304 // We'll do a lookup for the name internally.
305 $id = intval( substr( $name, 1 ) );
306
307 if( $database == '' ) {
308 $name = User::whoIs( $id );
309 } else {
310 $name = UserRightsProxy::whoIs( $database, $id );
311 }
312
313 if( !$name ) {
314 return new WikiErrorMsg( 'noname' );
315 }
316 } else {
317 $name = User::getCanonicalName( $name );
318 if( !$name ) {
319 // invalid name
320 return new WikiErrorMsg( 'nosuchusershort', $username );
321 }
322 }
323
324 if( $database == '' ) {
325 $user = User::newFromName( $name );
326 } else {
327 $user = UserRightsProxy::newFromName( $database, $name );
328 }
329
330 if( !$user || $user->isAnon() ) {
331 return new WikiErrorMsg( 'nosuchusershort', $username );
332 }
333
334 return $user;
335 }
336
337 function makeGroupNameList( $ids ) {
338 if( empty( $ids ) ) {
339 return wfMsgForContent( 'rightsnone' );
340 } else {
341 return implode( ', ', $ids );
342 }
343 }
344
345 function makeGroupNameListForLog( $ids ) {
346 if( empty( $ids ) ) {
347 return '';
348 } else {
349 return $this->makeGroupNameList( $ids );
350 }
351 }
352
353 /**
354 * Output a form to allow searching for a user
355 */
356 function switchForm() {
357 global $wgOut, $wgScript;
358 $wgOut->addHTML(
359 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
360 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
361 Xml::openElement( 'fieldset' ) .
362 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
363 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
364 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
365 Xml::closeElement( 'fieldset' ) .
366 Xml::closeElement( 'form' ) . "\n"
367 );
368 }
369
370 /**
371 * Go through used and available groups and return the ones that this
372 * form will be able to manipulate based on the current user's system
373 * permissions.
374 *
375 * @param $groups Array: list of groups the given user is in
376 * @return Array: Tuple of addable, then removable groups
377 */
378 protected function splitGroups( $groups ) {
379 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
380
381 $removable = array_intersect(
382 array_merge( $this->isself ? $removeself : array(), $removable ),
383 $groups
384 ); // Can't remove groups the user doesn't have
385 $addable = array_diff(
386 array_merge( $this->isself ? $addself : array(), $addable ),
387 $groups
388 ); // Can't add groups the user does have
389
390 return array( $addable, $removable );
391 }
392
393 /**
394 * Show the form to edit group memberships.
395 *
396 * @param $user User or UserRightsProxy you're editing
397 * @param $groups Array: Array of groups the user is in
398 */
399 protected function showEditUserGroupsForm( $user, $groups ) {
400 global $wgOut, $wgUser, $wgLang;
401
402 $list = array();
403 foreach( $groups as $group )
404 $list[] = self::buildGroupLink( $group );
405
406 $grouplist = '';
407 if( count( $list ) > 0 ) {
408 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
409 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . '</p>';
410 }
411 $wgOut->addHTML(
412 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
413 Xml::hidden( 'user', $this->mTarget ) .
414 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
415 Xml::openElement( 'fieldset' ) .
416 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
417 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
418 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
419 $grouplist .
420 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
421 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
422 "<tr>
423 <td class='mw-label'>" .
424 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
425 "</td>
426 <td class='mw-input'>" .
427 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
428 "</td>
429 </tr>
430 <tr>
431 <td></td>
432 <td class='mw-submit'>" .
433 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
434 "</td>
435 </tr>" .
436 Xml::closeElement( 'table' ) . "\n" .
437 Xml::closeElement( 'fieldset' ) .
438 Xml::closeElement( 'form' ) . "\n"
439 );
440 }
441
442 /**
443 * Format a link to a group description page
444 *
445 * @param $group string
446 * @return string
447 */
448 private static function buildGroupLink( $group ) {
449 static $cache = array();
450 if( !isset( $cache[$group] ) )
451 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
452 return $cache[$group];
453 }
454
455 /**
456 * Returns an array of all groups that may be edited
457 * @return array Array of groups that may be edited.
458 */
459 protected static function getAllGroups() {
460 return User::getAllGroups();
461 }
462
463 /**
464 * Adds a table with checkboxes where you can select what groups to add/remove
465 *
466 * @param $usergroups Array: groups the user belongs to
467 * @return string XHTML table element with checkboxes
468 */
469 private function groupCheckboxes( $usergroups ) {
470 $allgroups = $this->getAllGroups();
471 $ret = '';
472
473 # Put all column info into an associative array so that extensions can
474 # more easily manage it.
475 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
476
477 foreach( $allgroups as $group ) {
478 $set = in_array( $group, $usergroups );
479 # Should the checkbox be disabled?
480 $disabled = !(
481 ( $set && $this->canRemove( $group ) ) ||
482 ( !$set && $this->canAdd( $group ) ) );
483 # Do we need to point out that this action is irreversible?
484 $irreversible = !$disabled && (
485 ( $set && !$this->canAdd( $group ) ) ||
486 ( !$set && !$this->canRemove( $group ) ) );
487
488 $checkbox = array(
489 'set' => $set,
490 'disabled' => $disabled,
491 'irreversible' => $irreversible
492 );
493
494 if( $disabled ) {
495 $columns['unchangeable'][$group] = $checkbox;
496 } else {
497 $columns['changeable'][$group] = $checkbox;
498 }
499 }
500
501 # Build the HTML table
502 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
503 "<tr>\n";
504 foreach( $columns as $name => $column ) {
505 if( $column === array() )
506 continue;
507 $ret .= xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
508 }
509 $ret.= "</tr>\n<tr>\n";
510 foreach( $columns as $column ) {
511 if( $column === array() )
512 continue;
513 $ret .= "\t<td style='vertical-align:top;'>\n";
514 foreach( $column as $group => $checkbox ) {
515 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
516
517 if ( $checkbox['irreversible'] ) {
518 $text = htmlspecialchars( wfMsg( 'userrights-irreversible-marker',
519 User::getGroupMember( $group ) ) );
520 } else {
521 $text = htmlspecialchars( User::getGroupMember( $group ) );
522 }
523 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
524 "wpGroup-" . $group, $checkbox['set'], $attr );
525 $ret .= "\t\t" . ( $checkbox['disabled']
526 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
527 : $checkboxHtml
528 ) . "<br />\n";
529 }
530 $ret .= "\t</td>\n";
531 }
532 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
533
534 return $ret;
535 }
536
537 /**
538 * @param $group String: the name of the group to check
539 * @return bool Can we remove the group?
540 */
541 private function canRemove( $group ) {
542 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
543 // PHP.
544 $groups = $this->changeableGroups();
545 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
546 }
547
548 /**
549 * @param $group string: the name of the group to check
550 * @return bool Can we add the group?
551 */
552 private function canAdd( $group ) {
553 $groups = $this->changeableGroups();
554 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
555 }
556
557 /**
558 * Returns $wgUser->changeableGroups()
559 *
560 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
561 */
562 function changeableGroups() {
563 global $wgUser;
564 return $wgUser->changeableGroups();
565 }
566
567 /**
568 * Show a rights log fragment for the specified user
569 *
570 * @param $user User to show log for
571 * @param $output OutputPage to use
572 */
573 protected function showLogFragment( $user, $output ) {
574 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
575 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
576 }
577 }