Merge "Restored method for clearing a watchlist in web UI, and rebuilt code."
[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 $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 );
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 # Form tag
197 $out = Xml::openElement( 'form', array( 'method' => 'get', 'action' => $wgScript ) );
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 global $wgActiveUserDays;
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( $wgActiveUserDays ) ) );
254
255 // Occasionally merge in new updates
256 $seconds = min( self::mergeActiveUsers( 600 ), $wgActiveUserDays * 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 intr $period Seconds (do updates no more often than this)
284 * @return int How many seconds old the cache is
285 */
286 public static function mergeActiveUsers( $period ) {
287 global $wgActiveUserDays;
288
289 $dbr = wfGetDB( DB_SLAVE );
290 $cTime = $dbr->selectField( 'querycache_info',
291 'qci_timestamp',
292 array( 'qci_type' => 'activeusers' )
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 = $wgActiveUserDays * 86400; // small wiki
299 } else {
300 $window = $period * 2;
301 }
302 self::doQueryCacheUpdate( $dbw, $window );
303 }
304 }
305
306 return ( time() -
307 ( $cTime ? wfTimestamp( TS_UNIX, $cTime ) : $wgActiveUserDays * 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 * 86400 );
318 }
319
320 /**
321 * Update the query cache as needed
322 *
323 * @param DatabaseBase $dbw
324 * @param int $window Maximum time range of new data to scan (in seconds)
325 * @return bool Success
326 */
327 protected static function doQueryCacheUpdate( DatabaseBase $dbw, $window ) {
328 global $wgActiveUserDays;
329
330 $lockKey = wfWikiID() . '-activeusers';
331 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
332 return false; // exclusive update (avoids duplicate entries)
333 }
334
335 $now = time();
336 $cTime = $dbw->selectField( 'querycache_info',
337 'qci_timestamp',
338 array( 'qci_type' => 'activeusers' )
339 );
340 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
341
342 // Pick the date range to fetch from. This is normally from the last
343 // update to till the present time, but has a limited window for sanity.
344 // If the window is limited, multiple runs are need to fully populate it.
345 $sTimestamp = max( $cTimeUnix, $now - $wgActiveUserDays * 86400 );
346 $eTimestamp = min( $sTimestamp + $window, $now );
347
348 // Get all the users active since the last update
349 $res = $dbw->select(
350 array( 'recentchanges' ),
351 array( 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ),
352 array(
353 'rc_user > 0', // actual accounts
354 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
355 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
356 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
357 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
358 ),
359 __METHOD__,
360 array(
361 'GROUP BY' => array( 'rc_user_text' ),
362 'ORDER BY' => 'NULL' // avoid filesort
363 )
364 );
365 $names = array();
366 foreach ( $res as $row ) {
367 $names[$row->rc_user_text] = $row->lastedittime;
368 }
369
370 // Rotate out users that have not edited in too long (according to old data set)
371 $dbw->delete( 'querycachetwo',
372 array(
373 'qcc_type' => 'activeusers',
374 'qcc_value < ' . $dbw->addQuotes( $now - $wgActiveUserDays * 86400 ) // TS_UNIX
375 ),
376 __METHOD__
377 );
378
379 // Find which of the recently active users are already accounted for
380 if ( count( $names ) ) {
381 $res = $dbw->select( 'querycachetwo',
382 array( 'user_name' => 'qcc_title' ),
383 array(
384 'qcc_type' => 'activeusers',
385 'qcc_namespace' => NS_USER,
386 'qcc_title' => array_keys( $names ) ),
387 __METHOD__
388 );
389 foreach ( $res as $row ) {
390 unset( $names[$row->user_name] );
391 }
392 }
393
394 // Insert the users that need to be added to the list (which their last edit time
395 if ( count( $names ) ) {
396 $newRows = array();
397 foreach ( $names as $name => $lastEditTime ) {
398 $newRows[] = array(
399 'qcc_type' => 'activeusers',
400 'qcc_namespace' => NS_USER,
401 'qcc_title' => $name,
402 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
403 'qcc_namespacetwo' => 0, // unused
404 'qcc_titletwo' => '' // unused
405 );
406 }
407 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
408 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
409 wfWaitForSlaves();
410 }
411 }
412
413 // Touch the data freshness timestamp
414 $dbw->replace( 'querycache_info',
415 array( 'qci_type' ),
416 array( 'qci_type' => 'activeusers',
417 'qci_timestamp' => $dbw->timestamp( $eTimestamp ) ), // not always $now
418 __METHOD__
419 );
420
421 $dbw->unlock( $lockKey, __METHOD__ );
422
423 return true;
424 }
425 }