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