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