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