MediaWiki REL1_31
RecentChangesUpdateJob.php
Go to the documentation of this file.
1<?php
23
31 function __construct( Title $title, array $params ) {
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() {
123 global $wgActiveUserDays;
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}
$wgActiveUserDays
How many days user must be idle before he is considered inactive.
$wgRCMaxAge
Recentchanges items are periodically purged; entries older than this many seconds will go.
$wgUpdateRowsPerQuery
Number of rows to update per query.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Class to both describe a background job and handle jobs.
Definition Job.php:31
array $params
Array of job parameters.
Definition Job.php:36
MediaWikiServices is the service locator for the application scope of MediaWiki.
Job for pruning recent changes.
__construct(Title $title, array $params)
Represents a title within MediaWiki.
Definition Title.php:39
Exception class for replica DB wait timeouts.
$res
Definition database.txt:21
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
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
returning false will NOT prevent logging $e
Definition hooks.txt:2176
const NS_USER
Definition Defines.php:76
const RC_EXTERNAL
Definition Defines.php:155
const DB_MASTER
Definition defines.php:29