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