Follow-up r84814: revert redundant summary message addition.
[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 ) {
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 global $wgUser, $wgRequest, $wgOut;
67
68 if( $par !== null ) {
69 $this->mTarget = $par;
70 } else {
71 $this->mTarget = $wgRequest->getVal( 'user' );
72 }
73
74 /*
75 * If the user is blocked and they only have "partial" access
76 * (e.g. they don't have the userrights permission), then don't
77 * allow them to use Special:UserRights.
78 */
79 if( $wgUser->isBlocked() && !$wgUser->isAllowed( 'userrights' ) ) {
80 $wgOut->blockedPage();
81 return;
82 }
83
84 $available = $this->changeableGroups();
85
86 if ( $this->mTarget === null ) {
87 /*
88 * If the user specified no target, and they can only
89 * edit their own groups, automatically set them as the
90 * target.
91 */
92 if ( !count( $available['add'] ) && !count( $available['remove'] ) )
93 $this->mTarget = $wgUser->getName();
94 }
95
96 if ( User::getCanonicalName( $this->mTarget ) == $wgUser->getName() ) {
97 $this->isself = true;
98 }
99
100 if( !$this->userCanChangeRights( $wgUser, true ) ) {
101 // fixme... there may be intermediate groups we can mention.
102 $wgOut->showPermissionsErrorPage( array( array(
103 $wgUser->isAnon()
104 ? 'userrights-nologin'
105 : 'userrights-notallowed' ) ) );
106 return;
107 }
108
109 if ( wfReadOnly() ) {
110 $wgOut->readOnlyPage();
111 return;
112 }
113
114 $this->outputHeader();
115 $wgOut->addModuleStyles( 'mediawiki.special' );
116 $this->setHeaders();
117
118 // show the general form
119 if ( count( $available['add'] ) || count( $available['remove'] ) ) {
120 $this->switchForm();
121 }
122
123 if( $wgRequest->wasPosted() ) {
124 // save settings
125 if( $wgRequest->getCheck( 'saveusergroups' ) ) {
126 $reason = $wgRequest->getVal( 'user-reason' );
127 $tok = $wgRequest->getVal( 'wpEditToken' );
128 if( $wgUser->matchEditToken( $tok, $this->mTarget ) ) {
129 $this->saveUserGroups(
130 $this->mTarget,
131 $reason
132 );
133
134 $url = $this->getSuccessURL();
135 $wgOut->redirect( $url );
136 return;
137 }
138 }
139 }
140
141 // show some more forms
142 if( $this->mTarget !== null ) {
143 $this->editUserGroupsForm( $this->mTarget );
144 }
145 }
146
147 function getSuccessURL() {
148 return $this->getTitle( $this->mTarget )->getFullURL();
149 }
150
151 /**
152 * Save user groups changes in the database.
153 * Data comes from the editUserGroupsForm() form function
154 *
155 * @param $username String: username to apply changes to.
156 * @param $reason String: reason for group change
157 * @return null
158 */
159 function saveUserGroups( $username, $reason = '' ) {
160 global $wgRequest, $wgOut;
161
162 $status = $this->fetchUser( $username );
163 if( !$status->isOK() ) {
164 $wgOut->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 ( $wgRequest->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 global $wgUser;
200
201 // Validate input set...
202 $isself = ( $user->getName() == $wgUser->getName() );
203 $groups = $user->getGroups();
204 $changeable = $this->changeableGroups();
205 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
206 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
207
208 $remove = array_unique(
209 array_intersect( (array)$remove, $removable, $groups ) );
210 $add = array_unique( array_diff(
211 array_intersect( (array)$add, $addable ),
212 $groups )
213 );
214
215 $oldGroups = $user->getGroups();
216 $newGroups = $oldGroups;
217
218 // remove then add groups
219 if( $remove ) {
220 $newGroups = array_diff( $newGroups, $remove );
221 foreach( $remove as $group ) {
222 $user->removeGroup( $group );
223 }
224 }
225 if( $add ) {
226 $newGroups = array_merge( $newGroups, $add );
227 foreach( $add as $group ) {
228 $user->addGroup( $group );
229 }
230 }
231 $newGroups = array_unique( $newGroups );
232
233 // Ensure that caches are cleared
234 $user->invalidateCache();
235
236 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
237 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
238 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
239
240 if( $newGroups != $oldGroups ) {
241 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
242 }
243 return array( $add, $remove );
244 }
245
246
247 /**
248 * Add a rights log entry for an action.
249 */
250 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
251 $log = new LogPage( 'rights' );
252
253 $log->addEntry( 'rights',
254 $user->getUserPage(),
255 $reason,
256 array(
257 $this->makeGroupNameListForLog( $oldGroups ),
258 $this->makeGroupNameListForLog( $newGroups )
259 )
260 );
261 }
262
263 /**
264 * Edit user groups membership
265 * @param $username String: name of the user.
266 */
267 function editUserGroupsForm( $username ) {
268 global $wgOut;
269
270 $status = $this->fetchUser( $username );
271 if( !$status->isOK() ) {
272 $wgOut->addWikiText( $status->getWikiText() );
273 return;
274 } else {
275 $user = $status->value;
276 }
277
278 $groups = $user->getGroups();
279
280 $this->showEditUserGroupsForm( $user, $groups );
281
282 // This isn't really ideal logging behavior, but let's not hide the
283 // interwiki logs if we're using them as is.
284 $this->showLogFragment( $user, $wgOut );
285 }
286
287 /**
288 * Normalize the input username, which may be local or remote, and
289 * return a user (or proxy) object for manipulating it.
290 *
291 * Side effects: error output for invalid access
292 * @return Status object
293 */
294 public function fetchUser( $username ) {
295 global $wgUser, $wgUserrightsInterwikiDelimiter;
296
297 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
298 if( count( $parts ) < 2 ) {
299 $name = trim( $username );
300 $database = '';
301 } else {
302 list( $name, $database ) = array_map( 'trim', $parts );
303
304 if( $database == wfWikiID() ) {
305 $database = '';
306 } else {
307 if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
308 return Status::newFatal( 'userrights-no-interwiki' );
309 }
310 if( !UserRightsProxy::validDatabase( $database ) ) {
311 return Status::newFatal( 'userrights-nodatabase', $database );
312 }
313 }
314 }
315
316 if( $name === '' ) {
317 return Status::newFatal( 'nouserspecified' );
318 }
319
320 if( $name{0} == '#' ) {
321 // Numeric ID can be specified...
322 // We'll do a lookup for the name internally.
323 $id = intval( substr( $name, 1 ) );
324
325 if( $database == '' ) {
326 $name = User::whoIs( $id );
327 } else {
328 $name = UserRightsProxy::whoIs( $database, $id );
329 }
330
331 if( !$name ) {
332 return Status::newFatal( 'noname' );
333 }
334 } else {
335 $name = User::getCanonicalName( $name );
336 if( $name === false ) {
337 // invalid name
338 return Status::newFatal( 'nosuchusershort', $username );
339 }
340 }
341
342 if( $database == '' ) {
343 $user = User::newFromName( $name );
344 } else {
345 $user = UserRightsProxy::newFromName( $database, $name );
346 }
347
348 if( !$user || $user->isAnon() ) {
349 return Status::newFatal( 'nosuchusershort', $username );
350 }
351
352 return Status::newGood( $user );
353 }
354
355 function makeGroupNameList( $ids ) {
356 if( empty( $ids ) ) {
357 return wfMsgForContent( 'rightsnone' );
358 } else {
359 return implode( ', ', $ids );
360 }
361 }
362
363 function makeGroupNameListForLog( $ids ) {
364 if( empty( $ids ) ) {
365 return '';
366 } else {
367 return $this->makeGroupNameList( $ids );
368 }
369 }
370
371 /**
372 * Output a form to allow searching for a user
373 */
374 function switchForm() {
375 global $wgOut, $wgScript;
376 $wgOut->addHTML(
377 Html::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
378 Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) .
379 Xml::fieldset( wfMsg( 'userrights-lookup-user' ) ) .
380 Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, str_replace( '_', ' ', $this->mTarget ) ) . ' ' .
381 Xml::submitButton( wfMsg( 'editusergroup' ) ) .
382 Html::closeElement( 'fieldset' ) .
383 Html::closeElement( 'form' ) . "\n"
384 );
385 }
386
387 /**
388 * Go through used and available groups and return the ones that this
389 * form will be able to manipulate based on the current user's system
390 * permissions.
391 *
392 * @param $groups Array: list of groups the given user is in
393 * @return Array: Tuple of addable, then removable groups
394 */
395 protected function splitGroups( $groups ) {
396 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
397
398 $removable = array_intersect(
399 array_merge( $this->isself ? $removeself : array(), $removable ),
400 $groups
401 ); // Can't remove groups the user doesn't have
402 $addable = array_diff(
403 array_merge( $this->isself ? $addself : array(), $addable ),
404 $groups
405 ); // Can't add groups the user does have
406
407 return array( $addable, $removable );
408 }
409
410 /**
411 * Show the form to edit group memberships.
412 *
413 * @param $user User or UserRightsProxy you're editing
414 * @param $groups Array: Array of groups the user is in
415 */
416 protected function showEditUserGroupsForm( $user, $groups ) {
417 global $wgOut, $wgUser, $wgLang, $wgRequest;
418
419 $list = array();
420 foreach( $groups as $group ) {
421 $list[] = self::buildGroupLink( $group );
422 }
423
424 $autolist = array();
425 if ( $user instanceof User ) {
426 foreach( Autopromote::getAutopromoteGroups( $user ) as $group ) {
427 $autolist[] = self::buildGroupLink( $group );
428 }
429 }
430
431 $grouplist = '';
432 if( count( $list ) > 0 ) {
433 $grouplist = wfMsgHtml( 'userrights-groupsmember' );
434 $grouplist = '<p>' . $grouplist . ' ' . $wgLang->listToText( $list ) . "</p>\n";
435 }
436 if( count( $autolist ) > 0 ) {
437 $autogrouplistintro = wfMsgHtml( 'userrights-groupsmember-auto' );
438 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $wgLang->listToText( $autolist ) . "</p>\n";
439 }
440 $wgOut->addHTML(
441 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
442 Html::hidden( 'user', $this->mTarget ) .
443 Html::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
444 Xml::openElement( 'fieldset' ) .
445 Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
446 wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
447 wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
448 $grouplist .
449 Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
450 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
451 "<tr>
452 <td class='mw-label'>" .
453 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
454 "</td>
455 <td class='mw-input'>" .
456 Xml::input( 'user-reason', 60, $wgRequest->getVal( 'user-reason', false ),
457 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
458 "</td>
459 </tr>
460 <tr>
461 <td></td>
462 <td class='mw-submit'>" .
463 Xml::submitButton( wfMsg( 'saveusergroups' ),
464 array( 'name' => 'saveusergroups' ) + $wgUser->getSkin()->tooltipAndAccessKeyAttribs( 'userrights-set' ) ) .
465 "</td>
466 </tr>" .
467 Xml::closeElement( 'table' ) . "\n" .
468 Xml::closeElement( 'fieldset' ) .
469 Xml::closeElement( 'form' ) . "\n"
470 );
471 }
472
473 /**
474 * Format a link to a group description page
475 *
476 * @param $group string
477 * @return string
478 */
479 private static function buildGroupLink( $group ) {
480 static $cache = array();
481 if( !isset( $cache[$group] ) )
482 $cache[$group] = User::makeGroupLinkHtml( $group, htmlspecialchars( User::getGroupName( $group ) ) );
483 return $cache[$group];
484 }
485
486 /**
487 * Returns an array of all groups that may be edited
488 * @return array Array of groups that may be edited.
489 */
490 protected static function getAllGroups() {
491 return User::getAllGroups();
492 }
493
494 /**
495 * Adds a table with checkboxes where you can select what groups to add/remove
496 *
497 * @param $usergroups Array: groups the user belongs to
498 * @return string XHTML table element with checkboxes
499 */
500 private function groupCheckboxes( $usergroups ) {
501 $allgroups = $this->getAllGroups();
502 $ret = '';
503
504 # Put all column info into an associative array so that extensions can
505 # more easily manage it.
506 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
507
508 foreach( $allgroups as $group ) {
509 $set = in_array( $group, $usergroups );
510 # Should the checkbox be disabled?
511 $disabled = !(
512 ( $set && $this->canRemove( $group ) ) ||
513 ( !$set && $this->canAdd( $group ) ) );
514 # Do we need to point out that this action is irreversible?
515 $irreversible = !$disabled && (
516 ( $set && !$this->canAdd( $group ) ) ||
517 ( !$set && !$this->canRemove( $group ) ) );
518
519 $checkbox = array(
520 'set' => $set,
521 'disabled' => $disabled,
522 'irreversible' => $irreversible
523 );
524
525 if( $disabled ) {
526 $columns['unchangeable'][$group] = $checkbox;
527 } else {
528 $columns['changeable'][$group] = $checkbox;
529 }
530 }
531
532 # Build the HTML table
533 $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
534 "<tr>\n";
535 foreach( $columns as $name => $column ) {
536 if( $column === array() )
537 continue;
538 $ret .= Xml::element( 'th', null, wfMsg( 'userrights-' . $name . '-col' ) );
539 }
540 $ret.= "</tr>\n<tr>\n";
541 foreach( $columns as $column ) {
542 if( $column === array() )
543 continue;
544 $ret .= "\t<td style='vertical-align:top;'>\n";
545 foreach( $column as $group => $checkbox ) {
546 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
547
548 if ( $checkbox['irreversible'] ) {
549 $text = htmlspecialchars( wfMsg( 'userrights-irreversible-marker',
550 User::getGroupMember( $group ) ) );
551 } else {
552 $text = htmlspecialchars( User::getGroupMember( $group ) );
553 }
554 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
555 "wpGroup-" . $group, $checkbox['set'], $attr );
556 $ret .= "\t\t" . ( $checkbox['disabled']
557 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
558 : $checkboxHtml
559 ) . "<br />\n";
560 }
561 $ret .= "\t</td>\n";
562 }
563 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
564
565 return $ret;
566 }
567
568 /**
569 * @param $group String: the name of the group to check
570 * @return bool Can we remove the group?
571 */
572 private function canRemove( $group ) {
573 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
574 // PHP.
575 $groups = $this->changeableGroups();
576 return in_array( $group, $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] ) );
577 }
578
579 /**
580 * @param $group string: the name of the group to check
581 * @return bool Can we add the group?
582 */
583 private function canAdd( $group ) {
584 $groups = $this->changeableGroups();
585 return in_array( $group, $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] ) );
586 }
587
588 /**
589 * Returns $wgUser->changeableGroups()
590 *
591 * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
592 */
593 function changeableGroups() {
594 global $wgUser;
595 return $wgUser->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()->getPrefixedText() );
607 }
608 }