Merge "UsersMultiselect widget and form field."
[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 /**
31 * The target of the local right-adjuster's interest. Can be gotten from
32 * either a GET parameter or a subpage-style parameter, so have a member
33 * variable for it.
34 * @var null|string $mTarget
35 */
36 protected $mTarget;
37 /*
38 * @var null|User $mFetchedUser The user object of the target username or null.
39 */
40 protected $mFetchedUser = null;
41 protected $isself = false;
42
43 public function __construct() {
44 parent::__construct( 'Userrights' );
45 }
46
47 public function doesWrites() {
48 return true;
49 }
50
51 /**
52 * Check whether the current user (from context) can change the target user's rights.
53 *
54 * @param User $targetUser User whose rights are being changed
55 * @param bool $checkIfSelf If false, assume that the current user can add/remove groups defined
56 * in $wgGroupsAddToSelf / $wgGroupsRemoveFromSelf, without checking if it's the same as target
57 * user
58 * @return bool
59 */
60 public function userCanChangeRights( $targetUser, $checkIfSelf = true ) {
61 $isself = $this->getUser()->equals( $targetUser );
62
63 $available = $this->changeableGroups();
64 if ( $targetUser->getId() == 0 ) {
65 return false;
66 }
67
68 return !empty( $available['add'] )
69 || !empty( $available['remove'] )
70 || ( ( $isself || !$checkIfSelf ) &&
71 ( !empty( $available['add-self'] )
72 || !empty( $available['remove-self'] ) ) );
73 }
74
75 /**
76 * Manage forms to be shown according to posted data.
77 * Depending on the submit button used, call a form or a save function.
78 *
79 * @param string|null $par String if any subpage provided, else null
80 * @throws UserBlockedError|PermissionsError
81 */
82 public function execute( $par ) {
83 $user = $this->getUser();
84 $request = $this->getRequest();
85 $session = $request->getSession();
86 $out = $this->getOutput();
87
88 $out->addModules( [ 'mediawiki.special.userrights' ] );
89
90 if ( $par !== null ) {
91 $this->mTarget = $par;
92 } else {
93 $this->mTarget = $request->getVal( 'user' );
94 }
95
96 if ( is_string( $this->mTarget ) ) {
97 $this->mTarget = trim( $this->mTarget );
98 }
99
100 if ( $this->mTarget !== null && User::getCanonicalName( $this->mTarget ) === $user->getName() ) {
101 $this->isself = true;
102 }
103
104 $fetchedStatus = $this->fetchUser( $this->mTarget, true );
105 if ( $fetchedStatus->isOK() ) {
106 $this->mFetchedUser = $fetchedStatus->value;
107 if ( $this->mFetchedUser instanceof User ) {
108 // Set the 'relevant user' in the skin, so it displays links like Contributions,
109 // User logs, UserRights, etc.
110 $this->getSkin()->setRelevantUser( $this->mFetchedUser );
111 }
112 }
113
114 // show a successbox, if the user rights was saved successfully
115 if (
116 $session->get( 'specialUserrightsSaveSuccess' ) &&
117 $this->mFetchedUser !== null
118 ) {
119 // Remove session data for the success message
120 $session->remove( 'specialUserrightsSaveSuccess' );
121
122 $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
123 $out->addHTML(
124 Html::rawElement(
125 'div',
126 [
127 'class' => 'mw-notify-success successbox',
128 'id' => 'mw-preferences-success',
129 'data-mw-autohide' => 'false',
130 ],
131 Html::element(
132 'p',
133 [],
134 $this->msg( 'savedrights', $this->mFetchedUser->getName() )->text()
135 )
136 )
137 );
138 }
139
140 $this->setHeaders();
141 $this->outputHeader();
142
143 $out->addModuleStyles( 'mediawiki.special' );
144 $this->addHelpLink( 'Help:Assigning permissions' );
145
146 $this->switchForm();
147
148 if (
149 $request->wasPosted() &&
150 $request->getCheck( 'saveusergroups' ) &&
151 $this->mTarget !== null &&
152 $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
153 ) {
154 /*
155 * If the user is blocked and they only have "partial" access
156 * (e.g. they don't have the userrights permission), then don't
157 * allow them to change any user rights.
158 */
159 if ( $user->isBlocked() && !$user->isAllowed( 'userrights' ) ) {
160 throw new UserBlockedError( $user->getBlock() );
161 }
162
163 $this->checkReadOnly();
164
165 // save settings
166 if ( !$fetchedStatus->isOK() ) {
167 $this->getOutput()->addWikiText( $fetchedStatus->getWikiText() );
168
169 return;
170 }
171
172 $targetUser = $this->mFetchedUser;
173 if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (bug 61252)
174 $targetUser->clearInstanceCache(); // bug 38989
175 }
176
177 if ( $request->getVal( 'conflictcheck-originalgroups' )
178 !== implode( ',', $targetUser->getGroups() )
179 ) {
180 $out->addWikiMsg( 'userrights-conflict' );
181 } else {
182 $status = $this->saveUserGroups(
183 $this->mTarget,
184 $request->getVal( 'user-reason' ),
185 $targetUser
186 );
187
188 if ( $status->isOK() ) {
189 // Set session data for the success message
190 $session->set( 'specialUserrightsSaveSuccess', 1 );
191
192 $out->redirect( $this->getSuccessURL() );
193 return;
194 } else {
195 // Print an error message and redisplay the form
196 $out->addWikiText( '<div class="error">' . $status->getWikiText() . '</div>' );
197 }
198 }
199 }
200
201 // show some more forms
202 if ( $this->mTarget !== null ) {
203 $this->editUserGroupsForm( $this->mTarget );
204 }
205 }
206
207 function getSuccessURL() {
208 return $this->getPageTitle( $this->mTarget )->getFullURL();
209 }
210
211 /**
212 * Returns true if this user rights form can set and change user group expiries.
213 * Subclasses may wish to override this to return false.
214 *
215 * @return bool
216 */
217 public function canProcessExpiries() {
218 return !$this->getConfig()->get( 'DisableUserGroupExpiry' );
219 }
220
221 /**
222 * Converts a user group membership expiry string into a timestamp. Words like
223 * 'existing' or 'other' should have been filtered out before calling this
224 * function.
225 *
226 * @param string $expiry
227 * @return string|null|false A string containing a valid timestamp, or null
228 * if the expiry is infinite, or false if the timestamp is not valid
229 */
230 public static function expiryToTimestamp( $expiry ) {
231 if ( wfIsInfinity( $expiry ) ) {
232 return null;
233 }
234
235 $unix = strtotime( $expiry );
236
237 if ( !$unix || $unix === -1 ) {
238 return false;
239 }
240
241 // @todo FIXME: Non-qualified absolute times are not in users specified timezone
242 // and there isn't notice about it in the ui (see ProtectionForm::getExpiry)
243 return wfTimestamp( TS_MW, $unix );
244 }
245
246 /**
247 * Save user groups changes in the database.
248 * Data comes from the editUserGroupsForm() form function
249 *
250 * @param string $username Username to apply changes to.
251 * @param string $reason Reason for group change
252 * @param User|UserRightsProxy $user Target user object.
253 * @return Status
254 */
255 protected function saveUserGroups( $username, $reason, $user ) {
256 $allgroups = $this->getAllGroups();
257 $addgroup = [];
258 $groupExpiries = []; // associative array of (group name => expiry)
259 $removegroup = [];
260
261 // This could possibly create a highly unlikely race condition if permissions are changed between
262 // when the form is loaded and when the form is saved. Ignoring it for the moment.
263 foreach ( $allgroups as $group ) {
264 // We'll tell it to remove all unchecked groups, and add all checked groups.
265 // Later on, this gets filtered for what can actually be removed
266 if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
267 $addgroup[] = $group;
268
269 if ( $this->canProcessExpiries() ) {
270 // read the expiry information from the request
271 $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" );
272 if ( $expiryDropdown === 'other' ) {
273 $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" );
274 } elseif ( $expiryDropdown !== 'existing' ) {
275 $expiryValue = $expiryDropdown;
276 } else {
277 continue;
278 }
279
280 // validate the expiry
281 $groupExpiries[$group] = self::expiryToTimestamp( $expiryValue );
282
283 if ( $groupExpiries[$group] === false ) {
284 return Status::newFatal( 'userrights-invalid-expiry', $group );
285 }
286
287 // not allowed to have things expiring in the past
288 if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) {
289 return Status::newFatal( 'userrights-expiry-in-past', $group );
290 }
291 }
292 } else {
293 $removegroup[] = $group;
294 }
295 }
296
297 $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries );
298
299 return Status::newGood();
300 }
301
302 /**
303 * Save user groups changes in the database.
304 *
305 * @param User|UserRightsProxy $user
306 * @param array $add Array of groups to add
307 * @param array $remove Array of groups to remove
308 * @param string $reason Reason for group change
309 * @param array $tags Array of change tags to add to the log entry
310 * @param array $groupExpiries Associative array of (group name => expiry),
311 * containing only those groups that are to have new expiry values set
312 * @return array Tuple of added, then removed groups
313 */
314 function doSaveUserGroups( $user, $add, $remove, $reason = '', $tags = [],
315 $groupExpiries = [] ) {
316
317 // Validate input set...
318 $isself = $user->getName() == $this->getUser()->getName();
319 $groups = $user->getGroups();
320 $changeable = $this->changeableGroups();
321 $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : [] );
322 $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : [] );
323
324 $remove = array_unique(
325 array_intersect( (array)$remove, $removable, $groups ) );
326 $add = array_intersect( (array)$add, $addable );
327
328 // add only groups that are not already present or that need their expiry updated
329 $add = array_filter( $add,
330 function( $group ) use ( $groups, $groupExpiries ) {
331 return !in_array( $group, $groups ) || array_key_exists( $group, $groupExpiries );
332 } );
333
334 Hooks::run( 'ChangeUserGroups', [ $this->getUser(), $user, &$add, &$remove ] );
335
336 $oldGroups = $groups;
337 $oldUGMs = $user->getGroupMemberships();
338 $newGroups = $oldGroups;
339
340 // Remove groups, then add new ones/update expiries of existing ones
341 if ( $remove ) {
342 foreach ( $remove as $index => $group ) {
343 if ( !$user->removeGroup( $group ) ) {
344 unset( $remove[$index] );
345 }
346 }
347 $newGroups = array_diff( $newGroups, $remove );
348 }
349 if ( $add ) {
350 foreach ( $add as $index => $group ) {
351 $expiry = isset( $groupExpiries[$group] ) ? $groupExpiries[$group] : null;
352 if ( !$user->addGroup( $group, $expiry ) ) {
353 unset( $add[$index] );
354 }
355 }
356 $newGroups = array_merge( $newGroups, $add );
357 }
358 $newGroups = array_unique( $newGroups );
359 $newUGMs = $user->getGroupMemberships();
360
361 // Ensure that caches are cleared
362 $user->invalidateCache();
363
364 // update groups in external authentication database
365 Hooks::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(), $reason ] );
366 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin(
367 'updateExternalDBGroups', [ $user, $add, $remove ]
368 );
369
370 wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
371 wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
372 wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) . "\n" );
373 wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) . "\n" );
374 // Deprecated in favor of UserGroupsChanged hook
375 Hooks::run( 'UserRights', [ &$user, $add, $remove ], '1.26' );
376
377 // Only add a log entry if something actually changed
378 if ( $newGroups != $oldGroups || $newUGMs != $oldUGMs ) {
379 $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs );
380 }
381
382 return [ $add, $remove ];
383 }
384
385 /**
386 * Serialise a UserGroupMembership object for storage in the log_params section
387 * of the logging table. Only keeps essential data, removing redundant fields.
388 *
389 * @param UserGroupMembership|null $ugm May be null if things get borked
390 * @return array
391 */
392 protected static function serialiseUgmForLog( $ugm ) {
393 if ( !$ugm instanceof UserGroupMembership ) {
394 return null;
395 }
396 return [ 'expiry' => $ugm->getExpiry() ];
397 }
398
399 /**
400 * Add a rights log entry for an action.
401 * @param User|UserRightsProxy $user
402 * @param array $oldGroups
403 * @param array $newGroups
404 * @param array $reason
405 * @param array $tags Change tags for the log entry
406 * @param array $oldUGMs Associative array of (group name => UserGroupMembership)
407 * @param array $newUGMs Associative array of (group name => UserGroupMembership)
408 */
409 protected function addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags,
410 $oldUGMs, $newUGMs ) {
411
412 // make sure $oldUGMs and $newUGMs are in the same order, and serialise
413 // each UGM object to a simplified array
414 $oldUGMs = array_map( function( $group ) use ( $oldUGMs ) {
415 return isset( $oldUGMs[$group] ) ?
416 self::serialiseUgmForLog( $oldUGMs[$group] ) :
417 null;
418 }, $oldGroups );
419 $newUGMs = array_map( function( $group ) use ( $newUGMs ) {
420 return isset( $newUGMs[$group] ) ?
421 self::serialiseUgmForLog( $newUGMs[$group] ) :
422 null;
423 }, $newGroups );
424
425 $logEntry = new ManualLogEntry( 'rights', 'rights' );
426 $logEntry->setPerformer( $this->getUser() );
427 $logEntry->setTarget( $user->getUserPage() );
428 $logEntry->setComment( $reason );
429 $logEntry->setParameters( [
430 '4::oldgroups' => $oldGroups,
431 '5::newgroups' => $newGroups,
432 'oldmetadata' => $oldUGMs,
433 'newmetadata' => $newUGMs,
434 ] );
435 $logid = $logEntry->insert();
436 if ( count( $tags ) ) {
437 $logEntry->setTags( $tags );
438 }
439 $logEntry->publish( $logid );
440 }
441
442 /**
443 * Edit user groups membership
444 * @param string $username Name of the user.
445 */
446 function editUserGroupsForm( $username ) {
447 $status = $this->fetchUser( $username, true );
448 if ( !$status->isOK() ) {
449 $this->getOutput()->addWikiText( $status->getWikiText() );
450
451 return;
452 } else {
453 $user = $status->value;
454 }
455
456 $groups = $user->getGroups();
457 $groupMemberships = $user->getGroupMemberships();
458 $this->showEditUserGroupsForm( $user, $groups, $groupMemberships );
459
460 // This isn't really ideal logging behavior, but let's not hide the
461 // interwiki logs if we're using them as is.
462 $this->showLogFragment( $user, $this->getOutput() );
463 }
464
465 /**
466 * Normalize the input username, which may be local or remote, and
467 * return a user (or proxy) object for manipulating it.
468 *
469 * Side effects: error output for invalid access
470 * @param string $username
471 * @param bool $writing
472 * @return Status
473 */
474 public function fetchUser( $username, $writing = true ) {
475 $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
476 if ( count( $parts ) < 2 ) {
477 $name = trim( $username );
478 $database = '';
479 } else {
480 list( $name, $database ) = array_map( 'trim', $parts );
481
482 if ( $database == wfWikiID() ) {
483 $database = '';
484 } else {
485 if ( $writing && !$this->getUser()->isAllowed( 'userrights-interwiki' ) ) {
486 return Status::newFatal( 'userrights-no-interwiki' );
487 }
488 if ( !UserRightsProxy::validDatabase( $database ) ) {
489 return Status::newFatal( 'userrights-nodatabase', $database );
490 }
491 }
492 }
493
494 if ( $name === '' ) {
495 return Status::newFatal( 'nouserspecified' );
496 }
497
498 if ( $name[0] == '#' ) {
499 // Numeric ID can be specified...
500 // We'll do a lookup for the name internally.
501 $id = intval( substr( $name, 1 ) );
502
503 if ( $database == '' ) {
504 $name = User::whoIs( $id );
505 } else {
506 $name = UserRightsProxy::whoIs( $database, $id );
507 }
508
509 if ( !$name ) {
510 return Status::newFatal( 'noname' );
511 }
512 } else {
513 $name = User::getCanonicalName( $name );
514 if ( $name === false ) {
515 // invalid name
516 return Status::newFatal( 'nosuchusershort', $username );
517 }
518 }
519
520 if ( $database == '' ) {
521 $user = User::newFromName( $name );
522 } else {
523 $user = UserRightsProxy::newFromName( $database, $name );
524 }
525
526 if ( !$user || $user->isAnon() ) {
527 return Status::newFatal( 'nosuchusershort', $username );
528 }
529
530 return Status::newGood( $user );
531 }
532
533 /**
534 * @since 1.15
535 *
536 * @param array $ids
537 *
538 * @return string
539 */
540 public function makeGroupNameList( $ids ) {
541 if ( empty( $ids ) ) {
542 return $this->msg( 'rightsnone' )->inContentLanguage()->text();
543 } else {
544 return implode( ', ', $ids );
545 }
546 }
547
548 /**
549 * Output a form to allow searching for a user
550 */
551 function switchForm() {
552 $this->getOutput()->addModules( 'mediawiki.userSuggest' );
553
554 $this->getOutput()->addHTML(
555 Html::openElement(
556 'form',
557 [
558 'method' => 'get',
559 'action' => wfScript(),
560 'name' => 'uluser',
561 'id' => 'mw-userrights-form1'
562 ]
563 ) .
564 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
565 Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
566 Xml::inputLabel(
567 $this->msg( 'userrights-user-editname' )->text(),
568 'user',
569 'username',
570 30,
571 str_replace( '_', ' ', $this->mTarget ),
572 [
573 'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
574 ] + (
575 // Set autofocus on blank input and error input
576 $this->mFetchedUser === null ? [ 'autofocus' => '' ] : []
577 )
578 ) . ' ' .
579 Xml::submitButton(
580 $this->msg( 'editusergroup' )->text()
581 ) .
582 Html::closeElement( 'fieldset' ) .
583 Html::closeElement( 'form' ) . "\n"
584 );
585 }
586
587 /**
588 * Show the form to edit group memberships.
589 *
590 * @param User|UserRightsProxy $user User or UserRightsProxy you're editing
591 * @param array $groups Array of groups the user is in. Not used by this implementation
592 * anymore, but kept for backward compatibility with subclasses
593 * @param array $groupMemberships Associative array of (group name => UserGroupMembership
594 * object) containing the groups the user is in
595 */
596 protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) {
597 $list = $membersList = $tempList = $tempMembersList = [];
598 foreach ( $groupMemberships as $ugm ) {
599 $linkG = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html' );
600 $linkM = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html',
601 $user->getName() );
602 if ( $ugm->getExpiry() ) {
603 $tempList[] = $linkG;
604 $tempMembersList[] = $linkM;
605 } else {
606 $list[] = $linkG;
607 $membersList[] = $linkM;
608
609 }
610 }
611
612 $autoList = [];
613 $autoMembersList = [];
614 if ( $user instanceof User ) {
615 foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
616 $autoList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html' );
617 $autoMembersList[] = UserGroupMembership::getLink( $group, $this->getContext(),
618 'html', $user->getName() );
619 }
620 }
621
622 $language = $this->getLanguage();
623 $displayedList = $this->msg( 'userrights-groupsmember-type' )
624 ->rawParams(
625 $language->commaList( array_merge( $tempList, $list ) ),
626 $language->commaList( array_merge( $tempMembersList, $membersList ) )
627 )->escaped();
628 $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
629 ->rawParams(
630 $language->commaList( $autoList ),
631 $language->commaList( $autoMembersList )
632 )->escaped();
633
634 $grouplist = '';
635 $count = count( $list );
636 if ( $count > 0 ) {
637 $grouplist = $this->msg( 'userrights-groupsmember' )
638 ->numParams( $count )
639 ->params( $user->getName() )
640 ->parse();
641 $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
642 }
643
644 $count = count( $autoList );
645 if ( $count > 0 ) {
646 $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
647 ->numParams( $count )
648 ->params( $user->getName() )
649 ->parse();
650 $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
651 }
652
653 $userToolLinks = Linker::userToolLinks(
654 $user->getId(),
655 $user->getName(),
656 false, /* default for redContribsWhenNoEdits */
657 Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
658 );
659
660 list( $groupCheckboxes, $canChangeAny ) =
661 $this->groupCheckboxes( $groupMemberships, $user );
662 $this->getOutput()->addHTML(
663 Xml::openElement(
664 'form',
665 [
666 'method' => 'post',
667 'action' => $this->getPageTitle()->getLocalURL(),
668 'name' => 'editGroup',
669 'id' => 'mw-userrights-form2'
670 ]
671 ) .
672 Html::hidden( 'user', $this->mTarget ) .
673 Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
674 Html::hidden(
675 'conflictcheck-originalgroups',
676 implode( ',', $user->getGroups() )
677 ) . // Conflict detection
678 Xml::openElement( 'fieldset' ) .
679 Xml::element(
680 'legend',
681 [],
682 $this->msg(
683 $canChangeAny ? 'userrights-editusergroup' : 'userrights-viewusergroup',
684 $user->getName()
685 )->text()
686 ) .
687 $this->msg(
688 $canChangeAny ? 'editinguser' : 'viewinguserrights'
689 )->params( wfEscapeWikiText( $user->getName() ) )
690 ->rawParams( $userToolLinks )->parse()
691 );
692 if ( $canChangeAny ) {
693 $this->getOutput()->addHTML(
694 $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
695 $grouplist .
696 $groupCheckboxes .
697 Xml::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
698 "<tr>
699 <td class='mw-label'>" .
700 Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
701 "</td>
702 <td class='mw-input'>" .
703 Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ),
704 [ 'id' => 'wpReason', 'maxlength' => 255 ] ) .
705 "</td>
706 </tr>
707 <tr>
708 <td></td>
709 <td class='mw-submit'>" .
710 Xml::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
711 [ 'name' => 'saveusergroups' ] +
712 Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
713 ) .
714 "</td>
715 </tr>" .
716 Xml::closeElement( 'table' ) . "\n"
717 );
718 } else {
719 $this->getOutput()->addHTML( $grouplist );
720 }
721 $this->getOutput()->addHTML(
722 Xml::closeElement( 'fieldset' ) .
723 Xml::closeElement( 'form' ) . "\n"
724 );
725 }
726
727 /**
728 * Returns an array of all groups that may be edited
729 * @return array Array of groups that may be edited.
730 */
731 protected static function getAllGroups() {
732 return User::getAllGroups();
733 }
734
735 /**
736 * Adds a table with checkboxes where you can select what groups to add/remove
737 *
738 * @param array $usergroups Associative array of (group name as string =>
739 * UserGroupMembership object) for groups the user belongs to
740 * @param User $user
741 * @return Array with 2 elements: the XHTML table element with checkxboes, and
742 * whether any groups are changeable
743 */
744 private function groupCheckboxes( $usergroups, $user ) {
745 $allgroups = $this->getAllGroups();
746 $ret = '';
747
748 // Get the list of preset expiry times from the system message
749 $expiryOptionsMsg = $this->msg( 'userrights-expiry-options' )->inContentLanguage();
750 $expiryOptions = $expiryOptionsMsg->isDisabled() ?
751 [] :
752 explode( ',', $expiryOptionsMsg->text() );
753
754 // Put all column info into an associative array so that extensions can
755 // more easily manage it.
756 $columns = [ 'unchangeable' => [], 'changeable' => [] ];
757
758 foreach ( $allgroups as $group ) {
759 $set = isset( $usergroups[$group] );
760 // Should the checkbox be disabled?
761 $disabled = !(
762 ( $set && $this->canRemove( $group ) ) ||
763 ( !$set && $this->canAdd( $group ) ) );
764 // Do we need to point out that this action is irreversible?
765 $irreversible = !$disabled && (
766 ( $set && !$this->canAdd( $group ) ) ||
767 ( !$set && !$this->canRemove( $group ) ) );
768
769 $checkbox = [
770 'set' => $set,
771 'disabled' => $disabled,
772 'irreversible' => $irreversible
773 ];
774
775 if ( $disabled ) {
776 $columns['unchangeable'][$group] = $checkbox;
777 } else {
778 $columns['changeable'][$group] = $checkbox;
779 }
780 }
781
782 // Build the HTML table
783 $ret .= Xml::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
784 "<tr>\n";
785 foreach ( $columns as $name => $column ) {
786 if ( $column === [] ) {
787 continue;
788 }
789 // Messages: userrights-changeable-col, userrights-unchangeable-col
790 $ret .= Xml::element(
791 'th',
792 null,
793 $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
794 );
795 }
796
797 $ret .= "</tr>\n<tr>\n";
798 foreach ( $columns as $column ) {
799 if ( $column === [] ) {
800 continue;
801 }
802 $ret .= "\t<td style='vertical-align:top;'>\n";
803 foreach ( $column as $group => $checkbox ) {
804 $attr = $checkbox['disabled'] ? [ 'disabled' => 'disabled' ] : [];
805
806 $member = UserGroupMembership::getGroupMemberName( $group, $user->getName() );
807 if ( $checkbox['irreversible'] ) {
808 $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
809 } else {
810 $text = $member;
811 }
812 $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
813 "wpGroup-" . $group, $checkbox['set'], $attr );
814 $ret .= "\t\t" . ( $checkbox['disabled']
815 ? Xml::tags( 'div', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
816 : Xml::tags( 'div', [], $checkboxHtml )
817 ) . "\n";
818
819 if ( $this->canProcessExpiries() ) {
820 $uiUser = $this->getUser();
821 $uiLanguage = $this->getLanguage();
822
823 $currentExpiry = isset( $usergroups[$group] ) ?
824 $usergroups[$group]->getExpiry() :
825 null;
826
827 // If the user can't uncheck this checkbox, print the current expiry below
828 // it in plain text. Otherwise provide UI to set/change the expiry
829 if ( $checkbox['set'] && ( $checkbox['irreversible'] || $checkbox['disabled'] ) ) {
830 if ( $currentExpiry ) {
831 $expiryFormatted = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
832 $expiryFormattedD = $uiLanguage->userDate( $currentExpiry, $uiUser );
833 $expiryFormattedT = $uiLanguage->userTime( $currentExpiry, $uiUser );
834 $expiryHtml = $this->msg( 'userrights-expiry-current' )->params(
835 $expiryFormatted, $expiryFormattedD, $expiryFormattedT )->text();
836 } else {
837 $expiryHtml = $this->msg( 'userrights-expiry-none' )->text();
838 }
839 $expiryHtml .= "<br />\n";
840 } else {
841 $expiryHtml = Xml::element( 'span', null,
842 $this->msg( 'userrights-expiry' )->text() );
843 $expiryHtml .= Xml::openElement( 'span' );
844
845 // add a form element to set the expiry date
846 $expiryFormOptions = new XmlSelect(
847 "wpExpiry-$group",
848 "mw-input-wpExpiry-$group", // forward compatibility with HTMLForm
849 $currentExpiry ? 'existing' : 'infinite'
850 );
851 if ( $checkbox['disabled'] ) {
852 $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
853 }
854
855 if ( $currentExpiry ) {
856 $timestamp = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
857 $d = $uiLanguage->userDate( $currentExpiry, $uiUser );
858 $t = $uiLanguage->userTime( $currentExpiry, $uiUser );
859 $existingExpiryMessage = $this->msg( 'userrights-expiry-existing',
860 $timestamp, $d, $t );
861 $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
862 }
863
864 $expiryFormOptions->addOption(
865 $this->msg( 'userrights-expiry-none' )->text(),
866 'infinite'
867 );
868 $expiryFormOptions->addOption(
869 $this->msg( 'userrights-expiry-othertime' )->text(),
870 'other'
871 );
872 foreach ( $expiryOptions as $option ) {
873 if ( strpos( $option, ":" ) === false ) {
874 $displayText = $value = $option;
875 } else {
876 list( $displayText, $value ) = explode( ":", $option );
877 }
878 $expiryFormOptions->addOption( $displayText, htmlspecialchars( $value ) );
879 }
880
881 // Add expiry dropdown
882 $expiryHtml .= $expiryFormOptions->getHTML() . '<br />';
883
884 // Add custom expiry field
885 $attribs = [ 'id' => "mw-input-wpExpiry-$group-other" ];
886 if ( $checkbox['disabled'] ) {
887 $attribs['disabled'] = 'disabled';
888 }
889 $expiryHtml .= Xml::input( "wpExpiry-$group-other", 30, '', $attribs );
890
891 $expiryHtml .= Xml::closeElement( 'span' );
892 }
893
894 $divAttribs = [
895 'id' => "mw-userrights-nested-wpGroup-$group",
896 'class' => 'mw-userrights-nested',
897 ];
898 $ret .= "\t\t\t" . Xml::tags( 'div', $divAttribs, $expiryHtml ) . "\n";
899 }
900 }
901 $ret .= "\t</td>\n";
902 }
903 $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
904
905 return [ $ret, (bool)$columns['changeable'] ];
906 }
907
908 /**
909 * @param string $group The name of the group to check
910 * @return bool Can we remove the group?
911 */
912 private function canRemove( $group ) {
913 $groups = $this->changeableGroups();
914
915 return in_array(
916 $group,
917 $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
918 );
919 }
920
921 /**
922 * @param string $group The name of the group to check
923 * @return bool Can we add the group?
924 */
925 private function canAdd( $group ) {
926 $groups = $this->changeableGroups();
927
928 return in_array(
929 $group,
930 $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
931 );
932 }
933
934 /**
935 * Returns $this->getUser()->changeableGroups()
936 *
937 * @return array Array(
938 * 'add' => array( addablegroups ),
939 * 'remove' => array( removablegroups ),
940 * 'add-self' => array( addablegroups to self ),
941 * 'remove-self' => array( removable groups from self )
942 * )
943 */
944 function changeableGroups() {
945 return $this->getUser()->changeableGroups();
946 }
947
948 /**
949 * Show a rights log fragment for the specified user
950 *
951 * @param User $user User to show log for
952 * @param OutputPage $output OutputPage to use
953 */
954 protected function showLogFragment( $user, $output ) {
955 $rightsLogPage = new LogPage( 'rights' );
956 $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
957 LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
958 }
959
960 /**
961 * Return an array of subpages beginning with $search that this special page will accept.
962 *
963 * @param string $search Prefix to search for
964 * @param int $limit Maximum number of results to return (usually 10)
965 * @param int $offset Number of results to skip (usually 0)
966 * @return string[] Matching subpages
967 */
968 public function prefixSearchSubpages( $search, $limit, $offset ) {
969 $user = User::newFromName( $search );
970 if ( !$user ) {
971 // No prefix suggestion for invalid user
972 return [];
973 }
974 // Autocomplete subpage as user list - public to allow caching
975 return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
976 }
977
978 protected function getGroupName() {
979 return 'users';
980 }
981 }