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