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