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