MediaWiki REL1_28
LinkHolderArray.php
Go to the documentation of this file.
1<?php
28 public $internals = [];
29 public $interwikis = [];
30 public $size = 0;
31
35 public $parent;
36 protected $tempIdOffset;
37
41 public function __construct( $parent ) {
42 $this->parent = $parent;
43 }
44
48 public function __destruct() {
49 foreach ( $this as $name => $value ) {
50 unset( $this->$name );
51 }
52 }
53
62 public function __sleep() {
63 foreach ( $this->internals as &$nsLinks ) {
64 foreach ( $nsLinks as &$entry ) {
65 unset( $entry['title'] );
66 }
67 }
68 unset( $nsLinks );
69 unset( $entry );
70
71 foreach ( $this->interwikis as &$entry ) {
72 unset( $entry['title'] );
73 }
74 unset( $entry );
75
76 return [ 'internals', 'interwikis', 'size' ];
77 }
78
82 public function __wakeup() {
83 foreach ( $this->internals as &$nsLinks ) {
84 foreach ( $nsLinks as &$entry ) {
85 $entry['title'] = Title::newFromText( $entry['pdbk'] );
86 }
87 }
88 unset( $nsLinks );
89 unset( $entry );
90
91 foreach ( $this->interwikis as &$entry ) {
92 $entry['title'] = Title::newFromText( $entry['pdbk'] );
93 }
94 unset( $entry );
95 }
96
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;
108 }
109 }
110 $this->interwikis += $other->interwikis;
111 }
112
125 public function mergeForeign( $other, $texts ) {
126 $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
127 $maxId = 0;
128
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;
135 }
136 }
137 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
138 [ $this, 'mergeForeignCallback' ], $texts );
139
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;
145 }
146 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
147 [ $this, 'mergeForeignCallback' ], $texts );
148
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;
153 }
154
159 protected function mergeForeignCallback( $m ) {
160 return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
161 }
162
169 public function getSubArray( $text ) {
170 $sub = new LinkHolderArray( $this->parent );
171
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 )
177 ) {
178 break;
179 }
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] );
184 }
185
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;
191 }
192 $key = $m[1][0];
193 $sub->interwikis[$key] = $this->interwikis[$key];
194 $pos = $m[0][1] + strlen( $m[0][0] );
195 }
196 return $sub;
197 }
198
203 public function isBig() {
205 return $this->size > $wgLinkHolderBatchSize;
206 }
207
212 public function clear() {
213 $this->internals = [];
214 $this->interwikis = [];
215 $this->size = 0;
216 }
217
231 public function makeHolder( $nt, $text = '', $query = [], $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 );
238
239 $entry = [
240 'title' => $nt,
241 'text' => $prefix . $text . $inside,
242 'pdbk' => $nt->getPrefixedDBkey(),
243 ];
244 if ( $query !== [] ) {
245 $entry['query'] = $query;
246 }
247
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}";
258 }
259 $this->size++;
260 }
261 return $retVal;
262 }
263
269 public function replace( &$text ) {
270
271 $this->replaceInternal( $text );
272 $this->replaceInterwiki( $text );
273
274 }
275
280 protected function replaceInternal( &$text ) {
281 if ( !$this->internals ) {
282 return;
283 }
284
286
287 $colours = [];
288 $linkCache = LinkCache::singleton();
289 $output = $this->parent->getOutput();
290 $linkRenderer = $this->parent->getLinkRenderer();
291
293
294 # Sort by namespace
295 ksort( $this->internals );
296
297 $linkcolour_ids = [];
298
299 # Generate query
300 $lb = new LinkBatch();
301 $lb->setCaller( __METHOD__ );
302
303 foreach ( $this->internals as $ns => $entries ) {
304 foreach ( $entries as $entry ) {
306 $title = $entry['title'];
307 $pdbk = $entry['pdbk'];
308
309 # Skip invalid entries.
310 # Result will be ugly, but prevents crash.
311 if ( is_null( $title ) ) {
312 continue;
313 }
314
315 # Check if it's a static known link, e.g. interwiki
316 if ( $title->isAlwaysKnown() ) {
317 $colours[$pdbk] = '';
318 } elseif ( $ns == NS_SPECIAL ) {
319 $colours[$pdbk] = 'new';
320 } else {
321 $id = $linkCache->getGoodLinkID( $pdbk );
322 if ( $id != 0 ) {
323 $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
324 $output->addLink( $title, $id );
325 $linkcolour_ids[$id] = $pdbk;
326 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
327 $colours[$pdbk] = 'new';
328 } else {
329 # Not in the link cache, add it to the query
330 $lb->addObj( $title );
331 }
332 }
333 }
334 }
335 if ( !$lb->isEmpty() ) {
336 $fields = array_merge(
337 LinkCache::getSelectFields(),
338 [ 'page_namespace', 'page_title' ]
339 );
340
341 $res = $dbr->select(
342 'page',
343 $fields,
344 $lb->constructSet( 'page', $dbr ),
345 __METHOD__
346 );
347
348 # Fetch data and form into an associative array
349 # non-existent = broken
350 foreach ( $res as $s ) {
351 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
352 $pdbk = $title->getPrefixedDBkey();
353 $linkCache->addGoodLinkObjFromRow( $title, $s );
354 $output->addLink( $title, $s->page_id );
355 $colours[$pdbk] = $linkRenderer->getLinkClasses( $title );
356 // add id to the extension todolist
357 $linkcolour_ids[$s->page_id] = $pdbk;
358 }
359 unset( $res );
360 }
361 if ( count( $linkcolour_ids ) ) {
362 // pass an array of page_ids to an extension
363 Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours ] );
364 }
365
366 # Do a second query for different language variants of links and categories
367 if ( $wgContLang->hasVariants() ) {
368 $this->doVariants( $colours );
369 }
370
371 # Construct search and replace arrays
372 $replacePairs = [];
373 foreach ( $this->internals as $ns => $entries ) {
374 foreach ( $entries as $index => $entry ) {
375 $pdbk = $entry['pdbk'];
376 $title = $entry['title'];
377 $query = isset( $entry['query'] ) ? $entry['query'] : [];
378 $key = "$ns:$index";
379 $searchkey = "<!--LINK $key-->";
380 $displayText = $entry['text'];
381 if ( isset( $entry['selflink'] ) ) {
382 $replacePairs[$searchkey] = Linker::makeSelfLinkObj( $title, $displayText, $query );
383 continue;
384 }
385 if ( $displayText === '' ) {
386 $displayText = null;
387 } else {
388 $displayText = new HtmlArmor( $displayText );
389 }
390 if ( !isset( $colours[$pdbk] ) ) {
391 $colours[$pdbk] = 'new';
392 }
393 $attribs = [];
394 if ( $colours[$pdbk] == 'new' ) {
395 $linkCache->addBadLinkObj( $title );
396 $output->addLink( $title, 0 );
397 $link = $linkRenderer->makeBrokenLink(
398 $title, $displayText, $attribs, $query
399 );
400 } else {
401 $link = $linkRenderer->makePreloadedLink(
402 $title, $displayText, $colours[$pdbk], $attribs, $query
403 );
404 }
405
406 $replacePairs[$searchkey] = $link;
407 }
408 }
409 $replacer = new HashtableReplacer( $replacePairs, 1 );
410
411 # Do the thing
412 $text = preg_replace_callback(
413 '/(<!--LINK .*?-->)/',
414 $replacer->cb(),
415 $text
416 );
417
418 }
419
424 protected function replaceInterwiki( &$text ) {
425 if ( empty( $this->interwikis ) ) {
426 return;
427 }
428
429 # Make interwiki link HTML
430 $output = $this->parent->getOutput();
431 $replacePairs = [];
432 $linkRenderer = $this->parent->getLinkRenderer();
433 foreach ( $this->interwikis as $key => $link ) {
434 $replacePairs[$key] = $linkRenderer->makeLink(
435 $link['title'],
436 new HtmlArmor( $link['text'] )
437 );
438 $output->addInterwikiLink( $link['title'] );
439 }
440 $replacer = new HashtableReplacer( $replacePairs, 1 );
441
442 $text = preg_replace_callback(
443 '/<!--IWLINK (.*?)-->/',
444 $replacer->cb(),
445 $text );
446 }
447
452 protected function doVariants( &$colours ) {
454 $linkBatch = new LinkBatch();
455 $variantMap = []; // maps $pdbkey_Variant => $keys (of link holders)
456 $output = $this->parent->getOutput();
457 $linkCache = LinkCache::singleton();
458 $titlesToBeConverted = '';
459 $titlesAttrs = [];
460
461 // Concatenate titles to a single string, thus we only need auto convert the
462 // single string to all variants. This would improve parser's performance
463 // significantly.
464 foreach ( $this->internals as $ns => $entries ) {
465 if ( $ns == NS_SPECIAL ) {
466 continue;
467 }
468 foreach ( $entries as $index => $entry ) {
469 $pdbk = $entry['pdbk'];
470 // we only deal with new links (in its first query)
471 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
472 $titlesAttrs[] = [ $index, $entry['title'] ];
473 // separate titles with \0 because it would never appears
474 // in a valid title
475 $titlesToBeConverted .= $entry['title']->getText() . "\0";
476 }
477 }
478 }
479
480 // Now do the conversion and explode string to text of titles
481 $titlesAllVariants = $wgContLang->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 = $wgContLang->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 ] );
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
618 $text = preg_replace_callback(
619 '/<!--(LINK|IWLINK) (.*?)-->/',
620 [ $this, 'replaceTextCallback' ],
621 $text );
622
623 return $text;
624 }
625
633 public function replaceTextCallback( $matches ) {
634 $type = $matches[1];
635 $key = $matches[2];
636 if ( $type == 'LINK' ) {
637 list( $ns, $index ) = explode( ':', $key, 2 );
638 if ( isset( $this->internals[$ns][$index]['text'] ) ) {
639 return $this->internals[$ns][$index]['text'];
640 }
641 } elseif ( $type == 'IWLINK' ) {
642 if ( isset( $this->interwikis[$key]['text'] ) ) {
643 return $this->interwikis[$key]['text'];
644 }
645 }
646 return $matches[0];
647 }
648}
$wgLinkHolderBatchSize
LinkHolderArray batch size For debugging.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Class to perform replacement based on a simple hashtable lookup.
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:32
__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:277
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:1722
setCategoryLinks( $cl)
addInterwikiLink( $title)
addLink(Title $title, $id=null)
Record a local or interwiki inline link for saving in future link tables.
PHP Parser - Processes wiki markup (which uses a more user-friendly syntax, such as "[[link]]" for ma...
Definition Parser.php:70
$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 class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
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:45
const NS_CATEGORY
Definition Defines.php:70
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition hooks.txt:1102
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition hooks.txt:2568
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:986
if the prop value should be in the metadata multi language array can modify can modify indexed by page_id & $colours
Definition hooks.txt:1643
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:2900
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:1958
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
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:1595
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:1990
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
const DB_REPLICA
Definition defines.php:22