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