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