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