MediaWiki  1.27.2
SiteStatsUpdate.php
Go to the documentation of this file.
1 <?php
26  protected $edits = 0;
27 
29  protected $pages = 0;
30 
32  protected $articles = 0;
33 
35  protected $users = 0;
36 
38  protected $images = 0;
39 
40  // @todo deprecate this constructor
41  function __construct( $views, $edits, $good, $pages = 0, $users = 0 ) {
42  $this->edits = $edits;
43  $this->articles = $good;
44  $this->pages = $pages;
45  $this->users = $users;
46  }
47 
52  public static function factory( array $deltas ) {
53  $update = new self( 0, 0, 0 );
54 
55  $fields = [ 'views', 'edits', 'pages', 'articles', 'users', 'images' ];
56  foreach ( $fields as $field ) {
57  if ( isset( $deltas[$field] ) && $deltas[$field] ) {
58  $update->$field = $deltas[$field];
59  }
60  }
61 
62  return $update;
63  }
64 
65  public function doUpdate() {
66  global $wgSiteStatsAsyncFactor;
67 
68  $this->doUpdateContextStats();
69 
70  $rate = $wgSiteStatsAsyncFactor; // convenience
71  // If set to do so, only do actual DB updates 1 every $rate times.
72  // The other times, just update "pending delta" values in memcached.
73  if ( $rate && ( $rate < 0 || mt_rand( 0, $rate - 1 ) != 0 ) ) {
74  $this->doUpdatePendingDeltas();
75  } else {
76  // Need a separate transaction because this a global lock
77  wfGetDB( DB_MASTER )->onTransactionIdle( [ $this, 'tryDBUpdateInternal' ] );
78  }
79  }
80 
84  public function tryDBUpdateInternal() {
85  global $wgSiteStatsAsyncFactor;
86 
87  $dbw = wfGetDB( DB_MASTER );
88  $lockKey = wfMemcKey( 'site_stats' ); // prepend wiki ID
89  $pd = [];
90  if ( $wgSiteStatsAsyncFactor ) {
91  // Lock the table so we don't have double DB/memcached updates
92  if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
93  || !$dbw->lock( $lockKey, __METHOD__, 1 ) // 1 sec timeout
94  ) {
95  $this->doUpdatePendingDeltas();
96 
97  return;
98  }
99  $pd = $this->getPendingDeltas();
100  // Piggy-back the async deltas onto those of this stats update....
101  $this->edits += ( $pd['ss_total_edits']['+'] - $pd['ss_total_edits']['-'] );
102  $this->articles += ( $pd['ss_good_articles']['+'] - $pd['ss_good_articles']['-'] );
103  $this->pages += ( $pd['ss_total_pages']['+'] - $pd['ss_total_pages']['-'] );
104  $this->users += ( $pd['ss_users']['+'] - $pd['ss_users']['-'] );
105  $this->images += ( $pd['ss_images']['+'] - $pd['ss_images']['-'] );
106  }
107 
108  // Build up an SQL query of deltas and apply them...
109  $updates = '';
110  $this->appendUpdate( $updates, 'ss_total_edits', $this->edits );
111  $this->appendUpdate( $updates, 'ss_good_articles', $this->articles );
112  $this->appendUpdate( $updates, 'ss_total_pages', $this->pages );
113  $this->appendUpdate( $updates, 'ss_users', $this->users );
114  $this->appendUpdate( $updates, 'ss_images', $this->images );
115  if ( $updates != '' ) {
116  $dbw->update( 'site_stats', [ $updates ], [], __METHOD__ );
117  }
118 
119  if ( $wgSiteStatsAsyncFactor ) {
120  // Decrement the async deltas now that we applied them
121  $this->removePendingDeltas( $pd );
122  // Commit the updates and unlock the table
123  $dbw->unlock( $lockKey, __METHOD__ );
124  }
125  }
126 
131  public static function cacheUpdate( $dbw ) {
132  global $wgActiveUserDays;
133  $dbr = wfGetDB( DB_SLAVE, 'vslow' );
134  # Get non-bot users than did some recent action other than making accounts.
135  # If account creation is included, the number gets inflated ~20+ fold on enwiki.
136  $activeUsers = $dbr->selectField(
137  'recentchanges',
138  'COUNT( DISTINCT rc_user_text )',
139  [
140  'rc_user != 0',
141  'rc_bot' => 0,
142  'rc_log_type != ' . $dbr->addQuotes( 'newusers' ) . ' OR rc_log_type IS NULL',
143  'rc_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( wfTimestamp( TS_UNIX )
144  - $wgActiveUserDays * 24 * 3600 ) ),
145  ],
146  __METHOD__
147  );
148  $dbw->update(
149  'site_stats',
150  [ 'ss_active_users' => intval( $activeUsers ) ],
151  [ 'ss_row_id' => 1 ],
152  __METHOD__
153  );
154 
155  return $activeUsers;
156  }
157 
158  protected function doUpdateContextStats() {
159  $stats = RequestContext::getMain()->getStats();
160  foreach ( [ 'edits', 'articles', 'pages', 'users', 'images' ] as $type ) {
161  $delta = $this->$type;
162  if ( $delta !== 0 ) {
163  $stats->updateCount( "site.$type", $delta );
164  }
165  }
166  }
167 
168  protected function doUpdatePendingDeltas() {
169  $this->adjustPending( 'ss_total_edits', $this->edits );
170  $this->adjustPending( 'ss_good_articles', $this->articles );
171  $this->adjustPending( 'ss_total_pages', $this->pages );
172  $this->adjustPending( 'ss_users', $this->users );
173  $this->adjustPending( 'ss_images', $this->images );
174  }
175 
181  protected function appendUpdate( &$sql, $field, $delta ) {
182  if ( $delta ) {
183  if ( $sql ) {
184  $sql .= ',';
185  }
186  if ( $delta < 0 ) {
187  $sql .= "$field=$field-" . abs( $delta );
188  } else {
189  $sql .= "$field=$field+" . abs( $delta );
190  }
191  }
192  }
193 
199  private function getTypeCacheKey( $type, $sign ) {
200  return wfMemcKey( 'sitestatsupdate', 'pendingdelta', $type, $sign );
201  }
202 
209  protected function adjustPending( $type, $delta ) {
211  if ( $delta < 0 ) { // decrement
212  $key = $this->getTypeCacheKey( $type, '-' );
213  } else { // increment
214  $key = $this->getTypeCacheKey( $type, '+' );
215  }
216 
217  $magnitude = abs( $delta );
218  $cache->incrWithInit( $key, 0, $magnitude, $magnitude );
219  }
220 
225  protected function getPendingDeltas() {
227 
228  $pending = [];
229  foreach ( [ 'ss_total_edits',
230  'ss_good_articles', 'ss_total_pages', 'ss_users', 'ss_images' ] as $type
231  ) {
232  // Get pending increments and pending decrements
233  $flg = BagOStuff::READ_LATEST;
234  $pending[$type]['+'] = (int)$cache->get( $this->getTypeCacheKey( $type, '+' ), $flg );
235  $pending[$type]['-'] = (int)$cache->get( $this->getTypeCacheKey( $type, '-' ), $flg );
236  }
237 
238  return $pending;
239  }
240 
245  protected function removePendingDeltas( array $pd ) {
247 
248  foreach ( $pd as $type => $deltas ) {
249  foreach ( $deltas as $sign => $magnitude ) {
250  // Lower the pending counter now that we applied these changes
251  $cache->decr( $this->getTypeCacheKey( $type, $sign ), $magnitude );
252  }
253  }
254  }
255 }
__construct($views, $edits, $good, $pages=0, $users=0)
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
the array() calling protocol came about after MediaWiki 1.4rc1.
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
Interface that deferrable updates should implement.
static getMainStashInstance()
Get the cache object for the main stash.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
appendUpdate(&$sql, $field, $delta)
static cacheUpdate($dbw)
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getMain()
Static methods.
static factory(array $deltas)
getTypeCacheKey($type, $sign)
Class for handling updates to the site_stats table.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs which is used to update link tables of transcluding pages after edits
Definition: deferred.txt:11
$cache
Definition: mcc.php:33
const READ_LATEST
Bitfield constants for get()/getMulti()
Definition: BagOStuff.php:80
const DB_SLAVE
Definition: Defines.php:46
removePendingDeltas(array $pd)
Reduce pending delta counters after updates have been applied.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
The ContentHandler facility adds support for arbitrary content types on wiki pages
doUpdate()
Perform the actual work.
adjustPending($type, $delta)
Adjust the pending deltas for a stat type.
wfMemcKey()
Make a cache key for the local wiki.
const DB_MASTER
Definition: Defines.php:47
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
tryDBUpdateInternal()
Do not call this outside of SiteStatsUpdate.
getPendingDeltas()
Get pending delta counters for each stat type.