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