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