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