]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blobdiff - includes/parser/LinkHolderArray.php
MediaWiki 1.30.2
[autoinstallsdev/mediawiki.git] / includes / parser / LinkHolderArray.php
index 35b672b94f3491f4a1b3830b6e2a21c029824d8c..bc5182c1dd185c416bd250c692e8d232b4c09334 100644 (file)
 <?php
-
+/**
+ * Holder of replacement pairs for wiki links
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
+ *
+ * @file
+ * @ingroup Parser
+ */
+
+/**
+ * @ingroup Parser
+ */
 class LinkHolderArray {
-       var $internals = array(), $interwikis = array();
-       var $size = 0;
-       var $parent;
+       public $internals = [];
+       public $interwikis = [];
+       public $size = 0;
+
+       /**
+        * @var Parser
+        */
+       public $parent;
+       protected $tempIdOffset;
 
-       function __construct( $parent ) {
+       /**
+        * @param Parser $parent
+        */
+       public function __construct( $parent ) {
                $this->parent = $parent;
        }
 
        /**
         * Reduce memory usage to reduce the impact of circular references
         */
-       function __destruct() {
+       public function __destruct() {
                foreach ( $this as $name => $value ) {
                        unset( $this->$name );
                }
        }
 
+       /**
+        * Don't serialize the parent object, it is big, and not needed when it is
+        * a parameter to mergeForeign(), which is the only application of
+        * serializing at present.
+        *
+        * Compact the titles, only serialize the text form.
+        * @return array
+        */
+       public function __sleep() {
+               foreach ( $this->internals as &$nsLinks ) {
+                       foreach ( $nsLinks as &$entry ) {
+                               unset( $entry['title'] );
+                       }
+               }
+               unset( $nsLinks );
+               unset( $entry );
+
+               foreach ( $this->interwikis as &$entry ) {
+                       unset( $entry['title'] );
+               }
+               unset( $entry );
+
+               return [ 'internals', 'interwikis', 'size' ];
+       }
+
+       /**
+        * Recreate the Title objects
+        */
+       public function __wakeup() {
+               foreach ( $this->internals as &$nsLinks ) {
+                       foreach ( $nsLinks as &$entry ) {
+                               $entry['title'] = Title::newFromText( $entry['pdbk'] );
+                       }
+               }
+               unset( $nsLinks );
+               unset( $entry );
+
+               foreach ( $this->interwikis as &$entry ) {
+                       $entry['title'] = Title::newFromText( $entry['pdbk'] );
+               }
+               unset( $entry );
+       }
+
        /**
         * Merge another LinkHolderArray into this one
+        * @param LinkHolderArray $other
         */
-       function merge( $other ) {
+       public function merge( $other ) {
                foreach ( $other->internals as $ns => $entries ) {
                        $this->size += count( $entries );
                        if ( !isset( $this->internals[$ns] ) ) {
@@ -33,10 +110,97 @@ class LinkHolderArray {
                $this->interwikis += $other->interwikis;
        }
 
+       /**
+        * Merge a LinkHolderArray from another parser instance into this one. The
+        * keys will not be preserved. Any text which went with the old
+        * LinkHolderArray and needs to work with the new one should be passed in
+        * the $texts array. The strings in this array will have their link holders
+        * converted for use in the destination link holder. The resulting array of
+        * strings will be returned.
+        *
+        * @param LinkHolderArray $other
+        * @param array $texts Array of strings
+        * @return array
+        */
+       public function mergeForeign( $other, $texts ) {
+               $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
+               $maxId = 0;
+
+               # Renumber internal links
+               foreach ( $other->internals as $ns => $nsLinks ) {
+                       foreach ( $nsLinks as $key => $entry ) {
+                               $newKey = $idOffset + $key;
+                               $this->internals[$ns][$newKey] = $entry;
+                               $maxId = $newKey > $maxId ? $newKey : $maxId;
+                       }
+               }
+               $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
+                       [ $this, 'mergeForeignCallback' ], $texts );
+
+               # Renumber interwiki links
+               foreach ( $other->interwikis as $key => $entry ) {
+                       $newKey = $idOffset + $key;
+                       $this->interwikis[$newKey] = $entry;
+                       $maxId = $newKey > $maxId ? $newKey : $maxId;
+               }
+               $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
+                       [ $this, 'mergeForeignCallback' ], $texts );
+
+               # Set the parent link ID to be beyond the highest used ID
+               $this->parent->setLinkID( $maxId + 1 );
+               $this->tempIdOffset = null;
+               return $texts;
+       }
+
+       /**
+        * @param array $m
+        * @return string
+        */
+       protected function mergeForeignCallback( $m ) {
+               return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
+       }
+
+       /**
+        * Get a subset of the current LinkHolderArray which is sufficient to
+        * interpret the given text.
+        * @param string $text
+        * @return LinkHolderArray
+        */
+       public function getSubArray( $text ) {
+               $sub = new LinkHolderArray( $this->parent );
+
+               # Internal links
+               $pos = 0;
+               while ( $pos < strlen( $text ) ) {
+                       if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
+                               $text, $m, PREG_OFFSET_CAPTURE, $pos )
+                       ) {
+                               break;
+                       }
+                       $ns = $m[1][0];
+                       $key = $m[2][0];
+                       $sub->internals[$ns][$key] = $this->internals[$ns][$key];
+                       $pos = $m[0][1] + strlen( $m[0][0] );
+               }
+
+               # Interwiki links
+               $pos = 0;
+               while ( $pos < strlen( $text ) ) {
+                       if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
+                               break;
+                       }
+                       $key = $m[1][0];
+                       $sub->interwikis[$key] = $this->interwikis[$key];
+                       $pos = $m[0][1] + strlen( $m[0][0] );
+               }
+               return $sub;
+       }
+
        /**
         * Returns true if the memory requirements of this object are getting large
+        * @return bool
         */
-       function isBig() {
+       public function isBig() {
                global $wgLinkHolderBatchSize;
                return $this->size > $wgLinkHolderBatchSize;
        }
@@ -45,9 +209,9 @@ class LinkHolderArray {
         * Clear all stored link holders.
         * Make sure you don't have any text left using these link holders, before you call this
         */
-       function clear() {
-               $this->internals = array();
-               $this->interwikis = array();
+       public function clear() {
+               $this->internals = [];
+               $this->interwikis = [];
                $this->size = 0;
        }
 
@@ -57,22 +221,27 @@ class LinkHolderArray {
         * parsing of interwiki links, and secondly to allow all existence checks and
         * article length checks (for stub links) to be bundled into a single query.
         *
+        * @param Title $nt
+        * @param string $text
+        * @param array $query [optional]
+        * @param string $trail [optional]
+        * @param string $prefix [optional]
+        * @return string
         */
-       function makeHolder( $nt, $text = '', $query = '', $trail = '', $prefix = ''  ) {
-               wfProfileIn( __METHOD__ );
-               if ( ! is_object($nt) ) {
+       public function makeHolder( $nt, $text = '', $query = [], $trail = '', $prefix = '' ) {
+               if ( !is_object( $nt ) ) {
                        # Fail gracefully
                        $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
                } else {
                        # Separate the link trail from the rest of the link
                        list( $inside, $trail ) = Linker::splitTrail( $trail );
 
-                       $entry = array(
+                       $entry = [
                                'title' => $nt,
-                               'text' => $prefix.$text.$inside,
+                               'text' => $prefix . $text . $inside,
                                'pdbk' => $nt->getPrefixedDBkey(),
-                       );
-                       if ( $query !== '' ) {
+                       ];
+                       if ( $query !== [] ) {
                                $entry['query'] = $query;
                        }
 
@@ -89,66 +258,49 @@ class LinkHolderArray {
                        }
                        $this->size++;
                }
-               wfProfileOut( __METHOD__ );
                return $retVal;
        }
 
-       /**
-        * Get the stub threshold
-        */
-       function getStubThreshold() {
-               global $wgUser;
-               if ( !isset( $this->stubThreshold ) ) {
-                       $this->stubThreshold = $wgUser->getOption('stubthreshold');
-               }
-               return $this->stubThreshold;
-       }
-
        /**
         * Replace <!--LINK--> link placeholders with actual links, in the buffer
-        * Placeholders created in Skin::makeLinkObj()
-        * Returns an array of link CSS classes, indexed by PDBK.
+        *
+        * @param string &$text
         */
-       function replace( &$text ) {
-               wfProfileIn( __METHOD__ );
-
-               $colours = $this->replaceInternal( $text );
+       public function replace( &$text ) {
+               $this->replaceInternal( $text );
                $this->replaceInterwiki( $text );
-
-               wfProfileOut( __METHOD__ );
-               return $colours;
        }
 
        /**
         * Replace internal links
+        * @param string &$text
         */
        protected function replaceInternal( &$text ) {
                if ( !$this->internals ) {
                        return;
                }
 
-               wfProfileIn( __METHOD__ );
                global $wgContLang;
 
-               $colours = array();
-               $sk = $this->parent->getOptions()->getSkin();
+               $colours = [];
                $linkCache = LinkCache::singleton();
                $output = $this->parent->getOutput();
+               $linkRenderer = $this->parent->getLinkRenderer();
 
-               wfProfileIn( __METHOD__.'-check' );
-               $dbr = wfGetDB( DB_SLAVE );
-               $page = $dbr->tableName( 'page' );
-               $threshold = $this->getStubThreshold();
+               $dbr = wfGetDB( DB_REPLICA );
 
                # Sort by namespace
                ksort( $this->internals );
 
+               $linkcolour_ids = [];
+
                # Generate query
-               $query = false;
-               $current = null;
+               $lb = new LinkBatch();
+               $lb->setCaller( __METHOD__ );
+
                foreach ( $this->internals as $ns => $entries ) {
-                       foreach ( $entries as $index => $entry ) {
-                               $key =  "$ns:$index";
+                       foreach ( $entries as $entry ) {
+                               /** @var Title $title */
                                $title = $entry['title'];
                                $pdbk = $entry['pdbk'];
 
@@ -161,111 +313,126 @@ class LinkHolderArray {
                                # Check if it's a static known link, e.g. interwiki
                                if ( $title->isAlwaysKnown() ) {
                                        $colours[$pdbk] = '';
-                               } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
-                                       $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
-                                       $output->addLink( $title, $id );
-                               } elseif ( $linkCache->isBadLink( $pdbk ) ) {
+                               } elseif ( $ns == NS_SPECIAL ) {
                                        $colours[$pdbk] = 'new';
                                } else {
-                                       # Not in the link cache, add it to the query
-                                       if ( !isset( $current ) ) {
-                                               $current = $ns;
-                                               $query =  "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
-                                               $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
-                                       } elseif ( $current != $ns ) {
-                                               $current = $ns;
-                                               $query .= ")) OR (page_namespace=$ns AND page_title IN(";
+                                       $id = $linkCache->getGoodLinkID( $pdbk );
+                                       if ( $id != 0 ) {
+                                               $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
+                                               $output->addLink( $title, $id );
+                                               $linkcolour_ids[$id] = $pdbk;
+                                       } elseif ( $linkCache->isBadLink( $pdbk ) ) {
+                                               $colours[$pdbk] = 'new';
                                        } else {
-                                               $query .= ', ';
+                                               # Not in the link cache, add it to the query
+                                               $lb->addObj( $title );
                                        }
-
-                                       $query .= $dbr->addQuotes( $title->getDBkey() );
                                }
                        }
                }
-               if ( $query ) {
-                       $query .= '))';
+               if ( !$lb->isEmpty() ) {
+                       $fields = array_merge(
+                               LinkCache::getSelectFields(),
+                               [ 'page_namespace', 'page_title' ]
+                       );
 
-                       $res = $dbr->query( $query, __METHOD__ );
+                       $res = $dbr->select(
+                               'page',
+                               $fields,
+                               $lb->constructSet( 'page', $dbr ),
+                               __METHOD__
+                       );
 
                        # Fetch data and form into an associative array
                        # non-existent = broken
-                       $linkcolour_ids = array();
-                       while ( $s = $dbr->fetchObject($res) ) {
+                       foreach ( $res as $s ) {
                                $title = Title::makeTitle( $s->page_namespace, $s->page_title );
                                $pdbk = $title->getPrefixedDBkey();
-                               $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect );
+                               $linkCache->addGoodLinkObjFromRow( $title, $s );
                                $output->addLink( $title, $s->page_id );
-                               # FIXME: convoluted data flow
-                               # The redirect status and length is passed to getLinkColour via the LinkCache
-                               # Use formal parameters instead
-                               $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
-                               //add id to the extension todolist
+                               $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
+                               // add id to the extension todolist
                                $linkcolour_ids[$s->page_id] = $pdbk;
                        }
                        unset( $res );
-                       //pass an array of page_ids to an extension
-                       wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
                }
-               wfProfileOut( __METHOD__.'-check' );
+               if ( count( $linkcolour_ids ) ) {
+                       // pass an array of page_ids to an extension
+                       Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours ] );
+               }
 
                # Do a second query for different language variants of links and categories
-               if($wgContLang->hasVariants()) {
+               if ( $wgContLang->hasVariants() ) {
                        $this->doVariants( $colours );
                }
 
                # Construct search and replace arrays
-               wfProfileIn( __METHOD__.'-construct' );
-               $replacePairs = array();
+               $replacePairs = [];
                foreach ( $this->internals as $ns => $entries ) {
                        foreach ( $entries as $index => $entry ) {
                                $pdbk = $entry['pdbk'];
                                $title = $entry['title'];
-                               $query = isset( $entry['query'] ) ? $entry['query'] : '';
+                               $query = isset( $entry['query'] ) ? $entry['query'] : [];
                                $key = "$ns:$index";
                                $searchkey = "<!--LINK $key-->";
-                               if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
-                                       $linkCache->addBadLinkObj( $title );
+                               $displayText = $entry['text'];
+                               if ( isset( $entry['selflink'] ) ) {
+                                       $replacePairs[$searchkey] = Linker::makeSelfLinkObj( $title, $displayText, $query );
+                                       continue;
+                               }
+                               if ( $displayText === '' ) {
+                                       $displayText = null;
+                               } else {
+                                       $displayText = new HtmlArmor( $displayText );
+                               }
+                               if ( !isset( $colours[$pdbk] ) ) {
                                        $colours[$pdbk] = 'new';
+                               }
+                               $attribs = [];
+                               if ( $colours[$pdbk] == 'new' ) {
+                                       $linkCache->addBadLinkObj( $title );
                                        $output->addLink( $title, 0 );
-                                       $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
-                                                                       $entry['text'],
-                                                                       $query );
+                                       $link = $linkRenderer->makeBrokenLink(
+                                               $title, $displayText, $attribs, $query
+                                       );
                                } else {
-                                       $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
-                                                                       $entry['text'],
-                                                                       $query );
+                                       $link = $linkRenderer->makePreloadedLink(
+                                               $title, $displayText, $colours[$pdbk], $attribs, $query
+                                       );
                                }
+
+                               $replacePairs[$searchkey] = $link;
                        }
                }
                $replacer = new HashtableReplacer( $replacePairs, 1 );
-               wfProfileOut( __METHOD__.'-construct' );
 
                # Do the thing
-               wfProfileIn( __METHOD__.'-replace' );
                $text = preg_replace_callback(
                        '/(<!--LINK .*?-->)/',
                        $replacer->cb(),
-                       $text);
-
-               wfProfileOut( __METHOD__.'-replace' );
-               wfProfileOut( __METHOD__ );
+                       $text
+               );
        }
 
        /**
         * Replace interwiki links
+        * @param string &$text
         */
        protected function replaceInterwiki( &$text ) {
                if ( empty( $this->interwikis ) ) {
                        return;
                }
 
-               wfProfileIn( __METHOD__ );
                # Make interwiki link HTML
-               $sk = $this->parent->getOptions()->getSkin();
-               $replacePairs = array();
-               foreach( $this->interwikis as $key => $link ) {
-                       $replacePairs[$key] = $sk->link( $link['title'], $link['text'] );
+               $output = $this->parent->getOutput();
+               $replacePairs = [];
+               $linkRenderer = $this->parent->getLinkRenderer();
+               foreach ( $this->interwikis as $key => $link ) {
+                       $replacePairs[$key] = $linkRenderer->makeLink(
+                               $link['title'],
+                               new HtmlArmor( $link['text'] )
+                       );
+                       $output->addInterwikiLink( $link['title'] );
                }
                $replacer = new HashtableReplacer( $replacePairs, 1 );
 
@@ -273,126 +440,165 @@ class LinkHolderArray {
                        '/<!--IWLINK (.*?)-->/',
                        $replacer->cb(),
                        $text );
-               wfProfileOut( __METHOD__ );
        }
 
        /**
         * Modify $this->internals and $colours according to language variant linking rules
+        * @param array &$colours
         */
        protected function doVariants( &$colours ) {
                global $wgContLang;
                $linkBatch = new LinkBatch();
-               $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
+               $variantMap = []; // maps $pdbkey_Variant => $keys (of link holders)
                $output = $this->parent->getOutput();
                $linkCache = LinkCache::singleton();
-               $sk = $this->parent->getOptions()->getSkin();
-               $threshold = $this->getStubThreshold();
+               $titlesToBeConverted = '';
+               $titlesAttrs = [];
 
-               // Add variants of links to link batch
+               // Concatenate titles to a single string, thus we only need auto convert the
+               // single string to all variants. This would improve parser's performance
+               // significantly.
                foreach ( $this->internals as $ns => $entries ) {
+                       if ( $ns == NS_SPECIAL ) {
+                               continue;
+                       }
                        foreach ( $entries as $index => $entry ) {
-                               $key = "$ns:$index";
                                $pdbk = $entry['pdbk'];
-                               $title = $entry['title'];
-                               $titleText = $title->getText();
-
-                               // generate all variants of the link title text
-                               $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
-
-                               // if link was not found (in first query), add all variants to query
-                               if ( !isset($colours[$pdbk]) ){
-                                       foreach($allTextVariants as $textVariant){
-                                               if($textVariant != $titleText){
-                                                       $variantTitle = Title::makeTitle( $ns, $textVariant );
-                                                       if(is_null($variantTitle)) continue;
-                                                       $linkBatch->addObj( $variantTitle );
-                                                       $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
-                                               }
-                                       }
+                               // we only deal with new links (in its first query)
+                               if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
+                                       $titlesAttrs[] = [ $index, $entry['title'] ];
+                                       // separate titles with \0 because it would never appears
+                                       // in a valid title
+                                       $titlesToBeConverted .= $entry['title']->getText() . "\0";
                                }
                        }
                }
 
+               // Now do the conversion and explode string to text of titles
+               $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
+               $allVariantsName = array_keys( $titlesAllVariants );
+               foreach ( $titlesAllVariants as &$titlesVariant ) {
+                       $titlesVariant = explode( "\0", $titlesVariant );
+               }
+
+               // Then add variants of links to link batch
+               $parentTitle = $this->parent->getTitle();
+               foreach ( $titlesAttrs as $i => $attrs ) {
+                       /** @var Title $title */
+                       list( $index, $title ) = $attrs;
+                       $ns = $title->getNamespace();
+                       $text = $title->getText();
+
+                       foreach ( $allVariantsName as $variantName ) {
+                               $textVariant = $titlesAllVariants[$variantName][$i];
+                               if ( $textVariant === $text ) {
+                                       continue;
+                               }
+
+                               $variantTitle = Title::makeTitle( $ns, $textVariant );
+
+                               // Self-link checking for mixed/different variant titles. At this point, we
+                               // already know the exact title does not exist, so the link cannot be to a
+                               // variant of the current title that exists as a separate page.
+                               if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
+                                       $this->internals[$ns][$index]['selflink'] = true;
+                                       continue 2;
+                               }
+
+                               $linkBatch->addObj( $variantTitle );
+                               $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
+                       }
+               }
+
                // process categories, check if a category exists in some variant
-               $categoryMap = array(); // maps $category_variant => $category (dbkeys)
-               $varCategories = array(); // category replacements oldDBkey => newDBkey
-               foreach( $output->getCategoryLinks() as $category ){
-                       $variants = $wgContLang->convertLinkToAllVariants($category);
-                       foreach($variants as $variant){
-                               if($variant != $category){
-                                       $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
-                                       if(is_null($variantTitle)) continue;
+               $categoryMap = []; // maps $category_variant => $category (dbkeys)
+               $varCategories = []; // category replacements oldDBkey => newDBkey
+               foreach ( $output->getCategoryLinks() as $category ) {
+                       $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
+                       $linkBatch->addObj( $categoryTitle );
+                       $variants = $wgContLang->autoConvertToAllVariants( $category );
+                       foreach ( $variants as $variant ) {
+                               if ( $variant !== $category ) {
+                                       $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
+                                       if ( is_null( $variantTitle ) ) {
+                                               continue;
+                                       }
                                        $linkBatch->addObj( $variantTitle );
-                                       $categoryMap[$variant] = $category;
+                                       $categoryMap[$variant] = [ $category, $categoryTitle ];
                                }
                        }
                }
 
-
-               if(!$linkBatch->isEmpty()){
+               if ( !$linkBatch->isEmpty() ) {
                        // construct query
-                       $dbr = wfGetDB( DB_SLAVE );
-                       $page = $dbr->tableName( 'page' );
-                       $titleClause = $linkBatch->constructSet('page', $dbr);
-                       $variantQuery =  "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
-                       $variantQuery .= " FROM $page WHERE $titleClause";
-                       $varRes = $dbr->query( $variantQuery, __METHOD__ );
-                       $linkcolour_ids = array();
+                       $dbr = wfGetDB( DB_REPLICA );
+                       $fields = array_merge(
+                               LinkCache::getSelectFields(),
+                               [ 'page_namespace', 'page_title' ]
+                       );
 
-                       // for each found variants, figure out link holders and replace
-                       while ( $s = $dbr->fetchObject($varRes) ) {
+                       $varRes = $dbr->select( 'page',
+                               $fields,
+                               $linkBatch->constructSet( 'page', $dbr ),
+                               __METHOD__
+                       );
+
+                       $linkcolour_ids = [];
+                       $linkRenderer = $this->parent->getLinkRenderer();
 
+                       // for each found variants, figure out link holders and replace
+                       foreach ( $varRes as $s ) {
                                $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
                                $varPdbk = $variantTitle->getPrefixedDBkey();
                                $vardbk = $variantTitle->getDBkey();
 
-                               $holderKeys = array();
-                               if(isset($variantMap[$varPdbk])){
+                               $holderKeys = [];
+                               if ( isset( $variantMap[$varPdbk] ) ) {
                                        $holderKeys = $variantMap[$varPdbk];
-                                       $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
+                                       $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
                                        $output->addLink( $variantTitle, $s->page_id );
                                }
 
                                // loop over link holders
-                               foreach($holderKeys as $key){
+                               foreach ( $holderKeys as $key ) {
                                        list( $ns, $index ) = explode( ':', $key, 2 );
                                        $entry =& $this->internals[$ns][$index];
                                        $pdbk = $entry['pdbk'];
 
-                                       if(!isset($colours[$pdbk])){
+                                       if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
                                                // found link in some of the variants, replace the link holder data
                                                $entry['title'] = $variantTitle;
                                                $entry['pdbk'] = $varPdbk;
 
                                                // set pdbk and colour
-                                               # FIXME: convoluted data flow
-                                               # The redirect status and length is passed to getLinkColour via the LinkCache
-                                               # Use formal parameters instead
-                                               $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
+                                               $colours[$varPdbk] = $linkRenderer->getLinkClasses( $variantTitle );
                                                $linkcolour_ids[$s->page_id] = $pdbk;
                                        }
                                }
 
                                // check if the object is a variant of a category
-                               if(isset($categoryMap[$vardbk])){
-                                       $oldkey = $categoryMap[$vardbk];
-                                       if($oldkey != $vardbk)
-                                               $varCategories[$oldkey]=$vardbk;
+                               if ( isset( $categoryMap[$vardbk] ) ) {
+                                       list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
+                                       if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
+                                               $varCategories[$oldkey] = $vardbk;
+                                       }
                                }
                        }
-                       wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
+                       Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours ] );
 
                        // rebuild the categories in original order (if there are replacements)
-                       if(count($varCategories)>0){
-                               $newCats = array();
+                       if ( count( $varCategories ) > 0 ) {
+                               $newCats = [];
                                $originalCats = $output->getCategories();
-                               foreach($originalCats as $cat => $sortkey){
+                               foreach ( $originalCats as $cat => $sortkey ) {
                                        // make the replacement
-                                       if( array_key_exists($cat,$varCategories) )
+                                       if ( array_key_exists( $cat, $varCategories ) ) {
                                                $newCats[$varCategories[$cat]] = $sortkey;
-                                       else $newCats[$cat] = $sortkey;
+                                       } else {
+                                               $newCats[$cat] = $sortkey;
+                                       }
                                }
-                               $output->setCategoryLinks($newCats);
+                               $output->setCategoryLinks( $newCats );
                        }
                }
        }
@@ -400,36 +606,36 @@ class LinkHolderArray {
        /**
         * Replace <!--LINK--> link placeholders with plain text of links
         * (not HTML-formatted).
+        *
         * @param string $text
         * @return string
         */
-       function replaceText( $text ) {
-               wfProfileIn( __METHOD__ );
-
+       public function replaceText( $text ) {
                $text = preg_replace_callback(
                        '/<!--(LINK|IWLINK) (.*?)-->/',
-                       array( &$this, 'replaceTextCallback' ),
+                       [ $this, 'replaceTextCallback' ],
                        $text );
 
-               wfProfileOut( __METHOD__ );
                return $text;
        }
 
        /**
+        * Callback for replaceText()
+        *
         * @param array $matches
         * @return string
         * @private
         */
-       function replaceTextCallback( $matches ) {
+       public function replaceTextCallback( $matches ) {
                $type = $matches[1];
-               $key  = $matches[2];
-               if( $type == 'LINK' ) {
+               $key = $matches[2];
+               if ( $type == 'LINK' ) {
                        list( $ns, $index ) = explode( ':', $key, 2 );
-                       if( isset( $this->internals[$ns][$index]['text'] ) ) {
+                       if ( isset( $this->internals[$ns][$index]['text'] ) ) {
                                return $this->internals[$ns][$index]['text'];
                        }
-               } elseif( $type == 'IWLINK' ) {
-                       if( isset( $this->interwikis[$key]['text'] ) ) {
+               } elseif ( $type == 'IWLINK' ) {
+                       if ( isset( $this->interwikis[$key]['text'] ) ) {
                                return $this->interwikis[$key]['text'];
                        }
                }