* Another fix for SwiftFileBackend file listings
[mediawiki.git] / includes / SiteStats.php
blob90e04c0ae65ae74720ad2aa55826dc8b06285108
1 <?php
3 /**
4 * Static accessor class for site_stats and related things
5 */
6 class SiteStats {
7 static $row, $loaded = false;
8 static $admins, $jobs;
9 static $pageCount = array();
10 static $groupMemberCounts = array();
12 static function recache() {
13 self::load( true );
16 /**
17 * @param $recache bool
19 static function load( $recache = false ) {
20 if ( self::$loaded && !$recache ) {
21 return;
24 self::$row = self::loadAndLazyInit();
26 # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS
27 if ( !isset( self::$row->ss_total_pages ) && self::$row->ss_total_pages == -1 ) {
28 # Update schema
29 $u = new SiteStatsUpdate( 0, 0, 0 );
30 $u->doUpdate();
31 $dbr = wfGetDB( DB_SLAVE );
32 self::$row = $dbr->selectRow( 'site_stats', '*', false, __METHOD__ );
35 self::$loaded = true;
38 /**
39 * @return Bool|ResultWrapper
41 static function loadAndLazyInit() {
42 wfDebug( __METHOD__ . ": reading site_stats from slave\n" );
43 $row = self::doLoad( wfGetDB( DB_SLAVE ) );
45 if( !self::isSane( $row ) ) {
46 // Might have just been initialized during this request? Underflow?
47 wfDebug( __METHOD__ . ": site_stats damaged or missing on slave\n" );
48 $row = self::doLoad( wfGetDB( DB_MASTER ) );
51 if( !self::isSane( $row ) ) {
52 // Normally the site_stats table is initialized at install time.
53 // Some manual construction scenarios may leave the table empty or
54 // broken, however, for instance when importing from a dump into a
55 // clean schema with mwdumper.
56 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
58 SiteStatsInit::doAllAndCommit( wfGetDB( DB_SLAVE ) );
60 $row = self::doLoad( wfGetDB( DB_MASTER ) );
63 if( !self::isSane( $row ) ) {
64 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
66 return $row;
69 /**
70 * @param $db DatabaseBase
71 * @return Bool|ResultWrapper
73 static function doLoad( $db ) {
74 return $db->selectRow( 'site_stats', '*', false, __METHOD__ );
77 /**
78 * @return int
80 static function views() {
81 self::load();
82 return self::$row->ss_total_views;
85 /**
86 * @return int
88 static function edits() {
89 self::load();
90 return self::$row->ss_total_edits;
93 /**
94 * @return int
96 static function articles() {
97 self::load();
98 return self::$row->ss_good_articles;
102 * @return int
104 static function pages() {
105 self::load();
106 return self::$row->ss_total_pages;
110 * @return int
112 static function users() {
113 self::load();
114 return self::$row->ss_users;
118 * @return int
120 static function activeUsers() {
121 self::load();
122 return self::$row->ss_active_users;
126 * @return int
128 static function images() {
129 self::load();
130 return self::$row->ss_images;
134 * Find the number of users in a given user group.
135 * @param $group String: name of group
136 * @return Integer
138 static function numberingroup( $group ) {
139 if ( !isset( self::$groupMemberCounts[$group] ) ) {
140 global $wgMemc;
141 $key = wfMemcKey( 'SiteStats', 'groupcounts', $group );
142 $hit = $wgMemc->get( $key );
143 if ( !$hit ) {
144 $dbr = wfGetDB( DB_SLAVE );
145 $hit = $dbr->selectField(
146 'user_groups',
147 'COUNT(*)',
148 array( 'ug_group' => $group ),
149 __METHOD__
151 $wgMemc->set( $key, $hit, 3600 );
153 self::$groupMemberCounts[$group] = $hit;
155 return self::$groupMemberCounts[$group];
159 * @return int
161 static function jobs() {
162 if ( !isset( self::$jobs ) ) {
163 $dbr = wfGetDB( DB_SLAVE );
164 self::$jobs = $dbr->estimateRowCount( 'job' );
165 /* Zero rows still do single row read for row that doesn't exist, but people are annoyed by that */
166 if ( self::$jobs == 1 ) {
167 self::$jobs = 0;
170 return self::$jobs;
174 * @param $ns int
176 * @return int
178 static function pagesInNs( $ns ) {
179 wfProfileIn( __METHOD__ );
180 if( !isset( self::$pageCount[$ns] ) ) {
181 $dbr = wfGetDB( DB_SLAVE );
182 self::$pageCount[$ns] = (int)$dbr->selectField(
183 'page',
184 'COUNT(*)',
185 array( 'page_namespace' => $ns ),
186 __METHOD__
189 wfProfileOut( __METHOD__ );
190 return self::$pageCount[$ns];
194 * Is the provided row of site stats sane, or should it be regenerated?
196 * @param $row
198 * @return bool
200 private static function isSane( $row ) {
202 $row === false
203 || $row->ss_total_pages < $row->ss_good_articles
204 || $row->ss_total_edits < $row->ss_total_pages
206 return false;
208 // Now check for underflow/overflow
209 foreach( array( 'total_views', 'total_edits', 'good_articles',
210 'total_pages', 'users', 'admins', 'images' ) as $member ) {
212 $row->{"ss_$member"} > 2000000000
213 || $row->{"ss_$member"} < 0
215 return false;
218 return true;
223 * Class for handling updates to the site_stats table
225 class SiteStatsUpdate implements DeferrableUpdate {
227 var $mViews, $mEdits, $mGood, $mPages, $mUsers;
229 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
230 $this->mViews = $views;
231 $this->mEdits = $edits;
232 $this->mGood = $good;
233 $this->mPages = $pages;
234 $this->mUsers = $users;
238 * @param $sql
239 * @param $field
240 * @param $delta
242 function appendUpdate( &$sql, $field, $delta ) {
243 if ( $delta ) {
244 if ( $sql ) {
245 $sql .= ',';
247 if ( $delta < 0 ) {
248 $sql .= "$field=$field-1";
249 } else {
250 $sql .= "$field=$field+1";
255 function doUpdate() {
256 $dbw = wfGetDB( DB_MASTER );
258 $updates = '';
260 $this->appendUpdate( $updates, 'ss_total_views', $this->mViews );
261 $this->appendUpdate( $updates, 'ss_total_edits', $this->mEdits );
262 $this->appendUpdate( $updates, 'ss_good_articles', $this->mGood );
263 $this->appendUpdate( $updates, 'ss_total_pages', $this->mPages );
264 $this->appendUpdate( $updates, 'ss_users', $this->mUsers );
266 if ( $updates ) {
267 $site_stats = $dbw->tableName( 'site_stats' );
268 $sql = "UPDATE $site_stats SET $updates";
270 # Need a separate transaction because this a global lock
271 $dbw->begin( __METHOD__ );
272 $dbw->query( $sql, __METHOD__ );
273 $dbw->commit( __METHOD__ );
278 * @param $dbw DatabaseBase
279 * @return bool|mixed
281 public static function cacheUpdate( $dbw ) {
282 global $wgActiveUserDays;
283 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
284 # Get non-bot users than did some recent action other than making accounts.
285 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
286 $activeUsers = $dbr->selectField(
287 'recentchanges',
288 'COUNT( DISTINCT rc_user_text )',
289 array(
290 'rc_user != 0',
291 'rc_bot' => 0,
292 "rc_log_type != 'newusers' OR rc_log_type IS NULL",
293 "rc_timestamp >= '{$dbw->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 )}'",
295 __METHOD__
297 $dbw->update(
298 'site_stats',
299 array( 'ss_active_users' => intval( $activeUsers ) ),
300 array( 'ss_row_id' => 1 ),
301 __METHOD__
303 return $activeUsers;
308 * Class designed for counting of stats.
310 class SiteStatsInit {
312 // Database connection
313 private $db;
315 // Various stats
316 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
319 * Constructor
320 * @param $database Boolean or DatabaseBase:
321 * - Boolean: whether to use the master DB
322 * - DatabaseBase: database connection to use
324 public function __construct( $database = false ) {
325 if ( $database instanceof DatabaseBase ) {
326 $this->db = $database;
327 } else {
328 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
333 * Count the total number of edits
334 * @return Integer
336 public function edits() {
337 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
338 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
339 return $this->mEdits;
343 * Count pages in article space(s)
344 * @return Integer
346 public function articles() {
347 global $wgArticleCountMethod;
349 $tables = array( 'page' );
350 $conds = array(
351 'page_namespace' => MWNamespace::getContentNamespaces(),
352 'page_is_redirect' => 0,
355 if ( $wgArticleCountMethod == 'link' ) {
356 $tables[] = 'pagelinks';
357 $conds[] = 'pl_from=page_id';
358 } elseif ( $wgArticleCountMethod == 'comma' ) {
359 // To make a correct check for this, we would need, for each page,
360 // to load the text, maybe uncompress it, maybe decode it and then
361 // check if there's one comma.
362 // But one thing we are sure is that if the page is empty, it can't
363 // contain a comma :)
364 $conds[] = 'page_len > 0';
367 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
368 $conds, __METHOD__ );
369 return $this->mArticles;
373 * Count total pages
374 * @return Integer
376 public function pages() {
377 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
378 return $this->mPages;
382 * Count total users
383 * @return Integer
385 public function users() {
386 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
387 return $this->mUsers;
391 * Count views
392 * @return Integer
394 public function views() {
395 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
396 return $this->mViews;
400 * Count total files
401 * @return Integer
403 public function files() {
404 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
405 return $this->mFiles;
409 * Do all updates and commit them. More or less a replacement
410 * for the original initStats, but without output.
412 * @param $database DatabaseBase|bool
413 * - Boolean: whether to use the master DB
414 * - DatabaseBase: database connection to use
415 * @param $options Array of options, may contain the following values
416 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
417 * - views Boolean: when true, do not update the number of page views (default: true)
418 * - activeUsers Boolean: whether to update the number of active users (default: false)
420 public static function doAllAndCommit( $database, array $options = array() ) {
421 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
423 // Grab the object and count everything
424 $counter = new SiteStatsInit( $database );
426 $counter->edits();
427 $counter->articles();
428 $counter->pages();
429 $counter->users();
430 $counter->files();
432 // Only do views if we don't want to not count them
433 if( $options['views'] ) {
434 $counter->views();
437 // Update/refresh
438 if( $options['update'] ) {
439 $counter->update();
440 } else {
441 $counter->refresh();
444 // Count active users if need be
445 if( $options['activeUsers'] ) {
446 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
451 * Update the current row with the selected values
453 public function update() {
454 list( $values, $conds ) = $this->getDbParams();
455 $dbw = wfGetDB( DB_MASTER );
456 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
460 * Refresh site_stats. Erase the current record and save all
461 * the new values.
463 public function refresh() {
464 list( $values, $conds, $views ) = $this->getDbParams();
465 $dbw = wfGetDB( DB_MASTER );
466 $dbw->delete( 'site_stats', $conds, __METHOD__ );
467 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
471 * Return three arrays of params for the db queries
472 * @return Array
474 private function getDbParams() {
475 $values = array(
476 'ss_total_edits' => $this->mEdits,
477 'ss_good_articles' => $this->mArticles,
478 'ss_total_pages' => $this->mPages,
479 'ss_users' => $this->mUsers,
480 'ss_images' => $this->mFiles
482 $conds = array( 'ss_row_id' => 1 );
483 $views = array( 'ss_total_views' => $this->mViews );
484 return array( $values, $conds, $views );