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