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