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