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