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