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