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