More function and variable documentation
[lhc/web/wiklou.git] / includes / parser / LinkHolderArray.php
1 <?php
2 /**
3 * Holder of replacement pairs for wiki links
4 *
5 * @file
6 */
7
8 /**
9 * @ingroup Parser
10 */
11 class LinkHolderArray {
12 var $internals = array(), $interwikis = array();
13 var $size = 0;
14 var $parent;
15
16 function __construct( $parent ) {
17 $this->parent = $parent;
18 }
19
20 /**
21 * Reduce memory usage to reduce the impact of circular references
22 */
23 function __destruct() {
24 foreach ( $this as $name => $value ) {
25 unset( $this->$name );
26 }
27 }
28
29 /**
30 * Merge another LinkHolderArray into this one
31 * @param $other LinkHolderArray
32 */
33 function merge( $other ) {
34 foreach ( $other->internals as $ns => $entries ) {
35 $this->size += count( $entries );
36 if ( !isset( $this->internals[$ns] ) ) {
37 $this->internals[$ns] = $entries;
38 } else {
39 $this->internals[$ns] += $entries;
40 }
41 }
42 $this->interwikis += $other->interwikis;
43 }
44
45 /**
46 * Returns true if the memory requirements of this object are getting large
47 */
48 function isBig() {
49 global $wgLinkHolderBatchSize;
50 return $this->size > $wgLinkHolderBatchSize;
51 }
52
53 /**
54 * Clear all stored link holders.
55 * Make sure you don't have any text left using these link holders, before you call this
56 */
57 function clear() {
58 $this->internals = array();
59 $this->interwikis = array();
60 $this->size = 0;
61 }
62
63 /**
64 * Make a link placeholder. The text returned can be later resolved to a real link with
65 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
66 * parsing of interwiki links, and secondly to allow all existence checks and
67 * article length checks (for stub links) to be bundled into a single query.
68 *
69 * @param $nt Title
70 */
71 function makeHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
72 wfProfileIn( __METHOD__ );
73 if ( ! is_object($nt) ) {
74 # Fail gracefully
75 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
76 } else {
77 # Separate the link trail from the rest of the link
78 list( $inside, $trail ) = Linker::splitTrail( $trail );
79
80 $entry = array(
81 'title' => $nt,
82 'text' => $prefix.$text.$inside,
83 'pdbk' => $nt->getPrefixedDBkey(),
84 );
85 if ( $query !== '' ) {
86 $entry['query'] = $query;
87 }
88
89 if ( $nt->isExternal() ) {
90 // Use a globally unique ID to keep the objects mergable
91 $key = $this->parent->nextLinkID();
92 $this->interwikis[$key] = $entry;
93 $retVal = "<!--IWLINK $key-->{$trail}";
94 } else {
95 $key = $this->parent->nextLinkID();
96 $ns = $nt->getNamespace();
97 $this->internals[$ns][$key] = $entry;
98 $retVal = "<!--LINK $ns:$key-->{$trail}";
99 }
100 $this->size++;
101 }
102 wfProfileOut( __METHOD__ );
103 return $retVal;
104 }
105
106 /**
107 * Get the stub threshold
108 */
109 function getStubThreshold() {
110 if ( !isset( $this->stubThreshold ) ) {
111 $this->stubThreshold = $this->parent->getUser()->getStubThreshold();
112 }
113 return $this->stubThreshold;
114 }
115
116 /**
117 * FIXME: update documentation. makeLinkObj() is deprecated.
118 * Replace <!--LINK--> link placeholders with actual links, in the buffer
119 * Placeholders created in Skin::makeLinkObj()
120 * Returns an array of link CSS classes, indexed by PDBK.
121 */
122 function replace( &$text ) {
123 wfProfileIn( __METHOD__ );
124
125 $colours = $this->replaceInternal( $text );
126 $this->replaceInterwiki( $text );
127
128 wfProfileOut( __METHOD__ );
129 return $colours;
130 }
131
132 /**
133 * Replace internal links
134 */
135 protected function replaceInternal( &$text ) {
136 if ( !$this->internals ) {
137 return;
138 }
139
140 wfProfileIn( __METHOD__ );
141 global $wgContLang;
142
143 $colours = array();
144 $sk = $this->parent->getOptions()->getSkin( $this->parent->mTitle );
145 $linkCache = LinkCache::singleton();
146 $output = $this->parent->getOutput();
147
148 wfProfileIn( __METHOD__.'-check' );
149 $dbr = wfGetDB( DB_SLAVE );
150 $page = $dbr->tableName( 'page' );
151 $threshold = $this->getStubThreshold();
152
153 # Sort by namespace
154 ksort( $this->internals );
155
156 $linkcolour_ids = array();
157
158 # Generate query
159 $query = false;
160 $current = null;
161 foreach ( $this->internals as $ns => $entries ) {
162 foreach ( $entries as $entry ) {
163 $title = $entry['title'];
164 $pdbk = $entry['pdbk'];
165
166 # Skip invalid entries.
167 # Result will be ugly, but prevents crash.
168 if ( is_null( $title ) ) {
169 continue;
170 }
171
172 # Check if it's a static known link, e.g. interwiki
173 if ( $title->isAlwaysKnown() ) {
174 $colours[$pdbk] = '';
175 } elseif ( $ns == NS_SPECIAL ) {
176 $colours[$pdbk] = 'new';
177 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
178 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
179 $output->addLink( $title, $id );
180 $linkcolour_ids[$id] = $pdbk;
181 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
182 $colours[$pdbk] = 'new';
183 } else {
184 # Not in the link cache, add it to the query
185 if ( !isset( $current ) ) {
186 $current = $ns;
187 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len, page_latest";
188 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
189 } elseif ( $current != $ns ) {
190 $current = $ns;
191 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
192 } else {
193 $query .= ', ';
194 }
195
196 $query .= $dbr->addQuotes( $title->getDBkey() );
197 }
198 }
199 }
200 if ( $query ) {
201 $query .= '))';
202
203 $res = $dbr->query( $query, __METHOD__ );
204
205 # Fetch data and form into an associative array
206 # non-existent = broken
207 foreach ( $res as $s ) {
208 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
209 $pdbk = $title->getPrefixedDBkey();
210 $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect, $s->page_latest );
211 $output->addLink( $title, $s->page_id );
212 # FIXME: convoluted data flow
213 # The redirect status and length is passed to getLinkColour via the LinkCache
214 # Use formal parameters instead
215 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
216 //add id to the extension todolist
217 $linkcolour_ids[$s->page_id] = $pdbk;
218 }
219 unset( $res );
220 }
221 if ( count($linkcolour_ids) ) {
222 //pass an array of page_ids to an extension
223 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
224 }
225 wfProfileOut( __METHOD__.'-check' );
226
227 # Do a second query for different language variants of links and categories
228 if($wgContLang->hasVariants()) {
229 $this->doVariants( $colours );
230 }
231
232 # Construct search and replace arrays
233 wfProfileIn( __METHOD__.'-construct' );
234 $replacePairs = array();
235 foreach ( $this->internals as $ns => $entries ) {
236 foreach ( $entries as $index => $entry ) {
237 $pdbk = $entry['pdbk'];
238 $title = $entry['title'];
239 $query = isset( $entry['query'] ) ? $entry['query'] : '';
240 $key = "$ns:$index";
241 $searchkey = "<!--LINK $key-->";
242 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
243 $linkCache->addBadLinkObj( $title );
244 $colours[$pdbk] = 'new';
245 $output->addLink( $title, 0 );
246 // FIXME: replace deprecated makeBrokenLinkObj() by link()
247 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
248 $entry['text'],
249 $query );
250 } else {
251 // FIXME: replace deprecated makeColouredLinkObj() by link()
252 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
253 $entry['text'],
254 $query );
255 }
256 }
257 }
258 $replacer = new HashtableReplacer( $replacePairs, 1 );
259 wfProfileOut( __METHOD__.'-construct' );
260
261 # Do the thing
262 wfProfileIn( __METHOD__.'-replace' );
263 $text = preg_replace_callback(
264 '/(<!--LINK .*?-->)/',
265 $replacer->cb(),
266 $text);
267
268 wfProfileOut( __METHOD__.'-replace' );
269 wfProfileOut( __METHOD__ );
270 }
271
272 /**
273 * Replace interwiki links
274 */
275 protected function replaceInterwiki( &$text ) {
276 if ( empty( $this->interwikis ) ) {
277 return;
278 }
279
280 wfProfileIn( __METHOD__ );
281 # Make interwiki link HTML
282 $sk = $this->parent->getOptions()->getSkin( $this->parent->mTitle );
283 $output = $this->parent->getOutput();
284 $replacePairs = array();
285 foreach( $this->interwikis as $key => $link ) {
286 $replacePairs[$key] = $sk->link( $link['title'], $link['text'] );
287 $output->addInterwikiLink( $link['title'] );
288 }
289 $replacer = new HashtableReplacer( $replacePairs, 1 );
290
291 $text = preg_replace_callback(
292 '/<!--IWLINK (.*?)-->/',
293 $replacer->cb(),
294 $text );
295 wfProfileOut( __METHOD__ );
296 }
297
298 /**
299 * Modify $this->internals and $colours according to language variant linking rules
300 */
301 protected function doVariants( &$colours ) {
302 global $wgContLang;
303 $linkBatch = new LinkBatch();
304 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
305 $output = $this->parent->getOutput();
306 $linkCache = LinkCache::singleton();
307 $sk = $this->parent->getOptions()->getSkin( $this->parent->mTitle );
308 $threshold = $this->getStubThreshold();
309 $titlesToBeConverted = '';
310 $titlesAttrs = array();
311
312 // Concatenate titles to a single string, thus we only need auto convert the
313 // single string to all variants. This would improve parser's performance
314 // significantly.
315 foreach ( $this->internals as $ns => $entries ) {
316 foreach ( $entries as $index => $entry ) {
317 $pdbk = $entry['pdbk'];
318 // we only deal with new links (in its first query)
319 if ( !isset( $colours[$pdbk] ) ) {
320 $title = $entry['title'];
321 $titleText = $title->getText();
322 $titlesAttrs[] = array(
323 'ns' => $ns,
324 'key' => "$ns:$index",
325 'titleText' => $titleText,
326 );
327 // separate titles with \0 because it would never appears
328 // in a valid title
329 $titlesToBeConverted .= $titleText . "\0";
330 }
331 }
332 }
333
334 // Now do the conversion and explode string to text of titles
335 $titlesAllVariants = $wgContLang->autoConvertToAllVariants( $titlesToBeConverted );
336 $allVariantsName = array_keys( $titlesAllVariants );
337 foreach ( $titlesAllVariants as &$titlesVariant ) {
338 $titlesVariant = explode( "\0", $titlesVariant );
339 }
340 $l = count( $titlesAttrs );
341 // Then add variants of links to link batch
342 for ( $i = 0; $i < $l; $i ++ ) {
343 foreach ( $allVariantsName as $variantName ) {
344 $textVariant = $titlesAllVariants[$variantName][$i];
345 extract( $titlesAttrs[$i] );
346 if($textVariant != $titleText){
347 $variantTitle = Title::makeTitle( $ns, $textVariant );
348 if( is_null( $variantTitle ) ) {
349 continue;
350 }
351 $linkBatch->addObj( $variantTitle );
352 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
353 }
354 }
355 }
356
357 // process categories, check if a category exists in some variant
358 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
359 $varCategories = array(); // category replacements oldDBkey => newDBkey
360 foreach( $output->getCategoryLinks() as $category ){
361 $variants = $wgContLang->autoConvertToAllVariants( $category );
362 foreach($variants as $variant){
363 if($variant != $category){
364 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
365 if(is_null($variantTitle)) continue;
366 $linkBatch->addObj( $variantTitle );
367 $categoryMap[$variant] = $category;
368 }
369 }
370 }
371
372
373 if(!$linkBatch->isEmpty()){
374 // construct query
375 $dbr = wfGetDB( DB_SLAVE );
376 $varRes = $dbr->select( 'page',
377 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect', 'page_len' ),
378 $linkBatch->constructSet( 'page', $dbr ),
379 __METHOD__
380 );
381
382 $linkcolour_ids = array();
383
384 // for each found variants, figure out link holders and replace
385 foreach ( $varRes as $s ) {
386
387 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
388 $varPdbk = $variantTitle->getPrefixedDBkey();
389 $vardbk = $variantTitle->getDBkey();
390
391 $holderKeys = array();
392 if( isset( $variantMap[$varPdbk] ) ) {
393 $holderKeys = $variantMap[$varPdbk];
394 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
395 $output->addLink( $variantTitle, $s->page_id );
396 }
397
398 // loop over link holders
399 foreach( $holderKeys as $key ) {
400 list( $ns, $index ) = explode( ':', $key, 2 );
401 $entry =& $this->internals[$ns][$index];
402 $pdbk = $entry['pdbk'];
403
404 if(!isset($colours[$pdbk])){
405 // found link in some of the variants, replace the link holder data
406 $entry['title'] = $variantTitle;
407 $entry['pdbk'] = $varPdbk;
408
409 // set pdbk and colour
410 # FIXME: convoluted data flow
411 # The redirect status and length is passed to getLinkColour via the LinkCache
412 # Use formal parameters instead
413 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
414 $linkcolour_ids[$s->page_id] = $pdbk;
415 }
416 }
417
418 // check if the object is a variant of a category
419 if(isset($categoryMap[$vardbk])){
420 $oldkey = $categoryMap[$vardbk];
421 if($oldkey != $vardbk)
422 $varCategories[$oldkey]=$vardbk;
423 }
424 }
425 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
426
427 // rebuild the categories in original order (if there are replacements)
428 if(count($varCategories)>0){
429 $newCats = array();
430 $originalCats = $output->getCategories();
431 foreach($originalCats as $cat => $sortkey){
432 // make the replacement
433 if( array_key_exists($cat,$varCategories) )
434 $newCats[$varCategories[$cat]] = $sortkey;
435 else $newCats[$cat] = $sortkey;
436 }
437 $output->setCategoryLinks($newCats);
438 }
439 }
440 }
441
442 /**
443 * Replace <!--LINK--> link placeholders with plain text of links
444 * (not HTML-formatted).
445 *
446 * @param $text String
447 * @return String
448 */
449 function replaceText( $text ) {
450 wfProfileIn( __METHOD__ );
451
452 $text = preg_replace_callback(
453 '/<!--(LINK|IWLINK) (.*?)-->/',
454 array( &$this, 'replaceTextCallback' ),
455 $text );
456
457 wfProfileOut( __METHOD__ );
458 return $text;
459 }
460
461 /**
462 * Callback for replaceText()
463 *
464 * @param $matches Array
465 * @return string
466 * @private
467 */
468 function replaceTextCallback( $matches ) {
469 $type = $matches[1];
470 $key = $matches[2];
471 if( $type == 'LINK' ) {
472 list( $ns, $index ) = explode( ':', $key, 2 );
473 if( isset( $this->internals[$ns][$index]['text'] ) ) {
474 return $this->internals[$ns][$index]['text'];
475 }
476 } elseif( $type == 'IWLINK' ) {
477 if( isset( $this->interwikis[$key]['text'] ) ) {
478 return $this->interwikis[$key]['text'];
479 }
480 }
481 return $matches[0];
482 }
483 }