ISO 8601 timestamps can have decimal seconds
[mediawiki.git] / includes / LinksUpdate.php
blob4b8f6d6f1dff4b916c83c91704d44a9441a9a3f2
1 <?php
2 /**
3 * See docs/deferred.txt
5 * @todo document (e.g. one-sentence top-level class description).
6 */
7 class LinksUpdate {
9 /**@{{
10 * @private
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 $mProperties, //!< Map of arbitrary name to value
21 $mDb, //!< Database connection reference
22 $mOptions, //!< SELECT options to be used (array)
23 $mRecursive, //!< Whether to queue jobs for recursive updates
24 $mTouchTmplLinks; //!< Whether to queue HTMLCacheUpdate jobs IF recursive
25 /**@}}*/
27 /**
28 * Constructor
30 * @param Title $title Title of the page we're updating
31 * @param ParserOutput $parserOutput Output from a full parse of this page
32 * @param bool $recursive Queue jobs for recursive updates?
34 function LinksUpdate( $title, $parserOutput, $recursive = true ) {
35 global $wgAntiLockFlags;
37 if ( $wgAntiLockFlags & ALF_NO_LINK_LOCK ) {
38 $this->mOptions = array();
39 } else {
40 $this->mOptions = array( 'FOR UPDATE' );
42 $this->mDb = wfGetDB( DB_MASTER );
44 if ( !is_object( $title ) ) {
45 throw new MWException( "The calling convention to LinksUpdate::LinksUpdate() has changed. " .
46 "Please see Article::editUpdates() for an invocation example.\n" );
48 $this->mTitle = $title;
49 $this->mId = $title->getArticleID();
51 $this->mParserOutput = $parserOutput;
52 $this->mLinks = $parserOutput->getLinks();
53 $this->mImages = $parserOutput->getImages();
54 $this->mTemplates = $parserOutput->getTemplates();
55 $this->mExternals = $parserOutput->getExternalLinks();
56 $this->mCategories = $parserOutput->getCategories();
57 $this->mProperties = $parserOutput->getProperties();
59 # Convert the format of the interlanguage links
60 # I didn't want to change it in the ParserOutput, because that array is passed all
61 # the way back to the skin, so either a skin API break would be required, or an
62 # inefficient back-conversion.
63 $ill = $parserOutput->getLanguageLinks();
64 $this->mInterlangs = array();
65 foreach ( $ill as $link ) {
66 list( $key, $title ) = explode( ':', $link, 2 );
67 $this->mInterlangs[$key] = $title;
70 $this->mRecursive = $recursive;
71 $this->mTouchTmplLinks = false;
73 wfRunHooks( 'LinksUpdateConstructed', array( &$this ) );
76 /**
77 * Invalidate HTML cache of pages that include this page?
79 public function setRecursiveTouch( $val ) {
80 $this->mTouchTmplLinks = (bool)$val;
81 if( $val ) // Cannot invalidate without queueRecursiveJobs()
82 $this->mRecursive = true;
85 /**
86 * Update link tables with outgoing links from an updated article
88 public function doUpdate() {
89 global $wgUseDumbLinkUpdate;
91 wfRunHooks( 'LinksUpdate', array( &$this ) );
92 if ( $wgUseDumbLinkUpdate ) {
93 $this->doDumbUpdate();
94 } else {
95 $this->doIncrementalUpdate();
97 wfRunHooks( 'LinksUpdateComplete', array( &$this ) );
101 protected function doIncrementalUpdate() {
102 wfProfileIn( __METHOD__ );
104 # Page links
105 $existing = $this->getExistingLinks();
106 $this->incrTableUpdate( 'pagelinks', 'pl', $this->getLinkDeletions( $existing ),
107 $this->getLinkInsertions( $existing ) );
109 # Image links
110 $existing = $this->getExistingImages();
112 $imageDeletes = $this->getImageDeletions( $existing );
113 $this->incrTableUpdate( 'imagelinks', 'il', $imageDeletes, $this->getImageInsertions( $existing ) );
115 # Invalidate all image description pages which had links added or removed
116 $imageUpdates = $imageDeletes + array_diff_key( $this->mImages, $existing );
117 $this->invalidateImageDescriptions( $imageUpdates );
119 # External links
120 $existing = $this->getExistingExternals();
121 $this->incrTableUpdate( 'externallinks', 'el', $this->getExternalDeletions( $existing ),
122 $this->getExternalInsertions( $existing ) );
124 # Language links
125 $existing = $this->getExistingInterlangs();
126 $this->incrTableUpdate( 'langlinks', 'll', $this->getInterlangDeletions( $existing ),
127 $this->getInterlangInsertions( $existing ) );
129 # Template links
130 $existing = $this->getExistingTemplates();
131 $this->incrTableUpdate( 'templatelinks', 'tl', $this->getTemplateDeletions( $existing ),
132 $this->getTemplateInsertions( $existing ) );
134 # Category links
135 $existing = $this->getExistingCategories();
137 $categoryDeletes = $this->getCategoryDeletions( $existing );
139 $this->incrTableUpdate( 'categorylinks', 'cl', $categoryDeletes, $this->getCategoryInsertions( $existing ) );
141 # Invalidate all categories which were added, deleted or changed (set symmetric difference)
142 $categoryInserts = array_diff_assoc( $this->mCategories, $existing );
143 $categoryUpdates = $categoryInserts + $categoryDeletes;
144 $this->invalidateCategories( $categoryUpdates );
145 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
147 # Page properties
148 $existing = $this->getExistingProperties();
150 $propertiesDeletes = $this->getPropertyDeletions( $existing );
152 $this->incrTableUpdate( 'page_props', 'pp', $propertiesDeletes, $this->getPropertyInsertions( $existing ) );
154 # Invalidate the necessary pages
155 $changed = $propertiesDeletes + array_diff_assoc( $this->mProperties, $existing );
156 $this->invalidateProperties( $changed );
158 # Refresh links of all pages including this page
159 # This will be in a separate transaction
160 if ( $this->mRecursive ) {
161 $this->queueRecursiveJobs();
164 wfProfileOut( __METHOD__ );
168 * Link update which clears the previous entries and inserts new ones
169 * May be slower or faster depending on level of lock contention and write speed of DB
170 * Also useful where link table corruption needs to be repaired, e.g. in refreshLinks.php
172 protected function doDumbUpdate() {
173 wfProfileIn( __METHOD__ );
175 # Refresh category pages and image description pages
176 $existing = $this->getExistingCategories();
177 $categoryInserts = array_diff_assoc( $this->mCategories, $existing );
178 $categoryDeletes = array_diff_assoc( $existing, $this->mCategories );
179 $categoryUpdates = $categoryInserts + $categoryDeletes;
180 $existing = $this->getExistingImages();
181 $imageUpdates = array_diff_key( $existing, $this->mImages ) + array_diff_key( $this->mImages, $existing );
183 $this->dumbTableUpdate( 'pagelinks', $this->getLinkInsertions(), 'pl_from' );
184 $this->dumbTableUpdate( 'imagelinks', $this->getImageInsertions(), 'il_from' );
185 $this->dumbTableUpdate( 'categorylinks', $this->getCategoryInsertions(), 'cl_from' );
186 $this->dumbTableUpdate( 'templatelinks', $this->getTemplateInsertions(), 'tl_from' );
187 $this->dumbTableUpdate( 'externallinks', $this->getExternalInsertions(), 'el_from' );
188 $this->dumbTableUpdate( 'langlinks', $this->getInterlangInsertions(),'ll_from' );
189 $this->dumbTableUpdate( 'page_props', $this->getPropertyInsertions(), 'pp_page' );
191 # Update the cache of all the category pages and image description
192 # pages which were changed, and fix the category table count
193 $this->invalidateCategories( $categoryUpdates );
194 $this->updateCategoryCounts( $categoryInserts, $categoryDeletes );
195 $this->invalidateImageDescriptions( $imageUpdates );
197 # Refresh links of all pages including this page
198 # This will be in a separate transaction
199 if ( $this->mRecursive ) {
200 $this->queueRecursiveJobs();
203 wfProfileOut( __METHOD__ );
206 function queueRecursiveJobs() {
207 global $wgUpdateRowsPerJob;
208 wfProfileIn( __METHOD__ );
210 $dbr = wfGetDB( DB_SLAVE );
211 $res = $dbr->select( 'templatelinks',
212 array( 'tl_from' ),
213 array(
214 'tl_namespace' => $this->mTitle->getNamespace(),
215 'tl_title' => $this->mTitle->getDBkey()
216 ), __METHOD__
219 $numRows = $res->numRows();
220 if( !$numRows ) {
221 wfProfileOut( __METHOD__ );
222 return; // nothing to do
224 $numBatches = ceil( $numRows / $wgUpdateRowsPerJob );
225 $realBatchSize = $numRows / $numBatches;
226 $start = false;
227 $jobs = array();
228 do {
229 for( $i = 0; $i <= $realBatchSize - 1; $i++ ) {
230 $row = $res->fetchRow();
231 if( $row ) {
232 $id = $row[0];
233 } else {
234 $id = false;
235 break;
238 $params = array(
239 'start' => $start,
240 'end' => ( $id !== false ? $id - 1 : false ),
242 $jobs[] = new RefreshLinksJob2( $this->mTitle, $params );
243 # Hit page caches while we're at it if set to do so...
244 if( $this->mTouchTmplLinks ) {
245 $params['table'] = 'templatelinks';
246 $jobs[] = new HTMLCacheUpdateJob( $this->mTitle, $params );
248 $start = $id;
249 } while ( $start );
251 $dbr->freeResult( $res );
253 Job::batchInsert( $jobs );
255 wfProfileOut( __METHOD__ );
259 * Invalidate the cache of a list of pages from a single namespace
261 * @param integer $namespace
262 * @param array $dbkeys
264 function invalidatePages( $namespace, $dbkeys ) {
265 if ( !count( $dbkeys ) ) {
266 return;
270 * Determine which pages need to be updated
271 * This is necessary to prevent the job queue from smashing the DB with
272 * large numbers of concurrent invalidations of the same page
274 $now = $this->mDb->timestamp();
275 $ids = array();
276 $res = $this->mDb->select( 'page', array( 'page_id' ),
277 array(
278 'page_namespace' => $namespace,
279 'page_title IN (' . $this->mDb->makeList( $dbkeys ) . ')',
280 'page_touched < ' . $this->mDb->addQuotes( $now )
281 ), __METHOD__
283 while ( $row = $this->mDb->fetchObject( $res ) ) {
284 $ids[] = $row->page_id;
286 if ( !count( $ids ) ) {
287 return;
291 * Do the update
292 * We still need the page_touched condition, in case the row has changed since
293 * the non-locking select above.
295 $this->mDb->update( 'page', array( 'page_touched' => $now ),
296 array(
297 'page_id IN (' . $this->mDb->makeList( $ids ) . ')',
298 'page_touched < ' . $this->mDb->addQuotes( $now )
299 ), __METHOD__
303 function invalidateCategories( $cats ) {
304 $this->invalidatePages( NS_CATEGORY, array_keys( $cats ) );
308 * Update all the appropriate counts in the category table.
309 * @param $added associative array of category name => sort key
310 * @param $deleted associative array of category name => sort key
312 function updateCategoryCounts( $added, $deleted ) {
313 $a = new Article($this->mTitle);
314 $a->updateCategoryCounts(
315 array_keys( $added ), array_keys( $deleted )
319 function invalidateImageDescriptions( $images ) {
320 $this->invalidatePages( NS_IMAGE, array_keys( $images ) );
323 function dumbTableUpdate( $table, $insertions, $fromField ) {
324 $this->mDb->delete( $table, array( $fromField => $this->mId ), __METHOD__ );
325 if ( count( $insertions ) ) {
326 # The link array was constructed without FOR UPDATE, so there may
327 # be collisions. This may cause minor link table inconsistencies,
328 # which is better than crippling the site with lock contention.
329 $this->mDb->insert( $table, $insertions, __METHOD__, array( 'IGNORE' ) );
334 * Make a WHERE clause from a 2-d NS/dbkey array
336 * @param array $arr 2-d array indexed by namespace and DB key
337 * @param string $prefix Field name prefix, without the underscore
339 function makeWhereFrom2d( &$arr, $prefix ) {
340 $lb = new LinkBatch;
341 $lb->setArray( $arr );
342 return $lb->constructSet( $prefix, $this->mDb );
346 * Update a table by doing a delete query then an insert query
347 * @private
349 function incrTableUpdate( $table, $prefix, $deletions, $insertions ) {
350 if ( $table == 'page_props' ) {
351 $fromField = 'pp_page';
352 } else {
353 $fromField = "{$prefix}_from";
355 $where = array( $fromField => $this->mId );
356 if ( $table == 'pagelinks' || $table == 'templatelinks' ) {
357 $clause = $this->makeWhereFrom2d( $deletions, $prefix );
358 if ( $clause ) {
359 $where[] = $clause;
360 } else {
361 $where = false;
363 } else {
364 if ( $table == 'langlinks' ) {
365 $toField = 'll_lang';
366 } elseif ( $table == 'page_props' ) {
367 $toField = 'pp_propname';
368 } else {
369 $toField = $prefix . '_to';
371 if ( count( $deletions ) ) {
372 $where[] = "$toField IN (" . $this->mDb->makeList( array_keys( $deletions ) ) . ')';
373 } else {
374 $where = false;
377 if ( $where ) {
378 $this->mDb->delete( $table, $where, __METHOD__ );
380 if ( count( $insertions ) ) {
381 $this->mDb->insert( $table, $insertions, __METHOD__, 'IGNORE' );
387 * Get an array of pagelinks insertions for passing to the DB
388 * Skips the titles specified by the 2-D array $existing
389 * @private
391 function getLinkInsertions( $existing = array() ) {
392 $arr = array();
393 foreach( $this->mLinks as $ns => $dbkeys ) {
394 # array_diff_key() was introduced in PHP 5.1, there is a compatibility function
395 # in GlobalFunctions.php
396 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
397 foreach ( $diffs as $dbk => $id ) {
398 $arr[] = array(
399 'pl_from' => $this->mId,
400 'pl_namespace' => $ns,
401 'pl_title' => $dbk
405 return $arr;
409 * Get an array of template insertions. Like getLinkInsertions()
410 * @private
412 function getTemplateInsertions( $existing = array() ) {
413 $arr = array();
414 foreach( $this->mTemplates as $ns => $dbkeys ) {
415 $diffs = isset( $existing[$ns] ) ? array_diff_key( $dbkeys, $existing[$ns] ) : $dbkeys;
416 foreach ( $diffs as $dbk => $id ) {
417 $arr[] = array(
418 'tl_from' => $this->mId,
419 'tl_namespace' => $ns,
420 'tl_title' => $dbk
424 return $arr;
428 * Get an array of image insertions
429 * Skips the names specified in $existing
430 * @private
432 function getImageInsertions( $existing = array() ) {
433 $arr = array();
434 $diffs = array_diff_key( $this->mImages, $existing );
435 foreach( $diffs as $iname => $dummy ) {
436 $arr[] = array(
437 'il_from' => $this->mId,
438 'il_to' => $iname
441 return $arr;
445 * Get an array of externallinks insertions. Skips the names specified in $existing
446 * @private
448 function getExternalInsertions( $existing = array() ) {
449 $arr = array();
450 $diffs = array_diff_key( $this->mExternals, $existing );
451 foreach( $diffs as $url => $dummy ) {
452 $arr[] = array(
453 'el_from' => $this->mId,
454 'el_to' => $url,
455 'el_index' => wfMakeUrlIndex( $url ),
458 return $arr;
462 * Get an array of category insertions
463 * @param array $existing Array mapping existing category names to sort keys. If both
464 * match a link in $this, the link will be omitted from the output
465 * @private
467 function getCategoryInsertions( $existing = array() ) {
468 $diffs = array_diff_assoc( $this->mCategories, $existing );
469 $arr = array();
470 foreach ( $diffs as $name => $sortkey ) {
471 $arr[] = array(
472 'cl_from' => $this->mId,
473 'cl_to' => $name,
474 'cl_sortkey' => $sortkey,
475 'cl_timestamp' => $this->mDb->timestamp()
478 return $arr;
482 * Get an array of interlanguage link insertions
483 * @param array $existing Array mapping existing language codes to titles
484 * @private
486 function getInterlangInsertions( $existing = array() ) {
487 $diffs = array_diff_assoc( $this->mInterlangs, $existing );
488 $arr = array();
489 foreach( $diffs as $lang => $title ) {
490 $arr[] = array(
491 'll_from' => $this->mId,
492 'll_lang' => $lang,
493 'll_title' => $title
496 return $arr;
500 * Get an array of page property insertions
502 function getPropertyInsertions( $existing = array() ) {
503 $diffs = array_diff_assoc( $this->mProperties, $existing );
504 $arr = array();
505 foreach ( $diffs as $name => $value ) {
506 $arr[] = array(
507 'pp_page' => $this->mId,
508 'pp_propname' => $name,
509 'pp_value' => $value,
512 return $arr;
517 * Given an array of existing links, returns those links which are not in $this
518 * and thus should be deleted.
519 * @private
521 function getLinkDeletions( $existing ) {
522 $del = array();
523 foreach ( $existing as $ns => $dbkeys ) {
524 if ( isset( $this->mLinks[$ns] ) ) {
525 $del[$ns] = array_diff_key( $existing[$ns], $this->mLinks[$ns] );
526 } else {
527 $del[$ns] = $existing[$ns];
530 return $del;
534 * Given an array of existing templates, returns those templates which are not in $this
535 * and thus should be deleted.
536 * @private
538 function getTemplateDeletions( $existing ) {
539 $del = array();
540 foreach ( $existing as $ns => $dbkeys ) {
541 if ( isset( $this->mTemplates[$ns] ) ) {
542 $del[$ns] = array_diff_key( $existing[$ns], $this->mTemplates[$ns] );
543 } else {
544 $del[$ns] = $existing[$ns];
547 return $del;
551 * Given an array of existing images, returns those images which are not in $this
552 * and thus should be deleted.
553 * @private
555 function getImageDeletions( $existing ) {
556 return array_diff_key( $existing, $this->mImages );
560 * Given an array of existing external links, returns those links which are not
561 * in $this and thus should be deleted.
562 * @private
564 function getExternalDeletions( $existing ) {
565 return array_diff_key( $existing, $this->mExternals );
569 * Given an array of existing categories, returns those categories which are not in $this
570 * and thus should be deleted.
571 * @private
573 function getCategoryDeletions( $existing ) {
574 return array_diff_assoc( $existing, $this->mCategories );
578 * Given an array of existing interlanguage links, returns those links which are not
579 * in $this and thus should be deleted.
580 * @private
582 function getInterlangDeletions( $existing ) {
583 return array_diff_assoc( $existing, $this->mInterlangs );
587 * Get array of properties which should be deleted.
588 * @private
590 function getPropertyDeletions( $existing ) {
591 return array_diff_assoc( $existing, $this->mProperties );
595 * Get an array of existing links, as a 2-D array
596 * @private
598 function getExistingLinks() {
599 $res = $this->mDb->select( 'pagelinks', array( 'pl_namespace', 'pl_title' ),
600 array( 'pl_from' => $this->mId ), __METHOD__, $this->mOptions );
601 $arr = array();
602 while ( $row = $this->mDb->fetchObject( $res ) ) {
603 if ( !isset( $arr[$row->pl_namespace] ) ) {
604 $arr[$row->pl_namespace] = array();
606 $arr[$row->pl_namespace][$row->pl_title] = 1;
608 $this->mDb->freeResult( $res );
609 return $arr;
613 * Get an array of existing templates, as a 2-D array
614 * @private
616 function getExistingTemplates() {
617 $res = $this->mDb->select( 'templatelinks', array( 'tl_namespace', 'tl_title' ),
618 array( 'tl_from' => $this->mId ), __METHOD__, $this->mOptions );
619 $arr = array();
620 while ( $row = $this->mDb->fetchObject( $res ) ) {
621 if ( !isset( $arr[$row->tl_namespace] ) ) {
622 $arr[$row->tl_namespace] = array();
624 $arr[$row->tl_namespace][$row->tl_title] = 1;
626 $this->mDb->freeResult( $res );
627 return $arr;
631 * Get an array of existing images, image names in the keys
632 * @private
634 function getExistingImages() {
635 $res = $this->mDb->select( 'imagelinks', array( 'il_to' ),
636 array( 'il_from' => $this->mId ), __METHOD__, $this->mOptions );
637 $arr = array();
638 while ( $row = $this->mDb->fetchObject( $res ) ) {
639 $arr[$row->il_to] = 1;
641 $this->mDb->freeResult( $res );
642 return $arr;
646 * Get an array of existing external links, URLs in the keys
647 * @private
649 function getExistingExternals() {
650 $res = $this->mDb->select( 'externallinks', array( 'el_to' ),
651 array( 'el_from' => $this->mId ), __METHOD__, $this->mOptions );
652 $arr = array();
653 while ( $row = $this->mDb->fetchObject( $res ) ) {
654 $arr[$row->el_to] = 1;
656 $this->mDb->freeResult( $res );
657 return $arr;
661 * Get an array of existing categories, with the name in the key and sort key in the value.
662 * @private
664 function getExistingCategories() {
665 $res = $this->mDb->select( 'categorylinks', array( 'cl_to', 'cl_sortkey' ),
666 array( 'cl_from' => $this->mId ), __METHOD__, $this->mOptions );
667 $arr = array();
668 while ( $row = $this->mDb->fetchObject( $res ) ) {
669 $arr[$row->cl_to] = $row->cl_sortkey;
671 $this->mDb->freeResult( $res );
672 return $arr;
676 * Get an array of existing interlanguage links, with the language code in the key and the
677 * title in the value.
678 * @private
680 function getExistingInterlangs() {
681 $res = $this->mDb->select( 'langlinks', array( 'll_lang', 'll_title' ),
682 array( 'll_from' => $this->mId ), __METHOD__, $this->mOptions );
683 $arr = array();
684 while ( $row = $this->mDb->fetchObject( $res ) ) {
685 $arr[$row->ll_lang] = $row->ll_title;
687 return $arr;
691 * Get an array of existing categories, with the name in the key and sort key in the value.
692 * @private
694 function getExistingProperties() {
695 $res = $this->mDb->select( 'page_props', array( 'pp_propname', 'pp_value' ),
696 array( 'pp_page' => $this->mId ), __METHOD__, $this->mOptions );
697 $arr = array();
698 while ( $row = $this->mDb->fetchObject( $res ) ) {
699 $arr[$row->pp_propname] = $row->pp_value;
701 $this->mDb->freeResult( $res );
702 return $arr;
707 * Return the title object of the page being updated
709 function getTitle() {
710 return $this->mTitle;
714 * Invalidate any necessary link lists related to page property changes
716 function invalidateProperties( $changed ) {
717 global $wgPagePropLinkInvalidations;
719 foreach ( $changed as $name => $value ) {
720 if ( isset( $wgPagePropLinkInvalidations[$name] ) ) {
721 $inv = $wgPagePropLinkInvalidations[$name];
722 if ( !is_array( $inv ) ) {
723 $inv = array( $inv );
725 foreach ( $inv as $table ) {
726 $update = new HTMLCacheUpdate( $this->mTitle, $table );
727 $update->doUpdate();