Merge "(bug 32368) Add ParserCloned hook"
[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, 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, 'free',
1318 $this->getExternalLinkAttribs( $url ) );
1319 # Register it in the output object...
1320 # Replace unnecessary URL escape codes with their equivalent characters
1321 $pasteurized = self::replaceUnusualEscapes( $url );
1322 $this->mOutput->addExternalLink( $pasteurized );
1323 }
1324 wfProfileOut( __METHOD__ );
1325 return $text . $trail;
1326 }
1327
1328
1329 /**
1330 * Parse headers and return html
1331 *
1332 * @private
1333 *
1334 * @param $text string
1335 *
1336 * @return string
1337 */
1338 function doHeadings( $text ) {
1339 wfProfileIn( __METHOD__ );
1340 for ( $i = 6; $i >= 1; --$i ) {
1341 $h = str_repeat( '=', $i );
1342 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1343 "<h$i>\\1</h$i>", $text );
1344 }
1345 wfProfileOut( __METHOD__ );
1346 return $text;
1347 }
1348
1349 /**
1350 * Replace single quotes with HTML markup
1351 * @private
1352 *
1353 * @param $text string
1354 *
1355 * @return string the altered text
1356 */
1357 function doAllQuotes( $text ) {
1358 wfProfileIn( __METHOD__ );
1359 $outtext = '';
1360 $lines = StringUtils::explode( "\n", $text );
1361 foreach ( $lines as $line ) {
1362 $outtext .= $this->doQuotes( $line ) . "\n";
1363 }
1364 $outtext = substr( $outtext, 0,-1 );
1365 wfProfileOut( __METHOD__ );
1366 return $outtext;
1367 }
1368
1369 /**
1370 * Helper function for doAllQuotes()
1371 *
1372 * @param $text string
1373 *
1374 * @return string
1375 */
1376 public function doQuotes( $text ) {
1377 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1378 if ( count( $arr ) == 1 ) {
1379 return $text;
1380 } else {
1381 # First, do some preliminary work. This may shift some apostrophes from
1382 # being mark-up to being text. It also counts the number of occurrences
1383 # of bold and italics mark-ups.
1384 $numbold = 0;
1385 $numitalics = 0;
1386 for ( $i = 0; $i < count( $arr ); $i++ ) {
1387 if ( ( $i % 2 ) == 1 ) {
1388 # If there are ever four apostrophes, assume the first is supposed to
1389 # be text, and the remaining three constitute mark-up for bold text.
1390 if ( strlen( $arr[$i] ) == 4 ) {
1391 $arr[$i-1] .= "'";
1392 $arr[$i] = "'''";
1393 } elseif ( strlen( $arr[$i] ) > 5 ) {
1394 # If there are more than 5 apostrophes in a row, assume they're all
1395 # text except for the last 5.
1396 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1397 $arr[$i] = "'''''";
1398 }
1399 # Count the number of occurrences of bold and italics mark-ups.
1400 # We are not counting sequences of five apostrophes.
1401 if ( strlen( $arr[$i] ) == 2 ) {
1402 $numitalics++;
1403 } elseif ( strlen( $arr[$i] ) == 3 ) {
1404 $numbold++;
1405 } elseif ( strlen( $arr[$i] ) == 5 ) {
1406 $numitalics++;
1407 $numbold++;
1408 }
1409 }
1410 }
1411
1412 # If there is an odd number of both bold and italics, it is likely
1413 # that one of the bold ones was meant to be an apostrophe followed
1414 # by italics. Which one we cannot know for certain, but it is more
1415 # likely to be one that has a single-letter word before it.
1416 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1417 $i = 0;
1418 $firstsingleletterword = -1;
1419 $firstmultiletterword = -1;
1420 $firstspace = -1;
1421 foreach ( $arr as $r ) {
1422 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1423 $x1 = substr( $arr[$i-1], -1 );
1424 $x2 = substr( $arr[$i-1], -2, 1 );
1425 if ( $x1 === ' ' ) {
1426 if ( $firstspace == -1 ) {
1427 $firstspace = $i;
1428 }
1429 } elseif ( $x2 === ' ') {
1430 if ( $firstsingleletterword == -1 ) {
1431 $firstsingleletterword = $i;
1432 }
1433 } else {
1434 if ( $firstmultiletterword == -1 ) {
1435 $firstmultiletterword = $i;
1436 }
1437 }
1438 }
1439 $i++;
1440 }
1441
1442 # If there is a single-letter word, use it!
1443 if ( $firstsingleletterword > -1 ) {
1444 $arr[$firstsingleletterword] = "''";
1445 $arr[$firstsingleletterword-1] .= "'";
1446 } elseif ( $firstmultiletterword > -1 ) {
1447 # If not, but there's a multi-letter word, use that one.
1448 $arr[$firstmultiletterword] = "''";
1449 $arr[$firstmultiletterword-1] .= "'";
1450 } elseif ( $firstspace > -1 ) {
1451 # ... otherwise use the first one that has neither.
1452 # (notice that it is possible for all three to be -1 if, for example,
1453 # there is only one pentuple-apostrophe in the line)
1454 $arr[$firstspace] = "''";
1455 $arr[$firstspace-1] .= "'";
1456 }
1457 }
1458
1459 # Now let's actually convert our apostrophic mush to HTML!
1460 $output = '';
1461 $buffer = '';
1462 $state = '';
1463 $i = 0;
1464 foreach ( $arr as $r ) {
1465 if ( ( $i % 2 ) == 0 ) {
1466 if ( $state === 'both' ) {
1467 $buffer .= $r;
1468 } else {
1469 $output .= $r;
1470 }
1471 } else {
1472 if ( strlen( $r ) == 2 ) {
1473 if ( $state === 'i' ) {
1474 $output .= '</i>'; $state = '';
1475 } elseif ( $state === 'bi' ) {
1476 $output .= '</i>'; $state = 'b';
1477 } elseif ( $state === 'ib' ) {
1478 $output .= '</b></i><b>'; $state = 'b';
1479 } elseif ( $state === 'both' ) {
1480 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1481 } else { # $state can be 'b' or ''
1482 $output .= '<i>'; $state .= 'i';
1483 }
1484 } elseif ( strlen( $r ) == 3 ) {
1485 if ( $state === 'b' ) {
1486 $output .= '</b>'; $state = '';
1487 } elseif ( $state === 'bi' ) {
1488 $output .= '</i></b><i>'; $state = 'i';
1489 } elseif ( $state === 'ib' ) {
1490 $output .= '</b>'; $state = 'i';
1491 } elseif ( $state === 'both' ) {
1492 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1493 } else { # $state can be 'i' or ''
1494 $output .= '<b>'; $state .= 'b';
1495 }
1496 } elseif ( strlen( $r ) == 5 ) {
1497 if ( $state === 'b' ) {
1498 $output .= '</b><i>'; $state = 'i';
1499 } elseif ( $state === 'i' ) {
1500 $output .= '</i><b>'; $state = 'b';
1501 } elseif ( $state === 'bi' ) {
1502 $output .= '</i></b>'; $state = '';
1503 } elseif ( $state === 'ib' ) {
1504 $output .= '</b></i>'; $state = '';
1505 } elseif ( $state === 'both' ) {
1506 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1507 } else { # ($state == '')
1508 $buffer = ''; $state = 'both';
1509 }
1510 }
1511 }
1512 $i++;
1513 }
1514 # Now close all remaining tags. Notice that the order is important.
1515 if ( $state === 'b' || $state === 'ib' ) {
1516 $output .= '</b>';
1517 }
1518 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1519 $output .= '</i>';
1520 }
1521 if ( $state === 'bi' ) {
1522 $output .= '</b>';
1523 }
1524 # There might be lonely ''''', so make sure we have a buffer
1525 if ( $state === 'both' && $buffer ) {
1526 $output .= '<b><i>'.$buffer.'</i></b>';
1527 }
1528 return $output;
1529 }
1530 }
1531
1532 /**
1533 * Replace external links (REL)
1534 *
1535 * Note: this is all very hackish and the order of execution matters a lot.
1536 * Make sure to run maintenance/parserTests.php if you change this code.
1537 *
1538 * @private
1539 *
1540 * @param $text string
1541 *
1542 * @throws MWException
1543 * @return string
1544 */
1545 function replaceExternalLinks( $text ) {
1546 wfProfileIn( __METHOD__ );
1547
1548 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1549 if ( $bits === false ) {
1550 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1551 }
1552 $s = array_shift( $bits );
1553
1554 $i = 0;
1555 while ( $i<count( $bits ) ) {
1556 $url = $bits[$i++];
1557 // @todo FIXME: Unused variable.
1558 $protocol = $bits[$i++];
1559 $text = $bits[$i++];
1560 $trail = $bits[$i++];
1561
1562 # The characters '<' and '>' (which were escaped by
1563 # removeHTMLtags()) should not be included in
1564 # URLs, per RFC 2396.
1565 $m2 = array();
1566 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1567 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1568 $url = substr( $url, 0, $m2[0][1] );
1569 }
1570
1571 # If the link text is an image URL, replace it with an <img> tag
1572 # This happened by accident in the original parser, but some people used it extensively
1573 $img = $this->maybeMakeExternalImage( $text );
1574 if ( $img !== false ) {
1575 $text = $img;
1576 }
1577
1578 $dtrail = '';
1579
1580 # Set linktype for CSS - if URL==text, link is essentially free
1581 $linktype = ( $text === $url ) ? 'free' : 'text';
1582
1583 # No link text, e.g. [http://domain.tld/some.link]
1584 if ( $text == '' ) {
1585 # Autonumber
1586 $langObj = $this->getTargetLanguage();
1587 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1588 $linktype = 'autonumber';
1589 } else {
1590 # Have link text, e.g. [http://domain.tld/some.link text]s
1591 # Check for trail
1592 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1593 }
1594
1595 $text = $this->getConverterLanguage()->markNoConversion( $text );
1596
1597 $url = Sanitizer::cleanUrl( $url );
1598
1599 # Use the encoded URL
1600 # This means that users can paste URLs directly into the text
1601 # Funny characters like ö aren't valid in URLs anyway
1602 # This was changed in August 2004
1603 $s .= Linker::makeExternalLink( $url, $text, false, $linktype,
1604 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1605
1606 # Register link in the output object.
1607 # Replace unnecessary URL escape codes with the referenced character
1608 # This prevents spammers from hiding links from the filters
1609 $pasteurized = self::replaceUnusualEscapes( $url );
1610 $this->mOutput->addExternalLink( $pasteurized );
1611 }
1612
1613 wfProfileOut( __METHOD__ );
1614 return $s;
1615 }
1616
1617 /**
1618 * Get an associative array of additional HTML attributes appropriate for a
1619 * particular external link. This currently may include rel => nofollow
1620 * (depending on configuration, namespace, and the URL's domain) and/or a
1621 * target attribute (depending on configuration).
1622 *
1623 * @param $url String|bool optional URL, to extract the domain from for rel =>
1624 * nofollow if appropriate
1625 * @return Array associative array of HTML attributes
1626 */
1627 function getExternalLinkAttribs( $url = false ) {
1628 $attribs = array();
1629 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1630 $ns = $this->mTitle->getNamespace();
1631 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1632 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1633 {
1634 $attribs['rel'] = 'nofollow';
1635 }
1636 if ( $this->mOptions->getExternalLinkTarget() ) {
1637 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1638 }
1639 return $attribs;
1640 }
1641
1642 /**
1643 * Replace unusual URL escape codes with their equivalent characters
1644 *
1645 * @param $url String
1646 * @return String
1647 *
1648 * @todo This can merge genuinely required bits in the path or query string,
1649 * breaking legit URLs. A proper fix would treat the various parts of
1650 * the URL differently; as a workaround, just use the output for
1651 * statistical records, not for actual linking/output.
1652 */
1653 static function replaceUnusualEscapes( $url ) {
1654 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1655 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1656 }
1657
1658 /**
1659 * Callback function used in replaceUnusualEscapes().
1660 * Replaces unusual URL escape codes with their equivalent character
1661 *
1662 * @param $matches array
1663 *
1664 * @return string
1665 */
1666 private static function replaceUnusualEscapesCallback( $matches ) {
1667 $char = urldecode( $matches[0] );
1668 $ord = ord( $char );
1669 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1670 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1671 # No, shouldn't be escaped
1672 return $char;
1673 } else {
1674 # Yes, leave it escaped
1675 return $matches[0];
1676 }
1677 }
1678
1679 /**
1680 * make an image if it's allowed, either through the global
1681 * option, through the exception, or through the on-wiki whitelist
1682 * @private
1683 *
1684 * $param $url string
1685 *
1686 * @return string
1687 */
1688 function maybeMakeExternalImage( $url ) {
1689 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1690 $imagesexception = !empty( $imagesfrom );
1691 $text = false;
1692 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1693 if ( $imagesexception && is_array( $imagesfrom ) ) {
1694 $imagematch = false;
1695 foreach ( $imagesfrom as $match ) {
1696 if ( strpos( $url, $match ) === 0 ) {
1697 $imagematch = true;
1698 break;
1699 }
1700 }
1701 } elseif ( $imagesexception ) {
1702 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1703 } else {
1704 $imagematch = false;
1705 }
1706 if ( $this->mOptions->getAllowExternalImages()
1707 || ( $imagesexception && $imagematch ) ) {
1708 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1709 # Image found
1710 $text = Linker::makeExternalImage( $url );
1711 }
1712 }
1713 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1714 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1715 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1716 foreach ( $whitelist as $entry ) {
1717 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1718 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1719 continue;
1720 }
1721 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1722 # Image matches a whitelist entry
1723 $text = Linker::makeExternalImage( $url );
1724 break;
1725 }
1726 }
1727 }
1728 return $text;
1729 }
1730
1731 /**
1732 * Process [[ ]] wikilinks
1733 *
1734 * @param $s string
1735 *
1736 * @return String: processed text
1737 *
1738 * @private
1739 */
1740 function replaceInternalLinks( $s ) {
1741 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1742 return $s;
1743 }
1744
1745 /**
1746 * Process [[ ]] wikilinks (RIL)
1747 * @param $s
1748 * @throws MWException
1749 * @return LinkHolderArray
1750 *
1751 * @private
1752 */
1753 function replaceInternalLinks2( &$s ) {
1754 wfProfileIn( __METHOD__ );
1755
1756 wfProfileIn( __METHOD__.'-setup' );
1757 static $tc = FALSE, $e1, $e1_img;
1758 # the % is needed to support urlencoded titles as well
1759 if ( !$tc ) {
1760 $tc = Title::legalChars() . '#%';
1761 # Match a link having the form [[namespace:link|alternate]]trail
1762 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1763 # Match cases where there is no "]]", which might still be images
1764 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1765 }
1766
1767 $holders = new LinkHolderArray( $this );
1768
1769 # split the entire text string on occurrences of [[
1770 $a = StringUtils::explode( '[[', ' ' . $s );
1771 # get the first element (all text up to first [[), and remove the space we added
1772 $s = $a->current();
1773 $a->next();
1774 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1775 $s = substr( $s, 1 );
1776
1777 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1778 $e2 = null;
1779 if ( $useLinkPrefixExtension ) {
1780 # Match the end of a line for a word that's not followed by whitespace,
1781 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1782 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1783 }
1784
1785 if ( is_null( $this->mTitle ) ) {
1786 wfProfileOut( __METHOD__.'-setup' );
1787 wfProfileOut( __METHOD__ );
1788 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1789 }
1790 $nottalk = !$this->mTitle->isTalkPage();
1791
1792 if ( $useLinkPrefixExtension ) {
1793 $m = array();
1794 if ( preg_match( $e2, $s, $m ) ) {
1795 $first_prefix = $m[2];
1796 } else {
1797 $first_prefix = false;
1798 }
1799 } else {
1800 $prefix = '';
1801 }
1802
1803 if ( $this->getConverterLanguage()->hasVariants() ) {
1804 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1805 $this->mTitle->getPrefixedText() );
1806 } else {
1807 $selflink = array( $this->mTitle->getPrefixedText() );
1808 }
1809 $useSubpages = $this->areSubpagesAllowed();
1810 wfProfileOut( __METHOD__.'-setup' );
1811
1812 # Loop for each link
1813 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1814 # Check for excessive memory usage
1815 if ( $holders->isBig() ) {
1816 # Too big
1817 # Do the existence check, replace the link holders and clear the array
1818 $holders->replace( $s );
1819 $holders->clear();
1820 }
1821
1822 if ( $useLinkPrefixExtension ) {
1823 wfProfileIn( __METHOD__.'-prefixhandling' );
1824 if ( preg_match( $e2, $s, $m ) ) {
1825 $prefix = $m[2];
1826 $s = $m[1];
1827 } else {
1828 $prefix='';
1829 }
1830 # first link
1831 if ( $first_prefix ) {
1832 $prefix = $first_prefix;
1833 $first_prefix = false;
1834 }
1835 wfProfileOut( __METHOD__.'-prefixhandling' );
1836 }
1837
1838 $might_be_img = false;
1839
1840 wfProfileIn( __METHOD__."-e1" );
1841 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1842 $text = $m[2];
1843 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1844 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1845 # the real problem is with the $e1 regex
1846 # See bug 1300.
1847 #
1848 # Still some problems for cases where the ] is meant to be outside punctuation,
1849 # and no image is in sight. See bug 2095.
1850 #
1851 if ( $text !== '' &&
1852 substr( $m[3], 0, 1 ) === ']' &&
1853 strpos( $text, '[' ) !== false
1854 )
1855 {
1856 $text .= ']'; # so that replaceExternalLinks($text) works later
1857 $m[3] = substr( $m[3], 1 );
1858 }
1859 # fix up urlencoded title texts
1860 if ( strpos( $m[1], '%' ) !== false ) {
1861 # Should anchors '#' also be rejected?
1862 $m[1] = str_replace( array('<', '>'), array('&lt;', '&gt;'), rawurldecode( $m[1] ) );
1863 }
1864 $trail = $m[3];
1865 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1866 $might_be_img = true;
1867 $text = $m[2];
1868 if ( strpos( $m[1], '%' ) !== false ) {
1869 $m[1] = rawurldecode( $m[1] );
1870 }
1871 $trail = "";
1872 } else { # Invalid form; output directly
1873 $s .= $prefix . '[[' . $line ;
1874 wfProfileOut( __METHOD__."-e1" );
1875 continue;
1876 }
1877 wfProfileOut( __METHOD__."-e1" );
1878 wfProfileIn( __METHOD__."-misc" );
1879
1880 # Don't allow internal links to pages containing
1881 # PROTO: where PROTO is a valid URL protocol; these
1882 # should be external links.
1883 if ( preg_match( '/^(?i:' . $this->mUrlProtocols . ')/', $m[1] ) ) {
1884 $s .= $prefix . '[[' . $line ;
1885 wfProfileOut( __METHOD__."-misc" );
1886 continue;
1887 }
1888
1889 # Make subpage if necessary
1890 if ( $useSubpages ) {
1891 $link = $this->maybeDoSubpageLink( $m[1], $text );
1892 } else {
1893 $link = $m[1];
1894 }
1895
1896 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1897 if ( !$noforce ) {
1898 # Strip off leading ':'
1899 $link = substr( $link, 1 );
1900 }
1901
1902 wfProfileOut( __METHOD__."-misc" );
1903 wfProfileIn( __METHOD__."-title" );
1904 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1905 if ( $nt === null ) {
1906 $s .= $prefix . '[[' . $line;
1907 wfProfileOut( __METHOD__."-title" );
1908 continue;
1909 }
1910
1911 $ns = $nt->getNamespace();
1912 $iw = $nt->getInterWiki();
1913 wfProfileOut( __METHOD__."-title" );
1914
1915 if ( $might_be_img ) { # if this is actually an invalid link
1916 wfProfileIn( __METHOD__."-might_be_img" );
1917 if ( $ns == NS_FILE && $noforce ) { # but might be an image
1918 $found = false;
1919 while ( true ) {
1920 # look at the next 'line' to see if we can close it there
1921 $a->next();
1922 $next_line = $a->current();
1923 if ( $next_line === false || $next_line === null ) {
1924 break;
1925 }
1926 $m = explode( ']]', $next_line, 3 );
1927 if ( count( $m ) == 3 ) {
1928 # the first ]] closes the inner link, the second the image
1929 $found = true;
1930 $text .= "[[{$m[0]}]]{$m[1]}";
1931 $trail = $m[2];
1932 break;
1933 } elseif ( count( $m ) == 2 ) {
1934 # if there's exactly one ]] that's fine, we'll keep looking
1935 $text .= "[[{$m[0]}]]{$m[1]}";
1936 } else {
1937 # if $next_line is invalid too, we need look no further
1938 $text .= '[[' . $next_line;
1939 break;
1940 }
1941 }
1942 if ( !$found ) {
1943 # we couldn't find the end of this imageLink, so output it raw
1944 # but don't ignore what might be perfectly normal links in the text we've examined
1945 $holders->merge( $this->replaceInternalLinks2( $text ) );
1946 $s .= "{$prefix}[[$link|$text";
1947 # note: no $trail, because without an end, there *is* no trail
1948 wfProfileOut( __METHOD__."-might_be_img" );
1949 continue;
1950 }
1951 } else { # it's not an image, so output it raw
1952 $s .= "{$prefix}[[$link|$text";
1953 # note: no $trail, because without an end, there *is* no trail
1954 wfProfileOut( __METHOD__."-might_be_img" );
1955 continue;
1956 }
1957 wfProfileOut( __METHOD__."-might_be_img" );
1958 }
1959
1960 $wasblank = ( $text == '' );
1961 if ( $wasblank ) {
1962 $text = $link;
1963 } else {
1964 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1965 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1966 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1967 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1968 $text = $this->doQuotes( $text );
1969 }
1970
1971 # Link not escaped by : , create the various objects
1972 if ( $noforce ) {
1973 # Interwikis
1974 wfProfileIn( __METHOD__."-interwiki" );
1975 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && Language::fetchLanguageName( $iw, null, 'mw' ) ) {
1976 // XXX: the above check prevents links to sites with identifiers that are not language codes
1977
1978 # Bug 24502: filter duplicates
1979 if ( !isset( $this->mLangLinkLanguages[$iw] ) ) {
1980 $this->mLangLinkLanguages[$iw] = true;
1981 $this->mOutput->addLanguageLink( $nt->getFullText() );
1982 }
1983
1984 $s = rtrim( $s . $prefix );
1985 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
1986 wfProfileOut( __METHOD__."-interwiki" );
1987 continue;
1988 }
1989 wfProfileOut( __METHOD__."-interwiki" );
1990
1991 if ( $ns == NS_FILE ) {
1992 wfProfileIn( __METHOD__."-image" );
1993 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1994 if ( $wasblank ) {
1995 # if no parameters were passed, $text
1996 # becomes something like "File:Foo.png",
1997 # which we don't want to pass on to the
1998 # image generator
1999 $text = '';
2000 } else {
2001 # recursively parse links inside the image caption
2002 # actually, this will parse them in any other parameters, too,
2003 # but it might be hard to fix that, and it doesn't matter ATM
2004 $text = $this->replaceExternalLinks( $text );
2005 $holders->merge( $this->replaceInternalLinks2( $text ) );
2006 }
2007 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2008 $s .= $prefix . $this->armorLinks(
2009 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2010 } else {
2011 $s .= $prefix . $trail;
2012 }
2013 wfProfileOut( __METHOD__."-image" );
2014 continue;
2015 }
2016
2017 if ( $ns == NS_CATEGORY ) {
2018 wfProfileIn( __METHOD__."-category" );
2019 $s = rtrim( $s . "\n" ); # bug 87
2020
2021 if ( $wasblank ) {
2022 $sortkey = $this->getDefaultSort();
2023 } else {
2024 $sortkey = $text;
2025 }
2026 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
2027 $sortkey = str_replace( "\n", '', $sortkey );
2028 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2029 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
2030
2031 /**
2032 * Strip the whitespace Category links produce, see bug 87
2033 * @todo We might want to use trim($tmp, "\n") here.
2034 */
2035 $s .= trim( $prefix . $trail, "\n" ) == '' ? '' : $prefix . $trail;
2036
2037 wfProfileOut( __METHOD__."-category" );
2038 continue;
2039 }
2040 }
2041
2042 # Self-link checking
2043 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
2044 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2045 $s .= $prefix . Linker::makeSelfLinkObj( $nt, $text, '', $trail );
2046 continue;
2047 }
2048 }
2049
2050 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2051 # @todo FIXME: Should do batch file existence checks, see comment below
2052 if ( $ns == NS_MEDIA ) {
2053 wfProfileIn( __METHOD__."-media" );
2054 # Give extensions a chance to select the file revision for us
2055 $options = array();
2056 $descQuery = false;
2057 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2058 array( $this, $nt, &$options, &$descQuery ) );
2059 # Fetch and register the file (file title may be different via hooks)
2060 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2061 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2062 $s .= $prefix . $this->armorLinks(
2063 Linker::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2064 wfProfileOut( __METHOD__."-media" );
2065 continue;
2066 }
2067
2068 wfProfileIn( __METHOD__."-always_known" );
2069 # Some titles, such as valid special pages or files in foreign repos, should
2070 # be shown as bluelinks even though they're not included in the page table
2071 #
2072 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2073 # batch file existence checks for NS_FILE and NS_MEDIA
2074 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2075 $this->mOutput->addLink( $nt );
2076 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2077 } else {
2078 # Links will be added to the output link list after checking
2079 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2080 }
2081 wfProfileOut( __METHOD__."-always_known" );
2082 }
2083 wfProfileOut( __METHOD__ );
2084 return $holders;
2085 }
2086
2087 /**
2088 * Render a forced-blue link inline; protect against double expansion of
2089 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2090 * Since this little disaster has to split off the trail text to avoid
2091 * breaking URLs in the following text without breaking trails on the
2092 * wiki links, it's been made into a horrible function.
2093 *
2094 * @param $nt Title
2095 * @param $text String
2096 * @param $query Array or String
2097 * @param $trail String
2098 * @param $prefix String
2099 * @return String: HTML-wikitext mix oh yuck
2100 */
2101 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2102 list( $inside, $trail ) = Linker::splitTrail( $trail );
2103
2104 if ( is_string( $query ) ) {
2105 $query = wfCgiToArray( $query );
2106 }
2107 if ( $text == '' ) {
2108 $text = htmlspecialchars( $nt->getPrefixedText() );
2109 }
2110
2111 $link = Linker::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2112
2113 return $this->armorLinks( $link ) . $trail;
2114 }
2115
2116 /**
2117 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2118 * going to go through further parsing steps before inline URL expansion.
2119 *
2120 * Not needed quite as much as it used to be since free links are a bit
2121 * more sensible these days. But bracketed links are still an issue.
2122 *
2123 * @param $text String: more-or-less HTML
2124 * @return String: less-or-more HTML with NOPARSE bits
2125 */
2126 function armorLinks( $text ) {
2127 return preg_replace( '/\b((?i)' . $this->mUrlProtocols . ')/',
2128 "{$this->mUniqPrefix}NOPARSE$1", $text );
2129 }
2130
2131 /**
2132 * Return true if subpage links should be expanded on this page.
2133 * @return Boolean
2134 */
2135 function areSubpagesAllowed() {
2136 # Some namespaces don't allow subpages
2137 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
2138 }
2139
2140 /**
2141 * Handle link to subpage if necessary
2142 *
2143 * @param $target String: the source of the link
2144 * @param &$text String: the link text, modified as necessary
2145 * @return string the full name of the link
2146 * @private
2147 */
2148 function maybeDoSubpageLink( $target, &$text ) {
2149 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
2150 }
2151
2152 /**#@+
2153 * Used by doBlockLevels()
2154 * @private
2155 *
2156 * @return string
2157 */
2158 function closeParagraph() {
2159 $result = '';
2160 if ( $this->mLastSection != '' ) {
2161 $result = '</' . $this->mLastSection . ">\n";
2162 }
2163 $this->mInPre = false;
2164 $this->mLastSection = '';
2165 return $result;
2166 }
2167
2168 /**
2169 * getCommon() returns the length of the longest common substring
2170 * of both arguments, starting at the beginning of both.
2171 * @private
2172 *
2173 * @param $st1 string
2174 * @param $st2 string
2175 *
2176 * @return int
2177 */
2178 function getCommon( $st1, $st2 ) {
2179 $fl = strlen( $st1 );
2180 $shorter = strlen( $st2 );
2181 if ( $fl < $shorter ) {
2182 $shorter = $fl;
2183 }
2184
2185 for ( $i = 0; $i < $shorter; ++$i ) {
2186 if ( $st1[$i] != $st2[$i] ) {
2187 break;
2188 }
2189 }
2190 return $i;
2191 }
2192
2193 /**
2194 * These next three functions open, continue, and close the list
2195 * element appropriate to the prefix character passed into them.
2196 * @private
2197 *
2198 * @param $char string
2199 *
2200 * @return string
2201 */
2202 function openList( $char ) {
2203 $result = $this->closeParagraph();
2204
2205 if ( '*' === $char ) {
2206 $result .= '<ul><li>';
2207 } elseif ( '#' === $char ) {
2208 $result .= '<ol><li>';
2209 } elseif ( ':' === $char ) {
2210 $result .= '<dl><dd>';
2211 } elseif ( ';' === $char ) {
2212 $result .= '<dl><dt>';
2213 $this->mDTopen = true;
2214 } else {
2215 $result = '<!-- ERR 1 -->';
2216 }
2217
2218 return $result;
2219 }
2220
2221 /**
2222 * TODO: document
2223 * @param $char String
2224 * @private
2225 *
2226 * @return string
2227 */
2228 function nextItem( $char ) {
2229 if ( '*' === $char || '#' === $char ) {
2230 return '</li><li>';
2231 } elseif ( ':' === $char || ';' === $char ) {
2232 $close = '</dd>';
2233 if ( $this->mDTopen ) {
2234 $close = '</dt>';
2235 }
2236 if ( ';' === $char ) {
2237 $this->mDTopen = true;
2238 return $close . '<dt>';
2239 } else {
2240 $this->mDTopen = false;
2241 return $close . '<dd>';
2242 }
2243 }
2244 return '<!-- ERR 2 -->';
2245 }
2246
2247 /**
2248 * TODO: document
2249 * @param $char String
2250 * @private
2251 *
2252 * @return string
2253 */
2254 function closeList( $char ) {
2255 if ( '*' === $char ) {
2256 $text = '</li></ul>';
2257 } elseif ( '#' === $char ) {
2258 $text = '</li></ol>';
2259 } elseif ( ':' === $char ) {
2260 if ( $this->mDTopen ) {
2261 $this->mDTopen = false;
2262 $text = '</dt></dl>';
2263 } else {
2264 $text = '</dd></dl>';
2265 }
2266 } else {
2267 return '<!-- ERR 3 -->';
2268 }
2269 return $text."\n";
2270 }
2271 /**#@-*/
2272
2273 /**
2274 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2275 *
2276 * @param $text String
2277 * @param $linestart Boolean: whether or not this is at the start of a line.
2278 * @private
2279 * @return string the lists rendered as HTML
2280 */
2281 function doBlockLevels( $text, $linestart ) {
2282 wfProfileIn( __METHOD__ );
2283
2284 # Parsing through the text line by line. The main thing
2285 # happening here is handling of block-level elements p, pre,
2286 # and making lists from lines starting with * # : etc.
2287 #
2288 $textLines = StringUtils::explode( "\n", $text );
2289
2290 $lastPrefix = $output = '';
2291 $this->mDTopen = $inBlockElem = false;
2292 $prefixLength = 0;
2293 $paragraphStack = false;
2294
2295 foreach ( $textLines as $oLine ) {
2296 # Fix up $linestart
2297 if ( !$linestart ) {
2298 $output .= $oLine;
2299 $linestart = true;
2300 continue;
2301 }
2302 # * = ul
2303 # # = ol
2304 # ; = dt
2305 # : = dd
2306
2307 $lastPrefixLength = strlen( $lastPrefix );
2308 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2309 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2310 # If not in a <pre> element, scan for and figure out what prefixes are there.
2311 if ( !$this->mInPre ) {
2312 # Multiple prefixes may abut each other for nested lists.
2313 $prefixLength = strspn( $oLine, '*#:;' );
2314 $prefix = substr( $oLine, 0, $prefixLength );
2315
2316 # eh?
2317 # ; and : are both from definition-lists, so they're equivalent
2318 # for the purposes of determining whether or not we need to open/close
2319 # elements.
2320 $prefix2 = str_replace( ';', ':', $prefix );
2321 $t = substr( $oLine, $prefixLength );
2322 $this->mInPre = (bool)$preOpenMatch;
2323 } else {
2324 # Don't interpret any other prefixes in preformatted text
2325 $prefixLength = 0;
2326 $prefix = $prefix2 = '';
2327 $t = $oLine;
2328 }
2329
2330 # List generation
2331 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2332 # Same as the last item, so no need to deal with nesting or opening stuff
2333 $output .= $this->nextItem( substr( $prefix, -1 ) );
2334 $paragraphStack = false;
2335
2336 if ( substr( $prefix, -1 ) === ';') {
2337 # The one nasty exception: definition lists work like this:
2338 # ; title : definition text
2339 # So we check for : in the remainder text to split up the
2340 # title and definition, without b0rking links.
2341 $term = $t2 = '';
2342 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2343 $t = $t2;
2344 $output .= $term . $this->nextItem( ':' );
2345 }
2346 }
2347 } elseif ( $prefixLength || $lastPrefixLength ) {
2348 # We need to open or close prefixes, or both.
2349
2350 # Either open or close a level...
2351 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2352 $paragraphStack = false;
2353
2354 # Close all the prefixes which aren't shared.
2355 while ( $commonPrefixLength < $lastPrefixLength ) {
2356 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2357 --$lastPrefixLength;
2358 }
2359
2360 # Continue the current prefix if appropriate.
2361 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2362 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2363 }
2364
2365 # Open prefixes where appropriate.
2366 while ( $prefixLength > $commonPrefixLength ) {
2367 $char = substr( $prefix, $commonPrefixLength, 1 );
2368 $output .= $this->openList( $char );
2369
2370 if ( ';' === $char ) {
2371 # @todo FIXME: This is dupe of code above
2372 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2373 $t = $t2;
2374 $output .= $term . $this->nextItem( ':' );
2375 }
2376 }
2377 ++$commonPrefixLength;
2378 }
2379 $lastPrefix = $prefix2;
2380 }
2381
2382 # If we have no prefixes, go to paragraph mode.
2383 if ( 0 == $prefixLength ) {
2384 wfProfileIn( __METHOD__."-paragraph" );
2385 # No prefix (not in list)--go to paragraph mode
2386 # XXX: use a stack for nestable elements like span, table and div
2387 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2388 $closematch = preg_match(
2389 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2390 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2391 if ( $openmatch or $closematch ) {
2392 $paragraphStack = false;
2393 # TODO bug 5718: paragraph closed
2394 $output .= $this->closeParagraph();
2395 if ( $preOpenMatch and !$preCloseMatch ) {
2396 $this->mInPre = true;
2397 }
2398 $inBlockElem = !$closematch;
2399 } elseif ( !$inBlockElem && !$this->mInPre ) {
2400 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2401 # pre
2402 if ( $this->mLastSection !== 'pre' ) {
2403 $paragraphStack = false;
2404 $output .= $this->closeParagraph().'<pre>';
2405 $this->mLastSection = 'pre';
2406 }
2407 $t = substr( $t, 1 );
2408 } else {
2409 # paragraph
2410 if ( trim( $t ) === '' ) {
2411 if ( $paragraphStack ) {
2412 $output .= $paragraphStack.'<br />';
2413 $paragraphStack = false;
2414 $this->mLastSection = 'p';
2415 } else {
2416 if ( $this->mLastSection !== 'p' ) {
2417 $output .= $this->closeParagraph();
2418 $this->mLastSection = '';
2419 $paragraphStack = '<p>';
2420 } else {
2421 $paragraphStack = '</p><p>';
2422 }
2423 }
2424 } else {
2425 if ( $paragraphStack ) {
2426 $output .= $paragraphStack;
2427 $paragraphStack = false;
2428 $this->mLastSection = 'p';
2429 } elseif ( $this->mLastSection !== 'p' ) {
2430 $output .= $this->closeParagraph().'<p>';
2431 $this->mLastSection = 'p';
2432 }
2433 }
2434 }
2435 }
2436 wfProfileOut( __METHOD__."-paragraph" );
2437 }
2438 # somewhere above we forget to get out of pre block (bug 785)
2439 if ( $preCloseMatch && $this->mInPre ) {
2440 $this->mInPre = false;
2441 }
2442 if ( $paragraphStack === false ) {
2443 $output .= $t."\n";
2444 }
2445 }
2446 while ( $prefixLength ) {
2447 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2448 --$prefixLength;
2449 }
2450 if ( $this->mLastSection != '' ) {
2451 $output .= '</' . $this->mLastSection . '>';
2452 $this->mLastSection = '';
2453 }
2454
2455 wfProfileOut( __METHOD__ );
2456 return $output;
2457 }
2458
2459 /**
2460 * Split up a string on ':', ignoring any occurrences inside tags
2461 * to prevent illegal overlapping.
2462 *
2463 * @param $str String the string to split
2464 * @param &$before String set to everything before the ':'
2465 * @param &$after String set to everything after the ':'
2466 * @throws MWException
2467 * @return String the position of the ':', or false if none found
2468 */
2469 function findColonNoLinks( $str, &$before, &$after ) {
2470 wfProfileIn( __METHOD__ );
2471
2472 $pos = strpos( $str, ':' );
2473 if ( $pos === false ) {
2474 # Nothing to find!
2475 wfProfileOut( __METHOD__ );
2476 return false;
2477 }
2478
2479 $lt = strpos( $str, '<' );
2480 if ( $lt === false || $lt > $pos ) {
2481 # Easy; no tag nesting to worry about
2482 $before = substr( $str, 0, $pos );
2483 $after = substr( $str, $pos+1 );
2484 wfProfileOut( __METHOD__ );
2485 return $pos;
2486 }
2487
2488 # Ugly state machine to walk through avoiding tags.
2489 $state = self::COLON_STATE_TEXT;
2490 $stack = 0;
2491 $len = strlen( $str );
2492 for( $i = 0; $i < $len; $i++ ) {
2493 $c = $str[$i];
2494
2495 switch( $state ) {
2496 # (Using the number is a performance hack for common cases)
2497 case 0: # self::COLON_STATE_TEXT:
2498 switch( $c ) {
2499 case "<":
2500 # Could be either a <start> tag or an </end> tag
2501 $state = self::COLON_STATE_TAGSTART;
2502 break;
2503 case ":":
2504 if ( $stack == 0 ) {
2505 # We found it!
2506 $before = substr( $str, 0, $i );
2507 $after = substr( $str, $i + 1 );
2508 wfProfileOut( __METHOD__ );
2509 return $i;
2510 }
2511 # Embedded in a tag; don't break it.
2512 break;
2513 default:
2514 # Skip ahead looking for something interesting
2515 $colon = strpos( $str, ':', $i );
2516 if ( $colon === false ) {
2517 # Nothing else interesting
2518 wfProfileOut( __METHOD__ );
2519 return false;
2520 }
2521 $lt = strpos( $str, '<', $i );
2522 if ( $stack === 0 ) {
2523 if ( $lt === false || $colon < $lt ) {
2524 # We found it!
2525 $before = substr( $str, 0, $colon );
2526 $after = substr( $str, $colon + 1 );
2527 wfProfileOut( __METHOD__ );
2528 return $i;
2529 }
2530 }
2531 if ( $lt === false ) {
2532 # Nothing else interesting to find; abort!
2533 # We're nested, but there's no close tags left. Abort!
2534 break 2;
2535 }
2536 # Skip ahead to next tag start
2537 $i = $lt;
2538 $state = self::COLON_STATE_TAGSTART;
2539 }
2540 break;
2541 case 1: # self::COLON_STATE_TAG:
2542 # In a <tag>
2543 switch( $c ) {
2544 case ">":
2545 $stack++;
2546 $state = self::COLON_STATE_TEXT;
2547 break;
2548 case "/":
2549 # Slash may be followed by >?
2550 $state = self::COLON_STATE_TAGSLASH;
2551 break;
2552 default:
2553 # ignore
2554 }
2555 break;
2556 case 2: # self::COLON_STATE_TAGSTART:
2557 switch( $c ) {
2558 case "/":
2559 $state = self::COLON_STATE_CLOSETAG;
2560 break;
2561 case "!":
2562 $state = self::COLON_STATE_COMMENT;
2563 break;
2564 case ">":
2565 # Illegal early close? This shouldn't happen D:
2566 $state = self::COLON_STATE_TEXT;
2567 break;
2568 default:
2569 $state = self::COLON_STATE_TAG;
2570 }
2571 break;
2572 case 3: # self::COLON_STATE_CLOSETAG:
2573 # In a </tag>
2574 if ( $c === ">" ) {
2575 $stack--;
2576 if ( $stack < 0 ) {
2577 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2578 wfProfileOut( __METHOD__ );
2579 return false;
2580 }
2581 $state = self::COLON_STATE_TEXT;
2582 }
2583 break;
2584 case self::COLON_STATE_TAGSLASH:
2585 if ( $c === ">" ) {
2586 # Yes, a self-closed tag <blah/>
2587 $state = self::COLON_STATE_TEXT;
2588 } else {
2589 # Probably we're jumping the gun, and this is an attribute
2590 $state = self::COLON_STATE_TAG;
2591 }
2592 break;
2593 case 5: # self::COLON_STATE_COMMENT:
2594 if ( $c === "-" ) {
2595 $state = self::COLON_STATE_COMMENTDASH;
2596 }
2597 break;
2598 case self::COLON_STATE_COMMENTDASH:
2599 if ( $c === "-" ) {
2600 $state = self::COLON_STATE_COMMENTDASHDASH;
2601 } else {
2602 $state = self::COLON_STATE_COMMENT;
2603 }
2604 break;
2605 case self::COLON_STATE_COMMENTDASHDASH:
2606 if ( $c === ">" ) {
2607 $state = self::COLON_STATE_TEXT;
2608 } else {
2609 $state = self::COLON_STATE_COMMENT;
2610 }
2611 break;
2612 default:
2613 throw new MWException( "State machine error in " . __METHOD__ );
2614 }
2615 }
2616 if ( $stack > 0 ) {
2617 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2618 wfProfileOut( __METHOD__ );
2619 return false;
2620 }
2621 wfProfileOut( __METHOD__ );
2622 return false;
2623 }
2624
2625 /**
2626 * Return value of a magic variable (like PAGENAME)
2627 *
2628 * @private
2629 *
2630 * @param $index integer
2631 * @param bool|\PPFrame $frame
2632 *
2633 * @throws MWException
2634 * @return string
2635 */
2636 function getVariableValue( $index, $frame = false ) {
2637 global $wgContLang, $wgSitename, $wgServer;
2638 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2639
2640 if ( is_null( $this->mTitle ) ) {
2641 // If no title set, bad things are going to happen
2642 // later. Title should always be set since this
2643 // should only be called in the middle of a parse
2644 // operation (but the unit-tests do funky stuff)
2645 throw new MWException( __METHOD__ . ' Should only be '
2646 . ' called while parsing (no title set)' );
2647 }
2648
2649 /**
2650 * Some of these require message or data lookups and can be
2651 * expensive to check many times.
2652 */
2653 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2654 if ( isset( $this->mVarCache[$index] ) ) {
2655 return $this->mVarCache[$index];
2656 }
2657 }
2658
2659 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2660 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2661
2662 # Use the time zone
2663 global $wgLocaltimezone;
2664 if ( isset( $wgLocaltimezone ) ) {
2665 $oldtz = date_default_timezone_get();
2666 date_default_timezone_set( $wgLocaltimezone );
2667 }
2668
2669 $localTimestamp = date( 'YmdHis', $ts );
2670 $localMonth = date( 'm', $ts );
2671 $localMonth1 = date( 'n', $ts );
2672 $localMonthName = date( 'n', $ts );
2673 $localDay = date( 'j', $ts );
2674 $localDay2 = date( 'd', $ts );
2675 $localDayOfWeek = date( 'w', $ts );
2676 $localWeek = date( 'W', $ts );
2677 $localYear = date( 'Y', $ts );
2678 $localHour = date( 'H', $ts );
2679 if ( isset( $wgLocaltimezone ) ) {
2680 date_default_timezone_set( $oldtz );
2681 }
2682
2683 $pageLang = $this->getFunctionLang();
2684
2685 switch ( $index ) {
2686 case 'currentmonth':
2687 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2688 break;
2689 case 'currentmonth1':
2690 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2691 break;
2692 case 'currentmonthname':
2693 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2694 break;
2695 case 'currentmonthnamegen':
2696 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2697 break;
2698 case 'currentmonthabbrev':
2699 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2700 break;
2701 case 'currentday':
2702 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2703 break;
2704 case 'currentday2':
2705 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2706 break;
2707 case 'localmonth':
2708 $value = $pageLang->formatNum( $localMonth );
2709 break;
2710 case 'localmonth1':
2711 $value = $pageLang->formatNum( $localMonth1 );
2712 break;
2713 case 'localmonthname':
2714 $value = $pageLang->getMonthName( $localMonthName );
2715 break;
2716 case 'localmonthnamegen':
2717 $value = $pageLang->getMonthNameGen( $localMonthName );
2718 break;
2719 case 'localmonthabbrev':
2720 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2721 break;
2722 case 'localday':
2723 $value = $pageLang->formatNum( $localDay );
2724 break;
2725 case 'localday2':
2726 $value = $pageLang->formatNum( $localDay2 );
2727 break;
2728 case 'pagename':
2729 $value = wfEscapeWikiText( $this->mTitle->getText() );
2730 break;
2731 case 'pagenamee':
2732 $value = wfEscapeWikiText( $this->mTitle->getPartialURL() );
2733 break;
2734 case 'fullpagename':
2735 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2736 break;
2737 case 'fullpagenamee':
2738 $value = wfEscapeWikiText( $this->mTitle->getPrefixedURL() );
2739 break;
2740 case 'subpagename':
2741 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2742 break;
2743 case 'subpagenamee':
2744 $value = wfEscapeWikiText( $this->mTitle->getSubpageUrlForm() );
2745 break;
2746 case 'basepagename':
2747 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2748 break;
2749 case 'basepagenamee':
2750 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ) );
2751 break;
2752 case 'talkpagename':
2753 if ( $this->mTitle->canTalk() ) {
2754 $talkPage = $this->mTitle->getTalkPage();
2755 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2756 } else {
2757 $value = '';
2758 }
2759 break;
2760 case 'talkpagenamee':
2761 if ( $this->mTitle->canTalk() ) {
2762 $talkPage = $this->mTitle->getTalkPage();
2763 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2764 } else {
2765 $value = '';
2766 }
2767 break;
2768 case 'subjectpagename':
2769 $subjPage = $this->mTitle->getSubjectPage();
2770 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2771 break;
2772 case 'subjectpagenamee':
2773 $subjPage = $this->mTitle->getSubjectPage();
2774 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2775 break;
2776 case 'pageid': // requested in bug 23427
2777 $pageid = $this->getTitle()->getArticleId();
2778 if( $pageid == 0 ) {
2779 # 0 means the page doesn't exist in the database,
2780 # which means the user is previewing a new page.
2781 # The vary-revision flag must be set, because the magic word
2782 # will have a different value once the page is saved.
2783 $this->mOutput->setFlag( 'vary-revision' );
2784 wfDebug( __METHOD__ . ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2785 }
2786 $value = $pageid ? $pageid : null;
2787 break;
2788 case 'revisionid':
2789 # Let the edit saving system know we should parse the page
2790 # *after* a revision ID has been assigned.
2791 $this->mOutput->setFlag( 'vary-revision' );
2792 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2793 $value = $this->mRevisionId;
2794 break;
2795 case 'revisionday':
2796 # Let the edit saving system know we should parse the page
2797 # *after* a revision ID has been assigned. This is for null edits.
2798 $this->mOutput->setFlag( 'vary-revision' );
2799 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2800 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2801 break;
2802 case 'revisionday2':
2803 # Let the edit saving system know we should parse the page
2804 # *after* a revision ID has been assigned. This is for null edits.
2805 $this->mOutput->setFlag( 'vary-revision' );
2806 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2807 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2808 break;
2809 case 'revisionmonth':
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__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2814 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2815 break;
2816 case 'revisionmonth1':
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__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2821 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2822 break;
2823 case 'revisionyear':
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__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2828 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2829 break;
2830 case 'revisiontimestamp':
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__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2835 $value = $this->getRevisionTimestamp();
2836 break;
2837 case 'revisionuser':
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__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2842 $value = $this->getRevisionUser();
2843 break;
2844 case 'namespace':
2845 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2846 break;
2847 case 'namespacee':
2848 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2849 break;
2850 case 'namespacenumber':
2851 $value = $this->mTitle->getNamespace();
2852 break;
2853 case 'talkspace':
2854 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : '';
2855 break;
2856 case 'talkspacee':
2857 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2858 break;
2859 case 'subjectspace':
2860 $value = $this->mTitle->getSubjectNsText();
2861 break;
2862 case 'subjectspacee':
2863 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2864 break;
2865 case 'currentdayname':
2866 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2867 break;
2868 case 'currentyear':
2869 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2870 break;
2871 case 'currenttime':
2872 $value = $pageLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2873 break;
2874 case 'currenthour':
2875 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2876 break;
2877 case 'currentweek':
2878 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2879 # int to remove the padding
2880 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2881 break;
2882 case 'currentdow':
2883 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2884 break;
2885 case 'localdayname':
2886 $value = $pageLang->getWeekdayName( $localDayOfWeek + 1 );
2887 break;
2888 case 'localyear':
2889 $value = $pageLang->formatNum( $localYear, true );
2890 break;
2891 case 'localtime':
2892 $value = $pageLang->time( $localTimestamp, false, false );
2893 break;
2894 case 'localhour':
2895 $value = $pageLang->formatNum( $localHour, true );
2896 break;
2897 case 'localweek':
2898 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2899 # int to remove the padding
2900 $value = $pageLang->formatNum( (int)$localWeek );
2901 break;
2902 case 'localdow':
2903 $value = $pageLang->formatNum( $localDayOfWeek );
2904 break;
2905 case 'numberofarticles':
2906 $value = $pageLang->formatNum( SiteStats::articles() );
2907 break;
2908 case 'numberoffiles':
2909 $value = $pageLang->formatNum( SiteStats::images() );
2910 break;
2911 case 'numberofusers':
2912 $value = $pageLang->formatNum( SiteStats::users() );
2913 break;
2914 case 'numberofactiveusers':
2915 $value = $pageLang->formatNum( SiteStats::activeUsers() );
2916 break;
2917 case 'numberofpages':
2918 $value = $pageLang->formatNum( SiteStats::pages() );
2919 break;
2920 case 'numberofadmins':
2921 $value = $pageLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2922 break;
2923 case 'numberofedits':
2924 $value = $pageLang->formatNum( SiteStats::edits() );
2925 break;
2926 case 'numberofviews':
2927 global $wgDisableCounters;
2928 $value = !$wgDisableCounters ? $pageLang->formatNum( SiteStats::views() ) : '';
2929 break;
2930 case 'currenttimestamp':
2931 $value = wfTimestamp( TS_MW, $ts );
2932 break;
2933 case 'localtimestamp':
2934 $value = $localTimestamp;
2935 break;
2936 case 'currentversion':
2937 $value = SpecialVersion::getVersion();
2938 break;
2939 case 'articlepath':
2940 return $wgArticlePath;
2941 case 'sitename':
2942 return $wgSitename;
2943 case 'server':
2944 return $wgServer;
2945 case 'servername':
2946 $serverParts = wfParseUrl( $wgServer );
2947 return $serverParts && isset( $serverParts['host'] ) ? $serverParts['host'] : $wgServer;
2948 case 'scriptpath':
2949 return $wgScriptPath;
2950 case 'stylepath':
2951 return $wgStylePath;
2952 case 'directionmark':
2953 return $pageLang->getDirMark();
2954 case 'contentlanguage':
2955 global $wgLanguageCode;
2956 return $wgLanguageCode;
2957 default:
2958 $ret = null;
2959 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2960 return $ret;
2961 } else {
2962 return null;
2963 }
2964 }
2965
2966 if ( $index ) {
2967 $this->mVarCache[$index] = $value;
2968 }
2969
2970 return $value;
2971 }
2972
2973 /**
2974 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2975 *
2976 * @private
2977 */
2978 function initialiseVariables() {
2979 wfProfileIn( __METHOD__ );
2980 $variableIDs = MagicWord::getVariableIDs();
2981 $substIDs = MagicWord::getSubstIDs();
2982
2983 $this->mVariables = new MagicWordArray( $variableIDs );
2984 $this->mSubstWords = new MagicWordArray( $substIDs );
2985 wfProfileOut( __METHOD__ );
2986 }
2987
2988 /**
2989 * Preprocess some wikitext and return the document tree.
2990 * This is the ghost of replace_variables().
2991 *
2992 * @param $text String: The text to parse
2993 * @param $flags Integer: bitwise combination of:
2994 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2995 * included. Default is to assume a direct page view.
2996 *
2997 * The generated DOM tree must depend only on the input text and the flags.
2998 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2999 *
3000 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3001 * change in the DOM tree for a given text, must be passed through the section identifier
3002 * in the section edit link and thus back to extractSections().
3003 *
3004 * The output of this function is currently only cached in process memory, but a persistent
3005 * cache may be implemented at a later date which takes further advantage of these strict
3006 * dependency requirements.
3007 *
3008 * @private
3009 *
3010 * @return PPNode
3011 */
3012 function preprocessToDom( $text, $flags = 0 ) {
3013 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3014 return $dom;
3015 }
3016
3017 /**
3018 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3019 *
3020 * @param $s string
3021 *
3022 * @return array
3023 */
3024 public static function splitWhitespace( $s ) {
3025 $ltrimmed = ltrim( $s );
3026 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3027 $trimmed = rtrim( $ltrimmed );
3028 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3029 if ( $diff > 0 ) {
3030 $w2 = substr( $ltrimmed, -$diff );
3031 } else {
3032 $w2 = '';
3033 }
3034 return array( $w1, $trimmed, $w2 );
3035 }
3036
3037 /**
3038 * Replace magic variables, templates, and template arguments
3039 * with the appropriate text. Templates are substituted recursively,
3040 * taking care to avoid infinite loops.
3041 *
3042 * Note that the substitution depends on value of $mOutputType:
3043 * self::OT_WIKI: only {{subst:}} templates
3044 * self::OT_PREPROCESS: templates but not extension tags
3045 * self::OT_HTML: all templates and extension tags
3046 *
3047 * @param $text String the text to transform
3048 * @param $frame PPFrame Object describing the arguments passed to the template.
3049 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3050 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3051 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3052 * @private
3053 *
3054 * @return string
3055 */
3056 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3057 # Is there any text? Also, Prevent too big inclusions!
3058 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
3059 return $text;
3060 }
3061 wfProfileIn( __METHOD__ );
3062
3063 if ( $frame === false ) {
3064 $frame = $this->getPreprocessor()->newFrame();
3065 } elseif ( !( $frame instanceof PPFrame ) ) {
3066 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3067 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3068 }
3069
3070 $dom = $this->preprocessToDom( $text );
3071 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
3072 $text = $frame->expand( $dom, $flags );
3073
3074 wfProfileOut( __METHOD__ );
3075 return $text;
3076 }
3077
3078 /**
3079 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3080 *
3081 * @param $args array
3082 *
3083 * @return array
3084 */
3085 static function createAssocArgs( $args ) {
3086 $assocArgs = array();
3087 $index = 1;
3088 foreach ( $args as $arg ) {
3089 $eqpos = strpos( $arg, '=' );
3090 if ( $eqpos === false ) {
3091 $assocArgs[$index++] = $arg;
3092 } else {
3093 $name = trim( substr( $arg, 0, $eqpos ) );
3094 $value = trim( substr( $arg, $eqpos+1 ) );
3095 if ( $value === false ) {
3096 $value = '';
3097 }
3098 if ( $name !== false ) {
3099 $assocArgs[$name] = $value;
3100 }
3101 }
3102 }
3103
3104 return $assocArgs;
3105 }
3106
3107 /**
3108 * Warn the user when a parser limitation is reached
3109 * Will warn at most once the user per limitation type
3110 *
3111 * @param $limitationType String: should be one of:
3112 * 'expensive-parserfunction' (corresponding messages:
3113 * 'expensive-parserfunction-warning',
3114 * 'expensive-parserfunction-category')
3115 * 'post-expand-template-argument' (corresponding messages:
3116 * 'post-expand-template-argument-warning',
3117 * 'post-expand-template-argument-category')
3118 * 'post-expand-template-inclusion' (corresponding messages:
3119 * 'post-expand-template-inclusion-warning',
3120 * 'post-expand-template-inclusion-category')
3121 * @param $current int|null Current value
3122 * @param $max int|null Maximum allowed, when an explicit limit has been
3123 * exceeded, provide the values (optional)
3124 */
3125 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3126 # does no harm if $current and $max are present but are unnecessary for the message
3127 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3128 ->inContentLanguage()->escaped();
3129 $this->mOutput->addWarning( $warning );
3130 $this->addTrackingCategory( "$limitationType-category" );
3131 }
3132
3133 /**
3134 * Return the text of a template, after recursively
3135 * replacing any variables or templates within the template.
3136 *
3137 * @param $piece Array: the parts of the template
3138 * $piece['title']: the title, i.e. the part before the |
3139 * $piece['parts']: the parameter array
3140 * $piece['lineStart']: whether the brace was at the start of a line
3141 * @param $frame PPFrame The current frame, contains template arguments
3142 * @throws MWException
3143 * @return String: the text of the template
3144 * @private
3145 */
3146 function braceSubstitution( $piece, $frame ) {
3147 global $wgContLang;
3148 wfProfileIn( __METHOD__ );
3149 wfProfileIn( __METHOD__.'-setup' );
3150
3151 # Flags
3152 $found = false; # $text has been filled
3153 $nowiki = false; # wiki markup in $text should be escaped
3154 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3155 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3156 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3157 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3158
3159 # Title object, where $text came from
3160 $title = false;
3161
3162 # $part1 is the bit before the first |, and must contain only title characters.
3163 # Various prefixes will be stripped from it later.
3164 $titleWithSpaces = $frame->expand( $piece['title'] );
3165 $part1 = trim( $titleWithSpaces );
3166 $titleText = false;
3167
3168 # Original title text preserved for various purposes
3169 $originalTitle = $part1;
3170
3171 # $args is a list of argument nodes, starting from index 0, not including $part1
3172 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3173 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
3174 wfProfileOut( __METHOD__.'-setup' );
3175
3176 $titleProfileIn = null; // profile templates
3177
3178 # SUBST
3179 wfProfileIn( __METHOD__.'-modifiers' );
3180 if ( !$found ) {
3181
3182 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
3183
3184 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3185 # Decide whether to expand template or keep wikitext as-is.
3186 if ( $this->ot['wiki'] ) {
3187 if ( $substMatch === false ) {
3188 $literal = true; # literal when in PST with no prefix
3189 } else {
3190 $literal = false; # expand when in PST with subst: or safesubst:
3191 }
3192 } else {
3193 if ( $substMatch == 'subst' ) {
3194 $literal = true; # literal when not in PST with plain subst:
3195 } else {
3196 $literal = false; # expand when not in PST with safesubst: or no prefix
3197 }
3198 }
3199 if ( $literal ) {
3200 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3201 $isLocalObj = true;
3202 $found = true;
3203 }
3204 }
3205
3206 # Variables
3207 if ( !$found && $args->getLength() == 0 ) {
3208 $id = $this->mVariables->matchStartToEnd( $part1 );
3209 if ( $id !== false ) {
3210 $text = $this->getVariableValue( $id, $frame );
3211 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
3212 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
3213 }
3214 $found = true;
3215 }
3216 }
3217
3218 # MSG, MSGNW and RAW
3219 if ( !$found ) {
3220 # Check for MSGNW:
3221 $mwMsgnw = MagicWord::get( 'msgnw' );
3222 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3223 $nowiki = true;
3224 } else {
3225 # Remove obsolete MSG:
3226 $mwMsg = MagicWord::get( 'msg' );
3227 $mwMsg->matchStartAndRemove( $part1 );
3228 }
3229
3230 # Check for RAW:
3231 $mwRaw = MagicWord::get( 'raw' );
3232 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3233 $forceRawInterwiki = true;
3234 }
3235 }
3236 wfProfileOut( __METHOD__.'-modifiers' );
3237
3238 # Parser functions
3239 if ( !$found ) {
3240 wfProfileIn( __METHOD__ . '-pfunc' );
3241
3242 $colonPos = strpos( $part1, ':' );
3243 if ( $colonPos !== false ) {
3244 # Case sensitive functions
3245 $function = substr( $part1, 0, $colonPos );
3246 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3247 $function = $this->mFunctionSynonyms[1][$function];
3248 } else {
3249 # Case insensitive functions
3250 $function = $wgContLang->lc( $function );
3251 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3252 $function = $this->mFunctionSynonyms[0][$function];
3253 } else {
3254 $function = false;
3255 }
3256 }
3257 if ( $function ) {
3258 wfProfileIn( __METHOD__ . '-pfunc-' . $function );
3259 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3260 $initialArgs = array( &$this );
3261 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3262 if ( $flags & SFH_OBJECT_ARGS ) {
3263 # Add a frame parameter, and pass the arguments as an array
3264 $allArgs = $initialArgs;
3265 $allArgs[] = $frame;
3266 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3267 $funcArgs[] = $args->item( $i );
3268 }
3269 $allArgs[] = $funcArgs;
3270 } else {
3271 # Convert arguments to plain text
3272 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3273 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3274 }
3275 $allArgs = array_merge( $initialArgs, $funcArgs );
3276 }
3277
3278 # Workaround for PHP bug 35229 and similar
3279 if ( !is_callable( $callback ) ) {
3280 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3281 wfProfileOut( __METHOD__ . '-pfunc' );
3282 wfProfileOut( __METHOD__ );
3283 throw new MWException( "Tag hook for $function is not callable\n" );
3284 }
3285 $result = call_user_func_array( $callback, $allArgs );
3286 $found = true;
3287 $noparse = true;
3288 $preprocessFlags = 0;
3289
3290 if ( is_array( $result ) ) {
3291 if ( isset( $result[0] ) ) {
3292 $text = $result[0];
3293 unset( $result[0] );
3294 }
3295
3296 # Extract flags into the local scope
3297 # This allows callers to set flags such as nowiki, found, etc.
3298 extract( $result );
3299 } else {
3300 $text = $result;
3301 }
3302 if ( !$noparse ) {
3303 $text = $this->preprocessToDom( $text, $preprocessFlags );
3304 $isChildObj = true;
3305 }
3306 wfProfileOut( __METHOD__ . '-pfunc-' . $function );
3307 }
3308 }
3309 wfProfileOut( __METHOD__ . '-pfunc' );
3310 }
3311
3312 # Finish mangling title and then check for loops.
3313 # Set $title to a Title object and $titleText to the PDBK
3314 if ( !$found ) {
3315 $ns = NS_TEMPLATE;
3316 # Split the title into page and subpage
3317 $subpage = '';
3318 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3319 if ( $subpage !== '' ) {
3320 $ns = $this->mTitle->getNamespace();
3321 }
3322 $title = Title::newFromText( $part1, $ns );
3323 if ( $title ) {
3324 $titleText = $title->getPrefixedText();
3325 # Check for language variants if the template is not found
3326 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3327 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3328 }
3329 # Do recursion depth check
3330 $limit = $this->mOptions->getMaxTemplateDepth();
3331 if ( $frame->depth >= $limit ) {
3332 $found = true;
3333 $text = '<span class="error">'
3334 . wfMessage( 'parser-template-recursion-depth-warning' )
3335 ->numParams( $limit )->inContentLanguage()->text()
3336 . '</span>';
3337 }
3338 }
3339 }
3340
3341 # Load from database
3342 if ( !$found && $title ) {
3343 if ( !Profiler::instance()->isPersistent() ) {
3344 # Too many unique items can kill profiling DBs/collectors
3345 $titleProfileIn = __METHOD__ . "-title-" . $title->getDBKey();
3346 wfProfileIn( $titleProfileIn ); // template in
3347 }
3348 wfProfileIn( __METHOD__ . '-loadtpl' );
3349 if ( !$title->isExternal() ) {
3350 if ( $title->isSpecialPage()
3351 && $this->mOptions->getAllowSpecialInclusion()
3352 && $this->ot['html'] )
3353 {
3354 // Pass the template arguments as URL parameters.
3355 // "uselang" will have no effect since the Language object
3356 // is forced to the one defined in ParserOptions.
3357 $pageArgs = array();
3358 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3359 $bits = $args->item( $i )->splitArg();
3360 if ( strval( $bits['index'] ) === '' ) {
3361 $name = trim( $frame->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
3362 $value = trim( $frame->expand( $bits['value'] ) );
3363 $pageArgs[$name] = $value;
3364 }
3365 }
3366
3367 // Create a new context to execute the special page
3368 $context = new RequestContext;
3369 $context->setTitle( $title );
3370 $context->setRequest( new FauxRequest( $pageArgs ) );
3371 $context->setUser( $this->getUser() );
3372 $context->setLanguage( $this->mOptions->getUserLangObj() );
3373 $ret = SpecialPageFactory::capturePath( $title, $context );
3374 if ( $ret ) {
3375 $text = $context->getOutput()->getHTML();
3376 $this->mOutput->addOutputPageMetadata( $context->getOutput() );
3377 $found = true;
3378 $isHTML = true;
3379 $this->disableCache();
3380 }
3381 } elseif ( MWNamespace::isNonincludable( $title->getNamespace() ) ) {
3382 $found = false; # access denied
3383 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
3384 } else {
3385 list( $text, $title ) = $this->getTemplateDom( $title );
3386 if ( $text !== false ) {
3387 $found = true;
3388 $isChildObj = true;
3389 }
3390 }
3391
3392 # If the title is valid but undisplayable, make a link to it
3393 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3394 $text = "[[:$titleText]]";
3395 $found = true;
3396 }
3397 } elseif ( $title->isTrans() ) {
3398 # Interwiki transclusion
3399 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3400 $text = $this->interwikiTransclude( $title, 'render' );
3401 $isHTML = true;
3402 } else {
3403 $text = $this->interwikiTransclude( $title, 'raw' );
3404 # Preprocess it like a template
3405 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3406 $isChildObj = true;
3407 }
3408 $found = true;
3409 }
3410
3411 # Do infinite loop check
3412 # This has to be done after redirect resolution to avoid infinite loops via redirects
3413 if ( !$frame->loopCheck( $title ) ) {
3414 $found = true;
3415 $text = '<span class="error">'
3416 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3417 . '</span>';
3418 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3419 }
3420 wfProfileOut( __METHOD__ . '-loadtpl' );
3421 }
3422
3423 # If we haven't found text to substitute by now, we're done
3424 # Recover the source wikitext and return it
3425 if ( !$found ) {
3426 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3427 if ( $titleProfileIn ) {
3428 wfProfileOut( $titleProfileIn ); // template out
3429 }
3430 wfProfileOut( __METHOD__ );
3431 return array( 'object' => $text );
3432 }
3433
3434 # Expand DOM-style return values in a child frame
3435 if ( $isChildObj ) {
3436 # Clean up argument array
3437 $newFrame = $frame->newChild( $args, $title );
3438
3439 if ( $nowiki ) {
3440 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3441 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3442 # Expansion is eligible for the empty-frame cache
3443 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3444 $text = $this->mTplExpandCache[$titleText];
3445 } else {
3446 $text = $newFrame->expand( $text );
3447 $this->mTplExpandCache[$titleText] = $text;
3448 }
3449 } else {
3450 # Uncached expansion
3451 $text = $newFrame->expand( $text );
3452 }
3453 }
3454 if ( $isLocalObj && $nowiki ) {
3455 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3456 $isLocalObj = false;
3457 }
3458
3459 if ( $titleProfileIn ) {
3460 wfProfileOut( $titleProfileIn ); // template out
3461 }
3462
3463 # Replace raw HTML by a placeholder
3464 if ( $isHTML ) {
3465 $text = $this->insertStripItem( $text );
3466 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3467 # Escape nowiki-style return values
3468 $text = wfEscapeWikiText( $text );
3469 } elseif ( is_string( $text )
3470 && !$piece['lineStart']
3471 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3472 {
3473 # Bug 529: if the template begins with a table or block-level
3474 # element, it should be treated as beginning a new line.
3475 # This behaviour is somewhat controversial.
3476 $text = "\n" . $text;
3477 }
3478
3479 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3480 # Error, oversize inclusion
3481 if ( $titleText !== false ) {
3482 # Make a working, properly escaped link if possible (bug 23588)
3483 $text = "[[:$titleText]]";
3484 } else {
3485 # This will probably not be a working link, but at least it may
3486 # provide some hint of where the problem is
3487 preg_replace( '/^:/', '', $originalTitle );
3488 $text = "[[:$originalTitle]]";
3489 }
3490 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3491 $this->limitationWarn( 'post-expand-template-inclusion' );
3492 }
3493
3494 if ( $isLocalObj ) {
3495 $ret = array( 'object' => $text );
3496 } else {
3497 $ret = array( 'text' => $text );
3498 }
3499
3500 wfProfileOut( __METHOD__ );
3501 return $ret;
3502 }
3503
3504 /**
3505 * Get the semi-parsed DOM representation of a template with a given title,
3506 * and its redirect destination title. Cached.
3507 *
3508 * @param $title Title
3509 *
3510 * @return array
3511 */
3512 function getTemplateDom( $title ) {
3513 $cacheTitle = $title;
3514 $titleText = $title->getPrefixedDBkey();
3515
3516 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3517 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3518 $title = Title::makeTitle( $ns, $dbk );
3519 $titleText = $title->getPrefixedDBkey();
3520 }
3521 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3522 return array( $this->mTplDomCache[$titleText], $title );
3523 }
3524
3525 # Cache miss, go to the database
3526 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3527
3528 if ( $text === false ) {
3529 $this->mTplDomCache[$titleText] = false;
3530 return array( false, $title );
3531 }
3532
3533 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3534 $this->mTplDomCache[ $titleText ] = $dom;
3535
3536 if ( !$title->equals( $cacheTitle ) ) {
3537 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3538 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3539 }
3540
3541 return array( $dom, $title );
3542 }
3543
3544 /**
3545 * Fetch the unparsed text of a template and register a reference to it.
3546 * @param Title $title
3547 * @return Array ( string or false, Title )
3548 */
3549 function fetchTemplateAndTitle( $title ) {
3550 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3551 $stuff = call_user_func( $templateCb, $title, $this );
3552 $text = $stuff['text'];
3553 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3554 if ( isset( $stuff['deps'] ) ) {
3555 foreach ( $stuff['deps'] as $dep ) {
3556 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3557 }
3558 }
3559 return array( $text, $finalTitle );
3560 }
3561
3562 /**
3563 * Fetch the unparsed text of a template and register a reference to it.
3564 * @param Title $title
3565 * @return mixed string or false
3566 */
3567 function fetchTemplate( $title ) {
3568 $rv = $this->fetchTemplateAndTitle( $title );
3569 return $rv[0];
3570 }
3571
3572 /**
3573 * Static function to get a template
3574 * Can be overridden via ParserOptions::setTemplateCallback().
3575 *
3576 * @param $title Title
3577 * @param $parser Parser
3578 *
3579 * @return array
3580 */
3581 static function statelessFetchTemplate( $title, $parser = false ) {
3582 $text = $skip = false;
3583 $finalTitle = $title;
3584 $deps = array();
3585
3586 # Loop to fetch the article, with up to 1 redirect
3587 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3588 # Give extensions a chance to select the revision instead
3589 $id = false; # Assume current
3590 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3591 array( $parser, $title, &$skip, &$id ) );
3592
3593 if ( $skip ) {
3594 $text = false;
3595 $deps[] = array(
3596 'title' => $title,
3597 'page_id' => $title->getArticleID(),
3598 'rev_id' => null
3599 );
3600 break;
3601 }
3602 # Get the revision
3603 $rev = $id
3604 ? Revision::newFromId( $id )
3605 : Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
3606 $rev_id = $rev ? $rev->getId() : 0;
3607 # If there is no current revision, there is no page
3608 if ( $id === false && !$rev ) {
3609 $linkCache = LinkCache::singleton();
3610 $linkCache->addBadLinkObj( $title );
3611 }
3612
3613 $deps[] = array(
3614 'title' => $title,
3615 'page_id' => $title->getArticleID(),
3616 'rev_id' => $rev_id );
3617 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3618 # We fetched a rev from a different title; register it too...
3619 $deps[] = array(
3620 'title' => $rev->getTitle(),
3621 'page_id' => $rev->getPage(),
3622 'rev_id' => $rev_id );
3623 }
3624
3625 if ( $rev ) {
3626 $content = $rev->getContent();
3627 $text = $content ? $content->getWikitextForTransclusion() : null;
3628
3629 if ( $text === false || $text === null ) {
3630 $text = false;
3631 break;
3632 }
3633 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3634 global $wgContLang;
3635 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3636 if ( !$message->exists() ) {
3637 $text = false;
3638 break;
3639 }
3640 $content = $message->content();
3641 $text = $message->plain();
3642 } else {
3643 break;
3644 }
3645 if ( !$content ) {
3646 break;
3647 }
3648 # Redirect?
3649 $finalTitle = $title;
3650 $title = $content->getRedirectTarget();
3651 }
3652 return array(
3653 'text' => $text,
3654 'finalTitle' => $finalTitle,
3655 'deps' => $deps );
3656 }
3657
3658 /**
3659 * Fetch a file and its title and register a reference to it.
3660 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3661 * @param Title $title
3662 * @param Array $options Array of options to RepoGroup::findFile
3663 * @return File|bool
3664 */
3665 function fetchFile( $title, $options = array() ) {
3666 $res = $this->fetchFileAndTitle( $title, $options );
3667 return $res[0];
3668 }
3669
3670 /**
3671 * Fetch a file and its title and register a reference to it.
3672 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3673 * @param Title $title
3674 * @param Array $options Array of options to RepoGroup::findFile
3675 * @return Array ( File or false, Title of file )
3676 */
3677 function fetchFileAndTitle( $title, $options = array() ) {
3678 if ( isset( $options['broken'] ) ) {
3679 $file = false; // broken thumbnail forced by hook
3680 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3681 $file = RepoGroup::singleton()->findFileFromKey( $options['sha1'], $options );
3682 } else { // get by (name,timestamp)
3683 $file = wfFindFile( $title, $options );
3684 }
3685 $time = $file ? $file->getTimestamp() : false;
3686 $sha1 = $file ? $file->getSha1() : false;
3687 # Register the file as a dependency...
3688 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3689 if ( $file && !$title->equals( $file->getTitle() ) ) {
3690 # Update fetched file title
3691 $title = $file->getTitle();
3692 if ( is_null( $file->getRedirectedTitle() ) ) {
3693 # This file was not a redirect, but the title does not match.
3694 # Register under the new name because otherwise the link will
3695 # get lost.
3696 $this->mOutput->addImage( $title->getDBkey(), $time, $sha1 );
3697 }
3698 }
3699 return array( $file, $title );
3700 }
3701
3702 /**
3703 * Transclude an interwiki link.
3704 *
3705 * @param $title Title
3706 * @param $action
3707 *
3708 * @return string
3709 */
3710 function interwikiTransclude( $title, $action ) {
3711 global $wgEnableScaryTranscluding;
3712
3713 if ( !$wgEnableScaryTranscluding ) {
3714 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3715 }
3716
3717 $url = $title->getFullUrl( "action=$action" );
3718
3719 if ( strlen( $url ) > 255 ) {
3720 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3721 }
3722 return $this->fetchScaryTemplateMaybeFromCache( $url );
3723 }
3724
3725 /**
3726 * @param $url string
3727 * @return Mixed|String
3728 */
3729 function fetchScaryTemplateMaybeFromCache( $url ) {
3730 global $wgTranscludeCacheExpiry;
3731 $dbr = wfGetDB( DB_SLAVE );
3732 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3733 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3734 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3735 if ( $obj ) {
3736 return $obj->tc_contents;
3737 }
3738
3739 $req = MWHttpRequest::factory( $url );
3740 $status = $req->execute(); // Status object
3741 if ( $status->isOK() ) {
3742 $text = $req->getContent();
3743 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3744 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3745 } else {
3746 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3747 }
3748
3749 $dbw = wfGetDB( DB_MASTER );
3750 $dbw->replace( 'transcache', array('tc_url'), array(
3751 'tc_url' => $url,
3752 'tc_time' => $dbw->timestamp( time() ),
3753 'tc_contents' => $text)
3754 );
3755 return $text;
3756 }
3757
3758 /**
3759 * Triple brace replacement -- used for template arguments
3760 * @private
3761 *
3762 * @param $piece array
3763 * @param $frame PPFrame
3764 *
3765 * @return array
3766 */
3767 function argSubstitution( $piece, $frame ) {
3768 wfProfileIn( __METHOD__ );
3769
3770 $error = false;
3771 $parts = $piece['parts'];
3772 $nameWithSpaces = $frame->expand( $piece['title'] );
3773 $argName = trim( $nameWithSpaces );
3774 $object = false;
3775 $text = $frame->getArgument( $argName );
3776 if ( $text === false && $parts->getLength() > 0
3777 && (
3778 $this->ot['html']
3779 || $this->ot['pre']
3780 || ( $this->ot['wiki'] && $frame->isTemplate() )
3781 )
3782 ) {
3783 # No match in frame, use the supplied default
3784 $object = $parts->item( 0 )->getChildren();
3785 }
3786 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3787 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3788 $this->limitationWarn( 'post-expand-template-argument' );
3789 }
3790
3791 if ( $text === false && $object === false ) {
3792 # No match anywhere
3793 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3794 }
3795 if ( $error !== false ) {
3796 $text .= $error;
3797 }
3798 if ( $object !== false ) {
3799 $ret = array( 'object' => $object );
3800 } else {
3801 $ret = array( 'text' => $text );
3802 }
3803
3804 wfProfileOut( __METHOD__ );
3805 return $ret;
3806 }
3807
3808 /**
3809 * Return the text to be used for a given extension tag.
3810 * This is the ghost of strip().
3811 *
3812 * @param $params array Associative array of parameters:
3813 * name PPNode for the tag name
3814 * attr PPNode for unparsed text where tag attributes are thought to be
3815 * attributes Optional associative array of parsed attributes
3816 * inner Contents of extension element
3817 * noClose Original text did not have a close tag
3818 * @param $frame PPFrame
3819 *
3820 * @throws MWException
3821 * @return string
3822 */
3823 function extensionSubstitution( $params, $frame ) {
3824 $name = $frame->expand( $params['name'] );
3825 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3826 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3827 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3828
3829 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3830 ( $this->ot['html'] || $this->ot['pre'] );
3831 if ( $isFunctionTag ) {
3832 $markerType = 'none';
3833 } else {
3834 $markerType = 'general';
3835 }
3836 if ( $this->ot['html'] || $isFunctionTag ) {
3837 $name = strtolower( $name );
3838 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3839 if ( isset( $params['attributes'] ) ) {
3840 $attributes = $attributes + $params['attributes'];
3841 }
3842
3843 if ( isset( $this->mTagHooks[$name] ) ) {
3844 # Workaround for PHP bug 35229 and similar
3845 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3846 throw new MWException( "Tag hook for $name is not callable\n" );
3847 }
3848 $output = call_user_func_array( $this->mTagHooks[$name],
3849 array( $content, $attributes, $this, $frame ) );
3850 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3851 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3852 if ( !is_callable( $callback ) ) {
3853 throw new MWException( "Tag hook for $name is not callable\n" );
3854 }
3855
3856 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3857 } else {
3858 $output = '<span class="error">Invalid tag extension name: ' .
3859 htmlspecialchars( $name ) . '</span>';
3860 }
3861
3862 if ( is_array( $output ) ) {
3863 # Extract flags to local scope (to override $markerType)
3864 $flags = $output;
3865 $output = $flags[0];
3866 unset( $flags[0] );
3867 extract( $flags );
3868 }
3869 } else {
3870 if ( is_null( $attrText ) ) {
3871 $attrText = '';
3872 }
3873 if ( isset( $params['attributes'] ) ) {
3874 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3875 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3876 htmlspecialchars( $attrValue ) . '"';
3877 }
3878 }
3879 if ( $content === null ) {
3880 $output = "<$name$attrText/>";
3881 } else {
3882 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3883 $output = "<$name$attrText>$content$close";
3884 }
3885 }
3886
3887 if ( $markerType === 'none' ) {
3888 return $output;
3889 } elseif ( $markerType === 'nowiki' ) {
3890 $this->mStripState->addNoWiki( $marker, $output );
3891 } elseif ( $markerType === 'general' ) {
3892 $this->mStripState->addGeneral( $marker, $output );
3893 } else {
3894 throw new MWException( __METHOD__.': invalid marker type' );
3895 }
3896 return $marker;
3897 }
3898
3899 /**
3900 * Increment an include size counter
3901 *
3902 * @param $type String: the type of expansion
3903 * @param $size Integer: the size of the text
3904 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3905 */
3906 function incrementIncludeSize( $type, $size ) {
3907 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize() ) {
3908 return false;
3909 } else {
3910 $this->mIncludeSizes[$type] += $size;
3911 return true;
3912 }
3913 }
3914
3915 /**
3916 * Increment the expensive function count
3917 *
3918 * @return Boolean: false if the limit has been exceeded
3919 */
3920 function incrementExpensiveFunctionCount() {
3921 $this->mExpensiveFunctionCount++;
3922 return $this->mExpensiveFunctionCount <= $this->mOptions->getExpensiveParserFunctionLimit();
3923 }
3924
3925 /**
3926 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3927 * Fills $this->mDoubleUnderscores, returns the modified text
3928 *
3929 * @param $text string
3930 *
3931 * @return string
3932 */
3933 function doDoubleUnderscore( $text ) {
3934 wfProfileIn( __METHOD__ );
3935
3936 # The position of __TOC__ needs to be recorded
3937 $mw = MagicWord::get( 'toc' );
3938 if ( $mw->match( $text ) ) {
3939 $this->mShowToc = true;
3940 $this->mForceTocPosition = true;
3941
3942 # Set a placeholder. At the end we'll fill it in with the TOC.
3943 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3944
3945 # Only keep the first one.
3946 $text = $mw->replace( '', $text );
3947 }
3948
3949 # Now match and remove the rest of them
3950 $mwa = MagicWord::getDoubleUnderscoreArray();
3951 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3952
3953 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3954 $this->mOutput->mNoGallery = true;
3955 }
3956 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3957 $this->mShowToc = false;
3958 }
3959 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3960 $this->addTrackingCategory( 'hidden-category-category' );
3961 }
3962 # (bug 8068) Allow control over whether robots index a page.
3963 #
3964 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3965 # is not desirable, the last one on the page should win.
3966 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3967 $this->mOutput->setIndexPolicy( 'noindex' );
3968 $this->addTrackingCategory( 'noindex-category' );
3969 }
3970 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3971 $this->mOutput->setIndexPolicy( 'index' );
3972 $this->addTrackingCategory( 'index-category' );
3973 }
3974
3975 # Cache all double underscores in the database
3976 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3977 $this->mOutput->setProperty( $key, '' );
3978 }
3979
3980 wfProfileOut( __METHOD__ );
3981 return $text;
3982 }
3983
3984 /**
3985 * Add a tracking category, getting the title from a system message,
3986 * or print a debug message if the title is invalid.
3987 *
3988 * @param $msg String: message key
3989 * @return Boolean: whether the addition was successful
3990 */
3991 public function addTrackingCategory( $msg ) {
3992 if ( $this->mTitle->getNamespace() === NS_SPECIAL ) {
3993 wfDebug( __METHOD__.": Not adding tracking category $msg to special page!\n" );
3994 return false;
3995 }
3996 // Important to parse with correct title (bug 31469)
3997 $cat = wfMessage( $msg )
3998 ->title( $this->getTitle() )
3999 ->inContentLanguage()
4000 ->text();
4001
4002 # Allow tracking categories to be disabled by setting them to "-"
4003 if ( $cat === '-' ) {
4004 return false;
4005 }
4006
4007 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
4008 if ( $containerCategory ) {
4009 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4010 return true;
4011 } else {
4012 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
4013 return false;
4014 }
4015 }
4016
4017 /**
4018 * This function accomplishes several tasks:
4019 * 1) Auto-number headings if that option is enabled
4020 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4021 * 3) Add a Table of contents on the top for users who have enabled the option
4022 * 4) Auto-anchor headings
4023 *
4024 * It loops through all headlines, collects the necessary data, then splits up the
4025 * string and re-inserts the newly formatted headlines.
4026 *
4027 * @param $text String
4028 * @param $origText String: original, untouched wikitext
4029 * @param $isMain Boolean
4030 * @return mixed|string
4031 * @private
4032 */
4033 function formatHeadings( $text, $origText, $isMain=true ) {
4034 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4035
4036 # Inhibit editsection links if requested in the page
4037 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
4038 $maybeShowEditLink = $showEditLink = false;
4039 } else {
4040 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4041 $showEditLink = $this->mOptions->getEditSection();
4042 }
4043 if ( $showEditLink ) {
4044 $this->mOutput->setEditSectionTokens( true );
4045 }
4046
4047 # Get all headlines for numbering them and adding funky stuff like [edit]
4048 # links - this is for later, but we need the number of headlines right now
4049 $matches = array();
4050 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4051
4052 # if there are fewer than 4 headlines in the article, do not show TOC
4053 # unless it's been explicitly enabled.
4054 $enoughToc = $this->mShowToc &&
4055 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
4056
4057 # Allow user to stipulate that a page should have a "new section"
4058 # link added via __NEWSECTIONLINK__
4059 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
4060 $this->mOutput->setNewSection( true );
4061 }
4062
4063 # Allow user to remove the "new section"
4064 # link via __NONEWSECTIONLINK__
4065 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
4066 $this->mOutput->hideNewSection( true );
4067 }
4068
4069 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4070 # override above conditions and always show TOC above first header
4071 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
4072 $this->mShowToc = true;
4073 $enoughToc = true;
4074 }
4075
4076 # headline counter
4077 $headlineCount = 0;
4078 $numVisible = 0;
4079
4080 # Ugh .. the TOC should have neat indentation levels which can be
4081 # passed to the skin functions. These are determined here
4082 $toc = '';
4083 $full = '';
4084 $head = array();
4085 $sublevelCount = array();
4086 $levelCount = array();
4087 $level = 0;
4088 $prevlevel = 0;
4089 $toclevel = 0;
4090 $prevtoclevel = 0;
4091 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
4092 $baseTitleText = $this->mTitle->getPrefixedDBkey();
4093 $oldType = $this->mOutputType;
4094 $this->setOutputType( self::OT_WIKI );
4095 $frame = $this->getPreprocessor()->newFrame();
4096 $root = $this->preprocessToDom( $origText );
4097 $node = $root->getFirstChild();
4098 $byteOffset = 0;
4099 $tocraw = array();
4100 $refers = array();
4101
4102 foreach ( $matches[3] as $headline ) {
4103 $isTemplate = false;
4104 $titleText = false;
4105 $sectionIndex = false;
4106 $numbering = '';
4107 $markerMatches = array();
4108 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4109 $serial = $markerMatches[1];
4110 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
4111 $isTemplate = ( $titleText != $baseTitleText );
4112 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4113 }
4114
4115 if ( $toclevel ) {
4116 $prevlevel = $level;
4117 }
4118 $level = $matches[1][$headlineCount];
4119
4120 if ( $level > $prevlevel ) {
4121 # Increase TOC level
4122 $toclevel++;
4123 $sublevelCount[$toclevel] = 0;
4124 if ( $toclevel<$wgMaxTocLevel ) {
4125 $prevtoclevel = $toclevel;
4126 $toc .= Linker::tocIndent();
4127 $numVisible++;
4128 }
4129 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4130 # Decrease TOC level, find level to jump to
4131
4132 for ( $i = $toclevel; $i > 0; $i-- ) {
4133 if ( $levelCount[$i] == $level ) {
4134 # Found last matching level
4135 $toclevel = $i;
4136 break;
4137 } elseif ( $levelCount[$i] < $level ) {
4138 # Found first matching level below current level
4139 $toclevel = $i + 1;
4140 break;
4141 }
4142 }
4143 if ( $i == 0 ) {
4144 $toclevel = 1;
4145 }
4146 if ( $toclevel<$wgMaxTocLevel ) {
4147 if ( $prevtoclevel < $wgMaxTocLevel ) {
4148 # Unindent only if the previous toc level was shown :p
4149 $toc .= Linker::tocUnindent( $prevtoclevel - $toclevel );
4150 $prevtoclevel = $toclevel;
4151 } else {
4152 $toc .= Linker::tocLineEnd();
4153 }
4154 }
4155 } else {
4156 # No change in level, end TOC line
4157 if ( $toclevel<$wgMaxTocLevel ) {
4158 $toc .= Linker::tocLineEnd();
4159 }
4160 }
4161
4162 $levelCount[$toclevel] = $level;
4163
4164 # count number of headlines for each level
4165 @$sublevelCount[$toclevel]++;
4166 $dot = 0;
4167 for( $i = 1; $i <= $toclevel; $i++ ) {
4168 if ( !empty( $sublevelCount[$i] ) ) {
4169 if ( $dot ) {
4170 $numbering .= '.';
4171 }
4172 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4173 $dot = 1;
4174 }
4175 }
4176
4177 # The safe header is a version of the header text safe to use for links
4178
4179 # Remove link placeholders by the link text.
4180 # <!--LINK number-->
4181 # turns into
4182 # link text with suffix
4183 # Do this before unstrip since link text can contain strip markers
4184 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4185
4186 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4187 $safeHeadline = $this->mStripState->unstripBoth( $safeHeadline );
4188
4189 # Strip out HTML (first regex removes any tag not allowed)
4190 # Allowed tags are:
4191 # * <sup> and <sub> (bug 8393)
4192 # * <i> (bug 26375)
4193 # * <b> (r105284)
4194 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4195 #
4196 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4197 # to allow setting directionality in toc items.
4198 $tocline = preg_replace(
4199 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?'.'>#' ),
4200 array( '', '<$1>' ),
4201 $safeHeadline
4202 );
4203 $tocline = trim( $tocline );
4204
4205 # For the anchor, strip out HTML-y stuff period
4206 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4207 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
4208
4209 # Save headline for section edit hint before it's escaped
4210 $headlineHint = $safeHeadline;
4211
4212 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4213 # For reverse compatibility, provide an id that's
4214 # HTML4-compatible, like we used to.
4215 #
4216 # It may be worth noting, academically, that it's possible for
4217 # the legacy anchor to conflict with a non-legacy headline
4218 # anchor on the page. In this case likely the "correct" thing
4219 # would be to either drop the legacy anchors or make sure
4220 # they're numbered first. However, this would require people
4221 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4222 # manually, so let's not bother worrying about it.
4223 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
4224 array( 'noninitial', 'legacy' ) );
4225 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
4226
4227 if ( $legacyHeadline == $safeHeadline ) {
4228 # No reason to have both (in fact, we can't)
4229 $legacyHeadline = false;
4230 }
4231 } else {
4232 $legacyHeadline = false;
4233 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
4234 'noninitial' );
4235 }
4236
4237 # HTML names must be case-insensitively unique (bug 10721).
4238 # This does not apply to Unicode characters per
4239 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4240 # @todo FIXME: We may be changing them depending on the current locale.
4241 $arrayKey = strtolower( $safeHeadline );
4242 if ( $legacyHeadline === false ) {
4243 $legacyArrayKey = false;
4244 } else {
4245 $legacyArrayKey = strtolower( $legacyHeadline );
4246 }
4247
4248 # count how many in assoc. array so we can track dupes in anchors
4249 if ( isset( $refers[$arrayKey] ) ) {
4250 $refers[$arrayKey]++;
4251 } else {
4252 $refers[$arrayKey] = 1;
4253 }
4254 if ( isset( $refers[$legacyArrayKey] ) ) {
4255 $refers[$legacyArrayKey]++;
4256 } else {
4257 $refers[$legacyArrayKey] = 1;
4258 }
4259
4260 # Don't number the heading if it is the only one (looks silly)
4261 if ( count( $matches[3] ) > 1 && $this->mOptions->getNumberHeadings() ) {
4262 # the two are different if the line contains a link
4263 $headline = Html::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4264 }
4265
4266 # Create the anchor for linking from the TOC to the section
4267 $anchor = $safeHeadline;
4268 $legacyAnchor = $legacyHeadline;
4269 if ( $refers[$arrayKey] > 1 ) {
4270 $anchor .= '_' . $refers[$arrayKey];
4271 }
4272 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4273 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4274 }
4275 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
4276 $toc .= Linker::tocLine( $anchor, $tocline,
4277 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
4278 }
4279
4280 # Add the section to the section tree
4281 # Find the DOM node for this header
4282 while ( $node && !$isTemplate ) {
4283 if ( $node->getName() === 'h' ) {
4284 $bits = $node->splitHeading();
4285 if ( $bits['i'] == $sectionIndex ) {
4286 break;
4287 }
4288 }
4289 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
4290 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
4291 $node = $node->getNextSibling();
4292 }
4293 $tocraw[] = array(
4294 'toclevel' => $toclevel,
4295 'level' => $level,
4296 'line' => $tocline,
4297 'number' => $numbering,
4298 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
4299 'fromtitle' => $titleText,
4300 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
4301 'anchor' => $anchor,
4302 );
4303
4304 # give headline the correct <h#> tag
4305 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4306 // Output edit section links as markers with styles that can be customized by skins
4307 if ( $isTemplate ) {
4308 # Put a T flag in the section identifier, to indicate to extractSections()
4309 # that sections inside <includeonly> should be counted.
4310 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4311 } else {
4312 $editlinkArgs = array( $this->mTitle->getPrefixedText(), $sectionIndex, $headlineHint );
4313 }
4314 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4315 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4316 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4317 // so we don't have to worry about a user trying to input one of these markers directly.
4318 // We use a page and section attribute to stop the language converter from converting these important bits
4319 // of data, but put the headline hint inside a content block because the language converter is supposed to
4320 // be able to convert that piece of data.
4321 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4322 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4323 if ( isset($editlinkArgs[2]) ) {
4324 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4325 } else {
4326 $editlink .= '/>';
4327 }
4328 } else {
4329 $editlink = '';
4330 }
4331 $head[$headlineCount] = Linker::makeHeadline( $level,
4332 $matches['attrib'][$headlineCount], $anchor, $headline,
4333 $editlink, $legacyAnchor );
4334
4335 $headlineCount++;
4336 }
4337
4338 $this->setOutputType( $oldType );
4339
4340 # Never ever show TOC if no headers
4341 if ( $numVisible < 1 ) {
4342 $enoughToc = false;
4343 }
4344
4345 if ( $enoughToc ) {
4346 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4347 $toc .= Linker::tocUnindent( $prevtoclevel - 1 );
4348 }
4349 $toc = Linker::tocList( $toc, $this->mOptions->getUserLangObj() );
4350 $this->mOutput->setTOCHTML( $toc );
4351 }
4352
4353 if ( $isMain ) {
4354 $this->mOutput->setSections( $tocraw );
4355 }
4356
4357 # split up and insert constructed headlines
4358 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4359 $i = 0;
4360
4361 // build an array of document sections
4362 $sections = array();
4363 foreach ( $blocks as $block ) {
4364 // $head is zero-based, sections aren't.
4365 if ( empty( $head[$i - 1] ) ) {
4366 $sections[$i] = $block;
4367 } else {
4368 $sections[$i] = $head[$i - 1] . $block;
4369 }
4370
4371 /**
4372 * Send a hook, one per section.
4373 * The idea here is to be able to make section-level DIVs, but to do so in a
4374 * lower-impact, more correct way than r50769
4375 *
4376 * $this : caller
4377 * $section : the section number
4378 * &$sectionContent : ref to the content of the section
4379 * $showEditLinks : boolean describing whether this section has an edit link
4380 */
4381 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4382
4383 $i++;
4384 }
4385
4386 if ( $enoughToc && $isMain && !$this->mForceTocPosition ) {
4387 // append the TOC at the beginning
4388 // Top anchor now in skin
4389 $sections[0] = $sections[0] . $toc . "\n";
4390 }
4391
4392 $full .= join( '', $sections );
4393
4394 if ( $this->mForceTocPosition ) {
4395 return str_replace( '<!--MWTOC-->', $toc, $full );
4396 } else {
4397 return $full;
4398 }
4399 }
4400
4401 /**
4402 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4403 * conversion, substitting signatures, {{subst:}} templates, etc.
4404 *
4405 * @param $text String: the text to transform
4406 * @param $title Title: the Title object for the current article
4407 * @param $user User: the User object describing the current user
4408 * @param $options ParserOptions: parsing options
4409 * @param $clearState Boolean: whether to clear the parser state first
4410 * @return String: the altered wiki markup
4411 */
4412 public function preSaveTransform( $text, Title $title, User $user, ParserOptions $options, $clearState = true ) {
4413 $this->startParse( $title, $options, self::OT_WIKI, $clearState );
4414 $this->setUser( $user );
4415
4416 $pairs = array(
4417 "\r\n" => "\n",
4418 );
4419 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4420 if( $options->getPreSaveTransform() ) {
4421 $text = $this->pstPass2( $text, $user );
4422 }
4423 $text = $this->mStripState->unstripBoth( $text );
4424
4425 $this->setUser( null ); #Reset
4426
4427 return $text;
4428 }
4429
4430 /**
4431 * Pre-save transform helper function
4432 * @private
4433 *
4434 * @param $text string
4435 * @param $user User
4436 *
4437 * @return string
4438 */
4439 function pstPass2( $text, $user ) {
4440 global $wgContLang, $wgLocaltimezone;
4441
4442 # Note: This is the timestamp saved as hardcoded wikitext to
4443 # the database, we use $wgContLang here in order to give
4444 # everyone the same signature and use the default one rather
4445 # than the one selected in each user's preferences.
4446 # (see also bug 12815)
4447 $ts = $this->mOptions->getTimestamp();
4448 if ( isset( $wgLocaltimezone ) ) {
4449 $tz = $wgLocaltimezone;
4450 } else {
4451 $tz = date_default_timezone_get();
4452 }
4453
4454 $unixts = wfTimestamp( TS_UNIX, $ts );
4455 $oldtz = date_default_timezone_get();
4456 date_default_timezone_set( $tz );
4457 $ts = date( 'YmdHis', $unixts );
4458 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4459
4460 # Allow translation of timezones through wiki. date() can return
4461 # whatever crap the system uses, localised or not, so we cannot
4462 # ship premade translations.
4463 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4464 $msg = wfMessage( $key )->inContentLanguage();
4465 if ( $msg->exists() ) {
4466 $tzMsg = $msg->text();
4467 }
4468
4469 date_default_timezone_set( $oldtz );
4470
4471 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4472
4473 # Variable replacement
4474 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4475 $text = $this->replaceVariables( $text );
4476
4477 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4478 # which may corrupt this parser instance via its wfMessage()->text() call-
4479
4480 # Signatures
4481 $sigText = $this->getUserSig( $user );
4482 $text = strtr( $text, array(
4483 '~~~~~' => $d,
4484 '~~~~' => "$sigText $d",
4485 '~~~' => $sigText
4486 ) );
4487
4488 # Context links: [[|name]] and [[name (context)|]]
4489 $tc = '[' . Title::legalChars() . ']';
4490 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4491
4492 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4493 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4494 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4495 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4496
4497 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4498 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4499 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4500 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4501
4502 $t = $this->mTitle->getText();
4503 $m = array();
4504 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4505 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4506 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4507 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4508 } else {
4509 # if there's no context, don't bother duplicating the title
4510 $text = preg_replace( $p2, '[[\\1]]', $text );
4511 }
4512
4513 # Trim trailing whitespace
4514 $text = rtrim( $text );
4515
4516 return $text;
4517 }
4518
4519 /**
4520 * Fetch the user's signature text, if any, and normalize to
4521 * validated, ready-to-insert wikitext.
4522 * If you have pre-fetched the nickname or the fancySig option, you can
4523 * specify them here to save a database query.
4524 * Do not reuse this parser instance after calling getUserSig(),
4525 * as it may have changed if it's the $wgParser.
4526 *
4527 * @param $user User
4528 * @param $nickname String|bool nickname to use or false to use user's default nickname
4529 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4530 * or null to use default value
4531 * @return string
4532 */
4533 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4534 global $wgMaxSigChars;
4535
4536 $username = $user->getName();
4537
4538 # If not given, retrieve from the user object.
4539 if ( $nickname === false )
4540 $nickname = $user->getOption( 'nickname' );
4541
4542 if ( is_null( $fancySig ) ) {
4543 $fancySig = $user->getBoolOption( 'fancysig' );
4544 }
4545
4546 $nickname = $nickname == null ? $username : $nickname;
4547
4548 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4549 $nickname = $username;
4550 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4551 } elseif ( $fancySig !== false ) {
4552 # Sig. might contain markup; validate this
4553 if ( $this->validateSig( $nickname ) !== false ) {
4554 # Validated; clean up (if needed) and return it
4555 return $this->cleanSig( $nickname, true );
4556 } else {
4557 # Failed to validate; fall back to the default
4558 $nickname = $username;
4559 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4560 }
4561 }
4562
4563 # Make sure nickname doesnt get a sig in a sig
4564 $nickname = self::cleanSigInSig( $nickname );
4565
4566 # If we're still here, make it a link to the user page
4567 $userText = wfEscapeWikiText( $username );
4568 $nickText = wfEscapeWikiText( $nickname );
4569 $msgName = $user->isAnon() ? 'signature-anon' : 'signature';
4570
4571 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4572 }
4573
4574 /**
4575 * Check that the user's signature contains no bad XML
4576 *
4577 * @param $text String
4578 * @return mixed An expanded string, or false if invalid.
4579 */
4580 function validateSig( $text ) {
4581 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4582 }
4583
4584 /**
4585 * Clean up signature text
4586 *
4587 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4588 * 2) Substitute all transclusions
4589 *
4590 * @param $text String
4591 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4592 * @return String: signature text
4593 */
4594 public function cleanSig( $text, $parsing = false ) {
4595 if ( !$parsing ) {
4596 global $wgTitle;
4597 $this->startParse( $wgTitle, new ParserOptions, self::OT_PREPROCESS, true );
4598 }
4599
4600 # Option to disable this feature
4601 if ( !$this->mOptions->getCleanSignatures() ) {
4602 return $text;
4603 }
4604
4605 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4606 # => Move this logic to braceSubstitution()
4607 $substWord = MagicWord::get( 'subst' );
4608 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4609 $substText = '{{' . $substWord->getSynonym( 0 );
4610
4611 $text = preg_replace( $substRegex, $substText, $text );
4612 $text = self::cleanSigInSig( $text );
4613 $dom = $this->preprocessToDom( $text );
4614 $frame = $this->getPreprocessor()->newFrame();
4615 $text = $frame->expand( $dom );
4616
4617 if ( !$parsing ) {
4618 $text = $this->mStripState->unstripBoth( $text );
4619 }
4620
4621 return $text;
4622 }
4623
4624 /**
4625 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4626 *
4627 * @param $text String
4628 * @return String: signature text with /~{3,5}/ removed
4629 */
4630 public static function cleanSigInSig( $text ) {
4631 $text = preg_replace( '/~{3,5}/', '', $text );
4632 return $text;
4633 }
4634
4635 /**
4636 * Set up some variables which are usually set up in parse()
4637 * so that an external function can call some class members with confidence
4638 *
4639 * @param $title Title|null
4640 * @param $options ParserOptions
4641 * @param $outputType
4642 * @param $clearState bool
4643 */
4644 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4645 $this->startParse( $title, $options, $outputType, $clearState );
4646 }
4647
4648 /**
4649 * @param $title Title|null
4650 * @param $options ParserOptions
4651 * @param $outputType
4652 * @param $clearState bool
4653 */
4654 private function startParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4655 $this->setTitle( $title );
4656 $this->mOptions = $options;
4657 $this->setOutputType( $outputType );
4658 if ( $clearState ) {
4659 $this->clearState();
4660 }
4661 }
4662
4663 /**
4664 * Wrapper for preprocess()
4665 *
4666 * @param $text String: the text to preprocess
4667 * @param $options ParserOptions: options
4668 * @param $title Title object or null to use $wgTitle
4669 * @return String
4670 */
4671 public function transformMsg( $text, $options, $title = null ) {
4672 static $executing = false;
4673
4674 # Guard against infinite recursion
4675 if ( $executing ) {
4676 return $text;
4677 }
4678 $executing = true;
4679
4680 wfProfileIn( __METHOD__ );
4681 if ( !$title ) {
4682 global $wgTitle;
4683 $title = $wgTitle;
4684 }
4685 if ( !$title ) {
4686 # It's not uncommon having a null $wgTitle in scripts. See r80898
4687 # Create a ghost title in such case
4688 $title = Title::newFromText( 'Dwimmerlaik' );
4689 }
4690 $text = $this->preprocess( $text, $title, $options );
4691
4692 $executing = false;
4693 wfProfileOut( __METHOD__ );
4694 return $text;
4695 }
4696
4697 /**
4698 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4699 * The callback should have the following form:
4700 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4701 *
4702 * Transform and return $text. Use $parser for any required context, e.g. use
4703 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4704 *
4705 * Hooks may return extended information by returning an array, of which the
4706 * first numbered element (index 0) must be the return string, and all other
4707 * entries are extracted into local variables within an internal function
4708 * in the Parser class.
4709 *
4710 * This interface (introduced r61913) appears to be undocumented, but
4711 * 'markerName' is used by some core tag hooks to override which strip
4712 * array their results are placed in. **Use great caution if attempting
4713 * this interface, as it is not documented and injudicious use could smash
4714 * private variables.**
4715 *
4716 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4717 * @param $callback Mixed: the callback function (and object) to use for the tag
4718 * @throws MWException
4719 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4720 */
4721 public function setHook( $tag, $callback ) {
4722 $tag = strtolower( $tag );
4723 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4724 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4725 }
4726 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4727 $this->mTagHooks[$tag] = $callback;
4728 if ( !in_array( $tag, $this->mStripList ) ) {
4729 $this->mStripList[] = $tag;
4730 }
4731
4732 return $oldVal;
4733 }
4734
4735 /**
4736 * As setHook(), but letting the contents be parsed.
4737 *
4738 * Transparent tag hooks are like regular XML-style tag hooks, except they
4739 * operate late in the transformation sequence, on HTML instead of wikitext.
4740 *
4741 * This is probably obsoleted by things dealing with parser frames?
4742 * The only extension currently using it is geoserver.
4743 *
4744 * @since 1.10
4745 * @todo better document or deprecate this
4746 *
4747 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4748 * @param $callback Mixed: the callback function (and object) to use for the tag
4749 * @throws MWException
4750 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4751 */
4752 function setTransparentTagHook( $tag, $callback ) {
4753 $tag = strtolower( $tag );
4754 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4755 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4756 }
4757 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4758 $this->mTransparentTagHooks[$tag] = $callback;
4759
4760 return $oldVal;
4761 }
4762
4763 /**
4764 * Remove all tag hooks
4765 */
4766 function clearTagHooks() {
4767 $this->mTagHooks = array();
4768 $this->mFunctionTagHooks = array();
4769 $this->mStripList = $this->mDefaultStripList;
4770 }
4771
4772 /**
4773 * Create a function, e.g. {{sum:1|2|3}}
4774 * The callback function should have the form:
4775 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4776 *
4777 * Or with SFH_OBJECT_ARGS:
4778 * function myParserFunction( $parser, $frame, $args ) { ... }
4779 *
4780 * The callback may either return the text result of the function, or an array with the text
4781 * in element 0, and a number of flags in the other elements. The names of the flags are
4782 * specified in the keys. Valid flags are:
4783 * found The text returned is valid, stop processing the template. This
4784 * is on by default.
4785 * nowiki Wiki markup in the return value should be escaped
4786 * isHTML The returned text is HTML, armour it against wikitext transformation
4787 *
4788 * @param $id String: The magic word ID
4789 * @param $callback Mixed: the callback function (and object) to use
4790 * @param $flags Integer: a combination of the following flags:
4791 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4792 *
4793 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4794 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4795 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4796 * the arguments, and to control the way they are expanded.
4797 *
4798 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4799 * arguments, for instance:
4800 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4801 *
4802 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4803 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4804 * working if/when this is changed.
4805 *
4806 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4807 * expansion.
4808 *
4809 * Please read the documentation in includes/parser/Preprocessor.php for more information
4810 * about the methods available in PPFrame and PPNode.
4811 *
4812 * @throws MWException
4813 * @return string|callback The old callback function for this name, if any
4814 */
4815 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4816 global $wgContLang;
4817
4818 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4819 $this->mFunctionHooks[$id] = array( $callback, $flags );
4820
4821 # Add to function cache
4822 $mw = MagicWord::get( $id );
4823 if ( !$mw )
4824 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4825
4826 $synonyms = $mw->getSynonyms();
4827 $sensitive = intval( $mw->isCaseSensitive() );
4828
4829 foreach ( $synonyms as $syn ) {
4830 # Case
4831 if ( !$sensitive ) {
4832 $syn = $wgContLang->lc( $syn );
4833 }
4834 # Add leading hash
4835 if ( !( $flags & SFH_NO_HASH ) ) {
4836 $syn = '#' . $syn;
4837 }
4838 # Remove trailing colon
4839 if ( substr( $syn, -1, 1 ) === ':' ) {
4840 $syn = substr( $syn, 0, -1 );
4841 }
4842 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4843 }
4844 return $oldVal;
4845 }
4846
4847 /**
4848 * Get all registered function hook identifiers
4849 *
4850 * @return Array
4851 */
4852 function getFunctionHooks() {
4853 return array_keys( $this->mFunctionHooks );
4854 }
4855
4856 /**
4857 * Create a tag function, e.g. "<test>some stuff</test>".
4858 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4859 * Unlike parser functions, their content is not preprocessed.
4860 * @param $tag
4861 * @param $callback
4862 * @param $flags
4863 * @throws MWException
4864 * @return null
4865 */
4866 function setFunctionTagHook( $tag, $callback, $flags ) {
4867 $tag = strtolower( $tag );
4868 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4869 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4870 $this->mFunctionTagHooks[$tag] : null;
4871 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4872
4873 if ( !in_array( $tag, $this->mStripList ) ) {
4874 $this->mStripList[] = $tag;
4875 }
4876
4877 return $old;
4878 }
4879
4880 /**
4881 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4882 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4883 * Placeholders created in Skin::makeLinkObj()
4884 *
4885 * @param $text string
4886 * @param $options int
4887 *
4888 * @return array of link CSS classes, indexed by PDBK.
4889 */
4890 function replaceLinkHolders( &$text, $options = 0 ) {
4891 return $this->mLinkHolders->replace( $text );
4892 }
4893
4894 /**
4895 * Replace "<!--LINK-->" link placeholders with plain text of links
4896 * (not HTML-formatted).
4897 *
4898 * @param $text String
4899 * @return String
4900 */
4901 function replaceLinkHoldersText( $text ) {
4902 return $this->mLinkHolders->replaceText( $text );
4903 }
4904
4905 /**
4906 * Renders an image gallery from a text with one line per image.
4907 * text labels may be given by using |-style alternative text. E.g.
4908 * Image:one.jpg|The number "1"
4909 * Image:tree.jpg|A tree
4910 * given as text will return the HTML of a gallery with two images,
4911 * labeled 'The number "1"' and
4912 * 'A tree'.
4913 *
4914 * @param string $text
4915 * @param array $params
4916 * @return string HTML
4917 */
4918 function renderImageGallery( $text, $params ) {
4919 $ig = new ImageGallery();
4920 $ig->setContextTitle( $this->mTitle );
4921 $ig->setShowBytes( false );
4922 $ig->setShowFilename( false );
4923 $ig->setParser( $this );
4924 $ig->setHideBadImages();
4925 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4926
4927 if ( isset( $params['showfilename'] ) ) {
4928 $ig->setShowFilename( true );
4929 } else {
4930 $ig->setShowFilename( false );
4931 }
4932 if ( isset( $params['caption'] ) ) {
4933 $caption = $params['caption'];
4934 $caption = htmlspecialchars( $caption );
4935 $caption = $this->replaceInternalLinks( $caption );
4936 $ig->setCaptionHtml( $caption );
4937 }
4938 if ( isset( $params['perrow'] ) ) {
4939 $ig->setPerRow( $params['perrow'] );
4940 }
4941 if ( isset( $params['widths'] ) ) {
4942 $ig->setWidths( $params['widths'] );
4943 }
4944 if ( isset( $params['heights'] ) ) {
4945 $ig->setHeights( $params['heights'] );
4946 }
4947
4948 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4949
4950 $lines = StringUtils::explode( "\n", $text );
4951 foreach ( $lines as $line ) {
4952 # match lines like these:
4953 # Image:someimage.jpg|This is some image
4954 $matches = array();
4955 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4956 # Skip empty lines
4957 if ( count( $matches ) == 0 ) {
4958 continue;
4959 }
4960
4961 if ( strpos( $matches[0], '%' ) !== false ) {
4962 $matches[1] = rawurldecode( $matches[1] );
4963 }
4964 $title = Title::newFromText( $matches[1], NS_FILE );
4965 if ( is_null( $title ) ) {
4966 # Bogus title. Ignore these so we don't bomb out later.
4967 continue;
4968 }
4969
4970 $label = '';
4971 $alt = '';
4972 $link = '';
4973 if ( isset( $matches[3] ) ) {
4974 // look for an |alt= definition while trying not to break existing
4975 // captions with multiple pipes (|) in it, until a more sensible grammar
4976 // is defined for images in galleries
4977
4978 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4979 $parameterMatches = StringUtils::explode('|', $matches[3]);
4980 $magicWordAlt = MagicWord::get( 'img_alt' );
4981 $magicWordLink = MagicWord::get( 'img_link' );
4982
4983 foreach ( $parameterMatches as $parameterMatch ) {
4984 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4985 $alt = $this->stripAltText( $match, false );
4986 }
4987 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4988 $link = strip_tags($this->replaceLinkHoldersText($match));
4989 $chars = self::EXT_LINK_URL_CLASS;
4990 $prots = $this->mUrlProtocols;
4991 //check to see if link matches an absolute url, if not then it must be a wiki link.
4992 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4993 $localLinkTitle = Title::newFromText($link);
4994 $link = $localLinkTitle->getLocalURL();
4995 }
4996 }
4997 else {
4998 // concatenate all other pipes
4999 $label .= '|' . $parameterMatch;
5000 }
5001 }
5002 // remove the first pipe
5003 $label = substr( $label, 1 );
5004 }
5005
5006 $ig->add( $title, $label, $alt ,$link);
5007 }
5008 return $ig->toHTML();
5009 }
5010
5011 /**
5012 * @param $handler
5013 * @return array
5014 */
5015 function getImageParams( $handler ) {
5016 if ( $handler ) {
5017 $handlerClass = get_class( $handler );
5018 } else {
5019 $handlerClass = '';
5020 }
5021 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
5022 # Initialise static lists
5023 static $internalParamNames = array(
5024 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5025 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5026 'bottom', 'text-bottom' ),
5027 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5028 'upright', 'border', 'link', 'alt', 'class' ),
5029 );
5030 static $internalParamMap;
5031 if ( !$internalParamMap ) {
5032 $internalParamMap = array();
5033 foreach ( $internalParamNames as $type => $names ) {
5034 foreach ( $names as $name ) {
5035 $magicName = str_replace( '-', '_', "img_$name" );
5036 $internalParamMap[$magicName] = array( $type, $name );
5037 }
5038 }
5039 }
5040
5041 # Add handler params
5042 $paramMap = $internalParamMap;
5043 if ( $handler ) {
5044 $handlerParamMap = $handler->getParamMap();
5045 foreach ( $handlerParamMap as $magic => $paramName ) {
5046 $paramMap[$magic] = array( 'handler', $paramName );
5047 }
5048 }
5049 $this->mImageParams[$handlerClass] = $paramMap;
5050 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5051 }
5052 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
5053 }
5054
5055 /**
5056 * Parse image options text and use it to make an image
5057 *
5058 * @param $title Title
5059 * @param $options String
5060 * @param $holders LinkHolderArray|bool
5061 * @return string HTML
5062 */
5063 function makeImage( $title, $options, $holders = false ) {
5064 # Check if the options text is of the form "options|alt text"
5065 # Options are:
5066 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5067 # * left no resizing, just left align. label is used for alt= only
5068 # * right same, but right aligned
5069 # * none same, but not aligned
5070 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5071 # * center center the image
5072 # * frame Keep original image size, no magnify-button.
5073 # * framed Same as "frame"
5074 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5075 # * upright reduce width for upright images, rounded to full __0 px
5076 # * border draw a 1px border around the image
5077 # * alt Text for HTML alt attribute (defaults to empty)
5078 # * class Set a class for img node
5079 # * link Set the target of the image link. Can be external, interwiki, or local
5080 # vertical-align values (no % or length right now):
5081 # * baseline
5082 # * sub
5083 # * super
5084 # * top
5085 # * text-top
5086 # * middle
5087 # * bottom
5088 # * text-bottom
5089
5090 $parts = StringUtils::explode( "|", $options );
5091
5092 # Give extensions a chance to select the file revision for us
5093 $options = array();
5094 $descQuery = false;
5095 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5096 array( $this, $title, &$options, &$descQuery ) );
5097 # Fetch and register the file (file title may be different via hooks)
5098 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5099
5100 # Get parameter map
5101 $handler = $file ? $file->getHandler() : false;
5102
5103 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5104
5105 if ( !$file ) {
5106 $this->addTrackingCategory( 'broken-file-category' );
5107 }
5108
5109 # Process the input parameters
5110 $caption = '';
5111 $params = array( 'frame' => array(), 'handler' => array(),
5112 'horizAlign' => array(), 'vertAlign' => array() );
5113 foreach ( $parts as $part ) {
5114 $part = trim( $part );
5115 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5116 $validated = false;
5117 if ( isset( $paramMap[$magicName] ) ) {
5118 list( $type, $paramName ) = $paramMap[$magicName];
5119
5120 # Special case; width and height come in one variable together
5121 if ( $type === 'handler' && $paramName === 'width' ) {
5122 $parsedWidthParam = $this->parseWidthParam( $value );
5123 if( isset( $parsedWidthParam['width'] ) ) {
5124 $width = $parsedWidthParam['width'];
5125 if ( $handler->validateParam( 'width', $width ) ) {
5126 $params[$type]['width'] = $width;
5127 $validated = true;
5128 }
5129 }
5130 if( isset( $parsedWidthParam['height'] ) ) {
5131 $height = $parsedWidthParam['height'];
5132 if ( $handler->validateParam( 'height', $height ) ) {
5133 $params[$type]['height'] = $height;
5134 $validated = true;
5135 }
5136 }
5137 # else no validation -- bug 13436
5138 } else {
5139 if ( $type === 'handler' ) {
5140 # Validate handler parameter
5141 $validated = $handler->validateParam( $paramName, $value );
5142 } else {
5143 # Validate internal parameters
5144 switch( $paramName ) {
5145 case 'manualthumb':
5146 case 'alt':
5147 case 'class':
5148 # @todo FIXME: Possibly check validity here for
5149 # manualthumb? downstream behavior seems odd with
5150 # missing manual thumbs.
5151 $validated = true;
5152 $value = $this->stripAltText( $value, $holders );
5153 break;
5154 case 'link':
5155 $chars = self::EXT_LINK_URL_CLASS;
5156 $prots = $this->mUrlProtocols;
5157 if ( $value === '' ) {
5158 $paramName = 'no-link';
5159 $value = true;
5160 $validated = true;
5161 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5162 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5163 $paramName = 'link-url';
5164 $this->mOutput->addExternalLink( $value );
5165 if ( $this->mOptions->getExternalLinkTarget() ) {
5166 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
5167 }
5168 $validated = true;
5169 }
5170 } else {
5171 $linkTitle = Title::newFromText( $value );
5172 if ( $linkTitle ) {
5173 $paramName = 'link-title';
5174 $value = $linkTitle;
5175 $this->mOutput->addLink( $linkTitle );
5176 $validated = true;
5177 }
5178 }
5179 break;
5180 default:
5181 # Most other things appear to be empty or numeric...
5182 $validated = ( $value === false || is_numeric( trim( $value ) ) );
5183 }
5184 }
5185
5186 if ( $validated ) {
5187 $params[$type][$paramName] = $value;
5188 }
5189 }
5190 }
5191 if ( !$validated ) {
5192 $caption = $part;
5193 }
5194 }
5195
5196 # Process alignment parameters
5197 if ( $params['horizAlign'] ) {
5198 $params['frame']['align'] = key( $params['horizAlign'] );
5199 }
5200 if ( $params['vertAlign'] ) {
5201 $params['frame']['valign'] = key( $params['vertAlign'] );
5202 }
5203
5204 $params['frame']['caption'] = $caption;
5205
5206 # Will the image be presented in a frame, with the caption below?
5207 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5208 isset( $params['frame']['framed'] ) ||
5209 isset( $params['frame']['thumbnail'] ) ||
5210 isset( $params['frame']['manualthumb'] );
5211
5212 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5213 # came to also set the caption, ordinary text after the image -- which
5214 # makes no sense, because that just repeats the text multiple times in
5215 # screen readers. It *also* came to set the title attribute.
5216 #
5217 # Now that we have an alt attribute, we should not set the alt text to
5218 # equal the caption: that's worse than useless, it just repeats the
5219 # text. This is the framed/thumbnail case. If there's no caption, we
5220 # use the unnamed parameter for alt text as well, just for the time be-
5221 # ing, if the unnamed param is set and the alt param is not.
5222 #
5223 # For the future, we need to figure out if we want to tweak this more,
5224 # e.g., introducing a title= parameter for the title; ignoring the un-
5225 # named parameter entirely for images without a caption; adding an ex-
5226 # plicit caption= parameter and preserving the old magic unnamed para-
5227 # meter for BC; ...
5228 if ( $imageIsFramed ) { # Framed image
5229 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5230 # No caption or alt text, add the filename as the alt text so
5231 # that screen readers at least get some description of the image
5232 $params['frame']['alt'] = $title->getText();
5233 }
5234 # Do not set $params['frame']['title'] because tooltips don't make sense
5235 # for framed images
5236 } else { # Inline image
5237 if ( !isset( $params['frame']['alt'] ) ) {
5238 # No alt text, use the "caption" for the alt text
5239 if ( $caption !== '') {
5240 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5241 } else {
5242 # No caption, fall back to using the filename for the
5243 # alt text
5244 $params['frame']['alt'] = $title->getText();
5245 }
5246 }
5247 # Use the "caption" for the tooltip text
5248 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5249 }
5250
5251 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5252
5253 # Linker does the rest
5254 $time = isset( $options['time'] ) ? $options['time'] : false;
5255 $ret = Linker::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5256 $time, $descQuery, $this->mOptions->getThumbSize() );
5257
5258 # Give the handler a chance to modify the parser object
5259 if ( $handler ) {
5260 $handler->parserTransformHook( $this, $file );
5261 }
5262
5263 return $ret;
5264 }
5265
5266 /**
5267 * @param $caption
5268 * @param $holders LinkHolderArray
5269 * @return mixed|String
5270 */
5271 protected function stripAltText( $caption, $holders ) {
5272 # Strip bad stuff out of the title (tooltip). We can't just use
5273 # replaceLinkHoldersText() here, because if this function is called
5274 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5275 if ( $holders ) {
5276 $tooltip = $holders->replaceText( $caption );
5277 } else {
5278 $tooltip = $this->replaceLinkHoldersText( $caption );
5279 }
5280
5281 # make sure there are no placeholders in thumbnail attributes
5282 # that are later expanded to html- so expand them now and
5283 # remove the tags
5284 $tooltip = $this->mStripState->unstripBoth( $tooltip );
5285 $tooltip = Sanitizer::stripAllTags( $tooltip );
5286
5287 return $tooltip;
5288 }
5289
5290 /**
5291 * Set a flag in the output object indicating that the content is dynamic and
5292 * shouldn't be cached.
5293 */
5294 function disableCache() {
5295 wfDebug( "Parser output marked as uncacheable.\n" );
5296 if ( !$this->mOutput ) {
5297 throw new MWException( __METHOD__ .
5298 " can only be called when actually parsing something" );
5299 }
5300 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
5301 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
5302 }
5303
5304 /**
5305 * Callback from the Sanitizer for expanding items found in HTML attribute
5306 * values, so they can be safely tested and escaped.
5307 *
5308 * @param $text String
5309 * @param $frame PPFrame
5310 * @return String
5311 */
5312 function attributeStripCallback( &$text, $frame = false ) {
5313 $text = $this->replaceVariables( $text, $frame );
5314 $text = $this->mStripState->unstripBoth( $text );
5315 return $text;
5316 }
5317
5318 /**
5319 * Accessor
5320 *
5321 * @return array
5322 */
5323 function getTags() {
5324 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ), array_keys( $this->mFunctionTagHooks ) );
5325 }
5326
5327 /**
5328 * Replace transparent tags in $text with the values given by the callbacks.
5329 *
5330 * Transparent tag hooks are like regular XML-style tag hooks, except they
5331 * operate late in the transformation sequence, on HTML instead of wikitext.
5332 *
5333 * @param $text string
5334 *
5335 * @return string
5336 */
5337 function replaceTransparentTags( $text ) {
5338 $matches = array();
5339 $elements = array_keys( $this->mTransparentTagHooks );
5340 $text = self::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix );
5341 $replacements = array();
5342
5343 foreach ( $matches as $marker => $data ) {
5344 list( $element, $content, $params, $tag ) = $data;
5345 $tagName = strtolower( $element );
5346 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
5347 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
5348 } else {
5349 $output = $tag;
5350 }
5351 $replacements[$marker] = $output;
5352 }
5353 return strtr( $text, $replacements );
5354 }
5355
5356 /**
5357 * Break wikitext input into sections, and either pull or replace
5358 * some particular section's text.
5359 *
5360 * External callers should use the getSection and replaceSection methods.
5361 *
5362 * @param $text String: Page wikitext
5363 * @param $section String: a section identifier string of the form:
5364 * "<flag1> - <flag2> - ... - <section number>"
5365 *
5366 * Currently the only recognised flag is "T", which means the target section number
5367 * was derived during a template inclusion parse, in other words this is a template
5368 * section edit link. If no flags are given, it was an ordinary section edit link.
5369 * This flag is required to avoid a section numbering mismatch when a section is
5370 * enclosed by "<includeonly>" (bug 6563).
5371 *
5372 * The section number 0 pulls the text before the first heading; other numbers will
5373 * pull the given section along with its lower-level subsections. If the section is
5374 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5375 *
5376 * Section 0 is always considered to exist, even if it only contains the empty
5377 * string. If $text is the empty string and section 0 is replaced, $newText is
5378 * returned.
5379 *
5380 * @param $mode String: one of "get" or "replace"
5381 * @param $newText String: replacement text for section data.
5382 * @return String: for "get", the extracted section text.
5383 * for "replace", the whole page with the section replaced.
5384 */
5385 private function extractSections( $text, $section, $mode, $newText='' ) {
5386 global $wgTitle; # not generally used but removes an ugly failure mode
5387 $this->startParse( $wgTitle, new ParserOptions, self::OT_PLAIN, true );
5388 $outText = '';
5389 $frame = $this->getPreprocessor()->newFrame();
5390
5391 # Process section extraction flags
5392 $flags = 0;
5393 $sectionParts = explode( '-', $section );
5394 $sectionIndex = array_pop( $sectionParts );
5395 foreach ( $sectionParts as $part ) {
5396 if ( $part === 'T' ) {
5397 $flags |= self::PTD_FOR_INCLUSION;
5398 }
5399 }
5400
5401 # Check for empty input
5402 if ( strval( $text ) === '' ) {
5403 # Only sections 0 and T-0 exist in an empty document
5404 if ( $sectionIndex == 0 ) {
5405 if ( $mode === 'get' ) {
5406 return '';
5407 } else {
5408 return $newText;
5409 }
5410 } else {
5411 if ( $mode === 'get' ) {
5412 return $newText;
5413 } else {
5414 return $text;
5415 }
5416 }
5417 }
5418
5419 # Preprocess the text
5420 $root = $this->preprocessToDom( $text, $flags );
5421
5422 # <h> nodes indicate section breaks
5423 # They can only occur at the top level, so we can find them by iterating the root's children
5424 $node = $root->getFirstChild();
5425
5426 # Find the target section
5427 if ( $sectionIndex == 0 ) {
5428 # Section zero doesn't nest, level=big
5429 $targetLevel = 1000;
5430 } else {
5431 while ( $node ) {
5432 if ( $node->getName() === 'h' ) {
5433 $bits = $node->splitHeading();
5434 if ( $bits['i'] == $sectionIndex ) {
5435 $targetLevel = $bits['level'];
5436 break;
5437 }
5438 }
5439 if ( $mode === 'replace' ) {
5440 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5441 }
5442 $node = $node->getNextSibling();
5443 }
5444 }
5445
5446 if ( !$node ) {
5447 # Not found
5448 if ( $mode === 'get' ) {
5449 return $newText;
5450 } else {
5451 return $text;
5452 }
5453 }
5454
5455 # Find the end of the section, including nested sections
5456 do {
5457 if ( $node->getName() === 'h' ) {
5458 $bits = $node->splitHeading();
5459 $curLevel = $bits['level'];
5460 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5461 break;
5462 }
5463 }
5464 if ( $mode === 'get' ) {
5465 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5466 }
5467 $node = $node->getNextSibling();
5468 } while ( $node );
5469
5470 # Write out the remainder (in replace mode only)
5471 if ( $mode === 'replace' ) {
5472 # Output the replacement text
5473 # Add two newlines on -- trailing whitespace in $newText is conventionally
5474 # stripped by the editor, so we need both newlines to restore the paragraph gap
5475 # Only add trailing whitespace if there is newText
5476 if ( $newText != "" ) {
5477 $outText .= $newText . "\n\n";
5478 }
5479
5480 while ( $node ) {
5481 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
5482 $node = $node->getNextSibling();
5483 }
5484 }
5485
5486 if ( is_string( $outText ) ) {
5487 # Re-insert stripped tags
5488 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
5489 }
5490
5491 return $outText;
5492 }
5493
5494 /**
5495 * This function returns the text of a section, specified by a number ($section).
5496 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5497 * the first section before any such heading (section 0).
5498 *
5499 * If a section contains subsections, these are also returned.
5500 *
5501 * @param $text String: text to look in
5502 * @param $section String: section identifier
5503 * @param $deftext String: default to return if section is not found
5504 * @return string text of the requested section
5505 */
5506 public function getSection( $text, $section, $deftext='' ) {
5507 return $this->extractSections( $text, $section, "get", $deftext );
5508 }
5509
5510 /**
5511 * This function returns $oldtext after the content of the section
5512 * specified by $section has been replaced with $text. If the target
5513 * section does not exist, $oldtext is returned unchanged.
5514 *
5515 * @param $oldtext String: former text of the article
5516 * @param $section int section identifier
5517 * @param $text String: replacing text
5518 * @return String: modified text
5519 */
5520 public function replaceSection( $oldtext, $section, $text ) {
5521 return $this->extractSections( $oldtext, $section, "replace", $text );
5522 }
5523
5524 /**
5525 * Get the ID of the revision we are parsing
5526 *
5527 * @return Mixed: integer or null
5528 */
5529 function getRevisionId() {
5530 return $this->mRevisionId;
5531 }
5532
5533 /**
5534 * Get the revision object for $this->mRevisionId
5535 *
5536 * @return Revision|null either a Revision object or null
5537 */
5538 protected function getRevisionObject() {
5539 if ( !is_null( $this->mRevisionObject ) ) {
5540 return $this->mRevisionObject;
5541 }
5542 if ( is_null( $this->mRevisionId ) ) {
5543 return null;
5544 }
5545
5546 $this->mRevisionObject = Revision::newFromId( $this->mRevisionId );
5547 return $this->mRevisionObject;
5548 }
5549
5550 /**
5551 * Get the timestamp associated with the current revision, adjusted for
5552 * the default server-local timestamp
5553 */
5554 function getRevisionTimestamp() {
5555 if ( is_null( $this->mRevisionTimestamp ) ) {
5556 wfProfileIn( __METHOD__ );
5557
5558 global $wgContLang;
5559
5560 $revObject = $this->getRevisionObject();
5561 $timestamp = $revObject ? $revObject->getTimestamp() : wfTimestampNow();
5562
5563 # The cryptic '' timezone parameter tells to use the site-default
5564 # timezone offset instead of the user settings.
5565 #
5566 # Since this value will be saved into the parser cache, served
5567 # to other users, and potentially even used inside links and such,
5568 # it needs to be consistent for all visitors.
5569 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
5570
5571 wfProfileOut( __METHOD__ );
5572 }
5573 return $this->mRevisionTimestamp;
5574 }
5575
5576 /**
5577 * Get the name of the user that edited the last revision
5578 *
5579 * @return String: user name
5580 */
5581 function getRevisionUser() {
5582 if( is_null( $this->mRevisionUser ) ) {
5583 $revObject = $this->getRevisionObject();
5584
5585 # if this template is subst: the revision id will be blank,
5586 # so just use the current user's name
5587 if( $revObject ) {
5588 $this->mRevisionUser = $revObject->getUserText();
5589 } elseif( $this->ot['wiki'] || $this->mOptions->getIsPreview() ) {
5590 $this->mRevisionUser = $this->getUser()->getName();
5591 }
5592 }
5593 return $this->mRevisionUser;
5594 }
5595
5596 /**
5597 * Mutator for $mDefaultSort
5598 *
5599 * @param $sort string New value
5600 */
5601 public function setDefaultSort( $sort ) {
5602 $this->mDefaultSort = $sort;
5603 $this->mOutput->setProperty( 'defaultsort', $sort );
5604 }
5605
5606 /**
5607 * Accessor for $mDefaultSort
5608 * Will use the empty string if none is set.
5609 *
5610 * This value is treated as a prefix, so the
5611 * empty string is equivalent to sorting by
5612 * page name.
5613 *
5614 * @return string
5615 */
5616 public function getDefaultSort() {
5617 if ( $this->mDefaultSort !== false ) {
5618 return $this->mDefaultSort;
5619 } else {
5620 return '';
5621 }
5622 }
5623
5624 /**
5625 * Accessor for $mDefaultSort
5626 * Unlike getDefaultSort(), will return false if none is set
5627 *
5628 * @return string or false
5629 */
5630 public function getCustomDefaultSort() {
5631 return $this->mDefaultSort;
5632 }
5633
5634 /**
5635 * Try to guess the section anchor name based on a wikitext fragment
5636 * presumably extracted from a heading, for example "Header" from
5637 * "== Header ==".
5638 *
5639 * @param $text string
5640 *
5641 * @return string
5642 */
5643 public function guessSectionNameFromWikiText( $text ) {
5644 # Strip out wikitext links(they break the anchor)
5645 $text = $this->stripSectionName( $text );
5646 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5647 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5648 }
5649
5650 /**
5651 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5652 * instead. For use in redirects, since IE6 interprets Redirect: headers
5653 * as something other than UTF-8 (apparently?), resulting in breakage.
5654 *
5655 * @param $text String: The section name
5656 * @return string An anchor
5657 */
5658 public function guessLegacySectionNameFromWikiText( $text ) {
5659 # Strip out wikitext links(they break the anchor)
5660 $text = $this->stripSectionName( $text );
5661 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5662 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5663 }
5664
5665 /**
5666 * Strips a text string of wikitext for use in a section anchor
5667 *
5668 * Accepts a text string and then removes all wikitext from the
5669 * string and leaves only the resultant text (i.e. the result of
5670 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5671 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5672 * to create valid section anchors by mimicing the output of the
5673 * parser when headings are parsed.
5674 *
5675 * @param $text String: text string to be stripped of wikitext
5676 * for use in a Section anchor
5677 * @return string Filtered text string
5678 */
5679 public function stripSectionName( $text ) {
5680 # Strip internal link markup
5681 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5682 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5683
5684 # Strip external link markup
5685 # @todo FIXME: Not tolerant to blank link text
5686 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5687 # on how many empty links there are on the page - need to figure that out.
5688 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5689
5690 # Parse wikitext quotes (italics & bold)
5691 $text = $this->doQuotes( $text );
5692
5693 # Strip HTML tags
5694 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5695 return $text;
5696 }
5697
5698 /**
5699 * strip/replaceVariables/unstrip for preprocessor regression testing
5700 *
5701 * @param $text string
5702 * @param $title Title
5703 * @param $options ParserOptions
5704 * @param $outputType int
5705 *
5706 * @return string
5707 */
5708 function testSrvus( $text, Title $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5709 $this->startParse( $title, $options, $outputType, true );
5710
5711 $text = $this->replaceVariables( $text );
5712 $text = $this->mStripState->unstripBoth( $text );
5713 $text = Sanitizer::removeHTMLtags( $text );
5714 return $text;
5715 }
5716
5717 /**
5718 * @param $text string
5719 * @param $title Title
5720 * @param $options ParserOptions
5721 * @return string
5722 */
5723 function testPst( $text, Title $title, ParserOptions $options ) {
5724 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5725 }
5726
5727 /**
5728 * @param $text
5729 * @param $title Title
5730 * @param $options ParserOptions
5731 * @return string
5732 */
5733 function testPreprocess( $text, Title $title, ParserOptions $options ) {
5734 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5735 }
5736
5737 /**
5738 * Call a callback function on all regions of the given text that are not
5739 * inside strip markers, and replace those regions with the return value
5740 * of the callback. For example, with input:
5741 *
5742 * aaa<MARKER>bbb
5743 *
5744 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5745 * two strings will be replaced with the value returned by the callback in
5746 * each case.
5747 *
5748 * @param $s string
5749 * @param $callback
5750 *
5751 * @return string
5752 */
5753 function markerSkipCallback( $s, $callback ) {
5754 $i = 0;
5755 $out = '';
5756 while ( $i < strlen( $s ) ) {
5757 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5758 if ( $markerStart === false ) {
5759 $out .= call_user_func( $callback, substr( $s, $i ) );
5760 break;
5761 } else {
5762 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5763 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5764 if ( $markerEnd === false ) {
5765 $out .= substr( $s, $markerStart );
5766 break;
5767 } else {
5768 $markerEnd += strlen( self::MARKER_SUFFIX );
5769 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5770 $i = $markerEnd;
5771 }
5772 }
5773 }
5774 return $out;
5775 }
5776
5777 /**
5778 * Remove any strip markers found in the given text.
5779 *
5780 * @param $text Input string
5781 * @return string
5782 */
5783 function killMarkers( $text ) {
5784 return $this->mStripState->killMarkers( $text );
5785 }
5786
5787 /**
5788 * Save the parser state required to convert the given half-parsed text to
5789 * HTML. "Half-parsed" in this context means the output of
5790 * recursiveTagParse() or internalParse(). This output has strip markers
5791 * from replaceVariables (extensionSubstitution() etc.), and link
5792 * placeholders from replaceLinkHolders().
5793 *
5794 * Returns an array which can be serialized and stored persistently. This
5795 * array can later be loaded into another parser instance with
5796 * unserializeHalfParsedText(). The text can then be safely incorporated into
5797 * the return value of a parser hook.
5798 *
5799 * @param $text string
5800 *
5801 * @return array
5802 */
5803 function serializeHalfParsedText( $text ) {
5804 wfProfileIn( __METHOD__ );
5805 $data = array(
5806 'text' => $text,
5807 'version' => self::HALF_PARSED_VERSION,
5808 'stripState' => $this->mStripState->getSubState( $text ),
5809 'linkHolders' => $this->mLinkHolders->getSubArray( $text )
5810 );
5811 wfProfileOut( __METHOD__ );
5812 return $data;
5813 }
5814
5815 /**
5816 * Load the parser state given in the $data array, which is assumed to
5817 * have been generated by serializeHalfParsedText(). The text contents is
5818 * extracted from the array, and its markers are transformed into markers
5819 * appropriate for the current Parser instance. This transformed text is
5820 * returned, and can be safely included in the return value of a parser
5821 * hook.
5822 *
5823 * If the $data array has been stored persistently, the caller should first
5824 * check whether it is still valid, by calling isValidHalfParsedText().
5825 *
5826 * @param $data array Serialized data
5827 * @throws MWException
5828 * @return String
5829 */
5830 function unserializeHalfParsedText( $data ) {
5831 if ( !isset( $data['version'] ) || $data['version'] != self::HALF_PARSED_VERSION ) {
5832 throw new MWException( __METHOD__.': invalid version' );
5833 }
5834
5835 # First, extract the strip state.
5836 $texts = array( $data['text'] );
5837 $texts = $this->mStripState->merge( $data['stripState'], $texts );
5838
5839 # Now renumber links
5840 $texts = $this->mLinkHolders->mergeForeign( $data['linkHolders'], $texts );
5841
5842 # Should be good to go.
5843 return $texts[0];
5844 }
5845
5846 /**
5847 * Returns true if the given array, presumed to be generated by
5848 * serializeHalfParsedText(), is compatible with the current version of the
5849 * parser.
5850 *
5851 * @param $data Array
5852 *
5853 * @return bool
5854 */
5855 function isValidHalfParsedText( $data ) {
5856 return isset( $data['version'] ) && $data['version'] == self::HALF_PARSED_VERSION;
5857 }
5858
5859 /**
5860 * Parsed a width param of imagelink like 300px or 200x300px
5861 *
5862 * @param $value String
5863 *
5864 * @return array
5865 * @since 1.20
5866 */
5867 public function parseWidthParam( $value ) {
5868 $parsedWidthParam = array();
5869 if( $value === '' ) {
5870 return $parsedWidthParam;
5871 }
5872 $m = array();
5873 # (bug 13500) In both cases (width/height and width only),
5874 # permit trailing "px" for backward compatibility.
5875 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5876 $width = intval( $m[1] );
5877 $height = intval( $m[2] );
5878 $parsedWidthParam['width'] = $width;
5879 $parsedWidthParam['height'] = $height;
5880 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5881 $width = intval( $value );
5882 $parsedWidthParam['width'] = $width;
5883 }
5884 return $parsedWidthParam;
5885 }
5886 }