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