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