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