Merge "Moved begin() since the lock() function may cause a BEGIN."
[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 $dbr = wfGetDB( DB_SLAVE );
52 self::$row = $dbr->selectRow( 'site_stats', '*', false, __METHOD__ );
53 }
54
55 self::$loaded = true;
56 }
57
58 /**
59 * @return Bool|ResultWrapper
60 */
61 static function loadAndLazyInit() {
62 wfDebug( __METHOD__ . ": reading site_stats from slave\n" );
63 $row = self::doLoad( wfGetDB( DB_SLAVE ) );
64
65 if( !self::isSane( $row ) ) {
66 // Might have just been initialized during this request? Underflow?
67 wfDebug( __METHOD__ . ": site_stats damaged or missing on slave\n" );
68 $row = self::doLoad( wfGetDB( DB_MASTER ) );
69 }
70
71 if( !self::isSane( $row ) ) {
72 // Normally the site_stats table is initialized at install time.
73 // Some manual construction scenarios may leave the table empty or
74 // broken, however, for instance when importing from a dump into a
75 // clean schema with mwdumper.
76 wfDebug( __METHOD__ . ": initializing damaged or missing site_stats\n" );
77
78 SiteStatsInit::doAllAndCommit( wfGetDB( DB_SLAVE ) );
79
80 $row = self::doLoad( wfGetDB( DB_MASTER ) );
81 }
82
83 if( !self::isSane( $row ) ) {
84 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
85 }
86 return $row;
87 }
88
89 /**
90 * @param $db DatabaseBase
91 * @return Bool|ResultWrapper
92 */
93 static function doLoad( $db ) {
94 return $db->selectRow( 'site_stats', '*', false, __METHOD__ );
95 }
96
97 /**
98 * @return int
99 */
100 static function views() {
101 self::load();
102 return self::$row->ss_total_views;
103 }
104
105 /**
106 * @return int
107 */
108 static function edits() {
109 self::load();
110 return self::$row->ss_total_edits;
111 }
112
113 /**
114 * @return int
115 */
116 static function articles() {
117 self::load();
118 return self::$row->ss_good_articles;
119 }
120
121 /**
122 * @return int
123 */
124 static function pages() {
125 self::load();
126 return self::$row->ss_total_pages;
127 }
128
129 /**
130 * @return int
131 */
132 static function users() {
133 self::load();
134 return self::$row->ss_users;
135 }
136
137 /**
138 * @return int
139 */
140 static function activeUsers() {
141 self::load();
142 return self::$row->ss_active_users;
143 }
144
145 /**
146 * @return int
147 */
148 static function images() {
149 self::load();
150 return self::$row->ss_images;
151 }
152
153 /**
154 * Find the number of users in a given user group.
155 * @param $group String: name of group
156 * @return Integer
157 */
158 static function numberingroup( $group ) {
159 if ( !isset( self::$groupMemberCounts[$group] ) ) {
160 global $wgMemc;
161 $key = wfMemcKey( 'SiteStats', 'groupcounts', $group );
162 $hit = $wgMemc->get( $key );
163 if ( !$hit ) {
164 $dbr = wfGetDB( DB_SLAVE );
165 $hit = $dbr->selectField(
166 'user_groups',
167 'COUNT(*)',
168 array( 'ug_group' => $group ),
169 __METHOD__
170 );
171 $wgMemc->set( $key, $hit, 3600 );
172 }
173 self::$groupMemberCounts[$group] = $hit;
174 }
175 return self::$groupMemberCounts[$group];
176 }
177
178 /**
179 * @return int
180 */
181 static function jobs() {
182 if ( !isset( self::$jobs ) ) {
183 $dbr = wfGetDB( DB_SLAVE );
184 self::$jobs = $dbr->estimateRowCount( 'job' );
185 /* Zero rows still do single row read for row that doesn't exist, but people are annoyed by that */
186 if ( self::$jobs == 1 ) {
187 self::$jobs = 0;
188 }
189 }
190 return self::$jobs;
191 }
192
193 /**
194 * @param $ns int
195 *
196 * @return int
197 */
198 static function pagesInNs( $ns ) {
199 wfProfileIn( __METHOD__ );
200 if( !isset( self::$pageCount[$ns] ) ) {
201 $dbr = wfGetDB( DB_SLAVE );
202 self::$pageCount[$ns] = (int)$dbr->selectField(
203 'page',
204 'COUNT(*)',
205 array( 'page_namespace' => $ns ),
206 __METHOD__
207 );
208 }
209 wfProfileOut( __METHOD__ );
210 return self::$pageCount[$ns];
211 }
212
213 /**
214 * Is the provided row of site stats sane, or should it be regenerated?
215 *
216 * @param $row
217 *
218 * @return bool
219 */
220 private static function isSane( $row ) {
221 if(
222 $row === false
223 || $row->ss_total_pages < $row->ss_good_articles
224 || $row->ss_total_edits < $row->ss_total_pages
225 ) {
226 return false;
227 }
228 // Now check for underflow/overflow
229 foreach( array( 'total_views', 'total_edits', 'good_articles',
230 'total_pages', 'users', 'images' ) as $member ) {
231 if(
232 $row->{"ss_$member"} > 2000000000
233 || $row->{"ss_$member"} < 0
234 ) {
235 return false;
236 }
237 }
238 return true;
239 }
240 }
241
242 /**
243 * Class for handling updates to the site_stats table
244 */
245 class SiteStatsUpdate implements DeferrableUpdate {
246 protected $views = 0;
247 protected $edits = 0;
248 protected $pages = 0;
249 protected $articles = 0;
250 protected $users = 0;
251 protected $images = 0;
252
253 // @TODO: deprecate this constructor
254 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
255 $this->views = $views;
256 $this->edits = $edits;
257 $this->articles = $good;
258 $this->pages = $pages;
259 $this->users = $users;
260 }
261
262 /**
263 * @param $deltas Array
264 * @return SiteStatsUpdate
265 */
266 public static function factory( array $deltas ) {
267 $update = new self( 0, 0, 0 );
268
269 $fields = array( 'views', 'edits', 'pages', 'articles', 'users', 'images' );
270 foreach ( $fields as $field ) {
271 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
272 $update->$field = $deltas[$field];
273 }
274 }
275
276 return $update;
277 }
278
279 public function doUpdate() {
280 global $wgSiteStatsAsyncFactor;
281
282 $rate = $wgSiteStatsAsyncFactor; // convenience
283 // If set to do so, only do actual DB updates 1 every $rate times.
284 // The other times, just update "pending delta" values in memcached.
285 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
286 $this->doUpdatePendingDeltas();
287 } else {
288 $dbw = wfGetDB( DB_MASTER );
289 // Need a separate transaction because this a global lock
290 $dbw->begin( __METHOD__ );
291
292 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
293 if ( $rate ) {
294 // Lock the table so we don't have double DB/memcached updates
295 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
296 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
297 ) {
298 $this->doUpdatePendingDeltas();
299 return;
300 }
301 $pd = $this->getPendingDeltas();
302 // Piggy-back the async deltas onto those of this stats update....
303 $this->views += ( $pd['ss_total_views']['+'] - $pd['ss_total_views']['-'] );
304 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
305 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
306 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
307 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
308 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
309 }
310
311 // Build up an SQL query of deltas and apply them...
312 $updates = '';
313 $this->appendUpdate( $updates, 'ss_total_views', $this->views );
314 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
315 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
316 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
317 $this->appendUpdate( $updates, 'ss_users', $this->users );
318 $this->appendUpdate( $updates, 'ss_images', $this->images );
319 if ( $updates != '' ) {
320 $dbw->update( 'site_stats', array( $updates ), array(), __METHOD__ );
321 }
322
323 if ( $rate ) {
324 // Decrement the async deltas now that we applied them
325 $this->removePendingDeltas( $pd );
326 // Commit the updates and unlock the table
327 $dbw->unlock( $lockKey, __METHOD__ );
328 }
329
330 $dbw->commit( __METHOD__ );
331 }
332 }
333
334 /**
335 * @param $dbw DatabaseBase
336 * @return bool|mixed
337 */
338 public static function cacheUpdate( $dbw ) {
339 global $wgActiveUserDays;
340 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
341 # Get non-bot users than did some recent action other than making accounts.
342 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
343 $activeUsers = $dbr->selectField(
344 'recentchanges',
345 'COUNT( DISTINCT rc_user_text )',
346 array(
347 'rc_user != 0',
348 'rc_bot' => 0,
349 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
350 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 ) ),
351 ),
352 __METHOD__
353 );
354 $dbw->update(
355 'site_stats',
356 array( 'ss_active_users' => intval( $activeUsers ) ),
357 array( 'ss_row_id' => 1 ),
358 __METHOD__
359 );
360 return $activeUsers;
361 }
362
363 protected function doUpdatePendingDeltas() {
364 $this->adjustPending( 'ss_total_views', $this->views );
365 $this->adjustPending( 'ss_total_edits', $this->edits );
366 $this->adjustPending( 'ss_good_articles', $this->articles );
367 $this->adjustPending( 'ss_total_pages', $this->pages );
368 $this->adjustPending( 'ss_users', $this->users );
369 $this->adjustPending( 'ss_images', $this->images );
370 }
371
372 /**
373 * @param $sql string
374 * @param $field string
375 * @param $delta integer
376 */
377 protected function appendUpdate( &$sql, $field, $delta ) {
378 if ( $delta ) {
379 if ( $sql ) {
380 $sql .= ',';
381 }
382 if ( $delta < 0 ) {
383 $sql .= "$field=$field-" . abs( $delta );
384 } else {
385 $sql .= "$field=$field+" . abs( $delta );
386 }
387 }
388 }
389
390 /**
391 * @param $type string
392 * @param $sign string ('+' or '-')
393 * @return string
394 */
395 private function getTypeCacheKey( $type, $sign ) {
396 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
397 }
398
399 /**
400 * Adjust the pending deltas for a stat type.
401 * Each stat type has two pending counters, one for increments and decrements
402 * @param $type string
403 * @param $delta integer Delta (positive or negative)
404 * @return void
405 */
406 protected function adjustPending( $type, $delta ) {
407 global $wgMemc;
408
409 if ( $delta < 0 ) { // decrement
410 $key = $this->getTypeCacheKey( $type, '-' );
411 } else { // increment
412 $key = $this->getTypeCacheKey( $type, '+' );
413 }
414
415 $magnitude = abs( $delta );
416 if ( !$wgMemc->incr( $key, $magnitude ) ) { // not there?
417 if ( !$wgMemc->add( $key, $magnitude ) ) { // race?
418 $wgMemc->incr( $key, $magnitude );
419 }
420 }
421 }
422
423 /**
424 * Get pending delta counters for each stat type
425 * @return Array Positive and negative deltas for each type
426 * @return void
427 */
428 protected function getPendingDeltas() {
429 global $wgMemc;
430
431 $pending = array();
432 foreach ( array( 'ss_total_views', 'ss_total_edits',
433 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ) as $type )
434 {
435 // Get pending increments and pending decrements
436 $pending[$type]['+'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '+' ) );
437 $pending[$type]['-'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '-' ) );
438 }
439
440 return $pending;
441 }
442
443 /**
444 * Reduce pending delta counters after updates have been applied
445 * @param Array $pd Result of getPendingDeltas(), used for DB update
446 * @return void
447 */
448 protected function removePendingDeltas( array $pd ) {
449 global $wgMemc;
450
451 foreach ( $pd as $type => $deltas ) {
452 foreach ( $deltas as $sign => $magnitude ) {
453 // Lower the pending counter now that we applied these changes
454 $wgMemc->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
455 }
456 }
457 }
458 }
459
460 /**
461 * Class designed for counting of stats.
462 */
463 class SiteStatsInit {
464
465 // Database connection
466 private $db;
467
468 // Various stats
469 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
470
471 /**
472 * Constructor
473 * @param $database Boolean or DatabaseBase:
474 * - Boolean: whether to use the master DB
475 * - DatabaseBase: database connection to use
476 */
477 public function __construct( $database = false ) {
478 if ( $database instanceof DatabaseBase ) {
479 $this->db = $database;
480 } else {
481 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
482 }
483 }
484
485 /**
486 * Count the total number of edits
487 * @return Integer
488 */
489 public function edits() {
490 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
491 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
492 return $this->mEdits;
493 }
494
495 /**
496 * Count pages in article space(s)
497 * @return Integer
498 */
499 public function articles() {
500 global $wgArticleCountMethod;
501
502 $tables = array( 'page' );
503 $conds = array(
504 'page_namespace' => MWNamespace::getContentNamespaces(),
505 'page_is_redirect' => 0,
506 );
507
508 if ( $wgArticleCountMethod == 'link' ) {
509 $tables[] = 'pagelinks';
510 $conds[] = 'pl_from=page_id';
511 } elseif ( $wgArticleCountMethod == 'comma' ) {
512 // To make a correct check for this, we would need, for each page,
513 // to load the text, maybe uncompress it, maybe decode it and then
514 // check if there's one comma.
515 // But one thing we are sure is that if the page is empty, it can't
516 // contain a comma :)
517 $conds[] = 'page_len > 0';
518 }
519
520 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
521 $conds, __METHOD__ );
522 return $this->mArticles;
523 }
524
525 /**
526 * Count total pages
527 * @return Integer
528 */
529 public function pages() {
530 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
531 return $this->mPages;
532 }
533
534 /**
535 * Count total users
536 * @return Integer
537 */
538 public function users() {
539 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
540 return $this->mUsers;
541 }
542
543 /**
544 * Count views
545 * @return Integer
546 */
547 public function views() {
548 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
549 return $this->mViews;
550 }
551
552 /**
553 * Count total files
554 * @return Integer
555 */
556 public function files() {
557 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
558 return $this->mFiles;
559 }
560
561 /**
562 * Do all updates and commit them. More or less a replacement
563 * for the original initStats, but without output.
564 *
565 * @param $database DatabaseBase|bool
566 * - Boolean: whether to use the master DB
567 * - DatabaseBase: database connection to use
568 * @param $options Array of options, may contain the following values
569 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
570 * - views Boolean: when true, do not update the number of page views (default: true)
571 * - activeUsers Boolean: whether to update the number of active users (default: false)
572 */
573 public static function doAllAndCommit( $database, array $options = array() ) {
574 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
575
576 // Grab the object and count everything
577 $counter = new SiteStatsInit( $database );
578
579 $counter->edits();
580 $counter->articles();
581 $counter->pages();
582 $counter->users();
583 $counter->files();
584
585 // Only do views if we don't want to not count them
586 if( $options['views'] ) {
587 $counter->views();
588 }
589
590 // Update/refresh
591 if( $options['update'] ) {
592 $counter->update();
593 } else {
594 $counter->refresh();
595 }
596
597 // Count active users if need be
598 if( $options['activeUsers'] ) {
599 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
600 }
601 }
602
603 /**
604 * Update the current row with the selected values
605 */
606 public function update() {
607 list( $values, $conds ) = $this->getDbParams();
608 $dbw = wfGetDB( DB_MASTER );
609 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
610 }
611
612 /**
613 * Refresh site_stats. Erase the current record and save all
614 * the new values.
615 */
616 public function refresh() {
617 list( $values, $conds, $views ) = $this->getDbParams();
618 $dbw = wfGetDB( DB_MASTER );
619 $dbw->delete( 'site_stats', $conds, __METHOD__ );
620 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
621 }
622
623 /**
624 * Return three arrays of params for the db queries
625 * @return Array
626 */
627 private function getDbParams() {
628 $values = array(
629 'ss_total_edits' => $this->mEdits,
630 'ss_good_articles' => $this->mArticles,
631 'ss_total_pages' => $this->mPages,
632 'ss_users' => $this->mUsers,
633 'ss_images' => $this->mFiles
634 );
635 $conds = array( 'ss_row_id' => 1 );
636 $views = array( 'ss_total_views' => $this->mViews );
637 return array( $values, $conds, $views );
638 }
639 }