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