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