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