MediaWiki  1.34.0
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(
131  Html::rawElement(
132  'div',
133  [
134  'class' => 'mw-notify-success successbox',
135  'id' => 'mw-preferences-success',
136  'data-mw-autohide' => 'false',
137  ],
138  Html::element(
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( $block );
173  }
174  }
175 
176  $this->checkReadOnly();
177 
178  // save settings
179  if ( !$fetchedStatus->isOK() ) {
180  $this->getOutput()->addWikiTextAsInterface(
181  $fetchedStatus->getWikiText( false, false, $this->getLanguage() )
182  );
183 
184  return;
185  }
186 
187  $targetUser = $this->mFetchedUser;
188  if ( $targetUser instanceof User ) { // UserRightsProxy doesn't have this method (T63252)
189  $targetUser->clearInstanceCache(); // T40989
190  }
191 
192  $conflictCheck = $request->getVal( 'conflictcheck-originalgroups' );
193  $conflictCheck = ( $conflictCheck === '' ) ? [] : explode( ',', $conflictCheck );
194  $userGroups = $targetUser->getGroups();
195 
196  if ( $userGroups !== $conflictCheck ) {
197  $out->wrapWikiMsg( '<span class="error">$1</span>', 'userrights-conflict' );
198  } else {
199  $status = $this->saveUserGroups(
200  $this->mTarget,
201  $request->getVal( 'user-reason' ),
202  $targetUser
203  );
204 
205  if ( $status->isOK() ) {
206  // Set session data for the success message
207  $session->set( 'specialUserrightsSaveSuccess', 1 );
208 
209  $out->redirect( $this->getSuccessURL() );
210  return;
211  } else {
212  // Print an error message and redisplay the form
213  $out->wrapWikiTextAsInterface(
214  'error', $status->getWikiText( false, false, $this->getLanguage() )
215  );
216  }
217  }
218  }
219 
220  // show some more forms
221  if ( $this->mTarget !== null ) {
222  $this->editUserGroupsForm( $this->mTarget );
223  }
224  }
225 
226  function getSuccessURL() {
227  return $this->getPageTitle( $this->mTarget )->getFullURL();
228  }
229 
236  public function canProcessExpiries() {
237  return true;
238  }
239 
249  public static function expiryToTimestamp( $expiry ) {
250  if ( wfIsInfinity( $expiry ) ) {
251  return null;
252  }
253 
254  $unix = strtotime( $expiry );
255 
256  if ( !$unix || $unix === -1 ) {
257  return false;
258  }
259 
260  // @todo FIXME: Non-qualified absolute times are not in users specified timezone
261  // and there isn't notice about it in the ui (see ProtectionForm::getExpiry)
262  return wfTimestamp( TS_MW, $unix );
263  }
264 
274  protected function saveUserGroups( $username, $reason, $user ) {
275  $allgroups = $this->getAllGroups();
276  $addgroup = [];
277  $groupExpiries = []; // associative array of (group name => expiry)
278  $removegroup = [];
279  $existingUGMs = $user->getGroupMemberships();
280 
281  // This could possibly create a highly unlikely race condition if permissions are changed between
282  // when the form is loaded and when the form is saved. Ignoring it for the moment.
283  foreach ( $allgroups as $group ) {
284  // We'll tell it to remove all unchecked groups, and add all checked groups.
285  // Later on, this gets filtered for what can actually be removed
286  if ( $this->getRequest()->getCheck( "wpGroup-$group" ) ) {
287  $addgroup[] = $group;
288 
289  if ( $this->canProcessExpiries() ) {
290  // read the expiry information from the request
291  $expiryDropdown = $this->getRequest()->getVal( "wpExpiry-$group" );
292  if ( $expiryDropdown === 'existing' ) {
293  continue;
294  }
295 
296  if ( $expiryDropdown === 'other' ) {
297  $expiryValue = $this->getRequest()->getVal( "wpExpiry-$group-other" );
298  } else {
299  $expiryValue = $expiryDropdown;
300  }
301 
302  // validate the expiry
303  $groupExpiries[$group] = self::expiryToTimestamp( $expiryValue );
304 
305  if ( $groupExpiries[$group] === false ) {
306  return Status::newFatal( 'userrights-invalid-expiry', $group );
307  }
308 
309  // not allowed to have things expiring in the past
310  if ( $groupExpiries[$group] && $groupExpiries[$group] < wfTimestampNow() ) {
311  return Status::newFatal( 'userrights-expiry-in-past', $group );
312  }
313 
314  // if the user can only add this group (not remove it), the expiry time
315  // cannot be brought forward (T156784)
316  if ( !$this->canRemove( $group ) &&
317  isset( $existingUGMs[$group] ) &&
318  ( $existingUGMs[$group]->getExpiry() ?: 'infinity' ) >
319  ( $groupExpiries[$group] ?: 'infinity' )
320  ) {
321  return Status::newFatal( 'userrights-cannot-shorten-expiry', $group );
322  }
323  }
324  } else {
325  $removegroup[] = $group;
326  }
327  }
328 
329  $this->doSaveUserGroups( $user, $addgroup, $removegroup, $reason, [], $groupExpiries );
330 
331  return Status::newGood();
332  }
333 
347  function doSaveUserGroups( $user, array $add, array $remove, $reason = '',
348  array $tags = [], array $groupExpiries = []
349  ) {
350  // Validate input set...
351  $isself = $user->getName() == $this->getUser()->getName();
352  $groups = $user->getGroups();
353  $ugms = $user->getGroupMemberships();
354  $changeable = $this->changeableGroups();
355  $addable = array_merge( $changeable['add'], $isself ? $changeable['add-self'] : [] );
356  $removable = array_merge( $changeable['remove'], $isself ? $changeable['remove-self'] : [] );
357 
358  $remove = array_unique(
359  array_intersect( (array)$remove, $removable, $groups ) );
360  $add = array_intersect( (array)$add, $addable );
361 
362  // add only groups that are not already present or that need their expiry updated,
363  // UNLESS the user can only add this group (not remove it) and the expiry time
364  // is being brought forward (T156784)
365  $add = array_filter( $add,
366  function ( $group ) use ( $groups, $groupExpiries, $removable, $ugms ) {
367  if ( isset( $groupExpiries[$group] ) &&
368  !in_array( $group, $removable ) &&
369  isset( $ugms[$group] ) &&
370  ( $ugms[$group]->getExpiry() ?: 'infinity' ) >
371  ( $groupExpiries[$group] ?: 'infinity' )
372  ) {
373  return false;
374  }
375  return !in_array( $group, $groups ) || array_key_exists( $group, $groupExpiries );
376  } );
377 
378  Hooks::run( 'ChangeUserGroups', [ $this->getUser(), $user, &$add, &$remove ] );
379 
380  $oldGroups = $groups;
381  $oldUGMs = $user->getGroupMemberships();
382  $newGroups = $oldGroups;
383 
384  // Remove groups, then add new ones/update expiries of existing ones
385  if ( $remove ) {
386  foreach ( $remove as $index => $group ) {
387  if ( !$user->removeGroup( $group ) ) {
388  unset( $remove[$index] );
389  }
390  }
391  $newGroups = array_diff( $newGroups, $remove );
392  }
393  if ( $add ) {
394  foreach ( $add as $index => $group ) {
395  $expiry = $groupExpiries[$group] ?? null;
396  if ( !$user->addGroup( $group, $expiry ) ) {
397  unset( $add[$index] );
398  }
399  }
400  $newGroups = array_merge( $newGroups, $add );
401  }
402  $newGroups = array_unique( $newGroups );
403  $newUGMs = $user->getGroupMemberships();
404 
405  // Ensure that caches are cleared
406  $user->invalidateCache();
407 
408  // update groups in external authentication database
409  Hooks::run( 'UserGroupsChanged', [ $user, $add, $remove, $this->getUser(),
410  $reason, $oldUGMs, $newUGMs ] );
411 
412  wfDebug( 'oldGroups: ' . print_r( $oldGroups, true ) . "\n" );
413  wfDebug( 'newGroups: ' . print_r( $newGroups, true ) . "\n" );
414  wfDebug( 'oldUGMs: ' . print_r( $oldUGMs, true ) . "\n" );
415  wfDebug( 'newUGMs: ' . print_r( $newUGMs, true ) . "\n" );
416 
417  // Only add a log entry if something actually changed
418  if ( $newGroups != $oldGroups || $newUGMs != $oldUGMs ) {
419  $this->addLogEntry( $user, $oldGroups, $newGroups, $reason, $tags, $oldUGMs, $newUGMs );
420  }
421 
422  return [ $add, $remove ];
423  }
424 
432  protected static function serialiseUgmForLog( $ugm ) {
433  if ( !$ugm instanceof UserGroupMembership ) {
434  return null;
435  }
436  return [ 'expiry' => $ugm->getExpiry() ];
437  }
438 
449  protected function addLogEntry( $user, array $oldGroups, array $newGroups, $reason,
450  array $tags, array $oldUGMs, array $newUGMs
451  ) {
452  // make sure $oldUGMs and $newUGMs are in the same order, and serialise
453  // each UGM object to a simplified array
454  $oldUGMs = array_map( function ( $group ) use ( $oldUGMs ) {
455  return isset( $oldUGMs[$group] ) ?
456  self::serialiseUgmForLog( $oldUGMs[$group] ) :
457  null;
458  }, $oldGroups );
459  $newUGMs = array_map( function ( $group ) use ( $newUGMs ) {
460  return isset( $newUGMs[$group] ) ?
461  self::serialiseUgmForLog( $newUGMs[$group] ) :
462  null;
463  }, $newGroups );
464 
465  $logEntry = new ManualLogEntry( 'rights', 'rights' );
466  $logEntry->setPerformer( $this->getUser() );
467  $logEntry->setTarget( $user->getUserPage() );
468  $logEntry->setComment( $reason );
469  $logEntry->setParameters( [
470  '4::oldgroups' => $oldGroups,
471  '5::newgroups' => $newGroups,
472  'oldmetadata' => $oldUGMs,
473  'newmetadata' => $newUGMs,
474  ] );
475  $logid = $logEntry->insert();
476  if ( count( $tags ) ) {
477  $logEntry->addTags( $tags );
478  }
479  $logEntry->publish( $logid );
480  }
481 
486  function editUserGroupsForm( $username ) {
487  $status = $this->fetchUser( $username, true );
488  if ( !$status->isOK() ) {
489  $this->getOutput()->addWikiTextAsInterface(
490  $status->getWikiText( false, false, $this->getLanguage() )
491  );
492 
493  return;
494  }
495 
497  $user = $status->value;
498  '@phan-var User $user';
499 
500  $groups = $user->getGroups();
501  $groupMemberships = $user->getGroupMemberships();
502  $this->showEditUserGroupsForm( $user, $groups, $groupMemberships );
503 
504  // This isn't really ideal logging behavior, but let's not hide the
505  // interwiki logs if we're using them as is.
506  $this->showLogFragment( $user, $this->getOutput() );
507  }
508 
518  public function fetchUser( $username, $writing = true ) {
519  $parts = explode( $this->getConfig()->get( 'UserrightsInterwikiDelimiter' ), $username );
520  if ( count( $parts ) < 2 ) {
521  $name = trim( $username );
522  $dbDomain = '';
523  } else {
524  list( $name, $dbDomain ) = array_map( 'trim', $parts );
525 
526  if ( WikiMap::isCurrentWikiId( $dbDomain ) ) {
527  $dbDomain = '';
528  } else {
529  if ( $writing && !MediaWikiServices::getInstance()
531  ->userHasRight( $this->getUser(), 'userrights-interwiki' )
532  ) {
533  return Status::newFatal( 'userrights-no-interwiki' );
534  }
535  if ( !UserRightsProxy::validDatabase( $dbDomain ) ) {
536  return Status::newFatal( 'userrights-nodatabase', $dbDomain );
537  }
538  }
539  }
540 
541  if ( $name === '' ) {
542  return Status::newFatal( 'nouserspecified' );
543  }
544 
545  if ( $name[0] == '#' ) {
546  // Numeric ID can be specified...
547  // We'll do a lookup for the name internally.
548  $id = intval( substr( $name, 1 ) );
549 
550  if ( $dbDomain == '' ) {
551  $name = User::whoIs( $id );
552  } else {
553  $name = UserRightsProxy::whoIs( $dbDomain, $id );
554  }
555 
556  if ( !$name ) {
557  return Status::newFatal( 'noname' );
558  }
559  } else {
560  $name = User::getCanonicalName( $name );
561  if ( $name === false ) {
562  // invalid name
563  return Status::newFatal( 'nosuchusershort', $username );
564  }
565  }
566 
567  if ( $dbDomain == '' ) {
568  $user = User::newFromName( $name );
569  } else {
570  $user = UserRightsProxy::newFromName( $dbDomain, $name );
571  }
572 
573  if ( !$user || $user->isAnon() ) {
574  return Status::newFatal( 'nosuchusershort', $username );
575  }
576 
577  return Status::newGood( $user );
578  }
579 
587  public function makeGroupNameList( $ids ) {
588  if ( empty( $ids ) ) {
589  return $this->msg( 'rightsnone' )->inContentLanguage()->text();
590  } else {
591  return implode( ', ', $ids );
592  }
593  }
594 
598  function switchForm() {
599  $this->getOutput()->addModules( 'mediawiki.userSuggest' );
600 
601  $this->getOutput()->addHTML(
602  Html::openElement(
603  'form',
604  [
605  'method' => 'get',
606  'action' => wfScript(),
607  'name' => 'uluser',
608  'id' => 'mw-userrights-form1'
609  ]
610  ) .
611  Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
612  Xml::fieldset( $this->msg( 'userrights-lookup-user' )->text() ) .
614  $this->msg( 'userrights-user-editname' )->text(),
615  'user',
616  'username',
617  30,
618  str_replace( '_', ' ', $this->mTarget ),
619  [
620  'class' => 'mw-autocomplete-user', // used by mediawiki.userSuggest
621  ] + (
622  // Set autofocus on blank input and error input
623  $this->mFetchedUser === null ? [ 'autofocus' => '' ] : []
624  )
625  ) . ' ' .
627  $this->msg( 'editusergroup' )->text()
628  ) .
629  Html::closeElement( 'fieldset' ) .
630  Html::closeElement( 'form' ) . "\n"
631  );
632  }
633 
643  protected function showEditUserGroupsForm( $user, $groups, $groupMemberships ) {
644  $list = $membersList = $tempList = $tempMembersList = [];
645  foreach ( $groupMemberships as $ugm ) {
646  $linkG = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html' );
647  $linkM = UserGroupMembership::getLink( $ugm, $this->getContext(), 'html',
648  $user->getName() );
649  if ( $ugm->getExpiry() ) {
650  $tempList[] = $linkG;
651  $tempMembersList[] = $linkM;
652  } else {
653  $list[] = $linkG;
654  $membersList[] = $linkM;
655 
656  }
657  }
658 
659  $autoList = [];
660  $autoMembersList = [];
661  if ( $user instanceof User ) {
662  foreach ( Autopromote::getAutopromoteGroups( $user ) as $group ) {
663  $autoList[] = UserGroupMembership::getLink( $group, $this->getContext(), 'html' );
664  $autoMembersList[] = UserGroupMembership::getLink( $group, $this->getContext(),
665  'html', $user->getName() );
666  }
667  }
668 
669  $language = $this->getLanguage();
670  $displayedList = $this->msg( 'userrights-groupsmember-type' )
671  ->rawParams(
672  $language->commaList( array_merge( $tempList, $list ) ),
673  $language->commaList( array_merge( $tempMembersList, $membersList ) )
674  )->escaped();
675  $displayedAutolist = $this->msg( 'userrights-groupsmember-type' )
676  ->rawParams(
677  $language->commaList( $autoList ),
678  $language->commaList( $autoMembersList )
679  )->escaped();
680 
681  $grouplist = '';
682  $count = count( $list ) + count( $tempList );
683  if ( $count > 0 ) {
684  $grouplist = $this->msg( 'userrights-groupsmember' )
685  ->numParams( $count )
686  ->params( $user->getName() )
687  ->parse();
688  $grouplist = '<p>' . $grouplist . ' ' . $displayedList . "</p>\n";
689  }
690 
691  $count = count( $autoList );
692  if ( $count > 0 ) {
693  $autogrouplistintro = $this->msg( 'userrights-groupsmember-auto' )
694  ->numParams( $count )
695  ->params( $user->getName() )
696  ->parse();
697  $grouplist .= '<p>' . $autogrouplistintro . ' ' . $displayedAutolist . "</p>\n";
698  }
699 
700  $userToolLinks = Linker::userToolLinks(
701  $user->getId(),
702  $user->getName(),
703  false, /* default for redContribsWhenNoEdits */
704  Linker::TOOL_LINKS_EMAIL /* Add "send e-mail" link */
705  );
706 
707  list( $groupCheckboxes, $canChangeAny ) =
708  $this->groupCheckboxes( $groupMemberships, $user );
709  $this->getOutput()->addHTML(
711  'form',
712  [
713  'method' => 'post',
714  'action' => $this->getPageTitle()->getLocalURL(),
715  'name' => 'editGroup',
716  'id' => 'mw-userrights-form2'
717  ]
718  ) .
719  Html::hidden( 'user', $this->mTarget ) .
720  Html::hidden( 'wpEditToken', $this->getUser()->getEditToken( $this->mTarget ) ) .
721  Html::hidden(
722  'conflictcheck-originalgroups',
723  implode( ',', $user->getGroups() )
724  ) . // Conflict detection
725  Xml::openElement( 'fieldset' ) .
726  Xml::element(
727  'legend',
728  [],
729  $this->msg(
730  $canChangeAny ? 'userrights-editusergroup' : 'userrights-viewusergroup',
731  $user->getName()
732  )->text()
733  ) .
734  $this->msg(
735  $canChangeAny ? 'editinguser' : 'viewinguserrights'
736  )->params( wfEscapeWikiText( $user->getName() ) )
737  ->rawParams( $userToolLinks )->parse()
738  );
739  if ( $canChangeAny ) {
740  $this->getOutput()->addHTML(
741  $this->msg( 'userrights-groups-help', $user->getName() )->parse() .
742  $grouplist .
743  $groupCheckboxes .
744  Xml::openElement( 'table', [ 'id' => 'mw-userrights-table-outer' ] ) .
745  "<tr>
746  <td class='mw-label'>" .
747  Xml::label( $this->msg( 'userrights-reason' )->text(), 'wpReason' ) .
748  "</td>
749  <td class='mw-input'>" .
750  Xml::input( 'user-reason', 60, $this->getRequest()->getVal( 'user-reason', false ), [
751  'id' => 'wpReason',
752  // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
753  // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
754  // Unicode codepoints.
756  ] ) .
757  "</td>
758  </tr>
759  <tr>
760  <td></td>
761  <td class='mw-submit'>" .
762  Xml::submitButton( $this->msg( 'saveusergroups', $user->getName() )->text(),
763  [ 'name' => 'saveusergroups' ] +
764  Linker::tooltipAndAccesskeyAttribs( 'userrights-set' )
765  ) .
766  "</td>
767  </tr>" .
768  Xml::closeElement( 'table' ) . "\n"
769  );
770  } else {
771  $this->getOutput()->addHTML( $grouplist );
772  }
773  $this->getOutput()->addHTML(
774  Xml::closeElement( 'fieldset' ) .
775  Xml::closeElement( 'form' ) . "\n"
776  );
777  }
778 
783  protected static function getAllGroups() {
784  return User::getAllGroups();
785  }
786 
796  private function groupCheckboxes( $usergroups, $user ) {
797  $allgroups = $this->getAllGroups();
798  $ret = '';
799 
800  // Get the list of preset expiry times from the system message
801  $expiryOptionsMsg = $this->msg( 'userrights-expiry-options' )->inContentLanguage();
802  $expiryOptions = $expiryOptionsMsg->isDisabled() ?
803  [] :
804  explode( ',', $expiryOptionsMsg->text() );
805 
806  // Put all column info into an associative array so that extensions can
807  // more easily manage it.
808  $columns = [ 'unchangeable' => [], 'changeable' => [] ];
809 
810  foreach ( $allgroups as $group ) {
811  $set = isset( $usergroups[$group] );
812  // Users who can add the group, but not remove it, can only lengthen
813  // expiries, not shorten them. So they should only see the expiry
814  // dropdown if the group currently has a finite expiry
815  $canOnlyLengthenExpiry = ( $set && $this->canAdd( $group ) &&
816  !$this->canRemove( $group ) && $usergroups[$group]->getExpiry() );
817  // Should the checkbox be disabled?
818  $disabledCheckbox = !(
819  ( $set && $this->canRemove( $group ) ) ||
820  ( !$set && $this->canAdd( $group ) ) );
821  // Should the expiry elements be disabled?
822  $disabledExpiry = $disabledCheckbox && !$canOnlyLengthenExpiry;
823  // Do we need to point out that this action is irreversible?
824  $irreversible = !$disabledCheckbox && (
825  ( $set && !$this->canAdd( $group ) ) ||
826  ( !$set && !$this->canRemove( $group ) ) );
827 
828  $checkbox = [
829  'set' => $set,
830  'disabled' => $disabledCheckbox,
831  'disabled-expiry' => $disabledExpiry,
832  'irreversible' => $irreversible
833  ];
834 
835  if ( $disabledCheckbox && $disabledExpiry ) {
836  $columns['unchangeable'][$group] = $checkbox;
837  } else {
838  $columns['changeable'][$group] = $checkbox;
839  }
840  }
841 
842  // Build the HTML table
843  $ret .= Xml::openElement( 'table', [ 'class' => 'mw-userrights-groups' ] ) .
844  "<tr>\n";
845  foreach ( $columns as $name => $column ) {
846  if ( $column === [] ) {
847  continue;
848  }
849  // Messages: userrights-changeable-col, userrights-unchangeable-col
850  $ret .= Xml::element(
851  'th',
852  null,
853  $this->msg( 'userrights-' . $name . '-col', count( $column ) )->text()
854  );
855  }
856 
857  $ret .= "</tr>\n<tr>\n";
858  foreach ( $columns as $column ) {
859  if ( $column === [] ) {
860  continue;
861  }
862  $ret .= "\t<td style='vertical-align:top;'>\n";
863  foreach ( $column as $group => $checkbox ) {
864  $attr = [ 'class' => 'mw-userrights-groupcheckbox' ];
865  if ( $checkbox['disabled'] ) {
866  $attr['disabled'] = 'disabled';
867  }
868 
869  $member = UserGroupMembership::getGroupMemberName( $group, $user->getName() );
870  if ( $checkbox['irreversible'] ) {
871  $text = $this->msg( 'userrights-irreversible-marker', $member )->text();
872  } elseif ( $checkbox['disabled'] && !$checkbox['disabled-expiry'] ) {
873  $text = $this->msg( 'userrights-no-shorten-expiry-marker', $member )->text();
874  } else {
875  $text = $member;
876  }
877  $checkboxHtml = Xml::checkLabel( $text, "wpGroup-" . $group,
878  "wpGroup-" . $group, $checkbox['set'], $attr );
879 
880  if ( $this->canProcessExpiries() ) {
881  $uiUser = $this->getUser();
882  $uiLanguage = $this->getLanguage();
883 
884  $currentExpiry = isset( $usergroups[$group] ) ?
885  $usergroups[$group]->getExpiry() :
886  null;
887 
888  // If the user can't modify the expiry, print the current expiry below
889  // it in plain text. Otherwise provide UI to set/change the expiry
890  if ( $checkbox['set'] &&
891  ( $checkbox['irreversible'] || $checkbox['disabled-expiry'] )
892  ) {
893  if ( $currentExpiry ) {
894  $expiryFormatted = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
895  $expiryFormattedD = $uiLanguage->userDate( $currentExpiry, $uiUser );
896  $expiryFormattedT = $uiLanguage->userTime( $currentExpiry, $uiUser );
897  $expiryHtml = $this->msg( 'userrights-expiry-current' )->params(
898  $expiryFormatted, $expiryFormattedD, $expiryFormattedT )->text();
899  } else {
900  $expiryHtml = $this->msg( 'userrights-expiry-none' )->text();
901  }
902  // T171345: Add a hidden form element so that other groups can still be manipulated,
903  // otherwise saving errors out with an invalid expiry time for this group.
904  $expiryHtml .= Html::hidden( "wpExpiry-$group",
905  $currentExpiry ? 'existing' : 'infinite' );
906  $expiryHtml .= "<br />\n";
907  } else {
908  $expiryHtml = Xml::element( 'span', null,
909  $this->msg( 'userrights-expiry' )->text() );
910  $expiryHtml .= Xml::openElement( 'span' );
911 
912  // add a form element to set the expiry date
913  $expiryFormOptions = new XmlSelect(
914  "wpExpiry-$group",
915  "mw-input-wpExpiry-$group", // forward compatibility with HTMLForm
916  $currentExpiry ? 'existing' : 'infinite'
917  );
918  if ( $checkbox['disabled-expiry'] ) {
919  $expiryFormOptions->setAttribute( 'disabled', 'disabled' );
920  }
921 
922  if ( $currentExpiry ) {
923  $timestamp = $uiLanguage->userTimeAndDate( $currentExpiry, $uiUser );
924  $d = $uiLanguage->userDate( $currentExpiry, $uiUser );
925  $t = $uiLanguage->userTime( $currentExpiry, $uiUser );
926  $existingExpiryMessage = $this->msg( 'userrights-expiry-existing',
927  $timestamp, $d, $t );
928  $expiryFormOptions->addOption( $existingExpiryMessage->text(), 'existing' );
929  }
930 
931  $expiryFormOptions->addOption(
932  $this->msg( 'userrights-expiry-none' )->text(),
933  'infinite'
934  );
935  $expiryFormOptions->addOption(
936  $this->msg( 'userrights-expiry-othertime' )->text(),
937  'other'
938  );
939  foreach ( $expiryOptions as $option ) {
940  if ( strpos( $option, ":" ) === false ) {
941  $displayText = $value = $option;
942  } else {
943  list( $displayText, $value ) = explode( ":", $option );
944  }
945  $expiryFormOptions->addOption( $displayText, htmlspecialchars( $value ) );
946  }
947 
948  // Add expiry dropdown
949  $expiryHtml .= $expiryFormOptions->getHTML() . '<br />';
950 
951  // Add custom expiry field
952  $attribs = [
953  'id' => "mw-input-wpExpiry-$group-other",
954  'class' => 'mw-userrights-expiryfield',
955  ];
956  if ( $checkbox['disabled-expiry'] ) {
957  $attribs['disabled'] = 'disabled';
958  }
959  $expiryHtml .= Xml::input( "wpExpiry-$group-other", 30, '', $attribs );
960 
961  // If the user group is set but the checkbox is disabled, mimic a
962  // checked checkbox in the form submission
963  if ( $checkbox['set'] && $checkbox['disabled'] ) {
964  $expiryHtml .= Html::hidden( "wpGroup-$group", 1 );
965  }
966 
967  $expiryHtml .= Xml::closeElement( 'span' );
968  }
969 
970  $divAttribs = [
971  'id' => "mw-userrights-nested-wpGroup-$group",
972  'class' => 'mw-userrights-nested',
973  ];
974  $checkboxHtml .= "\t\t\t" . Xml::tags( 'div', $divAttribs, $expiryHtml ) . "\n";
975  }
976  $ret .= "\t\t" . ( ( $checkbox['disabled'] && $checkbox['disabled-expiry'] )
977  ? Xml::tags( 'div', [ 'class' => 'mw-userrights-disabled' ], $checkboxHtml )
978  : Xml::tags( 'div', [], $checkboxHtml )
979  ) . "\n";
980  }
981  $ret .= "\t</td>\n";
982  }
983  $ret .= Xml::closeElement( 'tr' ) . Xml::closeElement( 'table' );
984 
985  return [ $ret, (bool)$columns['changeable'] ];
986  }
987 
992  private function canRemove( $group ) {
993  $groups = $this->changeableGroups();
994 
995  return in_array(
996  $group,
997  $groups['remove'] ) || ( $this->isself && in_array( $group, $groups['remove-self'] )
998  );
999  }
1000 
1005  private function canAdd( $group ) {
1006  $groups = $this->changeableGroups();
1007 
1008  return in_array(
1009  $group,
1010  $groups['add'] ) || ( $this->isself && in_array( $group, $groups['add-self'] )
1011  );
1012  }
1013 
1024  function changeableGroups() {
1025  return $this->getUser()->changeableGroups();
1026  }
1027 
1034  protected function showLogFragment( $user, $output ) {
1035  $rightsLogPage = new LogPage( 'rights' );
1036  $output->addHTML( Xml::element( 'h2', null, $rightsLogPage->getName()->text() ) );
1037  LogEventsList::showLogExtract( $output, 'rights', $user->getUserPage() );
1038  }
1039 
1048  public function prefixSearchSubpages( $search, $limit, $offset ) {
1049  $user = User::newFromName( $search );
1050  if ( !$user ) {
1051  // No prefix suggestion for invalid user
1052  return [];
1053  }
1054  // Autocomplete subpage as user list - public to allow caching
1055  return UserNamePrefixSearch::search( 'public', $search, $limit, $offset );
1056  }
1057 
1058  protected function getGroupName() {
1059  return 'users';
1060  }
1061 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:672
SpecialPage\msg
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:792
UserrightsPage\canRemove
canRemove( $group)
Definition: SpecialUserrights.php:992
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
UserBlockedError
Show an error when the user tries to do something whilst blocked.
Definition: UserBlockedError.php:29
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:719
UserrightsPage\editUserGroupsForm
editUserGroupsForm( $username)
Edit user groups membership.
Definition: SpecialUserrights.php:486
WikiMap\isCurrentWikiId
static isCurrentWikiId( $wikiId)
Definition: WikiMap.php:312
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
Xml\label
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:358
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1869
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:943
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:63
Autopromote\getAutopromoteGroups
static getAutopromoteGroups(User $user)
Get the groups for the given user based on $wgAutopromote.
Definition: Autopromote.php:37
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:515
UserrightsPage\switchForm
switchForm()
Output a form to allow searching for a user.
Definition: SpecialUserrights.php:598
SpecialPage\getSkin
getSkin()
Shortcut to get the skin being used for this instance.
Definition: SpecialPage.php:739
UserrightsPage\execute
execute( $par)
Manage forms to be shown according to posted data.
Definition: SpecialUserrights.php:93
SpecialPage\getLanguage
getLanguage()
Shortcut to get user's language.
Definition: SpecialPage.php:749
UserrightsPage\userCanChangeRights
userCanChangeRights( $targetUser, $checkIfSelf=true)
Check whether the current user (from context) can change the target user's rights.
Definition: SpecialUserrights.php:62
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:1034
UserrightsPage\$mFetchedUser
$mFetchedUser
Definition: SpecialUserrights.php:42
Linker\tooltipAndAccesskeyAttribs
static tooltipAndAccesskeyAttribs( $name, array $msgParams=[], $options=null)
Returns the attributes for the tooltip and access key.
Definition: Linker.php:2195
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:1058
Xml\fieldset
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:609
UserrightsPage\expiryToTimestamp
static expiryToTimestamp( $expiry)
Converts a user group membership expiry string into a timestamp.
Definition: SpecialUserrights.php:249
UserrightsPage\prefixSearchSubpages
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
Definition: SpecialUserrights.php:1048
UserrightsPage\getAllGroups
static getAllGroups()
Returns an array of all groups that may be edited.
Definition: SpecialUserrights.php:783
UserrightsPage
Special page to allow managing user group membership.
Definition: SpecialUserrights.php:31
SpecialPage\addHelpLink
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: SpecialPage.php:828
UserrightsPage\showEditUserGroupsForm
showEditUserGroupsForm( $user, $groups, $groupMemberships)
Show the form to edit group memberships.
Definition: SpecialUserrights.php:643
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:758
UserrightsPage\serialiseUgmForLog
static serialiseUgmForLog( $ugm)
Serialise a UserGroupMembership object for storage in the log_params section of the logging table.
Definition: SpecialUserrights.php:432
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2642
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:376
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:518
LogPage
Class to simplify the use of log pages.
Definition: LogPage.php:33
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:449
UserrightsPage\canProcessExpiries
canProcessExpiries()
Returns true if this user rights form can set and change user group expiries.
Definition: SpecialUserrights.php:236
$t
$t
Definition: make-normalization-table.php:143
SpecialPage\setHeaders
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
Definition: SpecialPage.php:537
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:729
$output
$output
Definition: SyntaxHighlight.php:335
LogEventsList\showLogExtract
static showLogExtract(&$out, $types=[], $page='', $user='', $param=[])
Show log extract.
Definition: LogEventsList.php:624
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1898
UserrightsPage\getSuccessURL
getSuccessURL()
Definition: SpecialUserrights.php:226
UserrightsPage\canAdd
canAdd( $group)
Definition: SpecialUserrights.php:1005
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:913
UserrightsPage\__construct
__construct()
Definition: SpecialUserrights.php:45
SpecialPage\getContext
getContext()
Gets the context this SpecialPage is executed in.
Definition: SpecialPage.php:692
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:809
Linker\TOOL_LINKS_EMAIL
const TOOL_LINKS_EMAIL
Definition: Linker.php:40
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
SpecialPage
Parent class for all special pages.
Definition: SpecialPage.php:37
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:796
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2960
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:709
UserRightsProxy\newFromName
static newFromName( $dbDomain, $name, $ignoreInvalidDB=false)
Factory function; get a remote user entry by name.
Definition: UserRightsProxy.php:105
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1551
UserrightsPage\doesWrites
doesWrites()
Indicates whether this special page may perform database writes.
Definition: SpecialUserrights.php:49
User\getAllGroups
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:4808
UserRightsProxy\whoIs
static whoIs( $dbDomain, $id, $ignoreInvalidDB=false)
Same as User::whoIs()
Definition: UserRightsProxy.php:76
UserrightsPage\saveUserGroups
saveUserGroups( $username, $reason, $user)
Save user groups changes in the database.
Definition: SpecialUserrights.php:274
CommentStore\COMMENT_CHARACTER_LIMIT
const COMMENT_CHARACTER_LIMIT
Maximum length of a comment in UTF-8 characters.
Definition: CommentStore.php:37
$status
return $status
Definition: SyntaxHighlight.php:347
Xml\closeElement
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:117
UserrightsPage\makeGroupNameList
makeGroupNameList( $ids)
Definition: SpecialUserrights.php:587
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:1139
UserrightsPage\doSaveUserGroups
doSaveUserGroups( $user, array $add, array $remove, $reason='', array $tags=[], array $groupExpiries=[])
Save user groups changes in the database.
Definition: SpecialUserrights.php:347
ManualLogEntry
Class for creating new log entries and inserting them into the database.
Definition: ManualLogEntry.php:37
UserrightsPage\$mTarget
$mTarget
The target of the local right-adjuster's interest.
Definition: SpecialUserrights.php:38
Xml\input
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:274
SpecialPage\checkReadOnly
checkReadOnly()
If the wiki is currently in readonly mode, throws a ReadOnlyError.
Definition: SpecialPage.php:328
UserrightsPage\changeableGroups
changeableGroups()
Returns $this->getUser()->changeableGroups()
Definition: SpecialUserrights.php:1024
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:51
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
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:380
UserGroupMembership\getGroupMemberName
static getGroupMemberName( $group, $username)
Gets the localized name for a member of a group, if it exists.
Definition: UserGroupMembership.php:448
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:639
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:43
Xml\submitButton
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:459
Xml\checkLabel
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:419