MediaWiki  master
UsersPager.php
Go to the documentation of this file.
1 <?php
28 
36 class UsersPager extends AlphabeticPager {
37 
41  protected $userGroupCache;
42 
45 
47  protected $editsOnly;
48 
51 
53  protected $creationSort;
54 
56  protected $including;
57 
59  protected $requestedUser;
60 
63 
71  public function __construct(
72  IContextSource $context = null,
73  $par = null,
74  $including = null,
76  ) {
77  if ( $context ) {
78  $this->setContext( $context );
79  }
80 
81  $request = $this->getRequest();
82  $par = $par ?? '';
83  $parms = explode( '/', $par );
84  $symsForAll = [ '*', 'user' ];
85 
86  if ( $parms[0] != '' &&
87  ( in_array( $par, User::getAllGroups() ) || in_array( $par, $symsForAll ) )
88  ) {
89  $this->requestedGroup = $par;
90  $un = $request->getText( 'username' );
91  } elseif ( count( $parms ) == 2 ) {
92  $this->requestedGroup = $parms[0];
93  $un = $parms[1];
94  } else {
95  $this->requestedGroup = $request->getVal( 'group' );
96  $un = ( $par != '' ) ? $par : $request->getText( 'username' );
97  }
98 
99  if ( in_array( $this->requestedGroup, $symsForAll ) ) {
100  $this->requestedGroup = '';
101  }
102  $this->editsOnly = $request->getBool( 'editsOnly' );
103  $this->temporaryGroupsOnly = $request->getBool( 'temporaryGroupsOnly' );
104  $this->creationSort = $request->getBool( 'creationSort' );
105  $this->including = $including;
106  $this->mDefaultDirection = $request->getBool( 'desc' )
109 
110  $this->requestedUser = '';
111 
112  if ( $un != '' ) {
113  $username = Title::makeTitleSafe( NS_USER, $un );
114 
115  if ( $username !== null ) {
116  $this->requestedUser = $username->getText();
117  }
118  }
119 
120  parent::__construct();
121  $this->linkBatchFactory = $linkBatchFactory ?? MediaWikiServices::getInstance()->getLinkBatchFactory();
122  }
123 
127  public function getIndexField() {
128  return $this->creationSort ? 'user_id' : 'user_name';
129  }
130 
134  public function getQueryInfo() {
135  $dbr = wfGetDB( DB_REPLICA );
136  $conds = [];
137 
138  // Don't show hidden names
139  if ( !MediaWikiServices::getInstance()
141  ->userHasRight( $this->getUser(), 'hideuser' )
142  ) {
143  $conds[] = 'ipb_deleted IS NULL OR ipb_deleted = 0';
144  }
145 
146  $options = [];
147 
148  if ( $this->requestedGroup != '' || $this->temporaryGroupsOnly ) {
149  $conds[] = 'ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() ) .
150  ( !$this->temporaryGroupsOnly ? ' OR ug_expiry IS NULL' : '' );
151  }
152 
153  if ( $this->requestedGroup != '' ) {
154  $conds['ug_group'] = $this->requestedGroup;
155  }
156 
157  if ( $this->requestedUser != '' ) {
158  # Sorted either by account creation or name
159  if ( $this->creationSort ) {
160  $conds[] = 'user_id >= ' . intval( User::idFromName( $this->requestedUser ) );
161  } else {
162  $conds[] = 'user_name >= ' . $dbr->addQuotes( $this->requestedUser );
163  }
164  }
165 
166  if ( $this->editsOnly ) {
167  $conds[] = 'user_editcount > 0';
168  }
169 
170  $options['GROUP BY'] = $this->creationSort ? 'user_id' : 'user_name';
171 
172  $query = [
173  'tables' => [ 'user', 'user_groups', 'ipblocks' ],
174  'fields' => [
175  'user_name' => $this->creationSort ? 'MAX(user_name)' : 'user_name',
176  'user_id' => $this->creationSort ? 'user_id' : 'MAX(user_id)',
177  'edits' => 'MAX(user_editcount)',
178  'creation' => 'MIN(user_registration)',
179  'ipb_deleted' => 'MAX(ipb_deleted)', // block/hide status
180  'ipb_sitewide' => 'MAX(ipb_sitewide)'
181  ],
182  'options' => $options,
183  'join_conds' => [
184  'user_groups' => [ 'LEFT JOIN', 'user_id=ug_user' ],
185  'ipblocks' => [
186  'LEFT JOIN', [
187  'user_id=ipb_user',
188  'ipb_auto' => 0
189  ]
190  ],
191  ],
192  'conds' => $conds
193  ];
194 
195  $this->getHookRunner()->onSpecialListusersQueryInfo( $this, $query );
196 
197  return $query;
198  }
199 
204  public function formatRow( $row ) {
205  if ( $row->user_id == 0 ) { # T18487
206  return '';
207  }
208 
209  $userName = $row->user_name;
210 
211  $ulinks = Linker::userLink( $row->user_id, $userName );
213  $row->user_id,
214  $userName,
215  (int)$row->edits,
216  // don't render parentheses in HTML markup (CSS will provide)
217  false
218  );
219 
220  $lang = $this->getLanguage();
221 
222  $groups = '';
223  $ugms = self::getGroupMemberships( intval( $row->user_id ), $this->userGroupCache );
224 
225  if ( !$this->including && count( $ugms ) > 0 ) {
226  $list = [];
227  foreach ( $ugms as $ugm ) {
228  $list[] = $this->buildGroupLink( $ugm, $userName );
229  }
230  $groups = $lang->commaList( $list );
231  }
232 
233  $item = $lang->specialList( $ulinks, $groups );
234 
235  if ( $row->ipb_deleted ) {
236  $item = "<span class=\"deleted\">$item</span>";
237  }
238 
239  $edits = '';
240  if ( !$this->including && $this->getConfig()->get( 'Edititis' ) ) {
241  $count = $this->msg( 'usereditcount' )->numParams( $row->edits )->escaped();
242  $edits = $this->msg( 'word-separator' )->escaped() . $this->msg( 'brackets', $count )->escaped();
243  }
244 
245  $created = '';
246  # Some rows may be null
247  if ( !$this->including && $row->creation ) {
248  $user = $this->getUser();
249  $d = $lang->userDate( $row->creation, $user );
250  $t = $lang->userTime( $row->creation, $user );
251  $created = $this->msg( 'usercreated', $d, $t, $row->user_name )->escaped();
252  $created = ' ' . $this->msg( 'parentheses' )->rawParams( $created )->escaped();
253  }
254 
255  $blocked = $row->ipb_deleted !== null && $row->ipb_sitewide === '1' ?
256  ' ' . $this->msg( 'listusers-blocked', $userName )->escaped() :
257  '';
258 
259  $this->getHookRunner()->onSpecialListusersFormatRow( $item, $row );
260 
261  return Html::rawElement( 'li', [], "{$item}{$edits}{$created}{$blocked}" );
262  }
263 
264  protected function doBatchLookups() {
265  $batch = $this->linkBatchFactory->newLinkBatch();
266  $userIds = [];
267  # Give some pointers to make user links
268  foreach ( $this->mResult as $row ) {
269  $batch->add( NS_USER, $row->user_name );
270  $batch->add( NS_USER_TALK, $row->user_name );
271  $userIds[] = $row->user_id;
272  }
273 
274  // Lookup groups for all the users
275  $dbr = wfGetDB( DB_REPLICA );
276  $groupManager = MediaWikiServices::getInstance()->getUserGroupManager();
277  $groupsQueryInfo = $groupManager->getQueryInfo();
278  $groupRes = $dbr->select(
279  $groupsQueryInfo['tables'],
280  $groupsQueryInfo['fields'],
281  [ 'ug_user' => $userIds ],
282  __METHOD__,
283  $groupsQueryInfo['joins']
284  );
285  $cache = [];
286  $groups = [];
287  foreach ( $groupRes as $row ) {
288  $ugm = $groupManager->newGroupMembershipFromRow( $row );
289  if ( !$ugm->isExpired() ) {
290  $cache[$row->ug_user][$row->ug_group] = $ugm;
291  $groups[$row->ug_group] = true;
292  }
293  }
294 
295  // Give extensions a chance to add things like global user group data
296  // into the cache array to ensure proper output later on
297  $this->getHookRunner()->onUsersPagerDoBatchLookups( $dbr, $userIds, $cache, $groups );
298 
299  $this->userGroupCache = $cache;
300 
301  // Add page of groups to link batch
302  foreach ( $groups as $group => $unused ) {
303  $groupPage = UserGroupMembership::getGroupPage( $group );
304  if ( $groupPage ) {
305  $batch->addObj( $groupPage );
306  }
307  }
308 
309  $batch->execute();
310  $this->mResult->rewind();
311  }
312 
316  public function getPageHeader() {
317  $self = explode( '/', $this->getTitle()->getPrefixedDBkey(), 2 )[0];
318 
319  $groupOptions = [ $this->msg( 'group-all' )->text() => '' ];
320  foreach ( $this->getAllGroups() as $group => $groupText ) {
321  $groupOptions[ $groupText ] = $group;
322  }
323 
324  $formDescriptor = [
325  'user' => [
326  'class' => HTMLUserTextField::class,
327  'label' => $this->msg( 'listusersfrom' )->text(),
328  'name' => 'username',
329  'default' => $this->requestedUser,
330  ],
331  'dropdown' => [
332  'label' => $this->msg( 'group' )->text(),
333  'name' => 'group',
334  'default' => $this->requestedGroup,
335  'class' => HTMLSelectField::class,
336  'options' => $groupOptions,
337  ],
338  'editsOnly' => [
339  'type' => 'check',
340  'label' => $this->msg( 'listusers-editsonly' )->text(),
341  'name' => 'editsOnly',
342  'id' => 'editsOnly',
343  'default' => $this->editsOnly
344  ],
345  'temporaryGroupsOnly' => [
346  'type' => 'check',
347  'label' => $this->msg( 'listusers-temporarygroupsonly' )->text(),
348  'name' => 'temporaryGroupsOnly',
349  'id' => 'temporaryGroupsOnly',
350  'default' => $this->temporaryGroupsOnly
351  ],
352  'creationSort' => [
353  'type' => 'check',
354  'label' => $this->msg( 'listusers-creationsort' )->text(),
355  'name' => 'creationSort',
356  'id' => 'creationSort',
357  'default' => $this->creationSort
358  ],
359  'desc' => [
360  'type' => 'check',
361  'label' => $this->msg( 'listusers-desc' )->text(),
362  'name' => 'desc',
363  'id' => 'desc',
364  'default' => $this->mDefaultDirection
365  ],
366  'limithiddenfield' => [
367  'class' => HTMLHiddenField::class,
368  'name' => 'limit',
369  'default' => $this->mLimit
370  ]
371  ];
372 
373  $beforeSubmitButtonHookOut = '';
374  $this->getHookRunner()->onSpecialListusersHeaderForm( $this, $beforeSubmitButtonHookOut );
375 
376  if ( $beforeSubmitButtonHookOut !== '' ) {
377  $formDescriptor[ 'beforeSubmitButtonHookOut' ] = [
378  'class' => HTMLInfoField::class,
379  'raw' => true,
380  'default' => $beforeSubmitButtonHookOut
381  ];
382  }
383 
384  $formDescriptor[ 'submit' ] = [
385  'class' => HTMLSubmitField::class,
386  'buttonlabel-message' => 'listusers-submit',
387  ];
388 
389  $beforeClosingFieldsetHookOut = '';
390  $this->getHookRunner()->onSpecialListusersHeader( $this, $beforeClosingFieldsetHookOut );
391 
392  if ( $beforeClosingFieldsetHookOut !== '' ) {
393  $formDescriptor[ 'beforeClosingFieldsetHookOut' ] = [
394  'class' => HTMLInfoField::class,
395  'raw' => true,
396  'default' => $beforeClosingFieldsetHookOut
397  ];
398  }
399 
400  $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
401  $htmlForm
402  ->setMethod( 'get' )
403  ->setAction( Title::newFromText( $self )->getLocalURL() )
404  ->setId( 'mw-listusers-form' )
405  ->setFormIdentifier( 'mw-listusers-form' )
406  ->suppressDefaultSubmit()
407  ->setWrapperLegendMsg( 'listusers' );
408  return $htmlForm->prepareForm()->getHTML( true );
409  }
410 
415  private function getAllGroups() {
416  $result = [];
417  foreach ( User::getAllGroups() as $group ) {
418  $result[$group] = UserGroupMembership::getGroupName( $group );
419  }
420  asort( $result );
421 
422  return $result;
423  }
424 
429  public function getDefaultQuery() {
430  $query = parent::getDefaultQuery();
431  if ( $this->requestedGroup != '' ) {
432  $query['group'] = $this->requestedGroup;
433  }
434  if ( $this->requestedUser != '' ) {
435  $query['username'] = $this->requestedUser;
436  }
437  $this->getHookRunner()->onSpecialListusersDefaultQuery( $this, $query );
438 
439  return $query;
440  }
441 
450  protected static function getGroupMemberships( $uid, $cache = null ) {
451  if ( $cache === null ) {
452  $user = User::newFromId( $uid );
453  return $user->getGroupMemberships();
454  } else {
455  return $cache[$uid] ?? [];
456  }
457  }
458 
466  protected function buildGroupLink( $group, $username ) {
467  return UserGroupMembership::getLink( $group, $this->getContext(), 'html', $username );
468  }
469 }
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:67
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:562
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:328
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:42
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
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:158
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
UsersPager\$creationSort
bool $creationSort
Definition: UsersPager.php:53
UsersPager\getIndexField
getIndexField()
Definition: UsersPager.php:127
UsersPager\buildGroupLink
buildGroupLink( $group, $username)
Format a link to a group description page.
Definition: UsersPager.php:466
UsersPager\$linkBatchFactory
LinkBatchFactory $linkBatchFactory
Definition: UsersPager.php:62
UserGroupMembership\getGroupName
static getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
Definition: UserGroupMembership.php:344
UsersPager\$editsOnly
bool $editsOnly
Definition: UsersPager.php:47
UsersPager\$requestedGroup
string $requestedGroup
Definition: UsersPager.php:44
AlphabeticPager
IndexPager with an alphabetic list and a formatted navigation bar Stable to extend.
Definition: AlphabeticPager.php:29
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:76
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:131
ContextSource\getTitle
getTitle()
Definition: ContextSource.php:85
UserGroupMembership\getGroupPage
static getGroupPage( $group)
Gets the title of a page describing a particular user group.
Definition: UserGroupMembership.php:369
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:316
UsersPager\$requestedUser
string $requestedUser
Definition: UsersPager.php:59
$dbr
$dbr
Definition: testCompression.php:54
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:140
UsersPager\getDefaultQuery
getDefaultQuery()
Preserve group and username offset parameters when paging.
Definition: UsersPager.php:429
UserGroupMembership\getLink
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
Definition: UserGroupMembership.php:279
UsersPager\doBatchLookups
doBatchLookups()
Called from getBody(), before getStartBody() is called and after doQuery() was called.
Definition: UsersPager.php:264
getPermissionManager
getPermissionManager()
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2475
MediaWiki\Cache\LinkBatchFactory
Definition: LinkBatchFactory.php:38
UsersPager\$including
bool null $including
Definition: UsersPager.php:56
UsersPager
This class is used to get a list of user.
Definition: UsersPager.php:36
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
UsersPager\$temporaryGroupsOnly
bool $temporaryGroupsOnly
Definition: UsersPager.php:50
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:58
UsersPager\getAllGroups
getAllGroups()
Get a list of all explicit groups.
Definition: UsersPager.php:415
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:184
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
NS_USER_TALK
const NS_USER_TALK
Definition: Defines.php:72
UsersPager\formatRow
formatRow( $row)
Definition: UsersPager.php:204
Linker\userToolLinksRedContribs
static userToolLinksRedContribs( $userId, $userText, $edits=null, $useParentheses=true)
Alias for userToolLinks( $userId, $userText, true );.
Definition: Linker.php:1023
User\getAllGroups
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:4190
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
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:450
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:41
$self
$self
Definition: doMaintenance.php:63
UsersPager\getQueryInfo
getQueryInfo()
Definition: UsersPager.php:134
$cache
$cache
Definition: mcc.php:33
UsersPager\__construct
__construct(IContextSource $context=null, $par=null, $including=null, LinkBatchFactory $linkBatchFactory=null)
Definition: UsersPager.php:71
User\idFromName
static idFromName( $name, $flags=self::READ_NORMAL)
Get database id given a user name.
Definition: User.php:884
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
NS_USER
const NS_USER
Definition: Defines.php:71
$t
$t
Definition: testCompression.php:74
HTMLForm\factory
static factory( $displayFormat,... $arguments)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:315