Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / SiteStats.php
blob199c64fa9b8dce096045d092eb359ceee0badcf4
1 <?php
2 /**
3 * Accessors and mutators for the site-wide statistics.
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.
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.
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
20 * @file
23 /**
24 * Static accessor class for site_stats and related things
26 class SiteStats {
27 static $row, $loaded = false;
28 static $jobs;
29 static $pageCount = array();
30 static $groupMemberCounts = array();
32 static function recache() {
33 self::load( true );
36 /**
37 * @param $recache bool
39 static function load( $recache = false ) {
40 if ( self::$loaded && !$recache ) {
41 return;
44 self::$row = self::loadAndLazyInit();
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 ) );
54 self::$loaded = true;
57 /**
58 * @return Bool|ResultWrapper
60 static function loadAndLazyInit() {
61 wfDebug( __METHOD__ . ": reading site_stats from slave\n" );
62 $row = self::doLoad( wfGetDB( DB_SLAVE ) );
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 ) );
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" );
77 SiteStatsInit::doAllAndCommit( wfGetDB( DB_SLAVE ) );
79 $row = self::doLoad( wfGetDB( DB_MASTER ) );
82 if ( !self::isSane( $row ) ) {
83 wfDebug( __METHOD__ . ": site_stats persistently nonsensical o_O\n" );
85 return $row;
88 /**
89 * @param $db DatabaseBase
90 * @return Bool|ResultWrapper
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__ );
106 * @return int
108 static function views() {
109 self::load();
110 return self::$row->ss_total_views;
114 * @return int
116 static function edits() {
117 self::load();
118 return self::$row->ss_total_edits;
122 * @return int
124 static function articles() {
125 self::load();
126 return self::$row->ss_good_articles;
130 * @return int
132 static function pages() {
133 self::load();
134 return self::$row->ss_total_pages;
138 * @return int
140 static function users() {
141 self::load();
142 return self::$row->ss_users;
146 * @return int
148 static function activeUsers() {
149 self::load();
150 return self::$row->ss_active_users;
154 * @return int
156 static function images() {
157 self::load();
158 return self::$row->ss_images;
162 * Find the number of users in a given user group.
163 * @param string $group name of group
164 * @return Integer
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__
179 $wgMemc->set( $key, $hit, 3600 );
181 self::$groupMemberCounts[$group] = $hit;
183 return self::$groupMemberCounts[$group];
187 * @return int
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;
198 return self::$jobs;
202 * @param $ns int
204 * @return int
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__
217 wfProfileOut( __METHOD__ );
218 return self::$pageCount[$ns];
222 * Is the provided row of site stats sane, or should it be regenerated?
224 * @param $row
226 * @return bool
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
234 return false;
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_active_users',
244 'ss_images',
245 ) as $member ) {
246 if ( $row->$member > 2000000000 || $row->$member < 0 ) {
247 return false;
250 return true;
255 * Class for handling updates to the site_stats table
257 class SiteStatsUpdate implements DeferrableUpdate {
258 protected $views = 0;
259 protected $edits = 0;
260 protected $pages = 0;
261 protected $articles = 0;
262 protected $users = 0;
263 protected $images = 0;
265 // @todo deprecate this constructor
266 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
267 $this->views = $views;
268 $this->edits = $edits;
269 $this->articles = $good;
270 $this->pages = $pages;
271 $this->users = $users;
275 * @param $deltas Array
276 * @return SiteStatsUpdate
278 public static function factory( array $deltas ) {
279 $update = new self( 0, 0, 0 );
281 $fields = array( 'views', 'edits', 'pages', 'articles', 'users', 'images' );
282 foreach ( $fields as $field ) {
283 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
284 $update->$field = $deltas[$field];
288 return $update;
291 public function doUpdate() {
292 global $wgSiteStatsAsyncFactor;
294 $rate = $wgSiteStatsAsyncFactor; // convenience
295 // If set to do so, only do actual DB updates 1 every $rate times.
296 // The other times, just update "pending delta" values in memcached.
297 if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
298 $this->doUpdatePendingDeltas();
299 } else {
300 $dbw = wfGetDB( DB_MASTER );
302 $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
303 if ( $rate ) {
304 // Lock the table so we don't have double DB/memcached updates
305 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
306 || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
308 $this->doUpdatePendingDeltas();
309 return;
311 $pd = $this->getPendingDeltas();
312 // Piggy-back the async deltas onto those of this stats update....
313 $this->views += ( $pd['ss_total_views']['+'] - $pd['ss_total_views']['-'] );
314 $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
315 $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
316 $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
317 $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
318 $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
321 // Need a separate transaction because this a global lock
322 $dbw->begin( __METHOD__ );
324 // Build up an SQL query of deltas and apply them...
325 $updates = '';
326 $this->appendUpdate( $updates, 'ss_total_views', $this->views );
327 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
328 $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
329 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
330 $this->appendUpdate( $updates, 'ss_users', $this->users );
331 $this->appendUpdate( $updates, 'ss_images', $this->images );
332 if ( $updates != '' ) {
333 $dbw->update( 'site_stats', array( $updates ), array(), __METHOD__ );
336 if ( $rate ) {
337 // Decrement the async deltas now that we applied them
338 $this->removePendingDeltas( $pd );
339 // Commit the updates and unlock the table
340 $dbw->unlock( $lockKey, __METHOD__ );
343 $dbw->commit( __METHOD__ );
348 * @param $dbw DatabaseBase
349 * @return bool|mixed
351 public static function cacheUpdate( $dbw ) {
352 global $wgActiveUserDays;
353 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
354 # Get non-bot users than did some recent action other than making accounts.
355 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
356 $activeUsers = $dbr->selectField(
357 'recentchanges',
358 'COUNT( DISTINCT rc_user_text )',
359 array(
360 'rc_user != 0',
361 'rc_bot' => 0,
362 'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
363 'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays * 24 * 3600 ) ),
365 __METHOD__
367 $dbw->update(
368 'site_stats',
369 array( 'ss_active_users' => intval( $activeUsers ) ),
370 array( 'ss_row_id' => 1 ),
371 __METHOD__
373 return $activeUsers;
376 protected function doUpdatePendingDeltas() {
377 $this->adjustPending( 'ss_total_views', $this->views );
378 $this->adjustPending( 'ss_total_edits', $this->edits );
379 $this->adjustPending( 'ss_good_articles', $this->articles );
380 $this->adjustPending( 'ss_total_pages', $this->pages );
381 $this->adjustPending( 'ss_users', $this->users );
382 $this->adjustPending( 'ss_images', $this->images );
386 * @param $sql string
387 * @param $field string
388 * @param $delta integer
390 protected function appendUpdate( &$sql, $field, $delta ) {
391 if ( $delta ) {
392 if ( $sql ) {
393 $sql .= ',';
395 if ( $delta < 0 ) {
396 $sql .= "$field=$field-" . abs( $delta );
397 } else {
398 $sql .= "$field=$field+" . abs( $delta );
404 * @param $type string
405 * @param string $sign ('+' or '-')
406 * @return string
408 private function getTypeCacheKey( $type, $sign ) {
409 return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
413 * Adjust the pending deltas for a stat type.
414 * Each stat type has two pending counters, one for increments and decrements
415 * @param $type string
416 * @param $delta integer Delta (positive or negative)
417 * @return void
419 protected function adjustPending( $type, $delta ) {
420 global $wgMemc;
422 if ( $delta < 0 ) { // decrement
423 $key = $this->getTypeCacheKey( $type, '-' );
424 } else { // increment
425 $key = $this->getTypeCacheKey( $type, '+' );
428 $magnitude = abs( $delta );
429 if ( !$wgMemc->incr( $key, $magnitude ) ) { // not there?
430 if ( !$wgMemc->add( $key, $magnitude ) ) { // race?
431 $wgMemc->incr( $key, $magnitude );
437 * Get pending delta counters for each stat type
438 * @return Array Positive and negative deltas for each type
439 * @return void
441 protected function getPendingDeltas() {
442 global $wgMemc;
444 $pending = array();
445 foreach ( array( 'ss_total_views', 'ss_total_edits',
446 'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ) as $type )
448 // Get pending increments and pending decrements
449 $pending[$type]['+'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '+' ) );
450 $pending[$type]['-'] = (int)$wgMemc->get( $this->getTypeCacheKey( $type, '-' ) );
453 return $pending;
457 * Reduce pending delta counters after updates have been applied
458 * @param array $pd Result of getPendingDeltas(), used for DB update
459 * @return void
461 protected function removePendingDeltas( array $pd ) {
462 global $wgMemc;
464 foreach ( $pd as $type => $deltas ) {
465 foreach ( $deltas as $sign => $magnitude ) {
466 // Lower the pending counter now that we applied these changes
467 $wgMemc->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
474 * Class designed for counting of stats.
476 class SiteStatsInit {
478 // Database connection
479 private $db;
481 // Various stats
482 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
485 * Constructor
486 * @param $database Boolean or DatabaseBase:
487 * - Boolean: whether to use the master DB
488 * - DatabaseBase: database connection to use
490 public function __construct( $database = false ) {
491 if ( $database instanceof DatabaseBase ) {
492 $this->db = $database;
493 } else {
494 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
499 * Count the total number of edits
500 * @return Integer
502 public function edits() {
503 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
504 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
505 return $this->mEdits;
509 * Count pages in article space(s)
510 * @return Integer
512 public function articles() {
513 global $wgArticleCountMethod;
515 $tables = array( 'page' );
516 $conds = array(
517 'page_namespace' => MWNamespace::getContentNamespaces(),
518 'page_is_redirect' => 0,
521 if ( $wgArticleCountMethod == 'link' ) {
522 $tables[] = 'pagelinks';
523 $conds[] = 'pl_from=page_id';
524 } elseif ( $wgArticleCountMethod == 'comma' ) {
525 // To make a correct check for this, we would need, for each page,
526 // to load the text, maybe uncompress it, maybe decode it and then
527 // check if there's one comma.
528 // But one thing we are sure is that if the page is empty, it can't
529 // contain a comma :)
530 $conds[] = 'page_len > 0';
533 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
534 $conds, __METHOD__ );
535 return $this->mArticles;
539 * Count total pages
540 * @return Integer
542 public function pages() {
543 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
544 return $this->mPages;
548 * Count total users
549 * @return Integer
551 public function users() {
552 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
553 return $this->mUsers;
557 * Count views
558 * @return Integer
560 public function views() {
561 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
562 return $this->mViews;
566 * Count total files
567 * @return Integer
569 public function files() {
570 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
571 return $this->mFiles;
575 * Do all updates and commit them. More or less a replacement
576 * for the original initStats, but without output.
578 * @param $database DatabaseBase|bool
579 * - Boolean: whether to use the master DB
580 * - DatabaseBase: database connection to use
581 * @param array $options of options, may contain the following values
582 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
583 * - views Boolean: when true, do not update the number of page views (default: true)
584 * - activeUsers Boolean: whether to update the number of active users (default: false)
586 public static function doAllAndCommit( $database, array $options = array() ) {
587 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
589 // Grab the object and count everything
590 $counter = new SiteStatsInit( $database );
592 $counter->edits();
593 $counter->articles();
594 $counter->pages();
595 $counter->users();
596 $counter->files();
598 // Only do views if we don't want to not count them
599 if ( $options['views'] ) {
600 $counter->views();
603 // Update/refresh
604 if ( $options['update'] ) {
605 $counter->update();
606 } else {
607 $counter->refresh();
610 // Count active users if need be
611 if ( $options['activeUsers'] ) {
612 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
617 * Update the current row with the selected values
619 public function update() {
620 list( $values, $conds ) = $this->getDbParams();
621 $dbw = wfGetDB( DB_MASTER );
622 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
626 * Refresh site_stats. Erase the current record and save all
627 * the new values.
629 public function refresh() {
630 list( $values, $conds, $views ) = $this->getDbParams();
631 $dbw = wfGetDB( DB_MASTER );
632 $dbw->delete( 'site_stats', $conds, __METHOD__ );
633 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
637 * Return three arrays of params for the db queries
638 * @return Array
640 private function getDbParams() {
641 $values = array(
642 'ss_total_edits' => $this->mEdits,
643 'ss_good_articles' => $this->mArticles,
644 'ss_total_pages' => $this->mPages,
645 'ss_users' => $this->mUsers,
646 'ss_images' => $this->mFiles
648 $conds = array( 'ss_row_id' => 1 );
649 $views = array( 'ss_total_views' => $this->mViews );
650 return array( $values, $conds, $views );