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