* Modified hook UserRights::showEditUserGroupsForm to actually be able to do
[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 if( $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $this->mTarget ) ) {
100 $this->saveUserGroups(
101 $this->mTarget,
102 $reason
103 );
104 }
105 }
106 }
107
108 // show some more forms
109 if( $this->mTarget ) {
110 $this->editUserGroupsForm( $this->mTarget );
111 }
112 }
113
114 /**
115 * Save user groups changes in the database.
116 * Data comes from the editUserGroupsForm() form function
117 *
118 * @param $username String: username to apply changes to.
119 * @param $reason String: reason for group change
120 * @return null
121 */
122 function saveUserGroups( $username, $reason = '') {
123 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
124
125 $user = $this->fetchUser( $username );
126 if( !$user ) {
127 return;
128 }
129
130 $allgroups = $this->getAllGroups();
131 $addgroup = array();
132 $removegroup = array();
133
134 // This could possibly create a highly unlikely race condition if permissions are changed between
135 // when the form is loaded and when the form is saved. Ignoring it for the moment.
136 foreach ($allgroups as $group) {
137 // We'll tell it to remove all unchecked groups, and add all checked groups.
138 // Later on, this gets filtered for what can actually be removed
139 if ($wgRequest->getCheck( "wpGroup-$group" )) {
140 $addgroup[] = $group;
141 } else {
142 $removegroup[] = $group;
143 }
144 }
145
146 // Validate input set...
147 $changeable = $this->changeableGroups();
148 $addable = array_merge( $changeable['add'], $this->isself ? $changeable['add-self'] : array() );
149 $removable = array_merge( $changeable['remove'], $this->isself ? $changeable['remove-self'] : array() );
150
151 $removegroup = array_unique(
152 array_intersect( (array)$removegroup, $removable ) );
153 $addgroup = array_unique(
154 array_intersect( (array)$addgroup, $addable ) );
155
156 $oldGroups = $user->getGroups();
157 $newGroups = $oldGroups;
158 // remove then add groups
159 if( $removegroup ) {
160 $newGroups = array_diff($newGroups, $removegroup);
161 foreach( $removegroup as $group ) {
162 $user->removeGroup( $group );
163 }
164 }
165 if( $addgroup ) {
166 $newGroups = array_merge($newGroups, $addgroup);
167 foreach( $addgroup as $group ) {
168 $user->addGroup( $group );
169 }
170 }
171 $newGroups = array_unique( $newGroups );
172
173 // Ensure that caches are cleared
174 $user->invalidateCache();
175
176 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
177 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
178 if( $user instanceof User ) {
179 // hmmm
180 wfRunHooks( 'UserRights', array( &$user, $addgroup, $removegroup ) );
181 }
182
183 if( $newGroups != $oldGroups ) {
184 $this->addLogEntry( $user, $oldGroups, $newGroups );
185 }
186 }
187
188 /**
189 * Add a rights log entry for an action.
190 */
191 function addLogEntry( $user, $oldGroups, $newGroups ) {
192 global $wgRequest;
193 $log = new LogPage( 'rights' );
194
195 $log->addEntry( 'rights',
196 $user->getUserPage(),
197 $wgRequest->getText( 'user-reason' ),
198 array(
199 $this->makeGroupNameListForLog( $oldGroups ),
200 $this->makeGroupNameListForLog( $newGroups )
201 )
202 );
203 }
204
205 /**
206 * Edit user groups membership
207 * @param $username String: 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 if( empty( $ids ) ) {
291 return wfMsgForContent( 'rightsnone' );
292 } else {
293 return implode( ', ', $ids );
294 }
295 }
296
297 function makeGroupNameListForLog( $ids ) {
298 if( empty( $ids ) ) {
299 return '';
300 } else {
301 return $this->makeGroupNameList( $ids );
302 }
303 }
304
305 /**
306 * Output a form to allow searching for a user
307 */
308 function switchForm() {
309 global $wgOut, $wgScript;
310 $wgOut->addHTML(
311 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
312 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
313 Xml::openElement( 'fieldset' ) .
314 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
315 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
316 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
317 Xml::closeElement( 'fieldset' ) .
318 Xml::closeElement( 'form' ) . "\n"
319 );
320 }
321
322 /**
323 * Go through used and available groups and return the ones that this
324 * form will be able to manipulate based on the current user's system
325 * permissions.
326 *
327 * @param $groups Array: list of groups the given user is in
328 * @return Array: Tuple of addable, then removable groups
329 */
330 protected function splitGroups( $groups ) {
331 list($addable, $removable, $addself, $removeself) = array_values( $this->changeableGroups() );
332
333 $removable = array_intersect(
334 array_merge( $this->isself ? $removeself : array(), $removable ),
335 $groups ); // Can't remove groups the user doesn't have
336 $addable = array_diff(
337 array_merge( $this->isself ? $addself : array(), $addable ),
338 $groups ); // Can't add groups the user does have
339
340 return array( $addable, $removable );
341 }
342
343 /**
344 * Show the form to edit group memberships.
345 *
346 * @param $user User or UserRightsProxy you're editing
347 * @param $groups Array: Array of groups the user is in
348 */
349 protected function showEditUserGroupsForm( $user, $groups ) {
350 global $wgOut, $wgUser, $wgLang;
351
352 wfRunHooks( 'UserRights::showEditUserGroupsForm', array( &$user, &$groups ) );
353
354 $list = array();
355 foreach( $groups as $group )
356 $list[] = self::buildGroupLink( $group );
357
358 $grouplist = '';
359 if( count( $list ) > 0 ) {
360 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
361 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . '</p>';
362 }
363 $wgOut->addHTML(
364 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
365 Xml::hidden( 'user', $this->mTarget ) .
366 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
367 Xml::openElement( 'fieldset' ) .
368 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
369 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
370 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
371 $grouplist .
372 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
373 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
374 "<tr>
375 <td class='mw-label'>" .
376 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
377 "</td>
378 <td class='mw-input'>" .
379 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
380 "</td>
381 </tr>
382 <tr>
383 <td></td>
384 <td class='mw-submit'>" .
385 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
386 "</td>
387 </tr>" .
388 Xml::closeElement( 'table' ) . "\n" .
389 Xml::closeElement( 'fieldset' ) .
390 Xml::closeElement( 'form' ) . "\n"
391 );
392 }
393
394 /**
395 * Format a link to a group description page
396 *
397 * @param $group string
398 * @return string
399 */
400 private static function buildGroupLink( $group ) {
401 static $cache = array();
402 if( !isset( $cache[$group] ) )
403 $cache[$group] = User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
404 return $cache[$group];
405 }
406
407 /**
408 * Returns an array of all groups that may be edited
409 * @return array Array of groups that may be edited.
410 */
411 protected static function getAllGroups() {
412 return User::getAllGroups();
413 }
414
415 /**
416 * Adds a table with checkboxes where you can select what groups to add/remove
417 *
418 * @param $usergroups Array: groups the user belongs to
419 * @return string XHTML table element with checkboxes
420 */
421 private function groupCheckboxes( $usergroups ) {
422 $allgroups = $this->getAllGroups();
423 $ret = '';
424
425 $column = 1;
426 $settable_col = '';
427 $unsettable_col = '';
428
429 foreach ($allgroups as $group) {
430 $set = in_array( $group, $usergroups );
431 # Should the checkbox be disabled?
432 $disabled = !(
433 ( $set && $this->canRemove( $group ) ) ||
434 ( !$set && $this->canAdd( $group ) ) );
435 # Do we need to point out that this action is irreversible?
436 $irreversible = !$disabled && (
437 ($set && !$this->canAdd( $group )) ||
438 (!$set && !$this->canRemove( $group ) ) );
439
440 $attr = $disabled ? array( 'disabled' => 'disabled' ) : array();
441 $text = $irreversible
442 ? wfMsgHtml( 'userrights-irreversible-marker', User::getGroupMember( $group ) )
443 : User::getGroupMember( $group );
444 $checkbox = Xml::checkLabel( $text, "wpGroup-$group",
445 "wpGroup-$group", $set, $attr );
446 $checkbox = $disabled ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkbox ) : $checkbox;
447
448 if ($disabled) {
449 $unsettable_col .= "$checkbox<br />\n";
450 } else {
451 $settable_col .= "$checkbox<br />\n";
452 }
453 }
454
455 if ($column) {
456 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
457 "<tr>
458 ";
459 if( $settable_col !== '' ) {
460 $ret .= xml::element( 'th', null, wfMsg( 'userrights-changeable-col' ) );
461 }
462 if( $unsettable_col !== '' ) {
463 $ret .= xml::element( 'th', null, wfMsg( 'userrights-unchangeable-col' ) );
464 }
465 $ret.= "</tr>
466 <tr>
467 ";
468 if( $settable_col !== '' ) {
469 $ret .=
470 " <td style='vertical-align:top;'>
471 $settable_col
472 </td>
473 ";
474 }
475 if( $unsettable_col !== '' ) {
476 $ret .=
477 " <td style='vertical-align:top;'>
478 $unsettable_col
479 </td>
480 ";
481 }
482 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
483 }
484
485 return $ret;
486 }
487
488 /**
489 * @param $group String: the name of the group to check
490 * @return bool Can we remove the group?
491 */
492 private function canRemove( $group ) {
493 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
494 // PHP.
495 $groups = $this->changeableGroups();
496 return in_array( $group, $groups['remove'] ) || ($this->isself && in_array( $group, $groups['remove-self'] ));
497 }
498
499 /**
500 * @param $group string: the name of the group to check
501 * @return bool Can we add the group?
502 */
503 private function canAdd( $group ) {
504 $groups = $this->changeableGroups();
505 return in_array( $group, $groups['add'] ) || ($this->isself && in_array( $group, $groups['add-self'] ));
506 }
507
508 /**
509 * Returns an array of the groups that the user can add/remove.
510 *
511 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
512 */
513 function changeableGroups() {
514 global $wgUser;
515
516 if( $wgUser->isAllowed( 'userrights' ) ) {
517 // This group gives the right to modify everything (reverse-
518 // compatibility with old "userrights lets you change
519 // everything")
520 // Using array_merge to make the groups reindexed
521 $all = array_merge( User::getAllGroups() );
522 return array(
523 'add' => $all,
524 'remove' => $all,
525 'add-self' => array(),
526 'remove-self' => array()
527 );
528 }
529
530 // Okay, it's not so simple, we will have to go through the arrays
531 $groups = array(
532 'add' => array(),
533 'remove' => array(),
534 'add-self' => array(),
535 'remove-self' => array() );
536 $addergroups = $wgUser->getEffectiveGroups();
537
538 foreach ($addergroups as $addergroup) {
539 $groups = array_merge_recursive(
540 $groups, $this->changeableByGroup($addergroup)
541 );
542 $groups['add'] = array_unique( $groups['add'] );
543 $groups['remove'] = array_unique( $groups['remove'] );
544 $groups['add-self'] = array_unique( $groups['add-self'] );
545 $groups['remove-self'] = array_unique( $groups['remove-self'] );
546 }
547
548 // Run a hook because we can
549 wfRunHooks( 'UserrightsChangeableGroups', array( $this, $wgUser, $addergroups, &$groups ) );
550
551 return $groups;
552 }
553
554 /**
555 * Returns an array of the groups that a particular group can add/remove.
556 *
557 * @param $group String: the group to check for whether it can add/remove
558 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
559 */
560 private function changeableByGroup( $group ) {
561 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
562
563 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
564 if( empty($wgAddGroups[$group]) ) {
565 // Don't add anything to $groups
566 } elseif( $wgAddGroups[$group] === true ) {
567 // You get everything
568 $groups['add'] = User::getAllGroups();
569 } elseif( is_array($wgAddGroups[$group]) ) {
570 $groups['add'] = $wgAddGroups[$group];
571 }
572
573 // Same thing for remove
574 if( empty($wgRemoveGroups[$group]) ) {
575 } elseif($wgRemoveGroups[$group] === true ) {
576 $groups['remove'] = User::getAllGroups();
577 } elseif( is_array($wgRemoveGroups[$group]) ) {
578 $groups['remove'] = $wgRemoveGroups[$group];
579 }
580
581 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
582 if( empty($wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
583 foreach($wgGroupsAddToSelf as $key => $value) {
584 if( is_int($key) ) {
585 $wgGroupsAddToSelf['user'][] = $value;
586 }
587 }
588 }
589
590 if( empty($wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
591 foreach($wgGroupsRemoveFromSelf as $key => $value) {
592 if( is_int($key) ) {
593 $wgGroupsRemoveFromSelf['user'][] = $value;
594 }
595 }
596 }
597
598 // Now figure out what groups the user can add to him/herself
599 if( empty($wgGroupsAddToSelf[$group]) ) {
600 } elseif( $wgGroupsAddToSelf[$group] === true ) {
601 // No idea WHY this would be used, but it's there
602 $groups['add-self'] = User::getAllGroups();
603 } elseif( is_array($wgGroupsAddToSelf[$group]) ) {
604 $groups['add-self'] = $wgGroupsAddToSelf[$group];
605 }
606
607 if( empty($wgGroupsRemoveFromSelf[$group]) ) {
608 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
609 $groups['remove-self'] = User::getAllGroups();
610 } elseif( is_array($wgGroupsRemoveFromSelf[$group]) ) {
611 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
612 }
613
614 return $groups;
615 }
616
617 /**
618 * Show a rights log fragment for the specified user
619 *
620 * @param $user User to show log for
621 * @param $output OutputPage to use
622 */
623 protected function showLogFragment( $user, $output ) {
624 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
625 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
626 }
627 }