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