Back out r95396 and friends
[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 $mImages = array(), # DB keys of the images used, in the array key only
125 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
126 $mExternalLinks = array(), # External link URLs, in the key only
127 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
128 $mNewSection = false, # Show a new section link?
129 $mHideNewSection = false, # Hide the new section link?
130 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
131 $mHeadItems = array(), # Items to put in the <head> section
132 $mModules = array(), # Modules to be loaded by the resource loader
133 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
134 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
135 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
136 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
137 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
138 $mSections = array(), # Table of contents
139 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
140 $mProperties = array(), # Name/value pairs to be cached in the DB
141 $mTOCHTML = ''; # HTML of the TOC
142 private $mIndexPolicy = ''; # 'index' or 'noindex'? Any other value will result in no change.
143 private $mAccessedOptions = array(); # List of ParserOptions (stored in the keys)
144
145 const EDITSECTION_REGEX = '#<(?:mw:)?editsection page="(.*?)" section="(.*?)"(?:/>|>(.*?)(</(?:mw:)?editsection>))#';
146
147 function __construct( $text = '', $languageLinks = array(), $categoryLinks = array(),
148 $containsOldMagic = false, $titletext = '' )
149 {
150 $this->mText = $text;
151 $this->mLanguageLinks = $languageLinks;
152 $this->mCategories = $categoryLinks;
153 $this->mContainsOldMagic = $containsOldMagic;
154 $this->mTitleText = $titletext;
155 }
156
157 function getText() {
158 if ( $this->mEditSectionTokens ) {
159 return preg_replace_callback( ParserOutput::EDITSECTION_REGEX,
160 array( &$this, 'replaceEditSectionLinksCallback' ), $this->mText );
161 }
162 return $this->mText;
163 }
164
165 /**
166 * callback used by getText to replace editsection tokens
167 * @private
168 */
169 function replaceEditSectionLinksCallback( $m ) {
170 global $wgOut, $wgLang;
171 $args = array(
172 htmlspecialchars_decode($m[1]),
173 htmlspecialchars_decode($m[2]),
174 isset($m[4]) ? $m[3] : null,
175 );
176 $args[0] = Title::newFromText( $args[0] );
177 if ( !is_object($args[0]) ) {
178 throw new MWException("Bad parser output text.");
179 }
180 $args[] = $wgLang->getCode();
181 $skin = $wgOut->getSkin();
182 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
183 }
184
185 function &getLanguageLinks() { return $this->mLanguageLinks; }
186 function getInterwikiLinks() { return $this->mInterwikiLinks; }
187 function getCategoryLinks() { return array_keys( $this->mCategories ); }
188 function &getCategories() { return $this->mCategories; }
189 function getTitleText() { return $this->mTitleText; }
190 function getSections() { return $this->mSections; }
191 function getEditSectionTokens() { return $this->mEditSectionTokens; }
192 function &getLinks() { return $this->mLinks; }
193 function &getTemplates() { return $this->mTemplates; }
194 function &getTemplateIds() { return $this->mTemplateIds; }
195 function &getImages() { return $this->mImages; }
196 function &getFileSearchOptions() { return $this->mFileSearchOptions; }
197 function &getExternalLinks() { return $this->mExternalLinks; }
198 function getNoGallery() { return $this->mNoGallery; }
199 function getHeadItems() { return $this->mHeadItems; }
200 function getModules() { return $this->mModules; }
201 function getModuleScripts() { return $this->mModuleScripts; }
202 function getModuleStyles() { return $this->mModuleStyles; }
203 function getModuleMessages() { return $this->mModuleMessages; }
204 function getOutputHooks() { return (array)$this->mOutputHooks; }
205 function getWarnings() { return array_keys( $this->mWarnings ); }
206 function getIndexPolicy() { return $this->mIndexPolicy; }
207 function getTOCHTML() { return $this->mTOCHTML; }
208
209 function setText( $text ) { return wfSetVar( $this->mText, $text ); }
210 function setLanguageLinks( $ll ) { return wfSetVar( $this->mLanguageLinks, $ll ); }
211 function setCategoryLinks( $cl ) { return wfSetVar( $this->mCategories, $cl ); }
212
213 function setTitleText( $t ) { return wfSetVar( $this->mTitleText, $t ); }
214 function setSections( $toc ) { return wfSetVar( $this->mSections, $toc ); }
215 function setEditSectionTokens( $t ) { return wfSetVar( $this->mEditSectionTokens, $t ); }
216 function setIndexPolicy( $policy ) { return wfSetVar( $this->mIndexPolicy, $policy ); }
217 function setTOCHTML( $tochtml ) { return wfSetVar( $this->mTOCHTML, $tochtml ); }
218
219 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
220 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
221 function addWarning( $s ) { $this->mWarnings[$s] = 1; }
222
223 function addOutputHook( $hook, $data = false ) {
224 $this->mOutputHooks[] = array( $hook, $data );
225 }
226
227 function setNewSection( $value ) {
228 $this->mNewSection = (bool)$value;
229 }
230 function hideNewSection ( $value ) {
231 $this->mHideNewSection = (bool)$value;
232 }
233 function getHideNewSection () {
234 return (bool)$this->mHideNewSection;
235 }
236 function getNewSection() {
237 return (bool)$this->mNewSection;
238 }
239
240 function addExternalLink( $url ) {
241 # We don't register links pointing to our own server, unless... :-)
242 global $wgServer, $wgRegisterInternalExternals;
243 if( $wgRegisterInternalExternals or stripos($url,$wgServer.'/')!==0)
244 $this->mExternalLinks[$url] = 1;
245 }
246
247 /**
248 * Record a local or interwiki inline link for saving in future link tables.
249 *
250 * @param $title Title object
251 * @param $id Mixed: optional known page_id so we can skip the lookup
252 */
253 function addLink( $title, $id = null ) {
254 if ( $title->isExternal() ) {
255 // Don't record interwikis in pagelinks
256 $this->addInterwikiLink( $title );
257 return;
258 }
259 $ns = $title->getNamespace();
260 $dbk = $title->getDBkey();
261 if ( $ns == NS_MEDIA ) {
262 // Normalize this pseudo-alias if it makes it down here...
263 $ns = NS_FILE;
264 } elseif( $ns == NS_SPECIAL ) {
265 // We don't record Special: links currently
266 // It might actually be wise to, but we'd need to do some normalization.
267 return;
268 } elseif( $dbk === '' ) {
269 // Don't record self links - [[#Foo]]
270 return;
271 }
272 if ( !isset( $this->mLinks[$ns] ) ) {
273 $this->mLinks[$ns] = array();
274 }
275 if ( is_null( $id ) ) {
276 $id = $title->getArticleID();
277 }
278 $this->mLinks[$ns][$dbk] = $id;
279 }
280
281 /**
282 * Register a file dependency for this output
283 * @param $name string Title dbKey
284 * @param $timestamp string MW timestamp of file creation (or false if non-existing)
285 * @param $sha string base 36 SHA-1 of file (or false if non-existing)
286 * @return void
287 */
288 function addImage( $name, $timestamp = null, $sha1 = null ) {
289 $this->mImages[$name] = 1;
290 if ( $timestamp !== null && $sha1 !== null ) {
291 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
292 }
293 }
294
295 /**
296 * Register a template dependency for this output
297 * @param $title Title
298 * @param $page_id
299 * @param $rev_id
300 * @return void
301 */
302 function addTemplate( $title, $page_id, $rev_id ) {
303 $ns = $title->getNamespace();
304 $dbk = $title->getDBkey();
305 if ( !isset( $this->mTemplates[$ns] ) ) {
306 $this->mTemplates[$ns] = array();
307 }
308 $this->mTemplates[$ns][$dbk] = $page_id;
309 if ( !isset( $this->mTemplateIds[$ns] ) ) {
310 $this->mTemplateIds[$ns] = array();
311 }
312 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
313 }
314
315 /**
316 * @param $title Title object, must be an interwiki link
317 * @throws MWException if given invalid input
318 */
319 function addInterwikiLink( $title ) {
320 $prefix = $title->getInterwiki();
321 if( $prefix == '' ) {
322 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
323 }
324 if (!isset($this->mInterwikiLinks[$prefix])) {
325 $this->mInterwikiLinks[$prefix] = array();
326 }
327 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
328 }
329
330 /**
331 * Add some text to the <head>.
332 * If $tag is set, the section with that tag will only be included once
333 * in a given page.
334 */
335 function addHeadItem( $section, $tag = false ) {
336 if ( $tag !== false ) {
337 $this->mHeadItems[$tag] = $section;
338 } else {
339 $this->mHeadItems[] = $section;
340 }
341 }
342
343 public function addModules( $modules ) {
344 $this->mModules = array_merge( $this->mModules, (array) $modules );
345 }
346
347 public function addModuleScripts( $modules ) {
348 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
349 }
350
351 public function addModuleStyles( $modules ) {
352 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
353 }
354
355 public function addModuleMessages( $modules ) {
356 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
357 }
358
359 /**
360 * Copy items from the OutputPage object into this one
361 *
362 * @param $out OutputPage object
363 */
364 public function addOutputPageMetadata( OutputPage $out ) {
365 $this->addModules( $out->getModules() );
366 $this->addModuleScripts( $out->getModuleScripts() );
367 $this->addModuleStyles( $out->getModuleStyles() );
368 $this->addModuleMessages( $out->getModuleMessages() );
369
370 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
371 }
372
373 /**
374 * Override the title to be used for display
375 * -- this is assumed to have been validated
376 * (check equal normalisation, etc.)
377 *
378 * @param $text String: desired title text
379 */
380 public function setDisplayTitle( $text ) {
381 $this->setTitleText( $text );
382 $this->setProperty( 'displaytitle', $text );
383 }
384
385 /**
386 * Get the title to be used for display
387 *
388 * @return String
389 */
390 public function getDisplayTitle() {
391 $t = $this->getTitleText();
392 if( $t === '' ) {
393 return false;
394 }
395 return $t;
396 }
397
398 /**
399 * Fairly generic flag setter thingy.
400 */
401 public function setFlag( $flag ) {
402 $this->mFlags[$flag] = true;
403 }
404
405 public function getFlag( $flag ) {
406 return isset( $this->mFlags[$flag] );
407 }
408
409 /**
410 * Set a property to be cached in the DB
411 */
412 public function setProperty( $name, $value ) {
413 $this->mProperties[$name] = $value;
414 }
415
416 public function getProperty( $name ){
417 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
418 }
419
420 public function getProperties() {
421 if ( !isset( $this->mProperties ) ) {
422 $this->mProperties = array();
423 }
424 return $this->mProperties;
425 }
426
427
428 /**
429 * Returns the options from its ParserOptions which have been taken
430 * into account to produce this output or false if not available.
431 * @return mixed Array
432 */
433 public function getUsedOptions() {
434 if ( !isset( $this->mAccessedOptions ) ) {
435 return array();
436 }
437 return array_keys( $this->mAccessedOptions );
438 }
439
440 /**
441 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
442 * @access private
443 */
444 function recordOption( $option ) {
445 $this->mAccessedOptions[$option] = true;
446 }
447 }