Merge "API: Avoid unstubbing User for language pref when not needed"
[lhc/web/wiklou.git] / includes / specials / SpecialActiveusers.php
1 <?php
2 /**
3 * Implements Special:Activeusers
4 *
5 * Copyright © 2008 Aaron Schulz
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * This class is used to get a list of active users. The ones with specials
28 * rights (sysop, bureaucrat, developer) will have them displayed
29 * next to their names.
30 *
31 * @ingroup SpecialPage
32 */
33 class ActiveUsersPager extends UsersPager {
34 /**
35 * @var FormOptions
36 */
37 protected $opts;
38
39 /**
40 * @var array
41 */
42 protected $hideGroups = array();
43
44 /**
45 * @var array
46 */
47 protected $hideRights = array();
48
49 /**
50 * @var array
51 */
52 private $blockStatusByUid;
53
54 /**
55 * @param IContextSource $context
56 * @param null $group Unused
57 * @param string $par Parameter passed to the page
58 */
59 function __construct( IContextSource $context = null, $group = null, $par = null ) {
60 parent::__construct( $context );
61
62 $this->RCMaxAge = $this->getConfig()->get( 'ActiveUserDays' );
63 $un = $this->getRequest()->getText( 'username', $par );
64 $this->requestedUser = '';
65 if ( $un != '' ) {
66 $username = Title::makeTitleSafe( NS_USER, $un );
67 if ( !is_null( $username ) ) {
68 $this->requestedUser = $username->getText();
69 }
70 }
71
72 $this->setupOptions();
73 }
74
75 public function setupOptions() {
76 $this->opts = new FormOptions();
77
78 $this->opts->add( 'hidebots', false, FormOptions::BOOL );
79 $this->opts->add( 'hidesysops', false, FormOptions::BOOL );
80
81 $this->opts->fetchValuesFromRequest( $this->getRequest() );
82
83 if ( $this->opts->getValue( 'hidebots' ) == 1 ) {
84 $this->hideRights[] = 'bot';
85 }
86 if ( $this->opts->getValue( 'hidesysops' ) == 1 ) {
87 $this->hideGroups[] = 'sysop';
88 }
89 }
90
91 function getIndexField() {
92 return 'qcc_title';
93 }
94
95 function getQueryInfo() {
96 $dbr = $this->getDatabase();
97
98 $activeUserSeconds = $this->getConfig()->get( 'ActiveUserDays' ) * 86400;
99 $timestamp = $dbr->timestamp( wfTimestamp( TS_UNIX ) - $activeUserSeconds );
100 $conds = array(
101 'qcc_type' => 'activeusers',
102 'qcc_namespace' => NS_USER,
103 'user_name = qcc_title',
104 'rc_user_text = qcc_title',
105 'rc_type != ' . $dbr->addQuotes( RC_EXTERNAL ), // Don't count wikidata.
106 'rc_log_type IS NULL OR rc_log_type != ' . $dbr->addQuotes( 'newusers' ),
107 'rc_timestamp >= ' . $dbr->addQuotes( $timestamp ),
108 );
109 if ( $this->requestedUser != '' ) {
110 $conds[] = 'qcc_title >= ' . $dbr->addQuotes( $this->requestedUser );
111 }
112 if ( !$this->getUser()->isAllowed( 'hideuser' ) ) {
113 $conds[] = 'NOT EXISTS (' . $dbr->selectSQLText(
114 'ipblocks', '1', array( 'ipb_user=user_id', 'ipb_deleted' => 1 )
115 ) . ')';
116 }
117
118 return array(
119 'tables' => array( 'querycachetwo', 'user', 'recentchanges' ),
120 'fields' => array( 'user_name', 'user_id', 'recentedits' => 'COUNT(*)', 'qcc_title' ),
121 'options' => array( 'GROUP BY' => array( 'qcc_title' ) ),
122 'conds' => $conds
123 );
124 }
125
126 function doBatchLookups() {
127 parent::doBatchLookups();
128
129 $uids = array();
130 foreach ( $this->mResult as $row ) {
131 $uids[] = $row->user_id;
132 }
133 // Fetch the block status of the user for showing "(blocked)" text and for
134 // striking out names of suppressed users when privileged user views the list.
135 // Although the first query already hits the block table for un-privileged, this
136 // is done in two queries to avoid huge quicksorts and to make COUNT(*) correct.
137 $dbr = $this->getDatabase();
138 $res = $dbr->select( 'ipblocks',
139 array( 'ipb_user', 'MAX(ipb_deleted) AS block_status' ),
140 array( 'ipb_user' => $uids ),
141 __METHOD__,
142 array( 'GROUP BY' => array( 'ipb_user' ) )
143 );
144 $this->blockStatusByUid = array();
145 foreach ( $res as $row ) {
146 $this->blockStatusByUid[$row->ipb_user] = $row->block_status; // 0 or 1
147 }
148 $this->mResult->seek( 0 );
149 }
150
151 function formatRow( $row ) {
152 $userName = $row->user_name;
153
154 $ulinks = Linker::userLink( $row->user_id, $userName );
155 $ulinks .= Linker::userToolLinks( $row->user_id, $userName );
156
157 $lang = $this->getLanguage();
158
159 $list = array();
160 $user = User::newFromId( $row->user_id );
161
162 // User right filter
163 foreach ( $this->hideRights as $right ) {
164 // Calling User::getRights() within the loop so that
165 // if the hideRights() filter is empty, we don't have to
166 // trigger the lazy-init of the big userrights array in the
167 // User object
168 if ( in_array( $right, $user->getRights() ) ) {
169 return '';
170 }
171 }
172
173 // User group filter
174 // Note: This is a different loop than for user rights,
175 // because we're reusing it to build the group links
176 // at the same time
177 $groups_list = self::getGroups( intval( $row->user_id ), $this->userGroupCache );
178 foreach ( $groups_list as $group ) {
179 if ( in_array( $group, $this->hideGroups ) ) {
180 return '';
181 }
182 $list[] = self::buildGroupLink( $group, $userName );
183 }
184
185 $groups = $lang->commaList( $list );
186
187 $item = $lang->specialList( $ulinks, $groups );
188
189 $isBlocked = isset( $this->blockStatusByUid[$row->user_id] );
190 if ( $isBlocked && $this->blockStatusByUid[$row->user_id] == 1 ) {
191 $item = "<span class=\"deleted\">$item</span>";
192 }
193 $count = $this->msg( 'activeusers-count' )->numParams( $row->recentedits )
194 ->params( $userName )->numParams( $this->RCMaxAge )->escaped();
195 $blocked = $isBlocked ? ' ' . $this->msg( 'listusers-blocked', $userName )->escaped() : '';
196
197 return Html::rawElement( 'li', array(), "{$item} [{$count}]{$blocked}" );
198 }
199
200 function getPageHeader() {
201 $self = $this->getTitle();
202 $limit = $this->mLimit ? Html::hidden( 'limit', $this->mLimit ) : '';
203
204 # Form tag
205 $out = Xml::openElement( 'form', array( 'method' => 'get', 'action' => wfScript() ) );
206 $out .= Xml::fieldset( $this->msg( 'activeusers' )->text() ) . "\n";
207 $out .= Html::hidden( 'title', $self->getPrefixedDBkey() ) . $limit . "\n";
208
209 # Username field
210 $out .= Xml::inputLabel( $this->msg( 'activeusers-from' )->text(),
211 'username', 'offset', 20, $this->requestedUser,
212 array( 'class' => 'mw-ui-input-inline', 'tabindex' => 1 ) ) . '<br />';
213
214 $out .= Xml::checkLabel( $this->msg( 'activeusers-hidebots' )->text(),
215 'hidebots', 'hidebots', $this->opts->getValue( 'hidebots' ), array( 'tabindex' => 2 ) );
216
217 $out .= Xml::checkLabel(
218 $this->msg( 'activeusers-hidesysops' )->text(),
219 'hidesysops',
220 'hidesysops',
221 $this->opts->getValue( 'hidesysops' ),
222 array( 'tabindex' => 3 )
223 ) . '<br />';
224
225 # Submit button and form bottom
226 $out .= Xml::submitButton(
227 $this->msg( 'allpagessubmit' )->text(),
228 array( 'tabindex' => 4 )
229 ) . "\n";
230 $out .= Xml::closeElement( 'fieldset' );
231 $out .= Xml::closeElement( 'form' );
232
233 return $out;
234 }
235 }
236
237 /**
238 * @ingroup SpecialPage
239 */
240 class SpecialActiveUsers extends SpecialPage {
241
242 /**
243 * Constructor
244 */
245 public function __construct() {
246 parent::__construct( 'Activeusers' );
247 }
248
249 /**
250 * Show the special page
251 *
252 * @param string $par Parameter passed to the page or null
253 */
254 public function execute( $par ) {
255 $days = $this->getConfig()->get( 'ActiveUserDays' );
256
257 $this->setHeaders();
258 $this->outputHeader();
259
260 $out = $this->getOutput();
261 $out->wrapWikiMsg( "<div class='mw-activeusers-intro'>\n$1\n</div>",
262 array( 'activeusers-intro', $this->getLanguage()->formatNum( $days ) ) );
263
264 // Occasionally merge in new updates
265 $seconds = min( self::mergeActiveUsers( 300, $days ), $days * 86400 );
266 // Mention the level of staleness
267 $out->addWikiMsg( 'cachedspecial-viewing-cached-ttl',
268 $this->getLanguage()->formatDuration( $seconds ) );
269
270 $up = new ActiveUsersPager( $this->getContext(), null, $par );
271
272 # getBody() first to check, if empty
273 $usersbody = $up->getBody();
274
275 $out->addHTML( $up->getPageHeader() );
276 if ( $usersbody ) {
277 $out->addHTML(
278 $up->getNavigationBar() .
279 Html::rawElement( 'ul', array(), $usersbody ) .
280 $up->getNavigationBar()
281 );
282 } else {
283 $out->addWikiMsg( 'activeusers-noresult' );
284 }
285 }
286
287 protected function getGroupName() {
288 return 'users';
289 }
290
291 /**
292 * @param int $period Seconds (do updates no more often than this)
293 * @param int $days How many days user must be idle before he is considered inactive
294 * @return int How many seconds old the cache is
295 */
296 public static function mergeActiveUsers( $period, $days ) {
297 $dbr = wfGetDB( DB_SLAVE );
298 $cTime = $dbr->selectField( 'querycache_info',
299 'qci_timestamp',
300 array( 'qci_type' => 'activeusers' )
301 );
302
303 if ( !wfReadOnly() ) {
304 if ( !$cTime || ( time() - wfTimestamp( TS_UNIX, $cTime ) ) > $period ) {
305 $dbw = wfGetDB( DB_MASTER );
306 if ( $dbw->estimateRowCount( 'recentchanges' ) <= 10000 ) {
307 $window = $days * 86400; // small wiki
308 } else {
309 $window = $period * 2;
310 }
311 $cTime = self::doQueryCacheUpdate( $dbw, $days, $window ) ?: $cTime;
312 }
313 }
314
315 return ( time() -
316 ( $cTime ? wfTimestamp( TS_UNIX, $cTime ) : $days * 86400 ) );
317 }
318
319 /**
320 * @param IDatabase $dbw Passed in from updateSpecialPages.php
321 * @return void
322 */
323 public static function cacheUpdate( IDatabase $dbw ) {
324 global $wgActiveUserDays;
325
326 self::doQueryCacheUpdate( $dbw, $wgActiveUserDays, $wgActiveUserDays * 86400 );
327 }
328
329 /**
330 * Update the query cache as needed
331 *
332 * @param IDatabase $dbw
333 * @param int $days How many days user must be idle before he is considered inactive
334 * @param int $window Maximum time range of new data to scan (in seconds)
335 * @return int|bool UNIX timestamp the cache is now up-to-date as of (false on error)
336 */
337 protected static function doQueryCacheUpdate( IDatabase $dbw, $days, $window ) {
338 $dbw->startAtomic( __METHOD__ );
339
340 $lockKey = wfWikiID() . '-activeusers';
341 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
342 return false; // exclusive update (avoids duplicate entries)
343 }
344
345 $nowUnix = time();
346 // Get the last-updated timestamp for the cache
347 $cTime = $dbw->selectField( 'querycache_info',
348 'qci_timestamp',
349 array( 'qci_type' => 'activeusers' )
350 );
351 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
352
353 // Pick the date range to fetch from. This is normally from the last
354 // update to till the present time, but has a limited window for sanity.
355 // If the window is limited, multiple runs are need to fully populate it.
356 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
357 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
358
359 // Get all the users active since the last update
360 $res = $dbw->select(
361 array( 'recentchanges' ),
362 array( 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ),
363 array(
364 'rc_user > 0', // actual accounts
365 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
366 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
367 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
368 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
369 ),
370 __METHOD__,
371 array(
372 'GROUP BY' => array( 'rc_user_text' ),
373 'ORDER BY' => 'NULL' // avoid filesort
374 )
375 );
376 $names = array();
377 foreach ( $res as $row ) {
378 $names[$row->rc_user_text] = $row->lastedittime;
379 }
380
381 // Rotate out users that have not edited in too long (according to old data set)
382 $dbw->delete( 'querycachetwo',
383 array(
384 'qcc_type' => 'activeusers',
385 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
386 ),
387 __METHOD__
388 );
389
390 // Find which of the recently active users are already accounted for
391 if ( count( $names ) ) {
392 $res = $dbw->select( 'querycachetwo',
393 array( 'user_name' => 'qcc_title' ),
394 array(
395 'qcc_type' => 'activeusers',
396 'qcc_namespace' => NS_USER,
397 'qcc_title' => array_keys( $names ) ),
398 __METHOD__,
399 // See the latest data (ignoring trx snapshot) to avoid
400 // duplicates if this method was called in a transaction
401 array( 'LOCK IN SHARE MODE' )
402 );
403 foreach ( $res as $row ) {
404 unset( $names[$row->user_name] );
405 }
406 }
407
408 // Insert the users that need to be added to the list (which their last edit time
409 if ( count( $names ) ) {
410 $newRows = array();
411 foreach ( $names as $name => $lastEditTime ) {
412 $newRows[] = array(
413 'qcc_type' => 'activeusers',
414 'qcc_namespace' => NS_USER,
415 'qcc_title' => $name,
416 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
417 'qcc_namespacetwo' => 0, // unused
418 'qcc_titletwo' => '' // unused
419 );
420 }
421 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
422 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
423 if ( !$dbw->trxLevel() ) {
424 wfWaitForSlaves();
425 }
426 }
427 }
428
429 // If a transaction was already started, it might have an old
430 // snapshot, so kludge the timestamp range back as needed.
431 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
432
433 // Touch the data freshness timestamp
434 $dbw->replace( 'querycache_info',
435 array( 'qci_type' ),
436 array( 'qci_type' => 'activeusers',
437 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ), // not always $now
438 __METHOD__
439 );
440
441 $dbw->unlock( $lockKey, __METHOD__ );
442 $dbw->endAtomic( __METHOD__ );
443
444 return $eTimestamp;
445 }
446 }