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