Add a way for packagers to override some installation details
[mediawiki.git] / includes / SiteStats.php
blob10aed9cc9a66ac382f3ddd783164756adaa6891f
1 <?php
2 /**
3 * Accessors and mutators for the site-wide statistics.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Static accessor class for site_stats and related things
26 class SiteStats {
27 static $row, $loaded = false;
28 static $jobs;
29 static $pageCount = array();
30 static $groupMemberCounts = array();
32 static function recache() {
33 self::load( true );
36 /**
37 * @param $recache bool
39 static function load( $recache = false ) {
40 if ( self::$loaded && !$recache ) {
41 return;
44 self::$row = self::loadAndLazyInit();
46 # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS
47 if ( !isset( self::$row->ss_total_pages ) && self::$row->ss_total_pages == -1 ) {
48 # Update schema
49 $u = new SiteStatsUpdate( 0, 0, 0 );
50 $u->doUpdate();
51 $dbr = wfGetDB( DB_SLAVE );
52 self::$row = $dbr->selectRow( 'site_stats', '*', false, __METHOD__ );
55 self::$loaded = true;
58 /**
59 * @return Bool|ResultWrapper
61 static function loadAndLazyInit() {
62 wfDebug( __METHOD__ . ": reading site_stats from slave\n" );
63 $row = self::doLoad( wfGetDB( DB_SLAVE ) );
65 if( !self::isSane( $row ) ) {
66 // Might have just been initialized during this request? Underflow?
67 wfDebug( __METHOD__ . ": site_stats damaged or missing on slave\n" );
68 $row = self::doLoad( wfGetDB( DB_MASTER ) );
71 if( !self::isSane( $row ) ) {
72 // Normally the site_stats table is initialized at install time.
73 // Some manual construction scenarios may leave the table empty or
74 // broken, however, for instance when importing from a dump into a
75 // clean schema with mwdumper.
76 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
78 SiteStatsInit::doAllAndCommit( wfGetDB( DB_SLAVE ) );
80 $row = self::doLoad( wfGetDB( DB_MASTER ) );
83 if( !self::isSane( $row ) ) {
84 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
86 return $row;
89 /**
90 * @param $db DatabaseBase
91 * @return Bool|ResultWrapper
93 static function doLoad( $db ) {
94 return $db->selectRow( 'site_stats', '*', false, __METHOD__ );
97 /**
98 * @return int
100 static function views() {
101 self::load();
102 return self::$row->ss_total_views;
106 * @return int
108 static function edits() {
109 self::load();
110 return self::$row->ss_total_edits;
114 * @return int
116 static function articles() {
117 self::load();
118 return self::$row->ss_good_articles;
122 * @return int
124 static function pages() {
125 self::load();
126 return self::$row->ss_total_pages;
130 * @return int
132 static function users() {
133 self::load();
134 return self::$row->ss_users;
138 * @return int
140 static function activeUsers() {
141 self::load();
142 return self::$row->ss_active_users;
146 * @return int
148 static function images() {
149 self::load();
150 return self::$row->ss_images;
154 * Find the number of users in a given user group.
155 * @param $group String: name of group
156 * @return Integer
158 static function numberingroup( $group ) {
159 if ( !isset( self::$groupMemberCounts[$group] ) ) {
160 global $wgMemc;
161 $key = wfMemcKey( 'SiteStats', 'groupcounts', $group );
162 $hit = $wgMemc->get( $key );
163 if ( !$hit ) {
164 $dbr = wfGetDB( DB_SLAVE );
165 $hit = $dbr->selectField(
166 'user_groups',
167 'COUNT(*)',
168 array( 'ug_group' => $group ),
169 __METHOD__
171 $wgMemc->set( $key, $hit, 3600 );
173 self::$groupMemberCounts[$group] = $hit;
175 return self::$groupMemberCounts[$group];
179 * @return int
181 static function jobs() {
182 if ( !isset( self::$jobs ) ) {
183 $dbr = wfGetDB( DB_SLAVE );
184 self::$jobs = $dbr->estimateRowCount( 'job' );
185 /* Zero rows still do single row read for row that doesn't exist, but people are annoyed by that */
186 if ( self::$jobs == 1 ) {
187 self::$jobs = 0;
190 return self::$jobs;
194 * @param $ns int
196 * @return int
198 static function pagesInNs( $ns ) {
199 wfProfileIn( __METHOD__ );
200 if( !isset( self::$pageCount[$ns] ) ) {
201 $dbr = wfGetDB( DB_SLAVE );
202 self::$pageCount[$ns] = (int)$dbr->selectField(
203 'page',
204 'COUNT(*)',
205 array( 'page_namespace' => $ns ),
206 __METHOD__
209 wfProfileOut( __METHOD__ );
210 return self::$pageCount[$ns];
214 * Is the provided row of site stats sane, or should it be regenerated?
216 * @param $row
218 * @return bool
220 private static function isSane( $row ) {
222 $row === false
223 || $row->ss_total_pages < $row->ss_good_articles
224 || $row->ss_total_edits < $row->ss_total_pages
226 return false;
228 // Now check for underflow/overflow
229 foreach( array( 'total_views', 'total_edits', 'good_articles',
230 'total_pages', 'users', 'images' ) as $member ) {
232 $row->{"ss_$member"} > 2000000000
233 || $row->{"ss_$member"} < 0
235 return false;
238 return true;
243 * Class for handling updates to the site_stats table
245 class SiteStatsUpdate implements DeferrableUpdate {
246 protected $views = 0;
247 protected $edits = 0;
248 protected $pages = 0;
249 protected $articles = 0;
250 protected $users = 0;
251 protected $images = 0;
253 // @TODO: deprecate this constructor
254 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
255 $this->views = $views;
256 $this->edits = $edits;
257 $this->articles = $good;
258 $this->pages = $pages;
259 $this->users = $users;
263 * @param $deltas Array
264 * @return SiteStatsUpdate
266 public static function factory( array $deltas ) {
267 $update = new self( 0, 0, 0 );
269 $fields = array( 'views', 'edits', 'pages', 'articles', 'users', 'images' );
270 foreach ( $fields as $field ) {
271 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
272 $update->$field = $deltas[$field];
276 return $update;
279 public function doUpdate() {
280 global $wgSiteStatsAsyncFactor;
282 $rate = $wgSiteStatsAsyncFactor; // convenience
283 // If set to do so, only do actual DB updates 1 every $rate times.
284 // The other times, just update "pending delta" values in memcached.
285 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
286 $this->doUpdatePendingDeltas();
287 } else {
288 $dbw = wfGetDB( DB_MASTER );
290 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
291 if ( $rate ) {
292 // Lock the table so we don't have double DB/memcached updates
293 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
294 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
296 $this->doUpdatePendingDeltas();
297 return;
299 $pd = $this->getPendingDeltas();
300 // Piggy-back the async deltas onto those of this stats update....
301 $this->views += ( $pd['ss_total_views']['+'] - $pd['ss_total_views']['-'] );
302 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
303 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
304 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
305 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
306 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
309 // Need a separate transaction because this a global lock
310 $dbw->begin( __METHOD__ );
312 // Build up an SQL query of deltas and apply them...
313 $updates = '';
314 $this->appendUpdate( $updates, 'ss_total_views', $this->views );
315 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
316 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
317 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
318 $this->appendUpdate( $updates, 'ss_users', $this->users );
319 $this->appendUpdate( $updates, 'ss_images', $this->images );
320 if ( $updates != '' ) {
321 $dbw->update( 'site_stats', array( $updates ), array(), __METHOD__ );
324 if ( $rate ) {
325 // Decrement the async deltas now that we applied them
326 $this->removePendingDeltas( $pd );
327 // Commit the updates and unlock the table
328 $dbw->unlock( $lockKey, __METHOD__ );
331 $dbw->commit( __METHOD__ );
336 * @param $dbw DatabaseBase
337 * @return bool|mixed
339 public static function cacheUpdate( $dbw ) {
340 global $wgActiveUserDays;
341 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
342 # Get non-bot users than did some recent action other than making accounts.
343 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
344 $activeUsers = $dbr->selectField(
345 'recentchanges',
346 'COUNT( DISTINCT rc_user_text )',
347 array(
348 'rc_user != 0',
349 'rc_bot' => 0,
350 "rc_log_type != 'newusers' OR rc_log_type IS NULL",
351 "rc_timestamp >= '{$dbw->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 )}'",
353 __METHOD__
355 $dbw->update(
356 'site_stats',
357 array( 'ss_active_users' => intval( $activeUsers ) ),
358 array( 'ss_row_id' => 1 ),
359 __METHOD__
361 return $activeUsers;
364 protected function doUpdatePendingDeltas() {
365 $this->adjustPending( 'ss_total_views', $this->views );
366 $this->adjustPending( 'ss_total_edits', $this->edits );
367 $this->adjustPending( 'ss_good_articles', $this->articles );
368 $this->adjustPending( 'ss_total_pages', $this->pages );
369 $this->adjustPending( 'ss_users', $this->users );
370 $this->adjustPending( 'ss_images', $this->images );
374 * @param $sql string
375 * @param $field string
376 * @param $delta integer
378 protected function appendUpdate( &$sql, $field, $delta ) {
379 if ( $delta ) {
380 if ( $sql ) {
381 $sql .= ',';
383 if ( $delta < 0 ) {
384 $sql .= "$field=$field-" . abs( $delta );
385 } else {
386 $sql .= "$field=$field+" . abs( $delta );
392 * @param $type string
393 * @param $sign string ('+' or '-')
394 * @return void
396 private function getTypeCacheKey( $type, $sign ) {
397 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
401 * Adjust the pending deltas for a stat type.
402 * Each stat type has two pending counters, one for increments and decrements
403 * @param $type string
404 * @param $delta integer Delta (positive or negative)
405 * @return void
407 protected function adjustPending( $type, $delta ) {
408 global $wgMemc;
410 if ( $delta < 0 ) { // decrement
411 $key = $this->getTypeCacheKey( $type, '-' );
412 } else { // increment
413 $key = $this->getTypeCacheKey( $type, '+' );
416 $magnitude = abs( $delta );
417 if ( !$wgMemc->incr( $key, $magnitude ) ) { // not there?
418 if ( !$wgMemc->add( $key, $magnitude ) ) { // race?
419 $wgMemc->incr( $key, $magnitude );
425 * Get pending delta counters for each stat type
426 * @return Array Positive and negative deltas for each type
427 * @return void
429 protected function getPendingDeltas() {
430 global $wgMemc;
432 $pending = array();
433 foreach ( array( 'ss_total_views', 'ss_total_edits',
434 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ) as $type )
436 // Get pending increments and pending decrements
437 $pending[$type]['+'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '+' ) );
438 $pending[$type]['-'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '-' ) );
441 return $pending;
445 * Reduce pending delta counters after updates have been applied
446 * @param Array Result of getPendingDeltas(), used for DB update
447 * @return void
449 protected function removePendingDeltas( array $pd ) {
450 global $wgMemc;
452 foreach ( $pd as $type => $deltas ) {
453 foreach ( $deltas as $sign => $magnitude ) {
454 // Lower the pending counter now that we applied these changes
455 $wgMemc->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
462 * Class designed for counting of stats.
464 class SiteStatsInit {
466 // Database connection
467 private $db;
469 // Various stats
470 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
473 * Constructor
474 * @param $database Boolean or DatabaseBase:
475 * - Boolean: whether to use the master DB
476 * - DatabaseBase: database connection to use
478 public function __construct( $database = false ) {
479 if ( $database instanceof DatabaseBase ) {
480 $this->db = $database;
481 } else {
482 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
487 * Count the total number of edits
488 * @return Integer
490 public function edits() {
491 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
492 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
493 return $this->mEdits;
497 * Count pages in article space(s)
498 * @return Integer
500 public function articles() {
501 global $wgArticleCountMethod;
503 $tables = array( 'page' );
504 $conds = array(
505 'page_namespace' => MWNamespace::getContentNamespaces(),
506 'page_is_redirect' => 0,
509 if ( $wgArticleCountMethod == 'link' ) {
510 $tables[] = 'pagelinks';
511 $conds[] = 'pl_from=page_id';
512 } elseif ( $wgArticleCountMethod == 'comma' ) {
513 // To make a correct check for this, we would need, for each page,
514 // to load the text, maybe uncompress it, maybe decode it and then
515 // check if there's one comma.
516 // But one thing we are sure is that if the page is empty, it can't
517 // contain a comma :)
518 $conds[] = 'page_len > 0';
521 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
522 $conds, __METHOD__ );
523 return $this->mArticles;
527 * Count total pages
528 * @return Integer
530 public function pages() {
531 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
532 return $this->mPages;
536 * Count total users
537 * @return Integer
539 public function users() {
540 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
541 return $this->mUsers;
545 * Count views
546 * @return Integer
548 public function views() {
549 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
550 return $this->mViews;
554 * Count total files
555 * @return Integer
557 public function files() {
558 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
559 return $this->mFiles;
563 * Do all updates and commit them. More or less a replacement
564 * for the original initStats, but without output.
566 * @param $database DatabaseBase|bool
567 * - Boolean: whether to use the master DB
568 * - DatabaseBase: database connection to use
569 * @param $options Array of options, may contain the following values
570 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
571 * - views Boolean: when true, do not update the number of page views (default: true)
572 * - activeUsers Boolean: whether to update the number of active users (default: false)
574 public static function doAllAndCommit( $database, array $options = array() ) {
575 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
577 // Grab the object and count everything
578 $counter = new SiteStatsInit( $database );
580 $counter->edits();
581 $counter->articles();
582 $counter->pages();
583 $counter->users();
584 $counter->files();
586 // Only do views if we don't want to not count them
587 if( $options['views'] ) {
588 $counter->views();
591 // Update/refresh
592 if( $options['update'] ) {
593 $counter->update();
594 } else {
595 $counter->refresh();
598 // Count active users if need be
599 if( $options['activeUsers'] ) {
600 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
605 * Update the current row with the selected values
607 public function update() {
608 list( $values, $conds ) = $this->getDbParams();
609 $dbw = wfGetDB( DB_MASTER );
610 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
614 * Refresh site_stats. Erase the current record and save all
615 * the new values.
617 public function refresh() {
618 list( $values, $conds, $views ) = $this->getDbParams();
619 $dbw = wfGetDB( DB_MASTER );
620 $dbw->delete( 'site_stats', $conds, __METHOD__ );
621 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
625 * Return three arrays of params for the db queries
626 * @return Array
628 private function getDbParams() {
629 $values = array(
630 'ss_total_edits' => $this->mEdits,
631 'ss_good_articles' => $this->mArticles,
632 'ss_total_pages' => $this->mPages,
633 'ss_users' => $this->mUsers,
634 'ss_images' => $this->mFiles
636 $conds = array( 'ss_row_id' => 1 );
637 $views = array( 'ss_total_views' => $this->mViews );
638 return array( $values, $conds, $views );