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