MediaWiki  master
SpecialUserrights.php
Go to the documentation of this file.
1 <?php
29 
35 class UserrightsPage extends SpecialPage {
42  protected $mTarget;
46  protected $mFetchedUser = null;
47  protected $isself = false;
48 
51 
53  private $userNameUtils;
54 
57 
63  public function __construct(
64  UserGroupManagerFactory $userGroupManagerFactory = null,
67  ) {
68  parent::__construct( 'Userrights' );
69  $services = MediaWikiServices::getInstance();
70  // This class is extended and therefore falls back to global state - T263207
71  $this->userNameUtils = $userNameUtils ?? $services->getUserNameUtils();
72  $this->userNamePrefixSearch = $userNamePrefixSearch ?? $services->getUserNamePrefixSearch();
73 
74  // TODO don't hard code false, use interwiki domains. See T14518
75  $this->userGroupManager = ( $userGroupManagerFactory ?? $services->getUserGroupManagerFactory() )
76  ->getUserGroupManager( false );
77  }
78 
79  public function doesWrites() {
80  return true;
81  }
82 
92  public function userCanChangeRights( $targetUser, $checkIfSelf = true ) {
93  $isself = $this->getUser()->equals( $targetUser );
94 
95  $available = $this->changeableGroups();
96  if ( $targetUser->getId() === 0 ) {
97  return false;
98  }
99 
100  if ( $available['add'] || $available['remove'] ) {
101  // can change some rights for any user
102  return true;
103  }
104 
105  if ( ( $available['add-self'] || $available['remove-self'] )
106  && ( $isself || !$checkIfSelf )
107  ) {
108  // can change some rights for self
109  return true;
110  }
111 
112  return false;
113  }
114 
122  public function execute( $par ) {
123  $user = $this->getUser();
124  $request = $this->getRequest();
125  $session = $request->getSession();
126  $out = $this->getOutput();
127 
128  $out->addModules( [ 'mediawiki.special.userrights' ] );
129 
130  $this->mTarget = $par ?? $request->getVal( 'user' );
131 
132  if ( is_string( $this->mTarget ) ) {
133  $this->mTarget = trim( $this->mTarget );
134  }
135 
136  if ( $this->mTarget !== null && $this->userNameUtils->getCanonical( $this->mTarget ) === $user->getName() ) {
137  $this->isself = true;
138  }
139 
140  $fetchedStatus = $this->mTarget === null ? Status::newFatal( 'nouserspecified' ) :
141  $this->fetchUser( $this->mTarget, true );
142  if ( $fetchedStatus->isOK() ) {
143  $this->mFetchedUser = $fetchedStatus->value;
144  if ( $this->mFetchedUser instanceof User ) {
145  // Set the 'relevant user' in the skin, so it displays links like Contributions,
146  // User logs, UserRights, etc.
147  $this->getSkin()->setRelevantUser( $this->mFetchedUser );
148  }
149  }
150 
151  // show a successbox, if the user rights was saved successfully
152  if (
153  $session->get( 'specialUserrightsSaveSuccess' ) &&
154  $this->mFetchedUser !== null
155  ) {
156  // Remove session data for the success message
157  $session->remove( 'specialUserrightsSaveSuccess' );
158 
159  $out->addModuleStyles( 'mediawiki.notification.convertmessagebox.styles' );
160  $out->addHTML(
162  'div',
163  [
164  'class' => 'mw-notify-success successbox',
165  'id' => 'mw-preferences-success',
166  'data-mw-autohide' => 'false',
167  ],
169  'p',
170  [],
171  $this->msg( 'savedrights', $this->mFetchedUser->getName() )->text()
172  )
173  )
174  );
175  }
176 
177  $this->setHeaders();
178  $this->outputHeader();
179 
180  $out->addModuleStyles( 'mediawiki.special' );
181  $this->addHelpLink( 'Help:Assigning permissions' );
182 
183  $this->switchForm();
184 
185  if (
186  $request->wasPosted() &&
187  $request->getCheck( 'saveusergroups' ) &&
188  $this->mTarget !== null &&
189  $user->matchEditToken( $request->getVal( 'wpEditToken' ), $this->mTarget )
190  ) {
191  /*
192  * If the user is blocked and they only have "partial" access
193  * (e.g. they don't have the userrights permission), then don't
194  * allow them to change any user rights.
195  */
196  if ( !$this->getAuthority()->isAllowed( 'userrights' ) ) {
197  $block = $user->getBlock();
198  if ( $block && $block->isSitewide() ) {
199  throw new UserBlockedError(
200  $block,
201  $user,
202  $this->getLanguage(),
203  $request->getIP()
204  );
205  }
206  }
207 
208  $this->checkReadOnly();
209 
210  // save settings
211  if ( !$fetchedStatus->isOK() ) {
212  $this->getOutput()->addWikiTextAsInterface(
213  $fetchedStatus->getWikiText( false, false, $this->getLanguage() )
214  );
215 
216  return;
217  }
218 
219  $targetUser = $this->mFetchedUser;
220  if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (T63252)
221  $targetUser->clearInstanceCache(); // T40989
222  }
223 
224  $conflictCheck = $request->getVal( 'conflictcheck-originalgroups' );
225  $conflictCheck = ( $conflictCheck === '' ) ? [] : explode( ',', $conflictCheck );
226  $userGroups = $targetUser->getGroups();
227 
228  if ( $userGroups !== $conflictCheck ) {
229  $out->addHTML( Html::errorBox(
230  $this->msg( 'userrights-conflict' )->parse()
231  ) );
232  } else {
233  $status = $this->saveUserGroups(
234  $this->mTarget,
235  $request->getVal( 'user-reason' ),
236  $targetUser
237  );
238 
239  if ( $status->isOK() ) {
240  // Set session data for the success message
241  $session->set( 'specialUserrightsSaveSuccess', 1 );
242 
243  $out->redirect( $this->getSuccessURL() );
244  return;
245  } else {
246  // Print an error message and redisplay the form
247  $out->wrapWikiTextAsInterface(
248  'error', $status->getWikiText( false, false, $this->getLanguage() )
249  );
250  }
251  }
252  }
253 
254  // show some more forms
255  if ( $this->mTarget !== null ) {
256  $this->editUserGroupsForm( $this->mTarget );
257  }
258  }
259 
260  private function getSuccessURL() {
261  return $this->getPageTitle( $this->mTarget )->getFullURL();
262  }
263 
270  public function canProcessExpiries() {
271  return true;
272  }
273 
283  public static function expiryToTimestamp( $expiry ) {
284  if ( wfIsInfinity( $expiry ) ) {
285  return null;
286  }
287 
288  $unix = strtotime( $expiry );
289 
290  if ( !$unix || $unix === -1 ) {
291  return false;
292  }
293 
294  // @todo FIXME: Non-qualified absolute times are not in users specified timezone
295  // and there isn't notice about it in the ui (see ProtectionForm::getExpiry)
296  return wfTimestamp( TS_MW, $unix );
297  }
298 
308  protected function saveUserGroups( $username, $reason, $user ) {
309  $allgroups = $this->getAllGroups();
310  $addgroup = [];
311  $groupExpiries = []; // associative array of (group name => expiry)
312  $removegroup = [];
313  $existingUGMs = $user->getGroupMemberships();
314 
315  // This could possibly create a highly unlikely race condition if permissions are changed between
316  // when the form is loaded and when the form is saved. Ignoring it for the moment.
317  foreach ( $allgroups as $group ) {
318  // We'll tell it to remove all unchecked groups, and add all checked groups.
319  // Later on, this gets filtered for what can actually be removed
320  if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
321  $addgroup[] = $group;
322 
323  if ( $this->canProcessExpiries() ) {
324  // read the expiry information from the request
325  $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" );
326  if ( $expiryDropdown === 'existing' ) {
327  continue;
328  }
329 
330  if ( $expiryDropdown === 'other' ) {
331  $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" );
332  } else {
333  $expiryValue = $expiryDropdown;
334  }
335 
336  // validate the expiry
337  $groupExpiries[$group] = self::expiryToTimestamp( $expiryValue );
338 
339  if ( $groupExpiries[$group] === false ) {
340  return Status::newFatal( 'userrights-invalid-expiry', $group );
341  }
342 
343  // not allowed to have things expiring in the past
344  if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) {
345  return Status::newFatal( 'userrights-expiry-in-past', $group );
346  }
347 
348  // if the user can only add this group (not remove it), the expiry time
349  // cannot be brought forward (T156784)
350  if ( !$this->canRemove( $group ) &&
351  isset( $existingUGMs[$group] ) &&
352  ( $existingUGMs[$group]->getExpiry() ?: 'infinity' ) >
353  ( $groupExpiries[$group] ?: 'infinity' )
354  ) {
355  return Status::newFatal( 'userrights-cannot-shorten-expiry', $group );
356  }
357  }
358  } else {
359  $removegroup[] = $group;
360  }
361  }
362 
363  $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries );
364 
365  return Status::newGood();
366  }
367 
381  public function doSaveUserGroups( $user, array $add, array $remove, $reason = '',
382  array $tags = [], array $groupExpiries = []
383  ) {
384  // Validate input set...
385  $isself = $user->getName() == $this->getUser()->getName();
386  $groups = $user->getGroups();
387  $ugms = $user->getGroupMemberships();
388  $changeable = $this->changeableGroups();
389  $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : [] );
390  $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : [] );
391 
392  $remove = array_unique( array_intersect( $remove, $removable, $groups ) );
393  $add = array_intersect( $add, $addable );
394 
395  // add only groups that are not already present or that need their expiry updated,
396  // UNLESS the user can only add this group (not remove it) and the expiry time
397  // is being brought forward (T156784)
398  $add = array_filter( $add,
399  static function ( $group ) use ( $groups, $groupExpiries, $removable, $ugms ) {
400  if ( isset( $groupExpiries[$group] ) &&
401  !in_array( $group, $removable ) &&
402  isset( $ugms[$group] ) &&
403  ( $ugms[$group]->getExpiry() ?: 'infinity' ) >
404  ( $groupExpiries[$group] ?: 'infinity' )
405  ) {
406  return false;
407  }
408  return !in_array( $group, $groups ) || array_key_exists( $group, $groupExpiries );
409  } );
410 
411  $this->getHookRunner()->onChangeUserGroups( $this->getUser(), $user, $add, $remove );
412 
413  $oldGroups = $groups;
414  $oldUGMs = $user->getGroupMemberships();
415  $newGroups = $oldGroups;
416 
417  // Remove groups, then add new ones/update expiries of existing ones
418  if ( $remove ) {
419  foreach ( $remove as $index => $group ) {
420  if ( !$user->removeGroup( $group ) ) {
421  unset( $remove[$index] );
422  }
423  }
424  $newGroups = array_diff( $newGroups, $remove );
425  }
426  if ( $add ) {
427  foreach ( $add as $index => $group ) {
428  $expiry = $groupExpiries[$group] ?? null;
429  if ( !$user->addGroup( $group, $expiry ) ) {
430  unset( $add[$index] );
431  }
432  }
433  $newGroups = array_merge( $newGroups, $add );
434  }
435  $newGroups = array_unique( $newGroups );
436  $newUGMs = $user->getGroupMemberships();
437 
438  // Ensure that caches are cleared
439  $user->invalidateCache();
440 
441  // update groups in external authentication database
442  $this->getHookRunner()->onUserGroupsChanged( $user, $add, $remove,
443  $this->getUser(), $reason, $oldUGMs, $newUGMs );
444 
445  wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) );
446  wfDebug( 'newGroups: ' . print_r( $newGroups, true ) );
447  wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) );
448  wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) );
449 
450  // Only add a log entry if something actually changed
451  if ( $newGroups != $oldGroups || $newUGMs != $oldUGMs ) {
452  $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs );
453  }
454 
455  return [ $add, $remove ];
456  }
457 
465  protected static function serialiseUgmForLog( $ugm ) {
466  if ( !$ugm instanceof UserGroupMembership ) {
467  return null;
468  }
469  return [ 'expiry' => $ugm->getExpiry() ];
470  }
471 
482  protected function addLogEntry( $user, array $oldGroups, array $newGroups, $reason,
483  array $tags, array $oldUGMs, array $newUGMs
484  ) {
485  // make sure $oldUGMs and $newUGMs are in the same order, and serialise
486  // each UGM object to a simplified array
487  $oldUGMs = array_map( function ( $group ) use ( $oldUGMs ) {
488  return isset( $oldUGMs[$group] ) ?
489  self::serialiseUgmForLog( $oldUGMs[$group] ) :
490  null;
491  }, $oldGroups );
492  $newUGMs = array_map( function ( $group ) use ( $newUGMs ) {
493  return isset( $newUGMs[$group] ) ?
494  self::serialiseUgmForLog( $newUGMs[$group] ) :
495  null;
496  }, $newGroups );
497 
498  $logEntry = new ManualLogEntry( 'rights', 'rights' );
499  $logEntry->setPerformer( $this->getUser() );
500  $logEntry->setTarget( $user->getUserPage() );
501  $logEntry->setComment( $reason );
502  $logEntry->setParameters( [
503  '4::oldgroups' => $oldGroups,
504  '5::newgroups' => $newGroups,
505  'oldmetadata' => $oldUGMs,
506  'newmetadata' => $newUGMs,
507  ] );
508  $logid = $logEntry->insert();
509  if ( count( $tags ) ) {
510  $logEntry->addTags( $tags );
511  }
512  $logEntry->publish( $logid );
513  }
514 
519  private function editUserGroupsForm( $username ) {
520  $status = $this->fetchUser( $username, true );
521  if ( !$status->isOK() ) {
522  $this->getOutput()->addWikiTextAsInterface(
523  $status->getWikiText( false, false, $this->getLanguage() )
524  );
525 
526  return;
527  }
528 
530  $user = $status->value;
531  '@phan-var User $user';
532 
533  $groups = $user->getGroups();
534  $groupMemberships = $user->getGroupMemberships();
535  $this->showEditUserGroupsForm( $user, $groups, $groupMemberships );
536 
537  // This isn't really ideal logging behavior, but let's not hide the
538  // interwiki logs if we're using them as is.
539  $this->showLogFragment( $user, $this->getOutput() );
540  }
541 
551  public function fetchUser( $username, $writing = true ) {
552  $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
553  if ( count( $parts ) < 2 ) {
554  $name = trim( $username );
555  $dbDomain = '';
556  } else {
557  list( $name, $dbDomain ) = array_map( 'trim', $parts );
558 
559  if ( WikiMap::isCurrentWikiId( $dbDomain ) ) {
560  $dbDomain = '';
561  } else {
562  if ( $writing &&
563  !$this->getAuthority()->isAllowed( 'userrights-interwiki' )
564  ) {
565  return Status::newFatal( 'userrights-no-interwiki' );
566  }
567  if ( !UserRightsProxy::validDatabase( $dbDomain ) ) {
568  return Status::newFatal( 'userrights-nodatabase', $dbDomain );
569  }
570  }
571  }
572 
573  if ( $name === '' ) {
574  return Status::newFatal( 'nouserspecified' );
575  }
576 
577  if ( $name[0] == '#' ) {
578  // Numeric ID can be specified...
579  // We'll do a lookup for the name internally.
580  $id = intval( substr( $name, 1 ) );
581 
582  if ( $dbDomain == '' ) {
583  $name = User::whoIs( $id );
584  } else {
585  $name = UserRightsProxy::whoIs( $dbDomain, $id );
586  }
587 
588  if ( !$name ) {
589  return Status::newFatal( 'noname' );
590  }
591  } else {
592  $name = $this->userNameUtils->getCanonical( $name );
593  if ( $name === false ) {
594  // invalid name
595  return Status::newFatal( 'nosuchusershort', $username );
596  }
597  }
598 
599  if ( $dbDomain == '' ) {
600  $user = User::newFromName( $name );
601  } else {
602  $user = UserRightsProxy::newFromName( $dbDomain, $name );
603  }
604 
605  if ( !$user || $user->isAnon() ) {
606  return Status::newFatal( 'nosuchusershort', $username );
607  }
608 
609  if ( $user instanceof User &&
610  $user->isHidden() &&
611  !$this->getAuthority()->isAllowed( 'hideuser' )
612  ) {
613  // Cannot see hidden users, pretend they don't exist
614  return Status::newFatal( 'nosuchusershort', $username );
615  }
616 
617  return Status::newGood( $user );
618  }
619 
627  public function makeGroupNameList( $ids ) {
628  if ( empty( $ids ) ) {
629  return $this->msg( 'rightsnone' )->inContentLanguage()->text();
630  } else {
631  return implode( ', ', $ids );
632  }
633  }
634 
638  protected function switchForm() {
639  $this->getOutput()->addModules( 'mediawiki.userSuggest' );
640 
641  $this->getOutput()->addHTML(
643  'form',
644  [
645  'method' => 'get',
646  'action' => wfScript(),
647  'name' => 'uluser',
648  'id' => 'mw-userrights-form1'
649  ]
650  ) .
651  Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
652  Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
654  $this->msg( 'userrights-user-editname' )->text(),
655  'user',
656  'username',
657  30,
658  str_replace( '_', ' ', $this->mTarget ),
659  [
660  'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
661  ] + (
662  // Set autofocus on blank input and error input
663  $this->mFetchedUser === null ? [ 'autofocus' => '' ] : []
664  )
665  ) . ' ' .
667  $this->msg( 'editusergroup' )->text()
668  ) .
669  Html::closeElement( 'fieldset' ) .
670  Html::closeElement( 'form' ) . "\n"
671  );
672  }
673 
683  protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) {
684  $list = $membersList = $tempList = $tempMembersList = [];
685  foreach ( $groupMemberships as $ugm ) {
686  $linkG = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html' );
687  $linkM = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html',
688  $user->getName() );
689  if ( $ugm->getExpiry() ) {
690  $tempList[] = $linkG;
691  $tempMembersList[] = $linkM;
692  } else {
693  $list[] = $linkG;
694  $membersList[] = $linkM;
695 
696  }
697  }
698 
699  $autoList = [];
700  $autoMembersList = [];
701 
702  $isUserInstance = $user instanceof User;
703 
704  if ( $isUserInstance ) {
705  foreach ( $this->userGroupManager->getUserAutopromoteGroups( $user ) as $group ) {
706  $autoList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html' );
707  $autoMembersList[] = UserGroupMembership::getLink( $group, $this->getContext(),
708  'html', $user->getName() );
709  }
710  }
711 
712  $language = $this->getLanguage();
713  $displayedList = $this->msg( 'userrights-groupsmember-type' )
714  ->rawParams(
715  $language->commaList( array_merge( $tempList, $list ) ),
716  $language->commaList( array_merge( $tempMembersList, $membersList ) )
717  )->escaped();
718  $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
719  ->rawParams(
720  $language->commaList( $autoList ),
721  $language->commaList( $autoMembersList )
722  )->escaped();
723 
724  $grouplist = '';
725  $count = count( $list ) + count( $tempList );
726  if ( $count > 0 ) {
727  $grouplist = $this->msg( 'userrights-groupsmember' )
728  ->numParams( $count )
729  ->params( $user->getName() )
730  ->parse();
731  $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
732  }
733 
734  $count = count( $autoList );
735  if ( $count > 0 ) {
736  $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
737  ->numParams( $count )
738  ->params( $user->getName() )
739  ->parse();
740  $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
741  }
742 
743  $systemUser = $isUserInstance && $user->isSystemUser();
744  if ( $systemUser ) {
745  $systemusernote = $this->msg( 'userrights-systemuser' )
746  ->params( $user->getName() )
747  ->parse();
748  $grouplist .= '<p>' . $systemusernote . "</p>\n";
749  }
750 
751  // Only add an email link if the user is not a system user
752  $flags = $systemUser ? 0 : Linker::TOOL_LINKS_EMAIL;
753  $userToolLinks = Linker::userToolLinks(
754  $user->getId(),
755  $user->getName(),
756  false, /* default for redContribsWhenNoEdits */
757  $flags
758  );
759 
760  list( $groupCheckboxes, $canChangeAny ) =
761  $this->groupCheckboxes( $groupMemberships, $user );
762  $this->getOutput()->addHTML(
764  'form',
765  [
766  'method' => 'post',
767  'action' => $this->getPageTitle()->getLocalURL(),
768  'name' => 'editGroup',
769  'id' => 'mw-userrights-form2'
770  ]
771  ) .
772  Html::hidden( 'user', $this->mTarget ) .
773  Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
774  Html::hidden(
775  'conflictcheck-originalgroups',
776  implode( ',', $user->getGroups() )
777  ) . // Conflict detection
778  Xml::openElement( 'fieldset' ) .
779  Xml::element(
780  'legend',
781  [],
782  $this->msg(
783  $canChangeAny ? 'userrights-editusergroup' : 'userrights-viewusergroup',
784  $user->getName()
785  )->text()
786  ) .
787  $this->msg(
788  $canChangeAny ? 'editinguser' : 'viewinguserrights'
789  )->params( wfEscapeWikiText( $user->getName() ) )
790  ->rawParams( $userToolLinks )->parse()
791  );
792  if ( $canChangeAny ) {
793  $this->getOutput()->addHTML(
794  $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
795  $grouplist .
796  $groupCheckboxes .
797  Xml::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
798  "<tr>
799  <td class='mw-label'>" .
800  Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
801  "</td>
802  <td class='mw-input'>" .
803  Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ), [
804  'id' => 'wpReason',
805  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
806  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
807  // Unicode codepoints.
809  ] ) .
810  "</td>
811  </tr>
812  <tr>
813  <td></td>
814  <td class='mw-submit'>" .
815  Xml::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
816  [ 'name' => 'saveusergroups' ] +
817  Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
818  ) .
819  "</td>
820  </tr>" .
821  Xml::closeElement( 'table' ) . "\n"
822  );
823  } else {
824  $this->getOutput()->addHTML( $grouplist );
825  }
826  $this->getOutput()->addHTML(
827  Xml::closeElement( 'fieldset' ) .
828  Xml::closeElement( 'form' ) . "\n"
829  );
830  }
831 
835  protected static function getAllGroups() {
836  // TODO don't hard code false here (refers to local domain). See T14518
837  return MediaWikiServices::getInstance()
838  ->getUserGroupManagerFactory()
839  ->getUserGroupManager( false )
840  ->listAllGroups();
841  }
842 
852  private function groupCheckboxes( $usergroups, $user ) {
853  $allgroups = $this->getAllGroups();
854  $ret = '';
855 
856  // Get the list of preset expiry times from the system message
857  $expiryOptionsMsg = $this->msg( 'userrights-expiry-options' )->inContentLanguage();
858  $expiryOptions = $expiryOptionsMsg->isDisabled()
859  ? []
860  : XmlSelect::parseOptionsMessage( $expiryOptionsMsg->text() );
861 
862  // Put all column info into an associative array so that extensions can
863  // more easily manage it.
864  $columns = [ 'unchangeable' => [], 'changeable' => [] ];
865 
866  foreach ( $allgroups as $group ) {
867  $set = isset( $usergroups[$group] );
868  // Users who can add the group, but not remove it, can only lengthen
869  // expiries, not shorten them. So they should only see the expiry
870  // dropdown if the group currently has a finite expiry
871  $canOnlyLengthenExpiry = ( $set && $this->canAdd( $group ) &&
872  !$this->canRemove( $group ) && $usergroups[$group]->getExpiry() );
873  // Should the checkbox be disabled?
874  $disabledCheckbox = !(
875  ( $set && $this->canRemove( $group ) ) ||
876  ( !$set && $this->canAdd( $group ) ) );
877  // Should the expiry elements be disabled?
878  $disabledExpiry = $disabledCheckbox && !$canOnlyLengthenExpiry;
879  // Do we need to point out that this action is irreversible?
880  $irreversible = !$disabledCheckbox && (
881  ( $set && !$this->canAdd( $group ) ) ||
882  ( !$set && !$this->canRemove( $group ) ) );
883 
884  $checkbox = [
885  'set' => $set,
886  'disabled' => $disabledCheckbox,
887  'disabled-expiry' => $disabledExpiry,
888  'irreversible' => $irreversible
889  ];
890 
891  if ( $disabledCheckbox && $disabledExpiry ) {
892  $columns['unchangeable'][$group] = $checkbox;
893  } else {
894  $columns['changeable'][$group] = $checkbox;
895  }
896  }
897 
898  // Build the HTML table
899  $ret .= Xml::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
900  "<tr>\n";
901  foreach ( $columns as $name => $column ) {
902  if ( $column === [] ) {
903  continue;
904  }
905  // Messages: userrights-changeable-col, userrights-unchangeable-col
906  $ret .= Xml::element(
907  'th',
908  null,
909  $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
910  );
911  }
912 
913  $ret .= "</tr>\n<tr>\n";
914  foreach ( $columns as $column ) {
915  if ( $column === [] ) {
916  continue;
917  }
918  $ret .= "\t<td style='vertical-align:top;'>\n";
919  foreach ( $column as $group => $checkbox ) {
920  $attr = [ 'class' => 'mw-userrights-groupcheckbox' ];
921  if ( $checkbox['disabled'] ) {
922  $attr['disabled'] = 'disabled';
923  }
924 
925  $member = UserGroupMembership::getGroupMemberName( $group, $user->getName() );
926  if ( $checkbox['irreversible'] ) {
927  $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
928  } elseif ( $checkbox['disabled'] && !$checkbox['disabled-expiry'] ) {
929  $text = $this->msg( 'userrights-no-shorten-expiry-marker', $member )->text();
930  } else {
931  $text = $member;
932  }
933  $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
934  "wpGroup-" . $group, $checkbox['set'], $attr );
935 
936  if ( $this->canProcessExpiries() ) {
937  $uiUser = $this->getUser();
938  $uiLanguage = $this->getLanguage();
939 
940  $currentExpiry = isset( $usergroups[$group] ) ?
941  $usergroups[$group]->getExpiry() :
942  null;
943 
944  // If the user can't modify the expiry, print the current expiry below
945  // it in plain text. Otherwise provide UI to set/change the expiry
946  if ( $checkbox['set'] &&
947  ( $checkbox['irreversible'] || $checkbox['disabled-expiry'] )
948  ) {
949  if ( $currentExpiry ) {
950  $expiryFormatted = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
951  $expiryFormattedD = $uiLanguage->userDate( $currentExpiry, $uiUser );
952  $expiryFormattedT = $uiLanguage->userTime( $currentExpiry, $uiUser );
953  $expiryHtml = Xml::element( 'span', null,
954  $this->msg( 'userrights-expiry-current' )->params(
955  $expiryFormatted, $expiryFormattedD, $expiryFormattedT )->text() );
956  } else {
957  $expiryHtml = Xml::element( 'span', null,
958  $this->msg( 'userrights-expiry-none' )->text() );
959  }
960  // T171345: Add a hidden form element so that other groups can still be manipulated,
961  // otherwise saving errors out with an invalid expiry time for this group.
962  $expiryHtml .= Html::hidden( "wpExpiry-$group",
963  $currentExpiry ? 'existing' : 'infinite' );
964  $expiryHtml .= "<br />\n";
965  } else {
966  $expiryHtml = Xml::element( 'span', null,
967  $this->msg( 'userrights-expiry' )->text() );
968  $expiryHtml .= Xml::openElement( 'span' );
969 
970  // add a form element to set the expiry date
971  $expiryFormOptions = new XmlSelect(
972  "wpExpiry-$group",
973  "mw-input-wpExpiry-$group", // forward compatibility with HTMLForm
974  $currentExpiry ? 'existing' : 'infinite'
975  );
976  if ( $checkbox['disabled-expiry'] ) {
977  $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
978  }
979 
980  if ( $currentExpiry ) {
981  $timestamp = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
982  $d = $uiLanguage->userDate( $currentExpiry, $uiUser );
983  $t = $uiLanguage->userTime( $currentExpiry, $uiUser );
984  $existingExpiryMessage = $this->msg( 'userrights-expiry-existing',
985  $timestamp, $d, $t );
986  $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
987  }
988 
989  $expiryFormOptions->addOption(
990  $this->msg( 'userrights-expiry-none' )->text(),
991  'infinite'
992  );
993  $expiryFormOptions->addOption(
994  $this->msg( 'userrights-expiry-othertime' )->text(),
995  'other'
996  );
997 
998  $expiryFormOptions->addOptions( $expiryOptions );
999 
1000  // Add expiry dropdown
1001  $expiryHtml .= $expiryFormOptions->getHTML() . '<br />';
1002 
1003  // Add custom expiry field
1004  $attribs = [
1005  'id' => "mw-input-wpExpiry-$group-other",
1006  'class' => 'mw-userrights-expiryfield',
1007  ];
1008  if ( $checkbox['disabled-expiry'] ) {
1009  $attribs['disabled'] = 'disabled';
1010  }
1011  $expiryHtml .= Xml::input( "wpExpiry-$group-other", 30, '', $attribs );
1012 
1013  // If the user group is set but the checkbox is disabled, mimic a
1014  // checked checkbox in the form submission
1015  if ( $checkbox['set'] && $checkbox['disabled'] ) {
1016  $expiryHtml .= Html::hidden( "wpGroup-$group", 1 );
1017  }
1018 
1019  $expiryHtml .= Xml::closeElement( 'span' );
1020  }
1021 
1022  $divAttribs = [
1023  'id' => "mw-userrights-nested-wpGroup-$group",
1024  'class' => 'mw-userrights-nested',
1025  ];
1026  $checkboxHtml .= "\t\t\t" . Xml::tags( 'div', $divAttribs, $expiryHtml ) . "\n";
1027  }
1028  $ret .= "\t\t" . ( ( $checkbox['disabled'] && $checkbox['disabled-expiry'] )
1029  ? Xml::tags( 'div', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
1030  : Xml::tags( 'div', [], $checkboxHtml )
1031  ) . "\n";
1032  }
1033  $ret .= "\t</td>\n";
1034  }
1035  $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
1036 
1037  return [ $ret, (bool)$columns['changeable'] ];
1038  }
1039 
1044  private function canRemove( $group ) {
1045  $groups = $this->changeableGroups();
1046 
1047  return in_array(
1048  $group,
1049  $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
1050  );
1051  }
1052 
1057  private function canAdd( $group ) {
1058  $groups = $this->changeableGroups();
1059 
1060  return in_array(
1061  $group,
1062  $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
1063  );
1064  }
1065 
1076  protected function changeableGroups() {
1077  return $this->userGroupManager->getGroupsChangeableBy( $this->getContext()->getAuthority() );
1078  }
1079 
1086  protected function showLogFragment( $user, $output ) {
1087  $rightsLogPage = new LogPage( 'rights' );
1088  $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
1089  LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
1090  }
1091 
1100  public function prefixSearchSubpages( $search, $limit, $offset ) {
1101  $search = $this->userNameUtils->getCanonical( $search );
1102  if ( !$search ) {
1103  // No prefix suggestion for invalid user
1104  return [];
1105  }
1106  // Autocomplete subpage as user list - public to allow caching
1107  return $this->userNamePrefixSearch
1108  ->search( UserNamePrefixSearch::AUDIENCE_PUBLIC, $search, $limit, $offset );
1109  }
1110 
1111  protected function getGroupName() {
1112  return 'users';
1113  }
1114 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:743
SpecialPage\msg
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:911
UserrightsPage\canRemove
canRemove( $group)
Definition: SpecialUserrights.php:1044
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
UserBlockedError
Show an error when the user tries to do something whilst blocked.
Definition: UserBlockedError.php:32
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:789
UserrightsPage\editUserGroupsForm
editUserGroupsForm( $username)
Edit user groups membership.
Definition: SpecialUserrights.php:519
WikiMap\isCurrentWikiId
static isCurrentWikiId( $wikiId)
Definition: WikiMap.php:321
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:180
UserrightsPage\__construct
__construct(UserGroupManagerFactory $userGroupManagerFactory=null, UserNameUtils $userNameUtils=null, UserNamePrefixSearch $userNamePrefixSearch=null)
Definition: SpecialUserrights.php:63
Xml\label
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:364
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1692
Linker\userToolLinks
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:945
UserRightsProxy\validDatabase
static validDatabase( $dbDomain)
Confirm the selected database name is a valid local interwiki database name.
Definition: UserRightsProxy.php:71
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:589
UserrightsPage\switchForm
switchForm()
Output a form to allow searching for a user.
Definition: SpecialUserrights.php:638
SpecialPage\getSkin
getSkin()
Shortcut to get the skin being used for this instance.
Definition: SpecialPage.php:819
UserrightsPage\execute
execute( $par)
Manage forms to be shown according to posted data.
Definition: SpecialUserrights.php:122
SpecialPage\getAuthority
getAuthority()
Shortcut to get the Authority executing this instance.
Definition: SpecialPage.php:809
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:829
UserrightsPage\userCanChangeRights
userCanChangeRights( $targetUser, $checkIfSelf=true)
Check whether the current user (from context) can change the target user's rights.
Definition: SpecialUserrights.php:92
XmlSelect\parseOptionsMessage
static parseOptionsMessage(string $msg)
Parse labels and values out of a comma- and colon-separated list of options, such as is used for expi...
Definition: XmlSelect.php:146
Xml\openElement
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:110
UserrightsPage\showLogFragment
showLogFragment( $user, $output)
Show a rights log fragment for the specified user.
Definition: SpecialUserrights.php:1086
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2290
XmlSelect
Class for generating HTML <select> or <datalist> elements.
Definition: XmlSelect.php:26
UserrightsPage\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialUserrights.php:1111
Xml\fieldset
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:622
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:318
UserrightsPage\expiryToTimestamp
static expiryToTimestamp( $expiry)
Converts a user group membership expiry string into a timestamp.
Definition: SpecialUserrights.php:283
UserrightsPage\prefixSearchSubpages
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
Definition: SpecialUserrights.php:1100
MediaWiki\User\UserGroupManager
Managers user groups.
Definition: UserGroupManager.php:52
UserrightsPage\getAllGroups
static getAllGroups()
Definition: SpecialUserrights.php:835
UserrightsPage
Special page to allow managing user group membership.
Definition: SpecialUserrights.php:35
SpecialPage\addHelpLink
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: SpecialPage.php:947
SpecialPage\getHookRunner
getHookRunner()
Definition: SpecialPage.php:1094
UserrightsPage\showEditUserGroupsForm
showEditUserGroupsForm( $user, $groups, $groupMemberships)
Show the form to edit group memberships.
Definition: SpecialUserrights.php:683
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:877
UserrightsPage\serialiseUgmForLog
static serialiseUgmForLog( $ugm)
Serialise a UserGroupMembership object for storage in the log_params section of the logging table.
Definition: SpecialUserrights.php:465
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2375
UserGroupMembership\getLink
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
Definition: UserGroupMembership.php:121
UserrightsPage\fetchUser
fetchUser( $username, $writing=true)
Normalize the input username, which may be local or remote, and return a user (or proxy) object for m...
Definition: SpecialUserrights.php:551
MediaWiki\User\UserNamePrefixSearch
Handles searching prefixes of user names.
Definition: UserNamePrefixSearch.php:39
User\isHidden
isHidden()
Check if user account is hidden.
Definition: User.php:2039
LogPage
Class to simplify the use of log pages.
Definition: LogPage.php:38
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
UserrightsPage\addLogEntry
addLogEntry( $user, array $oldGroups, array $newGroups, $reason, array $tags, array $oldUGMs, array $newUGMs)
Add a rights log entry for an action.
Definition: SpecialUserrights.php:482
UserrightsPage\canProcessExpiries
canProcessExpiries()
Returns true if this user rights form can set and change user group expiries.
Definition: SpecialUserrights.php:270
SpecialPage\setHeaders
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
Definition: SpecialPage.php:617
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:799
User\clearInstanceCache
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
Definition: User.php:1532
LogEventsList\showLogExtract
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Definition: LogEventsList.php:607
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1721
UserrightsPage\getSuccessURL
getSuccessURL()
Definition: SpecialUserrights.php:260
UserrightsPage\canAdd
canAdd( $group)
Definition: SpecialUserrights.php:1057
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
Html\errorBox
static errorBox( $html, $heading='', $className='')
Return an error box.
Definition: Html.php:742
SpecialPage\getContext
getContext()
Gets the context this SpecialPage is executed in.
Definition: SpecialPage.php:763
Html\hidden
static hidden( $name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:805
MediaWiki\User\UserGroupManagerFactory
Factory service for UserGroupManager instances.
Definition: UserGroupManagerFactory.php:36
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:899
Linker\TOOL_LINKS_EMAIL
const TOOL_LINKS_EMAIL
Definition: Linker.php:42
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
SpecialPage
Parent class for all special pages.
Definition: SpecialPage.php:43
Xml\tags
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:132
UserrightsPage\groupCheckboxes
groupCheckboxes( $usergroups, $user)
Adds a table with checkboxes where you can select what groups to add/remove.
Definition: SpecialUserrights.php:852
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2615
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:779
UserRightsProxy\newFromName
static newFromName( $dbDomain, $name, $ignoreInvalidDB=false)
Factory function; get a remote user entry by name.
Definition: UserRightsProxy.php:113
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1456
UserrightsPage\doesWrites
doesWrites()
Indicates whether this special page may perform database writes.
Definition: SpecialUserrights.php:79
UserRightsProxy\whoIs
static whoIs( $dbDomain, $id, $ignoreInvalidDB=false)
Same as User::whoIs()
Definition: UserRightsProxy.php:84
UserrightsPage\saveUserGroups
saveUserGroups( $username, $reason, $user)
Save user groups changes in the database.
Definition: SpecialUserrights.php:308
CommentStore\COMMENT_CHARACTER_LIMIT
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
Definition: CommentStore.php:48
UserrightsPage\$mFetchedUser
null User $mFetchedUser
The user object of the target username or null.
Definition: SpecialUserrights.php:46
UserrightsPage\$userGroupManager
UserGroupManager $userGroupManager
Definition: SpecialUserrights.php:50
Xml\closeElement
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:119
MediaWiki\User\UserNameUtils
UserNameUtils service.
Definition: UserNameUtils.php:42
UserrightsPage\makeGroupNameList
makeGroupNameList( $ids)
Definition: SpecialUserrights.php:627
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:254
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
UserrightsPage\doSaveUserGroups
doSaveUserGroups( $user, array $add, array $remove, $reason='', array $tags=[], array $groupExpiries=[])
Save user groups changes in the database.
Definition: SpecialUserrights.php:381
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:43
UserrightsPage\$userNamePrefixSearch
UserNamePrefixSearch $userNamePrefixSearch
Definition: SpecialUserrights.php:56
UserrightsPage\$mTarget
null string $mTarget
The target of the local right-adjuster's interest.
Definition: SpecialUserrights.php:42
Xml\input
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:280
UserrightsPage\$userNameUtils
UserNameUtils $userNameUtils
Definition: SpecialUserrights.php:53
SpecialPage\checkReadOnly
checkReadOnly()
If the wiki is currently in readonly mode, throws a ReadOnlyError.
Definition: SpecialPage.php:370
$t
$t
Definition: testCompression.php:74
UserrightsPage\changeableGroups
changeableGroups()
Returns $this->getUser()->changeableGroups()
Definition: SpecialUserrights.php:1076
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:234
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:67
Xml\inputLabel
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:386
UserGroupMembership\getGroupMemberName
static getGroupMemberName( $group, $username)
Gets the localized name for a member of a group, if it exists.
Definition: UserGroupMembership.php:200
SpecialPage\outputHeader
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
Definition: SpecialPage.php:708
UserGroupMembership
Represents a "user group membership" – a specific instance of a user belonging to a group.
Definition: UserGroupMembership.php:36
UserrightsPage\$isself
$isself
Definition: SpecialUserrights.php:47
Xml\submitButton
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:465
Xml\checkLabel
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:425