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