3 * Holder of replacement pairs for wiki links
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.
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.
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
27 class LinkHolderArray
{
29 public $internals = array();
32 public $interwikis = array();
41 protected $tempIdOffset;
43 function __construct( $parent ) {
44 $this->parent
= $parent;
48 * Reduce memory usage to reduce the impact of circular references
50 function __destruct() {
51 foreach ( $this as $name => $value ) {
52 unset( $this->$name );
57 * Don't serialize the parent object, it is big, and not needed when it is
58 * a parameter to mergeForeign(), which is the only application of
59 * serializing at present.
61 * Compact the titles, only serialize the text form.
65 foreach ( $this->internals
as &$nsLinks ) {
66 foreach ( $nsLinks as &$entry ) {
67 unset( $entry['title'] );
73 foreach ( $this->interwikis
as &$entry ) {
74 unset( $entry['title'] );
78 return array( 'internals', 'interwikis', 'size' );
82 * Recreate the Title objects
85 foreach ( $this->internals
as &$nsLinks ) {
86 foreach ( $nsLinks as &$entry ) {
87 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
93 foreach ( $this->interwikis
as &$entry ) {
94 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
100 * Merge another LinkHolderArray into this one
101 * @param LinkHolderArray $other
103 function merge( $other ) {
104 foreach ( $other->internals
as $ns => $entries ) {
105 $this->size +
= count( $entries );
106 if ( !isset( $this->internals
[$ns] ) ) {
107 $this->internals
[$ns] = $entries;
109 $this->internals
[$ns] +
= $entries;
112 $this->interwikis +
= $other->interwikis
;
116 * Merge a LinkHolderArray from another parser instance into this one. The
117 * keys will not be preserved. Any text which went with the old
118 * LinkHolderArray and needs to work with the new one should be passed in
119 * the $texts array. The strings in this array will have their link holders
120 * converted for use in the destination link holder. The resulting array of
121 * strings will be returned.
123 * @param LinkHolderArray $other
124 * @param array $texts Array of strings
127 function mergeForeign( $other, $texts ) {
128 $this->tempIdOffset
= $idOffset = $this->parent
->nextLinkID();
131 # Renumber internal links
132 foreach ( $other->internals
as $ns => $nsLinks ) {
133 foreach ( $nsLinks as $key => $entry ) {
134 $newKey = $idOffset +
$key;
135 $this->internals
[$ns][$newKey] = $entry;
136 $maxId = $newKey > $maxId ?
$newKey : $maxId;
139 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
140 array( $this, 'mergeForeignCallback' ), $texts );
142 # Renumber interwiki links
143 foreach ( $other->interwikis
as $key => $entry ) {
144 $newKey = $idOffset +
$key;
145 $this->interwikis
[$newKey] = $entry;
146 $maxId = $newKey > $maxId ?
$newKey : $maxId;
148 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
149 array( $this, 'mergeForeignCallback' ), $texts );
151 # Set the parent link ID to be beyond the highest used ID
152 $this->parent
->setLinkID( $maxId +
1 );
153 $this->tempIdOffset
= null;
157 protected function mergeForeignCallback( $m ) {
158 return $m[1] . ( $m[2] +
$this->tempIdOffset
) . $m[3];
162 * Get a subset of the current LinkHolderArray which is sufficient to
163 * interpret the given text.
164 * @param string $text
165 * @return LinkHolderArray
167 function getSubArray( $text ) {
168 $sub = new LinkHolderArray( $this->parent
);
172 while ( $pos < strlen( $text ) ) {
173 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
174 $text, $m, PREG_OFFSET_CAPTURE
, $pos )
180 $sub->internals
[$ns][$key] = $this->internals
[$ns][$key];
181 $pos = $m[0][1] +
strlen( $m[0][0] );
186 while ( $pos < strlen( $text ) ) {
187 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE
, $pos ) ) {
191 $sub->interwikis
[$key] = $this->interwikis
[$key];
192 $pos = $m[0][1] +
strlen( $m[0][0] );
198 * Returns true if the memory requirements of this object are getting large
202 global $wgLinkHolderBatchSize;
203 return $this->size
> $wgLinkHolderBatchSize;
207 * Clear all stored link holders.
208 * Make sure you don't have any text left using these link holders, before you call this
211 $this->internals
= array();
212 $this->interwikis
= array();
217 * Make a link placeholder. The text returned can be later resolved to a real link with
218 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
219 * parsing of interwiki links, and secondly to allow all existence checks and
220 * article length checks (for stub links) to be bundled into a single query.
223 * @param string $text
224 * @param array $query [optional]
225 * @param string $trail [optional]
226 * @param string $prefix [optional]
229 function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
230 wfProfileIn( __METHOD__
);
231 if ( !is_object( $nt ) ) {
233 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
235 # Separate the link trail from the rest of the link
236 list( $inside, $trail ) = Linker
::splitTrail( $trail );
240 'text' => $prefix . $text . $inside,
241 'pdbk' => $nt->getPrefixedDBkey(),
243 if ( $query !== array() ) {
244 $entry['query'] = $query;
247 if ( $nt->isExternal() ) {
248 // Use a globally unique ID to keep the objects mergable
249 $key = $this->parent
->nextLinkID();
250 $this->interwikis
[$key] = $entry;
251 $retVal = "<!--IWLINK $key-->{$trail}";
253 $key = $this->parent
->nextLinkID();
254 $ns = $nt->getNamespace();
255 $this->internals
[$ns][$key] = $entry;
256 $retVal = "<!--LINK $ns:$key-->{$trail}";
260 wfProfileOut( __METHOD__
);
265 * Replace <!--LINK--> link placeholders with actual links, in the buffer
268 * @return array Array of link CSS classes, indexed by PDBK.
270 function replace( &$text ) {
271 wfProfileIn( __METHOD__
);
273 /** @todo FIXME: replaceInternal doesn't return a value */
274 $colours = $this->replaceInternal( $text );
275 $this->replaceInterwiki( $text );
277 wfProfileOut( __METHOD__
);
282 * Replace internal links
283 * @param string $text
285 protected function replaceInternal( &$text ) {
286 if ( !$this->internals
) {
290 wfProfileIn( __METHOD__
);
294 $linkCache = LinkCache
::singleton();
295 $output = $this->parent
->getOutput();
297 wfProfileIn( __METHOD__
. '-check' );
298 $dbr = wfGetDB( DB_SLAVE
);
299 $threshold = $this->parent
->getOptions()->getStubThreshold();
302 ksort( $this->internals
);
304 $linkcolour_ids = array();
308 foreach ( $this->internals
as $ns => $entries ) {
309 foreach ( $entries as $entry ) {
310 $title = $entry['title'];
311 $pdbk = $entry['pdbk'];
313 # Skip invalid entries.
314 # Result will be ugly, but prevents crash.
315 if ( is_null( $title ) ) {
319 # Check if it's a static known link, e.g. interwiki
320 if ( $title->isAlwaysKnown() ) {
321 $colours[$pdbk] = '';
322 } elseif ( $ns == NS_SPECIAL
) {
323 $colours[$pdbk] = 'new';
324 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
325 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
326 $output->addLink( $title, $id );
327 $linkcolour_ids[$id] = $pdbk;
328 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
329 $colours[$pdbk] = 'new';
331 # Not in the link cache, add it to the query
332 $queries[$ns][] = $title->getDBkey();
338 foreach ( $queries as $ns => $pages ) {
339 $where[] = $dbr->makeList(
341 'page_namespace' => $ns,
342 'page_title' => $pages,
350 array( 'page_id', 'page_namespace', 'page_title',
351 'page_is_redirect', 'page_len', 'page_latest' ),
352 $dbr->makeList( $where, LIST_OR
),
356 # Fetch data and form into an associative array
357 # non-existent = broken
358 foreach ( $res as $s ) {
359 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
360 $pdbk = $title->getPrefixedDBkey();
361 $linkCache->addGoodLinkObjFromRow( $title, $s );
362 $output->addLink( $title, $s->page_id
);
363 # @todo FIXME: Convoluted data flow
364 # The redirect status and length is passed to getLinkColour via the LinkCache
365 # Use formal parameters instead
366 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
367 //add id to the extension todolist
368 $linkcolour_ids[$s->page_id
] = $pdbk;
372 if ( count( $linkcolour_ids ) ) {
373 //pass an array of page_ids to an extension
374 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
376 wfProfileOut( __METHOD__
. '-check' );
378 # Do a second query for different language variants of links and categories
379 if ( $wgContLang->hasVariants() ) {
380 $this->doVariants( $colours );
383 # Construct search and replace arrays
384 wfProfileIn( __METHOD__
. '-construct' );
385 $replacePairs = array();
386 foreach ( $this->internals
as $ns => $entries ) {
387 foreach ( $entries as $index => $entry ) {
388 $pdbk = $entry['pdbk'];
389 $title = $entry['title'];
390 $query = isset( $entry['query'] ) ?
$entry['query'] : array();
392 $searchkey = "<!--LINK $key-->";
393 $displayText = $entry['text'];
394 if ( isset( $entry['selflink'] ) ) {
395 $replacePairs[$searchkey] = Linker
::makeSelfLinkObj( $title, $displayText, $query );
398 if ( $displayText === '' ) {
401 if ( !isset( $colours[$pdbk] ) ) {
402 $colours[$pdbk] = 'new';
405 if ( $colours[$pdbk] == 'new' ) {
406 $linkCache->addBadLinkObj( $title );
407 $output->addLink( $title, 0 );
408 $type = array( 'broken' );
410 if ( $colours[$pdbk] != '' ) {
411 $attribs['class'] = $colours[$pdbk];
413 $type = array( 'known', 'noclasses' );
415 $replacePairs[$searchkey] = Linker
::link( $title, $displayText,
416 $attribs, $query, $type );
419 $replacer = new HashtableReplacer( $replacePairs, 1 );
420 wfProfileOut( __METHOD__
. '-construct' );
423 wfProfileIn( __METHOD__
. '-replace' );
424 $text = preg_replace_callback(
425 '/(<!--LINK .*?-->)/',
430 wfProfileOut( __METHOD__
. '-replace' );
431 wfProfileOut( __METHOD__
);
435 * Replace interwiki links
436 * @param string $text
438 protected function replaceInterwiki( &$text ) {
439 if ( empty( $this->interwikis
) ) {
443 wfProfileIn( __METHOD__
);
444 # Make interwiki link HTML
445 $output = $this->parent
->getOutput();
446 $replacePairs = array();
447 foreach ( $this->interwikis
as $key => $link ) {
448 $replacePairs[$key] = Linker
::link( $link['title'], $link['text'] );
449 $output->addInterwikiLink( $link['title'] );
451 $replacer = new HashtableReplacer( $replacePairs, 1 );
453 $text = preg_replace_callback(
454 '/<!--IWLINK (.*?)-->/',
457 wfProfileOut( __METHOD__
);
461 * Modify $this->internals and $colours according to language variant linking rules
462 * @param array $colours
464 protected function doVariants( &$colours ) {
466 $linkBatch = new LinkBatch();
467 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
468 $output = $this->parent
->getOutput();
469 $linkCache = LinkCache
::singleton();
470 $threshold = $this->parent
->getOptions()->getStubThreshold();
471 $titlesToBeConverted = '';
472 $titlesAttrs = array();
474 // Concatenate titles to a single string, thus we only need auto convert the
475 // single string to all variants. This would improve parser's performance
477 foreach ( $this->internals
as $ns => $entries ) {
478 if ( $ns == NS_SPECIAL
) {
481 foreach ( $entries as $index => $entry ) {
482 $pdbk = $entry['pdbk'];
483 // we only deal with new links (in its first query)
484 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
485 $titlesAttrs[] = array( $index, $entry['title'] );
486 // separate titles with \0 because it would never appears
488 $titlesToBeConverted .= $entry['title']->getText() . "\0";
493 // Now do the conversion and explode string to text of titles
494 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
495 $allVariantsName = array_keys( $titlesAllVariants );
496 foreach ( $titlesAllVariants as &$titlesVariant ) {
497 $titlesVariant = explode( "\0", $titlesVariant );
500 // Then add variants of links to link batch
501 $parentTitle = $this->parent
->getTitle();
502 foreach ( $titlesAttrs as $i => $attrs ) {
503 list( $index, $title ) = $attrs;
504 $ns = $title->getNamespace();
505 $text = $title->getText();
507 foreach ( $allVariantsName as $variantName ) {
508 $textVariant = $titlesAllVariants[$variantName][$i];
509 if ( $textVariant === $text ) {
513 $variantTitle = Title
::makeTitle( $ns, $textVariant );
514 if ( is_null( $variantTitle ) ) {
518 // Self-link checking for mixed/different variant titles. At this point, we
519 // already know the exact title does not exist, so the link cannot be to a
520 // variant of the current title that exists as a separate page.
521 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
522 $this->internals
[$ns][$index]['selflink'] = true;
526 $linkBatch->addObj( $variantTitle );
527 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
531 // process categories, check if a category exists in some variant
532 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
533 $varCategories = array(); // category replacements oldDBkey => newDBkey
534 foreach ( $output->getCategoryLinks() as $category ) {
535 $categoryTitle = Title
::makeTitleSafe( NS_CATEGORY
, $category );
536 $linkBatch->addObj( $categoryTitle );
537 $variants = $wgContLang->autoConvertToAllVariants( $category );
538 foreach ( $variants as $variant ) {
539 if ( $variant !== $category ) {
540 $variantTitle = Title
::makeTitleSafe( NS_CATEGORY
, $variant );
541 if ( is_null( $variantTitle ) ) {
544 $linkBatch->addObj( $variantTitle );
545 $categoryMap[$variant] = array( $category, $categoryTitle );
550 if ( !$linkBatch->isEmpty() ) {
552 $dbr = wfGetDB( DB_SLAVE
);
553 $varRes = $dbr->select( 'page',
554 array( 'page_id', 'page_namespace', 'page_title',
555 'page_is_redirect', 'page_len', 'page_latest' ),
556 $linkBatch->constructSet( 'page', $dbr ),
560 $linkcolour_ids = array();
562 // for each found variants, figure out link holders and replace
563 foreach ( $varRes as $s ) {
565 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
566 $varPdbk = $variantTitle->getPrefixedDBkey();
567 $vardbk = $variantTitle->getDBkey();
569 $holderKeys = array();
570 if ( isset( $variantMap[$varPdbk] ) ) {
571 $holderKeys = $variantMap[$varPdbk];
572 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
573 $output->addLink( $variantTitle, $s->page_id
);
576 // loop over link holders
577 foreach ( $holderKeys as $key ) {
578 list( $ns, $index ) = explode( ':', $key, 2 );
579 $entry =& $this->internals
[$ns][$index];
580 $pdbk = $entry['pdbk'];
582 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
583 // found link in some of the variants, replace the link holder data
584 $entry['title'] = $variantTitle;
585 $entry['pdbk'] = $varPdbk;
587 // set pdbk and colour
588 # @todo FIXME: Convoluted data flow
589 # The redirect status and length is passed to getLinkColour via the LinkCache
590 # Use formal parameters instead
591 $colours[$varPdbk] = Linker
::getLinkColour( $variantTitle, $threshold );
592 $linkcolour_ids[$s->page_id
] = $pdbk;
596 // check if the object is a variant of a category
597 if ( isset( $categoryMap[$vardbk] ) ) {
598 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
599 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
600 $varCategories[$oldkey] = $vardbk;
604 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
606 // rebuild the categories in original order (if there are replacements)
607 if ( count( $varCategories ) > 0 ) {
609 $originalCats = $output->getCategories();
610 foreach ( $originalCats as $cat => $sortkey ) {
611 // make the replacement
612 if ( array_key_exists( $cat, $varCategories ) ) {
613 $newCats[$varCategories[$cat]] = $sortkey;
615 $newCats[$cat] = $sortkey;
618 $output->setCategoryLinks( $newCats );
624 * Replace <!--LINK--> link placeholders with plain text of links
625 * (not HTML-formatted).
627 * @param string $text
630 function replaceText( $text ) {
631 wfProfileIn( __METHOD__
);
633 $text = preg_replace_callback(
634 '/<!--(LINK|IWLINK) (.*?)-->/',
635 array( &$this, 'replaceTextCallback' ),
638 wfProfileOut( __METHOD__
);
643 * Callback for replaceText()
645 * @param array $matches
649 function replaceTextCallback( $matches ) {
652 if ( $type == 'LINK' ) {
653 list( $ns, $index ) = explode( ':', $key, 2 );
654 if ( isset( $this->internals
[$ns][$index]['text'] ) ) {
655 return $this->internals
[$ns][$index]['text'];
657 } elseif ( $type == 'IWLINK' ) {
658 if ( isset( $this->interwikis
[$key]['text'] ) ) {
659 return $this->interwikis
[$key]['text'];