* Fixed handling of whitespace before HTML comments, slightly broken since r29292.
[lhc/web/wiklou.git] / includes / Parser.php
1 <?php
2
3 /**
4 *
5 * File for Parser and related classes
6 *
7 * @addtogroup Parser
8 */
9
10
11 /**
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
16 *
17 * <pre>
18 * There are four main entry points into the Parser class:
19 * parse()
20 * produces HTML output
21 * preSaveTransform().
22 * produces altered wiki markup.
23 * transformMsg()
24 * performs brace substitution on MediaWiki messages
25 * preprocess()
26 * removes HTML comments and expands templates
27 *
28 * Globals used:
29 * objects: $wgLang, $wgContLang
30 *
31 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
32 *
33 * settings:
34 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
35 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
36 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
37 * $wgMaxArticleSize*
38 *
39 * * only within ParserOptions
40 * </pre>
41 *
42 * @addtogroup Parser
43 */
44 class Parser
45 {
46 /**
47 * Update this version number when the ParserOutput format
48 * changes in an incompatible way, so the parser cache
49 * can automatically discard old data.
50 */
51 const VERSION = '1.6.4';
52
53 # Flags for Parser::setFunctionHook
54 # Also available as global constants from Defines.php
55 const SFH_NO_HASH = 1;
56 const SFH_OBJECT_ARGS = 2;
57
58 # Constants needed for external link processing
59 # Everything except bracket, space, or control characters
60 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
61 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
62 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
63
64 // State constants for the definition list colon extraction
65 const COLON_STATE_TEXT = 0;
66 const COLON_STATE_TAG = 1;
67 const COLON_STATE_TAGSTART = 2;
68 const COLON_STATE_CLOSETAG = 3;
69 const COLON_STATE_TAGSLASH = 4;
70 const COLON_STATE_COMMENT = 5;
71 const COLON_STATE_COMMENTDASH = 6;
72 const COLON_STATE_COMMENTDASHDASH = 7;
73
74 // Flags for preprocessToDom
75 const PTD_FOR_INCLUSION = 1;
76
77 /**#@+
78 * @private
79 */
80 # Persistent:
81 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
82 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerSuffix,
83 $mExtLinkBracketedRegex;
84
85 # Cleared with clearState():
86 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
87 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
88 var $mInterwikiLinkHolders, $mLinkHolders;
89 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
90 var $mTplExpandCache,// empty-frame expansion cache
91 $mTemplatePath; // stores an unsorted hash of all the templates already loaded
92 // in this path. Used for loop detection.
93 var $mTplRedirCache, $mTplDomCache, $mHeadings;
94
95 # Temporary
96 # These are variables reset at least once per parse regardless of $clearState
97 var $mOptions, // ParserOptions object
98 $mTitle, // Title context, used for self-link rendering and similar things
99 $mOutputType, // Output type, one of the OT_xxx constants
100 $ot, // Shortcut alias, see setOutputType()
101 $mRevisionId, // ID to display in {{REVISIONID}} tags
102 $mRevisionTimestamp, // The timestamp of the specified revision ID
103 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
104
105 /**#@-*/
106
107 /**
108 * Constructor
109 *
110 * @public
111 */
112 function __construct( $conf = array() ) {
113 $this->mTagHooks = array();
114 $this->mTransparentTagHooks = array();
115 $this->mFunctionHooks = array();
116 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
117 $this->mStripList = array( 'nowiki', 'gallery' );
118 $this->mMarkerSuffix = "-QINU\x7f";
119 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
120 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
121 $this->mFirstCall = true;
122 }
123
124 /**
125 * Do various kinds of initialisation on the first call of the parser
126 */
127 function firstCallInit() {
128 if ( !$this->mFirstCall ) {
129 return;
130 }
131
132 wfProfileIn( __METHOD__ );
133 global $wgAllowDisplayTitle, $wgAllowSlowParserFunctions;
134
135 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
136
137 # Syntax for arguments (see self::setFunctionHook):
138 # "name for lookup in localized magic words array",
139 # function callback,
140 # optional SFH_NO_HASH to omit the hash from calls (e.g. {{int:...}
141 # instead of {{#int:...}})
142 $this->setFunctionHook( 'int', array( 'CoreParserFunctions', 'intFunction' ), SFH_NO_HASH );
143 $this->setFunctionHook( 'ns', array( 'CoreParserFunctions', 'ns' ), SFH_NO_HASH );
144 $this->setFunctionHook( 'urlencode', array( 'CoreParserFunctions', 'urlencode' ), SFH_NO_HASH );
145 $this->setFunctionHook( 'lcfirst', array( 'CoreParserFunctions', 'lcfirst' ), SFH_NO_HASH );
146 $this->setFunctionHook( 'ucfirst', array( 'CoreParserFunctions', 'ucfirst' ), SFH_NO_HASH );
147 $this->setFunctionHook( 'lc', array( 'CoreParserFunctions', 'lc' ), SFH_NO_HASH );
148 $this->setFunctionHook( 'uc', array( 'CoreParserFunctions', 'uc' ), SFH_NO_HASH );
149 $this->setFunctionHook( 'localurl', array( 'CoreParserFunctions', 'localurl' ), SFH_NO_HASH );
150 $this->setFunctionHook( 'localurle', array( 'CoreParserFunctions', 'localurle' ), SFH_NO_HASH );
151 $this->setFunctionHook( 'fullurl', array( 'CoreParserFunctions', 'fullurl' ), SFH_NO_HASH );
152 $this->setFunctionHook( 'fullurle', array( 'CoreParserFunctions', 'fullurle' ), SFH_NO_HASH );
153 $this->setFunctionHook( 'formatnum', array( 'CoreParserFunctions', 'formatnum' ), SFH_NO_HASH );
154 $this->setFunctionHook( 'grammar', array( 'CoreParserFunctions', 'grammar' ), SFH_NO_HASH );
155 $this->setFunctionHook( 'plural', array( 'CoreParserFunctions', 'plural' ), SFH_NO_HASH );
156 $this->setFunctionHook( 'numberofpages', array( 'CoreParserFunctions', 'numberofpages' ), SFH_NO_HASH );
157 $this->setFunctionHook( 'numberofusers', array( 'CoreParserFunctions', 'numberofusers' ), SFH_NO_HASH );
158 $this->setFunctionHook( 'numberofarticles', array( 'CoreParserFunctions', 'numberofarticles' ), SFH_NO_HASH );
159 $this->setFunctionHook( 'numberoffiles', array( 'CoreParserFunctions', 'numberoffiles' ), SFH_NO_HASH );
160 $this->setFunctionHook( 'numberofadmins', array( 'CoreParserFunctions', 'numberofadmins' ), SFH_NO_HASH );
161 $this->setFunctionHook( 'numberofedits', array( 'CoreParserFunctions', 'numberofedits' ), SFH_NO_HASH );
162 $this->setFunctionHook( 'language', array( 'CoreParserFunctions', 'language' ), SFH_NO_HASH );
163 $this->setFunctionHook( 'padleft', array( 'CoreParserFunctions', 'padleft' ), SFH_NO_HASH );
164 $this->setFunctionHook( 'padright', array( 'CoreParserFunctions', 'padright' ), SFH_NO_HASH );
165 $this->setFunctionHook( 'anchorencode', array( 'CoreParserFunctions', 'anchorencode' ), SFH_NO_HASH );
166 $this->setFunctionHook( 'special', array( 'CoreParserFunctions', 'special' ) );
167 $this->setFunctionHook( 'defaultsort', array( 'CoreParserFunctions', 'defaultsort' ), SFH_NO_HASH );
168 $this->setFunctionHook( 'filepath', array( 'CoreParserFunctions', 'filepath' ), SFH_NO_HASH );
169
170 if ( $wgAllowDisplayTitle ) {
171 $this->setFunctionHook( 'displaytitle', array( 'CoreParserFunctions', 'displaytitle' ), SFH_NO_HASH );
172 }
173 if ( $wgAllowSlowParserFunctions ) {
174 $this->setFunctionHook( 'pagesinnamespace', array( 'CoreParserFunctions', 'pagesinnamespace' ), SFH_NO_HASH );
175 }
176
177 $this->initialiseVariables();
178 $this->mFirstCall = false;
179 wfProfileOut( __METHOD__ );
180 }
181
182 /**
183 * Clear Parser state
184 *
185 * @private
186 */
187 function clearState() {
188 wfProfileIn( __METHOD__ );
189 if ( $this->mFirstCall ) {
190 $this->firstCallInit();
191 }
192 $this->mOutput = new ParserOutput;
193 $this->mAutonumber = 0;
194 $this->mLastSection = '';
195 $this->mDTopen = false;
196 $this->mIncludeCount = array();
197 $this->mStripState = new StripState;
198 $this->mArgStack = false;
199 $this->mInPre = false;
200 $this->mInterwikiLinkHolders = array(
201 'texts' => array(),
202 'titles' => array()
203 );
204 $this->mLinkHolders = array(
205 'namespaces' => array(),
206 'dbkeys' => array(),
207 'queries' => array(),
208 'texts' => array(),
209 'titles' => array()
210 );
211 $this->mRevisionTimestamp = $this->mRevisionId = null;
212
213 /**
214 * Prefix for temporary replacement strings for the multipass parser.
215 * \x07 should never appear in input as it's disallowed in XML.
216 * Using it at the front also gives us a little extra robustness
217 * since it shouldn't match when butted up against identifier-like
218 * string constructs.
219 *
220 * Must not consist of all title characters, or else it will change
221 * the behaviour of <nowiki> in a link.
222 */
223 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
224 $this->mUniqPrefix = "\x7fUNIQ" . Parser::getRandomString();
225
226 # Clear these on every parse, bug 4549
227 $this->mTemplatePath = array();
228 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
229
230 $this->mShowToc = true;
231 $this->mForceTocPosition = false;
232 $this->mIncludeSizes = array(
233 'post-expand' => 0,
234 'arg' => 0,
235 );
236 $this->mPPNodeCount = 0;
237 $this->mDefaultSort = false;
238 $this->mHeadings = array();
239
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__ );
242 }
243
244 function setOutputType( $ot ) {
245 $this->mOutputType = $ot;
246 // Shortcut alias
247 $this->ot = array(
248 'html' => $ot == OT_HTML,
249 'wiki' => $ot == OT_WIKI,
250 'msg' => $ot == OT_MSG,
251 'pre' => $ot == OT_PREPROCESS,
252 );
253 }
254
255 /**
256 * Accessor for mUniqPrefix.
257 *
258 * @public
259 */
260 function uniqPrefix() {
261 if( !isset( $this->mUniqPrefix ) ) {
262 // @fixme this is probably *horribly wrong*
263 // LanguageConverter seems to want $wgParser's uniqPrefix, however
264 // if this is called for a parser cache hit, the parser may not
265 // have ever been initialized in the first place.
266 // Not really sure what the heck is supposed to be going on here.
267 return '';
268 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
269 }
270 return $this->mUniqPrefix;
271 }
272
273 /**
274 * Convert wikitext to HTML
275 * Do not call this function recursively.
276 *
277 * @param string $text Text we want to parse
278 * @param Title &$title A title object
279 * @param array $options
280 * @param boolean $linestart
281 * @param boolean $clearState
282 * @param int $revid number to pass in {{REVISIONID}}
283 * @return ParserOutput a ParserOutput
284 */
285 public function parse( $text, &$title, $options, $linestart = true, $clearState = true, $revid = null ) {
286 /**
287 * First pass--just handle <nowiki> sections, pass the rest off
288 * to internalParse() which does all the real work.
289 */
290
291 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
292 $fname = 'Parser::parse-' . wfGetCaller();
293 wfProfileIn( __METHOD__ );
294 wfProfileIn( $fname );
295
296 if ( $clearState ) {
297 $this->clearState();
298 }
299
300 $this->mOptions = $options;
301 $this->mTitle =& $title;
302 $oldRevisionId = $this->mRevisionId;
303 $oldRevisionTimestamp = $this->mRevisionTimestamp;
304 if( $revid !== null ) {
305 $this->mRevisionId = $revid;
306 $this->mRevisionTimestamp = null;
307 }
308 $this->setOutputType( OT_HTML );
309 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
310 # No more strip!
311 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
312 $text = $this->internalParse( $text );
313 $text = $this->mStripState->unstripGeneral( $text );
314
315 # Clean up special characters, only run once, next-to-last before doBlockLevels
316 $fixtags = array(
317 # french spaces, last one Guillemet-left
318 # only if there is something before the space
319 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1&nbsp;\\2',
320 # french spaces, Guillemet-right
321 '/(\\302\\253) /' => '\\1&nbsp;',
322 );
323 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
324
325 # only once and last
326 $text = $this->doBlockLevels( $text, $linestart );
327
328 $this->replaceLinkHolders( $text );
329
330 # the position of the parserConvert() call should not be changed. it
331 # assumes that the links are all replaced and the only thing left
332 # is the <nowiki> mark.
333 # Side-effects: this calls $this->mOutput->setTitleText()
334 $text = $wgContLang->parserConvert( $text, $this );
335
336 $text = $this->mStripState->unstripNoWiki( $text );
337
338 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
339
340 //!JF Move to its own function
341
342 $uniq_prefix = $this->mUniqPrefix;
343 $matches = array();
344 $elements = array_keys( $this->mTransparentTagHooks );
345 $text = Parser::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
346
347 foreach( $matches as $marker => $data ) {
348 list( $element, $content, $params, $tag ) = $data;
349 $tagName = strtolower( $element );
350 if( isset( $this->mTransparentTagHooks[$tagName] ) ) {
351 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName],
352 array( $content, $params, $this ) );
353 } else {
354 $output = $tag;
355 }
356 $this->mStripState->general->setPair( $marker, $output );
357 }
358 $text = $this->mStripState->unstripGeneral( $text );
359
360 $text = Sanitizer::normalizeCharReferences( $text );
361
362 if (($wgUseTidy and $this->mOptions->mTidy) or $wgAlwaysUseTidy) {
363 $text = Parser::tidy($text);
364 } else {
365 # attempt to sanitize at least some nesting problems
366 # (bug #2702 and quite a few others)
367 $tidyregs = array(
368 # ''Something [http://www.cool.com cool''] -->
369 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
370 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
371 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
372 # fix up an anchor inside another anchor, only
373 # at least for a single single nested link (bug 3695)
374 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
375 '\\1\\2</a>\\3</a>\\1\\4</a>',
376 # fix div inside inline elements- doBlockLevels won't wrap a line which
377 # contains a div, so fix it up here; replace
378 # div with escaped text
379 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
380 '\\1\\3&lt;div\\5&gt;\\6&lt;/div&gt;\\8\\9',
381 # remove empty italic or bold tag pairs, some
382 # introduced by rules above
383 '/<([bi])><\/\\1>/' => '',
384 );
385
386 $text = preg_replace(
387 array_keys( $tidyregs ),
388 array_values( $tidyregs ),
389 $text );
390 }
391
392 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
393
394 # Information on include size limits, for the benefit of users who try to skirt them
395 if ( $this->mOptions->getEnableLimitReport() ) {
396 $max = $this->mOptions->getMaxIncludeSize();
397 $limitReport =
398 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
399 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
400 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n";
401 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
402 $text .= "\n<!-- \n$limitReport-->\n";
403 }
404 $this->mOutput->setText( $text );
405 $this->mRevisionId = $oldRevisionId;
406 $this->mRevisionTimestamp = $oldRevisionTimestamp;
407 wfProfileOut( $fname );
408 wfProfileOut( __METHOD__ );
409
410 return $this->mOutput;
411 }
412
413 /**
414 * Recursive parser entry point that can be called from an extension tag
415 * hook.
416 */
417 function recursiveTagParse( $text ) {
418 wfProfileIn( __METHOD__ );
419 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
420 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
421 $text = $this->internalParse( $text );
422 wfProfileOut( __METHOD__ );
423 return $text;
424 }
425
426 /**
427 * Expand templates and variables in the text, producing valid, static wikitext.
428 * Also removes comments.
429 */
430 function preprocess( $text, $title, $options, $revid = null ) {
431 wfProfileIn( __METHOD__ );
432 $this->clearState();
433 $this->setOutputType( OT_PREPROCESS );
434 $this->mOptions = $options;
435 $this->mTitle = $title;
436 if( $revid !== null ) {
437 $this->mRevisionId = $revid;
438 }
439 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
440 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
441 $text = $this->replaceVariables( $text );
442 if ( $this->mOptions->getRemoveComments() ) {
443 $text = Sanitizer::removeHTMLcomments( $text );
444 }
445 $text = $this->mStripState->unstripBoth( $text );
446 wfProfileOut( __METHOD__ );
447 return $text;
448 }
449
450 /**
451 * Get a random string
452 *
453 * @private
454 * @static
455 */
456 function getRandomString() {
457 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
458 }
459
460 function &getTitle() { return $this->mTitle; }
461 function getOptions() { return $this->mOptions; }
462
463 function getFunctionLang() {
464 global $wgLang, $wgContLang;
465 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
466 }
467
468 /**
469 * Replaces all occurrences of HTML-style comments and the given tags
470 * in the text with a random marker and returns teh next text. The output
471 * parameter $matches will be an associative array filled with data in
472 * the form:
473 * 'UNIQ-xxxxx' => array(
474 * 'element',
475 * 'tag content',
476 * array( 'param' => 'x' ),
477 * '<element param="x">tag content</element>' ) )
478 *
479 * @param $elements list of element names. Comments are always extracted.
480 * @param $text Source text string.
481 * @param $uniq_prefix
482 *
483 * @public
484 * @static
485 */
486 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
487 static $n = 1;
488 $stripped = '';
489 $matches = array();
490
491 $taglist = implode( '|', $elements );
492 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
493
494 while ( '' != $text ) {
495 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
496 $stripped .= $p[0];
497 if( count( $p ) < 5 ) {
498 break;
499 }
500 if( count( $p ) > 5 ) {
501 // comment
502 $element = $p[4];
503 $attributes = '';
504 $close = '';
505 $inside = $p[5];
506 } else {
507 // tag
508 $element = $p[1];
509 $attributes = $p[2];
510 $close = $p[3];
511 $inside = $p[4];
512 }
513
514 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++) . $this->mMarkerSuffix;
515 $stripped .= $marker;
516
517 if ( $close === '/>' ) {
518 // Empty element tag, <tag />
519 $content = null;
520 $text = $inside;
521 $tail = null;
522 } else {
523 if( $element == '!--' ) {
524 $end = '/(-->)/';
525 } else {
526 $end = "/(<\\/$element\\s*>)/i";
527 }
528 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
529 $content = $q[0];
530 if( count( $q ) < 3 ) {
531 # No end tag -- let it run out to the end of the text.
532 $tail = '';
533 $text = '';
534 } else {
535 $tail = $q[1];
536 $text = $q[2];
537 }
538 }
539
540 $matches[$marker] = array( $element,
541 $content,
542 Sanitizer::decodeTagAttributes( $attributes ),
543 "<$element$attributes$close$content$tail" );
544 }
545 return $stripped;
546 }
547
548 /**
549 * Get a list of strippable XML-like elements
550 */
551 function getStripList() {
552 global $wgRawHtml;
553 $elements = $this->mStripList;
554 if( $wgRawHtml ) {
555 $elements[] = 'html';
556 }
557 if( $this->mOptions->getUseTeX() ) {
558 $elements[] = 'math';
559 }
560 return $elements;
561 }
562
563 /**
564 * @deprecated use replaceVariables
565 */
566 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
567 return $text;
568 }
569
570 /**
571 * Restores pre, math, and other extensions removed by strip()
572 *
573 * always call unstripNoWiki() after this one
574 * @private
575 * @deprecated use $this->mStripState->unstrip()
576 */
577 function unstrip( $text, $state ) {
578 return $state->unstripGeneral( $text );
579 }
580
581 /**
582 * Always call this after unstrip() to preserve the order
583 *
584 * @private
585 * @deprecated use $this->mStripState->unstrip()
586 */
587 function unstripNoWiki( $text, $state ) {
588 return $state->unstripNoWiki( $text );
589 }
590
591 /**
592 * @deprecated use $this->mStripState->unstripBoth()
593 */
594 function unstripForHTML( $text ) {
595 return $this->mStripState->unstripBoth( $text );
596 }
597
598 /**
599 * Add an item to the strip state
600 * Returns the unique tag which must be inserted into the stripped text
601 * The tag will be replaced with the original text in unstrip()
602 *
603 * @private
604 */
605 function insertStripItem( $text ) {
606 static $n = 0;
607 $rnd = "{$this->mUniqPrefix}-item-$n-{$this->mMarkerSuffix}";
608 ++$n;
609 $this->mStripState->general->setPair( $rnd, $text );
610 return $rnd;
611 }
612
613 /**
614 * Interface with html tidy, used if $wgUseTidy = true.
615 * If tidy isn't able to correct the markup, the original will be
616 * returned in all its glory with a warning comment appended.
617 *
618 * Either the external tidy program or the in-process tidy extension
619 * will be used depending on availability. Override the default
620 * $wgTidyInternal setting to disable the internal if it's not working.
621 *
622 * @param string $text Hideous HTML input
623 * @return string Corrected HTML output
624 * @public
625 * @static
626 */
627 function tidy( $text ) {
628 global $wgTidyInternal;
629 $wrappedtext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'.
630 ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>'.
631 '<head><title>test</title></head><body>'.$text.'</body></html>';
632 if( $wgTidyInternal ) {
633 $correctedtext = Parser::internalTidy( $wrappedtext );
634 } else {
635 $correctedtext = Parser::externalTidy( $wrappedtext );
636 }
637 if( is_null( $correctedtext ) ) {
638 wfDebug( "Tidy error detected!\n" );
639 return $text . "\n<!-- Tidy found serious XHTML errors -->\n";
640 }
641 return $correctedtext;
642 }
643
644 /**
645 * Spawn an external HTML tidy process and get corrected markup back from it.
646 *
647 * @private
648 * @static
649 */
650 function externalTidy( $text ) {
651 global $wgTidyConf, $wgTidyBin, $wgTidyOpts;
652 $fname = 'Parser::externalTidy';
653 wfProfileIn( $fname );
654
655 $cleansource = '';
656 $opts = ' -utf8';
657
658 $descriptorspec = array(
659 0 => array('pipe', 'r'),
660 1 => array('pipe', 'w'),
661 2 => array('file', wfGetNull(), 'a')
662 );
663 $pipes = array();
664 $process = proc_open("$wgTidyBin -config $wgTidyConf $wgTidyOpts$opts", $descriptorspec, $pipes);
665 if (is_resource($process)) {
666 // Theoretically, this style of communication could cause a deadlock
667 // here. If the stdout buffer fills up, then writes to stdin could
668 // block. This doesn't appear to happen with tidy, because tidy only
669 // writes to stdout after it's finished reading from stdin. Search
670 // for tidyParseStdin and tidySaveStdout in console/tidy.c
671 fwrite($pipes[0], $text);
672 fclose($pipes[0]);
673 while (!feof($pipes[1])) {
674 $cleansource .= fgets($pipes[1], 1024);
675 }
676 fclose($pipes[1]);
677 proc_close($process);
678 }
679
680 wfProfileOut( $fname );
681
682 if( $cleansource == '' && $text != '') {
683 // Some kind of error happened, so we couldn't get the corrected text.
684 // Just give up; we'll use the source text and append a warning.
685 return null;
686 } else {
687 return $cleansource;
688 }
689 }
690
691 /**
692 * Use the HTML tidy PECL extension to use the tidy library in-process,
693 * saving the overhead of spawning a new process.
694 *
695 * 'pear install tidy' should be able to compile the extension module.
696 *
697 * @private
698 * @static
699 */
700 function internalTidy( $text ) {
701 global $wgTidyConf, $IP, $wgDebugTidy;
702 $fname = 'Parser::internalTidy';
703 wfProfileIn( $fname );
704
705 $tidy = new tidy;
706 $tidy->parseString( $text, $wgTidyConf, 'utf8' );
707 $tidy->cleanRepair();
708 if( $tidy->getStatus() == 2 ) {
709 // 2 is magic number for fatal error
710 // http://www.php.net/manual/en/function.tidy-get-status.php
711 $cleansource = null;
712 } else {
713 $cleansource = tidy_get_output( $tidy );
714 }
715 if ( $wgDebugTidy && $tidy->getStatus() > 0 ) {
716 $cleansource .= "<!--\nTidy reports:\n" .
717 str_replace( '-->', '--&gt;', $tidy->errorBuffer ) .
718 "\n-->";
719 }
720
721 wfProfileOut( $fname );
722 return $cleansource;
723 }
724
725 /**
726 * parse the wiki syntax used to render tables
727 *
728 * @private
729 */
730 function doTableStuff ( $text ) {
731 $fname = 'Parser::doTableStuff';
732 wfProfileIn( $fname );
733
734 $lines = explode ( "\n" , $text );
735 $td_history = array (); // Is currently a td tag open?
736 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
737 $tr_history = array (); // Is currently a tr tag open?
738 $tr_attributes = array (); // history of tr attributes
739 $has_opened_tr = array(); // Did this table open a <tr> element?
740 $indent_level = 0; // indent level of the table
741 foreach ( $lines as $key => $line )
742 {
743 $line = trim ( $line );
744
745 if( $line == '' ) { // empty line, go to next line
746 continue;
747 }
748 $first_character = $line{0};
749 $matches = array();
750
751 if ( preg_match( '/^(:*)\{\|(.*)$/' , $line , $matches ) ) {
752 // First check if we are starting a new table
753 $indent_level = strlen( $matches[1] );
754
755 $attributes = $this->mStripState->unstripBoth( $matches[2] );
756 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'table' );
757
758 $lines[$key] = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
759 array_push ( $td_history , false );
760 array_push ( $last_tag_history , '' );
761 array_push ( $tr_history , false );
762 array_push ( $tr_attributes , '' );
763 array_push ( $has_opened_tr , false );
764 } else if ( count ( $td_history ) == 0 ) {
765 // Don't do any of the following
766 continue;
767 } else if ( substr ( $line , 0 , 2 ) == '|}' ) {
768 // We are ending a table
769 $line = '</table>' . substr ( $line , 2 );
770 $last_tag = array_pop ( $last_tag_history );
771
772 if ( !array_pop ( $has_opened_tr ) ) {
773 $line = "<tr><td></td></tr>{$line}";
774 }
775
776 if ( array_pop ( $tr_history ) ) {
777 $line = "</tr>{$line}";
778 }
779
780 if ( array_pop ( $td_history ) ) {
781 $line = "</{$last_tag}>{$line}";
782 }
783 array_pop ( $tr_attributes );
784 $lines[$key] = $line . str_repeat( '</dd></dl>' , $indent_level );
785 } else if ( substr ( $line , 0 , 2 ) == '|-' ) {
786 // Now we have a table row
787 $line = preg_replace( '#^\|-+#', '', $line );
788
789 // Whats after the tag is now only attributes
790 $attributes = $this->mStripState->unstripBoth( $line );
791 $attributes = Sanitizer::fixTagAttributes ( $attributes , 'tr' );
792 array_pop ( $tr_attributes );
793 array_push ( $tr_attributes , $attributes );
794
795 $line = '';
796 $last_tag = array_pop ( $last_tag_history );
797 array_pop ( $has_opened_tr );
798 array_push ( $has_opened_tr , true );
799
800 if ( array_pop ( $tr_history ) ) {
801 $line = '</tr>';
802 }
803
804 if ( array_pop ( $td_history ) ) {
805 $line = "</{$last_tag}>{$line}";
806 }
807
808 $lines[$key] = $line;
809 array_push ( $tr_history , false );
810 array_push ( $td_history , false );
811 array_push ( $last_tag_history , '' );
812 }
813 else if ( $first_character == '|' || $first_character == '!' || substr ( $line , 0 , 2 ) == '|+' ) {
814 // This might be cell elements, td, th or captions
815 if ( substr ( $line , 0 , 2 ) == '|+' ) {
816 $first_character = '+';
817 $line = substr ( $line , 1 );
818 }
819
820 $line = substr ( $line , 1 );
821
822 if ( $first_character == '!' ) {
823 $line = str_replace ( '!!' , '||' , $line );
824 }
825
826 // Split up multiple cells on the same line.
827 // FIXME : This can result in improper nesting of tags processed
828 // by earlier parser steps, but should avoid splitting up eg
829 // attribute values containing literal "||".
830 $cells = StringUtils::explodeMarkup( '||' , $line );
831
832 $lines[$key] = '';
833
834 // Loop through each table cell
835 foreach ( $cells as $cell )
836 {
837 $previous = '';
838 if ( $first_character != '+' )
839 {
840 $tr_after = array_pop ( $tr_attributes );
841 if ( !array_pop ( $tr_history ) ) {
842 $previous = "<tr{$tr_after}>\n";
843 }
844 array_push ( $tr_history , true );
845 array_push ( $tr_attributes , '' );
846 array_pop ( $has_opened_tr );
847 array_push ( $has_opened_tr , true );
848 }
849
850 $last_tag = array_pop ( $last_tag_history );
851
852 if ( array_pop ( $td_history ) ) {
853 $previous = "</{$last_tag}>{$previous}";
854 }
855
856 if ( $first_character == '|' ) {
857 $last_tag = 'td';
858 } else if ( $first_character == '!' ) {
859 $last_tag = 'th';
860 } else if ( $first_character == '+' ) {
861 $last_tag = 'caption';
862 } else {
863 $last_tag = '';
864 }
865
866 array_push ( $last_tag_history , $last_tag );
867
868 // A cell could contain both parameters and data
869 $cell_data = explode ( '|' , $cell , 2 );
870
871 // Bug 553: Note that a '|' inside an invalid link should not
872 // be mistaken as delimiting cell parameters
873 if ( strpos( $cell_data[0], '[[' ) !== false ) {
874 $cell = "{$previous}<{$last_tag}>{$cell}";
875 } else if ( count ( $cell_data ) == 1 )
876 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
877 else {
878 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
879 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
880 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
881 }
882
883 $lines[$key] .= $cell;
884 array_push ( $td_history , true );
885 }
886 }
887 }
888
889 // Closing open td, tr && table
890 while ( count ( $td_history ) > 0 )
891 {
892 if ( array_pop ( $td_history ) ) {
893 $lines[] = '</td>' ;
894 }
895 if ( array_pop ( $tr_history ) ) {
896 $lines[] = '</tr>' ;
897 }
898 if ( !array_pop ( $has_opened_tr ) ) {
899 $lines[] = "<tr><td></td></tr>" ;
900 }
901
902 $lines[] = '</table>' ;
903 }
904
905 $output = implode ( "\n" , $lines ) ;
906
907 // special case: don't return empty table
908 if( $output == "<table>\n<tr><td></td></tr>\n</table>" ) {
909 $output = '';
910 }
911
912 wfProfileOut( $fname );
913
914 return $output;
915 }
916
917 /**
918 * Helper function for parse() that transforms wiki markup into
919 * HTML. Only called for $mOutputType == OT_HTML.
920 *
921 * @private
922 */
923 function internalParse( $text ) {
924 $isMain = true;
925 $fname = 'Parser::internalParse';
926 wfProfileIn( $fname );
927
928 # Hook to suspend the parser in this state
929 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
930 wfProfileOut( $fname );
931 return $text ;
932 }
933
934 $text = $this->replaceVariables( $text );
935 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
936 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
937
938 // Tables need to come after variable replacement for things to work
939 // properly; putting them before other transformations should keep
940 // exciting things like link expansions from showing up in surprising
941 // places.
942 $text = $this->doTableStuff( $text );
943
944 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
945
946 $text = $this->stripToc( $text );
947 $this->stripNoGallery( $text );
948 $text = $this->doHeadings( $text );
949 if($this->mOptions->getUseDynamicDates()) {
950 $df =& DateFormatter::getInstance();
951 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
952 }
953 $text = $this->doAllQuotes( $text );
954 $text = $this->replaceInternalLinks( $text );
955 $text = $this->replaceExternalLinks( $text );
956
957 # replaceInternalLinks may sometimes leave behind
958 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
959 $text = str_replace($this->mUniqPrefix."NOPARSE", "", $text);
960
961 $text = $this->doMagicLinks( $text );
962 $text = $this->formatHeadings( $text, $isMain );
963
964 wfProfileOut( $fname );
965 return $text;
966 }
967
968 /**
969 * Replace special strings like "ISBN xxx" and "RFC xxx" with
970 * magic external links.
971 *
972 * @private
973 */
974 function doMagicLinks( $text ) {
975 wfProfileIn( __METHOD__ );
976 $text = preg_replace_callback(
977 '!(?: # Start cases
978 <a.*?</a> | # Skip link text
979 <.*?> | # Skip stuff inside HTML elements
980 (?:RFC|PMID)\s+([0-9]+) | # RFC or PMID, capture number as m[1]
981 ISBN\s+(\b # ISBN, capture number as m[2]
982 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
983 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
984 [0-9Xx] # check digit
985 \b)
986 )!x', array( &$this, 'magicLinkCallback' ), $text );
987 wfProfileOut( __METHOD__ );
988 return $text;
989 }
990
991 function magicLinkCallback( $m ) {
992 if ( substr( $m[0], 0, 1 ) == '<' ) {
993 # Skip HTML element
994 return $m[0];
995 } elseif ( substr( $m[0], 0, 4 ) == 'ISBN' ) {
996 $isbn = $m[2];
997 $num = strtr( $isbn, array(
998 '-' => '',
999 ' ' => '',
1000 'x' => 'X',
1001 ));
1002 $titleObj = SpecialPage::getTitleFor( 'Booksources' );
1003 $text = '<a href="' .
1004 $titleObj->escapeLocalUrl( "isbn=$num" ) .
1005 "\" class=\"internal\">ISBN $isbn</a>";
1006 } else {
1007 if ( substr( $m[0], 0, 3 ) == 'RFC' ) {
1008 $keyword = 'RFC';
1009 $urlmsg = 'rfcurl';
1010 $id = $m[1];
1011 } elseif ( substr( $m[0], 0, 4 ) == 'PMID' ) {
1012 $keyword = 'PMID';
1013 $urlmsg = 'pubmedurl';
1014 $id = $m[1];
1015 } else {
1016 throw new MWException( __METHOD__.': unrecognised match type "' .
1017 substr($m[0], 0, 20 ) . '"' );
1018 }
1019
1020 $url = wfMsg( $urlmsg, $id);
1021 $sk = $this->mOptions->getSkin();
1022 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
1023 $text = "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1024 }
1025 return $text;
1026 }
1027
1028 /**
1029 * Parse headers and return html
1030 *
1031 * @private
1032 */
1033 function doHeadings( $text ) {
1034 $fname = 'Parser::doHeadings';
1035 wfProfileIn( $fname );
1036 for ( $i = 6; $i >= 1; --$i ) {
1037 $h = str_repeat( '=', $i );
1038 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1039 "<h$i>\\1</h$i>", $text );
1040 }
1041 wfProfileOut( $fname );
1042 return $text;
1043 }
1044
1045 /**
1046 * Replace single quotes with HTML markup
1047 * @private
1048 * @return string the altered text
1049 */
1050 function doAllQuotes( $text ) {
1051 $fname = 'Parser::doAllQuotes';
1052 wfProfileIn( $fname );
1053 $outtext = '';
1054 $lines = explode( "\n", $text );
1055 foreach ( $lines as $line ) {
1056 $outtext .= $this->doQuotes ( $line ) . "\n";
1057 }
1058 $outtext = substr($outtext, 0,-1);
1059 wfProfileOut( $fname );
1060 return $outtext;
1061 }
1062
1063 /**
1064 * Helper function for doAllQuotes()
1065 */
1066 public function doQuotes( $text ) {
1067 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1068 if ( count( $arr ) == 1 )
1069 return $text;
1070 else
1071 {
1072 # First, do some preliminary work. This may shift some apostrophes from
1073 # being mark-up to being text. It also counts the number of occurrences
1074 # of bold and italics mark-ups.
1075 $i = 0;
1076 $numbold = 0;
1077 $numitalics = 0;
1078 foreach ( $arr as $r )
1079 {
1080 if ( ( $i % 2 ) == 1 )
1081 {
1082 # If there are ever four apostrophes, assume the first is supposed to
1083 # be text, and the remaining three constitute mark-up for bold text.
1084 if ( strlen( $arr[$i] ) == 4 )
1085 {
1086 $arr[$i-1] .= "'";
1087 $arr[$i] = "'''";
1088 }
1089 # If there are more than 5 apostrophes in a row, assume they're all
1090 # text except for the last 5.
1091 else if ( strlen( $arr[$i] ) > 5 )
1092 {
1093 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1094 $arr[$i] = "'''''";
1095 }
1096 # Count the number of occurrences of bold and italics mark-ups.
1097 # We are not counting sequences of five apostrophes.
1098 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++; }
1099 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++; }
1100 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++; $numbold++; }
1101 }
1102 $i++;
1103 }
1104
1105 # If there is an odd number of both bold and italics, it is likely
1106 # that one of the bold ones was meant to be an apostrophe followed
1107 # by italics. Which one we cannot know for certain, but it is more
1108 # likely to be one that has a single-letter word before it.
1109 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) )
1110 {
1111 $i = 0;
1112 $firstsingleletterword = -1;
1113 $firstmultiletterword = -1;
1114 $firstspace = -1;
1115 foreach ( $arr as $r )
1116 {
1117 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) )
1118 {
1119 $x1 = substr ($arr[$i-1], -1);
1120 $x2 = substr ($arr[$i-1], -2, 1);
1121 if ($x1 == ' ') {
1122 if ($firstspace == -1) $firstspace = $i;
1123 } else if ($x2 == ' ') {
1124 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1125 } else {
1126 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1127 }
1128 }
1129 $i++;
1130 }
1131
1132 # If there is a single-letter word, use it!
1133 if ($firstsingleletterword > -1)
1134 {
1135 $arr [ $firstsingleletterword ] = "''";
1136 $arr [ $firstsingleletterword-1 ] .= "'";
1137 }
1138 # If not, but there's a multi-letter word, use that one.
1139 else if ($firstmultiletterword > -1)
1140 {
1141 $arr [ $firstmultiletterword ] = "''";
1142 $arr [ $firstmultiletterword-1 ] .= "'";
1143 }
1144 # ... otherwise use the first one that has neither.
1145 # (notice that it is possible for all three to be -1 if, for example,
1146 # there is only one pentuple-apostrophe in the line)
1147 else if ($firstspace > -1)
1148 {
1149 $arr [ $firstspace ] = "''";
1150 $arr [ $firstspace-1 ] .= "'";
1151 }
1152 }
1153
1154 # Now let's actually convert our apostrophic mush to HTML!
1155 $output = '';
1156 $buffer = '';
1157 $state = '';
1158 $i = 0;
1159 foreach ($arr as $r)
1160 {
1161 if (($i % 2) == 0)
1162 {
1163 if ($state == 'both')
1164 $buffer .= $r;
1165 else
1166 $output .= $r;
1167 }
1168 else
1169 {
1170 if (strlen ($r) == 2)
1171 {
1172 if ($state == 'i')
1173 { $output .= '</i>'; $state = ''; }
1174 else if ($state == 'bi')
1175 { $output .= '</i>'; $state = 'b'; }
1176 else if ($state == 'ib')
1177 { $output .= '</b></i><b>'; $state = 'b'; }
1178 else if ($state == 'both')
1179 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1180 else # $state can be 'b' or ''
1181 { $output .= '<i>'; $state .= 'i'; }
1182 }
1183 else if (strlen ($r) == 3)
1184 {
1185 if ($state == 'b')
1186 { $output .= '</b>'; $state = ''; }
1187 else if ($state == 'bi')
1188 { $output .= '</i></b><i>'; $state = 'i'; }
1189 else if ($state == 'ib')
1190 { $output .= '</b>'; $state = 'i'; }
1191 else if ($state == 'both')
1192 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1193 else # $state can be 'i' or ''
1194 { $output .= '<b>'; $state .= 'b'; }
1195 }
1196 else if (strlen ($r) == 5)
1197 {
1198 if ($state == 'b')
1199 { $output .= '</b><i>'; $state = 'i'; }
1200 else if ($state == 'i')
1201 { $output .= '</i><b>'; $state = 'b'; }
1202 else if ($state == 'bi')
1203 { $output .= '</i></b>'; $state = ''; }
1204 else if ($state == 'ib')
1205 { $output .= '</b></i>'; $state = ''; }
1206 else if ($state == 'both')
1207 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1208 else # ($state == '')
1209 { $buffer = ''; $state = 'both'; }
1210 }
1211 }
1212 $i++;
1213 }
1214 # Now close all remaining tags. Notice that the order is important.
1215 if ($state == 'b' || $state == 'ib')
1216 $output .= '</b>';
1217 if ($state == 'i' || $state == 'bi' || $state == 'ib')
1218 $output .= '</i>';
1219 if ($state == 'bi')
1220 $output .= '</b>';
1221 # There might be lonely ''''', so make sure we have a buffer
1222 if ($state == 'both' && $buffer)
1223 $output .= '<b><i>'.$buffer.'</i></b>';
1224 return $output;
1225 }
1226 }
1227
1228 /**
1229 * Replace external links
1230 *
1231 * Note: this is all very hackish and the order of execution matters a lot.
1232 * Make sure to run maintenance/parserTests.php if you change this code.
1233 *
1234 * @private
1235 */
1236 function replaceExternalLinks( $text ) {
1237 global $wgContLang;
1238 $fname = 'Parser::replaceExternalLinks';
1239 wfProfileIn( $fname );
1240
1241 $sk = $this->mOptions->getSkin();
1242
1243 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1244
1245 $s = $this->replaceFreeExternalLinks( array_shift( $bits ) );
1246
1247 $i = 0;
1248 while ( $i<count( $bits ) ) {
1249 $url = $bits[$i++];
1250 $protocol = $bits[$i++];
1251 $text = $bits[$i++];
1252 $trail = $bits[$i++];
1253
1254 # The characters '<' and '>' (which were escaped by
1255 # removeHTMLtags()) should not be included in
1256 # URLs, per RFC 2396.
1257 $m2 = array();
1258 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1259 $text = substr($url, $m2[0][1]) . ' ' . $text;
1260 $url = substr($url, 0, $m2[0][1]);
1261 }
1262
1263 # If the link text is an image URL, replace it with an <img> tag
1264 # This happened by accident in the original parser, but some people used it extensively
1265 $img = $this->maybeMakeExternalImage( $text );
1266 if ( $img !== false ) {
1267 $text = $img;
1268 }
1269
1270 $dtrail = '';
1271
1272 # Set linktype for CSS - if URL==text, link is essentially free
1273 $linktype = ($text == $url) ? 'free' : 'text';
1274
1275 # No link text, e.g. [http://domain.tld/some.link]
1276 if ( $text == '' ) {
1277 # Autonumber if allowed. See bug #5918
1278 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1279 $text = '[' . ++$this->mAutonumber . ']';
1280 $linktype = 'autonumber';
1281 } else {
1282 # Otherwise just use the URL
1283 $text = htmlspecialchars( $url );
1284 $linktype = 'free';
1285 }
1286 } else {
1287 # Have link text, e.g. [http://domain.tld/some.link text]s
1288 # Check for trail
1289 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1290 }
1291
1292 $text = $wgContLang->markNoConversion($text);
1293
1294 $url = Sanitizer::cleanUrl( $url );
1295
1296 # Process the trail (i.e. everything after this link up until start of the next link),
1297 # replacing any non-bracketed links
1298 $trail = $this->replaceFreeExternalLinks( $trail );
1299
1300 # Use the encoded URL
1301 # This means that users can paste URLs directly into the text
1302 # Funny characters like &ouml; aren't valid in URLs anyway
1303 # This was changed in August 2004
1304 $s .= $sk->makeExternalLink( $url, $text, false, $linktype, $this->mTitle->getNamespace() ) . $dtrail . $trail;
1305
1306 # Register link in the output object.
1307 # Replace unnecessary URL escape codes with the referenced character
1308 # This prevents spammers from hiding links from the filters
1309 $pasteurized = Parser::replaceUnusualEscapes( $url );
1310 $this->mOutput->addExternalLink( $pasteurized );
1311 }
1312
1313 wfProfileOut( $fname );
1314 return $s;
1315 }
1316
1317 /**
1318 * Replace anything that looks like a URL with a link
1319 * @private
1320 */
1321 function replaceFreeExternalLinks( $text ) {
1322 global $wgContLang;
1323 $fname = 'Parser::replaceFreeExternalLinks';
1324 wfProfileIn( $fname );
1325
1326 $bits = preg_split( '/(\b(?:' . wfUrlProtocols() . '))/S', $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1327 $s = array_shift( $bits );
1328 $i = 0;
1329
1330 $sk = $this->mOptions->getSkin();
1331
1332 while ( $i < count( $bits ) ){
1333 $protocol = $bits[$i++];
1334 $remainder = $bits[$i++];
1335
1336 $m = array();
1337 if ( preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $remainder, $m ) ) {
1338 # Found some characters after the protocol that look promising
1339 $url = $protocol . $m[1];
1340 $trail = $m[2];
1341
1342 # special case: handle urls as url args:
1343 # http://www.example.com/foo?=http://www.example.com/bar
1344 if(strlen($trail) == 0 &&
1345 isset($bits[$i]) &&
1346 preg_match('/^'. wfUrlProtocols() . '$/S', $bits[$i]) &&
1347 preg_match( '/^('.self::EXT_LINK_URL_CLASS.'+)(.*)$/s', $bits[$i + 1], $m ))
1348 {
1349 # add protocol, arg
1350 $url .= $bits[$i] . $m[1]; # protocol, url as arg to previous link
1351 $i += 2;
1352 $trail = $m[2];
1353 }
1354
1355 # The characters '<' and '>' (which were escaped by
1356 # removeHTMLtags()) should not be included in
1357 # URLs, per RFC 2396.
1358 $m2 = array();
1359 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE)) {
1360 $trail = substr($url, $m2[0][1]) . $trail;
1361 $url = substr($url, 0, $m2[0][1]);
1362 }
1363
1364 # Move trailing punctuation to $trail
1365 $sep = ',;\.:!?';
1366 # If there is no left bracket, then consider right brackets fair game too
1367 if ( strpos( $url, '(' ) === false ) {
1368 $sep .= ')';
1369 }
1370
1371 $numSepChars = strspn( strrev( $url ), $sep );
1372 if ( $numSepChars ) {
1373 $trail = substr( $url, -$numSepChars ) . $trail;
1374 $url = substr( $url, 0, -$numSepChars );
1375 }
1376
1377 $url = Sanitizer::cleanUrl( $url );
1378
1379 # Is this an external image?
1380 $text = $this->maybeMakeExternalImage( $url );
1381 if ( $text === false ) {
1382 # Not an image, make a link
1383 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free', $this->mTitle->getNamespace() );
1384 # Register it in the output object...
1385 # Replace unnecessary URL escape codes with their equivalent characters
1386 $pasteurized = Parser::replaceUnusualEscapes( $url );
1387 $this->mOutput->addExternalLink( $pasteurized );
1388 }
1389 $s .= $text . $trail;
1390 } else {
1391 $s .= $protocol . $remainder;
1392 }
1393 }
1394 wfProfileOut( $fname );
1395 return $s;
1396 }
1397
1398 /**
1399 * Replace unusual URL escape codes with their equivalent characters
1400 * @param string
1401 * @return string
1402 * @static
1403 * @todo This can merge genuinely required bits in the path or query string,
1404 * breaking legit URLs. A proper fix would treat the various parts of
1405 * the URL differently; as a workaround, just use the output for
1406 * statistical records, not for actual linking/output.
1407 */
1408 static function replaceUnusualEscapes( $url ) {
1409 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1410 array( 'Parser', 'replaceUnusualEscapesCallback' ), $url );
1411 }
1412
1413 /**
1414 * Callback function used in replaceUnusualEscapes().
1415 * Replaces unusual URL escape codes with their equivalent character
1416 * @static
1417 * @private
1418 */
1419 private static function replaceUnusualEscapesCallback( $matches ) {
1420 $char = urldecode( $matches[0] );
1421 $ord = ord( $char );
1422 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1423 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1424 // No, shouldn't be escaped
1425 return $char;
1426 } else {
1427 // Yes, leave it escaped
1428 return $matches[0];
1429 }
1430 }
1431
1432 /**
1433 * make an image if it's allowed, either through the global
1434 * option or through the exception
1435 * @private
1436 */
1437 function maybeMakeExternalImage( $url ) {
1438 $sk = $this->mOptions->getSkin();
1439 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1440 $imagesexception = !empty($imagesfrom);
1441 $text = false;
1442 if ( $this->mOptions->getAllowExternalImages()
1443 || ( $imagesexception && strpos( $url, $imagesfrom ) === 0 ) ) {
1444 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1445 # Image found
1446 $text = $sk->makeExternalImage( htmlspecialchars( $url ) );
1447 }
1448 }
1449 return $text;
1450 }
1451
1452 /**
1453 * Process [[ ]] wikilinks
1454 *
1455 * @private
1456 */
1457 function replaceInternalLinks( $s ) {
1458 global $wgContLang;
1459 static $fname = 'Parser::replaceInternalLinks' ;
1460
1461 wfProfileIn( $fname );
1462
1463 wfProfileIn( $fname.'-setup' );
1464 static $tc = FALSE;
1465 # the % is needed to support urlencoded titles as well
1466 if ( !$tc ) { $tc = Title::legalChars() . '#%'; }
1467
1468 $sk = $this->mOptions->getSkin();
1469
1470 #split the entire text string on occurences of [[
1471 $a = explode( '[[', ' ' . $s );
1472 #get the first element (all text up to first [[), and remove the space we added
1473 $s = array_shift( $a );
1474 $s = substr( $s, 1 );
1475
1476 # Match a link having the form [[namespace:link|alternate]]trail
1477 static $e1 = FALSE;
1478 if ( !$e1 ) { $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD"; }
1479 # Match cases where there is no "]]", which might still be images
1480 static $e1_img = FALSE;
1481 if ( !$e1_img ) { $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD"; }
1482
1483 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1484 $e2 = null;
1485 if ( $useLinkPrefixExtension ) {
1486 # Match the end of a line for a word that's not followed by whitespace,
1487 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1488 $e2 = wfMsgForContent( 'linkprefix' );
1489 }
1490
1491 if( is_null( $this->mTitle ) ) {
1492 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1493 }
1494 $nottalk = !$this->mTitle->isTalkPage();
1495
1496 if ( $useLinkPrefixExtension ) {
1497 $m = array();
1498 if ( preg_match( $e2, $s, $m ) ) {
1499 $first_prefix = $m[2];
1500 } else {
1501 $first_prefix = false;
1502 }
1503 } else {
1504 $prefix = '';
1505 }
1506
1507 if($wgContLang->hasVariants()) {
1508 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle->getPrefixedText());
1509 } else {
1510 $selflink = array($this->mTitle->getPrefixedText());
1511 }
1512 $useSubpages = $this->areSubpagesAllowed();
1513 wfProfileOut( $fname.'-setup' );
1514
1515 # Loop for each link
1516 for ($k = 0; isset( $a[$k] ); $k++) {
1517 $line = $a[$k];
1518 if ( $useLinkPrefixExtension ) {
1519 wfProfileIn( $fname.'-prefixhandling' );
1520 if ( preg_match( $e2, $s, $m ) ) {
1521 $prefix = $m[2];
1522 $s = $m[1];
1523 } else {
1524 $prefix='';
1525 }
1526 # first link
1527 if($first_prefix) {
1528 $prefix = $first_prefix;
1529 $first_prefix = false;
1530 }
1531 wfProfileOut( $fname.'-prefixhandling' );
1532 }
1533
1534 $might_be_img = false;
1535
1536 wfProfileIn( "$fname-e1" );
1537 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1538 $text = $m[2];
1539 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1540 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1541 # the real problem is with the $e1 regex
1542 # See bug 1300.
1543 #
1544 # Still some problems for cases where the ] is meant to be outside punctuation,
1545 # and no image is in sight. See bug 2095.
1546 #
1547 if( $text !== '' &&
1548 substr( $m[3], 0, 1 ) === ']' &&
1549 strpos($text, '[') !== false
1550 )
1551 {
1552 $text .= ']'; # so that replaceExternalLinks($text) works later
1553 $m[3] = substr( $m[3], 1 );
1554 }
1555 # fix up urlencoded title texts
1556 if( strpos( $m[1], '%' ) !== false ) {
1557 # Should anchors '#' also be rejected?
1558 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]) );
1559 }
1560 $trail = $m[3];
1561 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1562 $might_be_img = true;
1563 $text = $m[2];
1564 if ( strpos( $m[1], '%' ) !== false ) {
1565 $m[1] = urldecode($m[1]);
1566 }
1567 $trail = "";
1568 } else { # Invalid form; output directly
1569 $s .= $prefix . '[[' . $line ;
1570 wfProfileOut( "$fname-e1" );
1571 continue;
1572 }
1573 wfProfileOut( "$fname-e1" );
1574 wfProfileIn( "$fname-misc" );
1575
1576 # Don't allow internal links to pages containing
1577 # PROTO: where PROTO is a valid URL protocol; these
1578 # should be external links.
1579 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1580 $s .= $prefix . '[[' . $line ;
1581 continue;
1582 }
1583
1584 # Make subpage if necessary
1585 if( $useSubpages ) {
1586 $link = $this->maybeDoSubpageLink( $m[1], $text );
1587 } else {
1588 $link = $m[1];
1589 }
1590
1591 $noforce = (substr($m[1], 0, 1) != ':');
1592 if (!$noforce) {
1593 # Strip off leading ':'
1594 $link = substr($link, 1);
1595 }
1596
1597 wfProfileOut( "$fname-misc" );
1598 wfProfileIn( "$fname-title" );
1599 $nt = Title::newFromText( $this->mStripState->unstripNoWiki($link) );
1600 if( !$nt ) {
1601 $s .= $prefix . '[[' . $line;
1602 wfProfileOut( "$fname-title" );
1603 continue;
1604 }
1605
1606 $ns = $nt->getNamespace();
1607 $iw = $nt->getInterWiki();
1608 wfProfileOut( "$fname-title" );
1609
1610 if ($might_be_img) { # if this is actually an invalid link
1611 wfProfileIn( "$fname-might_be_img" );
1612 if ($ns == NS_IMAGE && $noforce) { #but might be an image
1613 $found = false;
1614 while (isset ($a[$k+1]) ) {
1615 #look at the next 'line' to see if we can close it there
1616 $spliced = array_splice( $a, $k + 1, 1 );
1617 $next_line = array_shift( $spliced );
1618 $m = explode( ']]', $next_line, 3 );
1619 if ( count( $m ) == 3 ) {
1620 # the first ]] closes the inner link, the second the image
1621 $found = true;
1622 $text .= "[[{$m[0]}]]{$m[1]}";
1623 $trail = $m[2];
1624 break;
1625 } elseif ( count( $m ) == 2 ) {
1626 #if there's exactly one ]] that's fine, we'll keep looking
1627 $text .= "[[{$m[0]}]]{$m[1]}";
1628 } else {
1629 #if $next_line is invalid too, we need look no further
1630 $text .= '[[' . $next_line;
1631 break;
1632 }
1633 }
1634 if ( !$found ) {
1635 # we couldn't find the end of this imageLink, so output it raw
1636 #but don't ignore what might be perfectly normal links in the text we've examined
1637 $text = $this->replaceInternalLinks($text);
1638 $s .= "{$prefix}[[$link|$text";
1639 # note: no $trail, because without an end, there *is* no trail
1640 wfProfileOut( "$fname-might_be_img" );
1641 continue;
1642 }
1643 } else { #it's not an image, so output it raw
1644 $s .= "{$prefix}[[$link|$text";
1645 # note: no $trail, because without an end, there *is* no trail
1646 wfProfileOut( "$fname-might_be_img" );
1647 continue;
1648 }
1649 wfProfileOut( "$fname-might_be_img" );
1650 }
1651
1652 $wasblank = ( '' == $text );
1653 if( $wasblank ) $text = $link;
1654
1655 # Link not escaped by : , create the various objects
1656 if( $noforce ) {
1657
1658 # Interwikis
1659 wfProfileIn( "$fname-interwiki" );
1660 if( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1661 $this->mOutput->addLanguageLink( $nt->getFullText() );
1662 $s = rtrim($s . $prefix);
1663 $s .= trim($trail, "\n") == '' ? '': $prefix . $trail;
1664 wfProfileOut( "$fname-interwiki" );
1665 continue;
1666 }
1667 wfProfileOut( "$fname-interwiki" );
1668
1669 if ( $ns == NS_IMAGE ) {
1670 wfProfileIn( "$fname-image" );
1671 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1672 # recursively parse links inside the image caption
1673 # actually, this will parse them in any other parameters, too,
1674 # but it might be hard to fix that, and it doesn't matter ATM
1675 $text = $this->replaceExternalLinks($text);
1676 $text = $this->replaceInternalLinks($text);
1677
1678 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1679 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text ) ) . $trail;
1680 $this->mOutput->addImage( $nt->getDBkey() );
1681
1682 wfProfileOut( "$fname-image" );
1683 continue;
1684 } else {
1685 # We still need to record the image's presence on the page
1686 $this->mOutput->addImage( $nt->getDBkey() );
1687 }
1688 wfProfileOut( "$fname-image" );
1689
1690 }
1691
1692 if ( $ns == NS_CATEGORY ) {
1693 wfProfileIn( "$fname-category" );
1694 $s = rtrim($s . "\n"); # bug 87
1695
1696 if ( $wasblank ) {
1697 $sortkey = $this->getDefaultSort();
1698 } else {
1699 $sortkey = $text;
1700 }
1701 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1702 $sortkey = str_replace( "\n", '', $sortkey );
1703 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1704 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1705
1706 /**
1707 * Strip the whitespace Category links produce, see bug 87
1708 * @todo We might want to use trim($tmp, "\n") here.
1709 */
1710 $s .= trim($prefix . $trail, "\n") == '' ? '': $prefix . $trail;
1711
1712 wfProfileOut( "$fname-category" );
1713 continue;
1714 }
1715 }
1716
1717 # Self-link checking
1718 if( $nt->getFragment() === '' ) {
1719 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1720 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1721 continue;
1722 }
1723 }
1724
1725 # Special and Media are pseudo-namespaces; no pages actually exist in them
1726 if( $ns == NS_MEDIA ) {
1727 $link = $sk->makeMediaLinkObj( $nt, $text );
1728 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1729 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1730 $this->mOutput->addImage( $nt->getDBkey() );
1731 continue;
1732 } elseif( $ns == NS_SPECIAL ) {
1733 if( SpecialPage::exists( $nt->getDBkey() ) ) {
1734 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1735 } else {
1736 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1737 }
1738 continue;
1739 } elseif( $ns == NS_IMAGE ) {
1740 $img = wfFindFile( $nt );
1741 if( $img ) {
1742 // Force a blue link if the file exists; may be a remote
1743 // upload on the shared repository, and we want to see its
1744 // auto-generated page.
1745 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1746 $this->mOutput->addLink( $nt );
1747 continue;
1748 }
1749 }
1750 $s .= $this->makeLinkHolder( $nt, $text, '', $trail, $prefix );
1751 }
1752 wfProfileOut( $fname );
1753 return $s;
1754 }
1755
1756 /**
1757 * Make a link placeholder. The text returned can be later resolved to a real link with
1758 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1759 * parsing of interwiki links, and secondly to allow all existence checks and
1760 * article length checks (for stub links) to be bundled into a single query.
1761 *
1762 */
1763 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1764 wfProfileIn( __METHOD__ );
1765 if ( ! is_object($nt) ) {
1766 # Fail gracefully
1767 $retVal = "<!-- ERROR -->{$prefix}{$text}{$trail}";
1768 } else {
1769 # Separate the link trail from the rest of the link
1770 list( $inside, $trail ) = Linker::splitTrail( $trail );
1771
1772 if ( $nt->isExternal() ) {
1773 $nr = array_push( $this->mInterwikiLinkHolders['texts'], $prefix.$text.$inside );
1774 $this->mInterwikiLinkHolders['titles'][] = $nt;
1775 $retVal = '<!--IWLINK '. ($nr-1) ."-->{$trail}";
1776 } else {
1777 $nr = array_push( $this->mLinkHolders['namespaces'], $nt->getNamespace() );
1778 $this->mLinkHolders['dbkeys'][] = $nt->getDBkey();
1779 $this->mLinkHolders['queries'][] = $query;
1780 $this->mLinkHolders['texts'][] = $prefix.$text.$inside;
1781 $this->mLinkHolders['titles'][] = $nt;
1782
1783 $retVal = '<!--LINK '. ($nr-1) ."-->{$trail}";
1784 }
1785 }
1786 wfProfileOut( __METHOD__ );
1787 return $retVal;
1788 }
1789
1790 /**
1791 * Render a forced-blue link inline; protect against double expansion of
1792 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1793 * Since this little disaster has to split off the trail text to avoid
1794 * breaking URLs in the following text without breaking trails on the
1795 * wiki links, it's been made into a horrible function.
1796 *
1797 * @param Title $nt
1798 * @param string $text
1799 * @param string $query
1800 * @param string $trail
1801 * @param string $prefix
1802 * @return string HTML-wikitext mix oh yuck
1803 */
1804 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1805 list( $inside, $trail ) = Linker::splitTrail( $trail );
1806 $sk = $this->mOptions->getSkin();
1807 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1808 return $this->armorLinks( $link ) . $trail;
1809 }
1810
1811 /**
1812 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1813 * going to go through further parsing steps before inline URL expansion.
1814 *
1815 * In particular this is important when using action=render, which causes
1816 * full URLs to be included.
1817 *
1818 * Oh man I hate our multi-layer parser!
1819 *
1820 * @param string more-or-less HTML
1821 * @return string less-or-more HTML with NOPARSE bits
1822 */
1823 function armorLinks( $text ) {
1824 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1825 "{$this->mUniqPrefix}NOPARSE$1", $text );
1826 }
1827
1828 /**
1829 * Return true if subpage links should be expanded on this page.
1830 * @return bool
1831 */
1832 function areSubpagesAllowed() {
1833 # Some namespaces don't allow subpages
1834 global $wgNamespacesWithSubpages;
1835 return !empty($wgNamespacesWithSubpages[$this->mTitle->getNamespace()]);
1836 }
1837
1838 /**
1839 * Handle link to subpage if necessary
1840 * @param string $target the source of the link
1841 * @param string &$text the link text, modified as necessary
1842 * @return string the full name of the link
1843 * @private
1844 */
1845 function maybeDoSubpageLink($target, &$text) {
1846 # Valid link forms:
1847 # Foobar -- normal
1848 # :Foobar -- override special treatment of prefix (images, language links)
1849 # /Foobar -- convert to CurrentPage/Foobar
1850 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1851 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1852 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1853
1854 $fname = 'Parser::maybeDoSubpageLink';
1855 wfProfileIn( $fname );
1856 $ret = $target; # default return value is no change
1857
1858 # Some namespaces don't allow subpages,
1859 # so only perform processing if subpages are allowed
1860 if( $this->areSubpagesAllowed() ) {
1861 $hash = strpos( $target, '#' );
1862 if( $hash !== false ) {
1863 $suffix = substr( $target, $hash );
1864 $target = substr( $target, 0, $hash );
1865 } else {
1866 $suffix = '';
1867 }
1868 # bug 7425
1869 $target = trim( $target );
1870 # Look at the first character
1871 if( $target != '' && $target{0} == '/' ) {
1872 # / at end means we don't want the slash to be shown
1873 $m = array();
1874 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1875 if( $trailingSlashes ) {
1876 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1877 } else {
1878 $noslash = substr( $target, 1 );
1879 }
1880
1881 $ret = $this->mTitle->getPrefixedText(). '/' . trim($noslash) . $suffix;
1882 if( '' === $text ) {
1883 $text = $target . $suffix;
1884 } # this might be changed for ugliness reasons
1885 } else {
1886 # check for .. subpage backlinks
1887 $dotdotcount = 0;
1888 $nodotdot = $target;
1889 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1890 ++$dotdotcount;
1891 $nodotdot = substr( $nodotdot, 3 );
1892 }
1893 if($dotdotcount > 0) {
1894 $exploded = explode( '/', $this->mTitle->GetPrefixedText() );
1895 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1896 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1897 # / at the end means don't show full path
1898 if( substr( $nodotdot, -1, 1 ) == '/' ) {
1899 $nodotdot = substr( $nodotdot, 0, -1 );
1900 if( '' === $text ) {
1901 $text = $nodotdot . $suffix;
1902 }
1903 }
1904 $nodotdot = trim( $nodotdot );
1905 if( $nodotdot != '' ) {
1906 $ret .= '/' . $nodotdot;
1907 }
1908 $ret .= $suffix;
1909 }
1910 }
1911 }
1912 }
1913
1914 wfProfileOut( $fname );
1915 return $ret;
1916 }
1917
1918 /**#@+
1919 * Used by doBlockLevels()
1920 * @private
1921 */
1922 /* private */ function closeParagraph() {
1923 $result = '';
1924 if ( '' != $this->mLastSection ) {
1925 $result = '</' . $this->mLastSection . ">\n";
1926 }
1927 $this->mInPre = false;
1928 $this->mLastSection = '';
1929 return $result;
1930 }
1931 # getCommon() returns the length of the longest common substring
1932 # of both arguments, starting at the beginning of both.
1933 #
1934 /* private */ function getCommon( $st1, $st2 ) {
1935 $fl = strlen( $st1 );
1936 $shorter = strlen( $st2 );
1937 if ( $fl < $shorter ) { $shorter = $fl; }
1938
1939 for ( $i = 0; $i < $shorter; ++$i ) {
1940 if ( $st1{$i} != $st2{$i} ) { break; }
1941 }
1942 return $i;
1943 }
1944 # These next three functions open, continue, and close the list
1945 # element appropriate to the prefix character passed into them.
1946 #
1947 /* private */ function openList( $char ) {
1948 $result = $this->closeParagraph();
1949
1950 if ( '*' == $char ) { $result .= '<ul><li>'; }
1951 else if ( '#' == $char ) { $result .= '<ol><li>'; }
1952 else if ( ':' == $char ) { $result .= '<dl><dd>'; }
1953 else if ( ';' == $char ) {
1954 $result .= '<dl><dt>';
1955 $this->mDTopen = true;
1956 }
1957 else { $result = '<!-- ERR 1 -->'; }
1958
1959 return $result;
1960 }
1961
1962 /* private */ function nextItem( $char ) {
1963 if ( '*' == $char || '#' == $char ) { return '</li><li>'; }
1964 else if ( ':' == $char || ';' == $char ) {
1965 $close = '</dd>';
1966 if ( $this->mDTopen ) { $close = '</dt>'; }
1967 if ( ';' == $char ) {
1968 $this->mDTopen = true;
1969 return $close . '<dt>';
1970 } else {
1971 $this->mDTopen = false;
1972 return $close . '<dd>';
1973 }
1974 }
1975 return '<!-- ERR 2 -->';
1976 }
1977
1978 /* private */ function closeList( $char ) {
1979 if ( '*' == $char ) { $text = '</li></ul>'; }
1980 else if ( '#' == $char ) { $text = '</li></ol>'; }
1981 else if ( ':' == $char ) {
1982 if ( $this->mDTopen ) {
1983 $this->mDTopen = false;
1984 $text = '</dt></dl>';
1985 } else {
1986 $text = '</dd></dl>';
1987 }
1988 }
1989 else { return '<!-- ERR 3 -->'; }
1990 return $text."\n";
1991 }
1992 /**#@-*/
1993
1994 /**
1995 * Make lists from lines starting with ':', '*', '#', etc.
1996 *
1997 * @private
1998 * @return string the lists rendered as HTML
1999 */
2000 function doBlockLevels( $text, $linestart ) {
2001 $fname = 'Parser::doBlockLevels';
2002 wfProfileIn( $fname );
2003
2004 # Parsing through the text line by line. The main thing
2005 # happening here is handling of block-level elements p, pre,
2006 # and making lists from lines starting with * # : etc.
2007 #
2008 $textLines = explode( "\n", $text );
2009
2010 $lastPrefix = $output = '';
2011 $this->mDTopen = $inBlockElem = false;
2012 $prefixLength = 0;
2013 $paragraphStack = false;
2014
2015 if ( !$linestart ) {
2016 $output .= array_shift( $textLines );
2017 }
2018 foreach ( $textLines as $oLine ) {
2019 $lastPrefixLength = strlen( $lastPrefix );
2020 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2021 $preOpenMatch = preg_match('/<pre/i', $oLine );
2022 if ( !$this->mInPre ) {
2023 # Multiple prefixes may abut each other for nested lists.
2024 $prefixLength = strspn( $oLine, '*#:;' );
2025 $pref = substr( $oLine, 0, $prefixLength );
2026
2027 # eh?
2028 $pref2 = str_replace( ';', ':', $pref );
2029 $t = substr( $oLine, $prefixLength );
2030 $this->mInPre = !empty($preOpenMatch);
2031 } else {
2032 # Don't interpret any other prefixes in preformatted text
2033 $prefixLength = 0;
2034 $pref = $pref2 = '';
2035 $t = $oLine;
2036 }
2037
2038 # List generation
2039 if( $prefixLength && 0 == strcmp( $lastPrefix, $pref2 ) ) {
2040 # Same as the last item, so no need to deal with nesting or opening stuff
2041 $output .= $this->nextItem( substr( $pref, -1 ) );
2042 $paragraphStack = false;
2043
2044 if ( substr( $pref, -1 ) == ';') {
2045 # The one nasty exception: definition lists work like this:
2046 # ; title : definition text
2047 # So we check for : in the remainder text to split up the
2048 # title and definition, without b0rking links.
2049 $term = $t2 = '';
2050 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2051 $t = $t2;
2052 $output .= $term . $this->nextItem( ':' );
2053 }
2054 }
2055 } elseif( $prefixLength || $lastPrefixLength ) {
2056 # Either open or close a level...
2057 $commonPrefixLength = $this->getCommon( $pref, $lastPrefix );
2058 $paragraphStack = false;
2059
2060 while( $commonPrefixLength < $lastPrefixLength ) {
2061 $output .= $this->closeList( $lastPrefix{$lastPrefixLength-1} );
2062 --$lastPrefixLength;
2063 }
2064 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2065 $output .= $this->nextItem( $pref{$commonPrefixLength-1} );
2066 }
2067 while ( $prefixLength > $commonPrefixLength ) {
2068 $char = substr( $pref, $commonPrefixLength, 1 );
2069 $output .= $this->openList( $char );
2070
2071 if ( ';' == $char ) {
2072 # FIXME: This is dupe of code above
2073 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2074 $t = $t2;
2075 $output .= $term . $this->nextItem( ':' );
2076 }
2077 }
2078 ++$commonPrefixLength;
2079 }
2080 $lastPrefix = $pref2;
2081 }
2082 if( 0 == $prefixLength ) {
2083 wfProfileIn( "$fname-paragraph" );
2084 # No prefix (not in list)--go to paragraph mode
2085 // XXX: use a stack for nestable elements like span, table and div
2086 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2087 $closematch = preg_match(
2088 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2089 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2090 if ( $openmatch or $closematch ) {
2091 $paragraphStack = false;
2092 # TODO bug 5718: paragraph closed
2093 $output .= $this->closeParagraph();
2094 if ( $preOpenMatch and !$preCloseMatch ) {
2095 $this->mInPre = true;
2096 }
2097 if ( $closematch ) {
2098 $inBlockElem = false;
2099 } else {
2100 $inBlockElem = true;
2101 }
2102 } else if ( !$inBlockElem && !$this->mInPre ) {
2103 if ( ' ' == $t{0} and ( $this->mLastSection == 'pre' or trim($t) != '' ) ) {
2104 // pre
2105 if ($this->mLastSection != 'pre') {
2106 $paragraphStack = false;
2107 $output .= $this->closeParagraph().'<pre>';
2108 $this->mLastSection = 'pre';
2109 }
2110 $t = substr( $t, 1 );
2111 } else {
2112 // paragraph
2113 if ( '' == trim($t) ) {
2114 if ( $paragraphStack ) {
2115 $output .= $paragraphStack.'<br />';
2116 $paragraphStack = false;
2117 $this->mLastSection = 'p';
2118 } else {
2119 if ($this->mLastSection != 'p' ) {
2120 $output .= $this->closeParagraph();
2121 $this->mLastSection = '';
2122 $paragraphStack = '<p>';
2123 } else {
2124 $paragraphStack = '</p><p>';
2125 }
2126 }
2127 } else {
2128 if ( $paragraphStack ) {
2129 $output .= $paragraphStack;
2130 $paragraphStack = false;
2131 $this->mLastSection = 'p';
2132 } else if ($this->mLastSection != 'p') {
2133 $output .= $this->closeParagraph().'<p>';
2134 $this->mLastSection = 'p';
2135 }
2136 }
2137 }
2138 }
2139 wfProfileOut( "$fname-paragraph" );
2140 }
2141 // somewhere above we forget to get out of pre block (bug 785)
2142 if($preCloseMatch && $this->mInPre) {
2143 $this->mInPre = false;
2144 }
2145 if ($paragraphStack === false) {
2146 $output .= $t."\n";
2147 }
2148 }
2149 while ( $prefixLength ) {
2150 $output .= $this->closeList( $pref2{$prefixLength-1} );
2151 --$prefixLength;
2152 }
2153 if ( '' != $this->mLastSection ) {
2154 $output .= '</' . $this->mLastSection . '>';
2155 $this->mLastSection = '';
2156 }
2157
2158 wfProfileOut( $fname );
2159 return $output;
2160 }
2161
2162 /**
2163 * Split up a string on ':', ignoring any occurences inside tags
2164 * to prevent illegal overlapping.
2165 * @param string $str the string to split
2166 * @param string &$before set to everything before the ':'
2167 * @param string &$after set to everything after the ':'
2168 * return string the position of the ':', or false if none found
2169 */
2170 function findColonNoLinks($str, &$before, &$after) {
2171 $fname = 'Parser::findColonNoLinks';
2172 wfProfileIn( $fname );
2173
2174 $pos = strpos( $str, ':' );
2175 if( $pos === false ) {
2176 // Nothing to find!
2177 wfProfileOut( $fname );
2178 return false;
2179 }
2180
2181 $lt = strpos( $str, '<' );
2182 if( $lt === false || $lt > $pos ) {
2183 // Easy; no tag nesting to worry about
2184 $before = substr( $str, 0, $pos );
2185 $after = substr( $str, $pos+1 );
2186 wfProfileOut( $fname );
2187 return $pos;
2188 }
2189
2190 // Ugly state machine to walk through avoiding tags.
2191 $state = self::COLON_STATE_TEXT;
2192 $stack = 0;
2193 $len = strlen( $str );
2194 for( $i = 0; $i < $len; $i++ ) {
2195 $c = $str{$i};
2196
2197 switch( $state ) {
2198 // (Using the number is a performance hack for common cases)
2199 case 0: // self::COLON_STATE_TEXT:
2200 switch( $c ) {
2201 case "<":
2202 // Could be either a <start> tag or an </end> tag
2203 $state = self::COLON_STATE_TAGSTART;
2204 break;
2205 case ":":
2206 if( $stack == 0 ) {
2207 // We found it!
2208 $before = substr( $str, 0, $i );
2209 $after = substr( $str, $i + 1 );
2210 wfProfileOut( $fname );
2211 return $i;
2212 }
2213 // Embedded in a tag; don't break it.
2214 break;
2215 default:
2216 // Skip ahead looking for something interesting
2217 $colon = strpos( $str, ':', $i );
2218 if( $colon === false ) {
2219 // Nothing else interesting
2220 wfProfileOut( $fname );
2221 return false;
2222 }
2223 $lt = strpos( $str, '<', $i );
2224 if( $stack === 0 ) {
2225 if( $lt === false || $colon < $lt ) {
2226 // We found it!
2227 $before = substr( $str, 0, $colon );
2228 $after = substr( $str, $colon + 1 );
2229 wfProfileOut( $fname );
2230 return $i;
2231 }
2232 }
2233 if( $lt === false ) {
2234 // Nothing else interesting to find; abort!
2235 // We're nested, but there's no close tags left. Abort!
2236 break 2;
2237 }
2238 // Skip ahead to next tag start
2239 $i = $lt;
2240 $state = self::COLON_STATE_TAGSTART;
2241 }
2242 break;
2243 case 1: // self::COLON_STATE_TAG:
2244 // In a <tag>
2245 switch( $c ) {
2246 case ">":
2247 $stack++;
2248 $state = self::COLON_STATE_TEXT;
2249 break;
2250 case "/":
2251 // Slash may be followed by >?
2252 $state = self::COLON_STATE_TAGSLASH;
2253 break;
2254 default:
2255 // ignore
2256 }
2257 break;
2258 case 2: // self::COLON_STATE_TAGSTART:
2259 switch( $c ) {
2260 case "/":
2261 $state = self::COLON_STATE_CLOSETAG;
2262 break;
2263 case "!":
2264 $state = self::COLON_STATE_COMMENT;
2265 break;
2266 case ">":
2267 // Illegal early close? This shouldn't happen D:
2268 $state = self::COLON_STATE_TEXT;
2269 break;
2270 default:
2271 $state = self::COLON_STATE_TAG;
2272 }
2273 break;
2274 case 3: // self::COLON_STATE_CLOSETAG:
2275 // In a </tag>
2276 if( $c == ">" ) {
2277 $stack--;
2278 if( $stack < 0 ) {
2279 wfDebug( "Invalid input in $fname; too many close tags\n" );
2280 wfProfileOut( $fname );
2281 return false;
2282 }
2283 $state = self::COLON_STATE_TEXT;
2284 }
2285 break;
2286 case self::COLON_STATE_TAGSLASH:
2287 if( $c == ">" ) {
2288 // Yes, a self-closed tag <blah/>
2289 $state = self::COLON_STATE_TEXT;
2290 } else {
2291 // Probably we're jumping the gun, and this is an attribute
2292 $state = self::COLON_STATE_TAG;
2293 }
2294 break;
2295 case 5: // self::COLON_STATE_COMMENT:
2296 if( $c == "-" ) {
2297 $state = self::COLON_STATE_COMMENTDASH;
2298 }
2299 break;
2300 case self::COLON_STATE_COMMENTDASH:
2301 if( $c == "-" ) {
2302 $state = self::COLON_STATE_COMMENTDASHDASH;
2303 } else {
2304 $state = self::COLON_STATE_COMMENT;
2305 }
2306 break;
2307 case self::COLON_STATE_COMMENTDASHDASH:
2308 if( $c == ">" ) {
2309 $state = self::COLON_STATE_TEXT;
2310 } else {
2311 $state = self::COLON_STATE_COMMENT;
2312 }
2313 break;
2314 default:
2315 throw new MWException( "State machine error in $fname" );
2316 }
2317 }
2318 if( $stack > 0 ) {
2319 wfDebug( "Invalid input in $fname; not enough close tags (stack $stack, state $state)\n" );
2320 return false;
2321 }
2322 wfProfileOut( $fname );
2323 return false;
2324 }
2325
2326 /**
2327 * Return value of a magic variable (like PAGENAME)
2328 *
2329 * @private
2330 */
2331 function getVariableValue( $index ) {
2332 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2333
2334 /**
2335 * Some of these require message or data lookups and can be
2336 * expensive to check many times.
2337 */
2338 static $varCache = array();
2339 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$varCache ) ) ) {
2340 if ( isset( $varCache[$index] ) ) {
2341 return $varCache[$index];
2342 }
2343 }
2344
2345 $ts = time();
2346 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2347
2348 # Use the time zone
2349 global $wgLocaltimezone;
2350 if ( isset( $wgLocaltimezone ) ) {
2351 $oldtz = getenv( 'TZ' );
2352 putenv( 'TZ='.$wgLocaltimezone );
2353 }
2354
2355 wfSuppressWarnings(); // E_STRICT system time bitching
2356 $localTimestamp = date( 'YmdHis', $ts );
2357 $localMonth = date( 'm', $ts );
2358 $localMonthName = date( 'n', $ts );
2359 $localDay = date( 'j', $ts );
2360 $localDay2 = date( 'd', $ts );
2361 $localDayOfWeek = date( 'w', $ts );
2362 $localWeek = date( 'W', $ts );
2363 $localYear = date( 'Y', $ts );
2364 $localHour = date( 'H', $ts );
2365 if ( isset( $wgLocaltimezone ) ) {
2366 putenv( 'TZ='.$oldtz );
2367 }
2368 wfRestoreWarnings();
2369
2370 switch ( $index ) {
2371 case 'currentmonth':
2372 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2373 case 'currentmonthname':
2374 return $varCache[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2375 case 'currentmonthnamegen':
2376 return $varCache[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2377 case 'currentmonthabbrev':
2378 return $varCache[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2379 case 'currentday':
2380 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2381 case 'currentday2':
2382 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2383 case 'localmonth':
2384 return $varCache[$index] = $wgContLang->formatNum( $localMonth );
2385 case 'localmonthname':
2386 return $varCache[$index] = $wgContLang->getMonthName( $localMonthName );
2387 case 'localmonthnamegen':
2388 return $varCache[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2389 case 'localmonthabbrev':
2390 return $varCache[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2391 case 'localday':
2392 return $varCache[$index] = $wgContLang->formatNum( $localDay );
2393 case 'localday2':
2394 return $varCache[$index] = $wgContLang->formatNum( $localDay2 );
2395 case 'pagename':
2396 return wfEscapeWikiText( $this->mTitle->getText() );
2397 case 'pagenamee':
2398 return $this->mTitle->getPartialURL();
2399 case 'fullpagename':
2400 return wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2401 case 'fullpagenamee':
2402 return $this->mTitle->getPrefixedURL();
2403 case 'subpagename':
2404 return wfEscapeWikiText( $this->mTitle->getSubpageText() );
2405 case 'subpagenamee':
2406 return $this->mTitle->getSubpageUrlForm();
2407 case 'basepagename':
2408 return wfEscapeWikiText( $this->mTitle->getBaseText() );
2409 case 'basepagenamee':
2410 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2411 case 'talkpagename':
2412 if( $this->mTitle->canTalk() ) {
2413 $talkPage = $this->mTitle->getTalkPage();
2414 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2415 } else {
2416 return '';
2417 }
2418 case 'talkpagenamee':
2419 if( $this->mTitle->canTalk() ) {
2420 $talkPage = $this->mTitle->getTalkPage();
2421 return $talkPage->getPrefixedUrl();
2422 } else {
2423 return '';
2424 }
2425 case 'subjectpagename':
2426 $subjPage = $this->mTitle->getSubjectPage();
2427 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2428 case 'subjectpagenamee':
2429 $subjPage = $this->mTitle->getSubjectPage();
2430 return $subjPage->getPrefixedUrl();
2431 case 'revisionid':
2432 // Let the edit saving system know we should parse the page
2433 // *after* a revision ID has been assigned.
2434 $this->mOutput->setFlag( 'vary-revision' );
2435 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2436 return $this->mRevisionId;
2437 case 'revisionday':
2438 // Let the edit saving system know we should parse the page
2439 // *after* a revision ID has been assigned. This is for null edits.
2440 $this->mOutput->setFlag( 'vary-revision' );
2441 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2442 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2443 case 'revisionday2':
2444 // Let the edit saving system know we should parse the page
2445 // *after* a revision ID has been assigned. This is for null edits.
2446 $this->mOutput->setFlag( 'vary-revision' );
2447 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2448 return substr( $this->getRevisionTimestamp(), 6, 2 );
2449 case 'revisionmonth':
2450 // Let the edit saving system know we should parse the page
2451 // *after* a revision ID has been assigned. This is for null edits.
2452 $this->mOutput->setFlag( 'vary-revision' );
2453 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2454 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2455 case 'revisionyear':
2456 // Let the edit saving system know we should parse the page
2457 // *after* a revision ID has been assigned. This is for null edits.
2458 $this->mOutput->setFlag( 'vary-revision' );
2459 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2460 return substr( $this->getRevisionTimestamp(), 0, 4 );
2461 case 'revisiontimestamp':
2462 // Let the edit saving system know we should parse the page
2463 // *after* a revision ID has been assigned. This is for null edits.
2464 $this->mOutput->setFlag( 'vary-revision' );
2465 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2466 return $this->getRevisionTimestamp();
2467 case 'namespace':
2468 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2469 case 'namespacee':
2470 return wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2471 case 'talkspace':
2472 return $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '';
2473 case 'talkspacee':
2474 return $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2475 case 'subjectspace':
2476 return $this->mTitle->getSubjectNsText();
2477 case 'subjectspacee':
2478 return( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2479 case 'currentdayname':
2480 return $varCache[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2481 case 'currentyear':
2482 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2483 case 'currenttime':
2484 return $varCache[$index] = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2485 case 'currenthour':
2486 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2487 case 'currentweek':
2488 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2489 // int to remove the padding
2490 return $varCache[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2491 case 'currentdow':
2492 return $varCache[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2493 case 'localdayname':
2494 return $varCache[$index] = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2495 case 'localyear':
2496 return $varCache[$index] = $wgContLang->formatNum( $localYear, true );
2497 case 'localtime':
2498 return $varCache[$index] = $wgContLang->time( $localTimestamp, false, false );
2499 case 'localhour':
2500 return $varCache[$index] = $wgContLang->formatNum( $localHour, true );
2501 case 'localweek':
2502 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2503 // int to remove the padding
2504 return $varCache[$index] = $wgContLang->formatNum( (int)$localWeek );
2505 case 'localdow':
2506 return $varCache[$index] = $wgContLang->formatNum( $localDayOfWeek );
2507 case 'numberofarticles':
2508 return $varCache[$index] = $wgContLang->formatNum( SiteStats::articles() );
2509 case 'numberoffiles':
2510 return $varCache[$index] = $wgContLang->formatNum( SiteStats::images() );
2511 case 'numberofusers':
2512 return $varCache[$index] = $wgContLang->formatNum( SiteStats::users() );
2513 case 'numberofpages':
2514 return $varCache[$index] = $wgContLang->formatNum( SiteStats::pages() );
2515 case 'numberofadmins':
2516 return $varCache[$index] = $wgContLang->formatNum( SiteStats::admins() );
2517 case 'numberofedits':
2518 return $varCache[$index] = $wgContLang->formatNum( SiteStats::edits() );
2519 case 'currenttimestamp':
2520 return $varCache[$index] = wfTimestampNow();
2521 case 'localtimestamp':
2522 return $varCache[$index] = $localTimestamp;
2523 case 'currentversion':
2524 return $varCache[$index] = SpecialVersion::getVersion();
2525 case 'sitename':
2526 return $wgSitename;
2527 case 'server':
2528 return $wgServer;
2529 case 'servername':
2530 return $wgServerName;
2531 case 'scriptpath':
2532 return $wgScriptPath;
2533 case 'directionmark':
2534 return $wgContLang->getDirMark();
2535 case 'contentlanguage':
2536 global $wgContLanguageCode;
2537 return $wgContLanguageCode;
2538 default:
2539 $ret = null;
2540 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$varCache, &$index, &$ret ) ) )
2541 return $ret;
2542 else
2543 return null;
2544 }
2545 }
2546
2547 /**
2548 * initialise the magic variables (like CURRENTMONTHNAME)
2549 *
2550 * @private
2551 */
2552 function initialiseVariables() {
2553 $fname = 'Parser::initialiseVariables';
2554 wfProfileIn( $fname );
2555 $variableIDs = MagicWord::getVariableIDs();
2556
2557 $this->mVariables = new MagicWordArray( $variableIDs );
2558 wfProfileOut( $fname );
2559 }
2560
2561 /**
2562 * Preprocess some wikitext and return the document tree.
2563 * This is the ghost of replace_variables().
2564 *
2565 * @param string $text The text to parse
2566 * @param integer flags Bitwise combination of:
2567 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2568 * included. Default is to assume a direct page view.
2569 *
2570 * The generated DOM tree must depend only on the input text, the flags, and $this->ot['msg'].
2571 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2572 *
2573 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2574 * change in the DOM tree for a given text, must be passed through the section identifier
2575 * in the section edit link and thus back to extractSections().
2576 *
2577 * The output of this function is currently only cached in process memory, but a persistent
2578 * cache may be implemented at a later date which takes further advantage of these strict
2579 * dependency requirements.
2580 *
2581 * @private
2582 */
2583 function preprocessToDom ( $text, $flags = 0 ) {
2584 wfProfileIn( __METHOD__ );
2585 wfProfileIn( __METHOD__.'-makexml' );
2586
2587 static $msgRules, $normalRules, $inclusionSupertags, $nonInclusionSupertags;
2588 if ( !$msgRules ) {
2589 $msgRules = array(
2590 '{' => array(
2591 'end' => '}',
2592 'names' => array(
2593 2 => 'template',
2594 ),
2595 'min' => 2,
2596 'max' => 2,
2597 ),
2598 '[' => array(
2599 'end' => ']',
2600 'names' => array( 2 => null ),
2601 'min' => 2,
2602 'max' => 2,
2603 )
2604 );
2605 $normalRules = array(
2606 '{' => array(
2607 'end' => '}',
2608 'names' => array(
2609 2 => 'template',
2610 3 => 'tplarg',
2611 ),
2612 'min' => 2,
2613 'max' => 3,
2614 ),
2615 '[' => array(
2616 'end' => ']',
2617 'names' => array( 2 => null ),
2618 'min' => 2,
2619 'max' => 2,
2620 )
2621 );
2622 }
2623 if ( $this->ot['msg'] ) {
2624 $rules = $msgRules;
2625 } else {
2626 $rules = $normalRules;
2627 }
2628 $forInclusion = $flags & self::PTD_FOR_INCLUSION;
2629
2630 $xmlishElements = $this->getStripList();
2631 $enableOnlyinclude = false;
2632 if ( $forInclusion ) {
2633 $ignoredTags = array( 'includeonly', '/includeonly' );
2634 $ignoredElements = array( 'noinclude' );
2635 $xmlishElements[] = 'noinclude';
2636 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
2637 $enableOnlyinclude = true;
2638 }
2639 } else {
2640 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
2641 $ignoredElements = array( 'includeonly' );
2642 $xmlishElements[] = 'includeonly';
2643 }
2644 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
2645
2646 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
2647 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
2648
2649 $stack = array(); # Stack of unclosed parentheses
2650 $stackIndex = -1; # Stack read pointer
2651
2652 $searchBase = implode( '', array_keys( $rules ) ) . '<';
2653 $revText = strrev( $text ); // For fast reverse searches
2654
2655 $i = -1; # Input pointer, starts out pointing to a pseudo-newline before the start
2656 $topAccum = '<root>'; # Top level text accumulator
2657 $accum =& $topAccum; # Current text accumulator
2658 $findEquals = false; # True to find equals signs in arguments
2659 $findHeading = false; # True to look at LF characters for possible headings
2660 $findPipe = false; # True to take notice of pipe characters
2661 $headingIndex = 1;
2662 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
2663 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
2664
2665 if ( $enableOnlyinclude ) {
2666 $i = 0;
2667 }
2668
2669 while ( true ) {
2670 if ( $findOnlyinclude ) {
2671 // Ignore all input up to the next <onlyinclude>
2672 $startPos = strpos( $text, '<onlyinclude>', $i );
2673 if ( $startPos === false ) {
2674 // Ignored section runs to the end
2675 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i ) ) . '</ignore>';
2676 break;
2677 }
2678 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
2679 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i ) ) . '</ignore>';
2680 $i = $tagEndPos;
2681 $findOnlyinclude = false;
2682 }
2683
2684 if ( $i == -1 ) {
2685 $found = 'line-start';
2686 $curChar = '';
2687 } else {
2688 # Find next opening brace, closing brace or pipe
2689 $search = $searchBase;
2690 if ( $stackIndex == -1 ) {
2691 $currentClosing = '';
2692 // Look for headings only at the top stack level
2693 // Among other things, this resolves the ambiguity between =
2694 // for headings and = for template arguments
2695 $search .= "\n";
2696 } else {
2697 $currentClosing = $stack[$stackIndex]['close'];
2698 $search .= $currentClosing;
2699 }
2700 if ( $findPipe ) {
2701 $search .= '|';
2702 }
2703 if ( $findEquals ) {
2704 $search .= '=';
2705 }
2706 $rule = null;
2707 # Output literal section, advance input counter
2708 $literalLength = strcspn( $text, $search, $i );
2709 if ( $literalLength > 0 ) {
2710 $accum .= htmlspecialchars( substr( $text, $i, $literalLength ) );
2711 $i += $literalLength;
2712 }
2713 if ( $i >= strlen( $text ) ) {
2714 if ( $currentClosing == "\n" ) {
2715 // Do a past-the-end run to finish off the heading
2716 $curChar = '';
2717 $found = 'line-end';
2718 } else {
2719 # All done
2720 break;
2721 }
2722 } else {
2723 $curChar = $text[$i];
2724 if ( $curChar == '|' ) {
2725 $found = 'pipe';
2726 } elseif ( $curChar == '=' ) {
2727 $found = 'equals';
2728 } elseif ( $curChar == '<' ) {
2729 $found = 'angle';
2730 } elseif ( $curChar == "\n" ) {
2731 if ( $stackIndex == -1 ) {
2732 $found = 'line-start';
2733 } else {
2734 $found = 'line-end';
2735 }
2736 } elseif ( $curChar == $currentClosing ) {
2737 $found = 'close';
2738 } elseif ( isset( $rules[$curChar] ) ) {
2739 $found = 'open';
2740 $rule = $rules[$curChar];
2741 } else {
2742 # Some versions of PHP have a strcspn which stops on null characters
2743 # Ignore and continue
2744 ++$i;
2745 continue;
2746 }
2747 }
2748 }
2749
2750 if ( $found == 'angle' ) {
2751 $matches = false;
2752 // Handle </onlyinclude>
2753 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
2754 $findOnlyinclude = true;
2755 continue;
2756 }
2757
2758 // Determine element name
2759 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
2760 // Element name missing or not listed
2761 $accum .= '&lt;';
2762 ++$i;
2763 continue;
2764 }
2765 // Handle comments
2766 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
2767 // To avoid leaving blank lines, when a comment is both preceded
2768 // and followed by a newline (ignoring spaces), trim leading and
2769 // trailing spaces and one of the newlines.
2770
2771 // Find the end
2772 $endPos = strpos( $text, '-->', $i + 4 );
2773 if ( $endPos === false ) {
2774 // Unclosed comment in input, runs to end
2775 $inner = substr( $text, $i );
2776 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2777 $i = strlen( $text );
2778 } else {
2779 // Search backwards for leading whitespace
2780 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
2781 // Search forwards for trailing whitespace
2782 // $wsEnd will be the position of the last space
2783 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
2784 // Eat the line if possible
2785 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
2786 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
2787 {
2788 $startPos = $wsStart;
2789 $endPos = $wsEnd + 1;
2790 // Remove leading whitespace from the end of the accumulator
2791 // Sanity check first though
2792 $wsLength = $i - $wsStart;
2793 if ( $wsLength > 0 && substr( $accum, -$wsLength ) === str_repeat( ' ', $wsLength ) ) {
2794 $accum = substr( $accum, 0, -$wsLength );
2795 }
2796 } else {
2797 // No line to eat, just take the comment itself
2798 $startPos = $i;
2799 $endPos += 2;
2800 }
2801
2802 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
2803 $accum .= '<comment>' . htmlspecialchars( $inner ) . '</comment>';
2804 $i = $endPos + 1;
2805 }
2806 continue;
2807 }
2808 $name = $matches[1];
2809 $attrStart = $i + strlen( $name ) + 1;
2810
2811 // Find end of tag
2812 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
2813 if ( $tagEndPos === false ) {
2814 // Infinite backtrack
2815 // Disable tag search to prevent worst-case O(N^2) performance
2816 $noMoreGT = true;
2817 $accum .= '&lt;';
2818 ++$i;
2819 continue;
2820 }
2821
2822 // Handle ignored tags
2823 if ( in_array( $name, $ignoredTags ) ) {
2824 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $i, $tagEndPos - $i + 1 ) ) . '</ignore>';
2825 $i = $tagEndPos + 1;
2826 continue;
2827 }
2828
2829 $tagStartPos = $i;
2830 if ( $text[$tagEndPos-1] == '/' ) {
2831 $attrEnd = $tagEndPos - 1;
2832 $inner = null;
2833 $i = $tagEndPos + 1;
2834 $close = '';
2835 } else {
2836 $attrEnd = $tagEndPos;
2837 // Find closing tag
2838 if ( preg_match( "/<\/$name\s*>/i", $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) ) {
2839 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
2840 $i = $matches[0][1] + strlen( $matches[0][0] );
2841 $close = '<close>' . htmlspecialchars( $matches[0][0] ) . '</close>';
2842 } else {
2843 // No end tag -- let it run out to the end of the text.
2844 $inner = substr( $text, $tagEndPos + 1 );
2845 $i = strlen( $text );
2846 $close = '';
2847 }
2848 }
2849 // <includeonly> and <noinclude> just become <ignore> tags
2850 if ( in_array( $name, $ignoredElements ) ) {
2851 $accum .= '<ignore>' . htmlspecialchars( substr( $text, $tagStartPos, $i - $tagStartPos ) )
2852 . '</ignore>';
2853 continue;
2854 }
2855
2856 $accum .= '<ext>';
2857 if ( $attrEnd <= $attrStart ) {
2858 $attr = '';
2859 } else {
2860 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
2861 }
2862 $accum .= '<name>' . htmlspecialchars( $name ) . '</name>' .
2863 // Note that the attr element contains the whitespace between name and attribute,
2864 // this is necessary for precise reconstruction during pre-save transform.
2865 '<attr>' . htmlspecialchars( $attr ) . '</attr>';
2866 if ( $inner !== null ) {
2867 $accum .= '<inner>' . htmlspecialchars( $inner ) . '</inner>';
2868 }
2869 $accum .= $close . '</ext>';
2870 }
2871
2872 elseif ( $found == 'line-start' ) {
2873 // Is this the start of a heading?
2874 // Line break belongs before the heading element in any case
2875 $accum .= $curChar;
2876 $i++;
2877
2878 $count = strspn( $text, '=', $i, 6 );
2879 if ( $count > 0 ) {
2880 $piece = array(
2881 'open' => "\n",
2882 'close' => "\n",
2883 'parts' => array( str_repeat( '=', $count ) ),
2884 'count' => $count );
2885 $stack[++$stackIndex] = $piece;
2886 $i += $count;
2887 $accum =& $stack[$stackIndex]['parts'][0];
2888 $findPipe = false;
2889 }
2890 }
2891
2892 elseif ( $found == 'line-end' ) {
2893 $piece = $stack[$stackIndex];
2894 // A heading must be open, otherwise \n wouldn't have been in the search list
2895 assert( $piece['open'] == "\n" );
2896 assert( $stackIndex == 0 );
2897 // Search back through the input to see if it has a proper close
2898 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
2899 $m = false;
2900 $count = $piece['count'];
2901 if ( preg_match( "/\s*(={{$count}})/A", $revText, $m, 0, strlen( $text ) - $i ) ) {
2902 // Found match, output <h>
2903 $count = min( strlen( $m[1] ), $count );
2904 $element = "<h level=\"$count\" i=\"$headingIndex\">$accum</h>";
2905 $headingIndex++;
2906 } else {
2907 // No match, no <h>, just pass down the inner text
2908 $element = $accum;
2909 }
2910 // Unwind the stack
2911 // Headings can only occur on the top level, so this is a bit simpler than the
2912 // generic stack unwind operation in the close case
2913 unset( $stack[$stackIndex--] );
2914 $accum =& $topAccum;
2915 $findEquals = false;
2916 $findPipe = false;
2917
2918 // Append the result to the enclosing accumulator
2919 $accum .= $element;
2920 // Note that we do NOT increment the input pointer.
2921 // This is because the closing linebreak could be the opening linebreak of
2922 // another heading. Infinite loops are avoided because the next iteration MUST
2923 // hit the heading open case above, which unconditionally increments the
2924 // input pointer.
2925 }
2926
2927 elseif ( $found == 'open' ) {
2928 # count opening brace characters
2929 $count = strspn( $text, $curChar, $i );
2930
2931 # we need to add to stack only if opening brace count is enough for one of the rules
2932 if ( $count >= $rule['min'] ) {
2933 # Add it to the stack
2934 $piece = array(
2935 'open' => $curChar,
2936 'close' => $rule['end'],
2937 'count' => $count,
2938 'parts' => array( '' ),
2939 'eqpos' => array(),
2940 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
2941 );
2942
2943 $stackIndex ++;
2944 $stack[$stackIndex] = $piece;
2945 $accum =& $stack[$stackIndex]['parts'][0];
2946 $findEquals = false;
2947 $findPipe = true;
2948 } else {
2949 # Add literal brace(s)
2950 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2951 }
2952 $i += $count;
2953 }
2954
2955 elseif ( $found == 'close' ) {
2956 $piece = $stack[$stackIndex];
2957 # lets check if there are enough characters for closing brace
2958 $maxCount = $piece['count'];
2959 $count = strspn( $text, $curChar, $i, $maxCount );
2960
2961 # check for maximum matching characters (if there are 5 closing
2962 # characters, we will probably need only 3 - depending on the rules)
2963 $matchingCount = 0;
2964 $rule = $rules[$piece['open']];
2965 if ( $count > $rule['max'] ) {
2966 # The specified maximum exists in the callback array, unless the caller
2967 # has made an error
2968 $matchingCount = $rule['max'];
2969 } else {
2970 # Count is less than the maximum
2971 # Skip any gaps in the callback array to find the true largest match
2972 # Need to use array_key_exists not isset because the callback can be null
2973 $matchingCount = $count;
2974 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
2975 --$matchingCount;
2976 }
2977 }
2978
2979 if ($matchingCount <= 0) {
2980 # No matching element found in callback array
2981 # Output a literal closing brace and continue
2982 $accum .= htmlspecialchars( str_repeat( $curChar, $count ) );
2983 $i += $count;
2984 continue;
2985 }
2986 $name = $rule['names'][$matchingCount];
2987 if ( $name === null ) {
2988 // No element, just literal text
2989 $element = str_repeat( $piece['open'], $matchingCount ) .
2990 implode( '|', $piece['parts'] ) .
2991 str_repeat( $rule['end'], $matchingCount );
2992 } else {
2993 # Create XML element
2994 # Note: $parts is already XML, does not need to be encoded further
2995 $parts = $piece['parts'];
2996 $title = $parts[0];
2997 unset( $parts[0] );
2998
2999 # The invocation is at the start of the line if lineStart is set in
3000 # the stack, and all opening brackets are used up.
3001 if ( $maxCount == $matchingCount && !empty( $piece['lineStart'] ) ) {
3002 $attr = ' lineStart="1"';
3003 } else {
3004 $attr = '';
3005 }
3006
3007 $element = "<$name$attr>";
3008 $element .= "<title>$title</title>";
3009 $argIndex = 1;
3010 foreach ( $parts as $partIndex => $part ) {
3011 if ( isset( $piece['eqpos'][$partIndex] ) ) {
3012 $eqpos = $piece['eqpos'][$partIndex];
3013 list( $ws1, $argName, $ws2 ) = self::splitWhitespace( substr( $part, 0, $eqpos ) );
3014 list( $ws3, $argValue, $ws4 ) = self::splitWhitespace( substr( $part, $eqpos + 1 ) );
3015 $element .= "<part>$ws1<name>$argName</name>$ws2=$ws3<value>$argValue</value>$ws4</part>";
3016 } else {
3017 list( $ws1, $value, $ws2 ) = self::splitWhitespace( $part );
3018 $element .= "<part>$ws1<name index=\"$argIndex\" /><value>$value</value>$ws2</part>";
3019 $argIndex++;
3020 }
3021 }
3022 $element .= "</$name>";
3023 }
3024
3025 # Advance input pointer
3026 $i += $matchingCount;
3027
3028 # Unwind the stack
3029 unset( $stack[$stackIndex--] );
3030 if ( $stackIndex == -1 ) {
3031 $accum =& $topAccum;
3032 $findEquals = false;
3033 $findPipe = false;
3034 } else {
3035 $partCount = count( $stack[$stackIndex]['parts'] );
3036 $accum =& $stack[$stackIndex]['parts'][$partCount - 1];
3037 $findPipe = $stack[$stackIndex]['open'] != "\n";
3038 $findEquals = $findPipe && $partCount > 1
3039 && !isset( $stack[$stackIndex]['eqpos'][$partCount - 1] );
3040 }
3041
3042 # Re-add the old stack element if it still has unmatched opening characters remaining
3043 if ($matchingCount < $piece['count']) {
3044 $piece['parts'] = array( '' );
3045 $piece['count'] -= $matchingCount;
3046 $piece['eqpos'] = array();
3047 # do we still qualify for any callback with remaining count?
3048 $names = $rules[$piece['open']]['names'];
3049 $skippedBraces = 0;
3050 $enclosingAccum =& $accum;
3051 while ( $piece['count'] ) {
3052 if ( array_key_exists( $piece['count'], $names ) ) {
3053 $stackIndex++;
3054 $stack[$stackIndex] = $piece;
3055 $accum =& $stack[$stackIndex]['parts'][0];
3056 $findEquals = true;
3057 $findPipe = true;
3058 break;
3059 }
3060 --$piece['count'];
3061 $skippedBraces ++;
3062 }
3063 $enclosingAccum .= str_repeat( $piece['open'], $skippedBraces );
3064 }
3065
3066 # Add XML element to the enclosing accumulator
3067 $accum .= $element;
3068 }
3069
3070 elseif ( $found == 'pipe' ) {
3071 $stack[$stackIndex]['parts'][] = '';
3072 $partsCount = count( $stack[$stackIndex]['parts'] );
3073 $accum =& $stack[$stackIndex]['parts'][$partsCount - 1];
3074 $findEquals = true;
3075 ++$i;
3076 }
3077
3078 elseif ( $found == 'equals' ) {
3079 $findEquals = false;
3080 $partsCount = count( $stack[$stackIndex]['parts'] );
3081 $stack[$stackIndex]['eqpos'][$partsCount - 1] = strlen( $accum );
3082 $accum .= '=';
3083 ++$i;
3084 }
3085 }
3086
3087 # Output any remaining unclosed brackets
3088 foreach ( $stack as $piece ) {
3089 if ( $piece['open'] == "\n" ) {
3090 $topAccum .= $piece['parts'][0];
3091 } else {
3092 $topAccum .= str_repeat( $piece['open'], $piece['count'] ) . implode( '|', $piece['parts'] );
3093 }
3094 }
3095 $topAccum .= '</root>';
3096
3097 wfProfileOut( __METHOD__.'-makexml' );
3098 wfProfileIn( __METHOD__.'-loadXML' );
3099 $dom = new DOMDocument;
3100 wfSuppressWarnings();
3101 $result = $dom->loadXML( $topAccum );
3102 wfRestoreWarnings();
3103 if ( !$result ) {
3104 // Try running the XML through UtfNormal to get rid of invalid characters
3105 $topAccum = UtfNormal::cleanUp( $topAccum );
3106 $result = $dom->loadXML( $topAccum );
3107 if ( !$result ) {
3108 throw new MWException( __METHOD__.' generated invalid XML' );
3109 }
3110 }
3111 wfProfileOut( __METHOD__.'-loadXML' );
3112 wfProfileOut( __METHOD__ );
3113 return $dom;
3114 }
3115
3116 /*
3117 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3118 */
3119 public static function splitWhitespace( $s ) {
3120 $ltrimmed = ltrim( $s );
3121 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3122 $trimmed = rtrim( $ltrimmed );
3123 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3124 if ( $diff > 0 ) {
3125 $w2 = substr( $ltrimmed, -$diff );
3126 } else {
3127 $w2 = '';
3128 }
3129 return array( $w1, $trimmed, $w2 );
3130 }
3131
3132 /**
3133 * Replace magic variables, templates, and template arguments
3134 * with the appropriate text. Templates are substituted recursively,
3135 * taking care to avoid infinite loops.
3136 *
3137 * Note that the substitution depends on value of $mOutputType:
3138 * OT_WIKI: only {{subst:}} templates
3139 * OT_MSG: only magic variables
3140 * OT_HTML: all templates and magic variables
3141 *
3142 * @param string $tex The text to transform
3143 * @param PPFrame $frame Object describing the arguments passed to the template
3144 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3145 * @private
3146 */
3147 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3148 # Prevent too big inclusions
3149 if( strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3150 return $text;
3151 }
3152
3153 $fname = __METHOD__;
3154 wfProfileIn( $fname );
3155
3156 if ( $frame === false ) {
3157 $frame = new PPFrame( $this );
3158 } elseif ( !( $frame instanceof PPFrame ) ) {
3159 throw new MWException( __METHOD__ . ' called using the old argument format' );
3160 }
3161
3162 $dom = $this->preprocessToDom( $text );
3163 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3164 $text = $frame->expand( $dom, $flags );
3165
3166 wfProfileOut( $fname );
3167 return $text;
3168 }
3169
3170 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3171 static function createAssocArgs( $args ) {
3172 $assocArgs = array();
3173 $index = 1;
3174 foreach( $args as $arg ) {
3175 $eqpos = strpos( $arg, '=' );
3176 if ( $eqpos === false ) {
3177 $assocArgs[$index++] = $arg;
3178 } else {
3179 $name = trim( substr( $arg, 0, $eqpos ) );
3180 $value = trim( substr( $arg, $eqpos+1 ) );
3181 if ( $value === false ) {
3182 $value = '';
3183 }
3184 if ( $name !== false ) {
3185 $assocArgs[$name] = $value;
3186 }
3187 }
3188 }
3189
3190 return $assocArgs;
3191 }
3192
3193 /**
3194 * Return the text of a template, after recursively
3195 * replacing any variables or templates within the template.
3196 *
3197 * @param array $piece The parts of the template
3198 * $piece['text']: matched text
3199 * $piece['title']: the title, i.e. the part before the |
3200 * $piece['parts']: the parameter array
3201 * @param PPFrame The current frame, contains template arguments
3202 * @return string the text of the template
3203 * @private
3204 */
3205 function braceSubstitution( $piece, $frame ) {
3206 global $wgContLang, $wgLang, $wgAllowDisplayTitle, $wgNonincludableNamespaces;
3207 $fname = __METHOD__;
3208 wfProfileIn( $fname );
3209 wfProfileIn( __METHOD__.'-setup' );
3210
3211 # Flags
3212 $found = false; # $text has been filled
3213 $nowiki = false; # wiki markup in $text should be escaped
3214 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3215 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3216 $isDOM = false; # $text is a DOM node needing expansion
3217
3218 # Title object, where $text came from
3219 $title = NULL;
3220
3221 # $part1 is the bit before the first |, and must contain only title characters.
3222 # Various prefixes will be stripped from it later.
3223 $titleWithSpaces = $frame->expand( $piece['title'] );
3224 $part1 = trim( $titleWithSpaces );
3225 $titleText = false;
3226
3227 # Original title text preserved for various purposes
3228 $originalTitle = $part1;
3229
3230 # $args is a list of argument nodes, starting from index 0, not including $part1
3231 $args = (null == $piece['parts']) ? array() : $piece['parts'];
3232 wfProfileOut( __METHOD__.'-setup' );
3233
3234 # SUBST
3235 wfProfileIn( __METHOD__.'-modifiers' );
3236 if ( !$found ) {
3237 $mwSubst =& MagicWord::get( 'subst' );
3238 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot['wiki'] ) {
3239 # One of two possibilities is true:
3240 # 1) Found SUBST but not in the PST phase
3241 # 2) Didn't find SUBST and in the PST phase
3242 # In either case, return without further processing
3243 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3244 $found = true;
3245 }
3246 }
3247
3248 # Variables
3249 if ( !$found && $args->length == 0 ) {
3250 $id = $this->mVariables->matchStartToEnd( $part1 );
3251 if ( $id !== false ) {
3252 $text = $this->getVariableValue( $id );
3253 $this->mOutput->mContainsOldMagic = true;
3254 $found = true;
3255 }
3256 }
3257
3258 # MSG, MSGNW and RAW
3259 if ( !$found ) {
3260 # Check for MSGNW:
3261 $mwMsgnw =& MagicWord::get( 'msgnw' );
3262 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3263 $nowiki = true;
3264 } else {
3265 # Remove obsolete MSG:
3266 $mwMsg =& MagicWord::get( 'msg' );
3267 $mwMsg->matchStartAndRemove( $part1 );
3268 }
3269
3270 # Check for RAW:
3271 $mwRaw =& MagicWord::get( 'raw' );
3272 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3273 $forceRawInterwiki = true;
3274 }
3275 }
3276 wfProfileOut( __METHOD__.'-modifiers' );
3277
3278 # Save path level before recursing into functions & templates.
3279 $lastPathLevel = $this->mTemplatePath;
3280
3281 # Parser functions
3282 if ( !$found ) {
3283 wfProfileIn( __METHOD__ . '-pfunc' );
3284
3285 $colonPos = strpos( $part1, ':' );
3286 if ( $colonPos !== false ) {
3287 # Case sensitive functions
3288 $function = substr( $part1, 0, $colonPos );
3289 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3290 $function = $this->mFunctionSynonyms[1][$function];
3291 } else {
3292 # Case insensitive functions
3293 $function = strtolower( $function );
3294 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3295 $function = $this->mFunctionSynonyms[0][$function];
3296 } else {
3297 $function = false;
3298 }
3299 }
3300 if ( $function ) {
3301 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3302 $initialArgs = array( &$this );
3303 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3304 if ( $flags & SFH_OBJECT_ARGS ) {
3305 # Add a frame parameter, and pass the arguments as an array
3306 $allArgs = $initialArgs;
3307 $allArgs[] = $frame;
3308 foreach ( $args as $arg ) {
3309 $funcArgs[] = $arg;
3310 }
3311 $allArgs[] = $funcArgs;
3312 } else {
3313 # Convert arguments to plain text
3314 foreach ( $args as $arg ) {
3315 $funcArgs[] = trim( $frame->expand( $arg ) );
3316 }
3317 $allArgs = array_merge( $initialArgs, $funcArgs );
3318 }
3319
3320 $result = call_user_func_array( $callback, $allArgs );
3321 $found = true;
3322
3323 if ( is_array( $result ) ) {
3324 if ( isset( $result[0] ) ) {
3325 $text = $result[0];
3326 unset( $result[0] );
3327 }
3328
3329 // Extract flags into the local scope
3330 // This allows callers to set flags such as nowiki, found, etc.
3331 extract( $result );
3332 } else {
3333 $text = $result;
3334 }
3335 }
3336 }
3337 wfProfileOut( __METHOD__ . '-pfunc' );
3338 }
3339
3340 # Finish mangling title and then check for loops.
3341 # Set $title to a Title object and $titleText to the PDBK
3342 if ( !$found ) {
3343 $ns = NS_TEMPLATE;
3344 # Split the title into page and subpage
3345 $subpage = '';
3346 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3347 if ($subpage !== '') {
3348 $ns = $this->mTitle->getNamespace();
3349 }
3350 $title = Title::newFromText( $part1, $ns );
3351 if ( $title ) {
3352 $titleText = $title->getPrefixedText();
3353 # Check for language variants if the template is not found
3354 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
3355 $wgContLang->findVariantLink($part1, $title);
3356 }
3357 # Do infinite loop check
3358 if ( isset( $this->mTemplatePath[$titleText] ) ) {
3359 $found = true;
3360 $text = "[[$part1]]" . $this->insertStripItem( '<!-- WARNING: template loop detected -->' );
3361 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3362 }
3363 }
3364 }
3365
3366 # Load from database
3367 if ( !$found && $title ) {
3368 wfProfileIn( __METHOD__ . '-loadtpl' );
3369 if ( !$title->isExternal() ) {
3370 if ( $title->getNamespace() == NS_SPECIAL && $this->mOptions->getAllowSpecialInclusion() && $this->ot['html'] ) {
3371 $text = SpecialPage::capturePath( $title );
3372 if ( is_string( $text ) ) {
3373 $found = true;
3374 $isHTML = true;
3375 $this->disableCache();
3376 }
3377 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3378 $found = false; //access denied
3379 wfDebug( "$fname: template inclusion denied for " . $title->getPrefixedDBkey() );
3380 } else {
3381 list( $text, $title ) = $this->getTemplateDom( $title );
3382 if ( $text !== false ) {
3383 $found = true;
3384 $isDOM = true;
3385 }
3386 }
3387
3388 # If the title is valid but undisplayable, make a link to it
3389 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3390 $text = "[[:$titleText]]";
3391 $found = true;
3392 }
3393 } elseif ( $title->isTrans() ) {
3394 // Interwiki transclusion
3395 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3396 $text = $this->interwikiTransclude( $title, 'render' );
3397 $isHTML = true;
3398 } else {
3399 $text = $this->interwikiTransclude( $title, 'raw' );
3400 // Preprocess it like a template
3401 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3402 $isDOM = true;
3403 }
3404 $found = true;
3405 }
3406 wfProfileOut( __METHOD__ . '-loadtpl' );
3407 }
3408
3409 # If we haven't found text to substitute by now, we're done
3410 # Recover the source wikitext and return it
3411 if ( !$found ) {
3412 $text = '{{' . $frame->implode( '|', $titleWithSpaces, $args ) . '}}';
3413 # Prune lower levels off the recursion check path
3414 $this->mTemplatePath = $lastPathLevel;
3415 wfProfileOut( $fname );
3416 return $text;
3417 }
3418
3419 # Expand DOM-style return values in a child frame
3420 if ( $isDOM ) {
3421 # Clean up argument array
3422 $newFrame = $frame->newChild( $args, $title );
3423 # Add a new element to the templace recursion path
3424 $this->mTemplatePath[$titleText] = 1;
3425
3426 if ( $titleText !== false && count( $newFrame->args ) == 0 ) {
3427 # Expansion is eligible for the empty-frame cache
3428 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3429 $text = $this->mTplExpandCache[$titleText];
3430 } else {
3431 $text = $newFrame->expand( $text );
3432 $this->mTplExpandCache[$titleText] = $text;
3433 }
3434 } else {
3435 $text = $newFrame->expand( $text );
3436 }
3437 }
3438
3439 # Replace raw HTML by a placeholder
3440 # Add a blank line preceding, to prevent it from mucking up
3441 # immediately preceding headings
3442 if ( $isHTML ) {
3443 $text = "\n\n" . $this->insertStripItem( $text );
3444 }
3445 # Escape nowiki-style return values
3446 elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3447 $text = wfEscapeWikiText( $text );
3448 }
3449 # Bug 529: if the template begins with a table or block-level
3450 # element, it should be treated as beginning a new line.
3451 # This behaviour is somewhat controversial.
3452 elseif ( !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3453 $text = "\n" . $text;
3454 }
3455
3456 # Prune lower levels off the recursion check path
3457 $this->mTemplatePath = $lastPathLevel;
3458
3459 if ( !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3460 # Error, oversize inclusion
3461 $text = "[[$originalTitle]]" .
3462 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3463 }
3464
3465 wfProfileOut( $fname );
3466 return $text;
3467 }
3468
3469 /**
3470 * Get the semi-parsed DOM representation of a template with a given title,
3471 * and its redirect destination title. Cached.
3472 */
3473 function getTemplateDom( $title ) {
3474 $cacheTitle = $title;
3475 $titleText = $title->getPrefixedDBkey();
3476
3477 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3478 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3479 $title = Title::makeTitle( $ns, $dbk );
3480 $titleText = $title->getPrefixedDBkey();
3481 }
3482 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3483 return array( $this->mTplDomCache[$titleText], $title );
3484 }
3485
3486 // Cache miss, go to the database
3487 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3488
3489 if ( $text === false ) {
3490 $this->mTplDomCache[$titleText] = false;
3491 return array( false, $title );
3492 }
3493
3494 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3495 $this->mTplDomCache[ $titleText ] = $dom;
3496
3497 if (! $title->equals($cacheTitle)) {
3498 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3499 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3500 }
3501
3502 return array( $dom, $title );
3503 }
3504
3505 /**
3506 * Fetch the unparsed text of a template and register a reference to it.
3507 */
3508 function fetchTemplateAndTitle( $title ) {
3509 $templateCb = $this->mOptions->getTemplateCallback();
3510 $stuff = call_user_func( $templateCb, $title );
3511 $text = $stuff['text'];
3512 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3513 if ( isset( $stuff['deps'] ) ) {
3514 foreach ( $stuff['deps'] as $dep ) {
3515 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3516 }
3517 }
3518 return array($text,$finalTitle);
3519 }
3520
3521 function fetchTemplate( $title ) {
3522 $rv = $this->fetchTemplateAndTitle($title);
3523 return $rv[0];
3524 }
3525
3526 /**
3527 * Static function to get a template
3528 * Can be overridden via ParserOptions::setTemplateCallback().
3529 */
3530 static function statelessFetchTemplate( $title ) {
3531 $text = $skip = false;
3532 $finalTitle = $title;
3533 $deps = array();
3534
3535 // Loop to fetch the article, with up to 1 redirect
3536 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3537 # Give extensions a chance to select the revision instead
3538 $id = false; // Assume current
3539 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( false, &$title, &$skip, &$id ) );
3540
3541 if( $skip ) {
3542 $text = false;
3543 $deps[] = array(
3544 'title' => $title,
3545 'page_id' => $title->getArticleID(),
3546 'rev_id' => null );
3547 break;
3548 }
3549 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3550 $rev_id = $rev ? $rev->getId() : 0;
3551
3552 $deps[] = array(
3553 'title' => $title,
3554 'page_id' => $title->getArticleID(),
3555 'rev_id' => $rev_id );
3556
3557 if( $rev ) {
3558 $text = $rev->getText();
3559 } elseif( $title->getNamespace() == NS_MEDIAWIKI ) {
3560 global $wgLang;
3561 $message = $wgLang->lcfirst( $title->getText() );
3562 $text = wfMsgForContentNoTrans( $message );
3563 if( wfEmptyMsg( $message, $text ) ) {
3564 $text = false;
3565 break;
3566 }
3567 } else {
3568 break;
3569 }
3570 if ( $text === false ) {
3571 break;
3572 }
3573 // Redirect?
3574 $finalTitle = $title;
3575 $title = Title::newFromRedirect( $text );
3576 }
3577 return array(
3578 'text' => $text,
3579 'finalTitle' => $finalTitle,
3580 'deps' => $deps );
3581 }
3582
3583 /**
3584 * Transclude an interwiki link.
3585 */
3586 function interwikiTransclude( $title, $action ) {
3587 global $wgEnableScaryTranscluding;
3588
3589 if (!$wgEnableScaryTranscluding)
3590 return wfMsg('scarytranscludedisabled');
3591
3592 $url = $title->getFullUrl( "action=$action" );
3593
3594 if (strlen($url) > 255)
3595 return wfMsg('scarytranscludetoolong');
3596 return $this->fetchScaryTemplateMaybeFromCache($url);
3597 }
3598
3599 function fetchScaryTemplateMaybeFromCache($url) {
3600 global $wgTranscludeCacheExpiry;
3601 $dbr = wfGetDB(DB_SLAVE);
3602 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3603 array('tc_url' => $url));
3604 if ($obj) {
3605 $time = $obj->tc_time;
3606 $text = $obj->tc_contents;
3607 if ($time && time() < $time + $wgTranscludeCacheExpiry ) {
3608 return $text;
3609 }
3610 }
3611
3612 $text = Http::get($url);
3613 if (!$text)
3614 return wfMsg('scarytranscludefailed', $url);
3615
3616 $dbw = wfGetDB(DB_MASTER);
3617 $dbw->replace('transcache', array('tc_url'), array(
3618 'tc_url' => $url,
3619 'tc_time' => time(),
3620 'tc_contents' => $text));
3621 return $text;
3622 }
3623
3624
3625 /**
3626 * Triple brace replacement -- used for template arguments
3627 * @private
3628 */
3629 function argSubstitution( $piece, $frame ) {
3630 wfProfileIn( __METHOD__ );
3631
3632 $text = false;
3633 $error = false;
3634 $parts = $piece['parts'];
3635 $argWithSpaces = $frame->expand( $piece['title'] );
3636 $arg = trim( $argWithSpaces );
3637
3638 if ( isset( $frame->args[$arg] ) ) {
3639 $text = $frame->parent->expand( $frame->args[$arg] );
3640 } else if ( ( $this->ot['html'] || $this->ot['pre'] ) && $parts->length > 0 ) {
3641 $text = $frame->expand( $parts->item( 0 ) );
3642 }
3643 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3644 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3645 }
3646
3647 if ( $text === false ) {
3648 $text = '{{{' . $frame->implode( '|', $argWithSpaces, $parts ) . '}}}';
3649 }
3650 if ( $error !== false ) {
3651 $text .= $error;
3652 }
3653
3654 wfProfileOut( __METHOD__ );
3655 return $text;
3656 }
3657
3658 /**
3659 * Return the text to be used for a given extension tag.
3660 * This is the ghost of strip().
3661 *
3662 * @param array $params Associative array of parameters:
3663 * name DOMNode for the tag name
3664 * attrText DOMNode for unparsed text where tag attributes are thought to be
3665 * inner Contents of extension element
3666 * noClose Original text did not have a close tag
3667 * @param PPFrame $frame
3668 */
3669 function extensionSubstitution( $params, $frame ) {
3670 global $wgRawHtml, $wgContLang;
3671 static $n = 1;
3672
3673 $name = $frame->expand( $params['name'] );
3674 $attrText = is_null( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3675 $content = is_null( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3676
3677 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $n++) . $this->mMarkerSuffix;
3678
3679 if ( $this->ot['html'] ) {
3680 $name = strtolower( $name );
3681
3682 $params = Sanitizer::decodeTagAttributes( $attrText );
3683 switch ( $name ) {
3684 case 'html':
3685 if( $wgRawHtml ) {
3686 $output = $content;
3687 break;
3688 } else {
3689 throw new MWException( '<html> extension tag encountered unexpectedly' );
3690 }
3691 case 'nowiki':
3692 $output = Xml::escapeTagsOnly( $content );
3693 break;
3694 case 'math':
3695 $output = $wgContLang->armourMath(
3696 MathRenderer::renderMath( $content, $params ) );
3697 break;
3698 case 'gallery':
3699 $output = $this->renderImageGallery( $content, $params );
3700 break;
3701 default:
3702 if( isset( $this->mTagHooks[$name] ) ) {
3703 $output = call_user_func_array( $this->mTagHooks[$name],
3704 array( $content, $params, $this ) );
3705 } else {
3706 throw new MWException( "Invalid call hook $name" );
3707 }
3708 }
3709 } else {
3710 if ( $content === null ) {
3711 $output = "<$name$attrText/>";
3712 } else {
3713 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3714 $output = "<$name$attrText>$content$close";
3715 }
3716 }
3717
3718 if ( $name == 'html' || $name == 'nowiki' ) {
3719 $this->mStripState->nowiki->setPair( $marker, $output );
3720 } else {
3721 $this->mStripState->general->setPair( $marker, $output );
3722 }
3723 return $marker;
3724 }
3725
3726 /**
3727 * Increment an include size counter
3728 *
3729 * @param string $type The type of expansion
3730 * @param integer $size The size of the text
3731 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3732 */
3733 function incrementIncludeSize( $type, $size ) {
3734 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3735 return false;
3736 } else {
3737 $this->mIncludeSizes[$type] += $size;
3738 return true;
3739 }
3740 }
3741
3742 /**
3743 * Detect __NOGALLERY__ magic word and set a placeholder
3744 */
3745 function stripNoGallery( &$text ) {
3746 # if the string __NOGALLERY__ (not case-sensitive) occurs in the HTML,
3747 # do not add TOC
3748 $mw = MagicWord::get( 'nogallery' );
3749 $this->mOutput->mNoGallery = $mw->matchAndRemove( $text ) ;
3750 }
3751
3752 /**
3753 * Find the first __TOC__ magic word and set a <!--MWTOC-->
3754 * placeholder that will then be replaced by the real TOC in
3755 * ->formatHeadings, this works because at this points real
3756 * comments will have already been discarded by the sanitizer.
3757 *
3758 * Any additional __TOC__ magic words left over will be discarded
3759 * as there can only be one TOC on the page.
3760 */
3761 function stripToc( $text ) {
3762 # if the string __NOTOC__ (not case-sensitive) occurs in the HTML,
3763 # do not add TOC
3764 $mw = MagicWord::get( 'notoc' );
3765 if( $mw->matchAndRemove( $text ) ) {
3766 $this->mShowToc = false;
3767 }
3768
3769 $mw = MagicWord::get( 'toc' );
3770 if( $mw->match( $text ) ) {
3771 $this->mShowToc = true;
3772 $this->mForceTocPosition = true;
3773
3774 // Set a placeholder. At the end we'll fill it in with the TOC.
3775 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3776
3777 // Only keep the first one.
3778 $text = $mw->replace( '', $text );
3779 }
3780 return $text;
3781 }
3782
3783 /**
3784 * This function accomplishes several tasks:
3785 * 1) Auto-number headings if that option is enabled
3786 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3787 * 3) Add a Table of contents on the top for users who have enabled the option
3788 * 4) Auto-anchor headings
3789 *
3790 * It loops through all headlines, collects the necessary data, then splits up the
3791 * string and re-inserts the newly formatted headlines.
3792 *
3793 * @param string $text
3794 * @param boolean $isMain
3795 * @private
3796 */
3797 function formatHeadings( $text, $isMain=true ) {
3798 global $wgMaxTocLevel, $wgContLang;
3799
3800 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3801 if( !$this->mTitle->quickUserCan( 'edit' ) ) {
3802 $showEditLink = 0;
3803 } else {
3804 $showEditLink = $this->mOptions->getEditSection();
3805 }
3806
3807 # Inhibit editsection links if requested in the page
3808 $esw =& MagicWord::get( 'noeditsection' );
3809 if( $esw->matchAndRemove( $text ) ) {
3810 $showEditLink = 0;
3811 }
3812
3813 # Get all headlines for numbering them and adding funky stuff like [edit]
3814 # links - this is for later, but we need the number of headlines right now
3815 $matches = array();
3816 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3817
3818 # if there are fewer than 4 headlines in the article, do not show TOC
3819 # unless it's been explicitly enabled.
3820 $enoughToc = $this->mShowToc &&
3821 (($numMatches >= 4) || $this->mForceTocPosition);
3822
3823 # Allow user to stipulate that a page should have a "new section"
3824 # link added via __NEWSECTIONLINK__
3825 $mw =& MagicWord::get( 'newsectionlink' );
3826 if( $mw->matchAndRemove( $text ) )
3827 $this->mOutput->setNewSection( true );
3828
3829 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3830 # override above conditions and always show TOC above first header
3831 $mw =& MagicWord::get( 'forcetoc' );
3832 if ($mw->matchAndRemove( $text ) ) {
3833 $this->mShowToc = true;
3834 $enoughToc = true;
3835 }
3836
3837 # We need this to perform operations on the HTML
3838 $sk = $this->mOptions->getSkin();
3839
3840 # headline counter
3841 $headlineCount = 0;
3842 $numVisible = 0;
3843
3844 # Ugh .. the TOC should have neat indentation levels which can be
3845 # passed to the skin functions. These are determined here
3846 $toc = '';
3847 $full = '';
3848 $head = array();
3849 $sublevelCount = array();
3850 $levelCount = array();
3851 $toclevel = 0;
3852 $level = 0;
3853 $prevlevel = 0;
3854 $toclevel = 0;
3855 $prevtoclevel = 0;
3856 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-{$this->mMarkerSuffix}";
3857 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3858 $tocraw = array();
3859
3860 foreach( $matches[3] as $headline ) {
3861 $isTemplate = false;
3862 $titleText = false;
3863 $sectionIndex = false;
3864 $numbering = '';
3865 $markerMatches = array();
3866 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3867 $serial = $markerMatches[1];
3868 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3869 $isTemplate = ($titleText != $baseTitleText);
3870 $headline = preg_replace("/^$markerRegex/", "", $headline);
3871 }
3872
3873 if( $toclevel ) {
3874 $prevlevel = $level;
3875 $prevtoclevel = $toclevel;
3876 }
3877 $level = $matches[1][$headlineCount];
3878
3879 if( $doNumberHeadings || $enoughToc ) {
3880
3881 if ( $level > $prevlevel ) {
3882 # Increase TOC level
3883 $toclevel++;
3884 $sublevelCount[$toclevel] = 0;
3885 if( $toclevel<$wgMaxTocLevel ) {
3886 $prevtoclevel = $toclevel;
3887 $toc .= $sk->tocIndent();
3888 $numVisible++;
3889 }
3890 }
3891 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3892 # Decrease TOC level, find level to jump to
3893
3894 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3895 # Can only go down to level 1
3896 $toclevel = 1;
3897 } else {
3898 for ($i = $toclevel; $i > 0; $i--) {
3899 if ( $levelCount[$i] == $level ) {
3900 # Found last matching level
3901 $toclevel = $i;
3902 break;
3903 }
3904 elseif ( $levelCount[$i] < $level ) {
3905 # Found first matching level below current level
3906 $toclevel = $i + 1;
3907 break;
3908 }
3909 }
3910 }
3911 if( $toclevel<$wgMaxTocLevel ) {
3912 if($prevtoclevel < $wgMaxTocLevel) {
3913 # Unindent only if the previous toc level was shown :p
3914 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3915 } else {
3916 $toc .= $sk->tocLineEnd();
3917 }
3918 }
3919 }
3920 else {
3921 # No change in level, end TOC line
3922 if( $toclevel<$wgMaxTocLevel ) {
3923 $toc .= $sk->tocLineEnd();
3924 }
3925 }
3926
3927 $levelCount[$toclevel] = $level;
3928
3929 # count number of headlines for each level
3930 @$sublevelCount[$toclevel]++;
3931 $dot = 0;
3932 for( $i = 1; $i <= $toclevel; $i++ ) {
3933 if( !empty( $sublevelCount[$i] ) ) {
3934 if( $dot ) {
3935 $numbering .= '.';
3936 }
3937 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3938 $dot = 1;
3939 }
3940 }
3941 }
3942
3943 # The safe header is a version of the header text safe to use for links
3944 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3945 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3946
3947 # Remove link placeholders by the link text.
3948 # <!--LINK number-->
3949 # turns into
3950 # link text with suffix
3951 $safeHeadline = preg_replace( '/<!--LINK ([0-9]*)-->/e',
3952 "\$this->mLinkHolders['texts'][\$1]",
3953 $safeHeadline );
3954 $safeHeadline = preg_replace( '/<!--IWLINK ([0-9]*)-->/e',
3955 "\$this->mInterwikiLinkHolders['texts'][\$1]",
3956 $safeHeadline );
3957
3958 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3959 $tocline = preg_replace(
3960 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3961 array( '', '<$1>'),
3962 $safeHeadline
3963 );
3964 $tocline = trim( $tocline );
3965
3966 # For the anchor, strip out HTML-y stuff period
3967 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3968 $safeHeadline = trim( $safeHeadline );
3969
3970 # Save headline for section edit hint before it's escaped
3971 $headlineHint = $safeHeadline;
3972 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3973 $refers[$headlineCount] = $safeHeadline;
3974
3975 # count how many in assoc. array so we can track dupes in anchors
3976 isset( $refers[$safeHeadline] ) ? $refers[$safeHeadline]++ : $refers[$safeHeadline] = 1;
3977 $refcount[$headlineCount] = $refers[$safeHeadline];
3978
3979 # Don't number the heading if it is the only one (looks silly)
3980 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3981 # the two are different if the line contains a link
3982 $headline=$numbering . ' ' . $headline;
3983 }
3984
3985 # Create the anchor for linking from the TOC to the section
3986 $anchor = $safeHeadline;
3987 if($refcount[$headlineCount] > 1 ) {
3988 $anchor .= '_' . $refcount[$headlineCount];
3989 }
3990 if( $enoughToc && ( !isset($wgMaxTocLevel) || $toclevel<$wgMaxTocLevel ) ) {
3991 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3992 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3993 }
3994 # give headline the correct <h#> tag
3995 if( $showEditLink && $sectionIndex !== false ) {
3996 if( $isTemplate ) {
3997 # Put a T flag in the section identifier, to indicate to extractSections()
3998 # that sections inside <includeonly> should be counted.
3999 $editlink = $sk->editSectionLinkForOther($titleText, "T-$sectionIndex");
4000 } else {
4001 $editlink = $sk->editSectionLink($this->mTitle, $sectionIndex, $headlineHint);
4002 }
4003 } else {
4004 $editlink = '';
4005 }
4006 $head[$headlineCount] = $sk->makeHeadline( $level, $matches['attrib'][$headlineCount], $anchor, $headline, $editlink );
4007
4008 $headlineCount++;
4009 }
4010
4011 $this->mOutput->setSections( $tocraw );
4012
4013 # Never ever show TOC if no headers
4014 if( $numVisible < 1 ) {
4015 $enoughToc = false;
4016 }
4017
4018 if( $enoughToc ) {
4019 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4020 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
4021 }
4022 $toc = $sk->tocList( $toc );
4023 }
4024
4025 # split up and insert constructed headlines
4026
4027 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4028 $i = 0;
4029
4030 foreach( $blocks as $block ) {
4031 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block != "\n" ) {
4032 # This is the [edit] link that appears for the top block of text when
4033 # section editing is enabled
4034
4035 # Disabled because it broke block formatting
4036 # For example, a bullet point in the top line
4037 # $full .= $sk->editSectionLink(0);
4038 }
4039 $full .= $block;
4040 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
4041 # Top anchor now in skin
4042 $full = $full.$toc;
4043 }
4044
4045 if( !empty( $head[$i] ) ) {
4046 $full .= $head[$i];
4047 }
4048 $i++;
4049 }
4050 if( $this->mForceTocPosition ) {
4051 return str_replace( '<!--MWTOC-->', $toc, $full );
4052 } else {
4053 return $full;
4054 }
4055 }
4056
4057 /**
4058 * Transform wiki markup when saving a page by doing \r\n -> \n
4059 * conversion, substitting signatures, {{subst:}} templates, etc.
4060 *
4061 * @param string $text the text to transform
4062 * @param Title &$title the Title object for the current article
4063 * @param User &$user the User object describing the current user
4064 * @param ParserOptions $options parsing options
4065 * @param bool $clearState whether to clear the parser state first
4066 * @return string the altered wiki markup
4067 * @public
4068 */
4069 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
4070 $this->mOptions = $options;
4071 $this->mTitle =& $title;
4072 $this->setOutputType( OT_WIKI );
4073
4074 if ( $clearState ) {
4075 $this->clearState();
4076 }
4077
4078 $pairs = array(
4079 "\r\n" => "\n",
4080 );
4081 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4082 $text = $this->pstPass2( $text, $user );
4083 $text = $this->mStripState->unstripBoth( $text );
4084 return $text;
4085 }
4086
4087 /**
4088 * Pre-save transform helper function
4089 * @private
4090 */
4091 function pstPass2( $text, $user ) {
4092 global $wgContLang, $wgLocaltimezone;
4093
4094 /* Note: This is the timestamp saved as hardcoded wikitext to
4095 * the database, we use $wgContLang here in order to give
4096 * everyone the same signature and use the default one rather
4097 * than the one selected in each user's preferences.
4098 */
4099 if ( isset( $wgLocaltimezone ) ) {
4100 $oldtz = getenv( 'TZ' );
4101 putenv( 'TZ='.$wgLocaltimezone );
4102 }
4103 $d = $wgContLang->timeanddate( date( 'YmdHis' ), false, false) .
4104 ' (' . date( 'T' ) . ')';
4105 if ( isset( $wgLocaltimezone ) ) {
4106 putenv( 'TZ='.$oldtz );
4107 }
4108
4109 # Variable replacement
4110 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4111 $text = $this->replaceVariables( $text );
4112
4113 # Strip out <nowiki> etc. added via replaceVariables
4114 #$text = $this->strip( $text, $this->mStripState, false, array( 'gallery' ) );
4115
4116 # Signatures
4117 $sigText = $this->getUserSig( $user );
4118 $text = strtr( $text, array(
4119 '~~~~~' => $d,
4120 '~~~~' => "$sigText $d",
4121 '~~~' => $sigText
4122 ) );
4123
4124 # Context links: [[|name]] and [[name (context)|]]
4125 #
4126 global $wgLegalTitleChars;
4127 $tc = "[$wgLegalTitleChars]";
4128 $nc = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
4129
4130 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4131 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4132 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4133
4134 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4135 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4136 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4137
4138 $t = $this->mTitle->getText();
4139 $m = array();
4140 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4141 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4142 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
4143 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4144 } else {
4145 # if there's no context, don't bother duplicating the title
4146 $text = preg_replace( $p2, '[[\\1]]', $text );
4147 }
4148
4149 # Trim trailing whitespace
4150 $text = rtrim( $text );
4151
4152 return $text;
4153 }
4154
4155 /**
4156 * Fetch the user's signature text, if any, and normalize to
4157 * validated, ready-to-insert wikitext.
4158 *
4159 * @param User $user
4160 * @return string
4161 * @private
4162 */
4163 function getUserSig( &$user ) {
4164 global $wgMaxSigChars;
4165
4166 $username = $user->getName();
4167 $nickname = $user->getOption( 'nickname' );
4168 $nickname = $nickname === '' ? $username : $nickname;
4169
4170 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4171 $nickname = $username;
4172 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4173 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
4174 # Sig. might contain markup; validate this
4175 if( $this->validateSig( $nickname ) !== false ) {
4176 # Validated; clean up (if needed) and return it
4177 return $this->cleanSig( $nickname, true );
4178 } else {
4179 # Failed to validate; fall back to the default
4180 $nickname = $username;
4181 wfDebug( "Parser::getUserSig: $username has bad XML tags in signature.\n" );
4182 }
4183 }
4184
4185 // Make sure nickname doesnt get a sig in a sig
4186 $nickname = $this->cleanSigInSig( $nickname );
4187
4188 # If we're still here, make it a link to the user page
4189 $userText = wfEscapeWikiText( $username );
4190 $nickText = wfEscapeWikiText( $nickname );
4191 if ( $user->isAnon() ) {
4192 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4193 } else {
4194 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4195 }
4196 }
4197
4198 /**
4199 * Check that the user's signature contains no bad XML
4200 *
4201 * @param string $text
4202 * @return mixed An expanded string, or false if invalid.
4203 */
4204 function validateSig( $text ) {
4205 return( wfIsWellFormedXmlFragment( $text ) ? $text : false );
4206 }
4207
4208 /**
4209 * Clean up signature text
4210 *
4211 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4212 * 2) Substitute all transclusions
4213 *
4214 * @param string $text
4215 * @param $parsing Whether we're cleaning (preferences save) or parsing
4216 * @return string Signature text
4217 */
4218 function cleanSig( $text, $parsing = false ) {
4219 if ( !$parsing ) {
4220 global $wgTitle;
4221 $this->startExternalParse( $wgTitle, new ParserOptions(), OT_MSG );
4222 }
4223
4224 # FIXME: regex doesn't respect extension tags or nowiki
4225 # => Move this logic to braceSubstitution()
4226 $substWord = MagicWord::get( 'subst' );
4227 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4228 $substText = '{{' . $substWord->getSynonym( 0 );
4229
4230 $text = preg_replace( $substRegex, $substText, $text );
4231 $text = $this->cleanSigInSig( $text );
4232 $dom = $this->preprocessToDom( $text );
4233 $frame = new PPFrame( $this );
4234 $text = $frame->expand( $dom->documentElement );
4235
4236 if ( !$parsing ) {
4237 $text = $this->mStripState->unstripBoth( $text );
4238 }
4239
4240 return $text;
4241 }
4242
4243 /**
4244 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4245 * @param string $text
4246 * @return string Signature text with /~{3,5}/ removed
4247 */
4248 function cleanSigInSig( $text ) {
4249 $text = preg_replace( '/~{3,5}/', '', $text );
4250 return $text;
4251 }
4252
4253 /**
4254 * Set up some variables which are usually set up in parse()
4255 * so that an external function can call some class members with confidence
4256 * @public
4257 */
4258 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4259 $this->mTitle =& $title;
4260 $this->mOptions = $options;
4261 $this->setOutputType( $outputType );
4262 if ( $clearState ) {
4263 $this->clearState();
4264 }
4265 }
4266
4267 /**
4268 * Transform a MediaWiki message by replacing magic variables.
4269 *
4270 * For some unknown reason, it also expands templates, but only to the
4271 * first recursion level. This is wrong and broken, probably introduced
4272 * accidentally during refactoring, but probably relied upon by thousands
4273 * of users.
4274 *
4275 * @param string $text the text to transform
4276 * @param ParserOptions $options options
4277 * @return string the text with variables substituted
4278 * @public
4279 */
4280 function transformMsg( $text, $options ) {
4281 global $wgTitle;
4282 static $executing = false;
4283
4284 $fname = "Parser::transformMsg";
4285
4286 # Guard against infinite recursion
4287 if ( $executing ) {
4288 return $text;
4289 }
4290 $executing = true;
4291
4292 wfProfileIn($fname);
4293
4294 if ( $wgTitle && !( $wgTitle instanceof FakeTitle ) ) {
4295 $this->mTitle = $wgTitle;
4296 } else {
4297 $this->mTitle = Title::newFromText('msg');
4298 }
4299 $this->mOptions = $options;
4300 $this->setOutputType( OT_MSG );
4301 $this->clearState();
4302 $text = $this->replaceVariables( $text );
4303 $text = $this->mStripState->unstripBoth( $text );
4304
4305 $executing = false;
4306 wfProfileOut($fname);
4307 return $text;
4308 }
4309
4310 /**
4311 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4312 * The callback should have the following form:
4313 * function myParserHook( $text, $params, &$parser ) { ... }
4314 *
4315 * Transform and return $text. Use $parser for any required context, e.g. use
4316 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4317 *
4318 * @public
4319 *
4320 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4321 * @param mixed $callback The callback function (and object) to use for the tag
4322 *
4323 * @return The old value of the mTagHooks array associated with the hook
4324 */
4325 function setHook( $tag, $callback ) {
4326 $tag = strtolower( $tag );
4327 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4328 $this->mTagHooks[$tag] = $callback;
4329 $this->mStripList[] = $tag;
4330
4331 return $oldVal;
4332 }
4333
4334 function setTransparentTagHook( $tag, $callback ) {
4335 $tag = strtolower( $tag );
4336 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4337 $this->mTransparentTagHooks[$tag] = $callback;
4338
4339 return $oldVal;
4340 }
4341
4342 /**
4343 * Create a function, e.g. {{sum:1|2|3}}
4344 * The callback function should have the form:
4345 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4346 *
4347 * The callback may either return the text result of the function, or an array with the text
4348 * in element 0, and a number of flags in the other elements. The names of the flags are
4349 * specified in the keys. Valid flags are:
4350 * found The text returned is valid, stop processing the template. This
4351 * is on by default.
4352 * nowiki Wiki markup in the return value should be escaped
4353 * noparse Unsafe HTML tags should not be stripped, etc.
4354 * noargs Don't replace triple-brace arguments in the return value
4355 * isHTML The returned text is HTML, armour it against wikitext transformation
4356 *
4357 * @public
4358 *
4359 * @param string $id The magic word ID
4360 * @param mixed $callback The callback function (and object) to use
4361 * @param integer $flags a combination of the following flags:
4362 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4363 *
4364 * @return The old callback function for this name, if any
4365 */
4366 function setFunctionHook( $id, $callback, $flags = 0 ) {
4367 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4368 $this->mFunctionHooks[$id] = array( $callback, $flags );
4369
4370 # Add to function cache
4371 $mw = MagicWord::get( $id );
4372 if( !$mw )
4373 throw new MWException( 'Parser::setFunctionHook() expecting a magic word identifier.' );
4374
4375 $synonyms = $mw->getSynonyms();
4376 $sensitive = intval( $mw->isCaseSensitive() );
4377
4378 foreach ( $synonyms as $syn ) {
4379 # Case
4380 if ( !$sensitive ) {
4381 $syn = strtolower( $syn );
4382 }
4383 # Add leading hash
4384 if ( !( $flags & SFH_NO_HASH ) ) {
4385 $syn = '#' . $syn;
4386 }
4387 # Remove trailing colon
4388 if ( substr( $syn, -1, 1 ) == ':' ) {
4389 $syn = substr( $syn, 0, -1 );
4390 }
4391 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4392 }
4393 return $oldVal;
4394 }
4395
4396 /**
4397 * Get all registered function hook identifiers
4398 *
4399 * @return array
4400 */
4401 function getFunctionHooks() {
4402 return array_keys( $this->mFunctionHooks );
4403 }
4404
4405 /**
4406 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4407 * Placeholders created in Skin::makeLinkObj()
4408 * Returns an array of link CSS classes, indexed by PDBK.
4409 * $options is a bit field, RLH_FOR_UPDATE to select for update
4410 */
4411 function replaceLinkHolders( &$text, $options = 0 ) {
4412 global $wgUser;
4413 global $wgContLang;
4414
4415 $fname = 'Parser::replaceLinkHolders';
4416 wfProfileIn( $fname );
4417
4418 $pdbks = array();
4419 $colours = array();
4420 $linkcolour_ids = array();
4421 $sk = $this->mOptions->getSkin();
4422 $linkCache =& LinkCache::singleton();
4423
4424 if ( !empty( $this->mLinkHolders['namespaces'] ) ) {
4425 wfProfileIn( $fname.'-check' );
4426 $dbr = wfGetDB( DB_SLAVE );
4427 $page = $dbr->tableName( 'page' );
4428 $threshold = $wgUser->getOption('stubthreshold');
4429
4430 # Sort by namespace
4431 asort( $this->mLinkHolders['namespaces'] );
4432
4433 # Generate query
4434 $query = false;
4435 $current = null;
4436 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4437 # Make title object
4438 $title = $this->mLinkHolders['titles'][$key];
4439
4440 # Skip invalid entries.
4441 # Result will be ugly, but prevents crash.
4442 if ( is_null( $title ) ) {
4443 continue;
4444 }
4445 $pdbk = $pdbks[$key] = $title->getPrefixedDBkey();
4446
4447 # Check if it's a static known link, e.g. interwiki
4448 if ( $title->isAlwaysKnown() ) {
4449 $colours[$pdbk] = '';
4450 } elseif ( ( $id = $linkCache->getGoodLinkID( $pdbk ) ) != 0 ) {
4451 $colours[$pdbk] = '';
4452 $this->mOutput->addLink( $title, $id );
4453 } elseif ( $linkCache->isBadLink( $pdbk ) ) {
4454 $colours[$pdbk] = 'new';
4455 } elseif ( $title->getNamespace() == NS_SPECIAL && !SpecialPage::exists( $pdbk ) ) {
4456 $colours[$pdbk] = 'new';
4457 } else {
4458 # Not in the link cache, add it to the query
4459 if ( !isset( $current ) ) {
4460 $current = $ns;
4461 $query = "SELECT page_id, page_namespace, page_title";
4462 if ( $threshold > 0 ) {
4463 $query .= ', page_len, page_is_redirect';
4464 }
4465 $query .= " FROM $page WHERE (page_namespace=$ns AND page_title IN(";
4466 } elseif ( $current != $ns ) {
4467 $current = $ns;
4468 $query .= ")) OR (page_namespace=$ns AND page_title IN(";
4469 } else {
4470 $query .= ', ';
4471 }
4472
4473 $query .= $dbr->addQuotes( $this->mLinkHolders['dbkeys'][$key] );
4474 }
4475 }
4476 if ( $query ) {
4477 $query .= '))';
4478 if ( $options & RLH_FOR_UPDATE ) {
4479 $query .= ' FOR UPDATE';
4480 }
4481
4482 $res = $dbr->query( $query, $fname );
4483
4484 # Fetch data and form into an associative array
4485 # non-existent = broken
4486 while ( $s = $dbr->fetchObject($res) ) {
4487 $title = Title::makeTitle( $s->page_namespace, $s->page_title );
4488 $pdbk = $title->getPrefixedDBkey();
4489 $linkCache->addGoodLinkObj( $s->page_id, $title );
4490 $this->mOutput->addLink( $title, $s->page_id );
4491 $colours[$pdbk] = $sk->getLinkColour( $s, $threshold );
4492 //add id to the extension todolist
4493 $linkcolour_ids[$s->page_id] = $pdbk;
4494 }
4495 //pass an array of page_ids to an extension
4496 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4497 }
4498 wfProfileOut( $fname.'-check' );
4499
4500 # Do a second query for different language variants of links and categories
4501 if($wgContLang->hasVariants()){
4502 $linkBatch = new LinkBatch();
4503 $variantMap = array(); // maps $pdbkey_Variant => $keys (of link holders)
4504 $categoryMap = array(); // maps $category_variant => $category (dbkeys)
4505 $varCategories = array(); // category replacements oldDBkey => newDBkey
4506
4507 $categories = $this->mOutput->getCategoryLinks();
4508
4509 // Add variants of links to link batch
4510 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4511 $title = $this->mLinkHolders['titles'][$key];
4512 if ( is_null( $title ) )
4513 continue;
4514
4515 $pdbk = $title->getPrefixedDBkey();
4516 $titleText = $title->getText();
4517
4518 // generate all variants of the link title text
4519 $allTextVariants = $wgContLang->convertLinkToAllVariants($titleText);
4520
4521 // if link was not found (in first query), add all variants to query
4522 if ( !isset($colours[$pdbk]) ){
4523 foreach($allTextVariants as $textVariant){
4524 if($textVariant != $titleText){
4525 $variantTitle = Title::makeTitle( $ns, $textVariant );
4526 if(is_null($variantTitle)) continue;
4527 $linkBatch->addObj( $variantTitle );
4528 $variantMap[$variantTitle->getPrefixedDBkey()][] = $key;
4529 }
4530 }
4531 }
4532 }
4533
4534 // process categories, check if a category exists in some variant
4535 foreach( $categories as $category ){
4536 $variants = $wgContLang->convertLinkToAllVariants($category);
4537 foreach($variants as $variant){
4538 if($variant != $category){
4539 $variantTitle = Title::newFromDBkey( Title::makeName(NS_CATEGORY,$variant) );
4540 if(is_null($variantTitle)) continue;
4541 $linkBatch->addObj( $variantTitle );
4542 $categoryMap[$variant] = $category;
4543 }
4544 }
4545 }
4546
4547
4548 if(!$linkBatch->isEmpty()){
4549 // construct query
4550 $titleClause = $linkBatch->constructSet('page', $dbr);
4551
4552 $variantQuery = "SELECT page_id, page_namespace, page_title";
4553 if ( $threshold > 0 ) {
4554 $variantQuery .= ', page_len, page_is_redirect';
4555 }
4556
4557 $variantQuery .= " FROM $page WHERE $titleClause";
4558 if ( $options & RLH_FOR_UPDATE ) {
4559 $variantQuery .= ' FOR UPDATE';
4560 }
4561
4562 $varRes = $dbr->query( $variantQuery, $fname );
4563
4564 // for each found variants, figure out link holders and replace
4565 while ( $s = $dbr->fetchObject($varRes) ) {
4566
4567 $variantTitle = Title::makeTitle( $s->page_namespace, $s->page_title );
4568 $varPdbk = $variantTitle->getPrefixedDBkey();
4569 $vardbk = $variantTitle->getDBkey();
4570
4571 $holderKeys = array();
4572 if(isset($variantMap[$varPdbk])){
4573 $holderKeys = $variantMap[$varPdbk];
4574 $linkCache->addGoodLinkObj( $s->page_id, $variantTitle );
4575 $this->mOutput->addLink( $variantTitle, $s->page_id );
4576 }
4577
4578 // loop over link holders
4579 foreach($holderKeys as $key){
4580 $title = $this->mLinkHolders['titles'][$key];
4581 if ( is_null( $title ) ) continue;
4582
4583 $pdbk = $title->getPrefixedDBkey();
4584
4585 if(!isset($colours[$pdbk])){
4586 // found link in some of the variants, replace the link holder data
4587 $this->mLinkHolders['titles'][$key] = $variantTitle;
4588 $this->mLinkHolders['dbkeys'][$key] = $variantTitle->getDBkey();
4589
4590 // set pdbk and colour
4591 $pdbks[$key] = $varPdbk;
4592 $colours[$varPdbk] = $sk->getLinkColour( $s, $threshold );
4593 $linkcolour_ids[$s->page_id] = $pdbk;
4594 }
4595 wfRunHooks( 'GetLinkColours', array( $linkcolour_ids, &$colours ) );
4596 }
4597
4598 // check if the object is a variant of a category
4599 if(isset($categoryMap[$vardbk])){
4600 $oldkey = $categoryMap[$vardbk];
4601 if($oldkey != $vardbk)
4602 $varCategories[$oldkey]=$vardbk;
4603 }
4604 }
4605
4606 // rebuild the categories in original order (if there are replacements)
4607 if(count($varCategories)>0){
4608 $newCats = array();
4609 $originalCats = $this->mOutput->getCategories();
4610 foreach($originalCats as $cat => $sortkey){
4611 // make the replacement
4612 if( array_key_exists($cat,$varCategories) )
4613 $newCats[$varCategories[$cat]] = $sortkey;
4614 else $newCats[$cat] = $sortkey;
4615 }
4616 $this->mOutput->setCategoryLinks($newCats);
4617 }
4618 }
4619 }
4620
4621 # Construct search and replace arrays
4622 wfProfileIn( $fname.'-construct' );
4623 $replacePairs = array();
4624 foreach ( $this->mLinkHolders['namespaces'] as $key => $ns ) {
4625 $pdbk = $pdbks[$key];
4626 $searchkey = "<!--LINK $key-->";
4627 $title = $this->mLinkHolders['titles'][$key];
4628 if ( !isset( $colours[$pdbk] ) || $colours[$pdbk] == 'new' ) {
4629 $linkCache->addBadLinkObj( $title );
4630 $colours[$pdbk] = 'new';
4631 $this->mOutput->addLink( $title, 0 );
4632 $replacePairs[$searchkey] = $sk->makeBrokenLinkObj( $title,
4633 $this->mLinkHolders['texts'][$key],
4634 $this->mLinkHolders['queries'][$key] );
4635 } else {
4636 $replacePairs[$searchkey] = $sk->makeColouredLinkObj( $title, $colours[$pdbk],
4637 $this->mLinkHolders['texts'][$key],
4638 $this->mLinkHolders['queries'][$key] );
4639 }
4640 }
4641 $replacer = new HashtableReplacer( $replacePairs, 1 );
4642 wfProfileOut( $fname.'-construct' );
4643
4644 # Do the thing
4645 wfProfileIn( $fname.'-replace' );
4646 $text = preg_replace_callback(
4647 '/(<!--LINK .*?-->)/',
4648 $replacer->cb(),
4649 $text);
4650
4651 wfProfileOut( $fname.'-replace' );
4652 }
4653
4654 # Now process interwiki link holders
4655 # This is quite a bit simpler than internal links
4656 if ( !empty( $this->mInterwikiLinkHolders['texts'] ) ) {
4657 wfProfileIn( $fname.'-interwiki' );
4658 # Make interwiki link HTML
4659 $replacePairs = array();
4660 foreach( $this->mInterwikiLinkHolders['texts'] as $key => $link ) {
4661 $title = $this->mInterwikiLinkHolders['titles'][$key];
4662 $replacePairs[$key] = $sk->makeLinkObj( $title, $link );
4663 }
4664 $replacer = new HashtableReplacer( $replacePairs, 1 );
4665
4666 $text = preg_replace_callback(
4667 '/<!--IWLINK (.*?)-->/',
4668 $replacer->cb(),
4669 $text );
4670 wfProfileOut( $fname.'-interwiki' );
4671 }
4672
4673 wfProfileOut( $fname );
4674 return $colours;
4675 }
4676
4677 /**
4678 * Replace <!--LINK--> link placeholders with plain text of links
4679 * (not HTML-formatted).
4680 * @param string $text
4681 * @return string
4682 */
4683 function replaceLinkHoldersText( $text ) {
4684 $fname = 'Parser::replaceLinkHoldersText';
4685 wfProfileIn( $fname );
4686
4687 $text = preg_replace_callback(
4688 '/<!--(LINK|IWLINK) (.*?)-->/',
4689 array( &$this, 'replaceLinkHoldersTextCallback' ),
4690 $text );
4691
4692 wfProfileOut( $fname );
4693 return $text;
4694 }
4695
4696 /**
4697 * @param array $matches
4698 * @return string
4699 * @private
4700 */
4701 function replaceLinkHoldersTextCallback( $matches ) {
4702 $type = $matches[1];
4703 $key = $matches[2];
4704 if( $type == 'LINK' ) {
4705 if( isset( $this->mLinkHolders['texts'][$key] ) ) {
4706 return $this->mLinkHolders['texts'][$key];
4707 }
4708 } elseif( $type == 'IWLINK' ) {
4709 if( isset( $this->mInterwikiLinkHolders['texts'][$key] ) ) {
4710 return $this->mInterwikiLinkHolders['texts'][$key];
4711 }
4712 }
4713 return $matches[0];
4714 }
4715
4716 /**
4717 * Tag hook handler for 'pre'.
4718 */
4719 function renderPreTag( $text, $attribs ) {
4720 // Backwards-compatibility hack
4721 $content = StringUtils::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4722
4723 $attribs = Sanitizer::validateTagAttributes( $attribs, 'pre' );
4724 return wfOpenElement( 'pre', $attribs ) .
4725 Xml::escapeTagsOnly( $content ) .
4726 '</pre>';
4727 }
4728
4729 /**
4730 * Renders an image gallery from a text with one line per image.
4731 * text labels may be given by using |-style alternative text. E.g.
4732 * Image:one.jpg|The number "1"
4733 * Image:tree.jpg|A tree
4734 * given as text will return the HTML of a gallery with two images,
4735 * labeled 'The number "1"' and
4736 * 'A tree'.
4737 */
4738 function renderImageGallery( $text, $params ) {
4739 $ig = new ImageGallery();
4740 $ig->setContextTitle( $this->mTitle );
4741 $ig->setShowBytes( false );
4742 $ig->setShowFilename( false );
4743 $ig->setParser( $this );
4744 $ig->setHideBadImages();
4745 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4746 $ig->useSkin( $this->mOptions->getSkin() );
4747 $ig->mRevisionId = $this->mRevisionId;
4748
4749 if( isset( $params['caption'] ) ) {
4750 $caption = $params['caption'];
4751 $caption = htmlspecialchars( $caption );
4752 $caption = $this->replaceInternalLinks( $caption );
4753 $ig->setCaptionHtml( $caption );
4754 }
4755 if( isset( $params['perrow'] ) ) {
4756 $ig->setPerRow( $params['perrow'] );
4757 }
4758 if( isset( $params['widths'] ) ) {
4759 $ig->setWidths( $params['widths'] );
4760 }
4761 if( isset( $params['heights'] ) ) {
4762 $ig->setHeights( $params['heights'] );
4763 }
4764
4765 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4766
4767 $lines = explode( "\n", $text );
4768 foreach ( $lines as $line ) {
4769 # match lines like these:
4770 # Image:someimage.jpg|This is some image
4771 $matches = array();
4772 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4773 # Skip empty lines
4774 if ( count( $matches ) == 0 ) {
4775 continue;
4776 }
4777 $tp = Title::newFromText( $matches[1] );
4778 $nt =& $tp;
4779 if( is_null( $nt ) ) {
4780 # Bogus title. Ignore these so we don't bomb out later.
4781 continue;
4782 }
4783 if ( isset( $matches[3] ) ) {
4784 $label = $matches[3];
4785 } else {
4786 $label = '';
4787 }
4788
4789 $pout = $this->parse( $label,
4790 $this->mTitle,
4791 $this->mOptions,
4792 false, // Strip whitespace...?
4793 false // Don't clear state!
4794 );
4795 $html = $pout->getText();
4796
4797 $ig->add( $nt, $html );
4798
4799 # Only add real images (bug #5586)
4800 if ( $nt->getNamespace() == NS_IMAGE ) {
4801 $this->mOutput->addImage( $nt->getDBkey() );
4802 }
4803 }
4804 return $ig->toHTML();
4805 }
4806
4807 function getImageParams( $handler ) {
4808 if ( $handler ) {
4809 $handlerClass = get_class( $handler );
4810 } else {
4811 $handlerClass = '';
4812 }
4813 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4814 // Initialise static lists
4815 static $internalParamNames = array(
4816 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4817 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4818 'bottom', 'text-bottom' ),
4819 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4820 'upright', 'border' ),
4821 );
4822 static $internalParamMap;
4823 if ( !$internalParamMap ) {
4824 $internalParamMap = array();
4825 foreach ( $internalParamNames as $type => $names ) {
4826 foreach ( $names as $name ) {
4827 $magicName = str_replace( '-', '_', "img_$name" );
4828 $internalParamMap[$magicName] = array( $type, $name );
4829 }
4830 }
4831 }
4832
4833 // Add handler params
4834 $paramMap = $internalParamMap;
4835 if ( $handler ) {
4836 $handlerParamMap = $handler->getParamMap();
4837 foreach ( $handlerParamMap as $magic => $paramName ) {
4838 $paramMap[$magic] = array( 'handler', $paramName );
4839 }
4840 }
4841 $this->mImageParams[$handlerClass] = $paramMap;
4842 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4843 }
4844 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4845 }
4846
4847 /**
4848 * Parse image options text and use it to make an image
4849 */
4850 function makeImage( $title, $options ) {
4851 # @TODO: let the MediaHandler specify its transform parameters
4852 #
4853 # Check if the options text is of the form "options|alt text"
4854 # Options are:
4855 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4856 # * left no resizing, just left align. label is used for alt= only
4857 # * right same, but right aligned
4858 # * none same, but not aligned
4859 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4860 # * center center the image
4861 # * framed Keep original image size, no magnify-button.
4862 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4863 # * upright reduce width for upright images, rounded to full __0 px
4864 # * border draw a 1px border around the image
4865 # vertical-align values (no % or length right now):
4866 # * baseline
4867 # * sub
4868 # * super
4869 # * top
4870 # * text-top
4871 # * middle
4872 # * bottom
4873 # * text-bottom
4874
4875 $parts = array_map( 'trim', explode( '|', $options) );
4876 $sk = $this->mOptions->getSkin();
4877
4878 # Give extensions a chance to select the file revision for us
4879 $skip = $time = false;
4880 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time ) );
4881
4882 if ( $skip ) {
4883 return $sk->makeLinkObj( $title );
4884 }
4885
4886 # Get parameter map
4887 $file = wfFindFile( $title, $time );
4888 $handler = $file ? $file->getHandler() : false;
4889
4890 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4891
4892 # Process the input parameters
4893 $caption = '';
4894 $params = array( 'frame' => array(), 'handler' => array(),
4895 'horizAlign' => array(), 'vertAlign' => array() );
4896 foreach( $parts as $part ) {
4897 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4898 if ( isset( $paramMap[$magicName] ) ) {
4899 list( $type, $paramName ) = $paramMap[$magicName];
4900 $params[$type][$paramName] = $value;
4901
4902 // Special case; width and height come in one variable together
4903 if( $type == 'handler' && $paramName == 'width' ) {
4904 $m = array();
4905 if ( preg_match( '/^([0-9]*)x([0-9]*)$/', $value, $m ) ) {
4906 $params[$type]['width'] = intval( $m[1] );
4907 $params[$type]['height'] = intval( $m[2] );
4908 } else {
4909 $params[$type]['width'] = intval( $value );
4910 }
4911 }
4912 } else {
4913 $caption = $part;
4914 }
4915 }
4916
4917 # Process alignment parameters
4918 if ( $params['horizAlign'] ) {
4919 $params['frame']['align'] = key( $params['horizAlign'] );
4920 }
4921 if ( $params['vertAlign'] ) {
4922 $params['frame']['valign'] = key( $params['vertAlign'] );
4923 }
4924
4925 # Validate the handler parameters
4926 if ( $handler ) {
4927 foreach ( $params['handler'] as $name => $value ) {
4928 if ( !$handler->validateParam( $name, $value ) ) {
4929 unset( $params['handler'][$name] );
4930 }
4931 }
4932 }
4933
4934 # Strip bad stuff out of the alt text
4935 $alt = $this->replaceLinkHoldersText( $caption );
4936
4937 # make sure there are no placeholders in thumbnail attributes
4938 # that are later expanded to html- so expand them now and
4939 # remove the tags
4940 $alt = $this->mStripState->unstripBoth( $alt );
4941 $alt = Sanitizer::stripAllTags( $alt );
4942
4943 $params['frame']['alt'] = $alt;
4944 $params['frame']['caption'] = $caption;
4945
4946 # Linker does the rest
4947 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'] );
4948
4949 # Give the handler a chance to modify the parser object
4950 if ( $handler ) {
4951 $handler->parserTransformHook( $this, $file );
4952 }
4953
4954 return $ret;
4955 }
4956
4957 /**
4958 * Set a flag in the output object indicating that the content is dynamic and
4959 * shouldn't be cached.
4960 */
4961 function disableCache() {
4962 wfDebug( "Parser output marked as uncacheable.\n" );
4963 $this->mOutput->mCacheTime = -1;
4964 }
4965
4966 /**#@+
4967 * Callback from the Sanitizer for expanding items found in HTML attribute
4968 * values, so they can be safely tested and escaped.
4969 * @param string $text
4970 * @param PPFrame $frame
4971 * @return string
4972 * @private
4973 */
4974 function attributeStripCallback( &$text, $frame = false ) {
4975 $text = $this->replaceVariables( $text, $frame );
4976 $text = $this->mStripState->unstripBoth( $text );
4977 return $text;
4978 }
4979
4980 /**#@-*/
4981
4982 /**#@+
4983 * Accessor/mutator
4984 */
4985 function Title( $x = NULL ) { return wfSetVar( $this->mTitle, $x ); }
4986 function Options( $x = NULL ) { return wfSetVar( $this->mOptions, $x ); }
4987 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType, $x ); }
4988 /**#@-*/
4989
4990 /**#@+
4991 * Accessor
4992 */
4993 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks), array_keys( $this->mTagHooks ) ); }
4994 /**#@-*/
4995
4996
4997 /**
4998 * Break wikitext input into sections, and either pull or replace
4999 * some particular section's text.
5000 *
5001 * External callers should use the getSection and replaceSection methods.
5002 *
5003 * @param string $text Page wikitext
5004 * @param string $section A section identifier string of the form:
5005 * <flag1> - <flag2> - ... - <section number>
5006 *
5007 * Currently the only recognised flag is "T", which means the target section number
5008 * was derived during a template inclusion parse, in other words this is a template
5009 * section edit link. If no flags are given, it was an ordinary section edit link.
5010 * This flag is required to avoid a section numbering mismatch when a section is
5011 * enclosed by <includeonly> (bug 6563).
5012 *
5013 * The section number 0 pulls the text before the first heading; other numbers will
5014 * pull the given section along with its lower-level subsections. If the section is
5015 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5016 *
5017 * @param string $mode One of "get" or "replace"
5018 * @param string $newText Replacement text for section data.
5019 * @return string for "get", the extracted section text.
5020 * for "replace", the whole page with the section replaced.
5021 */
5022 private function extractSections( $text, $section, $mode, $newText='' ) {
5023 global $wgTitle;
5024 $this->clearState();
5025 $this->mTitle = $wgTitle; // not generally used but removes an ugly failure mode
5026 $this->mOptions = new ParserOptions;
5027 $this->setOutputType( OT_WIKI );
5028 $curIndex = 0;
5029 $outText = '';
5030 $frame = new PPFrame( $this );
5031
5032 // Process section extraction flags
5033 $flags = 0;
5034 $sectionParts = explode( '-', $section );
5035 $sectionIndex = array_pop( $sectionParts );
5036 foreach ( $sectionParts as $part ) {
5037 if ( $part == 'T' ) {
5038 $flags |= self::PTD_FOR_INCLUSION;
5039 }
5040 }
5041 // Preprocess the text
5042 $dom = $this->preprocessToDom( $text, $flags );
5043 $root = $dom->documentElement;
5044
5045 // <h> nodes indicate section breaks
5046 // They can only occur at the top level, so we can find them by iterating the root's children
5047 $node = $root->firstChild;
5048
5049 // Find the target section
5050 if ( $sectionIndex == 0 ) {
5051 // Section zero doesn't nest, level=big
5052 $targetLevel = 1000;
5053 } else {
5054 while ( $node ) {
5055 if ( $node->nodeName == 'h' ) {
5056 if ( $curIndex + 1 == $sectionIndex ) {
5057 break;
5058 }
5059 $curIndex++;
5060 }
5061 if ( $mode == 'replace' ) {
5062 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5063 }
5064 $node = $node->nextSibling;
5065 }
5066 if ( $node ) {
5067 $targetLevel = $node->getAttribute( 'level' );
5068 }
5069 }
5070
5071 if ( !$node ) {
5072 // Not found
5073 if ( $mode == 'get' ) {
5074 return $newText;
5075 } else {
5076 return $text;
5077 }
5078 }
5079
5080 // Find the end of the section, including nested sections
5081 do {
5082 if ( $node->nodeName == 'h' ) {
5083 $curIndex++;
5084 $curLevel = $node->getAttribute( 'level' );
5085 if ( $curIndex != $sectionIndex && $curLevel <= $targetLevel ) {
5086 break;
5087 }
5088 }
5089 if ( $mode == 'get' ) {
5090 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5091 }
5092 $node = $node->nextSibling;
5093 } while ( $node );
5094
5095 // Write out the remainder (in replace mode only)
5096 if ( $mode == 'replace' ) {
5097 // Output the replacement text
5098 // Add two newlines on -- trailing whitespace in $newText is conventionally
5099 // stripped by the editor, so we need both newlines to restore the paragraph gap
5100 $outText .= $newText . "\n\n";
5101 while ( $node ) {
5102 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5103 $node = $node->nextSibling;
5104 }
5105 }
5106
5107 if ( is_string( $outText ) ) {
5108 // Re-insert stripped tags
5109 $outText = trim( $this->mStripState->unstripBoth( $outText ) );
5110 }
5111
5112 return $outText;
5113 }
5114
5115 /**
5116 * This function returns the text of a section, specified by a number ($section).
5117 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5118 * the first section before any such heading (section 0).
5119 *
5120 * If a section contains subsections, these are also returned.
5121 *
5122 * @param string $text text to look in
5123 * @param string $section section identifier
5124 * @param string $deftext default to return if section is not found
5125 * @return string text of the requested section
5126 */
5127 public function getSection( $text, $section, $deftext='' ) {
5128 return $this->extractSections( $text, $section, "get", $deftext );
5129 }
5130
5131 public function replaceSection( $oldtext, $section, $text ) {
5132 return $this->extractSections( $oldtext, $section, "replace", $text );
5133 }
5134
5135 /**
5136 * Get the timestamp associated with the current revision, adjusted for
5137 * the default server-local timestamp
5138 */
5139 function getRevisionTimestamp() {
5140 if ( is_null( $this->mRevisionTimestamp ) ) {
5141 wfProfileIn( __METHOD__ );
5142 global $wgContLang;
5143 $dbr = wfGetDB( DB_SLAVE );
5144 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5145 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
5146
5147 // Normalize timestamp to internal MW format for timezone processing.
5148 // This has the added side-effect of replacing a null value with
5149 // the current time, which gives us more sensible behavior for
5150 // previews.
5151 $timestamp = wfTimestamp( TS_MW, $timestamp );
5152
5153 // The cryptic '' timezone parameter tells to use the site-default
5154 // timezone offset instead of the user settings.
5155 //
5156 // Since this value will be saved into the parser cache, served
5157 // to other users, and potentially even used inside links and such,
5158 // it needs to be consistent for all visitors.
5159 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5160
5161 wfProfileOut( __METHOD__ );
5162 }
5163 return $this->mRevisionTimestamp;
5164 }
5165
5166 /**
5167 * Mutator for $mDefaultSort
5168 *
5169 * @param $sort New value
5170 */
5171 public function setDefaultSort( $sort ) {
5172 $this->mDefaultSort = $sort;
5173 }
5174
5175 /**
5176 * Accessor for $mDefaultSort
5177 * Will use the title/prefixed title if none is set
5178 *
5179 * @return string
5180 */
5181 public function getDefaultSort() {
5182 if( $this->mDefaultSort !== false ) {
5183 return $this->mDefaultSort;
5184 } else {
5185 return $this->mTitle->getNamespace() == NS_CATEGORY
5186 ? $this->mTitle->getText()
5187 : $this->mTitle->getPrefixedText();
5188 }
5189 }
5190
5191 /**
5192 * Try to guess the section anchor name based on a wikitext fragment
5193 * presumably extracted from a heading, for example "Header" from
5194 * "== Header ==".
5195 */
5196 public function guessSectionNameFromWikiText( $text ) {
5197 # Strip out wikitext links(they break the anchor)
5198 $text = $this->stripSectionName( $text );
5199 $headline = Sanitizer::decodeCharReferences( $text );
5200 # strip out HTML
5201 $headline = StringUtils::delimiterReplace( '<', '>', '', $headline );
5202 $headline = trim( $headline );
5203 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5204 $replacearray = array(
5205 '%3A' => ':',
5206 '%' => '.'
5207 );
5208 return str_replace(
5209 array_keys( $replacearray ),
5210 array_values( $replacearray ),
5211 $sectionanchor );
5212 }
5213
5214 /**
5215 * Strips a text string of wikitext for use in a section anchor
5216 *
5217 * Accepts a text string and then removes all wikitext from the
5218 * string and leaves only the resultant text (i.e. the result of
5219 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5220 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5221 * to create valid section anchors by mimicing the output of the
5222 * parser when headings are parsed.
5223 *
5224 * @param $text string Text string to be stripped of wikitext
5225 * for use in a Section anchor
5226 * @return Filtered text string
5227 */
5228 public function stripSectionName( $text ) {
5229 # Strip internal link markup
5230 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5231 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5232
5233 # Strip external link markup (FIXME: Not Tolerant to blank link text
5234 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5235 # on how many empty links there are on the page - need to figure that out.
5236 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5237
5238 # Parse wikitext quotes (italics & bold)
5239 $text = $this->doQuotes($text);
5240
5241 # Strip HTML tags
5242 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5243 return $text;
5244 }
5245
5246 /**
5247 * strip/replaceVariables/unstrip for preprocessor regression testing
5248 */
5249 function srvus( $text ) {
5250 $text = $this->replaceVariables( $text );
5251 $text = $this->mStripState->unstripBoth( $text );
5252 $text = Sanitizer::removeHTMLtags( $text );
5253 return $text;
5254 }
5255 }
5256
5257 /**
5258 * @todo document, briefly.
5259 * @addtogroup Parser
5260 */
5261 class OnlyIncludeReplacer {
5262 var $output = '';
5263
5264 function replace( $matches ) {
5265 if ( substr( $matches[1], -1 ) == "\n" ) {
5266 $this->output .= substr( $matches[1], 0, -1 );
5267 } else {
5268 $this->output .= $matches[1];
5269 }
5270 }
5271 }
5272
5273 /**
5274 * @todo document, briefly.
5275 * @addtogroup Parser
5276 */
5277 class StripState {
5278 var $general, $nowiki;
5279
5280 function __construct() {
5281 $this->general = new ReplacementArray;
5282 $this->nowiki = new ReplacementArray;
5283 }
5284
5285 function unstripGeneral( $text ) {
5286 wfProfileIn( __METHOD__ );
5287 do {
5288 $oldText = $text;
5289 $text = $this->general->replace( $text );
5290 } while ( $text != $oldText );
5291 wfProfileOut( __METHOD__ );
5292 return $text;
5293 }
5294
5295 function unstripNoWiki( $text ) {
5296 wfProfileIn( __METHOD__ );
5297 do {
5298 $oldText = $text;
5299 $text = $this->nowiki->replace( $text );
5300 } while ( $text != $oldText );
5301 wfProfileOut( __METHOD__ );
5302 return $text;
5303 }
5304
5305 function unstripBoth( $text ) {
5306 wfProfileIn( __METHOD__ );
5307 do {
5308 $oldText = $text;
5309 $text = $this->general->replace( $text );
5310 $text = $this->nowiki->replace( $text );
5311 } while ( $text != $oldText );
5312 wfProfileOut( __METHOD__ );
5313 return $text;
5314 }
5315 }
5316
5317 /**
5318 * An expansion frame, used as a context to expand the result of preprocessToDom()
5319 */
5320 class PPFrame {
5321 var $parser, $title;
5322 var $titleCache;
5323
5324 const NO_ARGS = 1;
5325 const NO_TEMPLATES = 2;
5326 const STRIP_COMMENTS = 4;
5327 const NO_IGNORE = 8;
5328
5329 const RECOVER_ORIG = 11;
5330
5331 /**
5332 * Construct a new preprocessor frame.
5333 * @param Parser $parser The parent parser
5334 * @param Title $title The context title, or false if there isn't one
5335 */
5336 function __construct( $parser ) {
5337 $this->parser = $parser;
5338 $this->title = $parser->mTitle;
5339 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
5340 }
5341
5342 /**
5343 * Create a new child frame
5344 * $args is optionally a DOMNodeList containing the template arguments
5345 */
5346 function newChild( $args = false, $title = false ) {
5347 $assocArgs = array();
5348 if ( $title === false ) {
5349 $title = $this->title;
5350 }
5351 if ( $args !== false ) {
5352 $xpath = false;
5353 foreach ( $args as $arg ) {
5354 if ( !$xpath ) {
5355 $xpath = new DOMXPath( $arg->ownerDocument );
5356 }
5357
5358 $nameNodes = $xpath->query( 'name', $arg );
5359 if ( $nameNodes->item( 0 )->hasAttributes() ) {
5360 // Numbered parameter
5361 $name = $nameNodes->item( 0 )->attributes->getNamedItem( 'index' )->textContent;
5362 } else {
5363 // Named parameter
5364 $name = $this->expand( $nameNodes->item( 0 ), PPFrame::STRIP_COMMENTS );
5365 }
5366
5367 $value = $xpath->query( 'value', $arg );
5368 $assocArgs[$name] = $value->item( 0 );
5369 }
5370 }
5371 return new PPTemplateFrame( $this->parser, $this, $assocArgs, $title );
5372 }
5373
5374 /**
5375 * Expand a DOMNode describing a preprocessed document into plain wikitext,
5376 * using the current context
5377 * @param $root the node
5378 */
5379 function expand( $root, $flags = 0 ) {
5380 if ( is_string( $root ) ) {
5381 return $root;
5382 }
5383
5384 if ( $this->parser->ot['html']
5385 && ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
5386 {
5387 return $this->parser->insertStripItem( '<!-- node-count limit exceeded -->' );
5388 }
5389
5390 if ( is_array( $root ) ) {
5391 $s = '';
5392 foreach ( $root as $node ) {
5393 $s .= $this->expand( $node, $flags );
5394 }
5395 } elseif ( $root instanceof DOMNodeList ) {
5396 $s = '';
5397 foreach ( $root as $node ) {
5398 $s .= $this->expand( $node, $flags );
5399 }
5400 } elseif ( $root instanceof DOMNode ) {
5401 if ( $root->nodeType == XML_TEXT_NODE ) {
5402 $s = $root->nodeValue;
5403 } elseif ( $root->nodeName == 'template' ) {
5404 # Double-brace expansion
5405 $xpath = new DOMXPath( $root->ownerDocument );
5406 $titles = $xpath->query( 'title', $root );
5407 $title = $titles->item( 0 );
5408 $parts = $xpath->query( 'part', $root );
5409 if ( $flags & self::NO_TEMPLATES ) {
5410 $s = '{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}';
5411 } else {
5412 $lineStart = $root->getAttribute( 'lineStart' );
5413 $params = array(
5414 'title' => $title,
5415 'parts' => $parts,
5416 'lineStart' => $lineStart,
5417 'text' => 'FIXME' );
5418 $s = $this->parser->braceSubstitution( $params, $this );
5419 }
5420 } elseif ( $root->nodeName == 'tplarg' ) {
5421 # Triple-brace expansion
5422 $xpath = new DOMXPath( $root->ownerDocument );
5423 $titles = $xpath->query( 'title', $root );
5424 $title = $titles->item( 0 );
5425 $parts = $xpath->query( 'part', $root );
5426 if ( $flags & self::NO_ARGS || $this->parser->ot['msg'] ) {
5427 $s = '{{{' . $this->implodeWithFlags( '|', $flags, $title, $parts ) . '}}}';
5428 } else {
5429 $params = array( 'title' => $title, 'parts' => $parts, 'text' => 'FIXME' );
5430 $s = $this->parser->argSubstitution( $params, $this );
5431 }
5432 } elseif ( $root->nodeName == 'comment' ) {
5433 # HTML-style comment
5434 if ( $this->parser->ot['html']
5435 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
5436 || ( $flags & self::STRIP_COMMENTS ) )
5437 {
5438 $s = '';
5439 } else {
5440 $s = $root->textContent;
5441 }
5442 } elseif ( $root->nodeName == 'ignore' ) {
5443 # Output suppression used by <includeonly> etc.
5444 # OT_WIKI will only respect <ignore> in substed templates.
5445 # The other output types respect it unless NO_IGNORE is set.
5446 # extractSections() sets NO_IGNORE and so never respects it.
5447 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
5448 $s = $root->textContent;
5449 } else {
5450 $s = '';
5451 }
5452 } elseif ( $root->nodeName == 'ext' ) {
5453 # Extension tag
5454 $xpath = new DOMXPath( $root->ownerDocument );
5455 $names = $xpath->query( 'name', $root );
5456 $attrs = $xpath->query( 'attr', $root );
5457 $inners = $xpath->query( 'inner', $root );
5458 $closes = $xpath->query( 'close', $root );
5459 $params = array(
5460 'name' => $names->item( 0 ),
5461 'attr' => $attrs->length > 0 ? $attrs->item( 0 ) : null,
5462 'inner' => $inners->length > 0 ? $inners->item( 0 ) : null,
5463 'close' => $closes->length > 0 ? $closes->item( 0 ) : null,
5464 );
5465 $s = $this->parser->extensionSubstitution( $params, $this );
5466 } elseif ( $root->nodeName == 'h' ) {
5467 # Heading
5468 $s = $this->expand( $root->childNodes, $flags );
5469
5470 if ( $this->parser->ot['html'] ) {
5471 # Insert heading index marker
5472 $headingIndex = $root->getAttribute( 'i' );
5473 $titleText = $this->title->getPrefixedDBkey();
5474 $this->parser->mHeadings[] = array( $titleText, $headingIndex );
5475 $serial = count( $this->parser->mHeadings ) - 1;
5476 $marker = "{$this->parser->mUniqPrefix}-h-$serial-{$this->parser->mMarkerSuffix}";
5477 $count = $root->getAttribute( 'level' );
5478 $s = substr( $s, 0, $count ) . $marker . substr( $s, $count );
5479 $this->parser->mStripState->general->setPair( $marker, '' );
5480 }
5481 } else {
5482 # Generic recursive expansion
5483 $s = '';
5484 for ( $node = $root->firstChild; $node; $node = $node->nextSibling ) {
5485 if ( $node->nodeType == XML_TEXT_NODE ) {
5486 $s .= $node->nodeValue;
5487 } elseif ( $node->nodeType == XML_ELEMENT_NODE ) {
5488 $s .= $this->expand( $node, $flags );
5489 }
5490 }
5491 }
5492 } else {
5493 throw new MWException( __METHOD__.': Invalid parameter type' );
5494 }
5495 return $s;
5496 }
5497
5498 function implodeWithFlags( $sep, $flags /*, ... */ ) {
5499 $args = array_slice( func_get_args(), 2 );
5500
5501 $first = true;
5502 $s = '';
5503 foreach ( $args as $root ) {
5504 if ( !is_array( $root ) && !( $root instanceof DOMNodeList ) ) {
5505 $root = array( $root );
5506 }
5507 foreach ( $root as $node ) {
5508 if ( $first ) {
5509 $first = false;
5510 } else {
5511 $s .= $sep;
5512 }
5513 $s .= $this->expand( $node, $flags );
5514 }
5515 }
5516 return $s;
5517 }
5518
5519 function implode( $sep /*, ... */ ) {
5520 $args = func_get_args();
5521 $args = array_merge( array_slice( $args, 0, 1 ), array( 0 ), array_slice( $args, 1 ) );
5522 return call_user_func_array( array( $this, 'implodeWithFlags' ), $args );
5523 }
5524
5525 /**
5526 * Split an <arg> or <template> node into a three-element array:
5527 * DOMNode name, string index and DOMNode value
5528 */
5529 function splitBraceNode( $node ) {
5530 $xpath = new DOMXPath( $node->ownerDocument );
5531 $names = $xpath->query( 'name', $node );
5532 $values = $xpath->query( 'value', $node );
5533 if ( !$names->length || !$values->length ) {
5534 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
5535 }
5536 $name = $names->item( 0 );
5537 $index = $name->getAttribute( 'index' );
5538 return array( $name, $index, $values->item( 0 ) );
5539 }
5540
5541 /**
5542 * Split an <ext> node into an associative array containing name, attr, inner and close
5543 * All values in the resulting array are DOMNodes. Inner and close are optional.
5544 */
5545 function splitExtNode( $node ) {
5546 $xpath = new DOMXPath( $node->ownerDocument );
5547 $names = $xpath->query( 'name', $node );
5548 $attrs = $xpath->query( 'attr', $node );
5549 $inners = $xpath->query( 'inner', $node );
5550 $closes = $xpath->query( 'close', $node );
5551 if ( !$names->length || !$attrs->length ) {
5552 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
5553 }
5554 $parts = array(
5555 'name' => $names->item( 0 ),
5556 'attr' => $attrs->item( 0 ) );
5557 if ( $inners->length ) {
5558 $parts['inner'] = $inners->item( 0 );
5559 }
5560 if ( $closes->length ) {
5561 $parts['close'] = $closes->item( 0 );
5562 }
5563 return $parts;
5564 }
5565
5566 function __toString() {
5567 return 'frame{}';
5568 }
5569
5570 function getPDBK( $level = false ) {
5571 if ( $level === false ) {
5572 return $this->title->getPrefixedDBkey();
5573 } else {
5574 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
5575 }
5576 }
5577 }
5578
5579 /**
5580 * Expansion frame with template arguments
5581 */
5582 class PPTemplateFrame extends PPFrame {
5583 var $parser, $args, $parent;
5584 var $titleCache;
5585
5586 function __construct( $parser, $parent = false, $args = array(), $title = false ) {
5587 $this->parser = $parser;
5588 $this->parent = $parent;
5589 $this->args = $args;
5590 $this->title = $title;
5591 $this->titleCache = $parent->titleCache;
5592 $this->titleCache[] = $title ? $title->getPrefixedDBkey() : false;
5593 }
5594
5595 function __toString() {
5596 $s = 'tplframe{';
5597 $first = true;
5598 foreach ( $this->args as $name => $value ) {
5599 if ( $first ) {
5600 $first = false;
5601 } else {
5602 $s .= ', ';
5603 }
5604 $s .= "\"$name\":\"" .
5605 str_replace( '"', '\\"', $value->ownerDocument->saveXML( $value ) ) . '"';
5606 }
5607 $s .= '}';
5608 return $s;
5609 }
5610 }
5611