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