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