*Add BeforeGalleryFindFile, TitleLinkUpdatesAfterCompletion, BeforeParserFetchTemplat...
[lhc/web/wiklou.git] / includes / LinksUpdate.php
1 <?php
2 /**
3 * See docs/deferred.txt
4 *
5 * @todo document (e.g. one-sentence top-level class description).
6 */
7 class LinksUpdate {
8
9 /**@{{
10 * @private
11 */
12 var $mId, //!< Page ID of the article linked from
13 $mTitle, //!< Title object of the article linked from
14 $mLinks, //!< Map of title strings to IDs for the links in the document
15 $mImages, //!< DB keys of the images used, in the array key only
16 $mTemplates, //!< Map of title strings to IDs for the template references, including broken ones
17 $mExternals, //!< URLs of external links, array key only
18 $mCategories, //!< Map of category names to sort keys
19 $mInterlangs, //!< Map of language codes to titles
20 $mDb, //!< Database connection reference
21 $mOptions, //!< SELECT options to be used (array)
22 $mRecursive; //!< Whether to queue jobs for recursive updates
23 /**@}}*/
24
25 /**
26 * Constructor
27 * Initialize private variables
28 * @param $title Integer: FIXME
29 * @param $parserOutput FIXME
30 * @param $recursive Boolean: FIXME, default 'true'.
31 */
32 function LinksUpdate( $title, $parserOutput, $recursive = true ) {
33 global $wgAntiLockFlags;
34
35 if ( $wgAntiLockFlags & ALF_NO_LINK_LOCK ) {
36 $this->mOptions = array();
37 } else {
38 $this->mOptions = array( 'FOR UPDATE' );
39 }
40 $this->mDb = wfGetDB( DB_MASTER );
41
42 if ( !is_object( $title ) ) {
43 throw new MWException( "The calling convention to LinksUpdate::LinksUpdate() has changed. " .
44 "Please see Article::editUpdates() for an invocation example.\n" );
45 }
46 $this->mTitle = $title;
47 $this->mId = $title->getArticleID();
48
49 $this->mLinks = $parserOutput->getLinks();
50 $this->mImages = $parserOutput->getImages();
51 $this->mTemplates = $parserOutput->getTemplates();
52 $this->mExternals = $parserOutput->getExternalLinks();
53 $this->mCategories = $parserOutput->getCategories();
54
55 # Convert the format of the interlanguage links
56 # I didn't want to change it in the ParserOutput, because that array is passed all
57 # the way back to the skin, so either a skin API break would be required, or an
58 # inefficient back-conversion.
59 $ill = $parserOutput->getLanguageLinks();
60 $this->mInterlangs = array();
61 foreach ( $ill as $link ) {
62 list( $key, $title ) = explode( ':', $link, 2 );
63 $this->mInterlangs[$key] = $title;
64 }
65
66 $this->mRecursive = $recursive;
67 }
68
69 /**
70 * Update link tables with outgoing links from an updated article
71 */
72 function doUpdate() {
73 global $wgUseDumbLinkUpdate;
74 if ( $wgUseDumbLinkUpdate ) {
75 $this->doDumbUpdate();
76 } else {
77 $this->doIncrementalUpdate();
78 }
79 wfRunHooks( 'TitleLinkUpdatesAfterCompletion', array( &$this->mTitle ) );
80 }
81
82 function doIncrementalUpdate() {
83 $fname = 'LinksUpdate::doIncrementalUpdate';
84 wfProfileIn( $fname );
85
86 # Page links
87 $existing = $this->getExistingLinks();
88 $this->incrTableUpdate( 'pagelinks', 'pl', $this->getLinkDeletions( $existing ),
89 $this->getLinkInsertions( $existing ) );
90
91 # Image links
92 $existing = $this->getExistingImages();
93 $this->incrTableUpdate( 'imagelinks', 'il', $this->getImageDeletions( $existing ),
94 $this->getImageInsertions( $existing ) );
95
96 # Invalidate all image description pages which had links added or removed
97 $imageUpdates = array_diff_key( $existing, $this->mImages ) + array_diff_key( $this->mImages, $existing );
98 $this->invalidateImageDescriptions( $imageUpdates );
99
100 # External links
101 $existing = $this->getExistingExternals();
102 $this->incrTableUpdate( 'externallinks', 'el', $this->getExternalDeletions( $existing ),
103 $this->getExternalInsertions( $existing ) );
104
105 # Language links
106 $existing = $this->getExistingInterlangs();
107 $this->incrTableUpdate( 'langlinks', 'll', $this->getInterlangDeletions( $existing ),
108 $this->getInterlangInsertions( $existing ) );
109
110 # Template links
111 $existing = $this->getExistingTemplates();
112 $this->incrTableUpdate( 'templatelinks', 'tl', $this->getTemplateDeletions( $existing ),
113 $this->getTemplateInsertions( $existing ) );
114
115 # Category links
116 $existing = $this->getExistingCategories();
117 $this->incrTableUpdate( 'categorylinks', 'cl', $this->getCategoryDeletions( $existing ),
118 $this->getCategoryInsertions( $existing ) );
119
120 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
121 $categoryUpdates = array_diff_assoc( $existing, $this->mCategories ) + array_diff_assoc( $this->mCategories, $existing );
122 $this->invalidateCategories( $categoryUpdates );
123
124 # Refresh links of all pages including this page
125 # This will be in a separate transaction
126 if ( $this->mRecursive ) {
127 $this->queueRecursiveJobs();
128 }
129
130 wfProfileOut( $fname );
131 }
132
133 /**
134 * Link update which clears the previous entries and inserts new ones
135 * May be slower or faster depending on level of lock contention and write speed of DB
136 * Also useful where link table corruption needs to be repaired, e.g. in refreshLinks.php
137 */
138 function doDumbUpdate() {
139 $fname = 'LinksUpdate::doDumbUpdate';
140 wfProfileIn( $fname );
141
142 # Refresh category pages and image description pages
143 $existing = $this->getExistingCategories();
144 $categoryUpdates = array_diff_assoc( $existing, $this->mCategories ) + array_diff_assoc( $this->mCategories, $existing );
145 $existing = $this->getExistingImages();
146 $imageUpdates = array_diff_key( $existing, $this->mImages ) + array_diff_key( $this->mImages, $existing );
147
148 $this->dumbTableUpdate( 'pagelinks', $this->getLinkInsertions(), 'pl_from' );
149 $this->dumbTableUpdate( 'imagelinks', $this->getImageInsertions(), 'il_from' );
150 $this->dumbTableUpdate( 'categorylinks', $this->getCategoryInsertions(), 'cl_from' );
151 $this->dumbTableUpdate( 'templatelinks', $this->getTemplateInsertions(), 'tl_from' );
152 $this->dumbTableUpdate( 'externallinks', $this->getExternalInsertions(), 'el_from' );
153 $this->dumbTableUpdate( 'langlinks', $this->getInterlangInsertions(), 'll_from' );
154
155 # Update the cache of all the category pages and image description pages which were changed
156 $this->invalidateCategories( $categoryUpdates );
157 $this->invalidateImageDescriptions( $imageUpdates );
158
159 # Refresh links of all pages including this page
160 # This will be in a separate transaction
161 if ( $this->mRecursive ) {
162 $this->queueRecursiveJobs();
163 }
164
165 wfProfileOut( $fname );
166 }
167
168 function queueRecursiveJobs() {
169 wfProfileIn( __METHOD__ );
170
171 $batchSize = 100;
172 $dbr = wfGetDB( DB_SLAVE );
173 $res = $dbr->select( array( 'templatelinks', 'page' ),
174 array( 'page_namespace', 'page_title' ),
175 array(
176 'page_id=tl_from',
177 'tl_namespace' => $this->mTitle->getNamespace(),
178 'tl_title' => $this->mTitle->getDBkey()
179 ), __METHOD__
180 );
181
182 $done = false;
183 while ( !$done ) {
184 $jobs = array();
185 for ( $i = 0; $i < $batchSize; $i++ ) {
186 $row = $dbr->fetchObject( $res );
187 if ( !$row ) {
188 $done = true;
189 break;
190 }
191 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
192 $jobs[] = Job::factory( 'refreshLinks', $title );
193 }
194 Job::batchInsert( $jobs );
195 }
196 $dbr->freeResult( $res );
197 wfProfileOut( __METHOD__ );
198 }
199
200 /**
201 * Invalidate the cache of a list of pages from a single namespace
202 *
203 * @param integer $namespace
204 * @param array $dbkeys
205 */
206 function invalidatePages( $namespace, $dbkeys ) {
207 $fname = 'LinksUpdate::invalidatePages';
208
209 if ( !count( $dbkeys ) ) {
210 return;
211 }
212
213 /**
214 * Determine which pages need to be updated
215 * This is necessary to prevent the job queue from smashing the DB with
216 * large numbers of concurrent invalidations of the same page
217 */
218 $now = $this->mDb->timestamp();
219 $ids = array();
220 $res = $this->mDb->select( 'page', array( 'page_id' ),
221 array(
222 'page_namespace' => $namespace,
223 'page_title IN (' . $this->mDb->makeList( $dbkeys ) . ')',
224 'page_touched < ' . $this->mDb->addQuotes( $now )
225 ), $fname
226 );
227 while ( $row = $this->mDb->fetchObject( $res ) ) {
228 $ids[] = $row->page_id;
229 }
230 if ( !count( $ids ) ) {
231 return;
232 }
233
234 /**
235 * Do the update
236 * We still need the page_touched condition, in case the row has changed since
237 * the non-locking select above.
238 */
239 $this->mDb->update( 'page', array( 'page_touched' => $now ),
240 array(
241 'page_id IN (' . $this->mDb->makeList( $ids ) . ')',
242 'page_touched < ' . $this->mDb->addQuotes( $now )
243 ), $fname
244 );
245 }
246
247 function invalidateCategories( $cats ) {
248 $this->invalidatePages( NS_CATEGORY, array_keys( $cats ) );
249 }
250
251 function invalidateImageDescriptions( $images ) {
252 $this->invalidatePages( NS_IMAGE, array_keys( $images ) );
253 }
254
255 function dumbTableUpdate( $table, $insertions, $fromField ) {
256 $fname = 'LinksUpdate::dumbTableUpdate';
257 $this->mDb->delete( $table, array( $fromField => $this->mId ), $fname );
258 if ( count( $insertions ) ) {
259 # The link array was constructed without FOR UPDATE, so there may be collisions
260 # This may cause minor link table inconsistencies, which is better than
261 # crippling the site with lock contention.
262 $this->mDb->insert( $table, $insertions, $fname, array( 'IGNORE' ) );
263 }
264 }
265
266 /**
267 * Make a WHERE clause from a 2-d NS/dbkey array
268 *
269 * @param array $arr 2-d array indexed by namespace and DB key
270 * @param string $prefix Field name prefix, without the underscore
271 */
272 function makeWhereFrom2d( &$arr, $prefix ) {
273 $lb = new LinkBatch;
274 $lb->setArray( $arr );
275 return $lb->constructSet( $prefix, $this->mDb );
276 }
277
278 /**
279 * Update a table by doing a delete query then an insert query
280 * @private
281 */
282 function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
283 $fname = 'LinksUpdate::incrTableUpdate';
284 $where = array( "{$prefix}_from" => $this->mId );
285 if ( $table == 'pagelinks' || $table == 'templatelinks' ) {
286 $clause = $this->makeWhereFrom2d( $deletions, $prefix );
287 if ( $clause ) {
288 $where[] = $clause;
289 } else {
290 $where = false;
291 }
292 } else {
293 if ( $table == 'langlinks' ) {
294 $toField = 'll_lang';
295 } else {
296 $toField = $prefix . '_to';
297 }
298 if ( count( $deletions ) ) {
299 $where[] = "$toField IN (" . $this->mDb->makeList( array_keys( $deletions ) ) . ')';
300 } else {
301 $where = false;
302 }
303 }
304 if ( $where ) {
305 $this->mDb->delete( $table, $where, $fname );
306 }
307 if ( count( $insertions ) ) {
308 $this->mDb->insert( $table, $insertions, $fname, 'IGNORE' );
309 }
310 }
311
312
313 /**
314 * Get an array of pagelinks insertions for passing to the DB
315 * Skips the titles specified by the 2-D array $existing
316 * @private
317 */
318 function getLinkInsertions( $existing = array() ) {
319 $arr = array();
320 foreach( $this->mLinks as $ns => $dbkeys ) {
321 # array_diff_key() was introduced in PHP 5.1, there is a compatibility function
322 # in GlobalFunctions.php
323 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
324 foreach ( $diffs as $dbk => $id ) {
325 $arr[] = array(
326 'pl_from' => $this->mId,
327 'pl_namespace' => $ns,
328 'pl_title' => $dbk
329 );
330 }
331 }
332 return $arr;
333 }
334
335 /**
336 * Get an array of template insertions. Like getLinkInsertions()
337 * @private
338 */
339 function getTemplateInsertions( $existing = array() ) {
340 $arr = array();
341 foreach( $this->mTemplates as $ns => $dbkeys ) {
342 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
343 foreach ( $diffs as $dbk => $id ) {
344 $arr[] = array(
345 'tl_from' => $this->mId,
346 'tl_namespace' => $ns,
347 'tl_title' => $dbk
348 );
349 }
350 }
351 return $arr;
352 }
353
354 /**
355 * Get an array of image insertions
356 * Skips the names specified in $existing
357 * @private
358 */
359 function getImageInsertions( $existing = array() ) {
360 $arr = array();
361 $diffs = array_diff_key( $this->mImages, $existing );
362 foreach( $diffs as $iname => $dummy ) {
363 $arr[] = array(
364 'il_from' => $this->mId,
365 'il_to' => $iname
366 );
367 }
368 return $arr;
369 }
370
371 /**
372 * Get an array of externallinks insertions. Skips the names specified in $existing
373 * @private
374 */
375 function getExternalInsertions( $existing = array() ) {
376 $arr = array();
377 $diffs = array_diff_key( $this->mExternals, $existing );
378 foreach( $diffs as $url => $dummy ) {
379 $arr[] = array(
380 'el_from' => $this->mId,
381 'el_to' => $url,
382 'el_index' => wfMakeUrlIndex( $url ),
383 );
384 }
385 return $arr;
386 }
387
388 /**
389 * Get an array of category insertions
390 * @param array $existing Array mapping existing category names to sort keys. If both
391 * match a link in $this, the link will be omitted from the output
392 * @private
393 */
394 function getCategoryInsertions( $existing = array() ) {
395 $diffs = array_diff_assoc( $this->mCategories, $existing );
396 $arr = array();
397 foreach ( $diffs as $name => $sortkey ) {
398 $arr[] = array(
399 'cl_from' => $this->mId,
400 'cl_to' => $name,
401 'cl_sortkey' => $sortkey,
402 'cl_timestamp' => $this->mDb->timestamp()
403 );
404 }
405 return $arr;
406 }
407
408 /**
409 * Get an array of interlanguage link insertions
410 * @param array $existing Array mapping existing language codes to titles
411 * @private
412 */
413 function getInterlangInsertions( $existing = array() ) {
414 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
415 $arr = array();
416 foreach( $diffs as $lang => $title ) {
417 $arr[] = array(
418 'll_from' => $this->mId,
419 'll_lang' => $lang,
420 'll_title' => $title
421 );
422 }
423 return $arr;
424 }
425
426 /**
427 * Given an array of existing links, returns those links which are not in $this
428 * and thus should be deleted.
429 * @private
430 */
431 function getLinkDeletions( $existing ) {
432 $del = array();
433 foreach ( $existing as $ns => $dbkeys ) {
434 if ( isset( $this->mLinks[$ns] ) ) {
435 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
436 } else {
437 $del[$ns] = $existing[$ns];
438 }
439 }
440 return $del;
441 }
442
443 /**
444 * Given an array of existing templates, returns those templates which are not in $this
445 * and thus should be deleted.
446 * @private
447 */
448 function getTemplateDeletions( $existing ) {
449 $del = array();
450 foreach ( $existing as $ns => $dbkeys ) {
451 if ( isset( $this->mTemplates[$ns] ) ) {
452 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
453 } else {
454 $del[$ns] = $existing[$ns];
455 }
456 }
457 return $del;
458 }
459
460 /**
461 * Given an array of existing images, returns those images which are not in $this
462 * and thus should be deleted.
463 * @private
464 */
465 function getImageDeletions( $existing ) {
466 return array_diff_key( $existing, $this->mImages );
467 }
468
469 /**
470 * Given an array of existing external links, returns those links which are not
471 * in $this and thus should be deleted.
472 * @private
473 */
474 function getExternalDeletions( $existing ) {
475 return array_diff_key( $existing, $this->mExternals );
476 }
477
478 /**
479 * Given an array of existing categories, returns those categories which are not in $this
480 * and thus should be deleted.
481 * @private
482 */
483 function getCategoryDeletions( $existing ) {
484 return array_diff_assoc( $existing, $this->mCategories );
485 }
486
487 /**
488 * Given an array of existing interlanguage links, returns those links which are not
489 * in $this and thus should be deleted.
490 * @private
491 */
492 function getInterlangDeletions( $existing ) {
493 return array_diff_assoc( $existing, $this->mInterlangs );
494 }
495
496 /**
497 * Get an array of existing links, as a 2-D array
498 * @private
499 */
500 function getExistingLinks() {
501 $fname = 'LinksUpdate::getExistingLinks';
502 $res = $this->mDb->select( 'pagelinks', array( 'pl_namespace', 'pl_title' ),
503 array( 'pl_from' => $this->mId ), $fname, $this->mOptions );
504 $arr = array();
505 while ( $row = $this->mDb->fetchObject( $res ) ) {
506 if ( !isset( $arr[$row->pl_namespace] ) ) {
507 $arr[$row->pl_namespace] = array();
508 }
509 $arr[$row->pl_namespace][$row->pl_title] = 1;
510 }
511 $this->mDb->freeResult( $res );
512 return $arr;
513 }
514
515 /**
516 * Get an array of existing templates, as a 2-D array
517 * @private
518 */
519 function getExistingTemplates() {
520 $fname = 'LinksUpdate::getExistingTemplates';
521 $res = $this->mDb->select( 'templatelinks', array( 'tl_namespace', 'tl_title' ),
522 array( 'tl_from' => $this->mId ), $fname, $this->mOptions );
523 $arr = array();
524 while ( $row = $this->mDb->fetchObject( $res ) ) {
525 if ( !isset( $arr[$row->tl_namespace] ) ) {
526 $arr[$row->tl_namespace] = array();
527 }
528 $arr[$row->tl_namespace][$row->tl_title] = 1;
529 }
530 $this->mDb->freeResult( $res );
531 return $arr;
532 }
533
534 /**
535 * Get an array of existing images, image names in the keys
536 * @private
537 */
538 function getExistingImages() {
539 $fname = 'LinksUpdate::getExistingImages';
540 $res = $this->mDb->select( 'imagelinks', array( 'il_to' ),
541 array( 'il_from' => $this->mId ), $fname, $this->mOptions );
542 $arr = array();
543 while ( $row = $this->mDb->fetchObject( $res ) ) {
544 $arr[$row->il_to] = 1;
545 }
546 $this->mDb->freeResult( $res );
547 return $arr;
548 }
549
550 /**
551 * Get an array of existing external links, URLs in the keys
552 * @private
553 */
554 function getExistingExternals() {
555 $fname = 'LinksUpdate::getExistingExternals';
556 $res = $this->mDb->select( 'externallinks', array( 'el_to' ),
557 array( 'el_from' => $this->mId ), $fname, $this->mOptions );
558 $arr = array();
559 while ( $row = $this->mDb->fetchObject( $res ) ) {
560 $arr[$row->el_to] = 1;
561 }
562 $this->mDb->freeResult( $res );
563 return $arr;
564 }
565
566 /**
567 * Get an array of existing categories, with the name in the key and sort key in the value.
568 * @private
569 */
570 function getExistingCategories() {
571 $fname = 'LinksUpdate::getExistingCategories';
572 $res = $this->mDb->select( 'categorylinks', array( 'cl_to', 'cl_sortkey' ),
573 array( 'cl_from' => $this->mId ), $fname, $this->mOptions );
574 $arr = array();
575 while ( $row = $this->mDb->fetchObject( $res ) ) {
576 $arr[$row->cl_to] = $row->cl_sortkey;
577 }
578 $this->mDb->freeResult( $res );
579 return $arr;
580 }
581
582 /**
583 * Get an array of existing interlanguage links, with the language code in the key and the
584 * title in the value.
585 * @private
586 */
587 function getExistingInterlangs() {
588 $fname = 'LinksUpdate::getExistingInterlangs';
589 $res = $this->mDb->select( 'langlinks', array( 'll_lang', 'll_title' ),
590 array( 'll_from' => $this->mId ), $fname, $this->mOptions );
591 $arr = array();
592 while ( $row = $this->mDb->fetchObject( $res ) ) {
593 $arr[$row->ll_lang] = $row->ll_title;
594 }
595 return $arr;
596 }
597 }
598 ?>