Fix Bug 33384 - database drivers cannot be provided by extension
[lhc/web/wiklou.git] / includes / SiteStats.php
1 <?php
2
3 /**
4 * Static accessor class for site_stats and related things
5 */
6 class SiteStats {
7 static $row, $loaded = false;
8 static $admins, $jobs;
9 static $pageCount = array();
10 static $groupMemberCounts = array();
11
12 static function recache() {
13 self::load( true );
14 }
15
16 /**
17 * @param $recache bool
18 */
19 static function load( $recache = false ) {
20 if ( self::$loaded && !$recache ) {
21 return;
22 }
23
24 self::$row = self::loadAndLazyInit();
25
26 # This code is somewhat schema-agnostic, because I'm changing it in a minor release -- TS
27 if ( !isset( self::$row->ss_total_pages ) && self::$row->ss_total_pages == -1 ) {
28 # Update schema
29 $u = new SiteStatsUpdate( 0, 0, 0 );
30 $u->doUpdate();
31 $dbr = wfGetDB( DB_SLAVE );
32 self::$row = $dbr->selectRow( 'site_stats', '*', false, __METHOD__ );
33 }
34
35 self::$loaded = true;
36 }
37
38 /**
39 * @return Bool|ResultWrapper
40 */
41 static function loadAndLazyInit() {
42 wfDebug( __METHOD__ . ": reading site_stats from slave\n" );
43 $row = self::doLoad( wfGetDB( DB_SLAVE ) );
44
45 if( !self::isSane( $row ) ) {
46 // Might have just been initialized during this request? Underflow?
47 wfDebug( __METHOD__ . ": site_stats damaged or missing on slave\n" );
48 $row = self::doLoad( wfGetDB( DB_MASTER ) );
49 }
50
51 if( !self::isSane( $row ) ) {
52 // Normally the site_stats table is initialized at install time.
53 // Some manual construction scenarios may leave the table empty or
54 // broken, however, for instance when importing from a dump into a
55 // clean schema with mwdumper.
56 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
57
58 SiteStatsInit::doAllAndCommit( wfGetDB( DB_SLAVE ) );
59
60 $row = self::doLoad( wfGetDB( DB_MASTER ) );
61 }
62
63 if( !self::isSane( $row ) ) {
64 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
65 }
66 return $row;
67 }
68
69 /**
70 * @param $db DatabaseBase
71 * @return Bool|ResultWrapper
72 */
73 static function doLoad( $db ) {
74 return $db->selectRow( 'site_stats', '*', false, __METHOD__ );
75 }
76
77 /**
78 * @return int
79 */
80 static function views() {
81 self::load();
82 return self::$row->ss_total_views;
83 }
84
85 /**
86 * @return int
87 */
88 static function edits() {
89 self::load();
90 return self::$row->ss_total_edits;
91 }
92
93 /**
94 * @return int
95 */
96 static function articles() {
97 self::load();
98 return self::$row->ss_good_articles;
99 }
100
101 /**
102 * @return int
103 */
104 static function pages() {
105 self::load();
106 return self::$row->ss_total_pages;
107 }
108
109 /**
110 * @return int
111 */
112 static function users() {
113 self::load();
114 return self::$row->ss_users;
115 }
116
117 /**
118 * @return int
119 */
120 static function activeUsers() {
121 self::load();
122 return self::$row->ss_active_users;
123 }
124
125 /**
126 * @return int
127 */
128 static function images() {
129 self::load();
130 return self::$row->ss_images;
131 }
132
133 /**
134 * Find the number of users in a given user group.
135 * @param $group String: name of group
136 * @return Integer
137 */
138 static function numberingroup( $group ) {
139 if ( !isset( self::$groupMemberCounts[$group] ) ) {
140 global $wgMemc;
141 $key = wfMemcKey( 'SiteStats', 'groupcounts', $group );
142 $hit = $wgMemc->get( $key );
143 if ( !$hit ) {
144 $dbr = wfGetDB( DB_SLAVE );
145 $hit = $dbr->selectField(
146 'user_groups',
147 'COUNT(*)',
148 array( 'ug_group' => $group ),
149 __METHOD__
150 );
151 $wgMemc->set( $key, $hit, 3600 );
152 }
153 self::$groupMemberCounts[$group] = $hit;
154 }
155 return self::$groupMemberCounts[$group];
156 }
157
158 /**
159 * @return int
160 */
161 static function jobs() {
162 if ( !isset( self::$jobs ) ) {
163 $dbr = wfGetDB( DB_SLAVE );
164 self::$jobs = $dbr->estimateRowCount( 'job' );
165 /* Zero rows still do single row read for row that doesn't exist, but people are annoyed by that */
166 if ( self::$jobs == 1 ) {
167 self::$jobs = 0;
168 }
169 }
170 return self::$jobs;
171 }
172
173 /**
174 * @param $ns int
175 *
176 * @return int
177 */
178 static function pagesInNs( $ns ) {
179 wfProfileIn( __METHOD__ );
180 if( !isset( self::$pageCount[$ns] ) ) {
181 $dbr = wfGetDB( DB_SLAVE );
182 self::$pageCount[$ns] = (int)$dbr->selectField(
183 'page',
184 'COUNT(*)',
185 array( 'page_namespace' => $ns ),
186 __METHOD__
187 );
188 }
189 wfProfileOut( __METHOD__ );
190 return self::$pageCount[$ns];
191 }
192
193 /**
194 * Is the provided row of site stats sane, or should it be regenerated?
195 *
196 * @param $row
197 *
198 * @return bool
199 */
200 private static function isSane( $row ) {
201 if(
202 $row === false
203 || $row->ss_total_pages < $row->ss_good_articles
204 || $row->ss_total_edits < $row->ss_total_pages
205 ) {
206 return false;
207 }
208 // Now check for underflow/overflow
209 foreach( array( 'total_views', 'total_edits', 'good_articles',
210 'total_pages', 'users', 'admins', 'images' ) as $member ) {
211 if(
212 $row->{"ss_$member"} > 2000000000
213 || $row->{"ss_$member"} < 0
214 ) {
215 return false;
216 }
217 }
218 return true;
219 }
220 }
221
222 /**
223 * Class for handling updates to the site_stats table
224 */
225 class SiteStatsUpdate implements DeferrableUpdate {
226
227 var $mViews, $mEdits, $mGood, $mPages, $mUsers;
228
229 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
230 $this->mViews = $views;
231 $this->mEdits = $edits;
232 $this->mGood = $good;
233 $this->mPages = $pages;
234 $this->mUsers = $users;
235 }
236
237 /**
238 * @param $sql
239 * @param $field
240 * @param $delta
241 */
242 function appendUpdate( &$sql, $field, $delta ) {
243 if ( $delta ) {
244 if ( $sql ) {
245 $sql .= ',';
246 }
247 if ( $delta < 0 ) {
248 $sql .= "$field=$field-1";
249 } else {
250 $sql .= "$field=$field+1";
251 }
252 }
253 }
254
255 function doUpdate() {
256 $dbw = wfGetDB( DB_MASTER );
257
258 $updates = '';
259
260 $this->appendUpdate( $updates, 'ss_total_views', $this->mViews );
261 $this->appendUpdate( $updates, 'ss_total_edits', $this->mEdits );
262 $this->appendUpdate( $updates, 'ss_good_articles', $this->mGood );
263 $this->appendUpdate( $updates, 'ss_total_pages', $this->mPages );
264 $this->appendUpdate( $updates, 'ss_users', $this->mUsers );
265
266 if ( $updates ) {
267 $site_stats = $dbw->tableName( 'site_stats' );
268 $sql = "UPDATE $site_stats SET $updates";
269
270 # Need a separate transaction because this a global lock
271 $dbw->begin();
272 $dbw->query( $sql, __METHOD__ );
273 $dbw->commit();
274 }
275 }
276
277 /**
278 * @param $dbw DatabaseBase
279 * @return bool|mixed
280 */
281 public static function cacheUpdate( $dbw ) {
282 global $wgActiveUserDays;
283 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
284 # Get non-bot users than did some recent action other than making accounts.
285 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
286 $activeUsers = $dbr->selectField(
287 'recentchanges',
288 'COUNT( DISTINCT rc_user_text )',
289 array(
290 'rc_user != 0',
291 'rc_bot' => 0,
292 "rc_log_type != 'newusers' OR rc_log_type IS NULL",
293 "rc_timestamp >= '{$dbw->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 )}'",
294 ),
295 __METHOD__
296 );
297 $dbw->update(
298 'site_stats',
299 array( 'ss_active_users' => intval( $activeUsers ) ),
300 array( 'ss_row_id' => 1 ),
301 __METHOD__
302 );
303 return $activeUsers;
304 }
305 }
306
307 /**
308 * Class designed for counting of stats.
309 */
310 class SiteStatsInit {
311
312 // Database connection
313 private $db;
314
315 // Various stats
316 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
317
318 /**
319 * Constructor
320 * @param $database Boolean or DatabaseBase:
321 * - Boolean: whether to use the master DB
322 * - DatabaseBase: database connection to use
323 */
324 public function __construct( $database = false ) {
325 if ( $database instanceof DatabaseBase ) {
326 $this->db = $database;
327 } else {
328 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
329 }
330 }
331
332 /**
333 * Count the total number of edits
334 * @return Integer
335 */
336 public function edits() {
337 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
338 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
339 return $this->mEdits;
340 }
341
342 /**
343 * Count pages in article space(s)
344 * @return Integer
345 */
346 public function articles() {
347 global $wgArticleCountMethod;
348
349 $tables = array( 'page' );
350 $conds = array(
351 'page_namespace' => MWNamespace::getContentNamespaces(),
352 'page_is_redirect' => 0,
353 );
354
355 if ( $wgArticleCountMethod == 'link' ) {
356 $tables[] = 'pagelinks';
357 $conds[] = 'pl_from=page_id';
358 } elseif ( $wgArticleCountMethod == 'comma' ) {
359 // To make a correct check for this, we would need, for each page,
360 // to load the text, maybe uncompress it, maybe decode it and then
361 // check if there's one comma.
362 // But one thing we are sure is that if the page is empty, it can't
363 // contain a comma :)
364 $conds[] = 'page_len > 0';
365 }
366
367 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
368 $conds, __METHOD__ );
369 return $this->mArticles;
370 }
371
372 /**
373 * Count total pages
374 * @return Integer
375 */
376 public function pages() {
377 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
378 return $this->mPages;
379 }
380
381 /**
382 * Count total users
383 * @return Integer
384 */
385 public function users() {
386 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
387 return $this->mUsers;
388 }
389
390 /**
391 * Count views
392 * @return Integer
393 */
394 public function views() {
395 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
396 return $this->mViews;
397 }
398
399 /**
400 * Count total files
401 * @return Integer
402 */
403 public function files() {
404 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
405 return $this->mFiles;
406 }
407
408 /**
409 * Do all updates and commit them. More or less a replacement
410 * for the original initStats, but without output.
411 *
412 * @param $database Boolean or DatabaseBase:
413 * - Boolean: whether to use the master DB
414 * - DatabaseBase: database connection to use
415 * @param $options Array of options, may contain the following values
416 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
417 * - views Boolean: when true, do not update the number of page views (default: true)
418 * - activeUsers Boolean: whether to update the number of active users (default: false)
419 */
420 public static function doAllAndCommit( $database, array $options = array() ) {
421 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
422
423 // Grab the object and count everything
424 $counter = new SiteStatsInit( $database );
425
426 $counter->edits();
427 $counter->articles();
428 $counter->pages();
429 $counter->users();
430 $counter->files();
431
432 // Only do views if we don't want to not count them
433 if( $options['views'] ) {
434 $counter->views();
435 }
436
437 // Update/refresh
438 if( $options['update'] ) {
439 $counter->update();
440 } else {
441 $counter->refresh();
442 }
443
444 // Count active users if need be
445 if( $options['activeUsers'] ) {
446 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
447 }
448 }
449
450 /**
451 * Update the current row with the selected values
452 */
453 public function update() {
454 list( $values, $conds ) = $this->getDbParams();
455 $dbw = wfGetDB( DB_MASTER );
456 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
457 }
458
459 /**
460 * Refresh site_stats. Erase the current record and save all
461 * the new values.
462 */
463 public function refresh() {
464 list( $values, $conds, $views ) = $this->getDbParams();
465 $dbw = wfGetDB( DB_MASTER );
466 $dbw->delete( 'site_stats', $conds, __METHOD__ );
467 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
468 }
469
470 /**
471 * Return three arrays of params for the db queries
472 * @return Array
473 */
474 private function getDbParams() {
475 $values = array(
476 'ss_total_edits' => $this->mEdits,
477 'ss_good_articles' => $this->mArticles,
478 'ss_total_pages' => $this->mPages,
479 'ss_users' => $this->mUsers,
480 'ss_images' => $this->mFiles
481 );
482 $conds = array( 'ss_row_id' => 1 );
483 $views = array( 'ss_total_views' => $this->mViews );
484 return array( $values, $conds, $views );
485 }
486 }