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