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