MediaWiki  1.30.0
RecentChangesUpdateJob.php
Go to the documentation of this file.
1 <?php
23 
30 class RecentChangesUpdateJob extends Job {
32  parent::__construct( 'recentChangesUpdate', $title, $params );
33 
34  if ( !isset( $params['type'] ) ) {
35  throw new Exception( "Missing 'type' parameter." );
36  }
37 
38  $this->removeDuplicates = true;
39  }
40 
44  final public static function newPurgeJob() {
45  return new self(
46  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
47  );
48  }
49 
54  final public static function newCacheUpdateJob() {
55  return new self(
56  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
57  );
58  }
59 
60  public function run() {
61  if ( $this->params['type'] === 'purge' ) {
62  $this->purgeExpiredRows();
63  } elseif ( $this->params['type'] === 'cacheUpdate' ) {
64  $this->updateActiveUsers();
65  } else {
66  throw new InvalidArgumentException(
67  "Invalid 'type' parameter '{$this->params['type']}'." );
68  }
69 
70  return true;
71  }
72 
73  protected function purgeExpiredRows() {
75 
76  $lockKey = wfWikiID() . ':recentchanges-prune';
77 
78  $dbw = wfGetDB( DB_MASTER );
79  if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
80  || !$dbw->lock( $lockKey, __METHOD__, 1 )
81  ) {
82  return; // already in progress
83  }
84 
85  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
86  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
87  $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
88  do {
89  $rcIds = [];
90  $rows = [];
91  $res = $dbw->select( 'recentchanges',
93  [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
94  __METHOD__,
95  [ 'LIMIT' => $wgUpdateRowsPerQuery ]
96  );
97  foreach ( $res as $row ) {
98  $rcIds[] = $row->rc_id;
99  $rows[] = $row;
100  }
101  if ( $rcIds ) {
102  $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
103  Hooks::run( 'RecentChangesPurgeRows', [ $rows ] );
104  // There might be more, so try waiting for replica DBs
105  try {
106  $factory->commitAndWaitForReplication(
107  __METHOD__, $ticket, [ 'timeout' => 3 ]
108  );
109  } catch ( DBReplicationWaitError $e ) {
110  // Another job will continue anyway
111  break;
112  }
113  }
114  } while ( $rcIds );
115 
116  $dbw->unlock( $lockKey, __METHOD__ );
117  }
118 
119  protected function updateActiveUsers() {
121 
122  // Users that made edits at least this many days ago are "active"
123  $days = $wgActiveUserDays;
124  // Pull in the full window of active users in this update
125  $window = $wgActiveUserDays * 86400;
126 
127  $dbw = wfGetDB( DB_MASTER );
128  // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
129  // onTransactionIdle() will run immediately since there is no trx.
130  $dbw->onTransactionIdle(
131  function () use ( $dbw, $days, $window ) {
132  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
133  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
134  // Avoid disconnect/ping() cycle that makes locks fall off
135  $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
136 
137  $lockKey = wfWikiID() . '-activeusers';
138  if ( !$dbw->lockIsFree( $lockKey, __METHOD__ ) || !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
139  // Exclusive update (avoids duplicate entries)… it's usually fine to just drop out here,
140  // if the Job is already running.
141  return;
142  }
143 
144  $nowUnix = time();
145  // Get the last-updated timestamp for the cache
146  $cTime = $dbw->selectField( 'querycache_info',
147  'qci_timestamp',
148  [ 'qci_type' => 'activeusers' ]
149  );
150  $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
151 
152  // Pick the date range to fetch from. This is normally from the last
153  // update to till the present time, but has a limited window for sanity.
154  // If the window is limited, multiple runs are need to fully populate it.
155  $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
156  $eTimestamp = min( $sTimestamp + $window, $nowUnix );
157 
158  // Get all the users active since the last update
159  $res = $dbw->select(
160  [ 'recentchanges' ],
161  [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
162  [
163  'rc_user > 0', // actual accounts
164  'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
165  'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
166  'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
167  'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
168  ],
169  __METHOD__,
170  [
171  'GROUP BY' => [ 'rc_user_text' ],
172  'ORDER BY' => 'NULL' // avoid filesort
173  ]
174  );
175  $names = [];
176  foreach ( $res as $row ) {
177  $names[$row->rc_user_text] = $row->lastedittime;
178  }
179 
180  // Find which of the recently active users are already accounted for
181  if ( count( $names ) ) {
182  $res = $dbw->select( 'querycachetwo',
183  [ 'user_name' => 'qcc_title' ],
184  [
185  'qcc_type' => 'activeusers',
186  'qcc_namespace' => NS_USER,
187  'qcc_title' => array_keys( $names ),
188  'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
189  ],
190  __METHOD__
191  );
192  // Note: In order for this to be actually consistent, we would need
193  // to update these rows with the new lastedittime.
194  foreach ( $res as $row ) {
195  unset( $names[$row->user_name] );
196  }
197  }
198 
199  // Insert the users that need to be added to the list
200  if ( count( $names ) ) {
201  $newRows = [];
202  foreach ( $names as $name => $lastEditTime ) {
203  $newRows[] = [
204  'qcc_type' => 'activeusers',
205  'qcc_namespace' => NS_USER,
206  'qcc_title' => $name,
207  'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
208  'qcc_namespacetwo' => 0, // unused
209  'qcc_titletwo' => '' // unused
210  ];
211  }
212  foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
213  $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
214  $factory->commitAndWaitForReplication( __METHOD__, $ticket );
215  }
216  }
217 
218  // If a transaction was already started, it might have an old
219  // snapshot, so kludge the timestamp range back as needed.
220  $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
221 
222  // Touch the data freshness timestamp
223  $dbw->replace( 'querycache_info',
224  [ 'qci_type' ],
225  [ 'qci_type' => 'activeusers',
226  'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
227  __METHOD__
228  );
229 
230  $dbw->unlock( $lockKey, __METHOD__ );
231 
232  // Rotate out users that have not edited in too long (according to old data set)
233  $dbw->delete( 'querycachetwo',
234  [
235  'qcc_type' => 'activeusers',
236  'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
237  ],
238  __METHOD__
239  );
240  },
241  __METHOD__
242  );
243  }
244 }
RC_EXTERNAL
const RC_EXTERNAL
Definition: Defines.php:146
RecentChangesUpdateJob
Job for pruning recent changes.
Definition: RecentChangesUpdateJob.php:30
captcha-old.count
count
Definition: captcha-old.py:249
RecentChangesUpdateJob\updateActiveUsers
updateActiveUsers()
Definition: RecentChangesUpdateJob.php:119
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
RecentChangesUpdateJob\run
run()
Run the job.
Definition: RecentChangesUpdateJob.php:60
Wikimedia\Rdbms\DBReplicationWaitError
Exception class for replica DB wait timeouts.
Definition: DBReplicationWaitError.php:28
Job\$title
Title $title
Definition: Job.php:42
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
RecentChangesUpdateJob\__construct
__construct(Title $title, array $params)
Definition: RecentChangesUpdateJob.php:31
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:82
RecentChangesUpdateJob\purgeExpiredRows
purgeExpiredRows()
Definition: RecentChangesUpdateJob.php:73
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
Job\$params
array $params
Array of job parameters.
Definition: Job.php:36
RecentChangesUpdateJob\newCacheUpdateJob
static newCacheUpdateJob()
Definition: RecentChangesUpdateJob.php:54
php
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
Job
Class to both describe a background job and handle jobs.
Definition: Job.php:31
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2856
$wgUpdateRowsPerQuery
$wgUpdateRowsPerQuery
Number of rows to update per query.
Definition: DefaultSettings.php:8331
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_MASTER
const DB_MASTER
Definition: defines.php:26
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2807
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
$wgActiveUserDays
$wgActiveUserDays
How many days user must be idle before he is considered inactive.
Definition: DefaultSettings.php:4469
$wgRCMaxAge
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
Definition: DefaultSettings.php:6681
Title
Represents a title within MediaWiki.
Definition: Title.php:39
RecentChange\selectFields
static selectFields()
Return the list of recentchanges fields that should be selected to create a new recentchanges object.
Definition: RecentChange.php:210
$rows
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition: hooks.txt:2581
as
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
RecentChangesUpdateJob\newPurgeJob
static newPurgeJob()
Definition: RecentChangesUpdateJob.php:44
NS_USER
const NS_USER
Definition: Defines.php:67
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
array
the array() calling protocol came about after MediaWiki 1.4rc1.