Merge "Revert "Make a hidden form field to keep the language code""
[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 string|null $par 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
222 * @param array $add Array of groups to add
223 * @param array $remove Array 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 * @param User $user
282 * @param array $oldGroups
283 * @param array $newGroups
284 * @param array $reason
285 */
286 function addLogEntry( $user, $oldGroups, $newGroups, $reason ) {
287 $logEntry = new ManualLogEntry( 'rights', 'rights' );
288 $logEntry->setPerformer( $this->getUser() );
289 $logEntry->setTarget( $user->getUserPage() );
290 $logEntry->setComment( $reason );
291 $logEntry->setParameters( array(
292 '4::oldgroups' => $oldGroups,
293 '5::newgroups' => $newGroups,
294 ) );
295 $logid = $logEntry->insert();
296 $logEntry->publish( $logid );
297 }
298
299 /**
300 * Edit user groups membership
301 * @param string $username Name of the user.
302 */
303 function editUserGroupsForm( $username ) {
304 $status = $this->fetchUser( $username );
305 if ( !$status->isOK() ) {
306 $this->getOutput()->addWikiText( $status->getWikiText() );
307
308 return;
309 } else {
310 $user = $status->value;
311 }
312
313 $groups = $user->getGroups();
314
315 $this->showEditUserGroupsForm( $user, $groups );
316
317 // This isn't really ideal logging behavior, but let's not hide the
318 // interwiki logs if we're using them as is.
319 $this->showLogFragment( $user, $this->getOutput() );
320 }
321
322 /**
323 * Normalize the input username, which may be local or remote, and
324 * return a user (or proxy) object for manipulating it.
325 *
326 * Side effects: error output for invalid access
327 * @param string $username
328 * @return Status
329 */
330 public function fetchUser( $username ) {
331 global $wgUserrightsInterwikiDelimiter;
332
333 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
334 if ( count( $parts ) < 2 ) {
335 $name = trim( $username );
336 $database = '';
337 } else {
338 list( $name, $database ) = array_map( 'trim', $parts );
339
340 if ( $database == wfWikiID() ) {
341 $database = '';
342 } else {
343 if ( !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
344 return Status::newFatal( 'userrights-no-interwiki' );
345 }
346 if ( !UserRightsProxy::validDatabase( $database ) ) {
347 return Status::newFatal( 'userrights-nodatabase', $database );
348 }
349 }
350 }
351
352 if ( $name === '' ) {
353 return Status::newFatal( 'nouserspecified' );
354 }
355
356 if ( $name[0] == '#' ) {
357 // Numeric ID can be specified...
358 // We'll do a lookup for the name internally.
359 $id = intval( substr( $name, 1 ) );
360
361 if ( $database == '' ) {
362 $name = User::whoIs( $id );
363 } else {
364 $name = UserRightsProxy::whoIs( $database, $id );
365 }
366
367 if ( !$name ) {
368 return Status::newFatal( 'noname' );
369 }
370 } else {
371 $name = User::getCanonicalName( $name );
372 if ( $name === false ) {
373 // invalid name
374 return Status::newFatal( 'nosuchusershort', $username );
375 }
376 }
377
378 if ( $database == '' ) {
379 $user = User::newFromName( $name );
380 } else {
381 $user = UserRightsProxy::newFromName( $database, $name );
382 }
383
384 if ( !$user || $user->isAnon() ) {
385 return Status::newFatal( 'nosuchusershort', $username );
386 }
387
388 return Status::newGood( $user );
389 }
390
391 function makeGroupNameList( $ids ) {
392 if ( empty( $ids ) ) {
393 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
394 } else {
395 return implode( ', ', $ids );
396 }
397 }
398
399 /**
400 * Make a list of group names to be stored as parameter for log entries
401 *
402 * @deprecated since 1.21; use LogFormatter instead.
403 * @param array $ids
404 * @return string
405 */
406 function makeGroupNameListForLog( $ids ) {
407 wfDeprecated( __METHOD__, '1.21' );
408
409 if ( empty( $ids ) ) {
410 return '';
411 } else {
412 return $this->makeGroupNameList( $ids );
413 }
414 }
415
416 /**
417 * Output a form to allow searching for a user
418 */
419 function switchForm() {
420 global $wgScript;
421 $this->getOutput()->addHTML(
422 Html::openElement(
423 'form',
424 array(
425 'method' => 'get',
426 'action' => $wgScript,
427 'name' => 'uluser',
428 'id' => 'mw-userrights-form1'
429 )
430 ) .
431 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
432 Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
433 Xml::inputLabel(
434 $this->msg( 'userrights-user-editname' )->text(),
435 'user',
436 'username',
437 30,
438 str_replace( '_', ' ', $this->mTarget ),
439 array( 'autofocus' => true )
440 ) . ' ' .
441 Xml::submitButton( $this->msg( 'editusergroup' )->text() ) .
442 Html::closeElement( 'fieldset' ) .
443 Html::closeElement( 'form' ) . "\n"
444 );
445 }
446
447 /**
448 * Go through used and available groups and return the ones that this
449 * form will be able to manipulate based on the current user's system
450 * permissions.
451 *
452 * @param array $groups List of groups the given user is in
453 * @return array Tuple of addable, then removable groups
454 */
455 protected function splitGroups( $groups ) {
456 list( $addable, $removable, $addself, $removeself ) = array_values( $this->changeableGroups() );
457
458 $removable = array_intersect(
459 array_merge( $this->isself ? $removeself : array(), $removable ),
460 $groups
461 ); // Can't remove groups the user doesn't have
462 $addable = array_diff(
463 array_merge( $this->isself ? $addself : array(), $addable ),
464 $groups
465 ); // Can't add groups the user does have
466
467 return array( $addable, $removable );
468 }
469
470 /**
471 * Show the form to edit group memberships.
472 *
473 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
474 * @param array $groups Array of groups the user is in
475 */
476 protected function showEditUserGroupsForm( $user, $groups ) {
477 $list = array();
478 $membersList = array();
479 foreach ( $groups as $group ) {
480 $list[] = self::buildGroupLink( $group );
481 $membersList[] = self::buildGroupMemberLink( $group );
482 }
483
484 $autoList = array();
485 $autoMembersList = array();
486 if ( $user instanceof User ) {
487 foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
488 $autoList[] = self::buildGroupLink( $group );
489 $autoMembersList[] = self::buildGroupMemberLink( $group );
490 }
491 }
492
493 $language = $this->getLanguage();
494 $displayedList = $this->msg( 'userrights-groupsmember-type',
495 $language->listToText( $list ),
496 $language->listToText( $membersList )
497 )->plain();
498 $displayedAutolist = $this->msg( 'userrights-groupsmember-type',
499 $language->listToText( $autoList ),
500 $language->listToText( $autoMembersList )
501 )->plain();
502
503 $grouplist = '';
504 $count = count( $list );
505 if ( $count > 0 ) {
506 $grouplist = $this->msg( 'userrights-groupsmember', $count, $user->getName() )->parse();
507 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
508 }
509
510 $count = count( $autoList );
511 if ( $count > 0 ) {
512 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto', $count, $user->getName() )
513 ->parse();
514 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
515 }
516
517 $userToolLinks = Linker::userToolLinks(
518 $user->getId(),
519 $user->getName(),
520 false, /* default for redContribsWhenNoEdits */
521 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
522 );
523
524 $this->getOutput()->addHTML(
525 Xml::openElement(
526 'form',
527 array(
528 'method' => 'post',
529 'action' => $this->getPageTitle()->getLocalURL(),
530 'name' => 'editGroup',
531 'id' => 'mw-userrights-form2'
532 )
533 ) .
534 Html::hidden( 'user', $this->mTarget ) .
535 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
536 Html::hidden(
537 'conflictcheck-originalgroups',
538 implode( ',', $user->getGroups() )
539 ) . // Conflict detection
540 Xml::openElement( 'fieldset' ) .
541 Xml::element(
542 'legend',
543 array(),
544 $this->msg( 'userrights-editusergroup', $user->getName() )->text()
545 ) .
546 $this->msg( 'editinguser' )->params( wfEscapeWikiText( $user->getName() ) )
547 ->rawParams( $userToolLinks )->parse() .
548 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
549 $grouplist .
550 $this->groupCheckboxes( $groups, $user ) .
551 Xml::openElement( 'table', array( 'id' => 'mw-userrights-table-outer' ) ) .
552 "<tr>
553 <td class='mw-label'>" .
554 Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
555 "</td>
556 <td class='mw-input'>" .
557 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
558 array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
559 "</td>
560 </tr>
561 <tr>
562 <td></td>
563 <td class='mw-submit'>" .
564 Xml::submitButton( $this->msg( 'saveusergroups' )->text(),
565 array( 'name' => 'saveusergroups' ) +
566 Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
567 ) .
568 "</td>
569 </tr>" .
570 Xml::closeElement( 'table' ) . "\n" .
571 Xml::closeElement( 'fieldset' ) .
572 Xml::closeElement( 'form' ) . "\n"
573 );
574 }
575
576 /**
577 * Format a link to a group description page
578 *
579 * @param string $group
580 * @return string
581 */
582 private static function buildGroupLink( $group ) {
583 return User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
584 }
585
586 /**
587 * Format a link to a group member description page
588 *
589 * @param string $group
590 * @return string
591 */
592 private static function buildGroupMemberLink( $group ) {
593 return User::makeGroupLinkHtml( $group, User::getGroupMember( $group ) );
594 }
595
596 /**
597 * Returns an array of all groups that may be edited
598 * @return array Array of groups that may be edited.
599 */
600 protected static function getAllGroups() {
601 return User::getAllGroups();
602 }
603
604 /**
605 * Adds a table with checkboxes where you can select what groups to add/remove
606 *
607 * @todo Just pass the username string?
608 * @param array $usergroups Groups the user belongs to
609 * @param User $user
610 * @return string XHTML table element with checkboxes
611 */
612 private function groupCheckboxes( $usergroups, $user ) {
613 $allgroups = $this->getAllGroups();
614 $ret = '';
615
616 // Put all column info into an associative array so that extensions can
617 // more easily manage it.
618 $columns = array( 'unchangeable' => array(), 'changeable' => array() );
619
620 foreach ( $allgroups as $group ) {
621 $set = in_array( $group, $usergroups );
622 // Should the checkbox be disabled?
623 $disabled = !(
624 ( $set && $this->canRemove( $group ) ) ||
625 ( !$set && $this->canAdd( $group ) ) );
626 // Do we need to point out that this action is irreversible?
627 $irreversible = !$disabled && (
628 ( $set && !$this->canAdd( $group ) ) ||
629 ( !$set && !$this->canRemove( $group ) ) );
630
631 $checkbox = array(
632 'set' => $set,
633 'disabled' => $disabled,
634 'irreversible' => $irreversible
635 );
636
637 if ( $disabled ) {
638 $columns['unchangeable'][$group] = $checkbox;
639 } else {
640 $columns['changeable'][$group] = $checkbox;
641 }
642 }
643
644 // Build the HTML table
645 $ret .= Xml::openElement( 'table', array( 'class' => 'mw-userrights-groups' ) ) .
646 "<tr>\n";
647 foreach ( $columns as $name => $column ) {
648 if ( $column === array() ) {
649 continue;
650 }
651 // Messages: userrights-changeable-col, userrights-unchangeable-col
652 $ret .= Xml::element(
653 'th',
654 null,
655 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
656 );
657 }
658
659 $ret .= "</tr>\n<tr>\n";
660 foreach ( $columns as $column ) {
661 if ( $column === array() ) {
662 continue;
663 }
664 $ret .= "\t<td style='vertical-align:top;'>\n";
665 foreach ( $column as $group => $checkbox ) {
666 $attr = $checkbox['disabled'] ? array( 'disabled' => 'disabled' ) : array();
667
668 $member = User::getGroupMember( $group, $user->getName() );
669 if ( $checkbox['irreversible'] ) {
670 $text = $this->msg( 'userrights-irreversible-marker', $member )->escaped();
671 } else {
672 $text = htmlspecialchars( $member );
673 }
674 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
675 "wpGroup-" . $group, $checkbox['set'], $attr );
676 $ret .= "\t\t" . ( $checkbox['disabled']
677 ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkboxHtml )
678 : $checkboxHtml
679 ) . "<br />\n";
680 }
681 $ret .= "\t</td>\n";
682 }
683 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
684
685 return $ret;
686 }
687
688 /**
689 * @param string $group The name of the group to check
690 * @return bool Can we remove the group?
691 */
692 private function canRemove( $group ) {
693 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks, PHP.
694 $groups = $this->changeableGroups();
695
696 return in_array(
697 $group,
698 $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
699 );
700 }
701
702 /**
703 * @param string $group The name of the group to check
704 * @return bool Can we add the group?
705 */
706 private function canAdd( $group ) {
707 $groups = $this->changeableGroups();
708
709 return in_array(
710 $group,
711 $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
712 );
713 }
714
715 /**
716 * Returns $this->getUser()->changeableGroups()
717 *
718 * @return array Array(
719 * 'add' => array( addablegroups ),
720 * 'remove' => array( removablegroups ),
721 * 'add-self' => array( addablegroups to self ),
722 * 'remove-self' => array( removable groups from self )
723 * )
724 */
725 function changeableGroups() {
726 return $this->getUser()->changeableGroups();
727 }
728
729 /**
730 * Show a rights log fragment for the specified user
731 *
732 * @param User $user User to show log for
733 * @param OutputPage $output OutputPage to use
734 */
735 protected function showLogFragment( $user, $output ) {
736 $rightsLogPage = new LogPage( 'rights' );
737 $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
738 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
739 }
740
741 protected function getGroupName() {
742 return 'users';
743 }
744 }