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