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