Part of bug 31503 - Allow gender distinction also for user groups
[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 $out = $this->getOutput();
103
104 if( !$this->userCanChangeRights( $user, true ) ) {
105 // @todo FIXME: There may be intermediate groups we can mention.
106 $out->showPermissionsErrorPage( array( array(
107 $user->isAnon()
108 ? 'userrights-nologin'
109 : 'userrights-notallowed' ) ) );
110 return;
111 }
112
113 if ( wfReadOnly() ) {
114 throw new ReadOnlyError;
115 }
116
117 $this->outputHeader();
118 $out->addModuleStyles( 'mediawiki.special' );
119 $this->setHeaders();
120
121 // show the general form
122 if ( count( $available['add'] ) || count( $available['remove'] ) ) {
123 $this->switchForm();
124 }
125
126 if( $request->wasPosted() ) {
127 // save settings
128 if( $request->getCheck( 'saveusergroups' ) ) {
129 $reason = $request->getVal( 'user-reason' );
130 $tok = $request->getVal( 'wpEditToken' );
131 if( $user->matchEditToken( $tok, $this->mTarget ) ) {
132 $this->saveUserGroups(
133 $this->mTarget,
134 $reason
135 );
136
137 $out->redirect( $this->getSuccessURL() );
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 $status = $this->fetchUser( $username );
163 if( !$status->isOK() ) {
164 $this->getOutput()->addWikiText( $status->getWikiText() );
165 return;
166 } else {
167 $user = $status->value;
168 }
169
170 $allgroups = $this->getAllGroups();
171 $addgroup = array();
172 $removegroup = array();
173
174 // This could possibly create a highly unlikely race condition if permissions are changed between
175 // when the form is loaded and when the form is saved. Ignoring it for the moment.
176 foreach ( $allgroups as $group ) {
177 // We'll tell it to remove all unchecked groups, and add all checked groups.
178 // Later on, this gets filtered for what can actually be removed
179 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
180 $addgroup[] = $group;
181 } else {
182 $removegroup[] = $group;
183 }
184 }
185
186 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
187 }
188
189 /**
190 * Save user groups changes in the database.
191 *
192 * @param $user User object
193 * @param $add Array of groups to add
194 * @param $remove Array of groups to remove
195 * @param $reason String: reason for group change
196 * @return Array: Tuple of added, then removed groups
197 */
198 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
199 // Validate input set...
200 $isself = ( $user->getName() == $this->getUser()->getName() );
201 $groups = $user->getGroups();
202 $changeable = $this->changeableGroups();
203 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
204 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
205
206 $remove = array_unique(
207 array_intersect( (array)$remove, $removable, $groups ) );
208 $add = array_unique( array_diff(
209 array_intersect( (array)$add, $addable ),
210 $groups )
211 );
212
213 $oldGroups = $user->getGroups();
214 $newGroups = $oldGroups;
215
216 // remove then add groups
217 if( $remove ) {
218 $newGroups = array_diff( $newGroups, $remove );
219 foreach( $remove as $group ) {
220 $user->removeGroup( $group );
221 }
222 }
223 if( $add ) {
224 $newGroups = array_merge( $newGroups, $add );
225 foreach( $add as $group ) {
226 $user->addGroup( $group );
227 }
228 }
229 $newGroups = array_unique( $newGroups );
230
231 // Ensure that caches are cleared
232 $user->invalidateCache();
233
234 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
235 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
236 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
237
238 if( $newGroups != $oldGroups ) {
239 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
240 }
241 return array( $add, $remove );
242 }
243
244
245 /**
246 * Add a rights log entry for an action.
247 */
248 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
249 $log = new LogPage( 'rights' );
250
251 $log->addEntry( 'rights',
252 $user->getUserPage(),
253 $reason,
254 array(
255 $this->makeGroupNameListForLog( $oldGroups ),
256 $this->makeGroupNameListForLog( $newGroups )
257 )
258 );
259 }
260
261 /**
262 * Edit user groups membership
263 * @param $username String: name of the user.
264 */
265 function editUserGroupsForm( $username ) {
266 $status = $this->fetchUser( $username );
267 if( !$status->isOK() ) {
268 $this->getOutput()->addWikiText( $status->getWikiText() );
269 return;
270 } else {
271 $user = $status->value;
272 }
273
274 $groups = $user->getGroups();
275
276 $this->showEditUserGroupsForm( $user, $groups );
277
278 // This isn't really ideal logging behavior, but let's not hide the
279 // interwiki logs if we're using them as is.
280 $this->showLogFragment( $user, $this->getOutput() );
281 }
282
283 /**
284 * Normalize the input username, which may be local or remote, and
285 * return a user (or proxy) object for manipulating it.
286 *
287 * Side effects: error output for invalid access
288 * @return Status object
289 */
290 public function fetchUser( $username ) {
291 global $wgUserrightsInterwikiDelimiter;
292
293 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
294 if( count( $parts ) < 2 ) {
295 $name = trim( $username );
296 $database = '';
297 } else {
298 list( $name, $database ) = array_map( 'trim', $parts );
299
300 if( $database == wfWikiID() ) {
301 $database = '';
302 } else {
303 if( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
304 return Status::newFatal( 'userrights-no-interwiki' );
305 }
306 if( !UserRightsProxy::validDatabase( $database ) ) {
307 return Status::newFatal( 'userrights-nodatabase', $database );
308 }
309 }
310 }
311
312 if( $name === '' ) {
313 return Status::newFatal( 'nouserspecified' );
314 }
315
316 if( $name[0] == '#' ) {
317 // Numeric ID can be specified...
318 // We'll do a lookup for the name internally.
319 $id = intval( substr( $name, 1 ) );
320
321 if( $database == '' ) {
322 $name = User::whoIs( $id );
323 } else {
324 $name = UserRightsProxy::whoIs( $database, $id );
325 }
326
327 if( !$name ) {
328 return Status::newFatal( 'noname' );
329 }
330 } else {
331 $name = User::getCanonicalName( $name );
332 if( $name === false ) {
333 // invalid name
334 return Status::newFatal( 'nosuchusershort', $username );
335 }
336 }
337
338 if( $database == '' ) {
339 $user = User::newFromName( $name );
340 } else {
341 $user = UserRightsProxy::newFromName( $database, $name );
342 }
343
344 if( !$user || $user->isAnon() ) {
345 return Status::newFatal( 'nosuchusershort', $username );
346 }
347
348 return Status::newGood( $user );
349 }
350
351 function makeGroupNameList( $ids ) {
352 if( empty( $ids ) ) {
353 return wfMsgForContent( 'rightsnone' );
354 } else {
355 return implode( ', ', $ids );
356 }
357 }
358
359 function makeGroupNameListForLog( $ids ) {
360 if( empty( $ids ) ) {
361 return '';
362 } else {
363 return $this->makeGroupNameList( $ids );
364 }
365 }
366
367 /**
368 * Output a form to allow searching for a user
369 */
370 function switchForm() {
371 global $wgScript;
372 $this->getOutput()->addHTML(
373 Html::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
374 Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
375 Xml::fieldset( wfMsg( 'userrights-lookup-user' ) ) .
376 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget ) ) . ' ' .
377 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
378 Html::closeElement( 'fieldset' ) .
379 Html::closeElement( 'form' ) . "\n"
380 );
381 }
382
383 /**
384 * Go through used and available groups and return the ones that this
385 * form will be able to manipulate based on the current user's system
386 * permissions.
387 *
388 * @param $groups Array: list of groups the given user is in
389 * @return Array: Tuple of addable, then removable groups
390 */
391 protected function splitGroups( $groups ) {
392 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
393
394 $removable = array_intersect(
395 array_merge( $this->isself ? $removeself : array(), $removable ),
396 $groups
397 ); // Can't remove groups the user doesn't have
398 $addable = array_diff(
399 array_merge( $this->isself ? $addself : array(), $addable ),
400 $groups
401 ); // Can't add groups the user does have
402
403 return array( $addable, $removable );
404 }
405
406 /**
407 * Show the form to edit group memberships.
408 *
409 * @param $user User or UserRightsProxy you're editing
410 * @param $groups Array: Array of groups the user is in
411 */
412 protected function showEditUserGroupsForm( $user, $groups ) {
413 $list = array();
414 foreach( $groups as $group ) {
415 $list[] = self::buildGroupLink( $group );
416 }
417
418 $autolist = array();
419 if ( $user instanceof User ) {
420 foreach( Autopromote::getAutopromoteGroups( $user ) as $group ) {
421 $autolist[] = self::buildGroupLink( $group );
422 }
423 }
424
425 $grouplist = '';
426 $count = count( $list );
427 if( $count > 0 ) {
428 $grouplist = wfMessage( 'userrights-groupsmember', $count)->parse();
429 $grouplist = '<p>' . $grouplist . ' ' . $this->getLang()->listToText( $list ) . "</p>\n";
430 }
431 $count = count( $autolist );
432 if( $count > 0 ) {
433 $autogrouplistintro = wfMessage( 'userrights-groupsmember-auto', $count)->parse();
434 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $this->getLang()->listToText( $autolist ) . "</p>\n";
435 }
436
437 $userToolLinks = Linker::userToolLinks(
438 $user->getId(),
439 $user->getName(),
440 false, /* default for redContribsWhenNoEdits */
441 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
442 );
443
444 $this->getOutput()->addHTML(
445 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
446 Html::hidden( 'user', $this->mTarget ) .
447 Html::hidden( 'wpEditToken', $this->getUser()->editToken( $this->mTarget ) ) .
448 Xml::openElement( 'fieldset' ) .
449 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
450 wfMessage( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )->rawParams( $userToolLinks )->parse() .
451 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
452 $grouplist .
453 Xml::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
454 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
455 "<tr>
456 <td class='mw-label'>" .
457 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
458 "</td>
459 <td class='mw-input'>" .
460 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
461 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
462 "</td>
463 </tr>
464 <tr>
465 <td></td>
466 <td class='mw-submit'>" .
467 Xml::submitButton( wfMsg( 'saveusergroups' ),
468 array( 'name' => 'saveusergroups' ) + Linker::tooltipAndAccesskeyAttribs( 'userrights-set' ) ) .
469 "</td>
470 </tr>" .
471 Xml::closeElement( 'table' ) . "\n" .
472 Xml::closeElement( 'fieldset' ) .
473 Xml::closeElement( 'form' ) . "\n"
474 );
475 }
476
477 /**
478 * Format a link to a group description page
479 *
480 * @param $group string
481 * @return string
482 */
483 private static function buildGroupLink( $group ) {
484 static $cache = array();
485 if( !isset( $cache[$group] ) )
486 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
487 return $cache[$group];
488 }
489
490 /**
491 * Returns an array of all groups that may be edited
492 * @return array Array of groups that may be edited.
493 */
494 protected static function getAllGroups() {
495 return User::getAllGroups();
496 }
497
498 /**
499 * Adds a table with checkboxes where you can select what groups to add/remove
500 *
501 * @param $usergroups Array: groups the user belongs to
502 * @return string XHTML table element with checkboxes
503 */
504 private function groupCheckboxes( $usergroups, $user ) {
505 $allgroups = $this->getAllGroups();
506 $ret = '';
507
508 # Put all column info into an associative array so that extensions can
509 # more easily manage it.
510 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
511
512 foreach( $allgroups as $group ) {
513 $set = in_array( $group, $usergroups );
514 # Should the checkbox be disabled?
515 $disabled = !(
516 ( $set && $this->canRemove( $group ) ) ||
517 ( !$set && $this->canAdd( $group ) ) );
518 # Do we need to point out that this action is irreversible?
519 $irreversible = !$disabled && (
520 ( $set && !$this->canAdd( $group ) ) ||
521 ( !$set && !$this->canRemove( $group ) ) );
522
523 $checkbox = array(
524 'set' => $set,
525 'disabled' => $disabled,
526 'irreversible' => $irreversible
527 );
528
529 if( $disabled ) {
530 $columns['unchangeable'][$group] = $checkbox;
531 } else {
532 $columns['changeable'][$group] = $checkbox;
533 }
534 }
535
536 # Build the HTML table
537 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
538 "<tr>\n";
539 foreach( $columns as $name => $column ) {
540 if( $column === array() )
541 continue;
542 $ret .= Xml::element( 'th', null, wfMessage( 'userrights-' . $name . '-col', count( $column ) )->text() );
543 }
544 $ret.= "</tr>\n<tr>\n";
545 foreach( $columns as $column ) {
546 if( $column === array() )
547 continue;
548 $ret .= "\t<td style='vertical-align:top;'>\n";
549 foreach( $column as $group => $checkbox ) {
550 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
551
552 $member = User::getGroupMember( $group, $user->getName() );
553 if ( $checkbox['irreversible'] ) {
554 $text = wfMessage( 'userrights-irreversible-marker', $member )->escaped();
555 } else {
556 $text = htmlspecialchars( $member );
557 }
558 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
559 "wpGroup-" . $group, $checkbox['set'], $attr );
560 $ret .= "\t\t" . ( $checkbox['disabled']
561 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
562 : $checkboxHtml
563 ) . "<br />\n";
564 }
565 $ret .= "\t</td>\n";
566 }
567 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
568
569 return $ret;
570 }
571
572 /**
573 * @param $group String: the name of the group to check
574 * @return bool Can we remove the group?
575 */
576 private function canRemove( $group ) {
577 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
578 // PHP.
579 $groups = $this->changeableGroups();
580 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
581 }
582
583 /**
584 * @param $group string: the name of the group to check
585 * @return bool Can we add the group?
586 */
587 private function canAdd( $group ) {
588 $groups = $this->changeableGroups();
589 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
590 }
591
592 /**
593 * Returns $this->getUser()->changeableGroups()
594 *
595 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
596 */
597 function changeableGroups() {
598 return $this->getUser()->changeableGroups();
599 }
600
601 /**
602 * Show a rights log fragment for the specified user
603 *
604 * @param $user User to show log for
605 * @param $output OutputPage to use
606 */
607 protected function showLogFragment( $user, $output ) {
608 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
609 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
610 }
611 }