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