Merge "Handle missing namespace prefix in XML dumps more gracefully"
[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 * @author Aaron Schulz
20 * @ingroup JobQueue
21 */
22 use MediaWiki\MediaWikiServices;
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 do {
89 $rcIds = $dbw->selectFieldValues( 'recentchanges',
90 'rc_id',
91 [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
92 __METHOD__,
93 [ 'LIMIT' => $wgUpdateRowsPerQuery ]
94 );
95 if ( $rcIds ) {
96 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
97 // There might be more, so try waiting for replica DBs
98 try {
99 $factory->commitAndWaitForReplication(
100 __METHOD__, $ticket, [ 'timeout' => 3 ]
101 );
102 } catch ( DBReplicationWaitError $e ) {
103 // Another job will continue anyway
104 break;
105 }
106 }
107 } while ( $rcIds );
108
109 $dbw->unlock( $lockKey, __METHOD__ );
110 }
111
112 protected function updateActiveUsers() {
113 global $wgActiveUserDays;
114
115 // Users that made edits at least this many days ago are "active"
116 $days = $wgActiveUserDays;
117 // Pull in the full window of active users in this update
118 $window = $wgActiveUserDays * 86400;
119
120 $dbw = wfGetDB( DB_MASTER );
121 // JobRunner uses DBO_TRX, but doesn't call begin/commit itself;
122 // onTransactionIdle() will run immediately since there is no trx.
123 $dbw->onTransactionIdle(
124 function () use ( $dbw, $days, $window ) {
125 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
126 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
127 // Avoid disconnect/ping() cycle that makes locks fall off
128 $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
129
130 $lockKey = wfWikiID() . '-activeusers';
131 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ ) || !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
132 // Exclusive update (avoids duplicate entries)… it's usually fine to just drop out here,
133 // if the Job is already running.
134 return;
135 }
136
137 $nowUnix = time();
138 // Get the last-updated timestamp for the cache
139 $cTime = $dbw->selectField( 'querycache_info',
140 'qci_timestamp',
141 [ 'qci_type' => 'activeusers' ]
142 );
143 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
144
145 // Pick the date range to fetch from. This is normally from the last
146 // update to till the present time, but has a limited window for sanity.
147 // If the window is limited, multiple runs are need to fully populate it.
148 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
149 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
150
151 // Get all the users active since the last update
152 $res = $dbw->select(
153 [ 'recentchanges' ],
154 [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
155 [
156 'rc_user > 0', // actual accounts
157 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
158 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
159 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
160 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
161 ],
162 __METHOD__,
163 [
164 'GROUP BY' => [ 'rc_user_text' ],
165 'ORDER BY' => 'NULL' // avoid filesort
166 ]
167 );
168 $names = [];
169 foreach ( $res as $row ) {
170 $names[$row->rc_user_text] = $row->lastedittime;
171 }
172
173 // Find which of the recently active users are already accounted for
174 if ( count( $names ) ) {
175 $res = $dbw->select( 'querycachetwo',
176 [ 'user_name' => 'qcc_title' ],
177 [
178 'qcc_type' => 'activeusers',
179 'qcc_namespace' => NS_USER,
180 'qcc_title' => array_keys( $names ),
181 'qcc_value >= ' . $dbw->addQuotes( $nowUnix - $days * 86400 ), // TS_UNIX
182 ],
183 __METHOD__
184 );
185 // Note: In order for this to be actually consistent, we would need
186 // to update these rows with the new lastedittime.
187 foreach ( $res as $row ) {
188 unset( $names[$row->user_name] );
189 }
190 }
191
192 // Insert the users that need to be added to the list
193 if ( count( $names ) ) {
194 $newRows = [];
195 foreach ( $names as $name => $lastEditTime ) {
196 $newRows[] = [
197 'qcc_type' => 'activeusers',
198 'qcc_namespace' => NS_USER,
199 'qcc_title' => $name,
200 'qcc_value' => wfTimestamp( TS_UNIX, $lastEditTime ),
201 'qcc_namespacetwo' => 0, // unused
202 'qcc_titletwo' => '' // unused
203 ];
204 }
205 foreach ( array_chunk( $newRows, 500 ) as $rowBatch ) {
206 $dbw->insert( 'querycachetwo', $rowBatch, __METHOD__ );
207 $factory->commitAndWaitForReplication( __METHOD__, $ticket );
208 }
209 }
210
211 // If a transaction was already started, it might have an old
212 // snapshot, so kludge the timestamp range back as needed.
213 $asOfTimestamp = min( $eTimestamp, (int)$dbw->trxTimestamp() );
214
215 // Touch the data freshness timestamp
216 $dbw->replace( 'querycache_info',
217 [ 'qci_type' ],
218 [ 'qci_type' => 'activeusers',
219 'qci_timestamp' => $dbw->timestamp( $asOfTimestamp ) ], // not always $now
220 __METHOD__
221 );
222
223 $dbw->unlock( $lockKey, __METHOD__ );
224
225 // Rotate out users that have not edited in too long (according to old data set)
226 $dbw->delete( 'querycachetwo',
227 [
228 'qcc_type' => 'activeusers',
229 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
230 ],
231 __METHOD__
232 );
233
234 },
235 __METHOD__
236 );
237 }
238 }