Slight fix for r47781: remove useless if($index) conditional: $index is always set...
[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 * Replace <!--LINK--> link placeholders with actual links, in the buffer
109 * Placeholders created in Skin::makeLinkObj()
110 * Returns an array of link CSS classes, indexed by PDBK.
111 */
112 function replace( &$text ) {
113 wfProfileIn( __METHOD__ );
114
115 $colours = $this->replaceInternal( $text );
116 $this->replaceInterwiki( $text );
117
118 wfProfileOut( __METHOD__ );
119 return $colours;
120 }
121
122 /**
123 * Replace internal links
124 */
125 protected function replaceInternal( &$text ) {
126 if ( !$this->internals ) {
127 return;
128 }
129
130 wfProfileIn( __METHOD__ );
131 global $wgContLang;
132
133 $colours = array();
134 $sk = $this->parent->getOptions()->getSkin();
135 $linkCache = LinkCache::singleton();
136 $output = $this->parent->getOutput();
137
138 wfProfileIn( __METHOD__.'-check' );
139 $dbr = wfGetDB( DB_SLAVE );
140 $page = $dbr->tableName( 'page' );
141 $threshold = $this->getStubThreshold();
142
143 # Sort by namespace
144 ksort( $this->internals );
145
146 # Generate query
147 $query = false;
148 $current = null;
149 foreach ( $this->internals as $ns => $entries ) {
150 foreach ( $entries as $index => $entry ) {
151 $key = "$ns:$index";
152 $title = $entry['title'];
153 $pdbk = $entry['pdbk'];
154
155 # Skip invalid entries.
156 # Result will be ugly, but prevents crash.
157 if ( is_null( $title ) ) {
158 continue;
159 }
160
161 # Check if it's a static known link, e.g. interwiki
162 if ( $title->isAlwaysKnown() ) {
163 $colours[$pdbk] = '';
164 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
165 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
166 $output->addLink( $title, $id );
167 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
168 $colours[$pdbk] = 'new';
169 } else {
170 # Not in the link cache, add it to the query
171 if ( !isset( $current ) ) {
172 $current = $ns;
173 $query = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
174 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
175 } elseif ( $current != $ns ) {
176 $current = $ns;
177 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
178 } else {
179 $query .= ', ';
180 }
181
182 $query .= $dbr->addQuotes( $title->getDBkey() );
183 }
184 }
185 }
186 if ( $query ) {
187 $query .= '))';
188
189 $res = $dbr->query( $query, __METHOD__ );
190
191 # Fetch data and form into an associative array
192 # non-existent = broken
193 $linkcolour_ids = array();
194 while ( $s = $dbr->fetchObject($res) ) {
195 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
196 $pdbk = $title->getPrefixedDBkey();
197 $linkCache->addGoodLinkObj( $s->page_id, $title, $s->page_len, $s->page_is_redirect );
198 $output->addLink( $title, $s->page_id );
199 # FIXME: convoluted data flow
200 # The redirect status and length is passed to getLinkColour via the LinkCache
201 # Use formal parameters instead
202 $colours[$pdbk] = $sk->getLinkColour( $title, $threshold );
203 //add id to the extension todolist
204 $linkcolour_ids[$s->page_id] = $pdbk;
205 }
206 unset( $res );
207 //pass an array of page_ids to an extension
208 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
209 }
210 wfProfileOut( __METHOD__.'-check' );
211
212 # Do a second query for different language variants of links and categories
213 if($wgContLang->hasVariants()) {
214 $this->doVariants( $colours );
215 }
216
217 # Construct search and replace arrays
218 wfProfileIn( __METHOD__.'-construct' );
219 $replacePairs = array();
220 foreach ( $this->internals as $ns => $entries ) {
221 foreach ( $entries as $index => $entry ) {
222 $pdbk = $entry['pdbk'];
223 $title = $entry['title'];
224 $query = isset( $entry['query'] ) ? $entry['query'] : '';
225 $key = "$ns:$index";
226 $searchkey = "<!--LINK $key-->";
227 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
228 $linkCache->addBadLinkObj( $title );
229 $colours[$pdbk] = 'new';
230 $output->addLink( $title, 0 );
231 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
232 $entry['text'],
233 $query );
234 } else {
235 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
236 $entry['text'],
237 $query );
238 }
239 }
240 }
241 $replacer = new HashtableReplacer( $replacePairs, 1 );
242 wfProfileOut( __METHOD__.'-construct' );
243
244 # Do the thing
245 wfProfileIn( __METHOD__.'-replace' );
246 $text = preg_replace_callback(
247 '/(<!--LINK .*?-->)/',
248 $replacer->cb(),
249 $text);
250
251 wfProfileOut( __METHOD__.'-replace' );
252 wfProfileOut( __METHOD__ );
253 }
254
255 /**
256 * Replace interwiki links
257 */
258 protected function replaceInterwiki( &$text ) {
259 if ( empty( $this->interwikis ) ) {
260 return;
261 }
262
263 wfProfileIn( __METHOD__ );
264 # Make interwiki link HTML
265 $sk = $this->parent->getOptions()->getSkin();
266 $replacePairs = array();
267 foreach( $this->interwikis as $key => $link ) {
268 $replacePairs[$key] = $sk->link( $link['title'], $link['text'] );
269 }
270 $replacer = new HashtableReplacer( $replacePairs, 1 );
271
272 $text = preg_replace_callback(
273 '/<!--IWLINK (.*?)-->/',
274 $replacer->cb(),
275 $text );
276 wfProfileOut( __METHOD__ );
277 }
278
279 /**
280 * Modify $this->internals and $colours according to language variant linking rules
281 */
282 protected function doVariants( &$colours ) {
283 global $wgContLang;
284 $linkBatch = new LinkBatch();
285 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
286 $output = $this->parent->getOutput();
287 $linkCache = LinkCache::singleton();
288 $sk = $this->parent->getOptions()->getSkin();
289 $threshold = $this->getStubThreshold();
290
291 // Add variants of links to link batch
292 foreach ( $this->internals as $ns => $entries ) {
293 foreach ( $entries as $index => $entry ) {
294 $key = "$ns:$index";
295 $pdbk = $entry['pdbk'];
296 $title = $entry['title'];
297 $titleText = $title->getText();
298
299 // generate all variants of the link title text
300 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
301
302 // if link was not found (in first query), add all variants to query
303 if ( !isset($colours[$pdbk]) ){
304 foreach($allTextVariants as $textVariant){
305 if($textVariant != $titleText){
306 $variantTitle = Title::makeTitle( $ns, $textVariant );
307 if(is_null($variantTitle)) continue;
308 $linkBatch->addObj( $variantTitle );
309 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
310 }
311 }
312 }
313 }
314 }
315
316 // process categories, check if a category exists in some variant
317 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
318 $varCategories = array(); // category replacements oldDBkey => newDBkey
319 foreach( $output->getCategoryLinks() as $category ){
320 $variants = $wgContLang->convertLinkToAllVariants($category);
321 foreach($variants as $variant){
322 if($variant != $category){
323 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
324 if(is_null($variantTitle)) continue;
325 $linkBatch->addObj( $variantTitle );
326 $categoryMap[$variant] = $category;
327 }
328 }
329 }
330
331
332 if(!$linkBatch->isEmpty()){
333 // construct query
334 $dbr = wfGetDB( DB_SLAVE );
335 $page = $dbr->tableName( 'page' );
336 $titleClause = $linkBatch->constructSet('page', $dbr);
337 $variantQuery = "SELECT page_id, page_namespace, page_title, page_is_redirect, page_len";
338 $variantQuery .= " FROM $page WHERE $titleClause";
339 $varRes = $dbr->query( $variantQuery, __METHOD__ );
340 $linkcolour_ids = array();
341
342 // for each found variants, figure out link holders and replace
343 while ( $s = $dbr->fetchObject($varRes) ) {
344
345 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
346 $varPdbk = $variantTitle->getPrefixedDBkey();
347 $vardbk = $variantTitle->getDBkey();
348
349 $holderKeys = array();
350 if(isset($variantMap[$varPdbk])){
351 $holderKeys = $variantMap[$varPdbk];
352 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle, $s->page_len, $s->page_is_redirect );
353 $output->addLink( $variantTitle, $s->page_id );
354 }
355
356 // loop over link holders
357 foreach($holderKeys as $key){
358 list( $ns, $index ) = explode( ':', $key, 2 );
359 $entry =& $this->internals[$ns][$index];
360 $pdbk = $entry['pdbk'];
361
362 if(!isset($colours[$pdbk])){
363 // found link in some of the variants, replace the link holder data
364 $entry['title'] = $variantTitle;
365 $entry['pdbk'] = $varPdbk;
366
367 // set pdbk and colour
368 # FIXME: convoluted data flow
369 # The redirect status and length is passed to getLinkColour via the LinkCache
370 # Use formal parameters instead
371 $colours[$varPdbk] = $sk->getLinkColour( $variantTitle, $threshold );
372 $linkcolour_ids[$s->page_id] = $pdbk;
373 }
374 }
375
376 // check if the object is a variant of a category
377 if(isset($categoryMap[$vardbk])){
378 $oldkey = $categoryMap[$vardbk];
379 if($oldkey != $vardbk)
380 $varCategories[$oldkey]=$vardbk;
381 }
382 }
383 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
384
385 // rebuild the categories in original order (if there are replacements)
386 if(count($varCategories)>0){
387 $newCats = array();
388 $originalCats = $output->getCategories();
389 foreach($originalCats as $cat => $sortkey){
390 // make the replacement
391 if( array_key_exists($cat,$varCategories) )
392 $newCats[$varCategories[$cat]] = $sortkey;
393 else $newCats[$cat] = $sortkey;
394 }
395 $output->setCategoryLinks($newCats);
396 }
397 }
398 }
399
400 /**
401 * Replace <!--LINK--> link placeholders with plain text of links
402 * (not HTML-formatted).
403 * @param string $text
404 * @return string
405 */
406 function replaceText( $text ) {
407 wfProfileIn( __METHOD__ );
408
409 $text = preg_replace_callback(
410 '/<!--(LINK|IWLINK) (.*?)-->/',
411 array( &$this, 'replaceTextCallback' ),
412 $text );
413
414 wfProfileOut( __METHOD__ );
415 return $text;
416 }
417
418 /**
419 * @param array $matches
420 * @return string
421 * @private
422 */
423 function replaceTextCallback( $matches ) {
424 $type = $matches[1];
425 $key = $matches[2];
426 if( $type == 'LINK' ) {
427 list( $ns, $index ) = explode( ':', $key, 2 );
428 if( isset( $this->internals[$ns][$index]['text'] ) ) {
429 return $this->internals[$ns][$index]['text'];
430 }
431 } elseif( $type == 'IWLINK' ) {
432 if( isset( $this->interwikis[$key]['text'] ) ) {
433 return $this->interwikis[$key]['text'];
434 }
435 }
436 return $matches[0];
437 }
438 }