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