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