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