Merge "Add attributes parameter to ShowSearchHitTitle"
[lhc/web/wiklou.git] / includes / jobqueue / jobs / RecentChangesUpdateJob.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup JobQueue
20 */
21 use MediaWiki\MediaWikiServices;
22 use Wikimedia\Rdbms\DBReplicationWaitError;
23
24 /**
25 * Job for pruning recent changes
26 *
27 * @ingroup JobQueue
28 * @since 1.25
29 */
30 class RecentChangesUpdateJob extends Job {
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->removeDuplicates = true;
39 }
40
41 /**
42 * @return RecentChangesUpdateJob
43 */
44 final public static function newPurgeJob() {
45 return new self(
46 SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
47 );
48 }
49
50 /**
51 * @return RecentChangesUpdateJob
52 * @since 1.26
53 */
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() {
74 global $wgRCMaxAge, $wgUpdateRowsPerQuery;
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 $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 // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
132 // onTransactionIdle() will run immediately since there is no trx.
133 $dbw->onTransactionIdle(
134 function () use ( $dbw, $days, $window ) {
135 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
136 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
137 // Avoid disconnect/ping() cycle that makes locks fall off
138 $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
139
140 $lockKey = wfWikiID() . '-activeusers';
141 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ ) || !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
142 // Exclusive update (avoids duplicate entries)… it's usually fine to just drop out here,
143 // if the Job is already running.
144 return;
145 }
146
147 $nowUnix = time();
148 // Get the last-updated timestamp for the cache
149 $cTime = $dbw->selectField( 'querycache_info',
150 'qci_timestamp',
151 [ 'qci_type' => 'activeusers' ]
152 );
153 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
154
155 // Pick the date range to fetch from. This is normally from the last
156 // update to till the present time, but has a limited window for sanity.
157 // If the window is limited, multiple runs are need to fully populate it.
158 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
159 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
160
161 // Get all the users active since the last update
162 $res = $dbw->select(
163 [ 'recentchanges' ],
164 [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
165 [
166 'rc_user > 0', // actual accounts
167 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
168 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
169 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
170 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
171 ],
172 __METHOD__,
173 [
174 'GROUP BY' => [ 'rc_user_text' ],
175 'ORDER BY' => 'NULL' // avoid filesort
176 ]
177 );
178 $names = [];
179 foreach ( $res as $row ) {
180 $names[$row->rc_user_text] = $row->lastedittime;
181 }
182
183 // Find which of the recently active users are already accounted for
184 if ( count( $names ) ) {
185 $res = $dbw->select( 'querycachetwo',
186 [ 'user_name' => 'qcc_title' ],
187 [
188 'qcc_type' => 'activeusers',
189 'qcc_namespace' => NS_USER,
190 'qcc_title' => array_keys( $names ),
191 'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
192 ],
193 __METHOD__
194 );
195 // Note: In order for this to be actually consistent, we would need
196 // to update these rows with the new lastedittime.
197 foreach ( $res as $row ) {
198 unset( $names[$row->user_name] );
199 }
200 }
201
202 // Insert the users that need to be added to the list
203 if ( count( $names ) ) {
204 $newRows = [];
205 foreach ( $names as $name => $lastEditTime ) {
206 $newRows[] = [
207 'qcc_type' => 'activeusers',
208 'qcc_namespace' => NS_USER,
209 'qcc_title' => $name,
210 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
211 'qcc_namespacetwo' => 0, // unused
212 'qcc_titletwo' => '' // unused
213 ];
214 }
215 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
216 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
217 $factory->commitAndWaitForReplication( __METHOD__, $ticket );
218 }
219 }
220
221 // If a transaction was already started, it might have an old
222 // snapshot, so kludge the timestamp range back as needed.
223 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
224
225 // Touch the data freshness timestamp
226 $dbw->replace( 'querycache_info',
227 [ 'qci_type' ],
228 [ 'qci_type' => 'activeusers',
229 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
230 __METHOD__
231 );
232
233 $dbw->unlock( $lockKey, __METHOD__ );
234
235 // Rotate out users that have not edited in too long (according to old data set)
236 $dbw->delete( 'querycachetwo',
237 [
238 'qcc_type' => 'activeusers',
239 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
240 ],
241 __METHOD__
242 );
243 },
244 __METHOD__
245 );
246 }
247 }