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