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