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
{
28 public $internals = array();
29 public $interwikis = array();
36 protected $tempIdOffset;
39 * @param Parser $parent
41 public function __construct( $parent ) {
42 $this->parent
= $parent;
46 * Reduce memory usage to reduce the impact of circular references
48 public function __destruct() {
49 foreach ( $this as $name => $value ) {
50 unset( $this->$name );
55 * Don't serialize the parent object, it is big, and not needed when it is
56 * a parameter to mergeForeign(), which is the only application of
57 * serializing at present.
59 * Compact the titles, only serialize the text form.
62 public function __sleep() {
63 foreach ( $this->internals
as &$nsLinks ) {
64 foreach ( $nsLinks as &$entry ) {
65 unset( $entry['title'] );
71 foreach ( $this->interwikis
as &$entry ) {
72 unset( $entry['title'] );
76 return array( 'internals', 'interwikis', 'size' );
80 * Recreate the Title objects
82 public function __wakeup() {
83 foreach ( $this->internals
as &$nsLinks ) {
84 foreach ( $nsLinks as &$entry ) {
85 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
91 foreach ( $this->interwikis
as &$entry ) {
92 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
98 * Merge another LinkHolderArray into this one
99 * @param LinkHolderArray $other
101 public function merge( $other ) {
102 foreach ( $other->internals
as $ns => $entries ) {
103 $this->size +
= count( $entries );
104 if ( !isset( $this->internals
[$ns] ) ) {
105 $this->internals
[$ns] = $entries;
107 $this->internals
[$ns] +
= $entries;
110 $this->interwikis +
= $other->interwikis
;
114 * Merge a LinkHolderArray from another parser instance into this one. The
115 * keys will not be preserved. Any text which went with the old
116 * LinkHolderArray and needs to work with the new one should be passed in
117 * the $texts array. The strings in this array will have their link holders
118 * converted for use in the destination link holder. The resulting array of
119 * strings will be returned.
121 * @param LinkHolderArray $other
122 * @param array $texts Array of strings
125 public function mergeForeign( $other, $texts ) {
126 $this->tempIdOffset
= $idOffset = $this->parent
->nextLinkID();
129 # Renumber internal links
130 foreach ( $other->internals
as $ns => $nsLinks ) {
131 foreach ( $nsLinks as $key => $entry ) {
132 $newKey = $idOffset +
$key;
133 $this->internals
[$ns][$newKey] = $entry;
134 $maxId = $newKey > $maxId ?
$newKey : $maxId;
137 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
138 array( $this, 'mergeForeignCallback' ), $texts );
140 # Renumber interwiki links
141 foreach ( $other->interwikis
as $key => $entry ) {
142 $newKey = $idOffset +
$key;
143 $this->interwikis
[$newKey] = $entry;
144 $maxId = $newKey > $maxId ?
$newKey : $maxId;
146 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
147 array( $this, 'mergeForeignCallback' ), $texts );
149 # Set the parent link ID to be beyond the highest used ID
150 $this->parent
->setLinkID( $maxId +
1 );
151 $this->tempIdOffset
= null;
159 protected function mergeForeignCallback( $m ) {
160 return $m[1] . ( $m[2] +
$this->tempIdOffset
) . $m[3];
164 * Get a subset of the current LinkHolderArray which is sufficient to
165 * interpret the given text.
166 * @param string $text
167 * @return LinkHolderArray
169 public function getSubArray( $text ) {
170 $sub = new LinkHolderArray( $this->parent
);
174 while ( $pos < strlen( $text ) ) {
175 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
176 $text, $m, PREG_OFFSET_CAPTURE
, $pos )
182 $sub->internals
[$ns][$key] = $this->internals
[$ns][$key];
183 $pos = $m[0][1] +
strlen( $m[0][0] );
188 while ( $pos < strlen( $text ) ) {
189 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE
, $pos ) ) {
193 $sub->interwikis
[$key] = $this->interwikis
[$key];
194 $pos = $m[0][1] +
strlen( $m[0][0] );
200 * Returns true if the memory requirements of this object are getting large
203 public function isBig() {
204 global $wgLinkHolderBatchSize;
205 return $this->size
> $wgLinkHolderBatchSize;
209 * Clear all stored link holders.
210 * Make sure you don't have any text left using these link holders, before you call this
212 public function clear() {
213 $this->internals
= array();
214 $this->interwikis
= array();
219 * Make a link placeholder. The text returned can be later resolved to a real link with
220 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
221 * parsing of interwiki links, and secondly to allow all existence checks and
222 * article length checks (for stub links) to be bundled into a single query.
225 * @param string $text
226 * @param array $query [optional]
227 * @param string $trail [optional]
228 * @param string $prefix [optional]
231 public function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
232 wfProfileIn( __METHOD__
);
233 if ( !is_object( $nt ) ) {
235 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
237 # Separate the link trail from the rest of the link
238 list( $inside, $trail ) = Linker
::splitTrail( $trail );
242 'text' => $prefix . $text . $inside,
243 'pdbk' => $nt->getPrefixedDBkey(),
245 if ( $query !== array() ) {
246 $entry['query'] = $query;
249 if ( $nt->isExternal() ) {
250 // Use a globally unique ID to keep the objects mergable
251 $key = $this->parent
->nextLinkID();
252 $this->interwikis
[$key] = $entry;
253 $retVal = "<!--IWLINK $key-->{$trail}";
255 $key = $this->parent
->nextLinkID();
256 $ns = $nt->getNamespace();
257 $this->internals
[$ns][$key] = $entry;
258 $retVal = "<!--LINK $ns:$key-->{$trail}";
262 wfProfileOut( __METHOD__
);
267 * Replace <!--LINK--> link placeholders with actual links, in the buffer
269 * @param string $text
271 public function replace( &$text ) {
272 wfProfileIn( __METHOD__
);
274 $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__
);
291 global $wgContLang, $wgContentHandlerUseDB;
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 /** @var Title $title */
311 $title = $entry['title'];
312 $pdbk = $entry['pdbk'];
314 # Skip invalid entries.
315 # Result will be ugly, but prevents crash.
316 if ( is_null( $title ) ) {
320 # Check if it's a static known link, e.g. interwiki
321 if ( $title->isAlwaysKnown() ) {
322 $colours[$pdbk] = '';
323 } elseif ( $ns == NS_SPECIAL
) {
324 $colours[$pdbk] = 'new';
325 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
326 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
327 $output->addLink( $title, $id );
328 $linkcolour_ids[$id] = $pdbk;
329 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
330 $colours[$pdbk] = 'new';
332 # Not in the link cache, add it to the query
333 $queries[$ns][] = $title->getDBkey();
339 foreach ( $queries as $ns => $pages ) {
340 $where[] = $dbr->makeList(
342 'page_namespace' => $ns,
343 'page_title' => array_unique( $pages ),
349 $fields = array( 'page_id', 'page_namespace', 'page_title',
350 'page_is_redirect', 'page_len', 'page_latest' );
352 if ( $wgContentHandlerUseDB ) {
353 $fields[] = 'page_content_model';
359 $dbr->makeList( $where, LIST_OR
),
363 # Fetch data and form into an associative array
364 # non-existent = broken
365 foreach ( $res as $s ) {
366 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
367 $pdbk = $title->getPrefixedDBkey();
368 $linkCache->addGoodLinkObjFromRow( $title, $s );
369 $output->addLink( $title, $s->page_id
);
370 # @todo FIXME: Convoluted data flow
371 # The redirect status and length is passed to getLinkColour via the LinkCache
372 # Use formal parameters instead
373 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
374 //add id to the extension todolist
375 $linkcolour_ids[$s->page_id
] = $pdbk;
379 if ( count( $linkcolour_ids ) ) {
380 //pass an array of page_ids to an extension
381 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
383 wfProfileOut( __METHOD__
. '-check' );
385 # Do a second query for different language variants of links and categories
386 if ( $wgContLang->hasVariants() ) {
387 $this->doVariants( $colours );
390 # Construct search and replace arrays
391 wfProfileIn( __METHOD__
. '-construct' );
392 $replacePairs = array();
393 foreach ( $this->internals
as $ns => $entries ) {
394 foreach ( $entries as $index => $entry ) {
395 $pdbk = $entry['pdbk'];
396 $title = $entry['title'];
397 $query = isset( $entry['query'] ) ?
$entry['query'] : array();
399 $searchkey = "<!--LINK $key-->";
400 $displayText = $entry['text'];
401 if ( isset( $entry['selflink'] ) ) {
402 $replacePairs[$searchkey] = Linker
::makeSelfLinkObj( $title, $displayText, $query );
405 if ( $displayText === '' ) {
408 if ( !isset( $colours[$pdbk] ) ) {
409 $colours[$pdbk] = 'new';
412 if ( $colours[$pdbk] == 'new' ) {
413 $linkCache->addBadLinkObj( $title );
414 $output->addLink( $title, 0 );
415 $type = array( 'broken' );
417 if ( $colours[$pdbk] != '' ) {
418 $attribs['class'] = $colours[$pdbk];
420 $type = array( 'known', 'noclasses' );
422 $replacePairs[$searchkey] = Linker
::link( $title, $displayText,
423 $attribs, $query, $type );
426 $replacer = new HashtableReplacer( $replacePairs, 1 );
427 wfProfileOut( __METHOD__
. '-construct' );
430 wfProfileIn( __METHOD__
. '-replace' );
431 $text = preg_replace_callback(
432 '/(<!--LINK .*?-->)/',
437 wfProfileOut( __METHOD__
. '-replace' );
438 wfProfileOut( __METHOD__
);
442 * Replace interwiki links
443 * @param string $text
445 protected function replaceInterwiki( &$text ) {
446 if ( empty( $this->interwikis
) ) {
450 wfProfileIn( __METHOD__
);
451 # Make interwiki link HTML
452 $output = $this->parent
->getOutput();
453 $replacePairs = array();
454 foreach ( $this->interwikis
as $key => $link ) {
455 $replacePairs[$key] = Linker
::link( $link['title'], $link['text'] );
456 $output->addInterwikiLink( $link['title'] );
458 $replacer = new HashtableReplacer( $replacePairs, 1 );
460 $text = preg_replace_callback(
461 '/<!--IWLINK (.*?)-->/',
464 wfProfileOut( __METHOD__
);
468 * Modify $this->internals and $colours according to language variant linking rules
469 * @param array $colours
471 protected function doVariants( &$colours ) {
472 global $wgContLang, $wgContentHandlerUseDB;
473 $linkBatch = new LinkBatch();
474 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
475 $output = $this->parent
->getOutput();
476 $linkCache = LinkCache
::singleton();
477 $threshold = $this->parent
->getOptions()->getStubThreshold();
478 $titlesToBeConverted = '';
479 $titlesAttrs = array();
481 // Concatenate titles to a single string, thus we only need auto convert the
482 // single string to all variants. This would improve parser's performance
484 foreach ( $this->internals
as $ns => $entries ) {
485 if ( $ns == NS_SPECIAL
) {
488 foreach ( $entries as $index => $entry ) {
489 $pdbk = $entry['pdbk'];
490 // we only deal with new links (in its first query)
491 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
492 $titlesAttrs[] = array( $index, $entry['title'] );
493 // separate titles with \0 because it would never appears
495 $titlesToBeConverted .= $entry['title']->getText() . "\0";
500 // Now do the conversion and explode string to text of titles
501 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
502 $allVariantsName = array_keys( $titlesAllVariants );
503 foreach ( $titlesAllVariants as &$titlesVariant ) {
504 $titlesVariant = explode( "\0", $titlesVariant );
507 // Then add variants of links to link batch
508 $parentTitle = $this->parent
->getTitle();
509 foreach ( $titlesAttrs as $i => $attrs ) {
510 /** @var Title $title */
511 list( $index, $title ) = $attrs;
512 $ns = $title->getNamespace();
513 $text = $title->getText();
515 foreach ( $allVariantsName as $variantName ) {
516 $textVariant = $titlesAllVariants[$variantName][$i];
517 if ( $textVariant === $text ) {
521 $variantTitle = Title
::makeTitle( $ns, $textVariant );
522 if ( is_null( $variantTitle ) ) {
526 // Self-link checking for mixed/different variant titles. At this point, we
527 // already know the exact title does not exist, so the link cannot be to a
528 // variant of the current title that exists as a separate page.
529 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
530 $this->internals
[$ns][$index]['selflink'] = true;
534 $linkBatch->addObj( $variantTitle );
535 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
539 // process categories, check if a category exists in some variant
540 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
541 $varCategories = array(); // category replacements oldDBkey => newDBkey
542 foreach ( $output->getCategoryLinks() as $category ) {
543 $categoryTitle = Title
::makeTitleSafe( NS_CATEGORY
, $category );
544 $linkBatch->addObj( $categoryTitle );
545 $variants = $wgContLang->autoConvertToAllVariants( $category );
546 foreach ( $variants as $variant ) {
547 if ( $variant !== $category ) {
548 $variantTitle = Title
::makeTitleSafe( NS_CATEGORY
, $variant );
549 if ( is_null( $variantTitle ) ) {
552 $linkBatch->addObj( $variantTitle );
553 $categoryMap[$variant] = array( $category, $categoryTitle );
558 if ( !$linkBatch->isEmpty() ) {
560 $dbr = wfGetDB( DB_SLAVE
);
561 $fields = array( 'page_id', 'page_namespace', 'page_title',
562 'page_is_redirect', 'page_len', 'page_latest' );
564 if ( $wgContentHandlerUseDB ) {
565 $fields[] = 'page_content_model';
568 $varRes = $dbr->select( 'page',
570 $linkBatch->constructSet( 'page', $dbr ),
574 $linkcolour_ids = array();
576 // for each found variants, figure out link holders and replace
577 foreach ( $varRes as $s ) {
579 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
580 $varPdbk = $variantTitle->getPrefixedDBkey();
581 $vardbk = $variantTitle->getDBkey();
583 $holderKeys = array();
584 if ( isset( $variantMap[$varPdbk] ) ) {
585 $holderKeys = $variantMap[$varPdbk];
586 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
587 $output->addLink( $variantTitle, $s->page_id
);
590 // loop over link holders
591 foreach ( $holderKeys as $key ) {
592 list( $ns, $index ) = explode( ':', $key, 2 );
593 $entry =& $this->internals
[$ns][$index];
594 $pdbk = $entry['pdbk'];
596 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
597 // found link in some of the variants, replace the link holder data
598 $entry['title'] = $variantTitle;
599 $entry['pdbk'] = $varPdbk;
601 // set pdbk and colour
602 # @todo FIXME: Convoluted data flow
603 # The redirect status and length is passed to getLinkColour via the LinkCache
604 # Use formal parameters instead
605 $colours[$varPdbk] = Linker
::getLinkColour( $variantTitle, $threshold );
606 $linkcolour_ids[$s->page_id
] = $pdbk;
610 // check if the object is a variant of a category
611 if ( isset( $categoryMap[$vardbk] ) ) {
612 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
613 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
614 $varCategories[$oldkey] = $vardbk;
618 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
620 // rebuild the categories in original order (if there are replacements)
621 if ( count( $varCategories ) > 0 ) {
623 $originalCats = $output->getCategories();
624 foreach ( $originalCats as $cat => $sortkey ) {
625 // make the replacement
626 if ( array_key_exists( $cat, $varCategories ) ) {
627 $newCats[$varCategories[$cat]] = $sortkey;
629 $newCats[$cat] = $sortkey;
632 $output->setCategoryLinks( $newCats );
638 * Replace <!--LINK--> link placeholders with plain text of links
639 * (not HTML-formatted).
641 * @param string $text
644 public function replaceText( $text ) {
645 wfProfileIn( __METHOD__
);
647 $text = preg_replace_callback(
648 '/<!--(LINK|IWLINK) (.*?)-->/',
649 array( &$this, 'replaceTextCallback' ),
652 wfProfileOut( __METHOD__
);
657 * Callback for replaceText()
659 * @param array $matches
663 public function replaceTextCallback( $matches ) {
666 if ( $type == 'LINK' ) {
667 list( $ns, $index ) = explode( ':', $key, 2 );
668 if ( isset( $this->internals
[$ns][$index]['text'] ) ) {
669 return $this->internals
[$ns][$index]['text'];
671 } elseif ( $type == 'IWLINK' ) {
672 if ( isset( $this->interwikis
[$key]['text'] ) ) {
673 return $this->interwikis
[$key]['text'];