MediaWiki  master
SpecialUserrights.php
Go to the documentation of this file.
1 <?php
25 
31 class UserrightsPage extends SpecialPage {
38  protected $mTarget;
39  /*
40  * @var null|User $mFetchedUser The user object of the target username or null.
41  */
42  protected $mFetchedUser = null;
43  protected $isself = false;
44 
45  public function __construct() {
46  parent::__construct( 'Userrights' );
47  }
48 
49  public function doesWrites() {
50  return true;
51  }
52 
62  public function userCanChangeRights( $targetUser, $checkIfSelf = true ) {
63  $isself = $this->getUser()->equals( $targetUser );
64 
65  $available = $this->changeableGroups();
66  if ( $targetUser->getId() === 0 ) {
67  return false;
68  }
69 
70  if ( $available['add'] || $available['remove'] ) {
71  // can change some rights for any user
72  return true;
73  }
74 
75  if ( ( $available['add-self'] || $available['remove-self'] )
76  && ( $isself || !$checkIfSelf )
77  ) {
78  // can change some rights for self
79  return true;
80  }
81 
82  return false;
83  }
84 
93  public function execute( $par ) {
94  $user = $this->getUser();
95  $request = $this->getRequest();
96  $session = $request->getSession();
97  $out = $this->getOutput();
98 
99  $out->addModules( [ 'mediawiki.special.userrights' ] );
100 
101  $this->mTarget = $par ?? $request->getVal( 'user' );
102 
103  if ( is_string( $this->mTarget ) ) {
104  $this->mTarget = trim( $this->mTarget );
105  }
106 
107  if ( $this->mTarget !== null && User::getCanonicalName( $this->mTarget ) === $user->getName() ) {
108  $this->isself = true;
109  }
110 
111  $fetchedStatus = $this->fetchUser( $this->mTarget, true );
112  if ( $fetchedStatus->isOK() ) {
113  $this->mFetchedUser = $fetchedStatus->value;
114  if ( $this->mFetchedUser instanceof User ) {
115  // Set the 'relevant user' in the skin, so it displays links like Contributions,
116  // User logs, UserRights, etc.
117  $this->getSkin()->setRelevantUser( $this->mFetchedUser );
118  }
119  }
120 
121  // show a successbox, if the user rights was saved successfully
122  if (
123  $session->get( 'specialUserrightsSaveSuccess' ) &&
124  $this->mFetchedUser !== null
125  ) {
126  // Remove session data for the success message
127  $session->remove( 'specialUserrightsSaveSuccess' );
128 
129  $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
130  $out->addHTML(
132  'div',
133  [
134  'class' => 'mw-notify-success successbox',
135  'id' => 'mw-preferences-success',
136  'data-mw-autohide' => 'false',
137  ],
139  'p',
140  [],
141  $this->msg( 'savedrights', $this->mFetchedUser->getName() )->text()
142  )
143  )
144  );
145  }
146 
147  $this->setHeaders();
148  $this->outputHeader();
149 
150  $out->addModuleStyles( 'mediawiki.special' );
151  $this->addHelpLink( 'Help:Assigning permissions' );
152 
153  $this->switchForm();
154 
155  if (
156  $request->wasPosted() &&
157  $request->getCheck( 'saveusergroups' ) &&
158  $this->mTarget !== null &&
159  $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
160  ) {
161  /*
162  * If the user is blocked and they only have "partial" access
163  * (e.g. they don't have the userrights permission), then don't
164  * allow them to change any user rights.
165  */
166  if ( !MediaWikiServices::getInstance()
167  ->getPermissionManager()
168  ->userHasRight( $user, 'userrights' )
169  ) {
170  $block = $user->getBlock();
171  if ( $block && $block->isSitewide() ) {
172  throw new UserBlockedError(
173  $block,
174  $user,
175  $this->getLanguage(),
176  $request->getIP()
177  );
178  }
179  }
180 
181  $this->checkReadOnly();
182 
183  // save settings
184  if ( !$fetchedStatus->isOK() ) {
185  $this->getOutput()->addWikiTextAsInterface(
186  $fetchedStatus->getWikiText( false, false, $this->getLanguage() )
187  );
188 
189  return;
190  }
191 
192  $targetUser = $this->mFetchedUser;
193  if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (T63252)
194  $targetUser->clearInstanceCache(); // T40989
195  }
196 
197  $conflictCheck = $request->getVal( 'conflictcheck-originalgroups' );
198  $conflictCheck = ( $conflictCheck === '' ) ? [] : explode( ',', $conflictCheck );
199  $userGroups = $targetUser->getGroups();
200 
201  if ( $userGroups !== $conflictCheck ) {
202  $out->wrapWikiMsg( '<span class="error">$1</span>', 'userrights-conflict' );
203  } else {
204  $status = $this->saveUserGroups(
205  $this->mTarget,
206  $request->getVal( 'user-reason' ),
207  $targetUser
208  );
209 
210  if ( $status->isOK() ) {
211  // Set session data for the success message
212  $session->set( 'specialUserrightsSaveSuccess', 1 );
213 
214  $out->redirect( $this->getSuccessURL() );
215  return;
216  } else {
217  // Print an error message and redisplay the form
218  $out->wrapWikiTextAsInterface(
219  'error', $status->getWikiText( false, false, $this->getLanguage() )
220  );
221  }
222  }
223  }
224 
225  // show some more forms
226  if ( $this->mTarget !== null ) {
227  $this->editUserGroupsForm( $this->mTarget );
228  }
229  }
230 
231  function getSuccessURL() {
232  return $this->getPageTitle( $this->mTarget )->getFullURL();
233  }
234 
241  public function canProcessExpiries() {
242  return true;
243  }
244 
254  public static function expiryToTimestamp( $expiry ) {
255  if ( wfIsInfinity( $expiry ) ) {
256  return null;
257  }
258 
259  $unix = strtotime( $expiry );
260 
261  if ( !$unix || $unix === -1 ) {
262  return false;
263  }
264 
265  // @todo FIXME: Non-qualified absolute times are not in users specified timezone
266  // and there isn't notice about it in the ui (see ProtectionForm::getExpiry)
267  return wfTimestamp( TS_MW, $unix );
268  }
269 
279  protected function saveUserGroups( $username, $reason, $user ) {
280  $allgroups = $this->getAllGroups();
281  $addgroup = [];
282  $groupExpiries = []; // associative array of (group name => expiry)
283  $removegroup = [];
284  $existingUGMs = $user->getGroupMemberships();
285 
286  // This could possibly create a highly unlikely race condition if permissions are changed between
287  // when the form is loaded and when the form is saved. Ignoring it for the moment.
288  foreach ( $allgroups as $group ) {
289  // We'll tell it to remove all unchecked groups, and add all checked groups.
290  // Later on, this gets filtered for what can actually be removed
291  if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
292  $addgroup[] = $group;
293 
294  if ( $this->canProcessExpiries() ) {
295  // read the expiry information from the request
296  $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" );
297  if ( $expiryDropdown === 'existing' ) {
298  continue;
299  }
300 
301  if ( $expiryDropdown === 'other' ) {
302  $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" );
303  } else {
304  $expiryValue = $expiryDropdown;
305  }
306 
307  // validate the expiry
308  $groupExpiries[$group] = self::expiryToTimestamp( $expiryValue );
309 
310  if ( $groupExpiries[$group] === false ) {
311  return Status::newFatal( 'userrights-invalid-expiry', $group );
312  }
313 
314  // not allowed to have things expiring in the past
315  if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) {
316  return Status::newFatal( 'userrights-expiry-in-past', $group );
317  }
318 
319  // if the user can only add this group (not remove it), the expiry time
320  // cannot be brought forward (T156784)
321  if ( !$this->canRemove( $group ) &&
322  isset( $existingUGMs[$group] ) &&
323  ( $existingUGMs[$group]->getExpiry() ?: 'infinity' ) >
324  ( $groupExpiries[$group] ?: 'infinity' )
325  ) {
326  return Status::newFatal( 'userrights-cannot-shorten-expiry', $group );
327  }
328  }
329  } else {
330  $removegroup[] = $group;
331  }
332  }
333 
334  $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries );
335 
336  return Status::newGood();
337  }
338 
352  function doSaveUserGroups( $user, array $add, array $remove, $reason = '',
353  array $tags = [], array $groupExpiries = []
354  ) {
355  // Validate input set...
356  $isself = $user->getName() == $this->getUser()->getName();
357  $groups = $user->getGroups();
358  $ugms = $user->getGroupMemberships();
359  $changeable = $this->changeableGroups();
360  $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : [] );
361  $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : [] );
362 
363  $remove = array_unique(
364  array_intersect( (array)$remove, $removable, $groups ) );
365  $add = array_intersect( (array)$add, $addable );
366 
367  // add only groups that are not already present or that need their expiry updated,
368  // UNLESS the user can only add this group (not remove it) and the expiry time
369  // is being brought forward (T156784)
370  $add = array_filter( $add,
371  function ( $group ) use ( $groups, $groupExpiries, $removable, $ugms ) {
372  if ( isset( $groupExpiries[$group] ) &&
373  !in_array( $group, $removable ) &&
374  isset( $ugms[$group] ) &&
375  ( $ugms[$group]->getExpiry() ?: 'infinity' ) >
376  ( $groupExpiries[$group] ?: 'infinity' )
377  ) {
378  return false;
379  }
380  return !in_array( $group, $groups ) || array_key_exists( $group, $groupExpiries );
381  } );
382 
383  Hooks::run( 'ChangeUserGroups', [ $this->getUser(), $user, &$add, &$remove ] );
384 
385  $oldGroups = $groups;
386  $oldUGMs = $user->getGroupMemberships();
387  $newGroups = $oldGroups;
388 
389  // Remove groups, then add new ones/update expiries of existing ones
390  if ( $remove ) {
391  foreach ( $remove as $index => $group ) {
392  if ( !$user->removeGroup( $group ) ) {
393  unset( $remove[$index] );
394  }
395  }
396  $newGroups = array_diff( $newGroups, $remove );
397  }
398  if ( $add ) {
399  foreach ( $add as $index => $group ) {
400  $expiry = $groupExpiries[$group] ?? null;
401  if ( !$user->addGroup( $group, $expiry ) ) {
402  unset( $add[$index] );
403  }
404  }
405  $newGroups = array_merge( $newGroups, $add );
406  }
407  $newGroups = array_unique( $newGroups );
408  $newUGMs = $user->getGroupMemberships();
409 
410  // Ensure that caches are cleared
411  $user->invalidateCache();
412 
413  // update groups in external authentication database
414  Hooks::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(),
415  $reason, $oldUGMs, $newUGMs ] );
416 
417  wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
418  wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
419  wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) . "\n" );
420  wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) . "\n" );
421 
422  // Only add a log entry if something actually changed
423  if ( $newGroups != $oldGroups || $newUGMs != $oldUGMs ) {
424  $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs );
425  }
426 
427  return [ $add, $remove ];
428  }
429 
437  protected static function serialiseUgmForLog( $ugm ) {
438  if ( !$ugm instanceof UserGroupMembership ) {
439  return null;
440  }
441  return [ 'expiry' => $ugm->getExpiry() ];
442  }
443 
454  protected function addLogEntry( $user, array $oldGroups, array $newGroups, $reason,
455  array $tags, array $oldUGMs, array $newUGMs
456  ) {
457  // make sure $oldUGMs and $newUGMs are in the same order, and serialise
458  // each UGM object to a simplified array
459  $oldUGMs = array_map( function ( $group ) use ( $oldUGMs ) {
460  return isset( $oldUGMs[$group] ) ?
461  self::serialiseUgmForLog( $oldUGMs[$group] ) :
462  null;
463  }, $oldGroups );
464  $newUGMs = array_map( function ( $group ) use ( $newUGMs ) {
465  return isset( $newUGMs[$group] ) ?
466  self::serialiseUgmForLog( $newUGMs[$group] ) :
467  null;
468  }, $newGroups );
469 
470  $logEntry = new ManualLogEntry( 'rights', 'rights' );
471  $logEntry->setPerformer( $this->getUser() );
472  $logEntry->setTarget( $user->getUserPage() );
473  $logEntry->setComment( $reason );
474  $logEntry->setParameters( [
475  '4::oldgroups' => $oldGroups,
476  '5::newgroups' => $newGroups,
477  'oldmetadata' => $oldUGMs,
478  'newmetadata' => $newUGMs,
479  ] );
480  $logid = $logEntry->insert();
481  if ( count( $tags ) ) {
482  $logEntry->addTags( $tags );
483  }
484  $logEntry->publish( $logid );
485  }
486 
491  function editUserGroupsForm( $username ) {
492  $status = $this->fetchUser( $username, true );
493  if ( !$status->isOK() ) {
494  $this->getOutput()->addWikiTextAsInterface(
495  $status->getWikiText( false, false, $this->getLanguage() )
496  );
497 
498  return;
499  }
500 
502  $user = $status->value;
503  '@phan-var User $user';
504 
505  $groups = $user->getGroups();
506  $groupMemberships = $user->getGroupMemberships();
507  $this->showEditUserGroupsForm( $user, $groups, $groupMemberships );
508 
509  // This isn't really ideal logging behavior, but let's not hide the
510  // interwiki logs if we're using them as is.
511  $this->showLogFragment( $user, $this->getOutput() );
512  }
513 
523  public function fetchUser( $username, $writing = true ) {
524  $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
525  if ( count( $parts ) < 2 ) {
526  $name = trim( $username );
527  $dbDomain = '';
528  } else {
529  list( $name, $dbDomain ) = array_map( 'trim', $parts );
530 
531  if ( WikiMap::isCurrentWikiId( $dbDomain ) ) {
532  $dbDomain = '';
533  } else {
534  if ( $writing && !MediaWikiServices::getInstance()
536  ->userHasRight( $this->getUser(), 'userrights-interwiki' )
537  ) {
538  return Status::newFatal( 'userrights-no-interwiki' );
539  }
540  if ( !UserRightsProxy::validDatabase( $dbDomain ) ) {
541  return Status::newFatal( 'userrights-nodatabase', $dbDomain );
542  }
543  }
544  }
545 
546  if ( $name === '' ) {
547  return Status::newFatal( 'nouserspecified' );
548  }
549 
550  if ( $name[0] == '#' ) {
551  // Numeric ID can be specified...
552  // We'll do a lookup for the name internally.
553  $id = intval( substr( $name, 1 ) );
554 
555  if ( $dbDomain == '' ) {
556  $name = User::whoIs( $id );
557  } else {
558  $name = UserRightsProxy::whoIs( $dbDomain, $id );
559  }
560 
561  if ( !$name ) {
562  return Status::newFatal( 'noname' );
563  }
564  } else {
565  $name = User::getCanonicalName( $name );
566  if ( $name === false ) {
567  // invalid name
568  return Status::newFatal( 'nosuchusershort', $username );
569  }
570  }
571 
572  if ( $dbDomain == '' ) {
573  $user = User::newFromName( $name );
574  } else {
575  $user = UserRightsProxy::newFromName( $dbDomain, $name );
576  }
577 
578  if ( !$user || $user->isAnon() ) {
579  return Status::newFatal( 'nosuchusershort', $username );
580  }
581 
582  return Status::newGood( $user );
583  }
584 
592  public function makeGroupNameList( $ids ) {
593  if ( empty( $ids ) ) {
594  return $this->msg( 'rightsnone' )->inContentLanguage()->text();
595  } else {
596  return implode( ', ', $ids );
597  }
598  }
599 
603  function switchForm() {
604  $this->getOutput()->addModules( 'mediawiki.userSuggest' );
605 
606  $this->getOutput()->addHTML(
608  'form',
609  [
610  'method' => 'get',
611  'action' => wfScript(),
612  'name' => 'uluser',
613  'id' => 'mw-userrights-form1'
614  ]
615  ) .
616  Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
617  Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
619  $this->msg( 'userrights-user-editname' )->text(),
620  'user',
621  'username',
622  30,
623  str_replace( '_', ' ', $this->mTarget ),
624  [
625  'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
626  ] + (
627  // Set autofocus on blank input and error input
628  $this->mFetchedUser === null ? [ 'autofocus' => '' ] : []
629  )
630  ) . ' ' .
632  $this->msg( 'editusergroup' )->text()
633  ) .
634  Html::closeElement( 'fieldset' ) .
635  Html::closeElement( 'form' ) . "\n"
636  );
637  }
638 
648  protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) {
649  $list = $membersList = $tempList = $tempMembersList = [];
650  foreach ( $groupMemberships as $ugm ) {
651  $linkG = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html' );
652  $linkM = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html',
653  $user->getName() );
654  if ( $ugm->getExpiry() ) {
655  $tempList[] = $linkG;
656  $tempMembersList[] = $linkM;
657  } else {
658  $list[] = $linkG;
659  $membersList[] = $linkM;
660 
661  }
662  }
663 
664  $autoList = [];
665  $autoMembersList = [];
666  if ( $user instanceof User ) {
667  foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
668  $autoList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html' );
669  $autoMembersList[] = UserGroupMembership::getLink( $group, $this->getContext(),
670  'html', $user->getName() );
671  }
672  }
673 
674  $language = $this->getLanguage();
675  $displayedList = $this->msg( 'userrights-groupsmember-type' )
676  ->rawParams(
677  $language->commaList( array_merge( $tempList, $list ) ),
678  $language->commaList( array_merge( $tempMembersList, $membersList ) )
679  )->escaped();
680  $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
681  ->rawParams(
682  $language->commaList( $autoList ),
683  $language->commaList( $autoMembersList )
684  )->escaped();
685 
686  $grouplist = '';
687  $count = count( $list ) + count( $tempList );
688  if ( $count > 0 ) {
689  $grouplist = $this->msg( 'userrights-groupsmember' )
690  ->numParams( $count )
691  ->params( $user->getName() )
692  ->parse();
693  $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
694  }
695 
696  $count = count( $autoList );
697  if ( $count > 0 ) {
698  $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
699  ->numParams( $count )
700  ->params( $user->getName() )
701  ->parse();
702  $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
703  }
704 
705  $userToolLinks = Linker::userToolLinks(
706  $user->getId(),
707  $user->getName(),
708  false, /* default for redContribsWhenNoEdits */
709  Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
710  );
711 
712  list( $groupCheckboxes, $canChangeAny ) =
713  $this->groupCheckboxes( $groupMemberships, $user );
714  $this->getOutput()->addHTML(
716  'form',
717  [
718  'method' => 'post',
719  'action' => $this->getPageTitle()->getLocalURL(),
720  'name' => 'editGroup',
721  'id' => 'mw-userrights-form2'
722  ]
723  ) .
724  Html::hidden( 'user', $this->mTarget ) .
725  Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
726  Html::hidden(
727  'conflictcheck-originalgroups',
728  implode( ',', $user->getGroups() )
729  ) . // Conflict detection
730  Xml::openElement( 'fieldset' ) .
731  Xml::element(
732  'legend',
733  [],
734  $this->msg(
735  $canChangeAny ? 'userrights-editusergroup' : 'userrights-viewusergroup',
736  $user->getName()
737  )->text()
738  ) .
739  $this->msg(
740  $canChangeAny ? 'editinguser' : 'viewinguserrights'
741  )->params( wfEscapeWikiText( $user->getName() ) )
742  ->rawParams( $userToolLinks )->parse()
743  );
744  if ( $canChangeAny ) {
745  $this->getOutput()->addHTML(
746  $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
747  $grouplist .
748  $groupCheckboxes .
749  Xml::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
750  "<tr>
751  <td class='mw-label'>" .
752  Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
753  "</td>
754  <td class='mw-input'>" .
755  Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ), [
756  'id' => 'wpReason',
757  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
758  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
759  // Unicode codepoints.
761  ] ) .
762  "</td>
763  </tr>
764  <tr>
765  <td></td>
766  <td class='mw-submit'>" .
767  Xml::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
768  [ 'name' => 'saveusergroups' ] +
769  Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
770  ) .
771  "</td>
772  </tr>" .
773  Xml::closeElement( 'table' ) . "\n"
774  );
775  } else {
776  $this->getOutput()->addHTML( $grouplist );
777  }
778  $this->getOutput()->addHTML(
779  Xml::closeElement( 'fieldset' ) .
780  Xml::closeElement( 'form' ) . "\n"
781  );
782  }
783 
788  protected static function getAllGroups() {
789  return User::getAllGroups();
790  }
791 
801  private function groupCheckboxes( $usergroups, $user ) {
802  $allgroups = $this->getAllGroups();
803  $ret = '';
804 
805  // Get the list of preset expiry times from the system message
806  $expiryOptionsMsg = $this->msg( 'userrights-expiry-options' )->inContentLanguage();
807  $expiryOptions = $expiryOptionsMsg->isDisabled() ?
808  [] :
809  explode( ',', $expiryOptionsMsg->text() );
810 
811  // Put all column info into an associative array so that extensions can
812  // more easily manage it.
813  $columns = [ 'unchangeable' => [], 'changeable' => [] ];
814 
815  foreach ( $allgroups as $group ) {
816  $set = isset( $usergroups[$group] );
817  // Users who can add the group, but not remove it, can only lengthen
818  // expiries, not shorten them. So they should only see the expiry
819  // dropdown if the group currently has a finite expiry
820  $canOnlyLengthenExpiry = ( $set && $this->canAdd( $group ) &&
821  !$this->canRemove( $group ) && $usergroups[$group]->getExpiry() );
822  // Should the checkbox be disabled?
823  $disabledCheckbox = !(
824  ( $set && $this->canRemove( $group ) ) ||
825  ( !$set && $this->canAdd( $group ) ) );
826  // Should the expiry elements be disabled?
827  $disabledExpiry = $disabledCheckbox && !$canOnlyLengthenExpiry;
828  // Do we need to point out that this action is irreversible?
829  $irreversible = !$disabledCheckbox && (
830  ( $set && !$this->canAdd( $group ) ) ||
831  ( !$set && !$this->canRemove( $group ) ) );
832 
833  $checkbox = [
834  'set' => $set,
835  'disabled' => $disabledCheckbox,
836  'disabled-expiry' => $disabledExpiry,
837  'irreversible' => $irreversible
838  ];
839 
840  if ( $disabledCheckbox && $disabledExpiry ) {
841  $columns['unchangeable'][$group] = $checkbox;
842  } else {
843  $columns['changeable'][$group] = $checkbox;
844  }
845  }
846 
847  // Build the HTML table
848  $ret .= Xml::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
849  "<tr>\n";
850  foreach ( $columns as $name => $column ) {
851  if ( $column === [] ) {
852  continue;
853  }
854  // Messages: userrights-changeable-col, userrights-unchangeable-col
855  $ret .= Xml::element(
856  'th',
857  null,
858  $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
859  );
860  }
861 
862  $ret .= "</tr>\n<tr>\n";
863  foreach ( $columns as $column ) {
864  if ( $column === [] ) {
865  continue;
866  }
867  $ret .= "\t<td style='vertical-align:top;'>\n";
868  foreach ( $column as $group => $checkbox ) {
869  $attr = [ 'class' => 'mw-userrights-groupcheckbox' ];
870  if ( $checkbox['disabled'] ) {
871  $attr['disabled'] = 'disabled';
872  }
873 
874  $member = UserGroupMembership::getGroupMemberName( $group, $user->getName() );
875  if ( $checkbox['irreversible'] ) {
876  $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
877  } elseif ( $checkbox['disabled'] && !$checkbox['disabled-expiry'] ) {
878  $text = $this->msg( 'userrights-no-shorten-expiry-marker', $member )->text();
879  } else {
880  $text = $member;
881  }
882  $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
883  "wpGroup-" . $group, $checkbox['set'], $attr );
884 
885  if ( $this->canProcessExpiries() ) {
886  $uiUser = $this->getUser();
887  $uiLanguage = $this->getLanguage();
888 
889  $currentExpiry = isset( $usergroups[$group] ) ?
890  $usergroups[$group]->getExpiry() :
891  null;
892 
893  // If the user can't modify the expiry, print the current expiry below
894  // it in plain text. Otherwise provide UI to set/change the expiry
895  if ( $checkbox['set'] &&
896  ( $checkbox['irreversible'] || $checkbox['disabled-expiry'] )
897  ) {
898  if ( $currentExpiry ) {
899  $expiryFormatted = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
900  $expiryFormattedD = $uiLanguage->userDate( $currentExpiry, $uiUser );
901  $expiryFormattedT = $uiLanguage->userTime( $currentExpiry, $uiUser );
902  $expiryHtml = $this->msg( 'userrights-expiry-current' )->params(
903  $expiryFormatted, $expiryFormattedD, $expiryFormattedT )->text();
904  } else {
905  $expiryHtml = $this->msg( 'userrights-expiry-none' )->text();
906  }
907  // T171345: Add a hidden form element so that other groups can still be manipulated,
908  // otherwise saving errors out with an invalid expiry time for this group.
909  $expiryHtml .= Html::hidden( "wpExpiry-$group",
910  $currentExpiry ? 'existing' : 'infinite' );
911  $expiryHtml .= "<br />\n";
912  } else {
913  $expiryHtml = Xml::element( 'span', null,
914  $this->msg( 'userrights-expiry' )->text() );
915  $expiryHtml .= Xml::openElement( 'span' );
916 
917  // add a form element to set the expiry date
918  $expiryFormOptions = new XmlSelect(
919  "wpExpiry-$group",
920  "mw-input-wpExpiry-$group", // forward compatibility with HTMLForm
921  $currentExpiry ? 'existing' : 'infinite'
922  );
923  if ( $checkbox['disabled-expiry'] ) {
924  $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
925  }
926 
927  if ( $currentExpiry ) {
928  $timestamp = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
929  $d = $uiLanguage->userDate( $currentExpiry, $uiUser );
930  $t = $uiLanguage->userTime( $currentExpiry, $uiUser );
931  $existingExpiryMessage = $this->msg( 'userrights-expiry-existing',
932  $timestamp, $d, $t );
933  $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
934  }
935 
936  $expiryFormOptions->addOption(
937  $this->msg( 'userrights-expiry-none' )->text(),
938  'infinite'
939  );
940  $expiryFormOptions->addOption(
941  $this->msg( 'userrights-expiry-othertime' )->text(),
942  'other'
943  );
944  foreach ( $expiryOptions as $option ) {
945  if ( strpos( $option, ":" ) === false ) {
946  $displayText = $value = $option;
947  } else {
948  list( $displayText, $value ) = explode( ":", $option );
949  }
950  $expiryFormOptions->addOption( $displayText, htmlspecialchars( $value ) );
951  }
952 
953  // Add expiry dropdown
954  $expiryHtml .= $expiryFormOptions->getHTML() . '<br />';
955 
956  // Add custom expiry field
957  $attribs = [
958  'id' => "mw-input-wpExpiry-$group-other",
959  'class' => 'mw-userrights-expiryfield',
960  ];
961  if ( $checkbox['disabled-expiry'] ) {
962  $attribs['disabled'] = 'disabled';
963  }
964  $expiryHtml .= Xml::input( "wpExpiry-$group-other", 30, '', $attribs );
965 
966  // If the user group is set but the checkbox is disabled, mimic a
967  // checked checkbox in the form submission
968  if ( $checkbox['set'] && $checkbox['disabled'] ) {
969  $expiryHtml .= Html::hidden( "wpGroup-$group", 1 );
970  }
971 
972  $expiryHtml .= Xml::closeElement( 'span' );
973  }
974 
975  $divAttribs = [
976  'id' => "mw-userrights-nested-wpGroup-$group",
977  'class' => 'mw-userrights-nested',
978  ];
979  $checkboxHtml .= "\t\t\t" . Xml::tags( 'div', $divAttribs, $expiryHtml ) . "\n";
980  }
981  $ret .= "\t\t" . ( ( $checkbox['disabled'] && $checkbox['disabled-expiry'] )
982  ? Xml::tags( 'div', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
983  : Xml::tags( 'div', [], $checkboxHtml )
984  ) . "\n";
985  }
986  $ret .= "\t</td>\n";
987  }
988  $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
989 
990  return [ $ret, (bool)$columns['changeable'] ];
991  }
992 
997  private function canRemove( $group ) {
998  $groups = $this->changeableGroups();
999 
1000  return in_array(
1001  $group,
1002  $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
1003  );
1004  }
1005 
1010  private function canAdd( $group ) {
1011  $groups = $this->changeableGroups();
1012 
1013  return in_array(
1014  $group,
1015  $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
1016  );
1017  }
1018 
1029  function changeableGroups() {
1030  return $this->getUser()->changeableGroups();
1031  }
1032 
1039  protected function showLogFragment( $user, $output ) {
1040  $rightsLogPage = new LogPage( 'rights' );
1041  $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
1042  LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
1043  }
1044 
1053  public function prefixSearchSubpages( $search, $limit, $offset ) {
1054  $user = User::newFromName( $search );
1055  if ( !$user ) {
1056  // No prefix suggestion for invalid user
1057  return [];
1058  }
1059  // Autocomplete subpage as user list - public to allow caching
1060  return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1061  }
1062 
1063  protected function getGroupName() {
1064  return 'users';
1065  }
1066 }
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
editUserGroupsForm( $username)
Edit user groups membership.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
static expiryToTimestamp( $expiry)
Converts a user group membership expiry string into a timestamp.
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:809
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
static whoIs( $dbDomain, $id, $ignoreInvalidDB=false)
Same as User::whoIs()
static newFromName( $dbDomain, $name, $ignoreInvalidDB=false)
Factory function; get a remote user entry by name.
addLogEntry( $user, array $oldGroups, array $newGroups, $reason, array $tags, array $oldUGMs, array $newUGMs)
Add a rights log entry for an action.
getContext()
Gets the context this SpecialPage is executed in.
doSaveUserGroups( $user, array $add, array $remove, $reason='', array $tags=[], array $groupExpiries=[])
Save user groups changes in the database.
execute( $par)
Manage forms to be shown according to posted data.
changeableGroups()
Returns $this->getUser()->changeableGroups()
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing &#39;/&#39;...
Definition: Html.php:251
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
Class for generating HTML <select> or <datalist> elements.
Definition: XmlSelect.php:26
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:274
wfIsInfinity( $str)
Determine input string is represents as infinity.
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
getOutput()
Get the OutputPage being used for this instance.
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
fetchUser( $username, $writing=true)
Normalize the input username, which may be local or remote, and return a user (or proxy) object for m...
static serialiseUgmForLog( $ugm)
Serialise a UserGroupMembership object for storage in the log_params section of the logging table...
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
static search( $audience, $search, $limit, $offset=0)
Do a prefix search of user names and return a list of matching user names.
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:4805
Class to simplify the use of log pages.
Definition: LogPage.php:33
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid...
Definition: User.php:1139
getPermissionManager()
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
switchForm()
Output a form to allow searching for a user.
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:108
static validDatabase( $dbDomain)
Confirm the selected database name is a valid local interwiki database name.
static getGroupMemberName( $group, $username)
Gets the localized name for a member of a group, if it exists.
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:609
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null, $useParentheses=true)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:943
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:459
userCanChangeRights( $targetUser, $checkIfSelf=true)
Check whether the current user (from context) can change the target user&#39;s rights.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
getSkin()
Shortcut to get the skin being used for this instance.
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:130
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:315
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
$mTarget
The target of the local right-adjuster&#39;s interest.
static getAutopromoteGroups(User $user)
Get the groups for the given user based on $wgAutopromote.
Definition: Autopromote.php:37
Show an error when the user tries to do something whilst blocked.
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:358
saveUserGroups( $username, $reason, $user)
Save user groups changes in the database.
canProcessExpiries()
Returns true if this user rights form can set and change user group expiries.
showEditUserGroupsForm( $user, $groups, $groupMemberships)
Show the form to edit group memberships.
static getAllGroups()
Returns an array of all groups that may be edited.
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:117
static isCurrentWikiId( $wikiId)
Definition: WikiMap.php:313
getUser()
Shortcut to get the User executing this instance.
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:802
getConfig()
Shortcut to get main config object.
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
getLanguage()
Shortcut to get user&#39;s language.
Special page to allow managing user group membership.
static inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field with a label.
Definition: Xml.php:380
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:419
groupCheckboxes( $usergroups, $user)
Adds a table with checkboxes where you can select what groups to add/remove.
getRequest()
Get the WebRequest being used for this instance.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:515
showLogFragment( $user, $output)
Show a rights log fragment for the specified user.
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2190
checkReadOnly()
If the wiki is currently in readonly mode, throws a ReadOnlyError.
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
getPageTitle( $subpage=false)
Get a self-referential title object.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
const TOOL_LINKS_EMAIL
Definition: Linker.php:40
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.