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