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