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