]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/specials/SpecialUserrights.php
MediaWiki 1.15.0
[autoinstalls/mediawiki.git] / includes / specials / SpecialUserrights.php
1 <?php
2 /**
3  * Special page to allow managing user group membership
4  *
5  * @file
6  * @ingroup SpecialPage
7  */
8
9 /**
10  * A class to manage user levels rights.
11  * @ingroup SpecialPage
12  */
13 class UserrightsPage extends SpecialPage {
14         # The target of the local right-adjuster's interest.  Can be gotten from
15         # either a GET parameter or a subpage-style parameter, so have a member
16         # variable for it.
17         protected $mTarget;
18         protected $isself = false;
19
20         public function __construct() {
21                 parent::__construct( 'Userrights' );
22         }
23
24         public function isRestricted() {
25                 return true;
26         }
27
28         public function userCanExecute( $user ) {
29                 return $this->userCanChangeRights( $user, false );
30         }
31
32         public function userCanChangeRights( $user, $checkIfSelf = true ) {
33                 $available = $this->changeableGroups();
34                 return !empty( $available['add'] )
35                         or !empty( $available['remove'] )
36                         or ( ( $this->isself || !$checkIfSelf ) and
37                                 (!empty( $available['add-self'] )
38                                  or !empty( $available['remove-self'] )));
39         }
40
41         /**
42          * Manage forms to be shown according to posted data.
43          * Depending on the submit button used, call a form or a save function.
44          *
45          * @param $par Mixed: string if any subpage provided, else null
46          */
47         function execute( $par ) {
48                 // If the visitor doesn't have permissions to assign or remove
49                 // any groups, it's a bit silly to give them the user search prompt.
50                 global $wgUser, $wgRequest;
51
52                 if( $par ) {
53                         $this->mTarget = $par;
54                 } else {
55                         $this->mTarget = $wgRequest->getVal( 'user' );
56                 }
57
58                 if (!$this->mTarget) {
59                         /*
60                          * If the user specified no target, and they can only
61                          * edit their own groups, automatically set them as the
62                          * target.
63                          */
64                         $available = $this->changeableGroups();
65                         if (empty($available['add']) && empty($available['remove']))
66                                 $this->mTarget = $wgUser->getName();
67                 }
68
69                 if ($this->mTarget == $wgUser->getName())
70                         $this->isself = true;
71
72                 if( !$this->userCanChangeRights( $wgUser, true ) ) {
73                         // fixme... there may be intermediate groups we can mention.
74                         global $wgOut;
75                         $wgOut->showPermissionsErrorPage( array(
76                                 $wgUser->isAnon()
77                                         ? 'userrights-nologin'
78                                         : 'userrights-notallowed' ) );
79                         return;
80                 }
81
82                 if ( wfReadOnly() ) {
83                         global $wgOut;
84                         $wgOut->readOnlyPage();
85                         return;
86                 }
87
88                 $this->outputHeader();
89
90                 $this->setHeaders();
91
92                 // show the general form
93                 $this->switchForm();
94
95                 if( $wgRequest->wasPosted() ) {
96                         // save settings
97                         if( $wgRequest->getCheck( 'saveusergroups' ) ) {
98                                 $reason = $wgRequest->getVal( 'user-reason' );
99                                 $tok = $wgRequest->getVal( 'wpEditToken' );
100                                 if( $wgUser->matchEditToken( $tok, $this->mTarget ) ) {
101                                         $this->saveUserGroups(
102                                                 $this->mTarget,
103                                                 $reason
104                                         );
105                                         
106                                         global $wgOut;
107                                         
108                                         $url = $this->getSuccessURL();
109                                         $wgOut->redirect( $url );
110                                         return;
111                                 }
112                         }
113                 }
114
115                 // show some more forms
116                 if( $this->mTarget ) {
117                         $this->editUserGroupsForm( $this->mTarget );
118                 }
119         }
120         
121         function getSuccessURL() {
122                 return $this->getTitle( $this->mTarget )->getFullURL();
123         }
124
125         /**
126          * Save user groups changes in the database.
127          * Data comes from the editUserGroupsForm() form function
128          *
129          * @param $username String: username to apply changes to.
130          * @param $reason String: reason for group change
131          * @return null
132          */
133         function saveUserGroups( $username, $reason = '') {
134                 global $wgRequest, $wgUser, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
135
136                 $user = $this->fetchUser( $username );
137                 if( !$user ) {
138                         return;
139                 }
140
141                 $allgroups = $this->getAllGroups();
142                 $addgroup = array();
143                 $removegroup = array();
144
145                 // This could possibly create a highly unlikely race condition if permissions are changed between
146                 //  when the form is loaded and when the form is saved. Ignoring it for the moment.
147                 foreach ($allgroups as $group) {
148                         // We'll tell it to remove all unchecked groups, and add all checked groups.
149                         // Later on, this gets filtered for what can actually be removed
150                         if ($wgRequest->getCheck( "wpGroup-$group" )) {
151                                 $addgroup[] = $group;
152                         } else {
153                                 $removegroup[] = $group;
154                         }
155                 }
156
157                 // Validate input set...
158                 $changeable = $this->changeableGroups();
159                 $addable = array_merge( $changeable['add'], $this->isself ? $changeable['add-self'] : array() );
160                 $removable = array_merge( $changeable['remove'], $this->isself ? $changeable['remove-self'] : array() );
161
162                 $removegroup = array_unique(
163                         array_intersect( (array)$removegroup, $removable ) );
164                 $addgroup = array_unique(
165                         array_intersect( (array)$addgroup, $addable ) );
166
167                 $oldGroups = $user->getGroups();
168                 $newGroups = $oldGroups;
169                 // remove then add groups
170                 if( $removegroup ) {
171                         $newGroups = array_diff($newGroups, $removegroup);
172                         foreach( $removegroup as $group ) {
173                                 $user->removeGroup( $group );
174                         }
175                 }
176                 if( $addgroup ) {
177                         $newGroups = array_merge($newGroups, $addgroup);
178                         foreach( $addgroup as $group ) {
179                                 $user->addGroup( $group );
180                         }
181                 }
182                 $newGroups = array_unique( $newGroups );
183
184                 // Ensure that caches are cleared
185                 $user->invalidateCache();
186
187                 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
188                 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
189                 if( $user instanceof User ) {
190                         // hmmm
191                         wfRunHooks( 'UserRights', array( &$user, $addgroup, $removegroup ) );
192                 }
193
194                 if( $newGroups != $oldGroups ) {
195                         $this->addLogEntry( $user, $oldGroups, $newGroups );
196                 }
197         }
198         
199         /**
200          * Add a rights log entry for an action.
201          */
202         function addLogEntry( $user, $oldGroups, $newGroups ) {
203                 global $wgRequest;
204                 $log = new LogPage( 'rights' );
205
206                 $log->addEntry( 'rights',
207                         $user->getUserPage(),
208                         $wgRequest->getText( 'user-reason' ),
209                         array(
210                                 $this->makeGroupNameListForLog( $oldGroups ),
211                                 $this->makeGroupNameListForLog( $newGroups )
212                         )
213                 );
214         }
215
216         /**
217          * Edit user groups membership
218          * @param $username String: name of the user.
219          */
220         function editUserGroupsForm( $username ) {
221                 global $wgOut;
222
223                 $user = $this->fetchUser( $username );
224                 if( !$user ) {
225                         return;
226                 }
227
228                 $groups = $user->getGroups();
229
230                 $this->showEditUserGroupsForm( $user, $groups );
231
232                 // This isn't really ideal logging behavior, but let's not hide the
233                 // interwiki logs if we're using them as is.
234                 $this->showLogFragment( $user, $wgOut );
235         }
236
237         /**
238          * Normalize the input username, which may be local or remote, and
239          * return a user (or proxy) object for manipulating it.
240          *
241          * Side effects: error output for invalid access
242          * @return mixed User, UserRightsProxy, or null
243          */
244         function fetchUser( $username ) {
245                 global $wgOut, $wgUser, $wgUserrightsInterwikiDelimiter;
246
247                 $parts = explode( $wgUserrightsInterwikiDelimiter, $username );
248                 if( count( $parts ) < 2 ) {
249                         $name = trim( $username );
250                         $database = '';
251                 } else {
252                         list( $name, $database ) = array_map( 'trim', $parts );
253
254                         if( !$wgUser->isAllowed( 'userrights-interwiki' ) ) {
255                                 $wgOut->addWikiMsg( 'userrights-no-interwiki' );
256                                 return null;
257                         }
258                         if( !UserRightsProxy::validDatabase( $database ) ) {
259                                 $wgOut->addWikiMsg( 'userrights-nodatabase', $database );
260                                 return null;
261                         }
262                 }
263
264                 if( $name == '' ) {
265                         $wgOut->addWikiMsg( 'nouserspecified' );
266                         return false;
267                 }
268
269                 if( $name{0} == '#' ) {
270                         // Numeric ID can be specified...
271                         // We'll do a lookup for the name internally.
272                         $id = intval( substr( $name, 1 ) );
273
274                         if( $database == '' ) {
275                                 $name = User::whoIs( $id );
276                         } else {
277                                 $name = UserRightsProxy::whoIs( $database, $id );
278                         }
279
280                         if( !$name ) {
281                                 $wgOut->addWikiMsg( 'noname' );
282                                 return null;
283                         }
284                 }
285
286                 if( $database == '' ) {
287                         $user = User::newFromName( $name );
288                 } else {
289                         $user = UserRightsProxy::newFromName( $database, $name );
290                 }
291
292                 if( !$user || $user->isAnon() ) {
293                         $wgOut->addWikiMsg( 'nosuchusershort', $username );
294                         return null;
295                 }
296
297                 return $user;
298         }
299
300         function makeGroupNameList( $ids ) {
301                 if( empty( $ids ) ) {
302                         return wfMsgForContent( 'rightsnone' );
303                 } else {
304                         return implode( ', ', $ids );
305                 }
306         }
307
308         function makeGroupNameListForLog( $ids ) {
309                 if( empty( $ids ) ) {
310                         return '';
311                 } else {
312                         return $this->makeGroupNameList( $ids );
313                 }
314         }
315
316         /**
317          * Output a form to allow searching for a user
318          */
319         function switchForm() {
320                 global $wgOut, $wgScript;
321                 $wgOut->addHTML(
322                         Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript, 'name' => 'uluser', 'id' => 'mw-userrights-form1' ) ) .
323                         Xml::hidden( 'title',  $this->getTitle()->getPrefixedText() ) .
324                         Xml::openElement( 'fieldset' ) .
325                         Xml::element( 'legend', array(), wfMsg( 'userrights-lookup-user' ) ) .
326                         Xml::inputLabel( wfMsg( 'userrights-user-editname' ), 'user', 'username', 30, $this->mTarget ) . ' ' .
327                         Xml::submitButton( wfMsg( 'editusergroup' ) ) .
328                         Xml::closeElement( 'fieldset' ) .
329                         Xml::closeElement( 'form' ) . "\n"
330                 );
331         }
332
333         /**
334          * Go through used and available groups and return the ones that this
335          * form will be able to manipulate based on the current user's system
336          * permissions.
337          *
338          * @param $groups Array: list of groups the given user is in
339          * @return Array:  Tuple of addable, then removable groups
340          */
341         protected function splitGroups( $groups ) {
342                 list($addable, $removable, $addself, $removeself) = array_values( $this->changeableGroups() );
343
344                 $removable = array_intersect(
345                                 array_merge( $this->isself ? $removeself : array(), $removable ),
346                                 $groups ); // Can't remove groups the user doesn't have
347                 $addable   = array_diff(
348                                 array_merge( $this->isself ? $addself : array(), $addable ),
349                                 $groups ); // Can't add groups the user does have
350
351                 return array( $addable, $removable );
352         }
353
354         /**
355          * Show the form to edit group memberships.
356          *
357          * @param $user      User or UserRightsProxy you're editing
358          * @param $groups    Array:  Array of groups the user is in
359          */
360         protected function showEditUserGroupsForm( $user, $groups ) {
361                 global $wgOut, $wgUser, $wgLang;
362
363                 $list = array();
364                 foreach( $groups as $group )
365                         $list[] = self::buildGroupLink( $group );
366
367                 $grouplist = '';
368                 if( count( $list ) > 0 ) {
369                         $grouplist = wfMsgHtml( 'userrights-groupsmember' );
370                         $grouplist = '<p>' . $grouplist  . ' ' . $wgLang->listToText( $list ) . '</p>';
371                 }
372                 $wgOut->addHTML(
373                         Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalURL(), 'name' => 'editGroup', 'id' => 'mw-userrights-form2' ) ) .
374                         Xml::hidden( 'user', $this->mTarget ) .
375                         Xml::hidden( 'wpEditToken', $wgUser->editToken( $this->mTarget ) ) .
376                         Xml::openElement( 'fieldset' ) .
377                         Xml::element( 'legend', array(), wfMsg( 'userrights-editusergroup' ) ) .
378                         wfMsgExt( 'editinguser', array( 'parse' ), wfEscapeWikiText( $user->getName() ) ) .
379                         wfMsgExt( 'userrights-groups-help', array( 'parse' ) ) .
380                         $grouplist .
381                         Xml::tags( 'p', null, $this->groupCheckboxes( $groups ) ) .
382                         Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-userrights-table-outer' ) ) .
383                                 "<tr>
384                                         <td class='mw-label'>" .
385                                                 Xml::label( wfMsg( 'userrights-reason' ), 'wpReason' ) .
386                                         "</td>
387                                         <td class='mw-input'>" .
388                                                 Xml::input( 'user-reason', 60, false, array( 'id' => 'wpReason', 'maxlength' => 255 ) ) .
389                                         "</td>
390                                 </tr>
391                                 <tr>
392                                         <td></td>
393                                         <td class='mw-submit'>" .
394                                                 Xml::submitButton( wfMsg( 'saveusergroups' ), array( 'name' => 'saveusergroups', 'accesskey' => 's' ) ) .
395                                         "</td>
396                                 </tr>" .
397                         Xml::closeElement( 'table' ) . "\n" .
398                         Xml::closeElement( 'fieldset' ) .
399                         Xml::closeElement( 'form' ) . "\n"
400                 );
401         }
402
403         /**
404          * Format a link to a group description page
405          *
406          * @param $group string
407          * @return string
408          */
409         private static function buildGroupLink( $group ) {
410                 static $cache = array();
411                 if( !isset( $cache[$group] ) )
412                         $cache[$group] = User::makeGroupLinkHtml( $group, User::getGroupName( $group ) );
413                 return $cache[$group];
414         }
415         
416         /**
417          * Returns an array of all groups that may be edited
418          * @return array Array of groups that may be edited.
419          */
420          protected static function getAllGroups() {
421                 return User::getAllGroups();
422          }
423
424         /**
425          * Adds a table with checkboxes where you can select what groups to add/remove
426          *
427          * @param $usergroups Array: groups the user belongs to
428          * @return string XHTML table element with checkboxes
429          */
430         private function groupCheckboxes( $usergroups ) {
431                 $allgroups = $this->getAllGroups();
432                 $ret = '';
433
434                 $column = 1;
435                 $settable_col = '';
436                 $unsettable_col = '';
437
438                 foreach ($allgroups as $group) {
439                         $set = in_array( $group, $usergroups );
440                         # Should the checkbox be disabled?
441                         $disabled = !(
442                                 ( $set && $this->canRemove( $group ) ) ||
443                                 ( !$set && $this->canAdd( $group ) ) );
444                         # Do we need to point out that this action is irreversible?
445                         $irreversible = !$disabled && (
446                                 ($set && !$this->canAdd( $group )) ||
447                                 (!$set && !$this->canRemove( $group ) ) );
448
449                         $attr = $disabled ? array( 'disabled' => 'disabled' ) : array();
450                         $text = $irreversible
451                                 ? wfMsgHtml( 'userrights-irreversible-marker', User::getGroupMember( $group ) )
452                                 : User::getGroupMember( $group );
453                         $checkbox = Xml::checkLabel( $text, "wpGroup-$group",
454                                 "wpGroup-$group", $set, $attr );
455                         $checkbox = $disabled ? Xml::tags( 'span', array( 'class' => 'mw-userrights-disabled' ), $checkbox ) : $checkbox;
456
457                         if ($disabled) {
458                                 $unsettable_col .= "$checkbox<br />\n";
459                         } else {
460                                 $settable_col .= "$checkbox<br />\n";
461                         }
462                 }
463
464                 if ($column) {
465                         $ret .= Xml::openElement( 'table', array( 'border' => '0', 'class' => 'mw-userrights-groups' ) ) .
466                                 "<tr>
467 ";
468                         if( $settable_col !== '' ) {
469                                 $ret .= xml::element( 'th', null, wfMsg( 'userrights-changeable-col' ) );
470                         }
471                         if( $unsettable_col !== '' ) {
472                                 $ret .= xml::element( 'th', null, wfMsg( 'userrights-unchangeable-col' ) );
473                         }
474                         $ret.= "</tr>
475                                 <tr>
476 ";
477                         if( $settable_col !== '' ) {
478                                 $ret .=
479 "                                       <td style='vertical-align:top;'>
480                                                 $settable_col
481                                         </td>
482 ";
483                         }
484                         if( $unsettable_col !== '' ) {
485                                 $ret .=
486 "                                       <td style='vertical-align:top;'>
487                                                 $unsettable_col
488                                         </td>
489 ";
490                         }
491                         $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
492                 }
493
494                 return $ret;
495         }
496
497         /**
498          * @param  $group String: the name of the group to check
499          * @return bool Can we remove the group?
500          */
501         private function canRemove( $group ) {
502                 // $this->changeableGroups()['remove'] doesn't work, of course. Thanks,
503                 // PHP.
504                 $groups = $this->changeableGroups();
505                 return in_array( $group, $groups['remove'] ) || ($this->isself && in_array( $group, $groups['remove-self'] ));
506         }
507
508         /**
509          * @param $group string: the name of the group to check
510          * @return bool Can we add the group?
511          */
512         private function canAdd( $group ) {
513                 $groups = $this->changeableGroups();
514                 return in_array( $group, $groups['add'] ) || ($this->isself && in_array( $group, $groups['add-self'] ));
515         }
516
517         /**
518          * Returns an array of the groups that the user can add/remove.
519          *
520          * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
521          */
522         function changeableGroups() {
523                 global $wgUser;
524
525                 if( $wgUser->isAllowed( 'userrights' ) ) {
526                         // This group gives the right to modify everything (reverse-
527                         // compatibility with old "userrights lets you change
528                         // everything")
529                         // Using array_merge to make the groups reindexed
530                         $all = array_merge( User::getAllGroups() );
531                         return array(
532                                 'add' => $all,
533                                 'remove' => $all,
534                                 'add-self' => array(),
535                                 'remove-self' => array()
536                         );
537                 }
538
539                 // Okay, it's not so simple, we will have to go through the arrays
540                 $groups = array(
541                                 'add' => array(),
542                                 'remove' => array(),
543                                 'add-self' => array(),
544                                 'remove-self' => array() );
545                 $addergroups = $wgUser->getEffectiveGroups();
546
547                 foreach ($addergroups as $addergroup) {
548                         $groups = array_merge_recursive(
549                                 $groups, $this->changeableByGroup($addergroup)
550                         );
551                         $groups['add']    = array_unique( $groups['add'] );
552                         $groups['remove'] = array_unique( $groups['remove'] );
553                         $groups['add-self'] = array_unique( $groups['add-self'] );
554                         $groups['remove-self'] = array_unique( $groups['remove-self'] );
555                 }
556                 
557                 // Run a hook because we can
558                 wfRunHooks( 'UserrightsChangeableGroups', array( $this, $wgUser, $addergroups, &$groups ) );
559                 
560                 return $groups;
561         }
562
563         /**
564          * Returns an array of the groups that a particular group can add/remove.
565          *
566          * @param $group String: the group to check for whether it can add/remove
567          * @return Array array( 'add' => array( addablegroups ), 'remove' => array( removablegroups ) , 'add-self' => array( addablegroups to self), 'remove-self' => array( removable groups from self) )
568          */
569         private function changeableByGroup( $group ) {
570                 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
571
572                 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
573                 if( empty($wgAddGroups[$group]) ) {
574                         // Don't add anything to $groups
575                 } elseif( $wgAddGroups[$group] === true ) {
576                         // You get everything
577                         $groups['add'] = User::getAllGroups();
578                 } elseif( is_array($wgAddGroups[$group]) ) {
579                         $groups['add'] = $wgAddGroups[$group];
580                 }
581
582                 // Same thing for remove
583                 if( empty($wgRemoveGroups[$group]) ) {
584                 } elseif($wgRemoveGroups[$group] === true ) {
585                         $groups['remove'] = User::getAllGroups();
586                 } elseif( is_array($wgRemoveGroups[$group]) ) {
587                         $groups['remove'] = $wgRemoveGroups[$group];
588                 }
589                 
590                 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
591                 if( empty($wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
592                         foreach($wgGroupsAddToSelf as $key => $value) {
593                                 if( is_int($key) ) {
594                                         $wgGroupsAddToSelf['user'][] = $value;
595                                 }
596                         }
597                 }
598                 
599                 if( empty($wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
600                         foreach($wgGroupsRemoveFromSelf as $key => $value) {
601                                 if( is_int($key) ) {
602                                         $wgGroupsRemoveFromSelf['user'][] = $value;
603                                 }
604                         }
605                 }
606                 
607                 // Now figure out what groups the user can add to him/herself
608                 if( empty($wgGroupsAddToSelf[$group]) ) {
609                 } elseif( $wgGroupsAddToSelf[$group] === true ) {
610                         // No idea WHY this would be used, but it's there
611                         $groups['add-self'] = User::getAllGroups();
612                 } elseif( is_array($wgGroupsAddToSelf[$group]) ) {
613                         $groups['add-self'] = $wgGroupsAddToSelf[$group];
614                 }
615                 
616                 if( empty($wgGroupsRemoveFromSelf[$group]) ) {
617                 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
618                         $groups['remove-self'] = User::getAllGroups();
619                 } elseif( is_array($wgGroupsRemoveFromSelf[$group]) ) {
620                         $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
621                 }
622                 
623                 return $groups;
624         }
625
626         /**
627          * Show a rights log fragment for the specified user
628          *
629          * @param $user User to show log for
630          * @param $output OutputPage to use
631          */
632         protected function showLogFragment( $user, $output ) {
633                 $output->addHTML( Xml::element( 'h2', null, LogPage::logName( 'rights' ) . "\n" ) );
634                 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage()->getPrefixedText() );
635         }
636 }