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