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