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