MediaWiki  REL1_31
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->executionFlags |= self::JOB_NO_EXPLICIT_TRX_ROUND;
39  $this->removeDuplicates = true;
40  }
41 
45  final public static function newPurgeJob() {
46  return new self(
47  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
48  );
49  }
50 
55  final public static function newCacheUpdateJob() {
56  return new self(
57  SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
58  );
59  }
60 
61  public function run() {
62  if ( $this->params['type'] === 'purge' ) {
63  $this->purgeExpiredRows();
64  } elseif ( $this->params['type'] === 'cacheUpdate' ) {
65  $this->updateActiveUsers();
66  } else {
67  throw new InvalidArgumentException(
68  "Invalid 'type' parameter '{$this->params['type']}'." );
69  }
70 
71  return true;
72  }
73 
74  protected function purgeExpiredRows() {
76 
77  $lockKey = wfWikiID() . ':recentchanges-prune';
78 
79  $dbw = wfGetDB( DB_MASTER );
80  if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
81  // already in progress
82  return;
83  }
84 
85  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
86  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
87  $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
88  $rcQuery = RecentChange::getQueryInfo();
89  do {
90  $rcIds = [];
91  $rows = [];
92  $res = $dbw->select(
93  $rcQuery['tables'],
94  $rcQuery['fields'],
95  [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
96  __METHOD__,
97  [ 'LIMIT' => $wgUpdateRowsPerQuery ],
98  $rcQuery['joins']
99  );
100  foreach ( $res as $row ) {
101  $rcIds[] = $row->rc_id;
102  $rows[] = $row;
103  }
104  if ( $rcIds ) {
105  $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
106  Hooks::run( 'RecentChangesPurgeRows', [ $rows ] );
107  // There might be more, so try waiting for replica DBs
108  try {
109  $factory->commitAndWaitForReplication(
110  __METHOD__, $ticket, [ 'timeout' => 3 ]
111  );
112  } catch ( DBReplicationWaitError $e ) {
113  // Another job will continue anyway
114  break;
115  }
116  }
117  } while ( $rcIds );
118 
119  $dbw->unlock( $lockKey, __METHOD__ );
120  }
121 
122  protected function updateActiveUsers() {
124 
125  // Users that made edits at least this many days ago are "active"
126  $days = $wgActiveUserDays;
127  // Pull in the full window of active users in this update
128  $window = $wgActiveUserDays * 86400;
129 
130  $dbw = wfGetDB( DB_MASTER );
131  $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
132  $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
133 
134  $lockKey = wfWikiID() . '-activeusers';
135  if ( !$dbw->lock( $lockKey, __METHOD__, 0 ) ) {
136  // Exclusive update (avoids duplicate entries)… it's usually fine to just
137  // drop out here, if the Job is already running.
138  return;
139  }
140 
141  // Long-running queries expected
142  $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
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  $actorQuery = ActorMigration::newMigration()->getJoin( 'rc_user' );
160  $res = $dbw->select(
161  [ 'recentchanges' ] + $actorQuery['tables'],
162  [
163  'rc_user_text' => $actorQuery['fields']['rc_user_text'],
164  'lastedittime' => 'MAX(rc_timestamp)'
165  ],
166  [
167  $actorQuery['fields']['rc_user'] . ' > 0', // actual accounts
168  'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
169  'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
170  'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
171  'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
172  ],
173  __METHOD__,
174  [
175  'GROUP BY' => [ 'rc_user_text' ],
176  'ORDER BY' => 'NULL' // avoid filesort
177  ],
178  $actorQuery['joins']
179  );
180  $names = [];
181  foreach ( $res as $row ) {
182  $names[$row->rc_user_text] = $row->lastedittime;
183  }
184 
185  // Find which of the recently active users are already accounted for
186  if ( count( $names ) ) {
187  $res = $dbw->select( 'querycachetwo',
188  [ 'user_name' => 'qcc_title' ],
189  [
190  'qcc_type' => 'activeusers',
191  'qcc_namespace' => NS_USER,
192  'qcc_title' => array_keys( $names ),
193  'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
194  ],
195  __METHOD__
196  );
197  // Note: In order for this to be actually consistent, we would need
198  // to update these rows with the new lastedittime.
199  foreach ( $res as $row ) {
200  unset( $names[$row->user_name] );
201  }
202  }
203 
204  // Insert the users that need to be added to the list
205  if ( count( $names ) ) {
206  $newRows = [];
207  foreach ( $names as $name => $lastEditTime ) {
208  $newRows[] = [
209  'qcc_type' => 'activeusers',
210  'qcc_namespace' => NS_USER,
211  'qcc_title' => $name,
212  'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
213  'qcc_namespacetwo' => 0, // unused
214  'qcc_titletwo' => '' // unused
215  ];
216  }
217  foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
218  $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
219  $factory->commitAndWaitForReplication( __METHOD__, $ticket );
220  }
221  }
222 
223  // If a transaction was already started, it might have an old
224  // snapshot, so kludge the timestamp range back as needed.
225  $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
226 
227  // Touch the data freshness timestamp
228  $dbw->replace( 'querycache_info',
229  [ 'qci_type' ],
230  [ 'qci_type' => 'activeusers',
231  'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
232  __METHOD__
233  );
234 
235  $dbw->unlock( $lockKey, __METHOD__ );
236 
237  // Rotate out users that have not edited in too long (according to old data set)
238  $dbw->delete( 'querycachetwo',
239  [
240  'qcc_type' => 'activeusers',
241  'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
242  ],
243  __METHOD__
244  );
245  }
246 }
RecentChange\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new recentchanges object.
Definition: RecentChange.php:268
RC_EXTERNAL
const RC_EXTERNAL
Definition: Defines.php:155
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
$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:2783
array
the array() calling protocol came about after MediaWiki 1.4rc1.
RecentChangesUpdateJob
Job for pruning recent changes.
Definition: RecentChangesUpdateJob.php:30
RecentChangesUpdateJob\updateActiveUsers
updateActiveUsers()
Definition: RecentChangesUpdateJob.php:122
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
RecentChangesUpdateJob\run
run()
Run the job.
Definition: RecentChangesUpdateJob.php:61
Wikimedia\Rdbms\DBReplicationWaitError
Exception class for replica DB wait timeouts.
Definition: DBReplicationWaitError.php:28
Job\$title
Title $title
Definition: Job.php:42
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:74
$res
$res
Definition: database.txt:21
Job\$params
array $params
Array of job parameters.
Definition: Job.php:36
RecentChangesUpdateJob\newCacheUpdateJob
static newCacheUpdateJob()
Definition: RecentChangesUpdateJob.php:55
ActorMigration\newMigration
static newMigration()
Static constructor.
Definition: ActorMigration.php:89
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:37
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:2812
$wgUpdateRowsPerQuery
$wgUpdateRowsPerQuery
Number of rows to update per query.
Definition: DefaultSettings.php:8437
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:95
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:2763
$wgActiveUserDays
$wgActiveUserDays
How many days user must be idle before he is considered inactive.
Definition: DefaultSettings.php:4461
$wgRCMaxAge
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
Definition: DefaultSettings.php:6736
Title
Represents a title within MediaWiki.
Definition: Title.php:39
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
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:22
RecentChangesUpdateJob\newPurgeJob
static newPurgeJob()
Definition: RecentChangesUpdateJob.php:45
NS_USER
const NS_USER
Definition: Defines.php:76
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:25
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2171