Merge "Perform a permission check on the title when changing the page language"
[lhc/web/wiklou.git] / includes / jobqueue / jobs / RefreshLinksJob.php
1 <?php
2 /**
3 * Job to update link tables for pages
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup JobQueue
22 */
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\DBReplicationWaitError;
25
26 /**
27 * Job to update link tables for pages
28 *
29 * This job comes in a few variants:
30 * - a) Recursive jobs to update links for backlink pages for a given title.
31 * These jobs have (recursive:true,table:<table>) set.
32 * - b) Jobs to update links for a set of pages (the job title is ignored).
33 * These jobs have (pages:(<page ID>:(<namespace>,<title>),...) set.
34 * - c) Jobs to update links for a single page (the job title)
35 * These jobs need no extra fields set.
36 *
37 * @ingroup JobQueue
38 */
39 class RefreshLinksJob extends Job {
40 /** @var float Cache parser output when it takes this long to render */
41 const PARSE_THRESHOLD_SEC = 1.0;
42 /** @var integer Lag safety margin when comparing root job times to last-refresh times */
43 const CLOCK_FUDGE = 10;
44 /** @var integer How many seconds to wait for replica DBs to catch up */
45 const LAG_WAIT_TIMEOUT = 15;
46
47 function __construct( Title $title, array $params ) {
48 parent::__construct( 'refreshLinks', $title, $params );
49 // Avoid the overhead of de-duplication when it would be pointless
50 $this->removeDuplicates = (
51 // Ranges rarely will line up
52 !isset( $params['range'] ) &&
53 // Multiple pages per job make matches unlikely
54 !( isset( $params['pages'] ) && count( $params['pages'] ) != 1 )
55 );
56 }
57
58 /**
59 * @param Title $title
60 * @param array $params
61 * @return RefreshLinksJob
62 */
63 public static function newPrioritized( Title $title, array $params ) {
64 $job = new self( $title, $params );
65 $job->command = 'refreshLinksPrioritized';
66
67 return $job;
68 }
69
70 /**
71 * @param Title $title
72 * @param array $params
73 * @return RefreshLinksJob
74 */
75 public static function newDynamic( Title $title, array $params ) {
76 $job = new self( $title, $params );
77 $job->command = 'refreshLinksDynamic';
78
79 return $job;
80 }
81
82 function run() {
83 global $wgUpdateRowsPerJob;
84
85 // Job to update all (or a range of) backlink pages for a page
86 if ( !empty( $this->params['recursive'] ) ) {
87 // When the base job branches, wait for the replica DBs to catch up to the master.
88 // From then on, we know that any template changes at the time the base job was
89 // enqueued will be reflected in backlink page parses when the leaf jobs run.
90 if ( !isset( $this->params['range'] ) ) {
91 try {
92 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
93 $lbFactory->waitForReplication( [
94 'wiki' => wfWikiID(),
95 'timeout' => self::LAG_WAIT_TIMEOUT
96 ] );
97 } catch ( DBReplicationWaitError $e ) { // only try so hard
98 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
99 $stats->increment( 'refreshlinks.lag_wait_failed' );
100 }
101 }
102 // Carry over information for de-duplication
103 $extraParams = $this->getRootJobParams();
104 $extraParams['triggeredRecursive'] = true;
105 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
106 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
107 $jobs = BacklinkJobUtils::partitionBacklinkJob(
108 $this,
109 $wgUpdateRowsPerJob,
110 1, // job-per-title
111 [ 'params' => $extraParams ]
112 );
113 JobQueueGroup::singleton()->push( $jobs );
114 // Job to update link tables for a set of titles
115 } elseif ( isset( $this->params['pages'] ) ) {
116 foreach ( $this->params['pages'] as $nsAndKey ) {
117 list( $ns, $dbKey ) = $nsAndKey;
118 $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
119 }
120 // Job to update link tables for a given title
121 } else {
122 $this->runForTitle( $this->title );
123 }
124
125 return true;
126 }
127
128 /**
129 * @param Title $title
130 * @return bool
131 */
132 protected function runForTitle( Title $title ) {
133 $services = MediaWikiServices::getInstance();
134 $stats = $services->getStatsdDataFactory();
135 $lbFactory = $services->getDBLoadBalancerFactory();
136 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
137
138 $page = WikiPage::factory( $title );
139 $page->loadPageData( WikiPage::READ_LATEST );
140
141 // Serialize links updates by page ID so they see each others' changes
142 $dbw = $lbFactory->getMainLB()->getConnection( DB_MASTER );
143 /** @noinspection PhpUnusedLocalVariableInspection */
144 $scopedLock = LinksUpdate::acquirePageLock( $dbw, $page->getId(), 'job' );
145 // Get the latest ID *after* acquirePageLock() flushed the transaction.
146 // This is used to detect edits/moves after loadPageData() but before the scope lock.
147 // The works around the chicken/egg problem of determining the scope lock key.
148 $latest = $title->getLatestRevID( Title::GAID_FOR_UPDATE );
149
150 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
151 // Fetch the specified revision; lockAndGetLatest() below detects if the page
152 // was edited since and aborts in order to avoid corrupting the link tables
153 $revision = Revision::newFromId(
154 $this->params['triggeringRevisionId'],
155 Revision::READ_LATEST
156 );
157 } else {
158 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
159 $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
160 }
161
162 if ( !$revision ) {
163 $stats->increment( 'refreshlinks.rev_not_found' );
164 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
165 return false; // just deleted?
166 } elseif ( $revision->getId() != $latest || $revision->getPage() !== $page->getId() ) {
167 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
168 // serialized, it would be OK to update links based on older revisions since it
169 // would eventually get to the latest. Since that is not the case (by design),
170 // only update the link tables to a state matching the current revision's output.
171 $stats->increment( 'refreshlinks.rev_not_current' );
172 $this->setLastError( "Revision {$revision->getId()} is not current" );
173 return false;
174 }
175
176 $content = $revision->getContent( Revision::RAW );
177 if ( !$content ) {
178 // If there is no content, pretend the content is empty
179 $content = $revision->getContentHandler()->makeEmptyContent();
180 }
181
182 $parserOutput = false;
183 $parserOptions = $page->makeParserOptions( 'canonical' );
184 // If page_touched changed after this root job, then it is likely that
185 // any views of the pages already resulted in re-parses which are now in
186 // cache. The cache can be reused to avoid expensive parsing in some cases.
187 if ( isset( $this->params['rootJobTimestamp'] ) ) {
188 $opportunistic = !empty( $this->params['isOpportunistic'] );
189
190 $skewedTimestamp = $this->params['rootJobTimestamp'];
191 if ( $opportunistic ) {
192 // Neither clock skew nor DB snapshot/replica DB lag matter much for such
193 // updates; focus on reusing the (often recently updated) cache
194 } else {
195 // For transclusion updates, the template changes must be reflected
196 $skewedTimestamp = wfTimestamp( TS_MW,
197 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
198 );
199 }
200
201 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
202 // Something already updated the backlinks since this job was made
203 $stats->increment( 'refreshlinks.update_skipped' );
204 return true;
205 }
206
207 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
208 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
209 // and it reflects the job's triggering change, then it is usable.
210 $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
211 if ( !$parserOutput
212 || $parserOutput->getCacheRevisionId() != $revision->getId()
213 || $parserOutput->getCacheTime() < $skewedTimestamp
214 ) {
215 $parserOutput = false; // too stale
216 }
217 }
218 }
219
220 // Fetch the current revision and parse it if necessary...
221 if ( $parserOutput ) {
222 $stats->increment( 'refreshlinks.parser_cached' );
223 } else {
224 $start = microtime( true );
225 // Revision ID must be passed to the parser output to get revision variables correct
226 $parserOutput = $content->getParserOutput(
227 $title, $revision->getId(), $parserOptions, false );
228 $elapsed = microtime( true ) - $start;
229 // If it took a long time to render, then save this back to the cache to avoid
230 // wasted CPU by other apaches or job runners. We don't want to always save to
231 // cache as this can cause high cache I/O and LRU churn when a template changes.
232 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
233 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
234 && $parserOutput->isCacheable()
235 ) {
236 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
237 ParserCache::singleton()->save(
238 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
239 );
240 }
241 $stats->increment( 'refreshlinks.parser_uncached' );
242 }
243
244 $updates = $content->getSecondaryDataUpdates(
245 $title,
246 null,
247 !empty( $this->params['useRecursiveLinksUpdate'] ),
248 $parserOutput
249 );
250
251 // For legacy hook handlers doing updates via LinksUpdateConstructed, make sure
252 // any pending writes they made get flushed before the doUpdate() calls below.
253 // This avoids snapshot-clearing errors in LinksUpdate::acquirePageLock().
254 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
255
256 foreach ( $updates as $update ) {
257 // FIXME: This code probably shouldn't be here?
258 // Needed by things like Echo notifications which need
259 // to know which user caused the links update
260 if ( $update instanceof LinksUpdate ) {
261 $update->setRevision( $revision );
262 if ( !empty( $this->params['triggeringUser'] ) ) {
263 $userInfo = $this->params['triggeringUser'];
264 if ( $userInfo['userId'] ) {
265 $user = User::newFromId( $userInfo['userId'] );
266 } else {
267 // Anonymous, use the username
268 $user = User::newFromName( $userInfo['userName'], false );
269 }
270 $update->setTriggeringUser( $user );
271 }
272 }
273 }
274
275 foreach ( $updates as $update ) {
276 $update->setTransactionTicket( $ticket );
277 $update->doUpdate();
278 }
279
280 InfoAction::invalidateCache( $title );
281
282 return true;
283 }
284
285 public function getDeduplicationInfo() {
286 $info = parent::getDeduplicationInfo();
287 if ( is_array( $info['params'] ) ) {
288 // For per-pages jobs, the job title is that of the template that changed
289 // (or similar), so remove that since it ruins duplicate detection
290 if ( isset( $info['pages'] ) ) {
291 unset( $info['namespace'] );
292 unset( $info['title'] );
293 }
294 }
295
296 return $info;
297 }
298
299 public function workItemCount() {
300 return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
301 }
302 }