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