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