Merge "Split editcascadeprotected permission from protect permission"
[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
23 /**
24 * Job for pruning recent changes
25 *
26 * @ingroup JobQueue
27 * @since 1.25
28 */
29 class RecentChangesUpdateJob extends Job {
30 function __construct( Title $title, array $params ) {
31 parent::__construct( 'recentChangesUpdate', $title, $params );
32
33 if ( !isset( $params['type'] ) ) {
34 throw new Exception( "Missing 'type' parameter." );
35 }
36
37 $this->removeDuplicates = true;
38 }
39
40 /**
41 * @return RecentChangesUpdateJob
42 */
43 final public static function newPurgeJob() {
44 return new self(
45 SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'purge' ]
46 );
47 }
48
49 /**
50 * @return RecentChangesUpdateJob
51 * @since 1.26
52 */
53 final public static function newCacheUpdateJob() {
54 return new self(
55 SpecialPage::getTitleFor( 'Recentchanges' ), [ 'type' => 'cacheUpdate' ]
56 );
57 }
58
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']}'." );
67 }
68
69 return true;
70 }
71
72 protected function purgeExpiredRows() {
73 global $wgRCMaxAge, $wgUpdateRowsPerQuery;
74
75 $lockKey = wfWikiID() . ':recentchanges-prune';
76
77 $dbw = wfGetDB( DB_MASTER );
78 if ( !$dbw->lockIsFree( $lockKey, __METHOD__ )
79 || !$dbw->lock( $lockKey, __METHOD__, 1 )
80 ) {
81 return; // already in progress
82 }
83
84 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
85 do {
86 $rcIds = $dbw->selectFieldValues( 'recentchanges',
87 'rc_id',
88 [ 'rc_timestamp < ' . $dbw->addQuotes( $cutoff ) ],
89 __METHOD__,
90 [ 'LIMIT' => $wgUpdateRowsPerQuery ]
91 );
92 if ( $rcIds ) {
93 $dbw->delete( 'recentchanges', [ 'rc_id' => $rcIds ], __METHOD__ );
94 }
95 // Commit in chunks to avoid slave lag
96 $dbw->commit( __METHOD__, 'flush' );
97
98 if ( count( $rcIds ) === $wgUpdateRowsPerQuery ) {
99 // There might be more, so try waiting for slaves
100 try {
101 wfGetLBFactory()->waitForReplication( [ 'timeout' => 3 ] );
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( function() use ( $dbw, $days, $window ) {
124 // Avoid disconnect/ping() cycle that makes locks fall off
125 $dbw->setSessionOptions( [ 'connTimeout' => 900 ] );
126
127 $lockKey = wfWikiID() . '-activeusers';
128 if ( !$dbw->lock( $lockKey, __METHOD__, 1 ) ) {
129 return; // exclusive update (avoids duplicate entries)
130 }
131
132 $nowUnix = time();
133 // Get the last-updated timestamp for the cache
134 $cTime = $dbw->selectField( 'querycache_info',
135 'qci_timestamp',
136 [ 'qci_type' => 'activeusers' ]
137 );
138 $cTimeUnix = $cTime ? wfTimestamp( TS_UNIX, $cTime ) : 1;
139
140 // Pick the date range to fetch from. This is normally from the last
141 // update to till the present time, but has a limited window for sanity.
142 // If the window is limited, multiple runs are need to fully populate it.
143 $sTimestamp = max( $cTimeUnix, $nowUnix - $days * 86400 );
144 $eTimestamp = min( $sTimestamp + $window, $nowUnix );
145
146 // Get all the users active since the last update
147 $res = $dbw->select(
148 [ 'recentchanges' ],
149 [ 'rc_user_text', 'lastedittime' => 'MAX(rc_timestamp)' ],
150 [
151 'rc_user > 0', // actual accounts
152 'rc_type != ' . $dbw->addQuotes( RC_EXTERNAL ), // no wikidata
153 'rc_log_type IS NULL OR rc_log_type != ' . $dbw->addQuotes( 'newusers' ),
154 'rc_timestamp >= ' . $dbw->addQuotes( $dbw->timestamp( $sTimestamp ) ),
155 'rc_timestamp <= ' . $dbw->addQuotes( $dbw->timestamp( $eTimestamp ) )
156 ],
157 __METHOD__,
158 [
159 'GROUP BY' => [ 'rc_user_text' ],
160 'ORDER BY' => 'NULL' // avoid filesort
161 ]
162 );
163 $names = [];
164 foreach ( $res as $row ) {
165 $names[$row->rc_user_text] = $row->lastedittime;
166 }
167
168 // Rotate out users that have not edited in too long (according to old data set)
169 $dbw->delete( 'querycachetwo',
170 [
171 'qcc_type' => 'activeusers',
172 'qcc_value < ' . $dbw->addQuotes( $nowUnix - $days * 86400 ) // TS_UNIX
173 ],
174 __METHOD__
175 );
176
177 // Find which of the recently active users are already accounted for
178 if ( count( $names ) ) {
179 $res = $dbw->select( 'querycachetwo',
180 [ 'user_name' => 'qcc_title' ],
181 [
182 'qcc_type' => 'activeusers',
183 'qcc_namespace' => NS_USER,
184 'qcc_title' => array_keys( $names ) ],
185 __METHOD__
186 );
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 wfGetLBFactory()->waitForReplication();
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 }
226 }