User::isSafeToLoad() should return false if MW_NO_SESSION
[mediawiki.git] / includes / jobqueue / jobs / RecentChangesUpdateJob.php
blob22afead165254cd4bb677fc0200545d13365c20f
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
19 * @author Aaron Schulz
20 * @ingroup JobQueue
23 /**
24 * Job for pruning recent changes
26 * @ingroup JobQueue
27 * @since 1.25
29 class RecentChangesUpdateJob extends Job {
30 function __construct( Title $title, array $params ) {
31 parent::__construct( 'recentChangesUpdate', $title, $params );
33 if ( !isset( $params['type'] ) ) {
34 throw new Exception( "Missing 'type' parameter." );
37 $this->removeDuplicates = true;
40 /**
41 * @return RecentChangesUpdateJob
43 final public static function newPurgeJob() {
44 return new self(
45 SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
49 /**
50 * @return RecentChangesUpdateJob
51 * @since 1.26
53 final public static function newCacheUpdateJob() {
54 return new self(
55 SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
59 public function run() {
60 if ( $this->params['type'] === 'purge' ) {
61 $this->purgeExpiredRows();
62 } elseif ( $this->params['type'] === 'cacheUpdate' ) {
63 $this->updateActiveUsers();
64 } else {
65 throw new InvalidArgumentException(
66 "Invalid 'type' parameter '{$this->params['type']}'." );
69 return true;
72 protected function purgeExpiredRows() {
73 global $wgRCMaxAge;
75 $lockKey = wfWikiID() . ':recentchanges-prune';
77 $dbw = wfGetDB( DB_MASTER );
78 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
79 || !$dbw->lock( $lockKey, __METHOD__, 1 )
80 ) {
81 return; // already in progress
84 $batchSize = 100; // avoid slave lag
85 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
86 do {
87 $rcIds = $dbw->selectFieldValues( 'recentchanges',
88 'rc_id',
89 [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
90 __METHOD__,
91 [ 'LIMIT' => $batchSize ]
93 if ( $rcIds ) {
94 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
96 // Commit in chunks to avoid slave lag
97 $dbw->commit( __METHOD__, 'flush' );
99 if ( count( $rcIds ) === $batchSize ) {
100 // There might be more, so try waiting for slaves
101 try {
102 wfGetLBFactory()->waitForReplication( [ 'timeout' => 3 ] );
103 } catch ( DBReplicationWaitError $e ) {
104 // Another job will continue anyway
105 break;
108 } while ( $rcIds );
110 $dbw->unlock( $lockKey, __METHOD__ );
113 protected function updateActiveUsers() {
114 global $wgActiveUserDays;
116 // Users that made edits at least this many days ago are "active"
117 $days = $wgActiveUserDays;
118 // Pull in the full window of active users in this update
119 $window = $wgActiveUserDays * 86400;
121 $dbw = wfGetDB( DB_MASTER );
122 // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
123 // onTransactionIdle() will run immediately since there is no trx.
124 $dbw->onTransactionIdle( function() use ( $dbw, $days, $window ) {
125 // Avoid disconnect/ping() cycle that makes locks fall off
126 $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
128 $lockKey = wfWikiID() . '-activeusers';
129 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
130 return; // exclusive update (avoids duplicate entries)
133 $nowUnix = time();
134 // Get the last-updated timestamp for the cache
135 $cTime = $dbw->selectField( 'querycache_info',
136 'qci_timestamp',
137 [ 'qci_type' => 'activeusers' ]
139 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
141 // Pick the date range to fetch from. This is normally from the last
142 // update to till the present time, but has a limited window for sanity.
143 // If the window is limited, multiple runs are need to fully populate it.
144 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
145 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
147 // Get all the users active since the last update
148 $res = $dbw->select(
149 [ 'recentchanges' ],
150 [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
152 'rc_user > 0', // actual accounts
153 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
154 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
155 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
156 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
158 __METHOD__,
160 'GROUP BY' => [ 'rc_user_text' ],
161 'ORDER BY' => 'NULL' // avoid filesort
164 $names = [];
165 foreach ( $res as $row ) {
166 $names[$row->rc_user_text] = $row->lastedittime;
169 // Rotate out users that have not edited in too long (according to old data set)
170 $dbw->delete( 'querycachetwo',
172 'qcc_type' => 'activeusers',
173 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
175 __METHOD__
178 // Find which of the recently active users are already accounted for
179 if ( count( $names ) ) {
180 $res = $dbw->select( 'querycachetwo',
181 [ 'user_name' => 'qcc_title' ],
183 'qcc_type' => 'activeusers',
184 'qcc_namespace' => NS_USER,
185 'qcc_title' => array_keys( $names ) ],
186 __METHOD__
188 foreach ( $res as $row ) {
189 unset( $names[$row->user_name] );
193 // Insert the users that need to be added to the list
194 if ( count( $names ) ) {
195 $newRows = [];
196 foreach ( $names as $name => $lastEditTime ) {
197 $newRows[] = [
198 'qcc_type' => 'activeusers',
199 'qcc_namespace' => NS_USER,
200 'qcc_title' => $name,
201 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
202 'qcc_namespacetwo' => 0, // unused
203 'qcc_titletwo' => '' // unused
206 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
207 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
208 wfGetLBFactory()->waitForReplication();
212 // If a transaction was already started, it might have an old
213 // snapshot, so kludge the timestamp range back as needed.
214 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
216 // Touch the data freshness timestamp
217 $dbw->replace( 'querycache_info',
218 [ 'qci_type' ],
219 [ 'qci_type' => 'activeusers',
220 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
221 __METHOD__
224 $dbw->unlock( $lockKey, __METHOD__ );
225 } );