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