fix typo in comment
[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 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;
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
197 $oldGroups = $user->getGroups();
198 $newGroups = $oldGroups;
199
200 // remove then add groups
201 if( $remove ) {
202 $newGroups = array_diff( $newGroups, $remove );
203 foreach( $remove as $group ) {
204 $user->removeGroup( $group );
205 }
206 }
207 if( $add ) {
208 $newGroups = array_merge( $newGroups, $add );
209 foreach( $add as $group ) {
210 $user->addGroup( $group );
211 }
212 }
213 $newGroups = array_unique( $newGroups );
214
215 // Ensure that caches are cleared
216 $user->invalidateCache();
217
218 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
219 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
220 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
221
222 if( $newGroups != $oldGroups ) {
223 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
224 }
225 return array( $add, $remove );
226 }
227
228
229 /**
230 * Add a rights log entry for an action.
231 */
232 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
233 $log = new LogPage( 'rights' );
234
235 $log->addEntry( 'rights',
236 $user->getUserPage(),
237 $reason,
238 array(
239 $this->makeGroupNameListForLog( $oldGroups ),
240 $this->makeGroupNameListForLog( $newGroups )
241 )
242 );
243 }
244
245 /**
246 * Edit user groups membership
247 * @param $username String: name of the user.
248 */
249 function editUserGroupsForm( $username ) {
250 global $wgOut;
251
252 $user = $this->fetchUser( $username );
253 if( $user instanceof WikiErrorMsg ) {
254 $wgOut->addWikiMsgArray( $user->getMessageKey(), $user->getMessageArgs() );
255 return;
256 }
257
258 $groups = $user->getGroups();
259
260 $this->showEditUserGroupsForm( $user, $groups );
261
262 // This isn't really ideal logging behavior, but let's not hide the
263 // interwiki logs if we're using them as is.
264 $this->showLogFragment( $user, $wgOut );
265 }
266
267 /**
268 * Normalize the input username, which may be local or remote, and
269 * return a user (or proxy) object for manipulating it.
270 *
271 * Side effects: error output for invalid access
272 * @return mixed User, UserRightsProxy, or WikiErrorMsg
273 */
274 function fetchUser( $username ) {
275 global $wgUser, $wgUserrightsInterwikiDelimiter;
276
277 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
278 if( count( $parts ) < 2 ) {
279 $name = trim( $username );
280 $database = '';
281 } else {
282 list( $name, $database ) = array_map( 'trim', $parts );
283
284 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
285 return new WikiErrorMsg( 'userrights-no-interwiki' );
286 }
287 if( !UserRightsProxy::validDatabase( $database ) ) {
288 return new WikiErrorMsg( 'userrights-nodatabase', $database );
289 }
290 }
291
292 if( $name == '' ) {
293 return new WikiErrorMsg( 'nouserspecified' );
294 }
295
296 if( $name{0} == '#' ) {
297 // Numeric ID can be specified...
298 // We'll do a lookup for the name internally.
299 $id = intval( substr( $name, 1 ) );
300
301 if( $database == '' ) {
302 $name = User::whoIs( $id );
303 } else {
304 $name = UserRightsProxy::whoIs( $database, $id );
305 }
306
307 if( !$name ) {
308 return new WikiErrorMsg( 'noname' );
309 }
310 }
311
312 if( $database == '' ) {
313 $user = User::newFromName( $name );
314 } else {
315 $user = UserRightsProxy::newFromName( $database, $name );
316 }
317
318 if( !$user || $user->isAnon() ) {
319 return new WikiErrorMsg( 'nosuchusershort', $username );
320 }
321
322 return $user;
323 }
324
325 function makeGroupNameList( $ids ) {
326 if( empty( $ids ) ) {
327 return wfMsgForContent( 'rightsnone' );
328 } else {
329 return implode( ', ', $ids );
330 }
331 }
332
333 function makeGroupNameListForLog( $ids ) {
334 if( empty( $ids ) ) {
335 return '';
336 } else {
337 return $this->makeGroupNameList( $ids );
338 }
339 }
340
341 /**
342 * Output a form to allow searching for a user
343 */
344 function switchForm() {
345 global $wgOut, $wgScript;
346 $wgOut->addHTML(
347 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
348 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
349 Xml::openElement( 'fieldset' ) .
350 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
351 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
352 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
353 Xml::closeElement( 'fieldset' ) .
354 Xml::closeElement( 'form' ) . "\n"
355 );
356 }
357
358 /**
359 * Go through used and available groups and return the ones that this
360 * form will be able to manipulate based on the current user's system
361 * permissions.
362 *
363 * @param $groups Array: list of groups the given user is in
364 * @return Array: Tuple of addable, then removable groups
365 */
366 protected function splitGroups( $groups ) {
367 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
368
369 $removable = array_intersect(
370 array_merge( $this->isself ? $removeself : array(), $removable ),
371 $groups
372 ); // Can't remove groups the user doesn't have
373 $addable = array_diff(
374 array_merge( $this->isself ? $addself : array(), $addable ),
375 $groups
376 ); // 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 # Build the HTML table
490 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
491 "<tr>\n";
492 foreach( $columns as $name => $column ) {
493 if( $column === array() )
494 continue;
495 $ret .= xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
496 }
497 $ret.= "</tr>\n<tr>\n";
498 foreach( $columns as $column ) {
499 if( $column === array() )
500 continue;
501 $ret .= "\t<td style='vertical-align:top;'>\n";
502 foreach( $column as $group => $checkbox ) {
503 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
504
505 if ( $checkbox['irreversible'] ) {
506 $text = htmlspecialchars( wfMsg( 'userrights-irreversible-marker',
507 User::getGroupMember( $group ) ) );
508 } else {
509 $text = htmlspecialchars( User::getGroupMember( $group ) );
510 }
511 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
512 "wpGroup-" . $group, $checkbox['set'], $attr );
513 $ret .= "\t\t" . ( $checkbox['disabled']
514 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
515 : $checkboxHtml
516 ) . "<br />\n";
517 }
518 $ret .= "\t</td>\n";
519 }
520 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
521
522 return $ret;
523 }
524
525 /**
526 * @param $group String: the name of the group to check
527 * @return bool Can we remove the group?
528 */
529 private function canRemove( $group ) {
530 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
531 // PHP.
532 $groups = $this->changeableGroups();
533 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
534 }
535
536 /**
537 * @param $group string: the name of the group to check
538 * @return bool Can we add the group?
539 */
540 private function canAdd( $group ) {
541 $groups = $this->changeableGroups();
542 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
543 }
544
545 /**
546 * Returns $wgUser->changeableGroups()
547 *
548 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
549 */
550 function changeableGroups() {
551 global $wgUser;
552 return $wgUser->changeableGroups();
553 }
554
555 /**
556 * Show a rights log fragment for the specified user
557 *
558 * @param $user User to show log for
559 * @param $output OutputPage to use
560 */
561 protected function showLogFragment( $user, $output ) {
562 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
563 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
564 }
565 }