Merge "ApiFeedRecentChanges: Validate param target"
[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 /**
49 * @param User $user
50 * @param bool $checkIfSelf
51 * @return bool
52 */
53 public function userCanChangeRights( $user, $checkIfSelf = true ) {
54 $available = $this->changeableGroups();
55 if ( $user->getId() == 0 ) {
56 return false;
57 }
58
59 return !empty( $available['add'] )
60 || !empty( $available['remove'] )
61 || ( ( $this->isself || !$checkIfSelf ) &&
62 ( !empty( $available['add-self'] )
63 || !empty( $available['remove-self'] ) ) );
64 }
65
66 /**
67 * Manage forms to be shown according to posted data.
68 * Depending on the submit button used, call a form or a save function.
69 *
70 * @param $par Mixed: string if any subpage provided, else null
71 * @throws UserBlockedError|PermissionsError
72 */
73 public function execute( $par ) {
74 // If the visitor doesn't have permissions to assign or remove
75 // any groups, it's a bit silly to give them the user search prompt.
76
77 $user = $this->getUser();
78
79 /*
80 * If the user is blocked and they only have "partial" access
81 * (e.g. they don't have the userrights permission), then don't
82 * allow them to use Special:UserRights.
83 */
84 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
85 throw new UserBlockedError( $user->getBlock() );
86 }
87
88 $request = $this->getRequest();
89
90 if ( $par !== null ) {
91 $this->mTarget = $par;
92 } else {
93 $this->mTarget = $request->getVal( 'user' );
94 }
95
96 $available = $this->changeableGroups();
97
98 if ( $this->mTarget === null ) {
99 /*
100 * If the user specified no target, and they can only
101 * edit their own groups, automatically set them as the
102 * target.
103 */
104 if ( !count( $available['add'] ) && !count( $available['remove'] ) ) {
105 $this->mTarget = $user->getName();
106 }
107 }
108
109 if ( User::getCanonicalName( $this->mTarget ) == $user->getName() ) {
110 $this->isself = true;
111 }
112
113 if ( !$this->userCanChangeRights( $user, true ) ) {
114 if ( $this->isself && $request->getCheck( 'success' ) ) {
115 // bug 48609: if the user just removed its own rights, this would
116 // leads it in a "permissions error" page. In that case, show a
117 // message that it can't anymore use this page instead of an error
118 $this->setHeaders();
119 $out = $this->getOutput();
120 $out->wrapWikiMsg( "<div class=\"successbox\">\n$1\n</div>", 'userrights-removed-self' );
121 $out->returnToMain();
122
123 return;
124 }
125
126 // @todo FIXME: There may be intermediate groups we can mention.
127 $msg = $user->isAnon() ? 'userrights-nologin' : 'userrights-notallowed';
128 throw new PermissionsError( null, array( array( $msg ) ) );
129 }
130
131 $this->checkReadOnly();
132
133 $this->setHeaders();
134 $this->outputHeader();
135
136 $out = $this->getOutput();
137 $out->addModuleStyles( 'mediawiki.special' );
138
139 // show the general form
140 if ( count( $available['add'] ) || count( $available['remove'] ) ) {
141 $this->switchForm();
142 }
143
144 if (
145 $request->wasPosted() &&
146 $request->getCheck( 'saveusergroups' ) &&
147 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
148 ) {
149 // save settings
150 $status = $this->fetchUser( $this->mTarget );
151 if ( !$status->isOK() ) {
152 $this->getOutput()->addWikiText( $status->getWikiText() );
153
154 return;
155 }
156
157 $targetUser = $status->value;
158 if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (bug 61252)
159 $targetUser->clearInstanceCache(); // bug 38989
160 }
161
162 if ( $request->getVal( 'conflictcheck-originalgroups' )
163 !== implode( ',', $targetUser->getGroups() )
164 ) {
165 $out->addWikiMsg( 'userrights-conflict' );
166 } else {
167 $this->saveUserGroups(
168 $this->mTarget,
169 $request->getVal( 'user-reason' ),
170 $targetUser
171 );
172
173 $out->redirect( $this->getSuccessURL() );
174
175 return;
176 }
177 }
178
179 // show some more forms
180 if ( $this->mTarget !== null ) {
181 $this->editUserGroupsForm( $this->mTarget );
182 }
183 }
184
185 function getSuccessURL() {
186 return $this->getPageTitle( $this->mTarget )->getFullURL( array( 'success' => 1 ) );
187 }
188
189 /**
190 * Save user groups changes in the database.
191 * Data comes from the editUserGroupsForm() form function
192 *
193 * @param string $username username to apply changes to.
194 * @param string $reason reason for group change
195 * @param User|UserRightsProxy $user Target user object.
196 * @return null
197 */
198 function saveUserGroups( $username, $reason, $user ) {
199 $allgroups = $this->getAllGroups();
200 $addgroup = array();
201 $removegroup = array();
202
203 // This could possibly create a highly unlikely race condition if permissions are changed between
204 // when the form is loaded and when the form is saved. Ignoring it for the moment.
205 foreach ( $allgroups as $group ) {
206 // We'll tell it to remove all unchecked groups, and add all checked groups.
207 // Later on, this gets filtered for what can actually be removed
208 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
209 $addgroup[] = $group;
210 } else {
211 $removegroup[] = $group;
212 }
213 }
214
215 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason );
216 }
217
218 /**
219 * Save user groups changes in the database.
220 *
221 * @param $user User object
222 * @param array $add of groups to add
223 * @param array $remove of groups to remove
224 * @param string $reason reason for group change
225 * @return Array: Tuple of added, then removed groups
226 */
227 function doSaveUserGroups( $user, $add, $remove, $reason = '' ) {
228 global $wgAuth;
229
230 // Validate input set...
231 $isself = ( $user->getName() == $this->getUser()->getName() );
232 $groups = $user->getGroups();
233 $changeable = $this->changeableGroups();
234 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : array() );
235 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : array() );
236
237 $remove = array_unique(
238 array_intersect( (array)$remove, $removable, $groups ) );
239 $add = array_unique( array_diff(
240 array_intersect( (array)$add, $addable ),
241 $groups )
242 );
243
244 $oldGroups = $user->getGroups();
245 $newGroups = $oldGroups;
246
247 // remove then add groups
248 if ( $remove ) {
249 $newGroups = array_diff( $newGroups, $remove );
250 foreach ( $remove as $group ) {
251 $user->removeGroup( $group );
252 }
253 }
254 if ( $add ) {
255 $newGroups = array_merge( $newGroups, $add );
256 foreach ( $add as $group ) {
257 $user->addGroup( $group );
258 }
259 }
260 $newGroups = array_unique( $newGroups );
261
262 // Ensure that caches are cleared
263 $user->invalidateCache();
264
265 // update groups in external authentication database
266 $wgAuth->updateExternalDBGroups( $user, $add, $remove );
267
268 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
269 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
270 wfRunHooks( 'UserRights', array( &$user, $add, $remove ) );
271
272 if ( $newGroups != $oldGroups ) {
273 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason );
274 }
275
276 return array( $add, $remove );
277 }
278
279 /**
280 * Add a rights log entry for an action.
281 */
282 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
283 $logEntry = new ManualLogEntry( 'rights', 'rights' );
284 $logEntry->setPerformer( $this->getUser() );
285 $logEntry->setTarget( $user->getUserPage() );
286 $logEntry->setComment( $reason );
287 $logEntry->setParameters( array(
288 '4::oldgroups' => $oldGroups,
289 '5::newgroups' => $newGroups,
290 ) );
291 $logid = $logEntry->insert();
292 $logEntry->publish( $logid );
293 }
294
295 /**
296 * Edit user groups membership
297 * @param string $username name of the user.
298 */
299 function editUserGroupsForm( $username ) {
300 $status = $this->fetchUser( $username );
301 if ( !$status->isOK() ) {
302 $this->getOutput()->addWikiText( $status->getWikiText() );
303
304 return;
305 } else {
306 $user = $status->value;
307 }
308
309 $groups = $user->getGroups();
310
311 $this->showEditUserGroupsForm( $user, $groups );
312
313 // This isn't really ideal logging behavior, but let's not hide the
314 // interwiki logs if we're using them as is.
315 $this->showLogFragment( $user, $this->getOutput() );
316 }
317
318 /**
319 * Normalize the input username, which may be local or remote, and
320 * return a user (or proxy) object for manipulating it.
321 *
322 * Side effects: error output for invalid access
323 * @param string $username
324 * @return Status object
325 */
326 public function fetchUser( $username ) {
327 global $wgUserrightsInterwikiDelimiter;
328
329 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
330 if ( count( $parts ) < 2 ) {
331 $name = trim( $username );
332 $database = '';
333 } else {
334 list( $name, $database ) = array_map( 'trim', $parts );
335
336 if ( $database == wfWikiID() ) {
337 $database = '';
338 } else {
339 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
340 return Status::newFatal( 'userrights-no-interwiki' );
341 }
342 if ( !UserRightsProxy::validDatabase( $database ) ) {
343 return Status::newFatal( 'userrights-nodatabase', $database );
344 }
345 }
346 }
347
348 if ( $name === '' ) {
349 return Status::newFatal( 'nouserspecified' );
350 }
351
352 if ( $name[0] == '#' ) {
353 // Numeric ID can be specified...
354 // We'll do a lookup for the name internally.
355 $id = intval( substr( $name, 1 ) );
356
357 if ( $database == '' ) {
358 $name = User::whoIs( $id );
359 } else {
360 $name = UserRightsProxy::whoIs( $database, $id );
361 }
362
363 if ( !$name ) {
364 return Status::newFatal( 'noname' );
365 }
366 } else {
367 $name = User::getCanonicalName( $name );
368 if ( $name === false ) {
369 // invalid name
370 return Status::newFatal( 'nosuchusershort', $username );
371 }
372 }
373
374 if ( $database == '' ) {
375 $user = User::newFromName( $name );
376 } else {
377 $user = UserRightsProxy::newFromName( $database, $name );
378 }
379
380 if ( !$user || $user->isAnon() ) {
381 return Status::newFatal( 'nosuchusershort', $username );
382 }
383
384 return Status::newGood( $user );
385 }
386
387 function makeGroupNameList( $ids ) {
388 if ( empty( $ids ) ) {
389 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
390 } else {
391 return implode( ', ', $ids );
392 }
393 }
394
395 /**
396 * Make a list of group names to be stored as parameter for log entries
397 *
398 * @deprecated in 1.21; use LogFormatter instead.
399 * @param $ids array
400 * @return string
401 */
402 function makeGroupNameListForLog( $ids ) {
403 wfDeprecated( __METHOD__, '1.21' );
404
405 if ( empty( $ids ) ) {
406 return '';
407 } else {
408 return $this->makeGroupNameList( $ids );
409 }
410 }
411
412 /**
413 * Output a form to allow searching for a user
414 */
415 function switchForm() {
416 global $wgScript;
417 $this->getOutput()->addHTML(
418 Html::openElement(
419 'form',
420 array(
421 'method' => 'get',
422 'action' => $wgScript,
423 'name' => 'uluser',
424 'id' => 'mw-userrights-form1'
425 )
426 ) .
427 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
428 Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
429 Xml::inputLabel(
430 $this->msg( 'userrights-user-editname' )->text(),
431 'user',
432 'username',
433 30,
434 str_replace( '_', ' ', $this->mTarget ),
435 array( 'autofocus' => true )
436 ) . ' ' .
437 Xml::submitButton( $this->msg( 'editusergroup' )->text() ) .
438 Html::closeElement( 'fieldset' ) .
439 Html::closeElement( 'form' ) . "\n"
440 );
441 }
442
443 /**
444 * Go through used and available groups and return the ones that this
445 * form will be able to manipulate based on the current user's system
446 * permissions.
447 *
448 * @param array $groups list of groups the given user is in
449 * @return Array: Tuple of addable, then removable groups
450 */
451 protected function splitGroups( $groups ) {
452 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
453
454 $removable = array_intersect(
455 array_merge( $this->isself ? $removeself : array(), $removable ),
456 $groups
457 ); // Can't remove groups the user doesn't have
458 $addable = array_diff(
459 array_merge( $this->isself ? $addself : array(), $addable ),
460 $groups
461 ); // Can't add groups the user does have
462
463 return array( $addable, $removable );
464 }
465
466 /**
467 * Show the form to edit group memberships.
468 *
469 * @param $user User or UserRightsProxy you're editing
470 * @param $groups Array: Array of groups the user is in
471 */
472 protected function showEditUserGroupsForm( $user, $groups ) {
473 $list = array();
474 $membersList = array();
475 foreach ( $groups as $group ) {
476 $list[] = self::buildGroupLink( $group );
477 $membersList[] = self::buildGroupMemberLink( $group );
478 }
479
480 $autoList = array();
481 $autoMembersList = array();
482 if ( $user instanceof User ) {
483 foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
484 $autoList[] = self::buildGroupLink( $group );
485 $autoMembersList[] = self::buildGroupMemberLink( $group );
486 }
487 }
488
489 $language = $this->getLanguage();
490 $displayedList = $this->msg( 'userrights-groupsmember-type',
491 $language->listToText( $list ),
492 $language->listToText( $membersList )
493 )->plain();
494 $displayedAutolist = $this->msg( 'userrights-groupsmember-type',
495 $language->listToText( $autoList ),
496 $language->listToText( $autoMembersList )
497 )->plain();
498
499 $grouplist = '';
500 $count = count( $list );
501 if ( $count > 0 ) {
502 $grouplist = $this->msg( 'userrights-groupsmember', $count, $user->getName() )->parse();
503 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
504 }
505
506 $count = count( $autoList );
507 if ( $count > 0 ) {
508 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto', $count, $user->getName() )
509 ->parse();
510 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
511 }
512
513 $userToolLinks = Linker::userToolLinks(
514 $user->getId(),
515 $user->getName(),
516 false, /* default for redContribsWhenNoEdits */
517 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
518 );
519
520 $this->getOutput()->addHTML(
521 Xml::openElement(
522 'form',
523 array(
524 'method' => 'post',
525 'action' => $this->getPageTitle()->getLocalURL(),
526 'name' => 'editGroup',
527 'id' => 'mw-userrights-form2'
528 )
529 ) .
530 Html::hidden( 'user', $this->mTarget ) .
531 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
532 Html::hidden(
533 'conflictcheck-originalgroups',
534 implode( ',', $user->getGroups() )
535 ) . // Conflict detection
536 Xml::openElement( 'fieldset' ) .
537 Xml::element(
538 'legend',
539 array(),
540 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
541 ) .
542 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
543 ->rawParams( $userToolLinks )->parse() .
544 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
545 $grouplist .
546 Xml::tags( 'p', null, $this->groupCheckboxes( $groups, $user ) ) .
547 Xml::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
548 "<tr>
549 <td class='mw-label'>" .
550 Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
551 "</td>
552 <td class='mw-input'>" .
553 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
554 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
555 "</td>
556 </tr>
557 <tr>
558 <td></td>
559 <td class='mw-submit'>" .
560 Xml::submitButton( $this->msg( 'saveusergroups' )->text(),
561 array( 'name' => 'saveusergroups' ) +
562 Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
563 ) .
564 "</td>
565 </tr>" .
566 Xml::closeElement( 'table' ) . "\n" .
567 Xml::closeElement( 'fieldset' ) .
568 Xml::closeElement( 'form' ) . "\n"
569 );
570 }
571
572 /**
573 * Format a link to a group description page
574 *
575 * @param $group string
576 * @return string
577 */
578 private static function buildGroupLink( $group ) {
579 return User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
580 }
581
582 /**
583 * Format a link to a group member description page
584 *
585 * @param $group string
586 * @return string
587 */
588 private static function buildGroupMemberLink( $group ) {
589 return User::makeGroupLinkHtml( $group, User::getGroupMember( $group ) );
590 }
591
592 /**
593 * Returns an array of all groups that may be edited
594 * @return array Array of groups that may be edited.
595 */
596 protected static function getAllGroups() {
597 return User::getAllGroups();
598 }
599
600 /**
601 * Adds a table with checkboxes where you can select what groups to add/remove
602 *
603 * @todo Just pass the username string?
604 * @param array $usergroups groups the user belongs to
605 * @param $user User a user object
606 * @return string XHTML table element with checkboxes
607 */
608 private function groupCheckboxes( $usergroups, $user ) {
609 $allgroups = $this->getAllGroups();
610 $ret = '';
611
612 // Put all column info into an associative array so that extensions can
613 // more easily manage it.
614 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
615
616 foreach ( $allgroups as $group ) {
617 $set = in_array( $group, $usergroups );
618 // Should the checkbox be disabled?
619 $disabled = !(
620 ( $set && $this->canRemove( $group ) ) ||
621 ( !$set && $this->canAdd( $group ) ) );
622 // Do we need to point out that this action is irreversible?
623 $irreversible = !$disabled && (
624 ( $set && !$this->canAdd( $group ) ) ||
625 ( !$set && !$this->canRemove( $group ) ) );
626
627 $checkbox = array(
628 'set' => $set,
629 'disabled' => $disabled,
630 'irreversible' => $irreversible
631 );
632
633 if ( $disabled ) {
634 $columns['unchangeable'][$group] = $checkbox;
635 } else {
636 $columns['changeable'][$group] = $checkbox;
637 }
638 }
639
640 // Build the HTML table
641 $ret .= Xml::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
642 "<tr>\n";
643 foreach ( $columns as $name => $column ) {
644 if ( $column === array() ) {
645 continue;
646 }
647 // Messages: userrights-changeable-col, userrights-unchangeable-col
648 $ret .= Xml::element(
649 'th',
650 null,
651 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
652 );
653 }
654
655 $ret .= "</tr>\n<tr>\n";
656 foreach ( $columns as $column ) {
657 if ( $column === array() ) {
658 continue;
659 }
660 $ret .= "\t<td style='vertical-align:top;'>\n";
661 foreach ( $column as $group => $checkbox ) {
662 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
663
664 $member = User::getGroupMember( $group, $user->getName() );
665 if ( $checkbox['irreversible'] ) {
666 $text = $this->msg( 'userrights-irreversible-marker', $member )->escaped();
667 } else {
668 $text = htmlspecialchars( $member );
669 }
670 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
671 "wpGroup-" . $group, $checkbox['set'], $attr );
672 $ret .= "\t\t" . ( $checkbox['disabled']
673 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
674 : $checkboxHtml
675 ) . "<br />\n";
676 }
677 $ret .= "\t</td>\n";
678 }
679 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
680
681 return $ret;
682 }
683
684 /**
685 * @param $group String: the name of the group to check
686 * @return bool Can we remove the group?
687 */
688 private function canRemove( $group ) {
689 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
690 $groups = $this->changeableGroups();
691
692 return in_array(
693 $group,
694 $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
695 );
696 }
697
698 /**
699 * @param string $group the name of the group to check
700 * @return bool Can we add the group?
701 */
702 private function canAdd( $group ) {
703 $groups = $this->changeableGroups();
704
705 return in_array(
706 $group,
707 $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
708 );
709 }
710
711 /**
712 * Returns $this->getUser()->changeableGroups()
713 *
714 * @return array array(
715 * 'add' => array( addablegroups ),
716 * 'remove' => array( removablegroups ),
717 * 'add-self' => array( addablegroups to self ),
718 * 'remove-self' => array( removable groups from self )
719 * )
720 */
721 function changeableGroups() {
722 return $this->getUser()->changeableGroups();
723 }
724
725 /**
726 * Show a rights log fragment for the specified user
727 *
728 * @param $user User to show log for
729 * @param $output OutputPage to use
730 */
731 protected function showLogFragment( $user, $output ) {
732 $rightsLogPage = new LogPage( 'rights' );
733 $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
734 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
735 }
736
737 protected function getGroupName() {
738 return 'users';
739 }
740 }