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