Merge "Generate $wgAutoloadLocalClasses with a maint script"
[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 $uids = array();
128 foreach ( $this->mResult as $row ) {
129 $uids[] = $row->user_id;
130 }
131 // Fetch the block status of the user for showing "(blocked)" text and for
132 // striking out names of suppressed users when privileged user views the list.
133 // Although the first query already hits the block table for un-privileged, this
134 // is done in two queries to avoid huge quicksorts and to make COUNT(*) correct.
135 $dbr = $this->getDatabase();
136 $res = $dbr->select( 'ipblocks',
137 array( 'ipb_user', 'MAX(ipb_deleted) AS block_status' ),
138 array( 'ipb_user' => $uids ),
139 __METHOD__,
140 array( 'GROUP BY' => array( 'ipb_user' ) )
141 );
142 $this->blockStatusByUid = array();
143 foreach ( $res as $row ) {
144 $this->blockStatusByUid[$row->ipb_user] = $row->block_status; // 0 or 1
145 }
146 $this->mResult->seek( 0 );
147 }
148
149 function formatRow( $row ) {
150 $userName = $row->user_name;
151
152 $ulinks = Linker::userLink( $row->user_id, $userName );
153 $ulinks .= Linker::userToolLinks( $row->user_id, $userName );
154
155 $lang = $this->getLanguage();
156
157 $list = array();
158 $user = User::newFromId( $row->user_id );
159
160 // User right filter
161 foreach ( $this->hideRights as $right ) {
162 // Calling User::getRights() within the loop so that
163 // if the hideRights() filter is empty, we don't have to
164 // trigger the lazy-init of the big userrights array in the
165 // User object
166 if ( in_array( $right, $user->getRights() ) ) {
167 return '';
168 }
169 }
170
171 // User group filter
172 // Note: This is a different loop than for user rights,
173 // because we're reusing it to build the group links
174 // at the same time
175 foreach ( $user->getGroups() as $group ) {
176 if ( in_array( $group, $this->hideGroups ) ) {
177 return '';
178 }
179 $list[] = self::buildGroupLink( $group, $userName );
180 }
181
182 $groups = $lang->commaList( $list );
183
184 $item = $lang->specialList( $ulinks, $groups );
185
186 $isBlocked = isset( $this->blockStatusByUid[$row->user_id] );
187 if ( $isBlocked && $this->blockStatusByUid[$row->user_id] == 1 ) {
188 $item = "<span class=\"deleted\">$item</span>";
189 }
190 $count = $this->msg( 'activeusers-count' )->numParams( $row->recentedits )
191 ->params( $userName )->numParams( $this->RCMaxAge )->escaped();
192 $blocked = $isBlocked ? ' ' . $this->msg( 'listusers-blocked', $userName )->escaped() : '';
193
194 return Html::rawElement( 'li', array(), "{$item} [{$count}]{$blocked}" );
195 }
196
197 function getPageHeader() {
198 $self = $this->getTitle();
199 $limit = $this->mLimit ? Html::hidden( 'limit', $this->mLimit ) : '';
200
201 # Form tag
202 $out = Xml::openElement( 'form', array( 'method' => 'get', 'action' => wfScript() ) );
203 $out .= Xml::fieldset( $this->msg( 'activeusers' )->text() ) . "\n";
204 $out .= Html::hidden( 'title', $self->getPrefixedDBkey() ) . $limit . "\n";
205
206 # Username field
207 $out .= Xml::inputLabel( $this->msg( 'activeusers-from' )->text(),
208 'username', 'offset', 20, $this->requestedUser,
209 array( 'class' => 'mw-ui-input-inline', 'tabindex' => 1 ) ) . '<br />';
210
211 $out .= Xml::checkLabel( $this->msg( 'activeusers-hidebots' )->text(),
212 'hidebots', 'hidebots', $this->opts->getValue( 'hidebots' ), array( 'tabindex' => 2 ) );
213
214 $out .= Xml::checkLabel(
215 $this->msg( 'activeusers-hidesysops' )->text(),
216 'hidesysops',
217 'hidesysops',
218 $this->opts->getValue( 'hidesysops' ),
219 array( 'tabindex' => 3 )
220 ) . '<br />';
221
222 # Submit button and form bottom
223 $out .= Xml::submitButton(
224 $this->msg( 'allpagessubmit' )->text(),
225 array( 'tabindex' => 4 )
226 ) . "\n";
227 $out .= Xml::closeElement( 'fieldset' );
228 $out .= Xml::closeElement( 'form' );
229
230 return $out;
231 }
232 }
233
234 /**
235 * @ingroup SpecialPage
236 */
237 class SpecialActiveUsers extends SpecialPage {
238
239 /**
240 * Constructor
241 */
242 public function __construct() {
243 parent::__construct( 'Activeusers' );
244 }
245
246 /**
247 * Show the special page
248 *
249 * @param string $par Parameter passed to the page or null
250 */
251 public function execute( $par ) {
252 $days = $this->getConfig()->get( 'ActiveUserDays' );
253
254 $this->setHeaders();
255 $this->outputHeader();
256
257 $out = $this->getOutput();
258 $out->wrapWikiMsg( "<div class='mw-activeusers-intro'>\n$1\n</div>",
259 array( 'activeusers-intro', $this->getLanguage()->formatNum( $days ) ) );
260
261 // Occasionally merge in new updates
262 $seconds = min( self::mergeActiveUsers( 300, $days ), $days * 86400 );
263 // Mention the level of staleness
264 $out->addWikiMsg( 'cachedspecial-viewing-cached-ttl',
265 $this->getLanguage()->formatDuration( $seconds ) );
266
267 $up = new ActiveUsersPager( $this->getContext(), null, $par );
268
269 # getBody() first to check, if empty
270 $usersbody = $up->getBody();
271
272 $out->addHTML( $up->getPageHeader() );
273 if ( $usersbody ) {
274 $out->addHTML(
275 $up->getNavigationBar() .
276 Html::rawElement( 'ul', array(), $usersbody ) .
277 $up->getNavigationBar()
278 );
279 } else {
280 $out->addWikiMsg( 'activeusers-noresult' );
281 }
282 }
283
284 protected function getGroupName() {
285 return 'users';
286 }
287
288 /**
289 * @param int $period Seconds (do updates no more often than this)
290 * @param int $days How many days user must be idle before he is considered inactive
291 * @return int How many seconds old the cache is
292 */
293 public static function mergeActiveUsers( $period, $days ) {
294 $dbr = wfGetDB( DB_SLAVE );
295 $cTime = $dbr->selectField( 'querycache_info',
296 'qci_timestamp',
297 array( 'qci_type' => 'activeusers' )
298 );
299
300 if ( !wfReadOnly() ) {
301 if ( !$cTime || ( time() - wfTimestamp( TS_UNIX, $cTime ) ) > $period ) {
302 $dbw = wfGetDB( DB_MASTER );
303 if ( $dbw->estimateRowCount( 'recentchanges' ) <= 10000 ) {
304 $window = $days * 86400; // small wiki
305 } else {
306 $window = $period * 2;
307 }
308 $cTime = self::doQueryCacheUpdate( $dbw, $days, $window ) ?: $cTime;
309 }
310 }
311
312 return ( time() -
313 ( $cTime ? wfTimestamp( TS_UNIX, $cTime ) : $days * 86400 ) );
314 }
315
316 /**
317 * @param DatabaseBase $dbw Passed in from updateSpecialPages.php
318 * @return void
319 */
320 public static function cacheUpdate( DatabaseBase $dbw ) {
321 global $wgActiveUserDays;
322
323 self::doQueryCacheUpdate( $dbw, $wgActiveUserDays, $wgActiveUserDays * 86400 );
324 }
325
326 /**
327 * Update the query cache as needed
328 *
329 * @param DatabaseBase $dbw
330 * @param int $days How many days user must be idle before he is considered inactive
331 * @param int $window Maximum time range of new data to scan (in seconds)
332 * @return int|bool UNIX timestamp the cache is now up-to-date as of (false on error)
333 */
334 protected static function doQueryCacheUpdate( DatabaseBase $dbw, $days, $window ) {
335 $dbw->startAtomic( __METHOD__ );
336
337 $lockKey = wfWikiID() . '-activeusers';
338 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
339 return false; // exclusive update (avoids duplicate entries)
340 }
341
342 $nowUnix = time();
343 // Get the last-updated timestamp for the cache
344 $cTime = $dbw->selectField( 'querycache_info',
345 'qci_timestamp',
346 array( 'qci_type' => 'activeusers' )
347 );
348 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
349
350 // Pick the date range to fetch from. This is normally from the last
351 // update to till the present time, but has a limited window for sanity.
352 // If the window is limited, multiple runs are need to fully populate it.
353 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
354 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
355
356 // Get all the users active since the last update
357 $res = $dbw->select(
358 array( 'recentchanges' ),
359 array( 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ),
360 array(
361 'rc_user > 0', // actual accounts
362 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
363 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
364 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
365 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
366 ),
367 __METHOD__,
368 array(
369 'GROUP BY' => array( 'rc_user_text' ),
370 'ORDER BY' => 'NULL' // avoid filesort
371 )
372 );
373 $names = array();
374 foreach ( $res as $row ) {
375 $names[$row->rc_user_text] = $row->lastedittime;
376 }
377
378 // Rotate out users that have not edited in too long (according to old data set)
379 $dbw->delete( 'querycachetwo',
380 array(
381 'qcc_type' => 'activeusers',
382 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
383 ),
384 __METHOD__
385 );
386
387 // Find which of the recently active users are already accounted for
388 if ( count( $names ) ) {
389 $res = $dbw->select( 'querycachetwo',
390 array( 'user_name' => 'qcc_title' ),
391 array(
392 'qcc_type' => 'activeusers',
393 'qcc_namespace' => NS_USER,
394 'qcc_title' => array_keys( $names ) ),
395 __METHOD__,
396 // See the latest data (ignoring trx snapshot) to avoid
397 // duplicates if this method was called in a transaction
398 array( 'LOCK IN SHARE MODE' )
399 );
400 foreach ( $res as $row ) {
401 unset( $names[$row->user_name] );
402 }
403 }
404
405 // Insert the users that need to be added to the list (which their last edit time
406 if ( count( $names ) ) {
407 $newRows = array();
408 foreach ( $names as $name => $lastEditTime ) {
409 $newRows[] = array(
410 'qcc_type' => 'activeusers',
411 'qcc_namespace' => NS_USER,
412 'qcc_title' => $name,
413 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
414 'qcc_namespacetwo' => 0, // unused
415 'qcc_titletwo' => '' // unused
416 );
417 }
418 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
419 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
420 if ( !$dbw->trxLevel() ) {
421 wfWaitForSlaves();
422 }
423 }
424 }
425
426 // If a transaction was already started, it might have an old
427 // snapshot, so kludge the timestamp range back as needed.
428 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
429
430 // Touch the data freshness timestamp
431 $dbw->replace( 'querycache_info',
432 array( 'qci_type' ),
433 array( 'qci_type' => 'activeusers',
434 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ), // not always $now
435 __METHOD__
436 );
437
438 $dbw->unlock( $lockKey, __METHOD__ );
439 $dbw->endAtomic( __METHOD__ );
440
441 return $eTimestamp;
442 }
443 }