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 var $internals = array(), $interwikis = array();
31 protected $tempIdOffset;
33 function __construct( $parent ) {
34 $this->parent
= $parent;
38 * Reduce memory usage to reduce the impact of circular references
40 function __destruct() {
41 foreach ( $this as $name => $value ) {
42 unset( $this->$name );
47 * Don't serialize the parent object, it is big, and not needed when it is
48 * a parameter to mergeForeign(), which is the only application of
49 * serializing at present.
51 * Compact the titles, only serialize the text form.
55 foreach ( $this->internals
as &$nsLinks ) {
56 foreach ( $nsLinks as &$entry ) {
57 unset( $entry['title'] );
63 foreach ( $this->interwikis
as &$entry ) {
64 unset( $entry['title'] );
68 return array( 'internals', 'interwikis', 'size' );
72 * Recreate the Title objects
75 foreach ( $this->internals
as &$nsLinks ) {
76 foreach ( $nsLinks as &$entry ) {
77 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
83 foreach ( $this->interwikis
as &$entry ) {
84 $entry['title'] = Title
::newFromText( $entry['pdbk'] );
90 * Merge another LinkHolderArray into this one
91 * @param $other LinkHolderArray
93 function merge( $other ) {
94 foreach ( $other->internals
as $ns => $entries ) {
95 $this->size +
= count( $entries );
96 if ( !isset( $this->internals
[$ns] ) ) {
97 $this->internals
[$ns] = $entries;
99 $this->internals
[$ns] +
= $entries;
102 $this->interwikis +
= $other->interwikis
;
106 * Merge a LinkHolderArray from another parser instance into this one. The
107 * keys will not be preserved. Any text which went with the old
108 * LinkHolderArray and needs to work with the new one should be passed in
109 * the $texts array. The strings in this array will have their link holders
110 * converted for use in the destination link holder. The resulting array of
111 * strings will be returned.
113 * @param $other LinkHolderArray
114 * @param array $texts of strings
117 function mergeForeign( $other, $texts ) {
118 $this->tempIdOffset
= $idOffset = $this->parent
->nextLinkID();
121 # Renumber internal links
122 foreach ( $other->internals
as $ns => $nsLinks ) {
123 foreach ( $nsLinks as $key => $entry ) {
124 $newKey = $idOffset +
$key;
125 $this->internals
[$ns][$newKey] = $entry;
126 $maxId = $newKey > $maxId ?
$newKey : $maxId;
129 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
130 array( $this, 'mergeForeignCallback' ), $texts );
132 # Renumber interwiki links
133 foreach ( $other->interwikis
as $key => $entry ) {
134 $newKey = $idOffset +
$key;
135 $this->interwikis
[$newKey] = $entry;
136 $maxId = $newKey > $maxId ?
$newKey : $maxId;
138 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
139 array( $this, 'mergeForeignCallback' ), $texts );
141 # Set the parent link ID to be beyond the highest used ID
142 $this->parent
->setLinkID( $maxId +
1 );
143 $this->tempIdOffset
= null;
147 protected function mergeForeignCallback( $m ) {
148 return $m[1] . ( $m[2] +
$this->tempIdOffset
) . $m[3];
152 * Get a subset of the current LinkHolderArray which is sufficient to
153 * interpret the given text.
154 * @return LinkHolderArray
156 function getSubArray( $text ) {
157 $sub = new LinkHolderArray( $this->parent
);
161 while ( $pos < strlen( $text ) ) {
162 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
163 $text, $m, PREG_OFFSET_CAPTURE
, $pos ) )
169 $sub->internals
[$ns][$key] = $this->internals
[$ns][$key];
170 $pos = $m[0][1] +
strlen( $m[0][0] );
175 while ( $pos < strlen( $text ) ) {
176 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE
, $pos ) ) {
180 $sub->interwikis
[$key] = $this->interwikis
[$key];
181 $pos = $m[0][1] +
strlen( $m[0][0] );
187 * Returns true if the memory requirements of this object are getting large
191 global $wgLinkHolderBatchSize;
192 return $this->size
> $wgLinkHolderBatchSize;
196 * Clear all stored link holders.
197 * Make sure you don't have any text left using these link holders, before you call this
200 $this->internals
= array();
201 $this->interwikis
= array();
206 * Make a link placeholder. The text returned can be later resolved to a real link with
207 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
208 * parsing of interwiki links, and secondly to allow all existence checks and
209 * article length checks (for stub links) to be bundled into a single query.
212 * @param $text String
213 * @param array $query [optional]
214 * @param string $trail [optional]
215 * @param string $prefix [optional]
218 function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
219 wfProfileIn( __METHOD__
);
220 if ( !is_object( $nt ) ) {
222 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
224 # Separate the link trail from the rest of the link
225 list( $inside, $trail ) = Linker
::splitTrail( $trail );
229 'text' => $prefix . $text . $inside,
230 'pdbk' => $nt->getPrefixedDBkey(),
232 if ( $query !== array() ) {
233 $entry['query'] = $query;
236 if ( $nt->isExternal() ) {
237 // Use a globally unique ID to keep the objects mergable
238 $key = $this->parent
->nextLinkID();
239 $this->interwikis
[$key] = $entry;
240 $retVal = "<!--IWLINK $key-->{$trail}";
242 $key = $this->parent
->nextLinkID();
243 $ns = $nt->getNamespace();
244 $this->internals
[$ns][$key] = $entry;
245 $retVal = "<!--LINK $ns:$key-->{$trail}";
249 wfProfileOut( __METHOD__
);
254 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
255 * Replace <!--LINK--> link placeholders with actual links, in the buffer
256 * Placeholders created in Skin::makeLinkObj()
257 * @return array of link CSS classes, indexed by PDBK.
259 function replace( &$text ) {
260 wfProfileIn( __METHOD__
);
262 $colours = $this->replaceInternal( $text ); // FIXME: replaceInternal doesn't return a value
263 $this->replaceInterwiki( $text );
265 wfProfileOut( __METHOD__
);
270 * Replace internal links
272 protected function replaceInternal( &$text ) {
273 if ( !$this->internals
) {
277 wfProfileIn( __METHOD__
);
281 $linkCache = LinkCache
::singleton();
282 $output = $this->parent
->getOutput();
284 wfProfileIn( __METHOD__
. '-check' );
285 $dbr = wfGetDB( DB_SLAVE
);
286 $threshold = $this->parent
->getOptions()->getStubThreshold();
289 ksort( $this->internals
);
291 $linkcolour_ids = array();
295 foreach ( $this->internals
as $ns => $entries ) {
296 foreach ( $entries as $entry ) {
297 $title = $entry['title'];
298 $pdbk = $entry['pdbk'];
300 # Skip invalid entries.
301 # Result will be ugly, but prevents crash.
302 if ( is_null( $title ) ) {
306 # Check if it's a static known link, e.g. interwiki
307 if ( $title->isAlwaysKnown() ) {
308 $colours[$pdbk] = '';
309 } elseif ( $ns == NS_SPECIAL
) {
310 $colours[$pdbk] = 'new';
311 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
312 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
313 $output->addLink( $title, $id );
314 $linkcolour_ids[$id] = $pdbk;
315 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
316 $colours[$pdbk] = 'new';
318 # Not in the link cache, add it to the query
319 $queries[$ns][] = $title->getDBkey();
325 foreach ( $queries as $ns => $pages ) {
326 $where[] = $dbr->makeList(
328 'page_namespace' => $ns,
329 'page_title' => $pages,
337 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
338 $dbr->makeList( $where, LIST_OR
),
342 # Fetch data and form into an associative array
343 # non-existent = broken
344 foreach ( $res as $s ) {
345 $title = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
346 $pdbk = $title->getPrefixedDBkey();
347 $linkCache->addGoodLinkObjFromRow( $title, $s );
348 $output->addLink( $title, $s->page_id
);
349 # @todo FIXME: Convoluted data flow
350 # The redirect status and length is passed to getLinkColour via the LinkCache
351 # Use formal parameters instead
352 $colours[$pdbk] = Linker
::getLinkColour( $title, $threshold );
353 //add id to the extension todolist
354 $linkcolour_ids[$s->page_id
] = $pdbk;
358 if ( count( $linkcolour_ids ) ) {
359 //pass an array of page_ids to an extension
360 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
362 wfProfileOut( __METHOD__
. '-check' );
364 # Do a second query for different language variants of links and categories
365 if ( $wgContLang->hasVariants() ) {
366 $this->doVariants( $colours );
369 # Construct search and replace arrays
370 wfProfileIn( __METHOD__
. '-construct' );
371 $replacePairs = array();
372 foreach ( $this->internals
as $ns => $entries ) {
373 foreach ( $entries as $index => $entry ) {
374 $pdbk = $entry['pdbk'];
375 $title = $entry['title'];
376 $query = isset( $entry['query'] ) ?
$entry['query'] : array();
378 $searchkey = "<!--LINK $key-->";
379 $displayText = $entry['text'];
380 if ( $displayText === '' ) {
383 if ( !isset( $colours[$pdbk] ) ) {
384 $colours[$pdbk] = 'new';
387 if ( $colours[$pdbk] == 'new' ) {
388 $linkCache->addBadLinkObj( $title );
389 $output->addLink( $title, 0 );
390 $type = array( 'broken' );
392 if ( $colours[$pdbk] != '' ) {
393 $attribs['class'] = $colours[$pdbk];
395 $type = array( 'known', 'noclasses' );
397 $replacePairs[$searchkey] = Linker
::link( $title, $displayText,
398 $attribs, $query, $type );
401 $replacer = new HashtableReplacer( $replacePairs, 1 );
402 wfProfileOut( __METHOD__
. '-construct' );
405 wfProfileIn( __METHOD__
. '-replace' );
406 $text = preg_replace_callback(
407 '/(<!--LINK .*?-->)/',
412 wfProfileOut( __METHOD__
. '-replace' );
413 wfProfileOut( __METHOD__
);
417 * Replace interwiki links
419 protected function replaceInterwiki( &$text ) {
420 if ( empty( $this->interwikis
) ) {
424 wfProfileIn( __METHOD__
);
425 # Make interwiki link HTML
426 $output = $this->parent
->getOutput();
427 $replacePairs = array();
428 foreach ( $this->interwikis
as $key => $link ) {
429 $replacePairs[$key] = Linker
::link( $link['title'], $link['text'] );
430 $output->addInterwikiLink( $link['title'] );
432 $replacer = new HashtableReplacer( $replacePairs, 1 );
434 $text = preg_replace_callback(
435 '/<!--IWLINK (.*?)-->/',
438 wfProfileOut( __METHOD__
);
442 * Modify $this->internals and $colours according to language variant linking rules
444 protected function doVariants( &$colours ) {
446 $linkBatch = new LinkBatch();
447 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
448 $output = $this->parent
->getOutput();
449 $linkCache = LinkCache
::singleton();
450 $threshold = $this->parent
->getOptions()->getStubThreshold();
451 $titlesToBeConverted = '';
452 $titlesAttrs = array();
454 // Concatenate titles to a single string, thus we only need auto convert the
455 // single string to all variants. This would improve parser's performance
457 foreach ( $this->internals
as $ns => $entries ) {
458 foreach ( $entries as $index => $entry ) {
459 $pdbk = $entry['pdbk'];
460 // we only deal with new links (in its first query)
461 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
462 $title = $entry['title'];
463 $titleText = $title->getText();
464 $titlesAttrs[] = array(
466 'key' => "$ns:$index",
467 'titleText' => $titleText,
469 // separate titles with \0 because it would never appears
471 $titlesToBeConverted .= $titleText . "\0";
476 // Now do the conversion and explode string to text of titles
477 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
478 $allVariantsName = array_keys( $titlesAllVariants );
479 foreach ( $titlesAllVariants as &$titlesVariant ) {
480 $titlesVariant = explode( "\0", $titlesVariant );
482 $l = count( $titlesAttrs );
483 // Then add variants of links to link batch
484 for ( $i = 0; $i < $l; $i ++
) {
485 foreach ( $allVariantsName as $variantName ) {
486 $textVariant = $titlesAllVariants[$variantName][$i];
487 if ( $textVariant != $titlesAttrs[$i]['titleText'] ) {
488 $variantTitle = Title
::makeTitle( $titlesAttrs[$i]['ns'], $textVariant );
489 if ( is_null( $variantTitle ) ) {
492 $linkBatch->addObj( $variantTitle );
493 $variantMap[$variantTitle->getPrefixedDBkey()][] = $titlesAttrs[$i]['key'];
498 // process categories, check if a category exists in some variant
499 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
500 $varCategories = array(); // category replacements oldDBkey => newDBkey
501 foreach ( $output->getCategoryLinks() as $category ) {
502 $categoryTitle = Title
::makeTitleSafe( NS_CATEGORY
, $category );
503 $linkBatch->addObj( $categoryTitle );
504 $variants = $wgContLang->autoConvertToAllVariants( $category );
505 foreach ( $variants as $variant ) {
506 if ( $variant !== $category ) {
507 $variantTitle = Title
::makeTitleSafe( NS_CATEGORY
, $variant );
508 if ( is_null( $variantTitle ) ) {
511 $linkBatch->addObj( $variantTitle );
512 $categoryMap[$variant] = array( $category, $categoryTitle );
517 if ( !$linkBatch->isEmpty() ) {
519 $dbr = wfGetDB( DB_SLAVE
);
520 $varRes = $dbr->select( 'page',
521 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
522 $linkBatch->constructSet( 'page', $dbr ),
526 $linkcolour_ids = array();
528 // for each found variants, figure out link holders and replace
529 foreach ( $varRes as $s ) {
531 $variantTitle = Title
::makeTitle( $s->page_namespace
, $s->page_title
);
532 $varPdbk = $variantTitle->getPrefixedDBkey();
533 $vardbk = $variantTitle->getDBkey();
535 $holderKeys = array();
536 if ( isset( $variantMap[$varPdbk] ) ) {
537 $holderKeys = $variantMap[$varPdbk];
538 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
539 $output->addLink( $variantTitle, $s->page_id
);
542 // loop over link holders
543 foreach ( $holderKeys as $key ) {
544 list( $ns, $index ) = explode( ':', $key, 2 );
545 $entry =& $this->internals
[$ns][$index];
546 $pdbk = $entry['pdbk'];
548 if ( !isset( $colours[$pdbk] ) ||
$colours[$pdbk] === 'new' ) {
549 // found link in some of the variants, replace the link holder data
550 $entry['title'] = $variantTitle;
551 $entry['pdbk'] = $varPdbk;
553 // set pdbk and colour
554 # @todo FIXME: Convoluted data flow
555 # The redirect status and length is passed to getLinkColour via the LinkCache
556 # Use formal parameters instead
557 $colours[$varPdbk] = Linker
::getLinkColour( $variantTitle, $threshold );
558 $linkcolour_ids[$s->page_id
] = $pdbk;
562 // check if the object is a variant of a category
563 if ( isset( $categoryMap[$vardbk] ) ) {
564 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
565 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
566 $varCategories[$oldkey] = $vardbk;
570 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
572 // rebuild the categories in original order (if there are replacements)
573 if ( count( $varCategories ) > 0 ) {
575 $originalCats = $output->getCategories();
576 foreach ( $originalCats as $cat => $sortkey ) {
577 // make the replacement
578 if ( array_key_exists( $cat, $varCategories ) ) {
579 $newCats[$varCategories[$cat]] = $sortkey;
581 $newCats[$cat] = $sortkey;
584 $output->setCategoryLinks( $newCats );
590 * Replace <!--LINK--> link placeholders with plain text of links
591 * (not HTML-formatted).
593 * @param $text String
596 function replaceText( $text ) {
597 wfProfileIn( __METHOD__
);
599 $text = preg_replace_callback(
600 '/<!--(LINK|IWLINK) (.*?)-->/',
601 array( &$this, 'replaceTextCallback' ),
604 wfProfileOut( __METHOD__
);
609 * Callback for replaceText()
611 * @param $matches Array
615 function replaceTextCallback( $matches ) {
618 if ( $type == 'LINK' ) {
619 list( $ns, $index ) = explode( ':', $key, 2 );
620 if ( isset( $this->internals
[$ns][$index]['text'] ) ) {
621 return $this->internals
[$ns][$index]['text'];
623 } elseif ( $type == 'IWLINK' ) {
624 if ( isset( $this->interwikis
[$key]['text'] ) ) {
625 return $this->interwikis
[$key]['text'];