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