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