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