Merge "Remove 'jquery.ui.button' as dependency for mediawiki.action.history"
[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 $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', '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 protected $views = 0;
227 protected $edits = 0;
228 protected $pages = 0;
229 protected $goodPages = 0;
230 protected $users = 0;
231 protected $images = 0;
232
233 // @TODO: deprecate this
234 function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
235 $this->views = $views;
236 $this->edits = $edits;
237 $this->goodPages = $good;
238 $this->pages = $pages;
239 $this->users = $users;
240 }
241
242 /**
243 * @param $deltas Array
244 * @return SiteStatsUpdate
245 */
246 public static function factory( array $deltas ) {
247 $update = new self( 0, 0, 0 );
248
249 $fields = array( 'views', 'edits', 'pages', 'goodPages', 'users', 'images' );
250 foreach ( $fields as $field ) {
251 if ( isset( $deltas[$field] ) && $deltas[$field] ) {
252 $update->$field = $deltas[$field];
253 }
254 }
255
256 return $update;
257 }
258
259 /**
260 * @param $sql
261 * @param $field
262 * @param $delta
263 */
264 function appendUpdate( &$sql, $field, $delta ) {
265 if ( $delta ) {
266 if ( $sql ) {
267 $sql .= ',';
268 }
269 if ( $delta < 0 ) {
270 $sql .= "$field=$field-1";
271 } else {
272 $sql .= "$field=$field+1";
273 }
274 }
275 }
276
277 public function doUpdate() {
278 $dbw = wfGetDB( DB_MASTER );
279
280 $updates = '';
281
282 $this->appendUpdate( $updates, 'ss_total_views', $this->views );
283 $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
284 $this->appendUpdate( $updates, 'ss_good_articles', $this->goodPages );
285 $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
286 $this->appendUpdate( $updates, 'ss_users', $this->users );
287 $this->appendUpdate( $updates, 'ss_images', $this->images );
288
289 if ( $updates ) {
290 $site_stats = $dbw->tableName( 'site_stats' );
291 $sql = "UPDATE $site_stats SET $updates";
292
293 # Need a separate transaction because this a global lock
294 $dbw->begin( __METHOD__ );
295 $dbw->query( $sql, __METHOD__ );
296 $dbw->commit( __METHOD__ );
297 }
298 }
299
300 /**
301 * @param $dbw DatabaseBase
302 * @return bool|mixed
303 */
304 public static function cacheUpdate( $dbw ) {
305 global $wgActiveUserDays;
306 $dbr = wfGetDB( DB_SLAVE, array( 'SpecialStatistics', 'vslow' ) );
307 # Get non-bot users than did some recent action other than making accounts.
308 # If account creation is included, the number gets inflated ~20+ fold on enwiki.
309 $activeUsers = $dbr->selectField(
310 'recentchanges',
311 'COUNT( DISTINCT rc_user_text )',
312 array(
313 'rc_user != 0',
314 'rc_bot' => 0,
315 "rc_log_type != 'newusers' OR rc_log_type IS NULL",
316 "rc_timestamp >= '{$dbw->timestamp( wfTimestamp( TS_UNIX ) - $wgActiveUserDays*24*3600 )}'",
317 ),
318 __METHOD__
319 );
320 $dbw->update(
321 'site_stats',
322 array( 'ss_active_users' => intval( $activeUsers ) ),
323 array( 'ss_row_id' => 1 ),
324 __METHOD__
325 );
326 return $activeUsers;
327 }
328 }
329
330 /**
331 * Class designed for counting of stats.
332 */
333 class SiteStatsInit {
334
335 // Database connection
336 private $db;
337
338 // Various stats
339 private $mEdits, $mArticles, $mPages, $mUsers, $mViews, $mFiles = 0;
340
341 /**
342 * Constructor
343 * @param $database Boolean or DatabaseBase:
344 * - Boolean: whether to use the master DB
345 * - DatabaseBase: database connection to use
346 */
347 public function __construct( $database = false ) {
348 if ( $database instanceof DatabaseBase ) {
349 $this->db = $database;
350 } else {
351 $this->db = wfGetDB( $database ? DB_MASTER : DB_SLAVE );
352 }
353 }
354
355 /**
356 * Count the total number of edits
357 * @return Integer
358 */
359 public function edits() {
360 $this->mEdits = $this->db->selectField( 'revision', 'COUNT(*)', '', __METHOD__ );
361 $this->mEdits += $this->db->selectField( 'archive', 'COUNT(*)', '', __METHOD__ );
362 return $this->mEdits;
363 }
364
365 /**
366 * Count pages in article space(s)
367 * @return Integer
368 */
369 public function articles() {
370 global $wgArticleCountMethod;
371
372 $tables = array( 'page' );
373 $conds = array(
374 'page_namespace' => MWNamespace::getContentNamespaces(),
375 'page_is_redirect' => 0,
376 );
377
378 if ( $wgArticleCountMethod == 'link' ) {
379 $tables[] = 'pagelinks';
380 $conds[] = 'pl_from=page_id';
381 } elseif ( $wgArticleCountMethod == 'comma' ) {
382 // To make a correct check for this, we would need, for each page,
383 // to load the text, maybe uncompress it, maybe decode it and then
384 // check if there's one comma.
385 // But one thing we are sure is that if the page is empty, it can't
386 // contain a comma :)
387 $conds[] = 'page_len > 0';
388 }
389
390 $this->mArticles = $this->db->selectField( $tables, 'COUNT(DISTINCT page_id)',
391 $conds, __METHOD__ );
392 return $this->mArticles;
393 }
394
395 /**
396 * Count total pages
397 * @return Integer
398 */
399 public function pages() {
400 $this->mPages = $this->db->selectField( 'page', 'COUNT(*)', '', __METHOD__ );
401 return $this->mPages;
402 }
403
404 /**
405 * Count total users
406 * @return Integer
407 */
408 public function users() {
409 $this->mUsers = $this->db->selectField( 'user', 'COUNT(*)', '', __METHOD__ );
410 return $this->mUsers;
411 }
412
413 /**
414 * Count views
415 * @return Integer
416 */
417 public function views() {
418 $this->mViews = $this->db->selectField( 'page', 'SUM(page_counter)', '', __METHOD__ );
419 return $this->mViews;
420 }
421
422 /**
423 * Count total files
424 * @return Integer
425 */
426 public function files() {
427 $this->mFiles = $this->db->selectField( 'image', 'COUNT(*)', '', __METHOD__ );
428 return $this->mFiles;
429 }
430
431 /**
432 * Do all updates and commit them. More or less a replacement
433 * for the original initStats, but without output.
434 *
435 * @param $database DatabaseBase|bool
436 * - Boolean: whether to use the master DB
437 * - DatabaseBase: database connection to use
438 * @param $options Array of options, may contain the following values
439 * - update Boolean: whether to update the current stats (true) or write fresh (false) (default: false)
440 * - views Boolean: when true, do not update the number of page views (default: true)
441 * - activeUsers Boolean: whether to update the number of active users (default: false)
442 */
443 public static function doAllAndCommit( $database, array $options = array() ) {
444 $options += array( 'update' => false, 'views' => true, 'activeUsers' => false );
445
446 // Grab the object and count everything
447 $counter = new SiteStatsInit( $database );
448
449 $counter->edits();
450 $counter->articles();
451 $counter->pages();
452 $counter->users();
453 $counter->files();
454
455 // Only do views if we don't want to not count them
456 if( $options['views'] ) {
457 $counter->views();
458 }
459
460 // Update/refresh
461 if( $options['update'] ) {
462 $counter->update();
463 } else {
464 $counter->refresh();
465 }
466
467 // Count active users if need be
468 if( $options['activeUsers'] ) {
469 SiteStatsUpdate::cacheUpdate( wfGetDB( DB_MASTER ) );
470 }
471 }
472
473 /**
474 * Update the current row with the selected values
475 */
476 public function update() {
477 list( $values, $conds ) = $this->getDbParams();
478 $dbw = wfGetDB( DB_MASTER );
479 $dbw->update( 'site_stats', $values, $conds, __METHOD__ );
480 }
481
482 /**
483 * Refresh site_stats. Erase the current record and save all
484 * the new values.
485 */
486 public function refresh() {
487 list( $values, $conds, $views ) = $this->getDbParams();
488 $dbw = wfGetDB( DB_MASTER );
489 $dbw->delete( 'site_stats', $conds, __METHOD__ );
490 $dbw->insert( 'site_stats', array_merge( $values, $conds, $views ), __METHOD__ );
491 }
492
493 /**
494 * Return three arrays of params for the db queries
495 * @return Array
496 */
497 private function getDbParams() {
498 $values = array(
499 'ss_total_edits' => $this->mEdits,
500 'ss_good_articles' => $this->mArticles,
501 'ss_total_pages' => $this->mPages,
502 'ss_users' => $this->mUsers,
503 'ss_images' => $this->mFiles
504 );
505 $conds = array( 'ss_row_id' => 1 );
506 $views = array( 'ss_total_views' => $this->mViews );
507 return array( $values, $conds, $views );
508 }
509 }