Merge "Make SiteStatsInit::doPlaceholderInit() use 1 for ss_row_id"
[lhc/web/wiklou.git] / includes / SiteStats.php
1 <?php
2 /**
3 * Accessors and mutators for the site-wide statistics.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\Database;
24 use Wikimedia\Rdbms\IDatabase;
25 use MediaWiki\MediaWikiServices;
26
27 /**
28 * Static accessor class for site_stats and related things
29 */
30 class SiteStats {
31 /** @var bool|stdClass */
32 private static $row;
33
34 /** @var bool */
35 private static $loaded = false;
36 /** @var int[] */
37 private static $pageCount = [];
38
39 static function unload() {
40 self::$loaded = false;
41 }
42
43 static function recache() {
44 self::load( true );
45 }
46
47 /**
48 * @param bool $recache
49 */
50 static function load( $recache = false ) {
51 if ( self::$loaded && !$recache ) {
52 return;
53 }
54
55 self::$row = self::loadAndLazyInit();
56
57 self::$loaded = true;
58 }
59
60 /**
61 * @return bool|stdClass
62 */
63 static function loadAndLazyInit() {
64 global $wgMiserMode;
65
66 wfDebug( __METHOD__ . ": reading site_stats from replica DB\n" );
67 $row = self::doLoad( wfGetDB( DB_REPLICA ) );
68
69 if ( !self::isSane( $row ) ) {
70 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
71 if ( $lb->hasOrMadeRecentMasterChanges() ) {
72 // Might have just been initialized during this request? Underflow?
73 wfDebug( __METHOD__ . ": site_stats damaged or missing on replica DB\n" );
74 $row = self::doLoad( wfGetDB( DB_MASTER ) );
75 }
76 }
77
78 if ( !self::isSane( $row ) ) {
79 if ( $wgMiserMode ) {
80 // Start off with all zeroes, assuming that this is a new wiki or any
81 // repopulations where done manually via script.
82 SiteStatsInit::doPlaceholderInit();
83 } else {
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" );
89 SiteStatsInit::doAllAndCommit( wfGetDB( DB_REPLICA ) );
90 }
91
92 $row = self::doLoad( wfGetDB( DB_MASTER ) );
93 }
94
95 if ( !self::isSane( $row ) ) {
96 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
97 $row = (object)array_fill_keys( self::selectFields(), 0 );
98 }
99
100 return $row;
101 }
102
103 /**
104 * @param IDatabase $db
105 * @return bool|stdClass
106 */
107 static function doLoad( $db ) {
108 return $db->selectRow(
109 'site_stats',
110 self::selectFields(),
111 [ 'ss_row_id' => 1 ],
112 __METHOD__
113 );
114 }
115
116 /**
117 * Return the total number of page views. Except we don't track those anymore.
118 * Stop calling this function, it will be removed some time in the future. It's
119 * kept here simply to prevent fatal errors.
120 *
121 * @deprecated since 1.25
122 * @return int
123 */
124 static function views() {
125 wfDeprecated( __METHOD__, '1.25' );
126 return 0;
127 }
128
129 /**
130 * @return int
131 */
132 static function edits() {
133 self::load();
134 return self::$row->ss_total_edits;
135 }
136
137 /**
138 * @return int
139 */
140 static function articles() {
141 self::load();
142 return self::$row->ss_good_articles;
143 }
144
145 /**
146 * @return int
147 */
148 static function pages() {
149 self::load();
150 return self::$row->ss_total_pages;
151 }
152
153 /**
154 * @return int
155 */
156 static function users() {
157 self::load();
158 return self::$row->ss_users;
159 }
160
161 /**
162 * @return int
163 */
164 static function activeUsers() {
165 self::load();
166 return self::$row->ss_active_users;
167 }
168
169 /**
170 * @return int
171 */
172 static function images() {
173 self::load();
174 return self::$row->ss_images;
175 }
176
177 /**
178 * Find the number of users in a given user group.
179 * @param string $group Name of group
180 * @return int
181 */
182 static function numberingroup( $group ) {
183 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
184 return $cache->getWithSetCallback(
185 $cache->makeKey( 'SiteStats', 'groupcounts', $group ),
186 $cache::TTL_HOUR,
187 function ( $oldValue, &$ttl, array &$setOpts ) use ( $group ) {
188 $dbr = wfGetDB( DB_REPLICA );
189
190 $setOpts += Database::getCacheSetOptions( $dbr );
191
192 return $dbr->selectField(
193 'user_groups',
194 'COUNT(*)',
195 [
196 'ug_group' => $group,
197 'ug_expiry IS NULL OR ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() )
198 ],
199 __METHOD__
200 );
201 },
202 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
203 );
204 }
205
206 /**
207 * Total number of jobs in the job queue.
208 * @return int
209 */
210 static function jobs() {
211 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
212 return $cache->getWithSetCallback(
213 $cache->makeKey( 'SiteStats', 'jobscount' ),
214 $cache::TTL_MINUTE,
215 function ( $oldValue, &$ttl, array &$setOpts ) {
216 try{
217 $jobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
218 } catch ( JobQueueError $e ) {
219 $jobs = 0;
220 }
221 return $jobs;
222 },
223 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
224 );
225 }
226
227 /**
228 * @param int $ns
229 *
230 * @return int
231 */
232 static function pagesInNs( $ns ) {
233 if ( !isset( self::$pageCount[$ns] ) ) {
234 $dbr = wfGetDB( DB_REPLICA );
235 self::$pageCount[$ns] = (int)$dbr->selectField(
236 'page',
237 'COUNT(*)',
238 [ 'page_namespace' => $ns ],
239 __METHOD__
240 );
241 }
242 return self::$pageCount[$ns];
243 }
244
245 /**
246 * @return array
247 */
248 public static function selectFields() {
249 return [
250 'ss_total_edits',
251 'ss_good_articles',
252 'ss_total_pages',
253 'ss_users',
254 'ss_active_users',
255 'ss_images',
256 ];
257 }
258
259 /**
260 * Is the provided row of site stats sane, or should it be regenerated?
261 *
262 * Checks only fields which are filled by SiteStatsInit::refresh.
263 *
264 * @param bool|object $row
265 * @return bool
266 */
267 private static function isSane( $row ) {
268 if ( $row === false
269 || $row->ss_total_pages < $row->ss_good_articles
270 || $row->ss_total_edits < $row->ss_total_pages
271 ) {
272 return false;
273 }
274 // Now check for underflow/overflow
275 foreach ( [
276 'ss_total_edits',
277 'ss_good_articles',
278 'ss_total_pages',
279 'ss_users',
280 'ss_images',
281 ] as $member ) {
282 if ( $row->$member > 2000000000 || $row->$member < 0 ) {
283 return false;
284 }
285 }
286 return true;
287 }
288 }
289
290 /**
291 * Class designed for counting of stats.
292 */
293 class SiteStatsInit {
294
295 // Database connection
296 private $db;
297
298 // Various stats
299 private $mEdits = null, $mArticles = null, $mPages = null;
300 private $mUsers = null, $mFiles = null;
301
302 /**
303 * @param bool|IDatabase $database
304 * - bool: Whether to use the master DB
305 * - IDatabase: Database connection to use
306 */
307 public function __construct( $database = false ) {
308 if ( $database instanceof IDatabase ) {
309 $this->db = $database;
310 } elseif ( $database ) {
311 $this->db = wfGetDB( DB_MASTER );
312 } else {
313 $this->db = wfGetDB( DB_REPLICA, 'vslow' );
314 }
315 }
316
317 /**
318 * Count the total number of edits
319 * @return int
320 */
321 public function edits() {
322 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
323 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
324 return $this->mEdits;
325 }
326
327 /**
328 * Count pages in article space(s)
329 * @return int
330 */
331 public function articles() {
332 global $wgArticleCountMethod;
333
334 $tables = [ 'page' ];
335 $conds = [
336 'page_namespace' => MWNamespace::getContentNamespaces(),
337 'page_is_redirect' => 0,
338 ];
339
340 if ( $wgArticleCountMethod == 'link' ) {
341 $tables[] = 'pagelinks';
342 $conds[] = 'pl_from=page_id';
343 } elseif ( $wgArticleCountMethod == 'comma' ) {
344 // To make a correct check for this, we would need, for each page,
345 // to load the text, maybe uncompress it, maybe decode it and then
346 // check if there's one comma.
347 // But one thing we are sure is that if the page is empty, it can't
348 // contain a comma :)
349 $conds[] = 'page_len > 0';
350 }
351
352 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
353 $conds, __METHOD__ );
354 return $this->mArticles;
355 }
356
357 /**
358 * Count total pages
359 * @return int
360 */
361 public function pages() {
362 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
363 return $this->mPages;
364 }
365
366 /**
367 * Count total users
368 * @return int
369 */
370 public function users() {
371 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
372 return $this->mUsers;
373 }
374
375 /**
376 * Count total files
377 * @return int
378 */
379 public function files() {
380 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
381 return $this->mFiles;
382 }
383
384 /**
385 * Do all updates and commit them. More or less a replacement
386 * for the original initStats, but without output.
387 *
388 * @param IDatabase|bool $database
389 * - bool: Whether to use the master DB
390 * - IDatabase: Database connection to use
391 * @param array $options Array of options, may contain the following values
392 * - activeUsers bool: Whether to update the number of active users (default: false)
393 */
394 public static function doAllAndCommit( $database, array $options = [] ) {
395 $options += [ 'update' => false, 'activeUsers' => false ];
396
397 // Grab the object and count everything
398 $counter = new SiteStatsInit( $database );
399
400 $counter->edits();
401 $counter->articles();
402 $counter->pages();
403 $counter->users();
404 $counter->files();
405
406 $counter->refresh();
407
408 // Count active users if need be
409 if ( $options['activeUsers'] ) {
410 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
411 }
412 }
413
414 /**
415 * Insert a dummy row with all zeroes if no row is present
416 */
417 public static function doPlaceholderInit() {
418 $dbw = wfGetDB( DB_MASTER );
419 $exists = $dbw->selectField( 'site_stats', '1', [ 'ss_row_id' => 1 ], __METHOD__ );
420 if ( $exists === false ) {
421 $dbw->insert(
422 'site_stats',
423 [ 'ss_row_id' => 1 ] + array_fill_keys( SiteStats::selectFields(), 0 ),
424 __METHOD__,
425 [ 'IGNORE' ]
426 );
427 }
428 }
429
430 /**
431 * Refresh site_stats
432 */
433 public function refresh() {
434 $values = [
435 'ss_row_id' => 1,
436 'ss_total_edits' => ( $this->mEdits === null ? $this->edits() : $this->mEdits ),
437 'ss_good_articles' => ( $this->mArticles === null ? $this->articles() : $this->mArticles ),
438 'ss_total_pages' => ( $this->mPages === null ? $this->pages() : $this->mPages ),
439 'ss_users' => ( $this->mUsers === null ? $this->users() : $this->mUsers ),
440 'ss_images' => ( $this->mFiles === null ? $this->files() : $this->mFiles ),
441 ];
442
443 $dbw = wfGetDB( DB_MASTER );
444 $dbw->upsert( 'site_stats', $values, [ 'ss_row_id' ], $values, __METHOD__ );
445 }
446 }