MediaWiki REL1_32
LinkHolderArray.php
Go to the documentation of this file.
1<?php
25
30 public $internals = [];
31 public $interwikis = [];
32 public $size = 0;
33
37 public $parent;
38 protected $tempIdOffset;
39
43 public function __construct( $parent ) {
44 $this->parent = $parent;
45 }
46
50 public function __destruct() {
51 foreach ( $this as $name => $value ) {
52 unset( $this->$name );
53 }
54 }
55
64 public function __sleep() {
65 foreach ( $this->internals as &$nsLinks ) {
66 foreach ( $nsLinks as &$entry ) {
67 unset( $entry['title'] );
68 }
69 }
70 unset( $nsLinks );
71 unset( $entry );
72
73 foreach ( $this->interwikis as &$entry ) {
74 unset( $entry['title'] );
75 }
76 unset( $entry );
77
78 return [ 'internals', 'interwikis', 'size' ];
79 }
80
84 public function __wakeup() {
85 foreach ( $this->internals as &$nsLinks ) {
86 foreach ( $nsLinks as &$entry ) {
87 $entry['title'] = Title::newFromText( $entry['pdbk'] );
88 }
89 }
90 unset( $nsLinks );
91 unset( $entry );
92
93 foreach ( $this->interwikis as &$entry ) {
94 $entry['title'] = Title::newFromText( $entry['pdbk'] );
95 }
96 unset( $entry );
97 }
98
103 public function merge( $other ) {
104 foreach ( $other->internals as $ns => $entries ) {
105 $this->size += count( $entries );
106 if ( !isset( $this->internals[$ns] ) ) {
107 $this->internals[$ns] = $entries;
108 } else {
109 $this->internals[$ns] += $entries;
110 }
111 }
112 $this->interwikis += $other->interwikis;
113 }
114
127 public function mergeForeign( $other, $texts ) {
128 $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
129 $maxId = 0;
130
131 # Renumber internal links
132 foreach ( $other->internals as $ns => $nsLinks ) {
133 foreach ( $nsLinks as $key => $entry ) {
134 $newKey = $idOffset + $key;
135 $this->internals[$ns][$newKey] = $entry;
136 $maxId = $newKey > $maxId ? $newKey : $maxId;
137 }
138 }
139 $texts = preg_replace_callback( '/(<!--LINK\'" \d+:)(\d+)(-->)/',
140 [ $this, 'mergeForeignCallback' ], $texts );
141
142 # Renumber interwiki links
143 foreach ( $other->interwikis as $key => $entry ) {
144 $newKey = $idOffset + $key;
145 $this->interwikis[$newKey] = $entry;
146 $maxId = $newKey > $maxId ? $newKey : $maxId;
147 }
148 $texts = preg_replace_callback( '/(<!--IWLINK\'" )(\d+)(-->)/',
149 [ $this, 'mergeForeignCallback' ], $texts );
150
151 # Set the parent link ID to be beyond the highest used ID
152 $this->parent->setLinkID( $maxId + 1 );
153 $this->tempIdOffset = null;
154 return $texts;
155 }
156
161 protected function mergeForeignCallback( $m ) {
162 return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
163 }
164
171 public function getSubArray( $text ) {
172 $sub = new LinkHolderArray( $this->parent );
173
174 # Internal links
175 $pos = 0;
176 while ( $pos < strlen( $text ) ) {
177 if ( !preg_match( '/<!--LINK\'" (\d+):(\d+)-->/',
178 $text, $m, PREG_OFFSET_CAPTURE, $pos )
179 ) {
180 break;
181 }
182 $ns = $m[1][0];
183 $key = $m[2][0];
184 $sub->internals[$ns][$key] = $this->internals[$ns][$key];
185 $pos = $m[0][1] + strlen( $m[0][0] );
186 }
187
188 # Interwiki links
189 $pos = 0;
190 while ( $pos < strlen( $text ) ) {
191 if ( !preg_match( '/<!--IWLINK\'" (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
192 break;
193 }
194 $key = $m[1][0];
195 $sub->interwikis[$key] = $this->interwikis[$key];
196 $pos = $m[0][1] + strlen( $m[0][0] );
197 }
198 return $sub;
199 }
200
205 public function isBig() {
207 return $this->size > $wgLinkHolderBatchSize;
208 }
209
214 public function clear() {
215 $this->internals = [];
216 $this->interwikis = [];
217 $this->size = 0;
218 }
219
233 public function makeHolder( $nt, $text = '', $query = [], $trail = '', $prefix = '' ) {
234 if ( !is_object( $nt ) ) {
235 # Fail gracefully
236 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
237 } else {
238 # Separate the link trail from the rest of the link
239 list( $inside, $trail ) = Linker::splitTrail( $trail );
240
241 $entry = [
242 'title' => $nt,
243 'text' => $prefix . $text . $inside,
244 'pdbk' => $nt->getPrefixedDBkey(),
245 ];
246 if ( $query !== [] ) {
247 $entry['query'] = $query;
248 }
249
250 if ( $nt->isExternal() ) {
251 // Use a globally unique ID to keep the objects mergable
252 $key = $this->parent->nextLinkID();
253 $this->interwikis[$key] = $entry;
254 $retVal = "<!--IWLINK'\" $key-->{$trail}";
255 } else {
256 $key = $this->parent->nextLinkID();
257 $ns = $nt->getNamespace();
258 $this->internals[$ns][$key] = $entry;
259 $retVal = "<!--LINK'\" $ns:$key-->{$trail}";
260 }
261 $this->size++;
262 }
263 return $retVal;
264 }
265
271 public function replace( &$text ) {
272 $this->replaceInternal( $text );
273 $this->replaceInterwiki( $text );
274 }
275
280 protected function replaceInternal( &$text ) {
281 if ( !$this->internals ) {
282 return;
283 }
284
285 $colours = [];
286 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
287 $output = $this->parent->getOutput();
288 $linkRenderer = $this->parent->getLinkRenderer();
289
291
292 # Sort by namespace
293 ksort( $this->internals );
294
295 $linkcolour_ids = [];
296
297 # Generate query
298 $lb = new LinkBatch();
299 $lb->setCaller( __METHOD__ );
300
301 foreach ( $this->internals as $ns => $entries ) {
302 foreach ( $entries as $entry ) {
304 $title = $entry['title'];
305 $pdbk = $entry['pdbk'];
306
307 # Skip invalid entries.
308 # Result will be ugly, but prevents crash.
309 if ( is_null( $title ) ) {
310 continue;
311 }
312
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 } else {
319 $id = $linkCache->getGoodLinkID( $pdbk );
320 if ( $id != 0 ) {
321 $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
322 $output->addLink( $title, $id );
323 $linkcolour_ids[$id] = $pdbk;
324 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
325 $colours[$pdbk] = 'new';
326 } else {
327 # Not in the link cache, add it to the query
328 $lb->addObj( $title );
329 }
330 }
331 }
332 }
333 if ( !$lb->isEmpty() ) {
334 $fields = array_merge(
335 LinkCache::getSelectFields(),
336 [ 'page_namespace', 'page_title' ]
337 );
338
339 $res = $dbr->select(
340 'page',
341 $fields,
342 $lb->constructSet( 'page', $dbr ),
343 __METHOD__
344 );
345
346 # Fetch data and form into an associative array
347 # non-existent = broken
348 foreach ( $res as $s ) {
349 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
350 $pdbk = $title->getPrefixedDBkey();
351 $linkCache->addGoodLinkObjFromRow( $title, $s );
352 $output->addLink( $title, $s->page_id );
353 $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
354 // add id to the extension todolist
355 $linkcolour_ids[$s->page_id] = $pdbk;
356 }
357 unset( $res );
358 }
359 if ( count( $linkcolour_ids ) ) {
360 // pass an array of page_ids to an extension
361 Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours, $this->parent->getTitle() ] );
362 }
363
364 # Do a second query for different language variants of links and categories
365 if ( $this->parent->getContentLanguage()->hasVariants() ) {
366 $this->doVariants( $colours );
367 }
368
369 # Construct search and replace arrays
370 $replacePairs = [];
371 foreach ( $this->internals as $ns => $entries ) {
372 foreach ( $entries as $index => $entry ) {
373 $pdbk = $entry['pdbk'];
374 $title = $entry['title'];
375 $query = $entry['query'] ?? [];
376 $key = "$ns:$index";
377 $searchkey = "<!--LINK'\" $key-->";
378 $displayText = $entry['text'];
379 if ( isset( $entry['selflink'] ) ) {
380 $replacePairs[$searchkey] = Linker::makeSelfLinkObj( $title, $displayText, $query );
381 continue;
382 }
383 if ( $displayText === '' ) {
384 $displayText = null;
385 } else {
386 $displayText = new HtmlArmor( $displayText );
387 }
388 if ( !isset( $colours[$pdbk] ) ) {
389 $colours[$pdbk] = 'new';
390 }
391 $attribs = [];
392 if ( $colours[$pdbk] == 'new' ) {
393 $linkCache->addBadLinkObj( $title );
394 $output->addLink( $title, 0 );
395 $link = $linkRenderer->makeBrokenLink(
396 $title, $displayText, $attribs, $query
397 );
398 } else {
399 $link = $linkRenderer->makePreloadedLink(
400 $title, $displayText, $colours[$pdbk], $attribs, $query
401 );
402 }
403
404 $replacePairs[$searchkey] = $link;
405 }
406 }
407
408 # Do the thing
409 $text = preg_replace_callback(
410 '/(<!--LINK\'" .*?-->)/',
411 function ( array $matches ) use ( $replacePairs ) {
412 return $replacePairs[$matches[1]];
413 },
414 $text
415 );
416 }
417
422 protected function replaceInterwiki( &$text ) {
423 if ( empty( $this->interwikis ) ) {
424 return;
425 }
426
427 # Make interwiki link HTML
428 $output = $this->parent->getOutput();
429 $replacePairs = [];
430 $linkRenderer = $this->parent->getLinkRenderer();
431 foreach ( $this->interwikis as $key => $link ) {
432 $replacePairs[$key] = $linkRenderer->makeLink(
433 $link['title'],
434 new HtmlArmor( $link['text'] )
435 );
436 $output->addInterwikiLink( $link['title'] );
437 }
438
439 $text = preg_replace_callback(
440 '/<!--IWLINK\'" (.*?)-->/',
441 function ( array $matches ) use ( $replacePairs ) {
442 return $replacePairs[$matches[1]];
443 },
444 $text
445 );
446 }
447
452 protected function doVariants( &$colours ) {
453 $linkBatch = new LinkBatch();
454 $variantMap = []; // maps $pdbkey_Variant => $keys (of link holders)
455 $output = $this->parent->getOutput();
456 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
457 $titlesToBeConverted = '';
458 $titlesAttrs = [];
459
460 // Concatenate titles to a single string, thus we only need auto convert the
461 // single string to all variants. This would improve parser's performance
462 // significantly.
463 foreach ( $this->internals as $ns => $entries ) {
464 if ( $ns == NS_SPECIAL ) {
465 continue;
466 }
467 foreach ( $entries as $index => $entry ) {
468 $pdbk = $entry['pdbk'];
469 // we only deal with new links (in its first query)
470 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
471 $titlesAttrs[] = [ $index, $entry['title'] ];
472 // separate titles with \0 because it would never appears
473 // in a valid title
474 $titlesToBeConverted .= $entry['title']->getText() . "\0";
475 }
476 }
477 }
478
479 // Now do the conversion and explode string to text of titles
480 $titlesAllVariants = $this->parent->getContentLanguage()->
481 autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
482 $allVariantsName = array_keys( $titlesAllVariants );
483 foreach ( $titlesAllVariants as &$titlesVariant ) {
484 $titlesVariant = explode( "\0", $titlesVariant );
485 }
486
487 // Then add variants of links to link batch
488 $parentTitle = $this->parent->getTitle();
489 foreach ( $titlesAttrs as $i => $attrs ) {
491 list( $index, $title ) = $attrs;
492 $ns = $title->getNamespace();
493 $text = $title->getText();
494
495 foreach ( $allVariantsName as $variantName ) {
496 $textVariant = $titlesAllVariants[$variantName][$i];
497 if ( $textVariant === $text ) {
498 continue;
499 }
500
501 $variantTitle = Title::makeTitle( $ns, $textVariant );
502
503 // Self-link checking for mixed/different variant titles. At this point, we
504 // already know the exact title does not exist, so the link cannot be to a
505 // variant of the current title that exists as a separate page.
506 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
507 $this->internals[$ns][$index]['selflink'] = true;
508 continue 2;
509 }
510
511 $linkBatch->addObj( $variantTitle );
512 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
513 }
514 }
515
516 // process categories, check if a category exists in some variant
517 $categoryMap = []; // maps $category_variant => $category (dbkeys)
518 $varCategories = []; // category replacements oldDBkey => newDBkey
519 foreach ( $output->getCategoryLinks() as $category ) {
520 $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
521 $linkBatch->addObj( $categoryTitle );
522 $variants = $this->parent->getContentLanguage()->autoConvertToAllVariants( $category );
523 foreach ( $variants as $variant ) {
524 if ( $variant !== $category ) {
525 $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
526 if ( is_null( $variantTitle ) ) {
527 continue;
528 }
529 $linkBatch->addObj( $variantTitle );
530 $categoryMap[$variant] = [ $category, $categoryTitle ];
531 }
532 }
533 }
534
535 if ( !$linkBatch->isEmpty() ) {
536 // construct query
538 $fields = array_merge(
539 LinkCache::getSelectFields(),
540 [ 'page_namespace', 'page_title' ]
541 );
542
543 $varRes = $dbr->select( 'page',
544 $fields,
545 $linkBatch->constructSet( 'page', $dbr ),
546 __METHOD__
547 );
548
549 $linkcolour_ids = [];
550 $linkRenderer = $this->parent->getLinkRenderer();
551
552 // for each found variants, figure out link holders and replace
553 foreach ( $varRes as $s ) {
554 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
555 $varPdbk = $variantTitle->getPrefixedDBkey();
556 $vardbk = $variantTitle->getDBkey();
557
558 $holderKeys = [];
559 if ( isset( $variantMap[$varPdbk] ) ) {
560 $holderKeys = $variantMap[$varPdbk];
561 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
562 $output->addLink( $variantTitle, $s->page_id );
563 }
564
565 // loop over link holders
566 foreach ( $holderKeys as $key ) {
567 list( $ns, $index ) = explode( ':', $key, 2 );
568 $entry =& $this->internals[$ns][$index];
569 $pdbk = $entry['pdbk'];
570
571 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
572 // found link in some of the variants, replace the link holder data
573 $entry['title'] = $variantTitle;
574 $entry['pdbk'] = $varPdbk;
575
576 // set pdbk and colour
577 $colours[$varPdbk] = $linkRenderer->getLinkClasses( $variantTitle );
578 $linkcolour_ids[$s->page_id] = $pdbk;
579 }
580 }
581
582 // check if the object is a variant of a category
583 if ( isset( $categoryMap[$vardbk] ) ) {
584 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
585 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
586 $varCategories[$oldkey] = $vardbk;
587 }
588 }
589 }
590 Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours, $this->parent->getTitle() ] );
591
592 // rebuild the categories in original order (if there are replacements)
593 if ( count( $varCategories ) > 0 ) {
594 $newCats = [];
595 $originalCats = $output->getCategories();
596 foreach ( $originalCats as $cat => $sortkey ) {
597 // make the replacement
598 if ( array_key_exists( $cat, $varCategories ) ) {
599 $newCats[$varCategories[$cat]] = $sortkey;
600 } else {
601 $newCats[$cat] = $sortkey;
602 }
603 }
604 $output->setCategoryLinks( $newCats );
605 }
606 }
607 }
608
616 public function replaceText( $text ) {
617 $text = preg_replace_callback(
618 '/<!--(LINK|IWLINK)\'" (.*?)-->/',
619 [ $this, 'replaceTextCallback' ],
620 $text );
621
622 return $text;
623 }
624
632 public function replaceTextCallback( $matches ) {
633 $type = $matches[1];
634 $key = $matches[2];
635 if ( $type == 'LINK' ) {
636 list( $ns, $index ) = explode( ':', $key, 2 );
637 if ( isset( $this->internals[$ns][$index]['text'] ) ) {
638 return $this->internals[$ns][$index]['text'];
639 }
640 } elseif ( $type == 'IWLINK' ) {
641 if ( isset( $this->interwikis[$key]['text'] ) ) {
642 return $this->interwikis[$key]['text'];
643 }
644 }
645 return $matches[0];
646 }
647}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgLinkHolderBatchSize
LinkHolderArray batch size For debugging.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Marks HTML that shouldn't be escaped.
Definition HtmlArmor.php:28
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
__wakeup()
Recreate the Title objects.
getSubArray( $text)
Get a subset of the current LinkHolderArray which is sufficient to interpret the given text.
replaceInterwiki(&$text)
Replace interwiki links.
merge( $other)
Merge another LinkHolderArray into this one.
replaceText( $text)
Replace link placeholders with plain text of links (not HTML-formatted).
replaceTextCallback( $matches)
Callback for replaceText()
mergeForeign( $other, $texts)
Merge a LinkHolderArray from another parser instance into this one.
replaceInternal(&$text)
Replace internal links.
__destruct()
Reduce memory usage to reduce the impact of circular references.
clear()
Clear all stored link holders.
isBig()
Returns true if the memory requirements of this object are getting large.
makeHolder( $nt, $text='', $query=[], $trail='', $prefix='')
Make a link placeholder.
doVariants(&$colours)
Modify $this->internals and $colours according to language variant linking rules.
__sleep()
Don't serialize the parent object, it is big, and not needed when it is a parameter to mergeForeign()...
replace(&$text)
Replace link placeholders with actual links, in the buffer.
static makeSelfLinkObj( $nt, $html='', $query='', $trail='', $prefix='')
Make appropriate markup for a link to the current article.
Definition Linker.php:163
static splitTrail( $trail)
Split a link trail, return the "inside" portion and the remainder of the trail as a two-element array...
Definition Linker.php:1664
MediaWikiServices is the service locator for the application scope of MediaWiki.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:68
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const NS_SPECIAL
Definition Defines.php:53
const NS_CATEGORY
Definition Defines.php:78
the value of this variable comes from LanguageConverter indexed by page_id & $colours
Definition hooks.txt:1720
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:994
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:3106
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing & $attribs
Definition hooks.txt:2063
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1656
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition hooks.txt:2105
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition hooks.txt:2317
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
const DB_REPLICA
Definition defines.php:25