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