Merge "Reorganize commonPrint.css"
[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 /**
25 * @ingroup Parser
26 */
27 class LinkHolderArray {
28 var $internals = array(), $interwikis = array();
29 var $size = 0;
30 var $parent;
31 protected $tempIdOffset;
32
33 function __construct( $parent ) {
34 $this->parent = $parent;
35 }
36
37 /**
38 * Reduce memory usage to reduce the impact of circular references
39 */
40 function __destruct() {
41 foreach ( $this as $name => $value ) {
42 unset( $this->$name );
43 }
44 }
45
46 /**
47 * Don't serialize the parent object, it is big, and not needed when it is
48 * a parameter to mergeForeign(), which is the only application of
49 * serializing at present.
50 *
51 * Compact the titles, only serialize the text form.
52 * @return array
53 */
54 function __sleep() {
55 foreach ( $this->internals as &$nsLinks ) {
56 foreach ( $nsLinks as &$entry ) {
57 unset( $entry['title'] );
58 }
59 }
60 unset( $nsLinks );
61 unset( $entry );
62
63 foreach ( $this->interwikis as &$entry ) {
64 unset( $entry['title'] );
65 }
66 unset( $entry );
67
68 return array( 'internals', 'interwikis', 'size' );
69 }
70
71 /**
72 * Recreate the Title objects
73 */
74 function __wakeup() {
75 foreach ( $this->internals as &$nsLinks ) {
76 foreach ( $nsLinks as &$entry ) {
77 $entry['title'] = Title::newFromText( $entry['pdbk'] );
78 }
79 }
80 unset( $nsLinks );
81 unset( $entry );
82
83 foreach ( $this->interwikis as &$entry ) {
84 $entry['title'] = Title::newFromText( $entry['pdbk'] );
85 }
86 unset( $entry );
87 }
88
89 /**
90 * Merge another LinkHolderArray into this one
91 * @param LinkHolderArray $other
92 */
93 function merge( $other ) {
94 foreach ( $other->internals as $ns => $entries ) {
95 $this->size += count( $entries );
96 if ( !isset( $this->internals[$ns] ) ) {
97 $this->internals[$ns] = $entries;
98 } else {
99 $this->internals[$ns] += $entries;
100 }
101 }
102 $this->interwikis += $other->interwikis;
103 }
104
105 /**
106 * Merge a LinkHolderArray from another parser instance into this one. The
107 * keys will not be preserved. Any text which went with the old
108 * LinkHolderArray and needs to work with the new one should be passed in
109 * the $texts array. The strings in this array will have their link holders
110 * converted for use in the destination link holder. The resulting array of
111 * strings will be returned.
112 *
113 * @param LinkHolderArray $other
114 * @param array $texts Array of strings
115 * @return array
116 */
117 function mergeForeign( $other, $texts ) {
118 $this->tempIdOffset = $idOffset = $this->parent->nextLinkID();
119 $maxId = 0;
120
121 # Renumber internal links
122 foreach ( $other->internals as $ns => $nsLinks ) {
123 foreach ( $nsLinks as $key => $entry ) {
124 $newKey = $idOffset + $key;
125 $this->internals[$ns][$newKey] = $entry;
126 $maxId = $newKey > $maxId ? $newKey : $maxId;
127 }
128 }
129 $texts = preg_replace_callback( '/(<!--LINK \d+:)(\d+)(-->)/',
130 array( $this, 'mergeForeignCallback' ), $texts );
131
132 # Renumber interwiki links
133 foreach ( $other->interwikis as $key => $entry ) {
134 $newKey = $idOffset + $key;
135 $this->interwikis[$newKey] = $entry;
136 $maxId = $newKey > $maxId ? $newKey : $maxId;
137 }
138 $texts = preg_replace_callback( '/(<!--IWLINK )(\d+)(-->)/',
139 array( $this, 'mergeForeignCallback' ), $texts );
140
141 # Set the parent link ID to be beyond the highest used ID
142 $this->parent->setLinkID( $maxId + 1 );
143 $this->tempIdOffset = null;
144 return $texts;
145 }
146
147 protected function mergeForeignCallback( $m ) {
148 return $m[1] . ( $m[2] + $this->tempIdOffset ) . $m[3];
149 }
150
151 /**
152 * Get a subset of the current LinkHolderArray which is sufficient to
153 * interpret the given text.
154 * @param string $text
155 * @return LinkHolderArray
156 */
157 function getSubArray( $text ) {
158 $sub = new LinkHolderArray( $this->parent );
159
160 # Internal links
161 $pos = 0;
162 while ( $pos < strlen( $text ) ) {
163 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
164 $text, $m, PREG_OFFSET_CAPTURE, $pos )
165 ) {
166 break;
167 }
168 $ns = $m[1][0];
169 $key = $m[2][0];
170 $sub->internals[$ns][$key] = $this->internals[$ns][$key];
171 $pos = $m[0][1] + strlen( $m[0][0] );
172 }
173
174 # Interwiki links
175 $pos = 0;
176 while ( $pos < strlen( $text ) ) {
177 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
178 break;
179 }
180 $key = $m[1][0];
181 $sub->interwikis[$key] = $this->interwikis[$key];
182 $pos = $m[0][1] + strlen( $m[0][0] );
183 }
184 return $sub;
185 }
186
187 /**
188 * Returns true if the memory requirements of this object are getting large
189 * @return bool
190 */
191 function isBig() {
192 global $wgLinkHolderBatchSize;
193 return $this->size > $wgLinkHolderBatchSize;
194 }
195
196 /**
197 * Clear all stored link holders.
198 * Make sure you don't have any text left using these link holders, before you call this
199 */
200 function clear() {
201 $this->internals = array();
202 $this->interwikis = array();
203 $this->size = 0;
204 }
205
206 /**
207 * Make a link placeholder. The text returned can be later resolved to a real link with
208 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
209 * parsing of interwiki links, and secondly to allow all existence checks and
210 * article length checks (for stub links) to be bundled into a single query.
211 *
212 * @param Title $nt
213 * @param string $text
214 * @param array $query [optional]
215 * @param string $trail [optional]
216 * @param string $prefix [optional]
217 * @return string
218 */
219 function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
220 wfProfileIn( __METHOD__ );
221 if ( !is_object( $nt ) ) {
222 # Fail gracefully
223 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
224 } else {
225 # Separate the link trail from the rest of the link
226 list( $inside, $trail ) = Linker::splitTrail( $trail );
227
228 $entry = array(
229 'title' => $nt,
230 'text' => $prefix . $text . $inside,
231 'pdbk' => $nt->getPrefixedDBkey(),
232 );
233 if ( $query !== array() ) {
234 $entry['query'] = $query;
235 }
236
237 if ( $nt->isExternal() ) {
238 // Use a globally unique ID to keep the objects mergable
239 $key = $this->parent->nextLinkID();
240 $this->interwikis[$key] = $entry;
241 $retVal = "<!--IWLINK $key-->{$trail}";
242 } else {
243 $key = $this->parent->nextLinkID();
244 $ns = $nt->getNamespace();
245 $this->internals[$ns][$key] = $entry;
246 $retVal = "<!--LINK $ns:$key-->{$trail}";
247 }
248 $this->size++;
249 }
250 wfProfileOut( __METHOD__ );
251 return $retVal;
252 }
253
254 /**
255 * Replace <!--LINK--> link placeholders with actual links, in the buffer
256 *
257 * @param $text
258 * @return array Array of link CSS classes, indexed by PDBK.
259 */
260 function replace( &$text ) {
261 wfProfileIn( __METHOD__ );
262
263 /** @todo FIXME: replaceInternal doesn't return a value */
264 $colours = $this->replaceInternal( $text );
265 $this->replaceInterwiki( $text );
266
267 wfProfileOut( __METHOD__ );
268 return $colours;
269 }
270
271 /**
272 * Replace internal links
273 * @param string $text
274 */
275 protected function replaceInternal( &$text ) {
276 if ( !$this->internals ) {
277 return;
278 }
279
280 wfProfileIn( __METHOD__ );
281 global $wgContLang;
282
283 $colours = array();
284 $linkCache = LinkCache::singleton();
285 $output = $this->parent->getOutput();
286
287 wfProfileIn( __METHOD__ . '-check' );
288 $dbr = wfGetDB( DB_SLAVE );
289 $threshold = $this->parent->getOptions()->getStubThreshold();
290
291 # Sort by namespace
292 ksort( $this->internals );
293
294 $linkcolour_ids = array();
295
296 # Generate query
297 $queries = array();
298 foreach ( $this->internals as $ns => $entries ) {
299 foreach ( $entries as $entry ) {
300 $title = $entry['title'];
301 $pdbk = $entry['pdbk'];
302
303 # Skip invalid entries.
304 # Result will be ugly, but prevents crash.
305 if ( is_null( $title ) ) {
306 continue;
307 }
308
309 # Check if it's a static known link, e.g. interwiki
310 if ( $title->isAlwaysKnown() ) {
311 $colours[$pdbk] = '';
312 } elseif ( $ns == NS_SPECIAL ) {
313 $colours[$pdbk] = 'new';
314 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
315 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
316 $output->addLink( $title, $id );
317 $linkcolour_ids[$id] = $pdbk;
318 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
319 $colours[$pdbk] = 'new';
320 } else {
321 # Not in the link cache, add it to the query
322 $queries[$ns][] = $title->getDBkey();
323 }
324 }
325 }
326 if ( $queries ) {
327 $where = array();
328 foreach ( $queries as $ns => $pages ) {
329 $where[] = $dbr->makeList(
330 array(
331 'page_namespace' => $ns,
332 'page_title' => $pages,
333 ),
334 LIST_AND
335 );
336 }
337
338 $res = $dbr->select(
339 'page',
340 array( 'page_id', 'page_namespace', 'page_title',
341 'page_is_redirect', 'page_len', 'page_latest' ),
342 $dbr->makeList( $where, LIST_OR ),
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 # @todo FIXME: Convoluted data flow
354 # The redirect status and length is passed to getLinkColour via the LinkCache
355 # Use formal parameters instead
356 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
357 //add id to the extension todolist
358 $linkcolour_ids[$s->page_id] = $pdbk;
359 }
360 unset( $res );
361 }
362 if ( count( $linkcolour_ids ) ) {
363 //pass an array of page_ids to an extension
364 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
365 }
366 wfProfileOut( __METHOD__ . '-check' );
367
368 # Do a second query for different language variants of links and categories
369 if ( $wgContLang->hasVariants() ) {
370 $this->doVariants( $colours );
371 }
372
373 # Construct search and replace arrays
374 wfProfileIn( __METHOD__ . '-construct' );
375 $replacePairs = array();
376 foreach ( $this->internals as $ns => $entries ) {
377 foreach ( $entries as $index => $entry ) {
378 $pdbk = $entry['pdbk'];
379 $title = $entry['title'];
380 $query = isset( $entry['query'] ) ? $entry['query'] : array();
381 $key = "$ns:$index";
382 $searchkey = "<!--LINK $key-->";
383 $displayText = $entry['text'];
384 if ( isset( $entry['selflink'] ) ) {
385 $replacePairs[$searchkey] = Linker::makeSelfLinkObj( $title, $displayText, $query );
386 continue;
387 }
388 if ( $displayText === '' ) {
389 $displayText = null;
390 }
391 if ( !isset( $colours[$pdbk] ) ) {
392 $colours[$pdbk] = 'new';
393 }
394 $attribs = array();
395 if ( $colours[$pdbk] == 'new' ) {
396 $linkCache->addBadLinkObj( $title );
397 $output->addLink( $title, 0 );
398 $type = array( 'broken' );
399 } else {
400 if ( $colours[$pdbk] != '' ) {
401 $attribs['class'] = $colours[$pdbk];
402 }
403 $type = array( 'known', 'noclasses' );
404 }
405 $replacePairs[$searchkey] = Linker::link( $title, $displayText,
406 $attribs, $query, $type );
407 }
408 }
409 $replacer = new HashtableReplacer( $replacePairs, 1 );
410 wfProfileOut( __METHOD__ . '-construct' );
411
412 # Do the thing
413 wfProfileIn( __METHOD__ . '-replace' );
414 $text = preg_replace_callback(
415 '/(<!--LINK .*?-->)/',
416 $replacer->cb(),
417 $text
418 );
419
420 wfProfileOut( __METHOD__ . '-replace' );
421 wfProfileOut( __METHOD__ );
422 }
423
424 /**
425 * Replace interwiki links
426 * @param string $text
427 */
428 protected function replaceInterwiki( &$text ) {
429 if ( empty( $this->interwikis ) ) {
430 return;
431 }
432
433 wfProfileIn( __METHOD__ );
434 # Make interwiki link HTML
435 $output = $this->parent->getOutput();
436 $replacePairs = array();
437 foreach ( $this->interwikis as $key => $link ) {
438 $replacePairs[$key] = Linker::link( $link['title'], $link['text'] );
439 $output->addInterwikiLink( $link['title'] );
440 }
441 $replacer = new HashtableReplacer( $replacePairs, 1 );
442
443 $text = preg_replace_callback(
444 '/<!--IWLINK (.*?)-->/',
445 $replacer->cb(),
446 $text );
447 wfProfileOut( __METHOD__ );
448 }
449
450 /**
451 * Modify $this->internals and $colours according to language variant linking rules
452 * @param array $colours
453 */
454 protected function doVariants( &$colours ) {
455 global $wgContLang;
456 $linkBatch = new LinkBatch();
457 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
458 $output = $this->parent->getOutput();
459 $linkCache = LinkCache::singleton();
460 $threshold = $this->parent->getOptions()->getStubThreshold();
461 $titlesToBeConverted = '';
462 $titlesAttrs = array();
463
464 // Concatenate titles to a single string, thus we only need auto convert the
465 // single string to all variants. This would improve parser's performance
466 // significantly.
467 foreach ( $this->internals as $ns => $entries ) {
468 if ( $ns == NS_SPECIAL ) {
469 continue;
470 }
471 foreach ( $entries as $index => $entry ) {
472 $pdbk = $entry['pdbk'];
473 // we only deal with new links (in its first query)
474 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
475 $titlesAttrs[] = array( $index, $entry['title'] );
476 // separate titles with \0 because it would never appears
477 // in a valid title
478 $titlesToBeConverted .= $entry['title']->getText() . "\0";
479 }
480 }
481 }
482
483 // Now do the conversion and explode string to text of titles
484 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
485 $allVariantsName = array_keys( $titlesAllVariants );
486 foreach ( $titlesAllVariants as &$titlesVariant ) {
487 $titlesVariant = explode( "\0", $titlesVariant );
488 }
489
490 // Then add variants of links to link batch
491 $parentTitle = $this->parent->getTitle();
492 foreach ( $titlesAttrs as $i => $attrs ) {
493 list( $index, $title ) = $attrs;
494 $ns = $title->getNamespace();
495 $text = $title->getText();
496
497 foreach ( $allVariantsName as $variantName ) {
498 $textVariant = $titlesAllVariants[$variantName][$i];
499 if ( $textVariant === $text ) {
500 continue;
501 }
502
503 $variantTitle = Title::makeTitle( $ns, $textVariant );
504 if ( is_null( $variantTitle ) ) {
505 continue;
506 }
507
508 // Self-link checking for mixed/different variant titles. At this point, we
509 // already know the exact title does not exist, so the link cannot be to a
510 // variant of the current title that exists as a separate page.
511 if ( $variantTitle->equals( $parentTitle ) && !$title->hasFragment() ) {
512 $this->internals[$ns][$index]['selflink'] = true;
513 continue 2;
514 }
515
516 $linkBatch->addObj( $variantTitle );
517 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
518 }
519 }
520
521 // process categories, check if a category exists in some variant
522 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
523 $varCategories = array(); // category replacements oldDBkey => newDBkey
524 foreach ( $output->getCategoryLinks() as $category ) {
525 $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
526 $linkBatch->addObj( $categoryTitle );
527 $variants = $wgContLang->autoConvertToAllVariants( $category );
528 foreach ( $variants as $variant ) {
529 if ( $variant !== $category ) {
530 $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
531 if ( is_null( $variantTitle ) ) {
532 continue;
533 }
534 $linkBatch->addObj( $variantTitle );
535 $categoryMap[$variant] = array( $category, $categoryTitle );
536 }
537 }
538 }
539
540 if ( !$linkBatch->isEmpty() ) {
541 // construct query
542 $dbr = wfGetDB( DB_SLAVE );
543 $varRes = $dbr->select( 'page',
544 array( 'page_id', 'page_namespace', 'page_title',
545 'page_is_redirect', 'page_len', 'page_latest' ),
546 $linkBatch->constructSet( 'page', $dbr ),
547 __METHOD__
548 );
549
550 $linkcolour_ids = array();
551
552 // for each found variants, figure out link holders and replace
553 foreach ( $varRes as $s ) {
554
555 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
556 $varPdbk = $variantTitle->getPrefixedDBkey();
557 $vardbk = $variantTitle->getDBkey();
558
559 $holderKeys = array();
560 if ( isset( $variantMap[$varPdbk] ) ) {
561 $holderKeys = $variantMap[$varPdbk];
562 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
563 $output->addLink( $variantTitle, $s->page_id );
564 }
565
566 // loop over link holders
567 foreach ( $holderKeys as $key ) {
568 list( $ns, $index ) = explode( ':', $key, 2 );
569 $entry =& $this->internals[$ns][$index];
570 $pdbk = $entry['pdbk'];
571
572 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
573 // found link in some of the variants, replace the link holder data
574 $entry['title'] = $variantTitle;
575 $entry['pdbk'] = $varPdbk;
576
577 // set pdbk and colour
578 # @todo FIXME: Convoluted data flow
579 # The redirect status and length is passed to getLinkColour via the LinkCache
580 # Use formal parameters instead
581 $colours[$varPdbk] = Linker::getLinkColour( $variantTitle, $threshold );
582 $linkcolour_ids[$s->page_id] = $pdbk;
583 }
584 }
585
586 // check if the object is a variant of a category
587 if ( isset( $categoryMap[$vardbk] ) ) {
588 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
589 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
590 $varCategories[$oldkey] = $vardbk;
591 }
592 }
593 }
594 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
595
596 // rebuild the categories in original order (if there are replacements)
597 if ( count( $varCategories ) > 0 ) {
598 $newCats = array();
599 $originalCats = $output->getCategories();
600 foreach ( $originalCats as $cat => $sortkey ) {
601 // make the replacement
602 if ( array_key_exists( $cat, $varCategories ) ) {
603 $newCats[$varCategories[$cat]] = $sortkey;
604 } else {
605 $newCats[$cat] = $sortkey;
606 }
607 }
608 $output->setCategoryLinks( $newCats );
609 }
610 }
611 }
612
613 /**
614 * Replace <!--LINK--> link placeholders with plain text of links
615 * (not HTML-formatted).
616 *
617 * @param string $text
618 * @return string
619 */
620 function replaceText( $text ) {
621 wfProfileIn( __METHOD__ );
622
623 $text = preg_replace_callback(
624 '/<!--(LINK|IWLINK) (.*?)-->/',
625 array( &$this, 'replaceTextCallback' ),
626 $text );
627
628 wfProfileOut( __METHOD__ );
629 return $text;
630 }
631
632 /**
633 * Callback for replaceText()
634 *
635 * @param array $matches
636 * @return string
637 * @private
638 */
639 function replaceTextCallback( $matches ) {
640 $type = $matches[1];
641 $key = $matches[2];
642 if ( $type == 'LINK' ) {
643 list( $ns, $index ) = explode( ':', $key, 2 );
644 if ( isset( $this->internals[$ns][$index]['text'] ) ) {
645 return $this->internals[$ns][$index]['text'];
646 }
647 } elseif ( $type == 'IWLINK' ) {
648 if ( isset( $this->interwikis[$key]['text'] ) ) {
649 return $this->interwikis[$key]['text'];
650 }
651 }
652 return $matches[0];
653 }
654 }