Fix bug in global auth caused by r48970 (I think). You need to call this->changeableG...
[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->getSuccessURL();
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 function getSuccessURL() {
122 return $this->getTitle( $this->mTarget )->getFullURL();
123 }
124
125 /**
126 * Save user groups changes in the database.
127 * Data comes from the editUserGroupsForm() form function
128 *
129 * @param $username String: username to apply changes to.
130 * @param $reason String: reason for group change
131 * @return null
132 */
133 function saveUserGroups( $username, $reason = '') {
134 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
135
136 $user = $this->fetchUser( $username );
137 if( $user instanceof WikiErrorMsg ) {
138 $wgOut->addWikiMsgArray($user->getMessageKey(), $user->getMessageArgs());
139 return;
140 }
141
142 $allgroups = $this->getAllGroups();
143 $addgroup = array();
144 $removegroup = array();
145
146 // This could possibly create a highly unlikely race condition if permissions are changed between
147 // when the form is loaded and when the form is saved. Ignoring it for the moment.
148 foreach ($allgroups as $group) {
149 // We'll tell it to remove all unchecked groups, and add all checked groups.
150 // Later on, this gets filtered for what can actually be removed
151 if ($wgRequest->getCheck( "wpGroup-$group" )) {
152 $addgroup[] = $group;
153 } else {
154 $removegroup[] = $group;
155 }
156 }
157
158 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
159 }
160
161 /**
162 * Save user groups changes in the database.
163 *
164 * @param $user User object
165 * @param $add Array of groups to add
166 * @param $remove Array of groups to remove
167 * @param $reason String: reason for group change
168 * @return Array: Tuple of added, then removed groups
169 */
170 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
171 global $wgUser;
172
173 // Validate input set...
174 $isself = ($user->getName() == $wgUser->getName());
175 $groups = $user->getGroups();
176 $changeable = $this->changeableGroups();
177 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
178 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
179
180 $remove = array_unique(
181 array_intersect( (array)$remove, $removable, $groups ) );
182 $add = array_unique( array_diff(
183 array_intersect( (array)$add, $addable ),
184 $groups ) );
185
186 $oldGroups = $user->getGroups();
187 $newGroups = $oldGroups;
188 // remove then add groups
189 if( $remove ) {
190 $newGroups = array_diff($newGroups, $remove);
191 foreach( $remove as $group ) {
192 $user->removeGroup( $group );
193 }
194 }
195 if( $add ) {
196 $newGroups = array_merge($newGroups, $add);
197 foreach( $add as $group ) {
198 $user->addGroup( $group );
199 }
200 }
201 $newGroups = array_unique( $newGroups );
202
203 // Ensure that caches are cleared
204 $user->invalidateCache();
205
206 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
207 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
208 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
209
210 if( $newGroups != $oldGroups ) {
211 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
212 }
213 return array( $add, $remove );
214 }
215
216
217 /**
218 * Add a rights log entry for an action.
219 */
220 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
221 $log = new LogPage( 'rights' );
222
223 $log->addEntry( 'rights',
224 $user->getUserPage(),
225 $reason,
226 array(
227 $this->makeGroupNameListForLog( $oldGroups ),
228 $this->makeGroupNameListForLog( $newGroups )
229 )
230 );
231 }
232
233 /**
234 * Edit user groups membership
235 * @param $username String: name of the user.
236 */
237 function editUserGroupsForm( $username ) {
238 global $wgOut;
239
240 $user = $this->fetchUser( $username );
241 if( $user instanceof WikiErrorMsg ) {
242 $wgOut->addWikiMsgArray($user->getMessageKey(), $user->getMessageArgs());
243 return;
244 }
245
246 $groups = $user->getGroups();
247
248 $this->showEditUserGroupsForm( $user, $groups );
249
250 // This isn't really ideal logging behavior, but let's not hide the
251 // interwiki logs if we're using them as is.
252 $this->showLogFragment( $user, $wgOut );
253 }
254
255 /**
256 * Normalize the input username, which may be local or remote, and
257 * return a user (or proxy) object for manipulating it.
258 *
259 * Side effects: error output for invalid access
260 * @return mixed User, UserRightsProxy, or WikiErrorMsg
261 */
262 function fetchUser( $username ) {
263 global $wgUser, $wgUserrightsInterwikiDelimiter;
264
265 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
266 if( count( $parts ) < 2 ) {
267 $name = trim( $username );
268 $database = '';
269 } else {
270 list( $name, $database ) = array_map( 'trim', $parts );
271
272 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
273 return new WikiErrorMsg( 'userrights-no-interwiki' );
274 }
275 if( !UserRightsProxy::validDatabase( $database ) ) {
276 return new WikiErrorMsg( 'userrights-nodatabase', $database );
277 }
278 }
279
280 if( $name == '' ) {
281 return new WikiErrorMsg( 'nouserspecified' );
282 }
283
284 if( $name{0} == '#' ) {
285 // Numeric ID can be specified...
286 // We'll do a lookup for the name internally.
287 $id = intval( substr( $name, 1 ) );
288
289 if( $database == '' ) {
290 $name = User::whoIs( $id );
291 } else {
292 $name = UserRightsProxy::whoIs( $database, $id );
293 }
294
295 if( !$name ) {
296 return new WikiErrorMsg( 'noname' );
297 }
298 }
299
300 if( $database == '' ) {
301 $user = User::newFromName( $name );
302 } else {
303 $user = UserRightsProxy::newFromName( $database, $name );
304 }
305
306 if( !$user || $user->isAnon() ) {
307 return new WikiErrorMsg( 'nosuchusershort', $username );
308 }
309
310 return $user;
311 }
312
313 function makeGroupNameList( $ids ) {
314 if( empty( $ids ) ) {
315 return wfMsgForContent( 'rightsnone' );
316 } else {
317 return implode( ', ', $ids );
318 }
319 }
320
321 function makeGroupNameListForLog( $ids ) {
322 if( empty( $ids ) ) {
323 return '';
324 } else {
325 return $this->makeGroupNameList( $ids );
326 }
327 }
328
329 /**
330 * Output a form to allow searching for a user
331 */
332 function switchForm() {
333 global $wgOut, $wgScript;
334 $wgOut->addHTML(
335 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
336 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
337 Xml::openElement( 'fieldset' ) .
338 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
339 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
340 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
341 Xml::closeElement( 'fieldset' ) .
342 Xml::closeElement( 'form' ) . "\n"
343 );
344 }
345
346 /**
347 * Go through used and available groups and return the ones that this
348 * form will be able to manipulate based on the current user's system
349 * permissions.
350 *
351 * @param $groups Array: list of groups the given user is in
352 * @return Array: Tuple of addable, then removable groups
353 */
354 protected function splitGroups( $groups ) {
355 list($addable, $removable, $addself, $removeself) = array_values( $this->changeableGroups() );
356
357 $removable = array_intersect(
358 array_merge( $this->isself ? $removeself : array(), $removable ),
359 $groups ); // Can't remove groups the user doesn't have
360 $addable = array_diff(
361 array_merge( $this->isself ? $addself : array(), $addable ),
362 $groups ); // Can't add groups the user does have
363
364 return array( $addable, $removable );
365 }
366
367 /**
368 * Show the form to edit group memberships.
369 *
370 * @param $user User or UserRightsProxy you're editing
371 * @param $groups Array: Array of groups the user is in
372 */
373 protected function showEditUserGroupsForm( $user, $groups ) {
374 global $wgOut, $wgUser, $wgLang;
375
376 $list = array();
377 foreach( $groups as $group )
378 $list[] = self::buildGroupLink( $group );
379
380 $grouplist = '';
381 if( count( $list ) > 0 ) {
382 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
383 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . '</p>';
384 }
385 $wgOut->addHTML(
386 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
387 Xml::hidden( 'user', $this->mTarget ) .
388 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
389 Xml::openElement( 'fieldset' ) .
390 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
391 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
392 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
393 $grouplist .
394 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
395 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
396 "<tr>
397 <td class='mw-label'>" .
398 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
399 "</td>
400 <td class='mw-input'>" .
401 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
402 "</td>
403 </tr>
404 <tr>
405 <td></td>
406 <td class='mw-submit'>" .
407 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
408 "</td>
409 </tr>" .
410 Xml::closeElement( 'table' ) . "\n" .
411 Xml::closeElement( 'fieldset' ) .
412 Xml::closeElement( 'form' ) . "\n"
413 );
414 }
415
416 /**
417 * Format a link to a group description page
418 *
419 * @param $group string
420 * @return string
421 */
422 private static function buildGroupLink( $group ) {
423 static $cache = array();
424 if( !isset( $cache[$group] ) )
425 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
426 return $cache[$group];
427 }
428
429 /**
430 * Returns an array of all groups that may be edited
431 * @return array Array of groups that may be edited.
432 */
433 protected static function getAllGroups() {
434 return User::getAllGroups();
435 }
436
437 /**
438 * Adds a table with checkboxes where you can select what groups to add/remove
439 *
440 * @param $usergroups Array: groups the user belongs to
441 * @return string XHTML table element with checkboxes
442 */
443 private function groupCheckboxes( $usergroups ) {
444 $allgroups = $this->getAllGroups();
445 $ret = '';
446
447 $column = 1;
448 $settable_col = '';
449 $unsettable_col = '';
450
451 foreach ($allgroups as $group) {
452 $set = in_array( $group, $usergroups );
453 # Should the checkbox be disabled?
454 $disabled = !(
455 ( $set && $this->canRemove( $group ) ) ||
456 ( !$set && $this->canAdd( $group ) ) );
457 # Do we need to point out that this action is irreversible?
458 $irreversible = !$disabled && (
459 ($set && !$this->canAdd( $group )) ||
460 (!$set && !$this->canRemove( $group ) ) );
461
462 $attr = $disabled ? array( 'disabled' => 'disabled' ) : array();
463 $text = $irreversible
464 ? wfMsgHtml( 'userrights-irreversible-marker', User::getGroupMember( $group ) )
465 : User::getGroupMember( $group );
466 $checkbox = Xml::checkLabel( $text, "wpGroup-$group",
467 "wpGroup-$group", $set, $attr );
468 $checkbox = $disabled ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkbox ) : $checkbox;
469
470 if ($disabled) {
471 $unsettable_col .= "$checkbox<br />\n";
472 } else {
473 $settable_col .= "$checkbox<br />\n";
474 }
475 }
476
477 if ($column) {
478 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
479 "<tr>
480 ";
481 if( $settable_col !== '' ) {
482 $ret .= xml::element( 'th', null, wfMsg( 'userrights-changeable-col' ) );
483 }
484 if( $unsettable_col !== '' ) {
485 $ret .= xml::element( 'th', null, wfMsg( 'userrights-unchangeable-col' ) );
486 }
487 $ret.= "</tr>
488 <tr>
489 ";
490 if( $settable_col !== '' ) {
491 $ret .=
492 " <td style='vertical-align:top;'>
493 $settable_col
494 </td>
495 ";
496 }
497 if( $unsettable_col !== '' ) {
498 $ret .=
499 " <td style='vertical-align:top;'>
500 $unsettable_col
501 </td>
502 ";
503 }
504 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
505 }
506
507 return $ret;
508 }
509
510 /**
511 * @param $group String: the name of the group to check
512 * @return bool Can we remove the group?
513 */
514 private function canRemove( $group ) {
515 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
516 // PHP.
517 $groups = $this->changeableGroups();
518 return in_array( $group, $groups['remove'] ) || ($this->isself && in_array( $group, $groups['remove-self'] ));
519 }
520
521 /**
522 * @param $group string: the name of the group to check
523 * @return bool Can we add the group?
524 */
525 private function canAdd( $group ) {
526 $groups = $this->changeableGroups();
527 return in_array( $group, $groups['add'] ) || ($this->isself && in_array( $group, $groups['add-self'] ));
528 }
529
530 /**
531 * Returns $wgUser->changeableGroups()
532 *
533 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
534 */
535 function changeableGroups() {
536 global $wgUser;
537 $groups = $wgUser->changeableGroups();
538 // Run a hook because we can
539 wfRunHooks( 'UserrightsChangeableGroups', array( $this,
540 $wgUser, $wgUser->getEffectiveGroups(), &$groups ) );
541 return $groups;
542 }
543
544 /**
545 * Show a rights log fragment for the specified user
546 *
547 * @param $user User to show log for
548 * @param $output OutputPage to use
549 */
550 protected function showLogFragment( $user, $output ) {
551 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
552 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
553 }
554 }