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