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