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 if ( !is_object( $nt ) ) {
234 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
236 # Separate the link trail from the rest of the link
237 list( $inside, $trail ) = Linker
::splitTrail( $trail );
241 'text' => $prefix . $text . $inside,
242 'pdbk' => $nt->getPrefixedDBkey(),
244 if ( $query !== array() ) {
245 $entry['query'] = $query;
248 if ( $nt->isExternal() ) {
249 // Use a globally unique ID to keep the objects mergable
250 $key = $this->parent
->nextLinkID();
251 $this->interwikis
[$key] = $entry;
252 $retVal = "<!--IWLINK $key-->{$trail}";
254 $key = $this->parent
->nextLinkID();
255 $ns = $nt->getNamespace();
256 $this->internals
[$ns][$key] = $entry;
257 $retVal = "<!--LINK $ns:$key-->{$trail}";
265 * Replace <!--LINK--> link placeholders with actual links, in the buffer
267 * @param string $text
269 public function replace( &$text ) {
271 $this->replaceInternal( $text );
272 $this->replaceInterwiki( $text );
277 * Replace internal links
278 * @param string $text
280 protected function replaceInternal( &$text ) {
281 if ( !$this->internals
) {
285 global $wgContLang, $wgContentHandlerUseDB;
288 $linkCache = LinkCache
::singleton();
289 $output = $this->parent
->getOutput();
291 $dbr = wfGetDB( DB_SLAVE
);
292 $threshold = $this->parent
->getOptions()->getStubThreshold();
295 ksort( $this->internals
);
297 $linkcolour_ids = array();
301 foreach ( $this->internals
as $ns => $entries ) {
302 foreach ( $entries as $entry ) {
303 /** @var Title $title */
304 $title = $entry['title'];
305 $pdbk = $entry['pdbk'];
307 # Skip invalid entries.
308 # Result will be ugly, but prevents crash.
309 if ( is_null( $title ) ) {
313 # Check if it's a static known link, e.g. interwiki
314 if ( $title->isAlwaysKnown() ) {
315 $colours[$pdbk] = '';
316 } elseif ( $ns == NS_SPECIAL
) {
317 $colours[$pdbk] = 'new';
319 $id = $linkCache->getGoodLinkID( $pdbk );
321 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
322 $output->addLink( $title, $id );
323 $linkcolour_ids[$id] = $pdbk;
324 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
325 $colours[$pdbk] = 'new';
327 # Not in the link cache, add it to the query
328 $queries[$ns][] = $title->getDBkey();
335 foreach ( $queries as $ns => $pages ) {
336 $where[] = $dbr->makeList(
338 'page_namespace' => $ns,
339 'page_title' => array_unique( $pages ),
345 $fields = array( 'page_id', 'page_namespace', 'page_title',
346 'page_is_redirect', 'page_len', 'page_latest' );
348 if ( $wgContentHandlerUseDB ) {
349 $fields[] = 'page_content_model';
355 $dbr->makeList( $where, LIST_OR
),
359 # Fetch data and form into an associative array
360 # non-existent = broken
361 foreach ( $res as $s ) {
362 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
363 $pdbk = $title->getPrefixedDBkey();
364 $linkCache->addGoodLinkObjFromRow( $title, $s );
365 $output->addLink( $title, $s->page_id
);
366 # @todo FIXME: Convoluted data flow
367 # The redirect status and length is passed to getLinkColour via the LinkCache
368 # Use formal parameters instead
369 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
370 // add id to the extension todolist
371 $linkcolour_ids[$s->page_id
] = $pdbk;
375 if ( count( $linkcolour_ids ) ) {
376 // pass an array of page_ids to an extension
377 Hooks
::run( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
380 # Do a second query for different language variants of links and categories
381 if ( $wgContLang->hasVariants() ) {
382 $this->doVariants( $colours );
385 # Construct search and replace arrays
386 $replacePairs = array();
387 foreach ( $this->internals
as $ns => $entries ) {
388 foreach ( $entries as $index => $entry ) {
389 $pdbk = $entry['pdbk'];
390 $title = $entry['title'];
391 $query = isset( $entry['query'] ) ?
$entry['query'] : array();
393 $searchkey = "<!--LINK $key-->";
394 $displayText = $entry['text'];
395 if ( isset( $entry['selflink'] ) ) {
396 $replacePairs[$searchkey] = Linker
::makeSelfLinkObj( $title, $displayText, $query );
399 if ( $displayText === '' ) {
402 if ( !isset( $colours[$pdbk] ) ) {
403 $colours[$pdbk] = 'new';
406 if ( $colours[$pdbk] == 'new' ) {
407 $linkCache->addBadLinkObj( $title );
408 $output->addLink( $title, 0 );
409 $type = array( 'broken' );
411 if ( $colours[$pdbk] != '' ) {
412 $attribs['class'] = $colours[$pdbk];
414 $type = array( 'known', 'noclasses' );
416 $replacePairs[$searchkey] = Linker
::link( $title, $displayText,
417 $attribs, $query, $type );
420 $replacer = new HashtableReplacer( $replacePairs, 1 );
423 $text = preg_replace_callback(
424 '/(<!--LINK .*?-->)/',
432 * Replace interwiki links
433 * @param string $text
435 protected function replaceInterwiki( &$text ) {
436 if ( empty( $this->interwikis
) ) {
440 # Make interwiki link HTML
441 $output = $this->parent
->getOutput();
442 $replacePairs = array();
444 'stubThreshold' => $this->parent
->getOptions()->getStubThreshold(),
446 foreach ( $this->interwikis
as $key => $link ) {
447 $replacePairs[$key] = Linker
::link( $link['title'], $link['text'], array(), array(), $options );
448 $output->addInterwikiLink( $link['title'] );
450 $replacer = new HashtableReplacer( $replacePairs, 1 );
452 $text = preg_replace_callback(
453 '/<!--IWLINK (.*?)-->/',
459 * Modify $this->internals and $colours according to language variant linking rules
460 * @param array $colours
462 protected function doVariants( &$colours ) {
463 global $wgContLang, $wgContentHandlerUseDB;
464 $linkBatch = new LinkBatch();
465 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
466 $output = $this->parent
->getOutput();
467 $linkCache = LinkCache
::singleton();
468 $threshold = $this->parent
->getOptions()->getStubThreshold();
469 $titlesToBeConverted = '';
470 $titlesAttrs = array();
472 // Concatenate titles to a single string, thus we only need auto convert the
473 // single string to all variants. This would improve parser's performance
475 foreach ( $this->internals
as $ns => $entries ) {
476 if ( $ns == NS_SPECIAL
) {
479 foreach ( $entries as $index => $entry ) {
480 $pdbk = $entry['pdbk'];
481 // we only deal with new links (in its first query)
482 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
483 $titlesAttrs[] = array( $index, $entry['title'] );
484 // separate titles with \0 because it would never appears
486 $titlesToBeConverted .= $entry['title']->getText() . "\0";
491 // Now do the conversion and explode string to text of titles
492 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
493 $allVariantsName = array_keys( $titlesAllVariants );
494 foreach ( $titlesAllVariants as &$titlesVariant ) {
495 $titlesVariant = explode( "\0", $titlesVariant );
498 // Then add variants of links to link batch
499 $parentTitle = $this->parent
->getTitle();
500 foreach ( $titlesAttrs as $i => $attrs ) {
501 /** @var Title $title */
502 list( $index, $title ) = $attrs;
503 $ns = $title->getNamespace();
504 $text = $title->getText();
506 foreach ( $allVariantsName as $variantName ) {
507 $textVariant = $titlesAllVariants[$variantName][$i];
508 if ( $textVariant === $text ) {
512 $variantTitle = Title
::makeTitle( $ns, $textVariant );
513 if ( is_null( $variantTitle ) ) {
517 // Self-link checking for mixed/different variant titles. At this point, we
518 // already know the exact title does not exist, so the link cannot be to a
519 // variant of the current title that exists as a separate page.
520 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
521 $this->internals
[$ns][$index]['selflink'] = true;
525 $linkBatch->addObj( $variantTitle );
526 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
530 // process categories, check if a category exists in some variant
531 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
532 $varCategories = array(); // category replacements oldDBkey => newDBkey
533 foreach ( $output->getCategoryLinks() as $category ) {
534 $categoryTitle = Title
::makeTitleSafe( NS_CATEGORY
, $category );
535 $linkBatch->addObj( $categoryTitle );
536 $variants = $wgContLang->autoConvertToAllVariants( $category );
537 foreach ( $variants as $variant ) {
538 if ( $variant !== $category ) {
539 $variantTitle = Title
::makeTitleSafe( NS_CATEGORY
, $variant );
540 if ( is_null( $variantTitle ) ) {
543 $linkBatch->addObj( $variantTitle );
544 $categoryMap[$variant] = array( $category, $categoryTitle );
549 if ( !$linkBatch->isEmpty() ) {
551 $dbr = wfGetDB( DB_SLAVE
);
552 $fields = array( 'page_id', 'page_namespace', 'page_title',
553 'page_is_redirect', 'page_len', 'page_latest' );
555 if ( $wgContentHandlerUseDB ) {
556 $fields[] = 'page_content_model';
559 $varRes = $dbr->select( 'page',
561 $linkBatch->constructSet( 'page', $dbr ),
565 $linkcolour_ids = array();
567 // for each found variants, figure out link holders and replace
568 foreach ( $varRes as $s ) {
569 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
570 $varPdbk = $variantTitle->getPrefixedDBkey();
571 $vardbk = $variantTitle->getDBkey();
573 $holderKeys = array();
574 if ( isset( $variantMap[$varPdbk] ) ) {
575 $holderKeys = $variantMap[$varPdbk];
576 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
577 $output->addLink( $variantTitle, $s->page_id
);
580 // loop over link holders
581 foreach ( $holderKeys as $key ) {
582 list( $ns, $index ) = explode( ':', $key, 2 );
583 $entry =& $this->internals
[$ns][$index];
584 $pdbk = $entry['pdbk'];
586 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
587 // found link in some of the variants, replace the link holder data
588 $entry['title'] = $variantTitle;
589 $entry['pdbk'] = $varPdbk;
591 // set pdbk and colour
592 # @todo FIXME: Convoluted data flow
593 # The redirect status and length is passed to getLinkColour via the LinkCache
594 # Use formal parameters instead
595 $colours[$varPdbk] = Linker
::getLinkColour( $variantTitle, $threshold );
596 $linkcolour_ids[$s->page_id
] = $pdbk;
600 // check if the object is a variant of a category
601 if ( isset( $categoryMap[$vardbk] ) ) {
602 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
603 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
604 $varCategories[$oldkey] = $vardbk;
608 Hooks
::run( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
610 // rebuild the categories in original order (if there are replacements)
611 if ( count( $varCategories ) > 0 ) {
613 $originalCats = $output->getCategories();
614 foreach ( $originalCats as $cat => $sortkey ) {
615 // make the replacement
616 if ( array_key_exists( $cat, $varCategories ) ) {
617 $newCats[$varCategories[$cat]] = $sortkey;
619 $newCats[$cat] = $sortkey;
622 $output->setCategoryLinks( $newCats );
628 * Replace <!--LINK--> link placeholders with plain text of links
629 * (not HTML-formatted).
631 * @param string $text
634 public function replaceText( $text ) {
636 $text = preg_replace_callback(
637 '/<!--(LINK|IWLINK) (.*?)-->/',
638 array( &$this, 'replaceTextCallback' ),
645 * Callback for replaceText()
647 * @param array $matches
651 public function replaceTextCallback( $matches ) {
654 if ( $type == 'LINK' ) {
655 list( $ns, $index ) = explode( ':', $key, 2 );
656 if ( isset( $this->internals
[$ns][$index]['text'] ) ) {
657 return $this->internals
[$ns][$index]['text'];
659 } elseif ( $type == 'IWLINK' ) {
660 if ( isset( $this->interwikis
[$key]['text'] ) ) {
661 return $this->interwikis
[$key]['text'];