Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / parser / LinkHolderArray.php
blob7026c5ce399d6721eaab3927ef17f3cdc4473826
1 <?php
2 /**
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
20 * @file
21 * @ingroup Parser
24 /**
25 * @ingroup Parser
27 class LinkHolderArray {
28 public $internals = array();
29 public $interwikis = array();
30 public $size = 0;
32 /**
33 * @var Parser
35 public $parent;
36 protected $tempIdOffset;
38 /**
39 * @param Parser $parent
41 public function __construct( $parent ) {
42 $this->parent = $parent;
45 /**
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 );
54 /**
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.
60 * @return array
62 public function __sleep() {
63 foreach ( $this->internals as &$nsLinks ) {
64 foreach ( $nsLinks as &$entry ) {
65 unset( $entry['title'] );
68 unset( $nsLinks );
69 unset( $entry );
71 foreach ( $this->interwikis as &$entry ) {
72 unset( $entry['title'] );
74 unset( $entry );
76 return array( 'internals', 'interwikis', 'size' );
79 /**
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'] );
88 unset( $nsLinks );
89 unset( $entry );
91 foreach ( $this->interwikis as &$entry ) {
92 $entry['title'] = Title::newFromText( $entry['pdbk'] );
94 unset( $entry );
97 /**
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;
106 } else {
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
123 * @return array
125 public function mergeForeign( $other, $texts ) {
126 $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
127 $maxId = 0;
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;
152 return $texts;
156 * @param array $m
157 * @return string
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 );
172 # Internal links
173 $pos = 0;
174 while ( $pos < strlen( $text ) ) {
175 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
176 $text, $m, PREG_OFFSET_CAPTURE, $pos )
178 break;
180 $ns = $m[1][0];
181 $key = $m[2][0];
182 $sub->internals[$ns][$key] = $this->internals[$ns][$key];
183 $pos = $m[0][1] + strlen( $m[0][0] );
186 # Interwiki links
187 $pos = 0;
188 while ( $pos < strlen( $text ) ) {
189 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
190 break;
192 $key = $m[1][0];
193 $sub->interwikis[$key] = $this->interwikis[$key];
194 $pos = $m[0][1] + strlen( $m[0][0] );
196 return $sub;
200 * Returns true if the memory requirements of this object are getting large
201 * @return bool
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();
215 $this->size = 0;
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.
224 * @param Title $nt
225 * @param string $text
226 * @param array $query [optional]
227 * @param string $trail [optional]
228 * @param string $prefix [optional]
229 * @return string
231 public function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
232 if ( !is_object( $nt ) ) {
233 # Fail gracefully
234 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
235 } else {
236 # Separate the link trail from the rest of the link
237 list( $inside, $trail ) = Linker::splitTrail( $trail );
239 $entry = array(
240 'title' => $nt,
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}";
253 } else {
254 $key = $this->parent->nextLinkID();
255 $ns = $nt->getNamespace();
256 $this->internals[$ns][$key] = $entry;
257 $retVal = "<!--LINK $ns:$key-->{$trail}";
259 $this->size++;
261 return $retVal;
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 ) {
282 return;
285 global $wgContLang, $wgContentHandlerUseDB;
287 $colours = array();
288 $linkCache = LinkCache::singleton();
289 $output = $this->parent->getOutput();
291 $dbr = wfGetDB( DB_SLAVE );
292 $threshold = $this->parent->getOptions()->getStubThreshold();
294 # Sort by namespace
295 ksort( $this->internals );
297 $linkcolour_ids = array();
299 # Generate query
300 $queries = 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 ) ) {
310 continue;
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';
318 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
319 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
320 $output->addLink( $title, $id );
321 $linkcolour_ids[$id] = $pdbk;
322 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
323 $colours[$pdbk] = 'new';
324 } else {
325 # Not in the link cache, add it to the query
326 $queries[$ns][] = $title->getDBkey();
330 if ( $queries ) {
331 $where = array();
332 foreach ( $queries as $ns => $pages ) {
333 $where[] = $dbr->makeList(
334 array(
335 'page_namespace' => $ns,
336 'page_title' => array_unique( $pages ),
338 LIST_AND
342 $fields = array( 'page_id', 'page_namespace', 'page_title',
343 'page_is_redirect', 'page_len', 'page_latest' );
345 if ( $wgContentHandlerUseDB ) {
346 $fields[] = 'page_content_model';
349 $res = $dbr->select(
350 'page',
351 $fields,
352 $dbr->makeList( $where, LIST_OR ),
353 __METHOD__
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;
370 unset( $res );
372 if ( count( $linkcolour_ids ) ) {
373 //pass an array of page_ids to an extension
374 Hooks::run( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
377 # Do a second query for different language variants of links and categories
378 if ( $wgContLang->hasVariants() ) {
379 $this->doVariants( $colours );
382 # Construct search and replace arrays
383 $replacePairs = array();
384 foreach ( $this->internals as $ns => $entries ) {
385 foreach ( $entries as $index => $entry ) {
386 $pdbk = $entry['pdbk'];
387 $title = $entry['title'];
388 $query = isset( $entry['query'] ) ? $entry['query'] : array();
389 $key = "$ns:$index";
390 $searchkey = "<!--LINK $key-->";
391 $displayText = $entry['text'];
392 if ( isset( $entry['selflink'] ) ) {
393 $replacePairs[$searchkey] = Linker::makeSelfLinkObj( $title, $displayText, $query );
394 continue;
396 if ( $displayText === '' ) {
397 $displayText = null;
399 if ( !isset( $colours[$pdbk] ) ) {
400 $colours[$pdbk] = 'new';
402 $attribs = array();
403 if ( $colours[$pdbk] == 'new' ) {
404 $linkCache->addBadLinkObj( $title );
405 $output->addLink( $title, 0 );
406 $type = array( 'broken' );
407 } else {
408 if ( $colours[$pdbk] != '' ) {
409 $attribs['class'] = $colours[$pdbk];
411 $type = array( 'known', 'noclasses' );
413 $replacePairs[$searchkey] = Linker::link( $title, $displayText,
414 $attribs, $query, $type );
417 $replacer = new HashtableReplacer( $replacePairs, 1 );
419 # Do the thing
420 $text = preg_replace_callback(
421 '/(<!--LINK .*?-->)/',
422 $replacer->cb(),
423 $text
429 * Replace interwiki links
430 * @param string $text
432 protected function replaceInterwiki( &$text ) {
433 if ( empty( $this->interwikis ) ) {
434 return;
437 # Make interwiki link HTML
438 $output = $this->parent->getOutput();
439 $replacePairs = array();
440 foreach ( $this->interwikis as $key => $link ) {
441 $replacePairs[$key] = Linker::link( $link['title'], $link['text'] );
442 $output->addInterwikiLink( $link['title'] );
444 $replacer = new HashtableReplacer( $replacePairs, 1 );
446 $text = preg_replace_callback(
447 '/<!--IWLINK (.*?)-->/',
448 $replacer->cb(),
449 $text );
453 * Modify $this->internals and $colours according to language variant linking rules
454 * @param array $colours
456 protected function doVariants( &$colours ) {
457 global $wgContLang, $wgContentHandlerUseDB;
458 $linkBatch = new LinkBatch();
459 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
460 $output = $this->parent->getOutput();
461 $linkCache = LinkCache::singleton();
462 $threshold = $this->parent->getOptions()->getStubThreshold();
463 $titlesToBeConverted = '';
464 $titlesAttrs = array();
466 // Concatenate titles to a single string, thus we only need auto convert the
467 // single string to all variants. This would improve parser's performance
468 // significantly.
469 foreach ( $this->internals as $ns => $entries ) {
470 if ( $ns == NS_SPECIAL ) {
471 continue;
473 foreach ( $entries as $index => $entry ) {
474 $pdbk = $entry['pdbk'];
475 // we only deal with new links (in its first query)
476 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
477 $titlesAttrs[] = array( $index, $entry['title'] );
478 // separate titles with \0 because it would never appears
479 // in a valid title
480 $titlesToBeConverted .= $entry['title']->getText() . "\0";
485 // Now do the conversion and explode string to text of titles
486 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
487 $allVariantsName = array_keys( $titlesAllVariants );
488 foreach ( $titlesAllVariants as &$titlesVariant ) {
489 $titlesVariant = explode( "\0", $titlesVariant );
492 // Then add variants of links to link batch
493 $parentTitle = $this->parent->getTitle();
494 foreach ( $titlesAttrs as $i => $attrs ) {
495 /** @var Title $title */
496 list( $index, $title ) = $attrs;
497 $ns = $title->getNamespace();
498 $text = $title->getText();
500 foreach ( $allVariantsName as $variantName ) {
501 $textVariant = $titlesAllVariants[$variantName][$i];
502 if ( $textVariant === $text ) {
503 continue;
506 $variantTitle = Title::makeTitle( $ns, $textVariant );
507 if ( is_null( $variantTitle ) ) {
508 continue;
511 // Self-link checking for mixed/different variant titles. At this point, we
512 // already know the exact title does not exist, so the link cannot be to a
513 // variant of the current title that exists as a separate page.
514 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
515 $this->internals[$ns][$index]['selflink'] = true;
516 continue 2;
519 $linkBatch->addObj( $variantTitle );
520 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
524 // process categories, check if a category exists in some variant
525 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
526 $varCategories = array(); // category replacements oldDBkey => newDBkey
527 foreach ( $output->getCategoryLinks() as $category ) {
528 $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
529 $linkBatch->addObj( $categoryTitle );
530 $variants = $wgContLang->autoConvertToAllVariants( $category );
531 foreach ( $variants as $variant ) {
532 if ( $variant !== $category ) {
533 $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
534 if ( is_null( $variantTitle ) ) {
535 continue;
537 $linkBatch->addObj( $variantTitle );
538 $categoryMap[$variant] = array( $category, $categoryTitle );
543 if ( !$linkBatch->isEmpty() ) {
544 // construct query
545 $dbr = wfGetDB( DB_SLAVE );
546 $fields = array( 'page_id', 'page_namespace', 'page_title',
547 'page_is_redirect', 'page_len', 'page_latest' );
549 if ( $wgContentHandlerUseDB ) {
550 $fields[] = 'page_content_model';
553 $varRes = $dbr->select( 'page',
554 $fields,
555 $linkBatch->constructSet( 'page', $dbr ),
556 __METHOD__
559 $linkcolour_ids = array();
561 // for each found variants, figure out link holders and replace
562 foreach ( $varRes as $s ) {
564 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
565 $varPdbk = $variantTitle->getPrefixedDBkey();
566 $vardbk = $variantTitle->getDBkey();
568 $holderKeys = array();
569 if ( isset( $variantMap[$varPdbk] ) ) {
570 $holderKeys = $variantMap[$varPdbk];
571 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
572 $output->addLink( $variantTitle, $s->page_id );
575 // loop over link holders
576 foreach ( $holderKeys as $key ) {
577 list( $ns, $index ) = explode( ':', $key, 2 );
578 $entry =& $this->internals[$ns][$index];
579 $pdbk = $entry['pdbk'];
581 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
582 // found link in some of the variants, replace the link holder data
583 $entry['title'] = $variantTitle;
584 $entry['pdbk'] = $varPdbk;
586 // set pdbk and colour
587 # @todo FIXME: Convoluted data flow
588 # The redirect status and length is passed to getLinkColour via the LinkCache
589 # Use formal parameters instead
590 $colours[$varPdbk] = Linker::getLinkColour( $variantTitle, $threshold );
591 $linkcolour_ids[$s->page_id] = $pdbk;
595 // check if the object is a variant of a category
596 if ( isset( $categoryMap[$vardbk] ) ) {
597 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
598 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
599 $varCategories[$oldkey] = $vardbk;
603 Hooks::run( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
605 // rebuild the categories in original order (if there are replacements)
606 if ( count( $varCategories ) > 0 ) {
607 $newCats = array();
608 $originalCats = $output->getCategories();
609 foreach ( $originalCats as $cat => $sortkey ) {
610 // make the replacement
611 if ( array_key_exists( $cat, $varCategories ) ) {
612 $newCats[$varCategories[$cat]] = $sortkey;
613 } else {
614 $newCats[$cat] = $sortkey;
617 $output->setCategoryLinks( $newCats );
623 * Replace <!--LINK--> link placeholders with plain text of links
624 * (not HTML-formatted).
626 * @param string $text
627 * @return string
629 public function replaceText( $text ) {
631 $text = preg_replace_callback(
632 '/<!--(LINK|IWLINK) (.*?)-->/',
633 array( &$this, 'replaceTextCallback' ),
634 $text );
636 return $text;
640 * Callback for replaceText()
642 * @param array $matches
643 * @return string
644 * @private
646 public function replaceTextCallback( $matches ) {
647 $type = $matches[1];
648 $key = $matches[2];
649 if ( $type == 'LINK' ) {
650 list( $ns, $index ) = explode( ':', $key, 2 );
651 if ( isset( $this->internals[$ns][$index]['text'] ) ) {
652 return $this->internals[$ns][$index]['text'];
654 } elseif ( $type == 'IWLINK' ) {
655 if ( isset( $this->interwikis[$key]['text'] ) ) {
656 return $this->interwikis[$key]['text'];
659 return $matches[0];