Move closing parenthesis from multi line if and function to own line
[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 $other LinkHolderArray
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 $other LinkHolderArray
114 * @param array $texts 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 * @return LinkHolderArray
155 */
156 function getSubArray( $text ) {
157 $sub = new LinkHolderArray( $this->parent );
158
159 # Internal links
160 $pos = 0;
161 while ( $pos < strlen( $text ) ) {
162 if ( !preg_match( '/<!--LINK (\d+):(\d+)-->/',
163 $text, $m, PREG_OFFSET_CAPTURE, $pos )
164 ) {
165 break;
166 }
167 $ns = $m[1][0];
168 $key = $m[2][0];
169 $sub->internals[$ns][$key] = $this->internals[$ns][$key];
170 $pos = $m[0][1] + strlen( $m[0][0] );
171 }
172
173 # Interwiki links
174 $pos = 0;
175 while ( $pos < strlen( $text ) ) {
176 if ( !preg_match( '/<!--IWLINK (\d+)-->/', $text, $m, PREG_OFFSET_CAPTURE, $pos ) ) {
177 break;
178 }
179 $key = $m[1][0];
180 $sub->interwikis[$key] = $this->interwikis[$key];
181 $pos = $m[0][1] + strlen( $m[0][0] );
182 }
183 return $sub;
184 }
185
186 /**
187 * Returns true if the memory requirements of this object are getting large
188 * @return bool
189 */
190 function isBig() {
191 global $wgLinkHolderBatchSize;
192 return $this->size > $wgLinkHolderBatchSize;
193 }
194
195 /**
196 * Clear all stored link holders.
197 * Make sure you don't have any text left using these link holders, before you call this
198 */
199 function clear() {
200 $this->internals = array();
201 $this->interwikis = array();
202 $this->size = 0;
203 }
204
205 /**
206 * Make a link placeholder. The text returned can be later resolved to a real link with
207 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
208 * parsing of interwiki links, and secondly to allow all existence checks and
209 * article length checks (for stub links) to be bundled into a single query.
210 *
211 * @param $nt Title
212 * @param $text String
213 * @param array $query [optional]
214 * @param string $trail [optional]
215 * @param string $prefix [optional]
216 * @return string
217 */
218 function makeHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
219 wfProfileIn( __METHOD__ );
220 if ( !is_object( $nt ) ) {
221 # Fail gracefully
222 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
223 } else {
224 # Separate the link trail from the rest of the link
225 list( $inside, $trail ) = Linker::splitTrail( $trail );
226
227 $entry = array(
228 'title' => $nt,
229 'text' => $prefix . $text . $inside,
230 'pdbk' => $nt->getPrefixedDBkey(),
231 );
232 if ( $query !== array() ) {
233 $entry['query'] = $query;
234 }
235
236 if ( $nt->isExternal() ) {
237 // Use a globally unique ID to keep the objects mergable
238 $key = $this->parent->nextLinkID();
239 $this->interwikis[$key] = $entry;
240 $retVal = "<!--IWLINK $key-->{$trail}";
241 } else {
242 $key = $this->parent->nextLinkID();
243 $ns = $nt->getNamespace();
244 $this->internals[$ns][$key] = $entry;
245 $retVal = "<!--LINK $ns:$key-->{$trail}";
246 }
247 $this->size++;
248 }
249 wfProfileOut( __METHOD__ );
250 return $retVal;
251 }
252
253 /**
254 * Replace <!--LINK--> link placeholders with actual links, in the buffer
255 *
256 * @return array of link CSS classes, indexed by PDBK.
257 */
258 function replace( &$text ) {
259 wfProfileIn( __METHOD__ );
260
261 $colours = $this->replaceInternal( $text ); // FIXME: replaceInternal doesn't return a value
262 $this->replaceInterwiki( $text );
263
264 wfProfileOut( __METHOD__ );
265 return $colours;
266 }
267
268 /**
269 * Replace internal links
270 */
271 protected function replaceInternal( &$text ) {
272 if ( !$this->internals ) {
273 return;
274 }
275
276 wfProfileIn( __METHOD__ );
277 global $wgContLang;
278
279 $colours = array();
280 $linkCache = LinkCache::singleton();
281 $output = $this->parent->getOutput();
282
283 wfProfileIn( __METHOD__ . '-check' );
284 $dbr = wfGetDB( DB_SLAVE );
285 $threshold = $this->parent->getOptions()->getStubThreshold();
286
287 # Sort by namespace
288 ksort( $this->internals );
289
290 $linkcolour_ids = array();
291
292 # Generate query
293 $queries = array();
294 foreach ( $this->internals as $ns => $entries ) {
295 foreach ( $entries as $entry ) {
296 $title = $entry['title'];
297 $pdbk = $entry['pdbk'];
298
299 # Skip invalid entries.
300 # Result will be ugly, but prevents crash.
301 if ( is_null( $title ) ) {
302 continue;
303 }
304
305 # Check if it's a static known link, e.g. interwiki
306 if ( $title->isAlwaysKnown() ) {
307 $colours[$pdbk] = '';
308 } elseif ( $ns == NS_SPECIAL ) {
309 $colours[$pdbk] = 'new';
310 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
311 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
312 $output->addLink( $title, $id );
313 $linkcolour_ids[$id] = $pdbk;
314 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
315 $colours[$pdbk] = 'new';
316 } else {
317 # Not in the link cache, add it to the query
318 $queries[$ns][] = $title->getDBkey();
319 }
320 }
321 }
322 if ( $queries ) {
323 $where = array();
324 foreach ( $queries as $ns => $pages ) {
325 $where[] = $dbr->makeList(
326 array(
327 'page_namespace' => $ns,
328 'page_title' => $pages,
329 ),
330 LIST_AND
331 );
332 }
333
334 $res = $dbr->select(
335 'page',
336 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
337 $dbr->makeList( $where, LIST_OR ),
338 __METHOD__
339 );
340
341 # Fetch data and form into an associative array
342 # non-existent = broken
343 foreach ( $res as $s ) {
344 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
345 $pdbk = $title->getPrefixedDBkey();
346 $linkCache->addGoodLinkObjFromRow( $title, $s );
347 $output->addLink( $title, $s->page_id );
348 # @todo FIXME: Convoluted data flow
349 # The redirect status and length is passed to getLinkColour via the LinkCache
350 # Use formal parameters instead
351 $colours[$pdbk] = Linker::getLinkColour( $title, $threshold );
352 //add id to the extension todolist
353 $linkcolour_ids[$s->page_id] = $pdbk;
354 }
355 unset( $res );
356 }
357 if ( count( $linkcolour_ids ) ) {
358 //pass an array of page_ids to an extension
359 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
360 }
361 wfProfileOut( __METHOD__ . '-check' );
362
363 # Do a second query for different language variants of links and categories
364 if ( $wgContLang->hasVariants() ) {
365 $this->doVariants( $colours );
366 }
367
368 # Construct search and replace arrays
369 wfProfileIn( __METHOD__ . '-construct' );
370 $replacePairs = array();
371 foreach ( $this->internals as $ns => $entries ) {
372 foreach ( $entries as $index => $entry ) {
373 $pdbk = $entry['pdbk'];
374 $title = $entry['title'];
375 $query = isset( $entry['query'] ) ? $entry['query'] : array();
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 }
386 if ( !isset( $colours[$pdbk] ) ) {
387 $colours[$pdbk] = 'new';
388 }
389 $attribs = array();
390 if ( $colours[$pdbk] == 'new' ) {
391 $linkCache->addBadLinkObj( $title );
392 $output->addLink( $title, 0 );
393 $type = array( 'broken' );
394 } else {
395 if ( $colours[$pdbk] != '' ) {
396 $attribs['class'] = $colours[$pdbk];
397 }
398 $type = array( 'known', 'noclasses' );
399 }
400 $replacePairs[$searchkey] = Linker::link( $title, $displayText,
401 $attribs, $query, $type );
402 }
403 }
404 $replacer = new HashtableReplacer( $replacePairs, 1 );
405 wfProfileOut( __METHOD__ . '-construct' );
406
407 # Do the thing
408 wfProfileIn( __METHOD__ . '-replace' );
409 $text = preg_replace_callback(
410 '/(<!--LINK .*?-->)/',
411 $replacer->cb(),
412 $text
413 );
414
415 wfProfileOut( __METHOD__ . '-replace' );
416 wfProfileOut( __METHOD__ );
417 }
418
419 /**
420 * Replace interwiki links
421 */
422 protected function replaceInterwiki( &$text ) {
423 if ( empty( $this->interwikis ) ) {
424 return;
425 }
426
427 wfProfileIn( __METHOD__ );
428 # Make interwiki link HTML
429 $output = $this->parent->getOutput();
430 $replacePairs = array();
431 foreach ( $this->interwikis as $key => $link ) {
432 $replacePairs[$key] = Linker::link( $link['title'], $link['text'] );
433 $output->addInterwikiLink( $link['title'] );
434 }
435 $replacer = new HashtableReplacer( $replacePairs, 1 );
436
437 $text = preg_replace_callback(
438 '/<!--IWLINK (.*?)-->/',
439 $replacer->cb(),
440 $text );
441 wfProfileOut( __METHOD__ );
442 }
443
444 /**
445 * Modify $this->internals and $colours according to language variant linking rules
446 */
447 protected function doVariants( &$colours ) {
448 global $wgContLang;
449 $linkBatch = new LinkBatch();
450 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
451 $output = $this->parent->getOutput();
452 $linkCache = LinkCache::singleton();
453 $threshold = $this->parent->getOptions()->getStubThreshold();
454 $titlesToBeConverted = '';
455 $titlesAttrs = array();
456
457 // Concatenate titles to a single string, thus we only need auto convert the
458 // single string to all variants. This would improve parser's performance
459 // significantly.
460 foreach ( $this->internals as $ns => $entries ) {
461 if ( $ns == NS_SPECIAL ) {
462 continue;
463 }
464 foreach ( $entries as $index => $entry ) {
465 $pdbk = $entry['pdbk'];
466 // we only deal with new links (in its first query)
467 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
468 $titlesAttrs[] = array( $index, $entry['title'] );
469 // separate titles with \0 because it would never appears
470 // in a valid title
471 $titlesToBeConverted .= $entry['title']->getText() . "\0";
472 }
473 }
474 }
475
476 // Now do the conversion and explode string to text of titles
477 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( rtrim( $titlesToBeConverted, "\0" ) );
478 $allVariantsName = array_keys( $titlesAllVariants );
479 foreach ( $titlesAllVariants as &$titlesVariant ) {
480 $titlesVariant = explode( "\0", $titlesVariant );
481 }
482
483 // Then add variants of links to link batch
484 $parentTitle = $this->parent->getTitle();
485 foreach ( $titlesAttrs as $i => $attrs ) {
486 list( $index, $title ) = $attrs;
487 $ns = $title->getNamespace();
488 $text = $title->getText();
489
490 foreach ( $allVariantsName as $variantName ) {
491 $textVariant = $titlesAllVariants[$variantName][$i];
492 if ( $textVariant === $text ) {
493 continue;
494 }
495
496 $variantTitle = Title::makeTitle( $ns, $textVariant );
497 if ( is_null( $variantTitle ) ) {
498 continue;
499 }
500
501 // Self-link checking for mixed/different variant titles. At this point, we
502 // already know the exact title does not exist, so the link cannot be to a
503 // variant of the current title that exists as a separate page.
504 if ( $variantTitle->equals( $parentTitle ) && $title->getFragment() === '' ) {
505 $this->internals[$ns][$index]['selflink'] = true;
506 continue 2;
507 }
508
509 $linkBatch->addObj( $variantTitle );
510 $variantMap[$variantTitle->getPrefixedDBkey()][] = "$ns:$index";
511 }
512 }
513
514 // process categories, check if a category exists in some variant
515 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
516 $varCategories = array(); // category replacements oldDBkey => newDBkey
517 foreach ( $output->getCategoryLinks() as $category ) {
518 $categoryTitle = Title::makeTitleSafe( NS_CATEGORY, $category );
519 $linkBatch->addObj( $categoryTitle );
520 $variants = $wgContLang->autoConvertToAllVariants( $category );
521 foreach ( $variants as $variant ) {
522 if ( $variant !== $category ) {
523 $variantTitle = Title::makeTitleSafe( NS_CATEGORY, $variant );
524 if ( is_null( $variantTitle ) ) {
525 continue;
526 }
527 $linkBatch->addObj( $variantTitle );
528 $categoryMap[$variant] = array( $category, $categoryTitle );
529 }
530 }
531 }
532
533 if ( !$linkBatch->isEmpty() ) {
534 // construct query
535 $dbr = wfGetDB( DB_SLAVE );
536 $varRes = $dbr->select( 'page',
537 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len', 'page_latest' ),
538 $linkBatch->constructSet( 'page', $dbr ),
539 __METHOD__
540 );
541
542 $linkcolour_ids = array();
543
544 // for each found variants, figure out link holders and replace
545 foreach ( $varRes as $s ) {
546
547 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
548 $varPdbk = $variantTitle->getPrefixedDBkey();
549 $vardbk = $variantTitle->getDBkey();
550
551 $holderKeys = array();
552 if ( isset( $variantMap[$varPdbk] ) ) {
553 $holderKeys = $variantMap[$varPdbk];
554 $linkCache->addGoodLinkObjFromRow( $variantTitle, $s );
555 $output->addLink( $variantTitle, $s->page_id );
556 }
557
558 // loop over link holders
559 foreach ( $holderKeys as $key ) {
560 list( $ns, $index ) = explode( ':', $key, 2 );
561 $entry =& $this->internals[$ns][$index];
562 $pdbk = $entry['pdbk'];
563
564 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] === 'new' ) {
565 // found link in some of the variants, replace the link holder data
566 $entry['title'] = $variantTitle;
567 $entry['pdbk'] = $varPdbk;
568
569 // set pdbk and colour
570 # @todo FIXME: Convoluted data flow
571 # The redirect status and length is passed to getLinkColour via the LinkCache
572 # Use formal parameters instead
573 $colours[$varPdbk] = Linker::getLinkColour( $variantTitle, $threshold );
574 $linkcolour_ids[$s->page_id] = $pdbk;
575 }
576 }
577
578 // check if the object is a variant of a category
579 if ( isset( $categoryMap[$vardbk] ) ) {
580 list( $oldkey, $oldtitle ) = $categoryMap[$vardbk];
581 if ( !isset( $varCategories[$oldkey] ) && !$oldtitle->exists() ) {
582 $varCategories[$oldkey] = $vardbk;
583 }
584 }
585 }
586 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
587
588 // rebuild the categories in original order (if there are replacements)
589 if ( count( $varCategories ) > 0 ) {
590 $newCats = array();
591 $originalCats = $output->getCategories();
592 foreach ( $originalCats as $cat => $sortkey ) {
593 // make the replacement
594 if ( array_key_exists( $cat, $varCategories ) ) {
595 $newCats[$varCategories[$cat]] = $sortkey;
596 } else {
597 $newCats[$cat] = $sortkey;
598 }
599 }
600 $output->setCategoryLinks( $newCats );
601 }
602 }
603 }
604
605 /**
606 * Replace <!--LINK--> link placeholders with plain text of links
607 * (not HTML-formatted).
608 *
609 * @param $text String
610 * @return String
611 */
612 function replaceText( $text ) {
613 wfProfileIn( __METHOD__ );
614
615 $text = preg_replace_callback(
616 '/<!--(LINK|IWLINK) (.*?)-->/',
617 array( &$this, 'replaceTextCallback' ),
618 $text );
619
620 wfProfileOut( __METHOD__ );
621 return $text;
622 }
623
624 /**
625 * Callback for replaceText()
626 *
627 * @param $matches Array
628 * @return string
629 * @private
630 */
631 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 }