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