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