Removed action=print; I can't find anything using this
[mediawiki.git] / includes / parser / LinkHolderArray.php
blob80377325c0b8f10a06331af92958a3f097be082b
1 <?php
2 /**
3 * Holder of replacement pairs for wiki links
5 * @file
6 */
8 /**
9 * @ingroup Parser
11 class LinkHolderArray {
12 var $internals = array(), $interwikis = array();
13 var $size = 0;
14 var $parent;
15 protected $tempIdOffset;
17 function __construct( $parent ) {
18 $this->parent = $parent;
21 /**
22 * Reduce memory usage to reduce the impact of circular references
24 function __destruct() {
25 foreach ( $this as $name => $value ) {
26 unset( $this->$name );
30 /**
31 * Don't serialize the parent object, it is big, and not needed when it is
32 * a parameter to mergeForeign(), which is the only application of
33 * serializing at present.
35 * Compact the titles, only serialize the text form.
37 function __sleep() {
38 foreach ( $this->internals as $ns => &$nsLinks ) {
39 foreach ( $nsLinks as $key => &$entry ) {
40 unset( $entry['title'] );
43 unset( $nsLinks );
44 unset( $entry );
46 foreach ( $this->interwikis as $key => &$entry ) {
47 unset( $entry['title'] );
49 unset( $entry );
51 return array( 'internals', 'interwikis', 'size' );
54 /**
55 * Recreate the Title objects
57 function __wakeup() {
58 foreach ( $this->internals as $ns => &$nsLinks ) {
59 foreach ( $nsLinks as $key => &$entry ) {
60 $entry['title'] = Title::newFromText( $entry['pdbk'] );
63 unset( $nsLinks );
64 unset( $entry );
66 foreach ( $this->interwikis as $key => &$entry ) {
67 $entry['title'] = Title::newFromText( $entry['pdbk'] );
69 unset( $entry );
72 /**
73 * Merge another LinkHolderArray into this one
74 * @param $other LinkHolderArray
76 function merge( $other ) {
77 foreach ( $other->internals as $ns => $entries ) {
78 $this->size += count( $entries );
79 if ( !isset( $this->internals[$ns] ) ) {
80 $this->internals[$ns] = $entries;
81 } else {
82 $this->internals[$ns] += $entries;
85 $this->interwikis += $other->interwikis;
88 /**
89 * Merge a LinkHolderArray from another parser instance into this one. The
90 * keys will not be preserved. Any text which went with the old
91 * LinkHolderArray and needs to work with the new one should be passed in
92 * the $texts array. The strings in this array will have their link holders
93 * converted for use in the destination link holder. The resulting array of
94 * strings will be returned.
96 * @param $other LinkHolderArray
97 * @param $text Array of strings
98 * @return Array
100 function mergeForeign( $other, $texts ) {
101 $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
102 $maxId = 0;
104 # Renumber internal links
105 foreach ( $other->internals as $ns => $nsLinks ) {
106 foreach ( $nsLinks as $key => $entry ) {
107 $newKey = $idOffset + $key;
108 $this->internals[$ns][$newKey] = $entry;
109 $maxId = $newKey > $maxId ? $newKey : $maxId;
112 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
113 array( $this, 'mergeForeignCallback' ), $texts );
115 # Renumber interwiki links
116 foreach ( $other->interwikis as $key => $entry ) {
117 $newKey = $idOffset + $key;
118 $this->interwikis[$newKey] = $entry;
119 $maxId = $newKey > $maxId ? $newKey : $maxId;
121 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
122 array( $this, 'mergeForeignCallback' ), $texts );
124 # Set the parent link ID to be beyond the highest used ID
125 $this->parent->setLinkID( $maxId + 1 );
126 $this->tempIdOffset = null;
127 return $texts;
130 protected function mergeForeignCallback( $m ) {
131 return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
135 * Get a subset of the current LinkHolderArray which is sufficient to
136 * interpret the given text.
138 function getSubArray( $text ) {
139 $sub = new LinkHolderArray( $this->parent );
141 # Internal links
142 $pos = 0;
143 while ( $pos < strlen( $text ) ) {
144 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
145 $text, $m, PREG_OFFSET_CAPTURE, $pos ) )
147 break;
149 $ns = $m[1][0];
150 $key = $m[2][0];
151 $sub->internals[$ns][$key] = $this->internals[$ns][$key];
152 $pos = $m[0][1] + strlen( $m[0][0] );
155 # Interwiki links
156 $pos = 0;
157 while ( $pos < strlen( $text ) ) {
158 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
159 break;
161 $key = $m[1][0];
162 $sub->interwikis[$key] = $this->interwikis[$key];
163 $pos = $m[0][1] + strlen( $m[0][0] );
165 return $sub;
169 * Returns true if the memory requirements of this object are getting large
171 function isBig() {
172 global $wgLinkHolderBatchSize;
173 return $this->size > $wgLinkHolderBatchSize;
177 * Clear all stored link holders.
178 * Make sure you don't have any text left using these link holders, before you call this
180 function clear() {
181 $this->internals = array();
182 $this->interwikis = array();
183 $this->size = 0;
187 * Make a link placeholder. The text returned can be later resolved to a real link with
188 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
189 * parsing of interwiki links, and secondly to allow all existence checks and
190 * article length checks (for stub links) to be bundled into a single query.
192 * @param $nt Title
194 function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
195 wfProfileIn( __METHOD__ );
196 if ( ! is_object($nt) ) {
197 # Fail gracefully
198 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
199 } else {
200 # Separate the link trail from the rest of the link
201 list( $inside, $trail ) = Linker::splitTrail( $trail );
203 $entry = array(
204 'title' => $nt,
205 'text' => $prefix.$text.$inside,
206 'pdbk' => $nt->getPrefixedDBkey(),
208 if ( $query !== array() ) {
209 $entry['query'] = $query;
212 if ( $nt->isExternal() ) {
213 // Use a globally unique ID to keep the objects mergable
214 $key = $this->parent->nextLinkID();
215 $this->interwikis[$key] = $entry;
216 $retVal = "<!--IWLINK $key-->{$trail}";
217 } else {
218 $key = $this->parent->nextLinkID();
219 $ns = $nt->getNamespace();
220 $this->internals[$ns][$key] = $entry;
221 $retVal = "<!--LINK $ns:$key-->{$trail}";
223 $this->size++;
225 wfProfileOut( __METHOD__ );
226 return $retVal;
230 * FIXME: update documentation. makeLinkObj() is deprecated.
231 * Replace <!--LINK--> link placeholders with actual links, in the buffer
232 * Placeholders created in Skin::makeLinkObj()
233 * Returns an array of link CSS classes, indexed by PDBK.
235 function replace( &$text ) {
236 wfProfileIn( __METHOD__ );
238 $colours = $this->replaceInternal( $text );
239 $this->replaceInterwiki( $text );
241 wfProfileOut( __METHOD__ );
242 return $colours;
246 * Replace internal links
248 protected function replaceInternal( &$text ) {
249 if ( !$this->internals ) {
250 return;
253 wfProfileIn( __METHOD__ );
254 global $wgContLang;
256 $colours = array();
257 $linkCache = LinkCache::singleton();
258 $output = $this->parent->getOutput();
260 wfProfileIn( __METHOD__.'-check' );
261 $dbr = wfGetDB( DB_SLAVE );
262 $page = $dbr->tableName( 'page' );
263 $threshold = $this->parent->getOptions()->getStubThreshold();
265 # Sort by namespace
266 ksort( $this->internals );
268 $linkcolour_ids = array();
270 # Generate query
271 $query = false;
272 $current = null;
273 $queries = array();
274 foreach ( $this->internals as $ns => $entries ) {
275 foreach ( $entries as $entry ) {
276 $title = $entry['title'];
277 $pdbk = $entry['pdbk'];
279 # Skip invalid entries.
280 # Result will be ugly, but prevents crash.
281 if ( is_null( $title ) ) {
282 continue;
285 # Check if it's a static known link, e.g. interwiki
286 if ( $title->isAlwaysKnown() ) {
287 $colours[$pdbk] = '';
288 } elseif ( $ns == NS_SPECIAL ) {
289 $colours[$pdbk] = 'new';
290 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
291 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
292 $output->addLink( $title, $id );
293 $linkcolour_ids[$id] = $pdbk;
294 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
295 $colours[$pdbk] = 'new';
296 } else {
297 # Not in the link cache, add it to the query
298 $queries[$ns][] = $title->getDBkey();
302 if ( $queries ) {
303 $where = array();
304 foreach( $queries as $ns => $pages ){
305 $where[] = $dbr->makeList(
306 array(
307 'page_namespace' => $ns,
308 'page_title' => $pages,
310 LIST_AND
314 $res = $dbr->select(
315 'page',
316 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
317 $dbr->makeList( $where, LIST_OR ),
318 __METHOD__
321 # Fetch data and form into an associative array
322 # non-existent = broken
323 foreach ( $res as $s ) {
324 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
325 $pdbk = $title->getPrefixedDBkey();
326 $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect, $s->page_latest );
327 $output->addLink( $title, $s->page_id );
328 # FIXME: convoluted data flow
329 # The redirect status and length is passed to getLinkColour via the LinkCache
330 # Use formal parameters instead
331 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
332 //add id to the extension todolist
333 $linkcolour_ids[$s->page_id] = $pdbk;
335 unset( $res );
337 if ( count($linkcolour_ids) ) {
338 //pass an array of page_ids to an extension
339 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
341 wfProfileOut( __METHOD__.'-check' );
343 # Do a second query for different language variants of links and categories
344 if($wgContLang->hasVariants()) {
345 $this->doVariants( $colours );
348 # Construct search and replace arrays
349 wfProfileIn( __METHOD__.'-construct' );
350 $replacePairs = array();
351 foreach ( $this->internals as $ns => $entries ) {
352 foreach ( $entries as $index => $entry ) {
353 $pdbk = $entry['pdbk'];
354 $title = $entry['title'];
355 $query = isset( $entry['query'] ) ? $entry['query'] : array();
356 $key = "$ns:$index";
357 $searchkey = "<!--LINK $key-->";
358 $displayText = $entry['text'];
359 if ( $displayText === '' ) {
360 $displayText = null;
362 if ( !isset( $colours[$pdbk] ) ) {
363 $colours[$pdbk] = 'new';
365 $attribs = array();
366 if ( $colours[$pdbk] == 'new' ) {
367 $linkCache->addBadLinkObj( $title );
368 $output->addLink( $title, 0 );
369 $type = array( 'broken' );
370 } else {
371 if ( $colours[$pdbk] != '' ) {
372 $attribs['class'] = $colours[$pdbk];
374 $type = array( 'known', 'noclasses' );
376 $replacePairs[$searchkey] = Linker::link( $title, $displayText,
377 $attribs, $query, $type );
380 $replacer = new HashtableReplacer( $replacePairs, 1 );
381 wfProfileOut( __METHOD__.'-construct' );
383 # Do the thing
384 wfProfileIn( __METHOD__.'-replace' );
385 $text = preg_replace_callback(
386 '/(<!--LINK .*?-->)/',
387 $replacer->cb(),
388 $text);
390 wfProfileOut( __METHOD__.'-replace' );
391 wfProfileOut( __METHOD__ );
395 * Replace interwiki links
397 protected function replaceInterwiki( &$text ) {
398 if ( empty( $this->interwikis ) ) {
399 return;
402 wfProfileIn( __METHOD__ );
403 # Make interwiki link HTML
404 $output = $this->parent->getOutput();
405 $replacePairs = array();
406 foreach( $this->interwikis as $key => $link ) {
407 $replacePairs[$key] = Linker::link( $link['title'], $link['text'] );
408 $output->addInterwikiLink( $link['title'] );
410 $replacer = new HashtableReplacer( $replacePairs, 1 );
412 $text = preg_replace_callback(
413 '/<!--IWLINK (.*?)-->/',
414 $replacer->cb(),
415 $text );
416 wfProfileOut( __METHOD__ );
420 * Modify $this->internals and $colours according to language variant linking rules
422 protected function doVariants( &$colours ) {
423 global $wgContLang;
424 $linkBatch = new LinkBatch();
425 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
426 $output = $this->parent->getOutput();
427 $linkCache = LinkCache::singleton();
428 $threshold = $this->parent->getOptions()->getStubThreshold();
429 $titlesToBeConverted = '';
430 $titlesAttrs = array();
432 // Concatenate titles to a single string, thus we only need auto convert the
433 // single string to all variants. This would improve parser's performance
434 // significantly.
435 foreach ( $this->internals as $ns => $entries ) {
436 foreach ( $entries as $index => $entry ) {
437 $pdbk = $entry['pdbk'];
438 // we only deal with new links (in its first query)
439 if ( !isset( $colours[$pdbk] ) ) {
440 $title = $entry['title'];
441 $titleText = $title->getText();
442 $titlesAttrs[] = array(
443 'ns' => $ns,
444 'key' => "$ns:$index",
445 'titleText' => $titleText,
447 // separate titles with \0 because it would never appears
448 // in a valid title
449 $titlesToBeConverted .= $titleText . "\0";
454 // Now do the conversion and explode string to text of titles
455 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( $titlesToBeConverted );
456 $allVariantsName = array_keys( $titlesAllVariants );
457 foreach ( $titlesAllVariants as &$titlesVariant ) {
458 $titlesVariant = explode( "\0", $titlesVariant );
460 $l = count( $titlesAttrs );
461 // Then add variants of links to link batch
462 for ( $i = 0; $i < $l; $i ++ ) {
463 foreach ( $allVariantsName as $variantName ) {
464 $textVariant = $titlesAllVariants[$variantName][$i];
465 if ( $textVariant != $titlesAttrs[$i]['titleText'] ) {
466 $variantTitle = Title::makeTitle( $titlesAttrs[$i]['ns'], $textVariant );
467 if( is_null( $variantTitle ) ) {
468 continue;
470 $linkBatch->addObj( $variantTitle );
471 $variantMap[$variantTitle->getPrefixedDBkey()][] = $titlesAttrs[$i]['key'];
476 // process categories, check if a category exists in some variant
477 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
478 $varCategories = array(); // category replacements oldDBkey => newDBkey
479 foreach( $output->getCategoryLinks() as $category ){
480 $variants = $wgContLang->autoConvertToAllVariants( $category );
481 foreach($variants as $variant){
482 if($variant != $category){
483 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
484 if(is_null($variantTitle)) continue;
485 $linkBatch->addObj( $variantTitle );
486 $categoryMap[$variant] = $category;
492 if(!$linkBatch->isEmpty()){
493 // construct query
494 $dbr = wfGetDB( DB_SLAVE );
495 $varRes = $dbr->select( 'page',
496 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len' ),
497 $linkBatch->constructSet( 'page', $dbr ),
498 __METHOD__
501 $linkcolour_ids = array();
503 // for each found variants, figure out link holders and replace
504 foreach ( $varRes as $s ) {
506 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
507 $varPdbk = $variantTitle->getPrefixedDBkey();
508 $vardbk = $variantTitle->getDBkey();
510 $holderKeys = array();
511 if( isset( $variantMap[$varPdbk] ) ) {
512 $holderKeys = $variantMap[$varPdbk];
513 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
514 $output->addLink( $variantTitle, $s->page_id );
517 // loop over link holders
518 foreach( $holderKeys as $key ) {
519 list( $ns, $index ) = explode( ':', $key, 2 );
520 $entry =& $this->internals[$ns][$index];
521 $pdbk = $entry['pdbk'];
523 if(!isset($colours[$pdbk])){
524 // found link in some of the variants, replace the link holder data
525 $entry['title'] = $variantTitle;
526 $entry['pdbk'] = $varPdbk;
528 // set pdbk and colour
529 # FIXME: convoluted data flow
530 # The redirect status and length is passed to getLinkColour via the LinkCache
531 # Use formal parameters instead
532 $colours[$varPdbk] = Linker::getLinkColour( $variantTitle, $threshold );
533 $linkcolour_ids[$s->page_id] = $pdbk;
537 // check if the object is a variant of a category
538 if(isset($categoryMap[$vardbk])){
539 $oldkey = $categoryMap[$vardbk];
540 if($oldkey != $vardbk)
541 $varCategories[$oldkey]=$vardbk;
544 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
546 // rebuild the categories in original order (if there are replacements)
547 if(count($varCategories)>0){
548 $newCats = array();
549 $originalCats = $output->getCategories();
550 foreach($originalCats as $cat => $sortkey){
551 // make the replacement
552 if( array_key_exists($cat,$varCategories) )
553 $newCats[$varCategories[$cat]] = $sortkey;
554 else $newCats[$cat] = $sortkey;
556 $output->setCategoryLinks($newCats);
562 * Replace <!--LINK--> link placeholders with plain text of links
563 * (not HTML-formatted).
565 * @param $text String
566 * @return String
568 function replaceText( $text ) {
569 wfProfileIn( __METHOD__ );
571 $text = preg_replace_callback(
572 '/<!--(LINK|IWLINK) (.*?)-->/',
573 array( &$this, 'replaceTextCallback' ),
574 $text );
576 wfProfileOut( __METHOD__ );
577 return $text;
581 * Callback for replaceText()
583 * @param $matches Array
584 * @return string
585 * @private
587 function replaceTextCallback( $matches ) {
588 $type = $matches[1];
589 $key = $matches[2];
590 if( $type == 'LINK' ) {
591 list( $ns, $index ) = explode( ':', $key, 2 );
592 if( isset( $this->internals[$ns][$index]['text'] ) ) {
593 return $this->internals[$ns][$index]['text'];
595 } elseif( $type == 'IWLINK' ) {
596 if( isset( $this->interwikis[$key]['text'] ) ) {
597 return $this->interwikis[$key]['text'];
600 return $matches[0];