Re-do r96798 ("LanguageConverter now depends on the page content language"), without...
[lhc/web/wiklou.git] / includes / parser / ParserOutput.php
1 <?php
2 /**
3 * Output of the PHP parser
4 *
5 * @file
6 * @ingroup Parser
7 */
8
9 /**
10 * @todo document
11 * @ingroup Parser
12 */
13
14 class CacheTime {
15 var $mVersion = Parser::VERSION, # Compatibility check
16 $mCacheTime = '', # Time when this object was generated, or -1 for uncacheable. Used in ParserCache.
17 $mCacheExpiry = null, # Seconds after which the object should expire, use 0 for uncachable. Used in ParserCache.
18 $mContainsOldMagic; # Boolean variable indicating if the input contained variables like {{CURRENTDAY}}
19
20 function getCacheTime() { return $this->mCacheTime; }
21
22 function containsOldMagic() { return $this->mContainsOldMagic; }
23 function setContainsOldMagic( $com ) { return wfSetVar( $this->mContainsOldMagic, $com ); }
24
25 /**
26 * setCacheTime() sets the timestamp expressing when the page has been rendered.
27 * This doesn not control expiry, see updateCacheExpiry() for that!
28 * @param $t string
29 * @return string
30 */
31 function setCacheTime( $t ) { return wfSetVar( $this->mCacheTime, $t ); }
32
33 /**
34 * Sets the number of seconds after which this object should expire.
35 * This value is used with the ParserCache.
36 * If called with a value greater than the value provided at any previous call,
37 * the new call has no effect. The value returned by getCacheExpiry is smaller
38 * or equal to the smallest number that was provided as an argument to
39 * updateCacheExpiry().
40 *
41 * @param $seconds number
42 */
43 function updateCacheExpiry( $seconds ) {
44 $seconds = (int)$seconds;
45
46 if ( $this->mCacheExpiry === null || $this->mCacheExpiry > $seconds ) {
47 $this->mCacheExpiry = $seconds;
48 }
49
50 // hack: set old-style marker for uncacheable entries.
51 if ( $this->mCacheExpiry !== null && $this->mCacheExpiry <= 0 ) {
52 $this->mCacheTime = -1;
53 }
54 }
55
56 /**
57 * Returns the number of seconds after which this object should expire.
58 * This method is used by ParserCache to determine how long the ParserOutput can be cached.
59 * The timestamp of expiry can be calculated by adding getCacheExpiry() to getCacheTime().
60 * The value returned by getCacheExpiry is smaller or equal to the smallest number
61 * that was provided to a call of updateCacheExpiry(), and smaller or equal to the
62 * value of $wgParserCacheExpireTime.
63 */
64 function getCacheExpiry() {
65 global $wgParserCacheExpireTime;
66
67 if ( $this->mCacheTime < 0 ) {
68 return 0;
69 } // old-style marker for "not cachable"
70
71 $expire = $this->mCacheExpiry;
72
73 if ( $expire === null ) {
74 $expire = $wgParserCacheExpireTime;
75 } else {
76 $expire = min( $expire, $wgParserCacheExpireTime );
77 }
78
79 if( $this->containsOldMagic() ) { //compatibility hack
80 $expire = min( $expire, 3600 ); # 1 hour
81 }
82
83 if ( $expire <= 0 ) {
84 return 0; // not cachable
85 } else {
86 return $expire;
87 }
88 }
89
90 /**
91 * @return bool
92 */
93 function isCacheable() {
94 return $this->getCacheExpiry() > 0;
95 }
96
97 /**
98 * Return true if this cached output object predates the global or
99 * per-article cache invalidation timestamps, or if it comes from
100 * an incompatible older version.
101 *
102 * @param $touched String: the affected article's last touched timestamp
103 * @return Boolean
104 */
105 public function expired( $touched ) {
106 global $wgCacheEpoch;
107 return !$this->isCacheable() || // parser says it's uncacheable
108 $this->getCacheTime() < $touched ||
109 $this->getCacheTime() <= $wgCacheEpoch ||
110 $this->getCacheTime() < wfTimestamp( TS_MW, time() - $this->getCacheExpiry() ) || // expiry period has passed
111 !isset( $this->mVersion ) ||
112 version_compare( $this->mVersion, Parser::VERSION, "lt" );
113 }
114 }
115
116 class ParserOutput extends CacheTime {
117 var $mText, # The output text
118 $mLanguageLinks, # List of the full text of language links, in the order they appear
119 $mCategories, # Map of category names to sort keys
120 $mTitleText, # title text of the chosen language variant
121 $mLinks = array(), # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
122 $mTemplates = array(), # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
123 $mTemplateIds = array(), # 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken.
124 $mDistantTemplates = array(), # 3-D map of WIKIID/NS/DBK to ID for the template references. ID=zero for broken.
125 $mDistantTemplateIds = array(), # 3-D map of WIKIID/NS/DBK to rev ID for the template references. ID=zero for broken.
126 $mImages = array(), # DB keys of the images used, in the array key only
127 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
128 $mExternalLinks = array(), # External link URLs, in the key only
129 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
130 $mNewSection = false, # Show a new section link?
131 $mHideNewSection = false, # Hide the new section link?
132 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
133 $mHeadItems = array(), # Items to put in the <head> section
134 $mModules = array(), # Modules to be loaded by the resource loader
135 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
136 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
137 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
138 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
139 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
140 $mSections = array(), # Table of contents
141 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
142 $mProperties = array(), # Name/value pairs to be cached in the DB
143 $mTOCHTML = ''; # HTML of the TOC
144 private $mIndexPolicy = ''; # 'index' or 'noindex'? Any other value will result in no change.
145 private $mAccessedOptions = array(); # List of ParserOptions (stored in the keys)
146
147 const EDITSECTION_REGEX = '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
148
149 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
150 $containsOldMagic = false, $titletext = '' )
151 {
152 $this->mText = $text;
153 $this->mLanguageLinks = $languageLinks;
154 $this->mCategories = $categoryLinks;
155 $this->mContainsOldMagic = $containsOldMagic;
156 $this->mTitleText = $titletext;
157 }
158
159 function getText() {
160 if ( $this->mEditSectionTokens ) {
161 return preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
162 array( &$this, 'replaceEditSectionLinksCallback' ), $this->mText );
163 }
164 return $this->mText;
165 }
166
167 /**
168 * callback used by getText to replace editsection tokens
169 * @private
170 */
171 function replaceEditSectionLinksCallback( $m ) {
172 global $wgOut, $wgLang;
173 $args = array(
174 htmlspecialchars_decode($m[1]),
175 htmlspecialchars_decode($m[2]),
176 isset($m[4]) ? $m[3] : null,
177 );
178 $args[0] = Title::newFromText( $args[0] );
179 if ( !is_object($args[0]) ) {
180 throw new MWException("Bad parser output text.");
181 }
182 $args[] = $wgLang->getCode();
183 $skin = $wgOut->getSkin();
184 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
185 }
186
187 function &getLanguageLinks() { return $this->mLanguageLinks; }
188 function getInterwikiLinks() { return $this->mInterwikiLinks; }
189 function getCategoryLinks() { return array_keys( $this->mCategories ); }
190 function &getCategories() { return $this->mCategories; }
191 function getTitleText() { return $this->mTitleText; }
192 function getSections() { return $this->mSections; }
193 function getEditSectionTokens() { return $this->mEditSectionTokens; }
194 function &getLinks() { return $this->mLinks; }
195 function &getTemplates() { return $this->mTemplates; }
196 function &getDistantTemplates() { return $this->mDistantTemplates; }
197 function &getDistantTemplateIds() { return $this->mDistantTemplateIds; }
198 function &getTemplateIds() { return $this->mTemplateIds; }
199 function &getImages() { return $this->mImages; }
200 function &getFileSearchOptions() { return $this->mFileSearchOptions; }
201 function &getExternalLinks() { return $this->mExternalLinks; }
202 function getNoGallery() { return $this->mNoGallery; }
203 function getHeadItems() { return $this->mHeadItems; }
204 function getModules() { return $this->mModules; }
205 function getModuleScripts() { return $this->mModuleScripts; }
206 function getModuleStyles() { return $this->mModuleStyles; }
207 function getModuleMessages() { return $this->mModuleMessages; }
208 function getOutputHooks() { return (array)$this->mOutputHooks; }
209 function getWarnings() { return array_keys( $this->mWarnings ); }
210 function getIndexPolicy() { return $this->mIndexPolicy; }
211 function getTOCHTML() { return $this->mTOCHTML; }
212
213 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
214 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
215 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
216
217 function setTitleText( $t ) { return wfSetVar( $this->mTitleText, $t ); }
218 function setSections( $toc ) { return wfSetVar( $this->mSections, $toc ); }
219 function setEditSectionTokens( $t ) { return wfSetVar( $this->mEditSectionTokens, $t ); }
220 function setIndexPolicy( $policy ) { return wfSetVar( $this->mIndexPolicy, $policy ); }
221 function setTOCHTML( $tochtml ) { return wfSetVar( $this->mTOCHTML, $tochtml ); }
222
223 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
224 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
225 function addWarning( $s ) { $this->mWarnings[$s] = 1; }
226
227 function addOutputHook( $hook, $data = false ) {
228 $this->mOutputHooks[] = array( $hook, $data );
229 }
230
231 function setNewSection( $value ) {
232 $this->mNewSection = (bool)$value;
233 }
234 function hideNewSection ( $value ) {
235 $this->mHideNewSection = (bool)$value;
236 }
237 function getHideNewSection () {
238 return (bool)$this->mHideNewSection;
239 }
240 function getNewSection() {
241 return (bool)$this->mNewSection;
242 }
243
244 function addExternalLink( $url ) {
245 # We don't register links pointing to our own server, unless... :-)
246 global $wgServer, $wgRegisterInternalExternals;
247 if( $wgRegisterInternalExternals or stripos($url,$wgServer.'/')!==0)
248 $this->mExternalLinks[$url] = 1;
249 }
250
251 /**
252 * Record a local or interwiki inline link for saving in future link tables.
253 *
254 * @param $title Title object
255 * @param $id Mixed: optional known page_id so we can skip the lookup
256 */
257 function addLink( $title, $id = null ) {
258 if ( $title->isExternal() ) {
259 // Don't record interwikis in pagelinks
260 $this->addInterwikiLink( $title );
261 return;
262 }
263 $ns = $title->getNamespace();
264 $dbk = $title->getDBkey();
265 if ( $ns == NS_MEDIA ) {
266 // Normalize this pseudo-alias if it makes it down here...
267 $ns = NS_FILE;
268 } elseif( $ns == NS_SPECIAL ) {
269 // We don't record Special: links currently
270 // It might actually be wise to, but we'd need to do some normalization.
271 return;
272 } elseif( $dbk === '' ) {
273 // Don't record self links - [[#Foo]]
274 return;
275 }
276 if ( !isset( $this->mLinks[$ns] ) ) {
277 $this->mLinks[$ns] = array();
278 }
279 if ( is_null( $id ) ) {
280 $id = $title->getArticleID();
281 }
282 $this->mLinks[$ns][$dbk] = $id;
283 }
284
285 /**
286 * Register a file dependency for this output
287 * @param $name string Title dbKey
288 * @param $timestamp string MW timestamp of file creation (or false if non-existing)
289 * @param $sha string base 36 SHA-1 of file (or false if non-existing)
290 * @return void
291 */
292 function addImage( $name, $timestamp = null, $sha1 = null ) {
293 $this->mImages[$name] = 1;
294 if ( $timestamp !== null && $sha1 !== null ) {
295 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
296 }
297 }
298
299 /**
300 * Register a template dependency for this output
301 * @param $title Title
302 * @param $page_id
303 * @param $rev_id
304 * @return void
305 */
306 function addTemplate( $title, $page_id, $rev_id ) {
307 $ns = $title->getNamespace();
308 $dbk = $title->getDBkey();
309 if ( !isset( $this->mTemplates[$ns] ) ) {
310 $this->mTemplates[$ns] = array();
311 }
312 $this->mTemplates[$ns][$dbk] = $page_id;
313 if ( !isset( $this->mTemplateIds[$ns] ) ) {
314 $this->mTemplateIds[$ns] = array();
315 }
316 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
317 }
318
319 function addDistantTemplate( $title, $page_id, $rev_id ) {
320 $prefix = $title->getInterwiki();
321 if ( $prefix !=='' ) {
322 $ns = $title->getNamespace();
323 $dbk = $title->getDBkey();
324
325 if ( !isset( $this->mDistantTemplates[$prefix] ) ) {
326 $this->mDistantTemplates[$prefix] = array();
327 }
328 if ( !isset( $this->mDistantTemplates[$prefix][$ns] ) ) {
329 $this->mDistantTemplates[$prefix][$ns] = array();
330 }
331 $this->mDistantTemplates[$prefix][$ns][$dbk] = $page_id;
332
333 // For versioning
334 if ( !isset( $this->mDistantTemplateIds[$prefix] ) ) {
335 $this->mDistantTemplateIds[$prefix] = array();
336 }
337 if ( !isset( $this->mDistantTemplateIds[$prefix][$ns] ) ) {
338 $this->mDistantTemplateIds[$prefix][$ns] = array();
339 }
340 $this->mDistantTemplateIds[$prefix][$ns][$dbk] = $rev_id;
341 }
342 }
343
344 /**
345 * @param $title Title object, must be an interwiki link
346 * @throws MWException if given invalid input
347 */
348 function addInterwikiLink( $title ) {
349 $prefix = $title->getInterwiki();
350 if( $prefix == '' ) {
351 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
352 }
353 if (!isset($this->mInterwikiLinks[$prefix])) {
354 $this->mInterwikiLinks[$prefix] = array();
355 }
356 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
357 }
358
359 /**
360 * Add some text to the <head>.
361 * If $tag is set, the section with that tag will only be included once
362 * in a given page.
363 */
364 function addHeadItem( $section, $tag = false ) {
365 if ( $tag !== false ) {
366 $this->mHeadItems[$tag] = $section;
367 } else {
368 $this->mHeadItems[] = $section;
369 }
370 }
371
372 public function addModules( $modules ) {
373 $this->mModules = array_merge( $this->mModules, (array) $modules );
374 }
375
376 public function addModuleScripts( $modules ) {
377 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
378 }
379
380 public function addModuleStyles( $modules ) {
381 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
382 }
383
384 public function addModuleMessages( $modules ) {
385 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
386 }
387
388 /**
389 * Copy items from the OutputPage object into this one
390 *
391 * @param $out OutputPage object
392 */
393 public function addOutputPageMetadata( OutputPage $out ) {
394 $this->addModules( $out->getModules() );
395 $this->addModuleScripts( $out->getModuleScripts() );
396 $this->addModuleStyles( $out->getModuleStyles() );
397 $this->addModuleMessages( $out->getModuleMessages() );
398
399 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
400 }
401
402 /**
403 * Override the title to be used for display
404 * -- this is assumed to have been validated
405 * (check equal normalisation, etc.)
406 *
407 * @param $text String: desired title text
408 */
409 public function setDisplayTitle( $text ) {
410 $this->setTitleText( $text );
411 $this->setProperty( 'displaytitle', $text );
412 }
413
414 /**
415 * Get the title to be used for display
416 *
417 * @return String
418 */
419 public function getDisplayTitle() {
420 $t = $this->getTitleText();
421 if( $t === '' ) {
422 return false;
423 }
424 return $t;
425 }
426
427 /**
428 * Fairly generic flag setter thingy.
429 */
430 public function setFlag( $flag ) {
431 $this->mFlags[$flag] = true;
432 }
433
434 public function getFlag( $flag ) {
435 return isset( $this->mFlags[$flag] );
436 }
437
438 /**
439 * Set a property to be cached in the DB
440 */
441 public function setProperty( $name, $value ) {
442 $this->mProperties[$name] = $value;
443 }
444
445 public function getProperty( $name ){
446 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
447 }
448
449 public function getProperties() {
450 if ( !isset( $this->mProperties ) ) {
451 $this->mProperties = array();
452 }
453 return $this->mProperties;
454 }
455
456
457 /**
458 * Returns the options from its ParserOptions which have been taken
459 * into account to produce this output or false if not available.
460 * @return mixed Array
461 */
462 public function getUsedOptions() {
463 if ( !isset( $this->mAccessedOptions ) ) {
464 return array();
465 }
466 return array_keys( $this->mAccessedOptions );
467 }
468
469 /**
470 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
471 * @access private
472 */
473 function recordOption( $option ) {
474 $this->mAccessedOptions[$option] = true;
475 }
476 }