Reverted r111188: backport conflict fodder
[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 * @return int|mixed|null
64 */
65 function getCacheExpiry() {
66 global $wgParserCacheExpireTime;
67
68 if ( $this->mCacheTime < 0 ) {
69 return 0;
70 } // old-style marker for "not cachable"
71
72 $expire = $this->mCacheExpiry;
73
74 if ( $expire === null ) {
75 $expire = $wgParserCacheExpireTime;
76 } else {
77 $expire = min( $expire, $wgParserCacheExpireTime );
78 }
79
80 if( $this->containsOldMagic() ) { //compatibility hack
81 $expire = min( $expire, 3600 ); # 1 hour
82 }
83
84 if ( $expire <= 0 ) {
85 return 0; // not cachable
86 } else {
87 return $expire;
88 }
89 }
90
91 /**
92 * @return bool
93 */
94 function isCacheable() {
95 return $this->getCacheExpiry() > 0;
96 }
97
98 /**
99 * Return true if this cached output object predates the global or
100 * per-article cache invalidation timestamps, or if it comes from
101 * an incompatible older version.
102 *
103 * @param $touched String: the affected article's last touched timestamp
104 * @return Boolean
105 */
106 public function expired( $touched ) {
107 global $wgCacheEpoch;
108 return !$this->isCacheable() || // parser says it's uncacheable
109 $this->getCacheTime() < $touched ||
110 $this->getCacheTime() <= $wgCacheEpoch ||
111 $this->getCacheTime() < wfTimestamp( TS_MW, time() - $this->getCacheExpiry() ) || // expiry period has passed
112 !isset( $this->mVersion ) ||
113 version_compare( $this->mVersion, Parser::VERSION, "lt" );
114 }
115 }
116
117 class ParserOutput extends CacheTime {
118 var $mText, # The output text
119 $mLanguageLinks, # List of the full text of language links, in the order they appear
120 $mCategories, # Map of category names to sort keys
121 $mTitleText, # title text of the chosen language variant
122 $mLinks = array(), # 2-D map of NS/DBK to ID for the links in the document. ID=zero for broken.
123 $mTemplates = array(), # 2-D map of NS/DBK to ID for the template references. ID=zero for broken.
124 $mTemplateIds = array(), # 2-D map of NS/DBK to rev ID for the template references. ID=zero for broken.
125 $mImages = array(), # DB keys of the images used, in the array key only
126 $mFileSearchOptions = array(), # DB keys of the images used mapped to sha1 and MW timestamp
127 $mExternalLinks = array(), # External link URLs, in the key only
128 $mInterwikiLinks = array(), # 2-D map of prefix/DBK (in keys only) for the inline interwiki links in the document.
129 $mNewSection = false, # Show a new section link?
130 $mHideNewSection = false, # Hide the new section link?
131 $mNoGallery = false, # No gallery on category page? (__NOGALLERY__)
132 $mHeadItems = array(), # Items to put in the <head> section
133 $mModules = array(), # Modules to be loaded by the resource loader
134 $mModuleScripts = array(), # Modules of which only the JS will be loaded by the resource loader
135 $mModuleStyles = array(), # Modules of which only the CSSS will be loaded by the resource loader
136 $mModuleMessages = array(), # Modules of which only the messages will be loaded by the resource loader
137 $mOutputHooks = array(), # Hook tags as per $wgParserOutputHooks
138 $mWarnings = array(), # Warning text to be returned to the user. Wikitext formatted, in the key only
139 $mSections = array(), # Table of contents
140 $mEditSectionTokens = false, # prefix/suffix markers if edit sections were output as tokens
141 $mProperties = array(), # Name/value pairs to be cached in the DB
142 $mTOCHTML = '', # HTML of the TOC
143 $mTimestamp; # Timestamp of the revision
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 preg_replace( ParserOutput::EDITSECTION_REGEX, '', $this->mText );
165 }
166
167 /**
168 * callback used by getText to replace editsection tokens
169 * @private
170 * @return mixed
171 */
172 function replaceEditSectionLinksCallback( $m ) {
173 global $wgOut, $wgLang;
174 $args = array(
175 htmlspecialchars_decode($m[1]),
176 htmlspecialchars_decode($m[2]),
177 isset($m[4]) ? $m[3] : null,
178 );
179 $args[0] = Title::newFromText( $args[0] );
180 if ( !is_object($args[0]) ) {
181 throw new MWException("Bad parser output text.");
182 }
183 $args[] = $wgLang->getCode();
184 $skin = $wgOut->getSkin();
185 return call_user_func_array( array( $skin, 'doEditSectionLink' ), $args );
186 }
187
188 function &getLanguageLinks() { return $this->mLanguageLinks; }
189 function getInterwikiLinks() { return $this->mInterwikiLinks; }
190 function getCategoryLinks() { return array_keys( $this->mCategories ); }
191 function &getCategories() { return $this->mCategories; }
192 function getTitleText() { return $this->mTitleText; }
193 function getSections() { return $this->mSections; }
194 function getEditSectionTokens() { return $this->mEditSectionTokens; }
195 function &getLinks() { return $this->mLinks; }
196 function &getTemplates() { return $this->mTemplates; }
197 function &getTemplateIds() { return $this->mTemplateIds; }
198 function &getImages() { return $this->mImages; }
199 function &getFileSearchOptions() { return $this->mFileSearchOptions; }
200 function &getExternalLinks() { return $this->mExternalLinks; }
201 function getNoGallery() { return $this->mNoGallery; }
202 function getHeadItems() { return $this->mHeadItems; }
203 function getModules() { return $this->mModules; }
204 function getModuleScripts() { return $this->mModuleScripts; }
205 function getModuleStyles() { return $this->mModuleStyles; }
206 function getModuleMessages() { return $this->mModuleMessages; }
207 function getOutputHooks() { return (array)$this->mOutputHooks; }
208 function getWarnings() { return array_keys( $this->mWarnings ); }
209 function getIndexPolicy() { return $this->mIndexPolicy; }
210 function getTOCHTML() { return $this->mTOCHTML; }
211 function getTimestamp() { return $this->mTimestamp; }
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 function setTimestamp( $timestamp ) { return wfSetVar( $this->mTimestamp, $timestamp ); }
223
224 function addCategory( $c, $sort ) { $this->mCategories[$c] = $sort; }
225 function addLanguageLink( $t ) { $this->mLanguageLinks[] = $t; }
226 function addWarning( $s ) { $this->mWarnings[$s] = 1; }
227
228 function addOutputHook( $hook, $data = false ) {
229 $this->mOutputHooks[] = array( $hook, $data );
230 }
231
232 function setNewSection( $value ) {
233 $this->mNewSection = (bool)$value;
234 }
235 function hideNewSection ( $value ) {
236 $this->mHideNewSection = (bool)$value;
237 }
238 function getHideNewSection () {
239 return (bool)$this->mHideNewSection;
240 }
241 function getNewSection() {
242 return (bool)$this->mNewSection;
243 }
244
245 function addExternalLink( $url ) {
246 # We don't register links pointing to our own server, unless... :-)
247 global $wgServer, $wgRegisterInternalExternals;
248 if( $wgRegisterInternalExternals or stripos($url,$wgServer.'/')!==0)
249 $this->mExternalLinks[$url] = 1;
250 }
251
252 /**
253 * Record a local or interwiki inline link for saving in future link tables.
254 *
255 * @param $title Title object
256 * @param $id Mixed: optional known page_id so we can skip the lookup
257 */
258 function addLink( $title, $id = null ) {
259 if ( $title->isExternal() ) {
260 // Don't record interwikis in pagelinks
261 $this->addInterwikiLink( $title );
262 return;
263 }
264 $ns = $title->getNamespace();
265 $dbk = $title->getDBkey();
266 if ( $ns == NS_MEDIA ) {
267 // Normalize this pseudo-alias if it makes it down here...
268 $ns = NS_FILE;
269 } elseif( $ns == NS_SPECIAL ) {
270 // We don't record Special: links currently
271 // It might actually be wise to, but we'd need to do some normalization.
272 return;
273 } elseif( $dbk === '' ) {
274 // Don't record self links - [[#Foo]]
275 return;
276 }
277 if ( !isset( $this->mLinks[$ns] ) ) {
278 $this->mLinks[$ns] = array();
279 }
280 if ( is_null( $id ) ) {
281 $id = $title->getArticleID();
282 }
283 $this->mLinks[$ns][$dbk] = $id;
284 }
285
286 /**
287 * Register a file dependency for this output
288 * @param $name string Title dbKey
289 * @param $timestamp string MW timestamp of file creation (or false if non-existing)
290 * @param $sha1 string base 36 SHA-1 of file (or false if non-existing)
291 * @return void
292 */
293 function addImage( $name, $timestamp = null, $sha1 = null ) {
294 $this->mImages[$name] = 1;
295 if ( $timestamp !== null && $sha1 !== null ) {
296 $this->mFileSearchOptions[$name] = array( 'time' => $timestamp, 'sha1' => $sha1 );
297 }
298 }
299
300 /**
301 * Register a template dependency for this output
302 * @param $title Title
303 * @param $page_id
304 * @param $rev_id
305 * @return void
306 */
307 function addTemplate( $title, $page_id, $rev_id ) {
308 $ns = $title->getNamespace();
309 $dbk = $title->getDBkey();
310 if ( !isset( $this->mTemplates[$ns] ) ) {
311 $this->mTemplates[$ns] = array();
312 }
313 $this->mTemplates[$ns][$dbk] = $page_id;
314 if ( !isset( $this->mTemplateIds[$ns] ) ) {
315 $this->mTemplateIds[$ns] = array();
316 }
317 $this->mTemplateIds[$ns][$dbk] = $rev_id; // For versioning
318 }
319
320 /**
321 * @param $title Title object, must be an interwiki link
322 * @throws MWException if given invalid input
323 */
324 function addInterwikiLink( $title ) {
325 $prefix = $title->getInterwiki();
326 if( $prefix == '' ) {
327 throw new MWException( 'Non-interwiki link passed, internal parser error.' );
328 }
329 if (!isset($this->mInterwikiLinks[$prefix])) {
330 $this->mInterwikiLinks[$prefix] = array();
331 }
332 $this->mInterwikiLinks[$prefix][$title->getDBkey()] = 1;
333 }
334
335 /**
336 * Add some text to the <head>.
337 * If $tag is set, the section with that tag will only be included once
338 * in a given page.
339 */
340 function addHeadItem( $section, $tag = false ) {
341 if ( $tag !== false ) {
342 $this->mHeadItems[$tag] = $section;
343 } else {
344 $this->mHeadItems[] = $section;
345 }
346 }
347
348 public function addModules( $modules ) {
349 $this->mModules = array_merge( $this->mModules, (array) $modules );
350 }
351
352 public function addModuleScripts( $modules ) {
353 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
354 }
355
356 public function addModuleStyles( $modules ) {
357 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
358 }
359
360 public function addModuleMessages( $modules ) {
361 $this->mModuleMessages = array_merge( $this->mModuleMessages, (array)$modules );
362 }
363
364 /**
365 * Copy items from the OutputPage object into this one
366 *
367 * @param $out OutputPage object
368 */
369 public function addOutputPageMetadata( OutputPage $out ) {
370 $this->addModules( $out->getModules() );
371 $this->addModuleScripts( $out->getModuleScripts() );
372 $this->addModuleStyles( $out->getModuleStyles() );
373 $this->addModuleMessages( $out->getModuleMessages() );
374
375 $this->mHeadItems = array_merge( $this->mHeadItems, $out->getHeadItemsArray() );
376 }
377
378 /**
379 * Override the title to be used for display
380 * -- this is assumed to have been validated
381 * (check equal normalisation, etc.)
382 *
383 * @param $text String: desired title text
384 */
385 public function setDisplayTitle( $text ) {
386 $this->setTitleText( $text );
387 $this->setProperty( 'displaytitle', $text );
388 }
389
390 /**
391 * Get the title to be used for display
392 *
393 * @return String
394 */
395 public function getDisplayTitle() {
396 $t = $this->getTitleText();
397 if( $t === '' ) {
398 return false;
399 }
400 return $t;
401 }
402
403 /**
404 * Fairly generic flag setter thingy.
405 */
406 public function setFlag( $flag ) {
407 $this->mFlags[$flag] = true;
408 }
409
410 public function getFlag( $flag ) {
411 return isset( $this->mFlags[$flag] );
412 }
413
414 /**
415 * Set a property to be cached in the DB
416 */
417 public function setProperty( $name, $value ) {
418 $this->mProperties[$name] = $value;
419 }
420
421 public function getProperty( $name ){
422 return isset( $this->mProperties[$name] ) ? $this->mProperties[$name] : false;
423 }
424
425 public function getProperties() {
426 if ( !isset( $this->mProperties ) ) {
427 $this->mProperties = array();
428 }
429 return $this->mProperties;
430 }
431
432
433 /**
434 * Returns the options from its ParserOptions which have been taken
435 * into account to produce this output or false if not available.
436 * @return mixed Array
437 */
438 public function getUsedOptions() {
439 if ( !isset( $this->mAccessedOptions ) ) {
440 return array();
441 }
442 return array_keys( $this->mAccessedOptions );
443 }
444
445 /**
446 * Callback passed by the Parser to the ParserOptions to keep track of which options are used.
447 * @access private
448 */
449 function recordOption( $option ) {
450 $this->mAccessedOptions[$option] = true;
451 }
452 }