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