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