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