Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[lhc/web/wiklou.git] / includes / parser / LinkHolderArray.php
1 <?php
2 /**
3 * Holder of replacement pairs for wiki links
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Parser
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * @ingroup Parser
28 */
29 class LinkHolderArray {
30 public $internals = [];
31 public $interwikis = [];
32 public $size = 0;
33
34 /**
35 * @var Parser
36 */
37 public $parent;
38 protected $tempIdOffset;
39
40 /**
41 * @param Parser $parent
42 */
43 public function __construct( $parent ) {
44 $this->parent = $parent;
45 }
46
47 /**
48 * Reduce memory usage to reduce the impact of circular references
49 */
50 public function __destruct() {
51 foreach ( $this as $name => $value ) {
52 unset( $this->$name );
53 }
54 }
55
56 /**
57 * Don't serialize the parent object, it is big, and not needed when it is
58 * a parameter to mergeForeign(), which is the only application of
59 * serializing at present.
60 *
61 * Compact the titles, only serialize the text form.
62 * @return array
63 */
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
81 /**
82 * Recreate the Title objects
83 */
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
99 /**
100 * Merge another LinkHolderArray into this one
101 * @param LinkHolderArray $other
102 */
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
115 /**
116 * Merge a LinkHolderArray from another parser instance into this one. The
117 * keys will not be preserved. Any text which went with the old
118 * LinkHolderArray and needs to work with the new one should be passed in
119 * the $texts array. The strings in this array will have their link holders
120 * converted for use in the destination link holder. The resulting array of
121 * strings will be returned.
122 *
123 * @param LinkHolderArray $other
124 * @param array $texts Array of strings
125 * @return array
126 */
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
157 /**
158 * @param array $m
159 * @return string
160 */
161 protected function mergeForeignCallback( $m ) {
162 return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
163 }
164
165 /**
166 * Get a subset of the current LinkHolderArray which is sufficient to
167 * interpret the given text.
168 * @param string $text
169 * @return LinkHolderArray
170 */
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
201 /**
202 * Returns true if the memory requirements of this object are getting large
203 * @return bool
204 */
205 public function isBig() {
206 global $wgLinkHolderBatchSize;
207 return $this->size > $wgLinkHolderBatchSize;
208 }
209
210 /**
211 * Clear all stored link holders.
212 * Make sure you don't have any text left using these link holders, before you call this
213 */
214 public function clear() {
215 $this->internals = [];
216 $this->interwikis = [];
217 $this->size = 0;
218 }
219
220 /**
221 * Make a link placeholder. The text returned can be later resolved to a real link with
222 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
223 * parsing of interwiki links, and secondly to allow all existence checks and
224 * article length checks (for stub links) to be bundled into a single query.
225 *
226 * @param Title $nt
227 * @param string $text
228 * @param array $query [optional]
229 * @param string $trail [optional]
230 * @param string $prefix [optional]
231 * @return string
232 */
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
266 /**
267 * Replace <!--LINK--> link placeholders with actual links, in the buffer
268 *
269 * @param string &$text
270 */
271 public function replace( &$text ) {
272 $this->replaceInternal( $text );
273 $this->replaceInterwiki( $text );
274 }
275
276 /**
277 * Replace internal links
278 * @param string &$text
279 */
280 protected function replaceInternal( &$text ) {
281 if ( !$this->internals ) {
282 return;
283 }
284
285 global $wgContLang;
286
287 $colours = [];
288 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
289 $output = $this->parent->getOutput();
290 $linkRenderer = $this->parent->getLinkRenderer();
291
292 $dbr = wfGetDB( DB_REPLICA );
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 ) {
305 /** @var Title $title */
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 = $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 /**
420 * Replace interwiki links
421 * @param string &$text
422 */
423 protected function replaceInterwiki( &$text ) {
424 if ( empty( $this->interwikis ) ) {
425 return;
426 }
427
428 # Make interwiki link HTML
429 $output = $this->parent->getOutput();
430 $replacePairs = [];
431 $linkRenderer = $this->parent->getLinkRenderer();
432 foreach ( $this->interwikis as $key => $link ) {
433 $replacePairs[$key] = $linkRenderer->makeLink(
434 $link['title'],
435 new HtmlArmor( $link['text'] )
436 );
437 $output->addInterwikiLink( $link['title'] );
438 }
439 $replacer = new HashtableReplacer( $replacePairs, 1 );
440
441 $text = preg_replace_callback(
442 '/<!--IWLINK\'" (.*?)-->/',
443 $replacer->cb(),
444 $text );
445 }
446
447 /**
448 * Modify $this->internals and $colours according to language variant linking rules
449 * @param array &$colours
450 */
451 protected function doVariants( &$colours ) {
452 global $wgContLang;
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 = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
481 $allVariantsName = array_keys( $titlesAllVariants );
482 foreach ( $titlesAllVariants as &$titlesVariant ) {
483 $titlesVariant = explode( "\0", $titlesVariant );
484 }
485
486 // Then add variants of links to link batch
487 $parentTitle = $this->parent->getTitle();
488 foreach ( $titlesAttrs as $i => $attrs ) {
489 /** @var Title $title */
490 list( $index, $title ) = $attrs;
491 $ns = $title->getNamespace();
492 $text = $title->getText();
493
494 foreach ( $allVariantsName as $variantName ) {
495 $textVariant = $titlesAllVariants[$variantName][$i];
496 if ( $textVariant === $text ) {
497 continue;
498 }
499
500 $variantTitle = Title::makeTitle( $ns, $textVariant );
501
502 // Self-link checking for mixed/different variant titles. At this point, we
503 // already know the exact title does not exist, so the link cannot be to a
504 // variant of the current title that exists as a separate page.
505 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
506 $this->internals[$ns][$index]['selflink'] = true;
507 continue 2;
508 }
509
510 $linkBatch->addObj( $variantTitle );
511 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
512 }
513 }
514
515 // process categories, check if a category exists in some variant
516 $categoryMap = []; // maps $category_variant => $category (dbkeys)
517 $varCategories = []; // category replacements oldDBkey => newDBkey
518 foreach ( $output->getCategoryLinks() as $category ) {
519 $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
520 $linkBatch->addObj( $categoryTitle );
521 $variants = $wgContLang->autoConvertToAllVariants( $category );
522 foreach ( $variants as $variant ) {
523 if ( $variant !== $category ) {
524 $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
525 if ( is_null( $variantTitle ) ) {
526 continue;
527 }
528 $linkBatch->addObj( $variantTitle );
529 $categoryMap[$variant] = [ $category, $categoryTitle ];
530 }
531 }
532 }
533
534 if ( !$linkBatch->isEmpty() ) {
535 // construct query
536 $dbr = wfGetDB( DB_REPLICA );
537 $fields = array_merge(
538 LinkCache::getSelectFields(),
539 [ 'page_namespace', 'page_title' ]
540 );
541
542 $varRes = $dbr->select( 'page',
543 $fields,
544 $linkBatch->constructSet( 'page', $dbr ),
545 __METHOD__
546 );
547
548 $linkcolour_ids = [];
549 $linkRenderer = $this->parent->getLinkRenderer();
550
551 // for each found variants, figure out link holders and replace
552 foreach ( $varRes as $s ) {
553 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
554 $varPdbk = $variantTitle->getPrefixedDBkey();
555 $vardbk = $variantTitle->getDBkey();
556
557 $holderKeys = [];
558 if ( isset( $variantMap[$varPdbk] ) ) {
559 $holderKeys = $variantMap[$varPdbk];
560 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
561 $output->addLink( $variantTitle, $s->page_id );
562 }
563
564 // loop over link holders
565 foreach ( $holderKeys as $key ) {
566 list( $ns, $index ) = explode( ':', $key, 2 );
567 $entry =& $this->internals[$ns][$index];
568 $pdbk = $entry['pdbk'];
569
570 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
571 // found link in some of the variants, replace the link holder data
572 $entry['title'] = $variantTitle;
573 $entry['pdbk'] = $varPdbk;
574
575 // set pdbk and colour
576 $colours[$varPdbk] = $linkRenderer->getLinkClasses( $variantTitle );
577 $linkcolour_ids[$s->page_id] = $pdbk;
578 }
579 }
580
581 // check if the object is a variant of a category
582 if ( isset( $categoryMap[$vardbk] ) ) {
583 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
584 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
585 $varCategories[$oldkey] = $vardbk;
586 }
587 }
588 }
589 Hooks::run( 'GetLinkColours', [ $linkcolour_ids, &$colours ] );
590
591 // rebuild the categories in original order (if there are replacements)
592 if ( count( $varCategories ) > 0 ) {
593 $newCats = [];
594 $originalCats = $output->getCategories();
595 foreach ( $originalCats as $cat => $sortkey ) {
596 // make the replacement
597 if ( array_key_exists( $cat, $varCategories ) ) {
598 $newCats[$varCategories[$cat]] = $sortkey;
599 } else {
600 $newCats[$cat] = $sortkey;
601 }
602 }
603 $output->setCategoryLinks( $newCats );
604 }
605 }
606 }
607
608 /**
609 * Replace <!--LINK--> link placeholders with plain text of links
610 * (not HTML-formatted).
611 *
612 * @param string $text
613 * @return string
614 */
615 public function replaceText( $text ) {
616 $text = preg_replace_callback(
617 '/<!--(LINK|IWLINK)\'" (.*?)-->/',
618 [ $this, 'replaceTextCallback' ],
619 $text );
620
621 return $text;
622 }
623
624 /**
625 * Callback for replaceText()
626 *
627 * @param array $matches
628 * @return string
629 * @private
630 */
631 public function replaceTextCallback( $matches ) {
632 $type = $matches[1];
633 $key = $matches[2];
634 if ( $type == 'LINK' ) {
635 list( $ns, $index ) = explode( ':', $key, 2 );
636 if ( isset( $this->internals[$ns][$index]['text'] ) ) {
637 return $this->internals[$ns][$index]['text'];
638 }
639 } elseif ( $type == 'IWLINK' ) {
640 if ( isset( $this->interwikis[$key]['text'] ) ) {
641 return $this->interwikis[$key]['text'];
642 }
643 }
644 return $matches[0];
645 }
646 }