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