Use display name in category page subheadings if provided
[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
25 /**
26 * Job to update link tables for pages
27 *
28 * This job comes in a few variants:
29 * - a) Recursive jobs to update links for backlink pages for a given title.
30 * These jobs have (recursive:true,table:<table>) set.
31 * - b) Jobs to update links for a set of pages (the job title is ignored).
32 * These jobs have (pages:(<page ID>:(<namespace>,<title>),...) set.
33 * - c) Jobs to update links for a single page (the job title)
34 * These jobs need no extra fields set.
35 *
36 * @ingroup JobQueue
37 */
38 class RefreshLinksJob extends Job {
39 /** @var float Cache parser output when it takes this long to render */
40 const PARSE_THRESHOLD_SEC = 1.0;
41 /** @var integer Lag safety margin when comparing root job times to last-refresh times */
42 const CLOCK_FUDGE = 10;
43
44 function __construct( Title $title, array $params ) {
45 parent::__construct( 'refreshLinks', $title, $params );
46 // Avoid the overhead of de-duplication when it would be pointless
47 $this->removeDuplicates = (
48 // Master positions won't match
49 !isset( $params['masterPos'] ) &&
50 // Ranges rarely will line up
51 !isset( $params['range'] ) &&
52 // Multiple pages per job make matches unlikely
53 !( isset( $params['pages'] ) && count( $params['pages'] ) != 1 )
54 );
55 }
56
57 /**
58 * @param Title $title
59 * @param array $params
60 * @return RefreshLinksJob
61 */
62 public static function newPrioritized( Title $title, array $params ) {
63 $job = new self( $title, $params );
64 $job->command = 'refreshLinksPrioritized';
65
66 return $job;
67 }
68
69 /**
70 * @param Title $title
71 * @param array $params
72 * @return RefreshLinksJob
73 */
74 public static function newDynamic( Title $title, array $params ) {
75 $job = new self( $title, $params );
76 $job->command = 'refreshLinksDynamic';
77
78 return $job;
79 }
80
81 function run() {
82 global $wgUpdateRowsPerJob;
83
84 // Job to update all (or a range of) backlink pages for a page
85 if ( !empty( $this->params['recursive'] ) ) {
86 // Carry over information for de-duplication
87 $extraParams = $this->getRootJobParams();
88 // Avoid slave lag when fetching templates.
89 // When the outermost job is run, we know that the caller that enqueued it must have
90 // committed the relevant changes to the DB by now. At that point, record the master
91 // position and pass it along as the job recursively breaks into smaller range jobs.
92 // Hopefully, when leaf jobs are popped, the slaves will have reached that position.
93 if ( isset( $this->params['masterPos'] ) ) {
94 $extraParams['masterPos'] = $this->params['masterPos'];
95 } elseif ( wfGetLB()->getServerCount() > 1 ) {
96 $extraParams['masterPos'] = wfGetLB()->getMasterPos();
97 } else {
98 $extraParams['masterPos'] = false;
99 }
100 $extraParams['triggeredRecursive'] = true;
101 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
102 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
103 $jobs = BacklinkJobUtils::partitionBacklinkJob(
104 $this,
105 $wgUpdateRowsPerJob,
106 1, // job-per-title
107 [ 'params' => $extraParams ]
108 );
109 JobQueueGroup::singleton()->push( $jobs );
110 // Job to update link tables for a set of titles
111 } elseif ( isset( $this->params['pages'] ) ) {
112 $this->waitForMasterPosition();
113 foreach ( $this->params['pages'] as $pageId => $nsAndKey ) {
114 list( $ns, $dbKey ) = $nsAndKey;
115 $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
116 }
117 // Job to update link tables for a given title
118 } else {
119 $this->waitForMasterPosition();
120 $this->runForTitle( $this->title );
121 }
122
123 return true;
124 }
125
126 protected function waitForMasterPosition() {
127 if ( !empty( $this->params['masterPos'] ) && wfGetLB()->getServerCount() > 1 ) {
128 // Wait for the current/next slave DB handle to catch up to the master.
129 // This way, we get the correct page_latest for templates or files that just
130 // changed milliseconds ago, having triggered this job to begin with.
131 wfGetLB()->waitFor( $this->params['masterPos'] );
132 }
133 }
134
135 /**
136 * @param Title $title
137 * @return bool
138 */
139 protected function runForTitle( Title $title ) {
140 $page = WikiPage::factory( $title );
141 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
142 // Fetch the specified revision; lockAndGetLatest() below detects if the page
143 // was edited since and aborts in order to avoid corrupting the link tables
144 $revision = Revision::newFromId(
145 $this->params['triggeringRevisionId'],
146 Revision::READ_LATEST
147 );
148 } else {
149 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
150 $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
151 }
152
153 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
154
155 if ( !$revision ) {
156 $stats->increment( 'refreshlinks.rev_not_found' );
157 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
158 return false; // just deleted?
159 } elseif ( !$revision->isCurrent() ) {
160 // If the revision isn't current, there's no point in doing a bunch
161 // of work just to fail at the lockAndGetLatest() check later.
162 $stats->increment( 'refreshlinks.rev_not_current' );
163 $this->setLastError( "Revision {$revision->getId()} is not current" );
164 return false;
165 }
166
167 $content = $revision->getContent( Revision::RAW );
168 if ( !$content ) {
169 // If there is no content, pretend the content is empty
170 $content = $revision->getContentHandler()->makeEmptyContent();
171 }
172
173 $parserOutput = false;
174 $parserOptions = $page->makeParserOptions( 'canonical' );
175 // If page_touched changed after this root job, then it is likely that
176 // any views of the pages already resulted in re-parses which are now in
177 // cache. The cache can be reused to avoid expensive parsing in some cases.
178 if ( isset( $this->params['rootJobTimestamp'] ) ) {
179 $opportunistic = !empty( $this->params['isOpportunistic'] );
180
181 $skewedTimestamp = $this->params['rootJobTimestamp'];
182 if ( $opportunistic ) {
183 // Neither clock skew nor DB snapshot/slave lag matter much for such
184 // updates; focus on reusing the (often recently updated) cache
185 } else {
186 // For transclusion updates, the template changes must be reflected
187 $skewedTimestamp = wfTimestamp( TS_MW,
188 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
189 );
190 }
191
192 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
193 // Something already updated the backlinks since this job was made
194 $stats->increment( 'refreshlinks.update_skipped' );
195 return true;
196 }
197
198 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
199 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
200 // and it reflects the job's triggering change, then it is usable.
201 $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
202 if ( !$parserOutput
203 || $parserOutput->getCacheRevisionId() != $revision->getId()
204 || $parserOutput->getCacheTime() < $skewedTimestamp
205 ) {
206 $parserOutput = false; // too stale
207 }
208 }
209 }
210
211 // Fetch the current revision and parse it if necessary...
212 if ( $parserOutput ) {
213 $stats->increment( 'refreshlinks.parser_cached' );
214 } else {
215 $start = microtime( true );
216 // Revision ID must be passed to the parser output to get revision variables correct
217 $parserOutput = $content->getParserOutput(
218 $title, $revision->getId(), $parserOptions, false );
219 $elapsed = microtime( true ) - $start;
220 // If it took a long time to render, then save this back to the cache to avoid
221 // wasted CPU by other apaches or job runners. We don't want to always save to
222 // cache as this can cause high cache I/O and LRU churn when a template changes.
223 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
224 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
225 && $parserOutput->isCacheable()
226 ) {
227 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
228 ParserCache::singleton()->save(
229 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
230 );
231 }
232 $stats->increment( 'refreshlinks.parser_uncached' );
233 }
234
235 $updates = $content->getSecondaryDataUpdates(
236 $title,
237 null,
238 !empty( $this->params['useRecursiveLinksUpdate'] ),
239 $parserOutput
240 );
241
242 foreach ( $updates as $key => $update ) {
243 // FIXME: This code probably shouldn't be here?
244 // Needed by things like Echo notifications which need
245 // to know which user caused the links update
246 if ( $update instanceof LinksUpdate ) {
247 $update->setRevision( $revision );
248 if ( !empty( $this->params['triggeringUser'] ) ) {
249 $userInfo = $this->params['triggeringUser'];
250 if ( $userInfo['userId'] ) {
251 $user = User::newFromId( $userInfo['userId'] );
252 } else {
253 // Anonymous, use the username
254 $user = User::newFromName( $userInfo['userName'], false );
255 }
256 $update->setTriggeringUser( $user );
257 }
258 }
259 }
260
261 $latestNow = $page->lockAndGetLatest();
262 if ( !$latestNow || $revision->getId() != $latestNow ) {
263 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
264 // serialized, it would be OK to update links based on older revisions since it
265 // would eventually get to the latest. Since that is not the case (by design),
266 // only update the link tables to a state matching the current revision's output.
267 $stats->increment( 'refreshlinks.rev_cas_failure' );
268 $this->setLastError( "page_latest changed from {$revision->getId()} to $latestNow" );
269 return false;
270 }
271
272 DataUpdate::runUpdates( $updates );
273
274 InfoAction::invalidateCache( $title );
275
276 return true;
277 }
278
279 public function getDeduplicationInfo() {
280 $info = parent::getDeduplicationInfo();
281 if ( is_array( $info['params'] ) ) {
282 // For per-pages jobs, the job title is that of the template that changed
283 // (or similar), so remove that since it ruins duplicate detection
284 if ( isset( $info['pages'] ) ) {
285 unset( $info['namespace'] );
286 unset( $info['title'] );
287 }
288 }
289
290 return $info;
291 }
292
293 public function workItemCount() {
294 return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
295 }
296 }