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