More userrights stuff.
[lhc/web/wiklou.git] / includes / SpecialUserrights.php
1 <?php
2
3 /**
4 * Special page to allow managing user group membership
5 *
6 * @addtogroup SpecialPage
7 * @todo Use checkboxes or something, this list thing is incomprehensible to
8 * normal human beings.
9 */
10
11 /**
12 * A class to manage user levels rights.
13 * @addtogroup SpecialPage
14 */
15 class UserrightsPage extends SpecialPage {
16 # The target of the local right-adjuster's interest. Can be gotten from
17 # either a GET parameter or a subpage-style parameter, so have a member
18 # variable for it.
19 protected $mTarget;
20
21 public function __construct() {
22 parent::__construct( 'Userrights' );
23 }
24
25 public function isRestricted() {
26 return true;
27 }
28
29 public function userCanExecute( $user ) {
30 $available = $this->changeableGroups();
31 return !empty( $available['add'] ) or !empty( $available['remove'] );
32 }
33
34 /**
35 * Manage forms to be shown according to posted data.
36 * Depending on the submit button used, call a form or a save function.
37 *
38 * @param mixed $par String if any subpage provided, else null
39 */
40 function execute( $par ) {
41 // If the visitor doesn't have permissions to assign or remove
42 // any groups, it's a bit silly to give them the user search prompt.
43 global $wgUser;
44 if( !$this->userCanExecute( $wgUser ) ) {
45 // fixme... there may be intermediate groups we can mention.
46 global $wgOut;
47 $wgOut->showPermissionsErrorPage( array(
48 $wgUser->isAnon()
49 ? 'userrights-nologin'
50 : 'userrights-notallowed' ) );
51 return;
52 }
53
54 global $wgRequest;
55 if( $par ) {
56 $this->mTarget = $par;
57 } else {
58 $this->mTarget = $wgRequest->getVal( 'user' );
59 }
60
61 $this->setHeaders();
62
63 // show the general form
64 $this->switchForm();
65
66 if( $wgRequest->wasPosted() ) {
67 // save settings
68 if( $wgRequest->getCheck( 'saveusergroups' ) ) {
69 $reason = $wgRequest->getVal( 'user-reason' );
70 if( $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ), $this->mTarget ) ) {
71 $this->saveUserGroups(
72 $this->mTarget,
73 $wgRequest->getArray( 'removable' ),
74 $wgRequest->getArray( 'available' ),
75 $reason
76 );
77 }
78 }
79 }
80
81 // show some more forms
82 if( $this->mTarget ) {
83 $this->editUserGroupsForm( $this->mTarget );
84 }
85 }
86
87 /**
88 * Save user groups changes in the database.
89 * Data comes from the editUserGroupsForm() form function
90 *
91 * @param string $username Username to apply changes to.
92 * @param array $removegroup id of groups to be removed.
93 * @param array $addgroup id of groups to be added.
94 * @param string $reason Reason for group change
95 * @return null
96 */
97 function saveUserGroups( $username, $removegroup, $addgroup, $reason = '') {
98 $user = $this->fetchUser( $username );
99 if( !$user ) {
100 return;
101 }
102
103 // Validate input set...
104 $changeable = $this->changeableGroups();
105 $removegroup = array_unique(
106 array_intersect( (array)$removegroup, $changeable['remove'] ) );
107 $addgroup = array_unique(
108 array_intersect( (array)$addgroup, $changeable['add'] ) );
109
110 $oldGroups = $user->getGroups();
111 $newGroups = $oldGroups;
112 // remove then add groups
113 if( $removegroup ) {
114 $newGroups = array_diff($newGroups, $removegroup);
115 foreach( $removegroup as $group ) {
116 $user->removeGroup( $group );
117 }
118 }
119 if( $addgroup ) {
120 $newGroups = array_merge($newGroups, $addgroup);
121 foreach( $addgroup as $group ) {
122 $user->addGroup( $group );
123 }
124 }
125 $newGroups = array_unique( $newGroups );
126
127 // Ensure that caches are cleared
128 $user->invalidateCache();
129
130 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
131 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
132 if( $user instanceof User ) {
133 // hmmm
134 wfRunHooks( 'UserRights', array( &$user, $addgroup, $removegroup ) );
135 }
136
137 $log = new LogPage( 'rights' );
138
139 global $wgRequest;
140 $log->addEntry( 'rights',
141 $user->getUserPage(),
142 $wgRequest->getText( 'user-reason' ),
143 array(
144 $this->makeGroupNameList( $oldGroups ),
145 $this->makeGroupNameList( $newGroups )
146 )
147 );
148 }
149
150 /**
151 * Edit user groups membership
152 * @param string $username Name of the user.
153 */
154 function editUserGroupsForm( $username ) {
155 global $wgOut;
156
157 $user = $this->fetchUser( $username );
158 if( !$user ) {
159 return;
160 }
161
162 $groups = $user->getGroups();
163
164 $this->showEditUserGroupsForm( $user, $groups );
165
166 // This isn't really ideal logging behavior, but let's not hide the
167 // interwiki logs if we're using them as is.
168 $this->showLogFragment( $user, $wgOut );
169 }
170
171 /**
172 * Normalize the input username, which may be local or remote, and
173 * return a user (or proxy) object for manipulating it.
174 *
175 * Side effects: error output for invalid access
176 * @return mixed User, UserRightsProxy, or null
177 */
178 function fetchUser( $username ) {
179 global $wgOut, $wgUser;
180
181 $parts = explode( '@', $username );
182 if( count( $parts ) < 2 ) {
183 $name = trim( $username );
184 $database = '';
185 } else {
186 list( $name, $database ) = array_map( 'trim', $parts );
187
188 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
189 $wgOut->addWikiText( wfMsg( 'userrights-no-interwiki' ) );
190 return null;
191 }
192 if( !UserRightsProxy::validDatabase( $database ) ) {
193 $wgOut->addWikiText( wfMsg( 'userrights-nodatabase', $database ) );
194 return null;
195 }
196 }
197
198 if( $name == '' ) {
199 $wgOut->addWikiText( wfMsg( 'nouserspecified' ) );
200 return false;
201 }
202
203 if( $name{0} == '#' ) {
204 // Numeric ID can be specified...
205 // We'll do a lookup for the name internally.
206 $id = intval( substr( $name, 1 ) );
207
208 if( $database == '' ) {
209 $name = User::whoIs( $id );
210 } else {
211 $name = UserRightsProxy::whoIs( $database, $id );
212 }
213
214 if( !$name ) {
215 $wgOut->addWikiText( wfMsg( 'noname' ) );
216 return null;
217 }
218 }
219
220 if( $database == '' ) {
221 $user = User::newFromName( $name );
222 } else {
223 $user = UserRightsProxy::newFromName( $database, $name );
224 }
225
226 if( !$user || $user->isAnon() ) {
227 $wgOut->addWikiText( wfMsg( 'nosuchusershort', wfEscapeWikiText( $username ) ) );
228 return null;
229 }
230
231 return $user;
232 }
233
234 function makeGroupNameList( $ids ) {
235 return implode( ', ', $ids );
236 }
237
238 /**
239 * Output a form to allow searching for a user
240 */
241 function switchForm() {
242 global $wgOut;
243 $form = Xml::openElement( 'form', array( 'method' => 'get', 'action' => $this->getTitle()->escapeLocalURL(), 'name' => 'uluser' ) );
244 $form .= '<fieldset><legend>' . wfMsgHtml( 'userrights-lookup-user' ) . '</legend>';
245 $form .= '<p>' . Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . '</p>';
246 $form .= '<p>' . Xml::submitButton( wfMsg( 'editusergroup' ) ) . '</p>';
247 $form .= '</fieldset>';
248 $form .= '</form>';
249 $wgOut->addHTML( $form );
250 }
251
252 /**
253 * Go through used and available groups and return the ones that this
254 * form will be able to manipulate based on the current user's system
255 * permissions.
256 *
257 * @param $groups Array: list of groups the given user is in
258 * @return Array: Tuple of addable, then removable groups
259 */
260 protected function splitGroups( $groups ) {
261 list($addable, $removable) = array_values( $this->changeableGroups() );
262 $removable = array_intersect($removable, $groups ); // Can't remove groups the user doesn't have
263 $addable = array_diff( $addable, $groups ); // Can't add groups the user does have
264
265 return array( $addable, $removable );
266 }
267
268 /**
269 * Show the form to edit group memberships.
270 *
271 * @todo make all CSS-y and semantic
272 * @param $user User or UserRightsProxy you're editing
273 * @param $groups Array: Array of groups the user is in
274 */
275 protected function showEditUserGroupsForm( $user, $groups ) {
276 global $wgOut, $wgUser;
277
278 list( $addable, $removable ) = $this->splitGroups( $groups );
279
280 $list = array();
281 foreach( $user->getGroups() as $group )
282 $list[] = self::buildGroupLink( $group );
283
284 $grouplist = '';
285 if( count( $list ) > 0 ) {
286 $grouplist = '<p>' . wfMsgHtml( 'userrights-groupsmember' ) . ' ' . implode( ', ', $list ) . '</p>';
287 }
288 $wgOut->addHTML(
289 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->escapeLocalURL(), 'name' => 'editGroup' ) ) .
290 Xml::hidden( 'user', $user->getName() ) .
291 Xml::hidden( 'wpEditToken', $wgUser->editToken( $user->getName() ) ) .
292 Xml::openElement( 'fieldset' ) .
293 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
294 wfMsgExt( 'editinguser', array( 'parse' ),
295 wfEscapeWikiText( $user->getName() ) ) .
296 $grouplist .
297 $this->explainRights() .
298 "<table border='0'>
299 <tr>
300 <td></td>
301 <td>
302 <table width='400'>
303 <tr>
304 <td width='50%'>" . $this->removeSelect( $removable ) . "</td>
305 <td width='50%'>" . $this->addSelect( $addable ) . "</td>
306 </tr>
307 </table>
308 </tr>
309 <tr>
310 <td colspan='2'>" .
311 $wgOut->parse( wfMsg('userrights-groupshelp') ) .
312 "</td>
313 </tr>
314 <tr>
315 <td>" .
316 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
317 "</td>
318 <td>" .
319 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
320 "</td>
321 </tr>
322 <tr>
323 <td></td>
324 <td>" .
325 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups' ) ) .
326 "</td>
327 </tr>
328 </table>\n" .
329 Xml::closeElement( 'fieldset' ) .
330 Xml::closeElement( 'form' ) . "\n"
331 );
332 }
333
334 /**
335 * Format a link to a group description page
336 *
337 * @param string $group
338 * @return string
339 */
340 private static function buildGroupLink( $group ) {
341 static $cache = array();
342 if( !isset( $cache[$group] ) )
343 $cache[$group] = User::makeGroupLinkHtml( $group, User::getGroupMember( $group ) );
344 return $cache[$group];
345 }
346
347 /**
348 * Prepare a list of groups the user is able to add and remove
349 *
350 * @return string
351 */
352 private function explainRights() {
353 global $wgUser, $wgLang;
354
355 $out = array();
356 list( $add, $remove ) = array_values( $this->changeableGroups() );
357
358 if( count( $add ) > 0 )
359 $out[] = wfMsgExt( 'userrights-available-add', 'parseinline', $wgLang->listToText( $add ), count( $add ) );
360 if( count( $remove ) > 0 )
361 $out[] = wfMsgExt( 'userrights-available-remove', 'parseinline', $wgLang->listToText( $remove ), count( $add ) );
362
363 return count( $out ) > 0
364 ? implode( '<br />', $out )
365 : wfMsgExt( 'userrights-available-none', 'parseinline' );
366 }
367
368 /**
369 * Adds the <select> thingie where you can select what groups to remove
370 *
371 * @param array $groups The groups that can be removed
372 * @return string XHTML <select> element
373 */
374 private function removeSelect( $groups ) {
375 return $this->doSelect( $groups, 'removable' );
376 }
377
378 /**
379 * Adds the <select> thingie where you can select what groups to add
380 *
381 * @param array $groups The groups that can be added
382 * @return string XHTML <select> element
383 */
384 private function addSelect( $groups ) {
385 return $this->doSelect( $groups, 'available' );
386 }
387
388 /**
389 * Adds the <select> thingie where you can select what groups to add/remove
390 *
391 * @param array $groups The groups that can be added/removed
392 * @param string $name 'removable' or 'available'
393 * @return string XHTML <select> element
394 */
395 private function doSelect( $groups, $name ) {
396 $ret = wfMsgHtml( "{$this->mName}-groups$name" ) .
397 Xml::openElement( 'select', array(
398 'name' => "{$name}[]",
399 'multiple' => 'multiple',
400 'size' => '6',
401 'style' => 'width: 100%;'
402 )
403 );
404 foreach ($groups as $group) {
405 $ret .= Xml::element( 'option', array( 'value' => $group ), User::getGroupName( $group ) );
406 }
407 $ret .= Xml::closeElement( 'select' );
408 return $ret;
409 }
410
411 /**
412 * @param string $group The name of the group to check
413 * @return bool Can we remove the group?
414 */
415 private function canRemove( $group ) {
416 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
417 // PHP.
418 $groups = $this->changeableGroups();
419 return in_array( $group, $groups['remove'] );
420 }
421
422 /**
423 * @param string $group The name of the group to check
424 * @return bool Can we add the group?
425 */
426 private function canAdd( $group ) {
427 $groups = $this->changeableGroups();
428 return in_array( $group, $groups['add'] );
429 }
430
431 /**
432 * Returns an array of the groups that the user can add/remove.
433 *
434 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) )
435 */
436 function changeableGroups() {
437 global $wgUser;
438
439 if( $wgUser->isAllowed( 'userrights' ) ) {
440 // This group gives the right to modify everything (reverse-
441 // compatibility with old "userrights lets you change
442 // everything")
443 // Using array_merge to make the groups reindexed
444 $all = array_merge( User::getAllGroups() );
445 return array(
446 'add' => $all,
447 'remove' => $all
448 );
449 }
450
451 // Okay, it's not so simple, we will have to go through the arrays
452 $groups = array( 'add' => array(), 'remove' => array() );
453 $addergroups = $wgUser->getEffectiveGroups();
454
455 foreach ($addergroups as $addergroup) {
456 $groups = array_merge_recursive(
457 $groups, $this->changeableByGroup($addergroup)
458 );
459 $groups['add'] = array_unique( $groups['add'] );
460 $groups['remove'] = array_unique( $groups['remove'] );
461 }
462 return $groups;
463 }
464
465 /**
466 * Returns an array of the groups that a particular group can add/remove.
467 *
468 * @param String $group The group to check for whether it can add/remove
469 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) )
470 */
471 private function changeableByGroup( $group ) {
472 global $wgAddGroups, $wgRemoveGroups;
473
474 $groups = array( 'add' => array(), 'remove' => array() );
475 if( empty($wgAddGroups[$group]) ) {
476 // Don't add anything to $groups
477 } elseif( $wgAddGroups[$group] === true ) {
478 // You get everything
479 $groups['add'] = User::getAllGroups();
480 } elseif( is_array($wgAddGroups[$group]) ) {
481 $groups['add'] = $wgAddGroups[$group];
482 }
483
484 // Same thing for remove
485 if( empty($wgRemoveGroups[$group]) ) {
486 } elseif($wgRemoveGroups[$group] === true ) {
487 $groups['remove'] = User::getAllGroups();
488 } elseif( is_array($wgRemoveGroups[$group]) ) {
489 $groups['remove'] = $wgRemoveGroups[$group];
490 }
491 return $groups;
492 }
493
494 /**
495 * Show a rights log fragment for the specified user
496 *
497 * @param User $user User to show log for
498 * @param OutputPage $output OutputPage to use
499 */
500 protected function showLogFragment( $user, $output ) {
501 $viewer = new LogViewer(
502 new LogReader(
503 new FauxRequest(
504 array(
505 'type' => 'rights',
506 'page' => $user->getUserPage()->getPrefixedText(),
507 )
508 )
509 )
510 );
511 $output->addHtml( "<h2>" . htmlspecialchars( LogPage::logName( 'rights' ) ) . "</h2>\n" );
512 $viewer->showList( $output );
513 }
514
515 }