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