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