MediaWiki  master
UsersPager.php
Go to the documentation of this file.
1 <?php
31 
39 class UsersPager extends AlphabeticPager {
40 
44  protected $userGroupCache;
45 
48 
50  protected $editsOnly;
51 
54 
56  protected $creationSort;
57 
59  protected $including;
60 
62  protected $requestedUser;
63 
66 
68  private $hookRunner;
69 
72 
83  public function __construct(
85  $par,
86  $including,
88  HookContainer $hookContainer,
89  ILoadBalancer $loadBalancer,
91  ) {
92  if ( $context ) {
93  $this->setContext( $context );
94  }
95 
96  $request = $this->getRequest();
97  $par = $par ?? '';
98  $parms = explode( '/', $par );
99  $symsForAll = [ '*', 'user' ];
100 
101  if ( $parms[0] != '' &&
102  ( in_array( $par, $userGroupManager->listAllGroups() ) || in_array( $par, $symsForAll ) )
103  ) {
104  $this->requestedGroup = $par;
105  $un = $request->getText( 'username' );
106  } elseif ( count( $parms ) == 2 ) {
107  $this->requestedGroup = $parms[0];
108  $un = $parms[1];
109  } else {
110  $this->requestedGroup = $request->getVal( 'group' );
111  $un = ( $par != '' ) ? $par : $request->getText( 'username' );
112  }
113 
114  if ( in_array( $this->requestedGroup, $symsForAll ) ) {
115  $this->requestedGroup = '';
116  }
117  $this->editsOnly = $request->getBool( 'editsOnly' );
118  $this->temporaryGroupsOnly = $request->getBool( 'temporaryGroupsOnly' );
119  $this->creationSort = $request->getBool( 'creationSort' );
120  $this->including = $including;
121  $this->mDefaultDirection = $request->getBool( 'desc' )
124 
125  $this->requestedUser = '';
126 
127  if ( $un != '' ) {
128  $username = Title::makeTitleSafe( NS_USER, $un );
129 
130  if ( $username !== null ) {
131  $this->requestedUser = $username->getText();
132  }
133  }
134 
135  // Set database before parent constructor to avoid setting it there with wfGetDB
136  $this->mDb = $loadBalancer->getConnectionRef( ILoadBalancer::DB_REPLICA );
137  parent::__construct();
138  $this->linkBatchFactory = $linkBatchFactory;
139  $this->hookRunner = new HookRunner( $hookContainer );
140  $this->userGroupManager = $userGroupManager;
141  }
142 
146  public function getIndexField() {
147  return $this->creationSort ? 'user_id' : 'user_name';
148  }
149 
153  public function getQueryInfo() {
154  $dbr = $this->getDatabase();
155  $conds = [];
156 
157  // Don't show hidden names
158  if ( !$this->canSeeHideuser() ) {
159  $conds[] = 'ipb_deleted IS NULL OR ipb_deleted = 0';
160  }
161 
162  $options = [];
163 
164  if ( $this->requestedGroup != '' || $this->temporaryGroupsOnly ) {
165  $conds[] = 'ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() ) .
166  ( !$this->temporaryGroupsOnly ? ' OR ug_expiry IS NULL' : '' );
167  }
168 
169  if ( $this->requestedGroup != '' ) {
170  $conds['ug_group'] = $this->requestedGroup;
171  }
172 
173  if ( $this->requestedUser != '' ) {
174  # Sorted either by account creation or name
175  if ( $this->creationSort ) {
176  $conds[] = 'user_id >= ' . intval( User::idFromName( $this->requestedUser ) );
177  } else {
178  $conds[] = 'user_name >= ' . $dbr->addQuotes( $this->requestedUser );
179  }
180  }
181 
182  if ( $this->editsOnly ) {
183  $conds[] = 'user_editcount > 0';
184  }
185 
186  $options['GROUP BY'] = $this->creationSort ? 'user_id' : 'user_name';
187 
188  $query = [
189  'tables' => [ 'user', 'user_groups', 'ipblocks' ],
190  'fields' => [
191  'user_name' => $this->creationSort ? 'MAX(user_name)' : 'user_name',
192  'user_id' => $this->creationSort ? 'user_id' : 'MAX(user_id)',
193  'edits' => 'MAX(user_editcount)',
194  'creation' => 'MIN(user_registration)',
195  'ipb_deleted' => 'MAX(ipb_deleted)', // block/hide status
196  'ipb_sitewide' => 'MAX(ipb_sitewide)'
197  ],
198  'options' => $options,
199  'join_conds' => [
200  'user_groups' => [ 'LEFT JOIN', 'user_id=ug_user' ],
201  'ipblocks' => [
202  'LEFT JOIN', [
203  'user_id=ipb_user',
204  'ipb_auto' => 0
205  ]
206  ],
207  ],
208  'conds' => $conds
209  ];
210 
211  $this->hookRunner->onSpecialListusersQueryInfo( $this, $query );
212 
213  return $query;
214  }
215 
220  public function formatRow( $row ) {
221  if ( $row->user_id == 0 ) { # T18487
222  return '';
223  }
224 
225  $userName = $row->user_name;
226 
227  $ulinks = Linker::userLink( $row->user_id, $userName );
229  $row->user_id,
230  $userName,
231  (int)$row->edits,
232  // don't render parentheses in HTML markup (CSS will provide)
233  false
234  );
235 
236  $lang = $this->getLanguage();
237 
238  $groups = '';
239  $ugms = self::getGroupMemberships( intval( $row->user_id ), $this->userGroupCache );
240 
241  if ( !$this->including && count( $ugms ) > 0 ) {
242  $list = [];
243  foreach ( $ugms as $ugm ) {
244  $list[] = $this->buildGroupLink( $ugm, $userName );
245  }
246  $groups = $lang->commaList( $list );
247  }
248 
249  $item = $lang->specialList( $ulinks, $groups );
250 
251  if ( $row->ipb_deleted ) {
252  $item = "<span class=\"deleted\">$item</span>";
253  }
254 
255  $edits = '';
256  if ( !$this->including && $this->getConfig()->get( 'Edititis' ) ) {
257  $count = $this->msg( 'usereditcount' )->numParams( $row->edits )->escaped();
258  $edits = $this->msg( 'word-separator' )->escaped() . $this->msg( 'brackets', $count )->escaped();
259  }
260 
261  $created = '';
262  # Some rows may be null
263  if ( !$this->including && $row->creation ) {
264  $user = $this->getUser();
265  $d = $lang->userDate( $row->creation, $user );
266  $t = $lang->userTime( $row->creation, $user );
267  $created = $this->msg( 'usercreated', $d, $t, $row->user_name )->escaped();
268  $created = ' ' . $this->msg( 'parentheses' )->rawParams( $created )->escaped();
269  }
270 
271  $blocked = $row->ipb_deleted !== null && $row->ipb_sitewide === '1' ?
272  ' ' . $this->msg( 'listusers-blocked', $userName )->escaped() :
273  '';
274 
275  $this->hookRunner->onSpecialListusersFormatRow( $item, $row );
276 
277  return Html::rawElement( 'li', [], "{$item}{$edits}{$created}{$blocked}" );
278  }
279 
280  protected function doBatchLookups() {
281  $batch = $this->linkBatchFactory->newLinkBatch();
282  $userIds = [];
283  # Give some pointers to make user links
284  foreach ( $this->mResult as $row ) {
285  $batch->add( NS_USER, $row->user_name );
286  $batch->add( NS_USER_TALK, $row->user_name );
287  $userIds[] = $row->user_id;
288  }
289 
290  // Lookup groups for all the users
291  $dbr = $this->getDatabase();
292  $groupsQueryInfo = $this->userGroupManager->getQueryInfo();
293  $groupRes = $dbr->select(
294  $groupsQueryInfo['tables'],
295  $groupsQueryInfo['fields'],
296  [ 'ug_user' => $userIds ],
297  __METHOD__,
298  $groupsQueryInfo['joins']
299  );
300  $cache = [];
301  $groups = [];
302  foreach ( $groupRes as $row ) {
303  $ugm = $this->userGroupManager->newGroupMembershipFromRow( $row );
304  if ( !$ugm->isExpired() ) {
305  $cache[$row->ug_user][$row->ug_group] = $ugm;
306  $groups[$row->ug_group] = true;
307  }
308  }
309 
310  // Give extensions a chance to add things like global user group data
311  // into the cache array to ensure proper output later on
312  $this->hookRunner->onUsersPagerDoBatchLookups( $dbr, $userIds, $cache, $groups );
313 
314  $this->userGroupCache = $cache;
315 
316  // Add page of groups to link batch
317  foreach ( $groups as $group => $unused ) {
318  $groupPage = UserGroupMembership::getGroupPage( $group );
319  if ( $groupPage ) {
320  $batch->addObj( $groupPage );
321  }
322  }
323 
324  $batch->execute();
325  $this->mResult->rewind();
326  }
327 
331  public function getPageHeader() {
332  $self = explode( '/', $this->getTitle()->getPrefixedDBkey(), 2 )[0];
333 
334  $groupOptions = [ $this->msg( 'group-all' )->text() => '' ];
335  foreach ( $this->getAllGroups() as $group => $groupText ) {
336  $groupOptions[ $groupText ] = $group;
337  }
338 
339  $formDescriptor = [
340  'user' => [
341  'class' => HTMLUserTextField::class,
342  'label' => $this->msg( 'listusersfrom' )->text(),
343  'name' => 'username',
344  'default' => $this->requestedUser,
345  ],
346  'dropdown' => [
347  'label' => $this->msg( 'group' )->text(),
348  'name' => 'group',
349  'default' => $this->requestedGroup,
350  'class' => HTMLSelectField::class,
351  'options' => $groupOptions,
352  ],
353  'editsOnly' => [
354  'type' => 'check',
355  'label' => $this->msg( 'listusers-editsonly' )->text(),
356  'name' => 'editsOnly',
357  'id' => 'editsOnly',
358  'default' => $this->editsOnly
359  ],
360  'temporaryGroupsOnly' => [
361  'type' => 'check',
362  'label' => $this->msg( 'listusers-temporarygroupsonly' )->text(),
363  'name' => 'temporaryGroupsOnly',
364  'id' => 'temporaryGroupsOnly',
365  'default' => $this->temporaryGroupsOnly
366  ],
367  'creationSort' => [
368  'type' => 'check',
369  'label' => $this->msg( 'listusers-creationsort' )->text(),
370  'name' => 'creationSort',
371  'id' => 'creationSort',
372  'default' => $this->creationSort
373  ],
374  'desc' => [
375  'type' => 'check',
376  'label' => $this->msg( 'listusers-desc' )->text(),
377  'name' => 'desc',
378  'id' => 'desc',
379  'default' => $this->mDefaultDirection
380  ],
381  'limithiddenfield' => [
382  'class' => HTMLHiddenField::class,
383  'name' => 'limit',
384  'default' => $this->mLimit
385  ]
386  ];
387 
388  $beforeSubmitButtonHookOut = '';
389  $this->hookRunner->onSpecialListusersHeaderForm( $this, $beforeSubmitButtonHookOut );
390 
391  if ( $beforeSubmitButtonHookOut !== '' ) {
392  $formDescriptor[ 'beforeSubmitButtonHookOut' ] = [
393  'class' => HTMLInfoField::class,
394  'raw' => true,
395  'default' => $beforeSubmitButtonHookOut
396  ];
397  }
398 
399  $formDescriptor[ 'submit' ] = [
400  'class' => HTMLSubmitField::class,
401  'buttonlabel-message' => 'listusers-submit',
402  ];
403 
404  $beforeClosingFieldsetHookOut = '';
405  $this->hookRunner->onSpecialListusersHeader( $this, $beforeClosingFieldsetHookOut );
406 
407  if ( $beforeClosingFieldsetHookOut !== '' ) {
408  $formDescriptor[ 'beforeClosingFieldsetHookOut' ] = [
409  'class' => HTMLInfoField::class,
410  'raw' => true,
411  'default' => $beforeClosingFieldsetHookOut
412  ];
413  }
414 
415  $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
416  $htmlForm
417  ->setMethod( 'get' )
418  ->setAction( Title::newFromText( $self )->getLocalURL() )
419  ->setId( 'mw-listusers-form' )
420  ->setFormIdentifier( 'mw-listusers-form' )
421  ->suppressDefaultSubmit()
422  ->setWrapperLegendMsg( 'listusers' );
423  return $htmlForm->prepareForm()->getHTML( true );
424  }
425 
426  protected function canSeeHideuser() {
427  return $this->getAuthority()->isAllowed( 'hideuser' );
428  }
429 
434  private function getAllGroups() {
435  $result = [];
436  foreach ( $this->userGroupManager->listAllGroups() as $group ) {
437  $result[$group] = UserGroupMembership::getGroupName( $group );
438  }
439  asort( $result );
440 
441  return $result;
442  }
443 
448  public function getDefaultQuery() {
449  $query = parent::getDefaultQuery();
450  if ( $this->requestedGroup != '' ) {
451  $query['group'] = $this->requestedGroup;
452  }
453  if ( $this->requestedUser != '' ) {
454  $query['username'] = $this->requestedUser;
455  }
456  $this->hookRunner->onSpecialListusersDefaultQuery( $this, $query );
457 
458  return $query;
459  }
460 
469  protected static function getGroupMemberships( $uid, $cache = null ) {
470  if ( $cache === null ) {
471  $user = User::newFromId( $uid );
472  return $user->getGroupMemberships();
473  } else {
474  return $cache[$uid] ?? [];
475  }
476  }
477 
485  protected function buildGroupLink( $group, $username ) {
486  return UserGroupMembership::getLink( $group, $this->getContext(), 'html', $username );
487  }
488 }
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:38
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:71
IndexPager\$mLimit
int $mLimit
The maximum number of entries to show.
Definition: IndexPager.php:96
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:623
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:364
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:46
IndexPager\$mDefaultDirection
bool $mDefaultDirection
$mDefaultDirection gives the direction to use when sorting results: DIR_ASCENDING or DIR_DESCENDING.
Definition: IndexPager.php:133
Linker\userLink
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:896
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
UsersPager\$creationSort
bool $creationSort
Definition: UsersPager.php:56
UsersPager\getIndexField
getIndexField()
Definition: UsersPager.php:146
UsersPager\buildGroupLink
buildGroupLink( $group, $username)
Format a link to a group description page.
Definition: UsersPager.php:485
UsersPager\$linkBatchFactory
LinkBatchFactory $linkBatchFactory
Definition: UsersPager.php:65
UserGroupMembership\getGroupName
static getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: UserGroupMembership.php:187
UsersPager\$editsOnly
bool $editsOnly
Definition: UsersPager.php:50
IndexPager\getDatabase
getDatabase()
Get the Database object in use.
Definition: IndexPager.php:244
UsersPager\$requestedGroup
string $requestedGroup
Definition: UsersPager.php:47
AlphabeticPager
IndexPager with an alphabetic list and a formatted navigation bar Stable to extend.
Definition: AlphabeticPager.php:29
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:80
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:135
ContextSource\getTitle
getTitle()
Definition: ContextSource.php:89
UserGroupMembership\getGroupPage
static getGroupPage( $group)
Gets the title of a page describing a particular user group.
Definition: UserGroupMembership.php:212
IndexPager\DIR_ASCENDING
const DIR_ASCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:78
UsersPager\getPageHeader
getPageHeader()
Definition: UsersPager.php:331
Wikimedia\Rdbms\ILoadBalancer\getConnectionRef
getConnectionRef( $i, $groups=[], $domain=false, $flags=0)
Get a live database handle reference for a server index.
UsersPager\$hookRunner
HookRunner $hookRunner
Definition: UsersPager.php:68
UsersPager\$requestedUser
string $requestedUser
Definition: UsersPager.php:62
$dbr
$dbr
Definition: testCompression.php:54
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:151
MediaWiki\User\UserGroupManager
Managers user groups.
Definition: UserGroupManager.php:51
UsersPager\getDefaultQuery
getDefaultQuery()
Preserve group and username offset parameters when paging.
Definition: UsersPager.php:448
UsersPager\__construct
__construct(?IContextSource $context, $par, $including, LinkBatchFactory $linkBatchFactory, HookContainer $hookContainer, ILoadBalancer $loadBalancer, UserGroupManager $userGroupManager)
Definition: UsersPager.php:83
UserGroupMembership\getLink
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
Definition: UserGroupMembership.php:121
UsersPager\doBatchLookups
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition: UsersPager.php:280
MediaWiki\Cache\LinkBatchFactory
Definition: LinkBatchFactory.php:38
UsersPager\$including
bool null $including
Definition: UsersPager.php:59
UsersPager
This class is used to get a list of user.
Definition: UsersPager.php:39
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
UsersPager\$temporaryGroupsOnly
bool $temporaryGroupsOnly
Definition: UsersPager.php:53
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:62
UsersPager\getAllGroups
getAllGroups()
Get a list of all explicit groups.
Definition: UsersPager.php:434
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:195
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:653
UsersPager\formatRow
formatRow( $row)
Definition: UsersPager.php:220
UsersPager\$userGroupManager
UserGroupManager $userGroupManager
Definition: UsersPager.php:71
Linker\userToolLinksRedContribs
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1023
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:142
NS_USER
const NS_USER
Definition: Defines.php:66
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:57
UsersPager\getGroupMemberships
static getGroupMemberships( $uid, $cache=null)
Get an associative array containing groups the specified user belongs to, and the relevant UserGroupM...
Definition: UsersPager.php:469
IndexPager\DIR_DESCENDING
const DIR_DESCENDING
Backwards-compatible constant for $mDefaultDirection field (do not change)
Definition: IndexPager.php:80
UsersPager\$userGroupCache
array[] $userGroupCache
A array with user ids as key and a array of groups as value.
Definition: UsersPager.php:44
$self
$self
Definition: doMaintenance.php:63
UsersPager\getQueryInfo
getQueryInfo()
Definition: UsersPager.php:153
$cache
$cache
Definition: mcc.php:33
User\idFromName
static idFromName( $name, $flags=self::READ_NORMAL)
Get database id given a user name.
Definition: User.php:930
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:67
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:575
$t
$t
Definition: testCompression.php:74
MediaWiki\User\UserGroupManager\listAllGroups
listAllGroups()
Return the set of defined explicit groups.
Definition: UserGroupManager.php:180
HTMLForm\factory
static factory( $displayFormat,... $arguments)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:322
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:81
UsersPager\canSeeHideuser
canSeeHideuser()
Definition: UsersPager.php:426