Merge "RC Filters: Last revision filter group"
[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
37 /** @var int */
38 private static $jobs;
39
40 /** @var int[] */
41 private static $pageCount = [];
42
43 static function unload() {
44 self::$loaded = false;
45 }
46
47 static function recache() {
48 self::load( true );
49 }
50
51 /**
52 * @param bool $recache
53 */
54 static function load( $recache = false ) {
55 if ( self::$loaded && !$recache ) {
56 return;
57 }
58
59 self::$row = self::loadAndLazyInit();
60
61 # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS
62 if ( !isset( self::$row->ss_total_pages ) && self::$row->ss_total_pages == -1 ) {
63 # Update schema
64 $u = new SiteStatsUpdate( 0, 0, 0 );
65 $u->doUpdate();
66 self::$row = self::doLoad( wfGetDB( DB_REPLICA ) );
67 }
68
69 self::$loaded = true;
70 }
71
72 /**
73 * @return bool|stdClass
74 */
75 static function loadAndLazyInit() {
76 global $wgMiserMode;
77
78 wfDebug( __METHOD__ . ": reading site_stats from replica DB\n" );
79 $row = self::doLoad( wfGetDB( DB_REPLICA ) );
80
81 if ( !self::isSane( $row ) ) {
82 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
83 if ( $lb->hasOrMadeRecentMasterChanges() ) {
84 // Might have just been initialized during this request? Underflow?
85 wfDebug( __METHOD__ . ": site_stats damaged or missing on replica DB\n" );
86 $row = self::doLoad( wfGetDB( DB_MASTER ) );
87 }
88 }
89
90 if ( !$wgMiserMode && !self::isSane( $row ) ) {
91 // Normally the site_stats table is initialized at install time.
92 // Some manual construction scenarios may leave the table empty or
93 // broken, however, for instance when importing from a dump into a
94 // clean schema with mwdumper.
95 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
96
97 SiteStatsInit::doAllAndCommit( wfGetDB( DB_REPLICA ) );
98
99 $row = self::doLoad( wfGetDB( DB_MASTER ) );
100 }
101
102 if ( !self::isSane( $row ) ) {
103 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
104 }
105
106 return $row;
107 }
108
109 /**
110 * @param IDatabase $db
111 * @return bool|stdClass
112 */
113 static function doLoad( $db ) {
114 return $db->selectRow( 'site_stats', [
115 'ss_row_id',
116 'ss_total_edits',
117 'ss_good_articles',
118 'ss_total_pages',
119 'ss_users',
120 'ss_active_users',
121 'ss_images',
122 ], [], __METHOD__ );
123 }
124
125 /**
126 * Return the total number of page views. Except we don't track those anymore.
127 * Stop calling this function, it will be removed some time in the future. It's
128 * kept here simply to prevent fatal errors.
129 *
130 * @deprecated since 1.25
131 * @return int
132 */
133 static function views() {
134 wfDeprecated( __METHOD__, '1.25' );
135 return 0;
136 }
137
138 /**
139 * @return int
140 */
141 static function edits() {
142 self::load();
143 return self::$row->ss_total_edits;
144 }
145
146 /**
147 * @return int
148 */
149 static function articles() {
150 self::load();
151 return self::$row->ss_good_articles;
152 }
153
154 /**
155 * @return int
156 */
157 static function pages() {
158 self::load();
159 return self::$row->ss_total_pages;
160 }
161
162 /**
163 * @return int
164 */
165 static function users() {
166 self::load();
167 return self::$row->ss_users;
168 }
169
170 /**
171 * @return int
172 */
173 static function activeUsers() {
174 self::load();
175 return self::$row->ss_active_users;
176 }
177
178 /**
179 * @return int
180 */
181 static function images() {
182 self::load();
183 return self::$row->ss_images;
184 }
185
186 /**
187 * Find the number of users in a given user group.
188 * @param string $group Name of group
189 * @return int
190 */
191 static function numberingroup( $group ) {
192 $cache = ObjectCache::getMainWANInstance();
193 return $cache->getWithSetCallback(
194 wfMemcKey( 'SiteStats', 'groupcounts', $group ),
195 $cache::TTL_HOUR,
196 function ( $oldValue, &$ttl, array &$setOpts ) use ( $group ) {
197 global $wgDisableUserGroupExpiry;
198 $dbr = wfGetDB( DB_REPLICA );
199
200 $setOpts += Database::getCacheSetOptions( $dbr );
201
202 return $dbr->selectField(
203 'user_groups',
204 'COUNT(*)',
205 [
206 'ug_group' => $group,
207 $wgDisableUserGroupExpiry ?
208 '1' :
209 'ug_expiry IS NULL OR ug_expiry >= ' . $dbr->addQuotes( $dbr->timestamp() )
210 ],
211 __METHOD__
212 );
213 },
214 [ 'pcTTL' => $cache::TTL_PROC_LONG ]
215 );
216 }
217
218 /**
219 * @return int
220 */
221 static function jobs() {
222 if ( !isset( self::$jobs ) ) {
223 try{
224 self::$jobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
225 } catch ( JobQueueError $e ) {
226 self::$jobs = 0;
227 }
228 /**
229 * Zero rows still do single row read for row that doesn't exist,
230 * but people are annoyed by that
231 */
232 if ( self::$jobs == 1 ) {
233 self::$jobs = 0;
234 }
235 }
236 return self::$jobs;
237 }
238
239 /**
240 * @param int $ns
241 *
242 * @return int
243 */
244 static function pagesInNs( $ns ) {
245 if ( !isset( self::$pageCount[$ns] ) ) {
246 $dbr = wfGetDB( DB_REPLICA );
247 self::$pageCount[$ns] = (int)$dbr->selectField(
248 'page',
249 'COUNT(*)',
250 [ 'page_namespace' => $ns ],
251 __METHOD__
252 );
253 }
254 return self::$pageCount[$ns];
255 }
256
257 /**
258 * Is the provided row of site stats sane, or should it be regenerated?
259 *
260 * Checks only fields which are filled by SiteStatsInit::refresh.
261 *
262 * @param bool|object $row
263 *
264 * @return bool
265 */
266 private static function isSane( $row ) {
267 if ( $row === false
268 || $row->ss_total_pages < $row->ss_good_articles
269 || $row->ss_total_edits < $row->ss_total_pages
270 ) {
271 return false;
272 }
273 // Now check for underflow/overflow
274 foreach ( [
275 'ss_total_edits',
276 'ss_good_articles',
277 'ss_total_pages',
278 'ss_users',
279 'ss_images',
280 ] as $member ) {
281 if ( $row->$member > 2000000000 || $row->$member < 0 ) {
282 return false;
283 }
284 }
285 return true;
286 }
287 }
288
289 /**
290 * Class designed for counting of stats.
291 */
292 class SiteStatsInit {
293
294 // Database connection
295 private $db;
296
297 // Various stats
298 private $mEdits = null, $mArticles = null, $mPages = null;
299 private $mUsers = null, $mFiles = null;
300
301 /**
302 * Constructor
303 * @param bool|IDatabase $database
304 * - boolean: 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 * - boolean: 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 boolean: 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 * Refresh site_stats
416 */
417 public function refresh() {
418 $values = [
419 'ss_row_id' => 1,
420 'ss_total_edits' => ( $this->mEdits === null ? $this->edits() : $this->mEdits ),
421 'ss_good_articles' => ( $this->mArticles === null ? $this->articles() : $this->mArticles ),
422 'ss_total_pages' => ( $this->mPages === null ? $this->pages() : $this->mPages ),
423 'ss_users' => ( $this->mUsers === null ? $this->users() : $this->mUsers ),
424 'ss_images' => ( $this->mFiles === null ? $this->files() : $this->mFiles ),
425 ];
426
427 $dbw = wfGetDB( DB_MASTER );
428 $dbw->upsert( 'site_stats', $values, [ 'ss_row_id' ], $values, __METHOD__ );
429 }
430 }