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