eol ws cleanup
[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 !== null ) {
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 $available = $this->changeableGroups();
69
70 if ( $this->mTarget === null ) {
71 /*
72 * If the user specified no target, and they can only
73 * edit their own groups, automatically set them as the
74 * target.
75 */
76 if ( !count( $available['add'] ) && !count( $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 $wgOut->showPermissionsErrorPage( array( array(
86 $wgUser->isAnon()
87 ? 'userrights-nologin'
88 : 'userrights-notallowed' ) ) );
89 return;
90 }
91
92 if ( wfReadOnly() ) {
93 $wgOut->readOnlyPage();
94 return;
95 }
96
97 $this->outputHeader();
98
99 $this->setHeaders();
100
101 // show the general form
102 if ( count( $available['add'] ) || count( $available['remove'] ) )
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 $url = $this->getSuccessURL();
117 $wgOut->redirect( $url );
118 return;
119 }
120 }
121 }
122
123 // show some more forms
124 if( $this->mTarget !== null ) {
125 $this->editUserGroupsForm( $this->mTarget );
126 }
127 }
128
129 function getSuccessURL() {
130 return $this->getTitle( $this->mTarget )->getFullURL();
131 }
132
133 /**
134 * Save user groups changes in the database.
135 * Data comes from the editUserGroupsForm() form function
136 *
137 * @param $username String: username to apply changes to.
138 * @param $reason String: reason for group change
139 * @return null
140 */
141 function saveUserGroups( $username, $reason = '' ) {
142 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
143
144 $status = $this->fetchUser( $username );
145 if( !$status->isOK() ) {
146 $wgOut->addWikiText( $status->getWikiText() );
147 return;
148 } else {
149 $user = $status->value;
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 $status = $this->fetchUser( $username );
253 if( !$status->isOK() ) {
254 $wgOut->addWikiText( $status->getWikiText() );
255 return;
256 } else {
257 $user = $status->value;
258 }
259
260 $groups = $user->getGroups();
261
262 $this->showEditUserGroupsForm( $user, $groups );
263
264 // This isn't really ideal logging behavior, but let's not hide the
265 // interwiki logs if we're using them as is.
266 $this->showLogFragment( $user, $wgOut );
267 }
268
269 /**
270 * Normalize the input username, which may be local or remote, and
271 * return a user (or proxy) object for manipulating it.
272 *
273 * Side effects: error output for invalid access
274 * @return Status object
275 */
276 public function fetchUser( $username ) {
277 global $wgUser, $wgUserrightsInterwikiDelimiter;
278
279 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
280 if( count( $parts ) < 2 ) {
281 $name = trim( $username );
282 $database = '';
283 } else {
284 list( $name, $database ) = array_map( 'trim', $parts );
285
286 if( $database == wfWikiID() ) {
287 $database = '';
288 } else {
289 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
290 return Status::newFatal( 'userrights-no-interwiki' );
291 }
292 if( !UserRightsProxy::validDatabase( $database ) ) {
293 return Status::newFatal( 'userrights-nodatabase', $database );
294 }
295 }
296 }
297
298 if( $name === '' ) {
299 return Status::newFatal( 'nouserspecified' );
300 }
301
302 if( $name{0} == '#' ) {
303 // Numeric ID can be specified...
304 // We'll do a lookup for the name internally.
305 $id = intval( substr( $name, 1 ) );
306
307 if( $database == '' ) {
308 $name = User::whoIs( $id );
309 } else {
310 $name = UserRightsProxy::whoIs( $database, $id );
311 }
312
313 if( !$name ) {
314 return Status::newFatal( 'noname' );
315 }
316 } else {
317 $name = User::getCanonicalName( $name );
318 if( $name === false ) {
319 // invalid name
320 return Status::newFatal( 'nosuchusershort', $username );
321 }
322 }
323
324 if( $database == '' ) {
325 $user = User::newFromName( $name );
326 } else {
327 $user = UserRightsProxy::newFromName( $database, $name );
328 }
329
330 if( !$user || $user->isAnon() ) {
331 return Status::newFatal( 'nosuchusershort', $username );
332 }
333
334 return Status::newGood( $user );
335 }
336
337 function makeGroupNameList( $ids ) {
338 if( empty( $ids ) ) {
339 return wfMsgForContent( 'rightsnone' );
340 } else {
341 return implode( ', ', $ids );
342 }
343 }
344
345 function makeGroupNameListForLog( $ids ) {
346 if( empty( $ids ) ) {
347 return '';
348 } else {
349 return $this->makeGroupNameList( $ids );
350 }
351 }
352
353 /**
354 * Output a form to allow searching for a user
355 */
356 function switchForm() {
357 global $wgOut, $wgScript;
358 $wgOut->addHTML(
359 Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
360 Xml::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
361 Xml::openElement( 'fieldset' ) .
362 Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
363 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
364 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
365 Xml::closeElement( 'fieldset' ) .
366 Xml::closeElement( 'form' ) . "\n"
367 );
368 }
369
370 /**
371 * Go through used and available groups and return the ones that this
372 * form will be able to manipulate based on the current user's system
373 * permissions.
374 *
375 * @param $groups Array: list of groups the given user is in
376 * @return Array: Tuple of addable, then removable groups
377 */
378 protected function splitGroups( $groups ) {
379 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
380
381 $removable = array_intersect(
382 array_merge( $this->isself ? $removeself : array(), $removable ),
383 $groups
384 ); // Can't remove groups the user doesn't have
385 $addable = array_diff(
386 array_merge( $this->isself ? $addself : array(), $addable ),
387 $groups
388 ); // Can't add groups the user does have
389
390 return array( $addable, $removable );
391 }
392
393 /**
394 * Show the form to edit group memberships.
395 *
396 * @param $user User or UserRightsProxy you're editing
397 * @param $groups Array: Array of groups the user is in
398 */
399 protected function showEditUserGroupsForm( $user, $groups ) {
400 global $wgOut, $wgUser, $wgLang;
401
402 $list = array();
403 foreach( $groups as $group )
404 $list[] = self::buildGroupLink( $group );
405
406 $autolist = array();
407 if ( $user instanceof User ) {
408 foreach( Autopromote::getAutopromoteGroups( $user ) as $group ) {
409 $autolist[] = self::buildGroupLink( $group );
410 }
411 }
412
413 $grouplist = '';
414 if( count( $list ) > 0 ) {
415 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
416 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . "</p>\n";
417 }
418 if( count( $autolist ) > 0 ) {
419 $autogrouplistintro = wfMsgHtml( 'userrights-groupsmember-auto' );
420 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $wgLang->listToText( $autolist ) . "</p>\n";
421 }
422 $wgOut->addHTML(
423 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
424 Xml::hidden( 'user', $this->mTarget ) .
425 Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
426 Xml::openElement( 'fieldset' ) .
427 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
428 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
429 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
430 $grouplist .
431 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
432 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
433 "<tr>
434 <td class='mw-label'>" .
435 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
436 "</td>
437 <td class='mw-input'>" .
438 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
439 "</td>
440 </tr>
441 <tr>
442 <td></td>
443 <td class='mw-submit'>" .
444 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
445 "</td>
446 </tr>" .
447 Xml::closeElement( 'table' ) . "\n" .
448 Xml::closeElement( 'fieldset' ) .
449 Xml::closeElement( 'form' ) . "\n"
450 );
451 }
452
453 /**
454 * Format a link to a group description page
455 *
456 * @param $group string
457 * @return string
458 */
459 private static function buildGroupLink( $group ) {
460 static $cache = array();
461 if( !isset( $cache[$group] ) )
462 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
463 return $cache[$group];
464 }
465
466 /**
467 * Returns an array of all groups that may be edited
468 * @return array Array of groups that may be edited.
469 */
470 protected static function getAllGroups() {
471 return User::getAllGroups();
472 }
473
474 /**
475 * Adds a table with checkboxes where you can select what groups to add/remove
476 *
477 * @param $usergroups Array: groups the user belongs to
478 * @return string XHTML table element with checkboxes
479 */
480 private function groupCheckboxes( $usergroups ) {
481 $allgroups = $this->getAllGroups();
482 $ret = '';
483
484 # Put all column info into an associative array so that extensions can
485 # more easily manage it.
486 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
487
488 foreach( $allgroups as $group ) {
489 $set = in_array( $group, $usergroups );
490 # Should the checkbox be disabled?
491 $disabled = !(
492 ( $set && $this->canRemove( $group ) ) ||
493 ( !$set && $this->canAdd( $group ) ) );
494 # Do we need to point out that this action is irreversible?
495 $irreversible = !$disabled && (
496 ( $set && !$this->canAdd( $group ) ) ||
497 ( !$set && !$this->canRemove( $group ) ) );
498
499 $checkbox = array(
500 'set' => $set,
501 'disabled' => $disabled,
502 'irreversible' => $irreversible
503 );
504
505 if( $disabled ) {
506 $columns['unchangeable'][$group] = $checkbox;
507 } else {
508 $columns['changeable'][$group] = $checkbox;
509 }
510 }
511
512 # Build the HTML table
513 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
514 "<tr>\n";
515 foreach( $columns as $name => $column ) {
516 if( $column === array() )
517 continue;
518 $ret .= xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
519 }
520 $ret.= "</tr>\n<tr>\n";
521 foreach( $columns as $column ) {
522 if( $column === array() )
523 continue;
524 $ret .= "\t<td style='vertical-align:top;'>\n";
525 foreach( $column as $group => $checkbox ) {
526 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
527
528 if ( $checkbox['irreversible'] ) {
529 $text = htmlspecialchars( wfMsg( 'userrights-irreversible-marker',
530 User::getGroupMember( $group ) ) );
531 } else {
532 $text = htmlspecialchars( User::getGroupMember( $group ) );
533 }
534 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
535 "wpGroup-" . $group, $checkbox['set'], $attr );
536 $ret .= "\t\t" . ( $checkbox['disabled']
537 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
538 : $checkboxHtml
539 ) . "<br />\n";
540 }
541 $ret .= "\t</td>\n";
542 }
543 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
544
545 return $ret;
546 }
547
548 /**
549 * @param $group String: the name of the group to check
550 * @return bool Can we remove the group?
551 */
552 private function canRemove( $group ) {
553 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
554 // PHP.
555 $groups = $this->changeableGroups();
556 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
557 }
558
559 /**
560 * @param $group string: the name of the group to check
561 * @return bool Can we add the group?
562 */
563 private function canAdd( $group ) {
564 $groups = $this->changeableGroups();
565 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
566 }
567
568 /**
569 * Returns $wgUser->changeableGroups()
570 *
571 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
572 */
573 function changeableGroups() {
574 global $wgUser;
575 return $wgUser->changeableGroups();
576 }
577
578 /**
579 * Show a rights log fragment for the specified user
580 *
581 * @param $user User to show log for
582 * @param $output OutputPage to use
583 */
584 protected function showLogFragment( $user, $output ) {
585 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
586 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
587 }
588 }