Merge "Less wild whitespace"
[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 $group String: 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 = $dbr->estimateRowCount( 'job' );
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(
230 $row === false
231 || $row->ss_total_pages < $row->ss_good_articles
232 || $row->ss_total_edits < $row->ss_total_pages
233 ) {
234 return false;
235 }
236 // Now check for underflow/overflow
237 foreach( array( 'total_views', 'total_edits', 'good_articles',
238 'total_pages', 'users', 'images' ) as $member ) {
239 if(
240 $row->{"ss_$member"} > 2000000000
241 || $row->{"ss_$member"} < 0
242 ) {
243 return false;
244 }
245 }
246 return true;
247 }
248 }
249
250 /**
251 * Class for handling updates to the site_stats table
252 */
253 class SiteStatsUpdate implements DeferrableUpdate {
254 protected $views = 0;
255 protected $edits = 0;
256 protected $pages = 0;
257 protected $articles = 0;
258 protected $users = 0;
259 protected $images = 0;
260
261 // @TODO: deprecate this constructor
262 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
263 $this->views = $views;
264 $this->edits = $edits;
265 $this->articles = $good;
266 $this->pages = $pages;
267 $this->users = $users;
268 }
269
270 /**
271 * @param $deltas Array
272 * @return SiteStatsUpdate
273 */
274 public static function factory( array $deltas ) {
275 $update = new self( 0, 0, 0 );
276
277 $fields = array( 'views', 'edits', 'pages', 'articles', 'users', 'images' );
278 foreach ( $fields as $field ) {
279 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
280 $update->$field = $deltas[$field];
281 }
282 }
283
284 return $update;
285 }
286
287 public function doUpdate() {
288 global $wgSiteStatsAsyncFactor;
289
290 $rate = $wgSiteStatsAsyncFactor; // convenience
291 // If set to do so, only do actual DB updates 1 every $rate times.
292 // The other times, just update "pending delta" values in memcached.
293 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
294 $this->doUpdatePendingDeltas();
295 } else {
296 $dbw = wfGetDB( DB_MASTER );
297 // Need a separate transaction because this a global lock
298 $dbw->begin( __METHOD__ );
299
300 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
301 if ( $rate ) {
302 // Lock the table so we don't have double DB/memcached updates
303 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
304 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
305 ) {
306 $this->doUpdatePendingDeltas();
307 return;
308 }
309 $pd = $this->getPendingDeltas();
310 // Piggy-back the async deltas onto those of this stats update....
311 $this->views += ( $pd['ss_total_views']['+'] - $pd['ss_total_views']['-'] );
312 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
313 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
314 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
315 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
316 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
317 }
318
319 // Build up an SQL query of deltas and apply them...
320 $updates = '';
321 $this->appendUpdate( $updates, 'ss_total_views', $this->views );
322 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
323 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
324 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
325 $this->appendUpdate( $updates, 'ss_users', $this->users );
326 $this->appendUpdate( $updates, 'ss_images', $this->images );
327 if ( $updates != '' ) {
328 $dbw->update( 'site_stats', array( $updates ), array(), __METHOD__ );
329 }
330
331 if ( $rate ) {
332 // Decrement the async deltas now that we applied them
333 $this->removePendingDeltas( $pd );
334 // Commit the updates and unlock the table
335 $dbw->unlock( $lockKey, __METHOD__ );
336 }
337
338 $dbw->commit( __METHOD__ );
339 }
340 }
341
342 /**
343 * @param $dbw DatabaseBase
344 * @return bool|mixed
345 */
346 public static function cacheUpdate( $dbw ) {
347 global $wgActiveUserDays;
348 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
349 # Get non-bot users than did some recent action other than making accounts.
350 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
351 $activeUsers = $dbr->selectField(
352 'recentchanges',
353 'COUNT( DISTINCT rc_user_text )',
354 array(
355 'rc_user != 0',
356 'rc_bot' => 0,
357 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
358 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 ) ),
359 ),
360 __METHOD__
361 );
362 $dbw->update(
363 'site_stats',
364 array( 'ss_active_users' => intval( $activeUsers ) ),
365 array( 'ss_row_id' => 1 ),
366 __METHOD__
367 );
368 return $activeUsers;
369 }
370
371 protected function doUpdatePendingDeltas() {
372 $this->adjustPending( 'ss_total_views', $this->views );
373 $this->adjustPending( 'ss_total_edits', $this->edits );
374 $this->adjustPending( 'ss_good_articles', $this->articles );
375 $this->adjustPending( 'ss_total_pages', $this->pages );
376 $this->adjustPending( 'ss_users', $this->users );
377 $this->adjustPending( 'ss_images', $this->images );
378 }
379
380 /**
381 * @param $sql string
382 * @param $field string
383 * @param $delta integer
384 */
385 protected function appendUpdate( &$sql, $field, $delta ) {
386 if ( $delta ) {
387 if ( $sql ) {
388 $sql .= ',';
389 }
390 if ( $delta < 0 ) {
391 $sql .= "$field=$field-" . abs( $delta );
392 } else {
393 $sql .= "$field=$field+" . abs( $delta );
394 }
395 }
396 }
397
398 /**
399 * @param $type string
400 * @param $sign string ('+' or '-')
401 * @return string
402 */
403 private function getTypeCacheKey( $type, $sign ) {
404 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
405 }
406
407 /**
408 * Adjust the pending deltas for a stat type.
409 * Each stat type has two pending counters, one for increments and decrements
410 * @param $type string
411 * @param $delta integer Delta (positive or negative)
412 * @return void
413 */
414 protected function adjustPending( $type, $delta ) {
415 global $wgMemc;
416
417 if ( $delta < 0 ) { // decrement
418 $key = $this->getTypeCacheKey( $type, '-' );
419 } else { // increment
420 $key = $this->getTypeCacheKey( $type, '+' );
421 }
422
423 $magnitude = abs( $delta );
424 if ( !$wgMemc->incr( $key, $magnitude ) ) { // not there?
425 if ( !$wgMemc->add( $key, $magnitude ) ) { // race?
426 $wgMemc->incr( $key, $magnitude );
427 }
428 }
429 }
430
431 /**
432 * Get pending delta counters for each stat type
433 * @return Array Positive and negative deltas for each type
434 * @return void
435 */
436 protected function getPendingDeltas() {
437 global $wgMemc;
438
439 $pending = array();
440 foreach ( array( 'ss_total_views', 'ss_total_edits',
441 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ) as $type )
442 {
443 // Get pending increments and pending decrements
444 $pending[$type]['+'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '+' ) );
445 $pending[$type]['-'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '-' ) );
446 }
447
448 return $pending;
449 }
450
451 /**
452 * Reduce pending delta counters after updates have been applied
453 * @param Array $pd Result of getPendingDeltas(), used for DB update
454 * @return void
455 */
456 protected function removePendingDeltas( array $pd ) {
457 global $wgMemc;
458
459 foreach ( $pd as $type => $deltas ) {
460 foreach ( $deltas as $sign => $magnitude ) {
461 // Lower the pending counter now that we applied these changes
462 $wgMemc->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
463 }
464 }
465 }
466 }
467
468 /**
469 * Class designed for counting of stats.
470 */
471 class SiteStatsInit {
472
473 // Database connection
474 private $db;
475
476 // Various stats
477 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
478
479 /**
480 * Constructor
481 * @param $database Boolean or DatabaseBase:
482 * - Boolean: whether to use the master DB
483 * - DatabaseBase: database connection to use
484 */
485 public function __construct( $database = false ) {
486 if ( $database instanceof DatabaseBase ) {
487 $this->db = $database;
488 } else {
489 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
490 }
491 }
492
493 /**
494 * Count the total number of edits
495 * @return Integer
496 */
497 public function edits() {
498 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
499 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
500 return $this->mEdits;
501 }
502
503 /**
504 * Count pages in article space(s)
505 * @return Integer
506 */
507 public function articles() {
508 global $wgArticleCountMethod;
509
510 $tables = array( 'page' );
511 $conds = array(
512 'page_namespace' => MWNamespace::getContentNamespaces(),
513 'page_is_redirect' => 0,
514 );
515
516 if ( $wgArticleCountMethod == 'link' ) {
517 $tables[] = 'pagelinks';
518 $conds[] = 'pl_from=page_id';
519 } elseif ( $wgArticleCountMethod == 'comma' ) {
520 // To make a correct check for this, we would need, for each page,
521 // to load the text, maybe uncompress it, maybe decode it and then
522 // check if there's one comma.
523 // But one thing we are sure is that if the page is empty, it can't
524 // contain a comma :)
525 $conds[] = 'page_len > 0';
526 }
527
528 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
529 $conds, __METHOD__ );
530 return $this->mArticles;
531 }
532
533 /**
534 * Count total pages
535 * @return Integer
536 */
537 public function pages() {
538 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
539 return $this->mPages;
540 }
541
542 /**
543 * Count total users
544 * @return Integer
545 */
546 public function users() {
547 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
548 return $this->mUsers;
549 }
550
551 /**
552 * Count views
553 * @return Integer
554 */
555 public function views() {
556 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
557 return $this->mViews;
558 }
559
560 /**
561 * Count total files
562 * @return Integer
563 */
564 public function files() {
565 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
566 return $this->mFiles;
567 }
568
569 /**
570 * Do all updates and commit them. More or less a replacement
571 * for the original initStats, but without output.
572 *
573 * @param $database DatabaseBase|bool
574 * - Boolean: whether to use the master DB
575 * - DatabaseBase: database connection to use
576 * @param $options Array of options, may contain the following values
577 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
578 * - views Boolean: when true, do not update the number of page views (default: true)
579 * - activeUsers Boolean: whether to update the number of active users (default: false)
580 */
581 public static function doAllAndCommit( $database, array $options = array() ) {
582 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
583
584 // Grab the object and count everything
585 $counter = new SiteStatsInit( $database );
586
587 $counter->edits();
588 $counter->articles();
589 $counter->pages();
590 $counter->users();
591 $counter->files();
592
593 // Only do views if we don't want to not count them
594 if( $options['views'] ) {
595 $counter->views();
596 }
597
598 // Update/refresh
599 if( $options['update'] ) {
600 $counter->update();
601 } else {
602 $counter->refresh();
603 }
604
605 // Count active users if need be
606 if( $options['activeUsers'] ) {
607 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
608 }
609 }
610
611 /**
612 * Update the current row with the selected values
613 */
614 public function update() {
615 list( $values, $conds ) = $this->getDbParams();
616 $dbw = wfGetDB( DB_MASTER );
617 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
618 }
619
620 /**
621 * Refresh site_stats. Erase the current record and save all
622 * the new values.
623 */
624 public function refresh() {
625 list( $values, $conds, $views ) = $this->getDbParams();
626 $dbw = wfGetDB( DB_MASTER );
627 $dbw->delete( 'site_stats', $conds, __METHOD__ );
628 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
629 }
630
631 /**
632 * Return three arrays of params for the db queries
633 * @return Array
634 */
635 private function getDbParams() {
636 $values = array(
637 'ss_total_edits' => $this->mEdits,
638 'ss_good_articles' => $this->mArticles,
639 'ss_total_pages' => $this->mPages,
640 'ss_users' => $this->mUsers,
641 'ss_images' => $this->mFiles
642 );
643 $conds = array( 'ss_row_id' => 1 );
644 $views = array( 'ss_total_views' => $this->mViews );
645 return array( $values, $conds, $views );
646 }
647 }