Move remaining LoadBalancer classes to Rdbms
[mediawiki.git] / includes / SiteStats.php
blob105a58188897b1f2ed802f05e58e7cf6d8ed53f1
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 /** @var bool|stdClass */
28 private static $row;
30 /** @var bool */
31 private static $loaded = false;
33 /** @var int */
34 private static $jobs;
36 /** @var int[] */
37 private static $pageCount = [];
39 static function unload() {
40 self::$loaded = false;
43 static function recache() {
44 self::load( true );
47 /**
48 * @param bool $recache
50 static function load( $recache = false ) {
51 if ( self::$loaded && !$recache ) {
52 return;
55 self::$row = self::loadAndLazyInit();
57 # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS
58 if ( !isset( self::$row->ss_total_pages ) && self::$row->ss_total_pages == -1 ) {
59 # Update schema
60 $u = new SiteStatsUpdate( 0, 0, 0 );
61 $u->doUpdate();
62 self::$row = self::doLoad( wfGetDB( DB_REPLICA ) );
65 self::$loaded = true;
68 /**
69 * @return bool|stdClass
71 static function loadAndLazyInit() {
72 global $wgMiserMode;
74 wfDebug( __METHOD__ . ": reading site_stats from replica DB\n" );
75 $row = self::doLoad( wfGetDB( DB_REPLICA ) );
77 if ( !self::isSane( $row ) ) {
78 // Might have just been initialized during this request? Underflow?
79 wfDebug( __METHOD__ . ": site_stats damaged or missing on replica DB\n" );
80 $row = self::doLoad( wfGetDB( DB_MASTER ) );
83 if ( !$wgMiserMode && !self::isSane( $row ) ) {
84 // Normally the site_stats table is initialized at install time.
85 // Some manual construction scenarios may leave the table empty or
86 // broken, however, for instance when importing from a dump into a
87 // clean schema with mwdumper.
88 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
90 SiteStatsInit::doAllAndCommit( wfGetDB( DB_REPLICA ) );
92 $row = self::doLoad( wfGetDB( DB_MASTER ) );
95 if ( !self::isSane( $row ) ) {
96 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
98 return $row;
102 * @param IDatabase $db
103 * @return bool|stdClass
105 static function doLoad( $db ) {
106 return $db->selectRow( 'site_stats', [
107 'ss_row_id',
108 'ss_total_edits',
109 'ss_good_articles',
110 'ss_total_pages',
111 'ss_users',
112 'ss_active_users',
113 'ss_images',
114 ], [], __METHOD__ );
118 * Return the total number of page views. Except we don't track those anymore.
119 * Stop calling this function, it will be removed some time in the future. It's
120 * kept here simply to prevent fatal errors.
122 * @deprecated since 1.25
123 * @return int
125 static function views() {
126 wfDeprecated( __METHOD__, '1.25' );
127 return 0;
131 * @return int
133 static function edits() {
134 self::load();
135 return self::$row->ss_total_edits;
139 * @return int
141 static function articles() {
142 self::load();
143 return self::$row->ss_good_articles;
147 * @return int
149 static function pages() {
150 self::load();
151 return self::$row->ss_total_pages;
155 * @return int
157 static function users() {
158 self::load();
159 return self::$row->ss_users;
163 * @return int
165 static function activeUsers() {
166 self::load();
167 return self::$row->ss_active_users;
171 * @return int
173 static function images() {
174 self::load();
175 return self::$row->ss_images;
179 * Find the number of users in a given user group.
180 * @param string $group Name of group
181 * @return int
183 static function numberingroup( $group ) {
184 $cache = ObjectCache::getMainWANInstance();
185 return $cache->getWithSetCallback(
186 wfMemcKey( 'SiteStats', 'groupcounts', $group ),
187 $cache::TTL_HOUR,
188 function ( $oldValue, &$ttl, array &$setOpts ) use ( $group ) {
189 global $wgDisableUserGroupExpiry;
190 $dbr = wfGetDB( DB_REPLICA );
192 $setOpts += Database::getCacheSetOptions( $dbr );
194 return $dbr->selectField(
195 'user_groups',
196 'COUNT(*)',
198 'ug_group' => $group,
199 $wgDisableUserGroupExpiry ?
200 '1' :
201 'ug_expiry IS NULL OR ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() )
203 __METHOD__
206 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
211 * @return int
213 static function jobs() {
214 if ( !isset( self::$jobs ) ) {
215 try{
216 self::$jobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
217 } catch ( JobQueueError $e ) {
218 self::$jobs = 0;
221 * Zero rows still do single row read for row that doesn't exist,
222 * but people are annoyed by that
224 if ( self::$jobs == 1 ) {
225 self::$jobs = 0;
228 return self::$jobs;
232 * @param int $ns
234 * @return int
236 static function pagesInNs( $ns ) {
237 if ( !isset( self::$pageCount[$ns] ) ) {
238 $dbr = wfGetDB( DB_REPLICA );
239 self::$pageCount[$ns] = (int)$dbr->selectField(
240 'page',
241 'COUNT(*)',
242 [ 'page_namespace' => $ns ],
243 __METHOD__
246 return self::$pageCount[$ns];
250 * Is the provided row of site stats sane, or should it be regenerated?
252 * Checks only fields which are filled by SiteStatsInit::refresh.
254 * @param bool|object $row
256 * @return bool
258 private static function isSane( $row ) {
259 if ( $row === false
260 || $row->ss_total_pages < $row->ss_good_articles
261 || $row->ss_total_edits < $row->ss_total_pages
263 return false;
265 // Now check for underflow/overflow
266 foreach ( [
267 'ss_total_edits',
268 'ss_good_articles',
269 'ss_total_pages',
270 'ss_users',
271 'ss_images',
272 ] as $member ) {
273 if ( $row->$member > 2000000000 || $row->$member < 0 ) {
274 return false;
277 return true;
282 * Class designed for counting of stats.
284 class SiteStatsInit {
286 // Database connection
287 private $db;
289 // Various stats
290 private $mEdits = null, $mArticles = null, $mPages = null;
291 private $mUsers = null, $mFiles = null;
294 * Constructor
295 * @param bool|IDatabase $database
296 * - boolean: Whether to use the master DB
297 * - IDatabase: Database connection to use
299 public function __construct( $database = false ) {
300 if ( $database instanceof IDatabase ) {
301 $this->db = $database;
302 } elseif ( $database ) {
303 $this->db = wfGetDB( DB_MASTER );
304 } else {
305 $this->db = wfGetDB( DB_REPLICA, 'vslow' );
310 * Count the total number of edits
311 * @return int
313 public function edits() {
314 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
315 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
316 return $this->mEdits;
320 * Count pages in article space(s)
321 * @return int
323 public function articles() {
324 global $wgArticleCountMethod;
326 $tables = [ 'page' ];
327 $conds = [
328 'page_namespace' => MWNamespace::getContentNamespaces(),
329 'page_is_redirect' => 0,
332 if ( $wgArticleCountMethod == 'link' ) {
333 $tables[] = 'pagelinks';
334 $conds[] = 'pl_from=page_id';
335 } elseif ( $wgArticleCountMethod == 'comma' ) {
336 // To make a correct check for this, we would need, for each page,
337 // to load the text, maybe uncompress it, maybe decode it and then
338 // check if there's one comma.
339 // But one thing we are sure is that if the page is empty, it can't
340 // contain a comma :)
341 $conds[] = 'page_len > 0';
344 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
345 $conds, __METHOD__ );
346 return $this->mArticles;
350 * Count total pages
351 * @return int
353 public function pages() {
354 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
355 return $this->mPages;
359 * Count total users
360 * @return int
362 public function users() {
363 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
364 return $this->mUsers;
368 * Count total files
369 * @return int
371 public function files() {
372 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
373 return $this->mFiles;
377 * Do all updates and commit them. More or less a replacement
378 * for the original initStats, but without output.
380 * @param IDatabase|bool $database
381 * - boolean: Whether to use the master DB
382 * - IDatabase: Database connection to use
383 * @param array $options Array of options, may contain the following values
384 * - activeUsers boolean: Whether to update the number of active users (default: false)
386 public static function doAllAndCommit( $database, array $options = [] ) {
387 $options += [ 'update' => false, 'activeUsers' => false ];
389 // Grab the object and count everything
390 $counter = new SiteStatsInit( $database );
392 $counter->edits();
393 $counter->articles();
394 $counter->pages();
395 $counter->users();
396 $counter->files();
398 $counter->refresh();
400 // Count active users if need be
401 if ( $options['activeUsers'] ) {
402 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
407 * Refresh site_stats
409 public function refresh() {
410 $values = [
411 'ss_row_id' => 1,
412 'ss_total_edits' => ( $this->mEdits === null ? $this->edits() : $this->mEdits ),
413 'ss_good_articles' => ( $this->mArticles === null ? $this->articles() : $this->mArticles ),
414 'ss_total_pages' => ( $this->mPages === null ? $this->pages() : $this->mPages ),
415 'ss_users' => ( $this->mUsers === null ? $this->users() : $this->mUsers ),
416 'ss_images' => ( $this->mFiles === null ? $this->files() : $this->mFiles ),
419 $dbw = wfGetDB( DB_MASTER );
420 $dbw->upsert( 'site_stats', $values, [ 'ss_row_id' ], $values, __METHOD__ );