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