Merge "Fix positioning of jQuery.tipsy tooltip arrows"
[mediawiki.git] / includes / parser / Preprocessor_Hash.php
blob50eaefbce33e85779e7ec0de89b495a323092963
1 <?php
2 /**
3 * Preprocessor using PHP arrays
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.
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.
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
20 * @file
21 * @ingroup Parser
24 /**
25 * Differences from DOM schema:
26 * * attribute nodes are children
27 * * "<h>" nodes that aren't at the top are replaced with <possible-h>
28 * @ingroup Parser
30 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
31 class Preprocessor_Hash extends Preprocessor {
32 // @codingStandardsIgnoreEnd
34 /**
35 * @var Parser
37 public $parser;
39 const CACHE_PREFIX = 'preprocess-hash';
41 public function __construct( $parser ) {
42 $this->parser = $parser;
45 /**
46 * @return PPFrame_Hash
48 public function newFrame() {
49 return new PPFrame_Hash( $this );
52 /**
53 * @param array $args
54 * @return PPCustomFrame_Hash
56 public function newCustomFrame( $args ) {
57 return new PPCustomFrame_Hash( $this, $args );
60 /**
61 * @param array $values
62 * @return PPNode_Hash_Array
64 public function newPartNodeArray( $values ) {
65 $list = array();
67 foreach ( $values as $k => $val ) {
68 $partNode = new PPNode_Hash_Tree( 'part' );
69 $nameNode = new PPNode_Hash_Tree( 'name' );
71 if ( is_int( $k ) ) {
72 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
73 $partNode->addChild( $nameNode );
74 } else {
75 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
76 $partNode->addChild( $nameNode );
77 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
80 $valueNode = new PPNode_Hash_Tree( 'value' );
81 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
82 $partNode->addChild( $valueNode );
84 $list[] = $partNode;
87 $node = new PPNode_Hash_Array( $list );
88 return $node;
91 /**
92 * Preprocess some wikitext and return the document tree.
93 * This is the ghost of Parser::replace_variables().
95 * @param string $text The text to parse
96 * @param int $flags Bitwise combination of:
97 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
98 * included. Default is to assume a direct page view.
100 * The generated DOM tree must depend only on the input text and the flags.
101 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
103 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
104 * change in the DOM tree for a given text, must be passed through the section identifier
105 * in the section edit link and thus back to extractSections().
107 * The output of this function is currently only cached in process memory, but a persistent
108 * cache may be implemented at a later date which takes further advantage of these strict
109 * dependency requirements.
111 * @throws MWException
112 * @return PPNode_Hash_Tree
114 public function preprocessToObj( $text, $flags = 0 ) {
115 $tree = $this->cacheGetTree( $text, $flags );
116 if ( $tree !== false ) {
117 return unserialize( $tree );
120 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
122 $xmlishElements = $this->parser->getStripList();
123 $enableOnlyinclude = false;
124 if ( $forInclusion ) {
125 $ignoredTags = array( 'includeonly', '/includeonly' );
126 $ignoredElements = array( 'noinclude' );
127 $xmlishElements[] = 'noinclude';
128 if ( strpos( $text, '<onlyinclude>' ) !== false
129 && strpos( $text, '</onlyinclude>' ) !== false
131 $enableOnlyinclude = true;
133 } else {
134 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
135 $ignoredElements = array( 'includeonly' );
136 $xmlishElements[] = 'includeonly';
138 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
140 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
141 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
143 $stack = new PPDStack_Hash;
145 $searchBase = "[{<\n";
146 // For fast reverse searches
147 $revText = strrev( $text );
148 $lengthText = strlen( $text );
150 // Input pointer, starts out pointing to a pseudo-newline before the start
151 $i = 0;
152 // Current accumulator
153 $accum =& $stack->getAccum();
154 // True to find equals signs in arguments
155 $findEquals = false;
156 // True to take notice of pipe characters
157 $findPipe = false;
158 $headingIndex = 1;
159 // True if $i is inside a possible heading
160 $inHeading = false;
161 // True if there are no more greater-than (>) signs right of $i
162 $noMoreGT = false;
163 // True to ignore all input up to the next <onlyinclude>
164 $findOnlyinclude = $enableOnlyinclude;
165 // Do a line-start run without outputting an LF character
166 $fakeLineStart = true;
168 while ( true ) {
169 // $this->memCheck();
171 if ( $findOnlyinclude ) {
172 // Ignore all input up to the next <onlyinclude>
173 $startPos = strpos( $text, '<onlyinclude>', $i );
174 if ( $startPos === false ) {
175 // Ignored section runs to the end
176 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
177 break;
179 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
180 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
181 $i = $tagEndPos;
182 $findOnlyinclude = false;
185 if ( $fakeLineStart ) {
186 $found = 'line-start';
187 $curChar = '';
188 } else {
189 # Find next opening brace, closing brace or pipe
190 $search = $searchBase;
191 if ( $stack->top === false ) {
192 $currentClosing = '';
193 } else {
194 $currentClosing = $stack->top->close;
195 $search .= $currentClosing;
197 if ( $findPipe ) {
198 $search .= '|';
200 if ( $findEquals ) {
201 // First equals will be for the template
202 $search .= '=';
204 $rule = null;
205 # Output literal section, advance input counter
206 $literalLength = strcspn( $text, $search, $i );
207 if ( $literalLength > 0 ) {
208 $accum->addLiteral( substr( $text, $i, $literalLength ) );
209 $i += $literalLength;
211 if ( $i >= $lengthText ) {
212 if ( $currentClosing == "\n" ) {
213 // Do a past-the-end run to finish off the heading
214 $curChar = '';
215 $found = 'line-end';
216 } else {
217 # All done
218 break;
220 } else {
221 $curChar = $text[$i];
222 if ( $curChar == '|' ) {
223 $found = 'pipe';
224 } elseif ( $curChar == '=' ) {
225 $found = 'equals';
226 } elseif ( $curChar == '<' ) {
227 $found = 'angle';
228 } elseif ( $curChar == "\n" ) {
229 if ( $inHeading ) {
230 $found = 'line-end';
231 } else {
232 $found = 'line-start';
234 } elseif ( $curChar == $currentClosing ) {
235 $found = 'close';
236 } elseif ( isset( $this->rules[$curChar] ) ) {
237 $found = 'open';
238 $rule = $this->rules[$curChar];
239 } else {
240 # Some versions of PHP have a strcspn which stops on null characters
241 # Ignore and continue
242 ++$i;
243 continue;
248 if ( $found == 'angle' ) {
249 $matches = false;
250 // Handle </onlyinclude>
251 if ( $enableOnlyinclude
252 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
254 $findOnlyinclude = true;
255 continue;
258 // Determine element name
259 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
260 // Element name missing or not listed
261 $accum->addLiteral( '<' );
262 ++$i;
263 continue;
265 // Handle comments
266 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
268 // To avoid leaving blank lines, when a sequence of
269 // space-separated comments is both preceded and followed by
270 // a newline (ignoring spaces), then
271 // trim leading and trailing spaces and the trailing newline.
273 // Find the end
274 $endPos = strpos( $text, '-->', $i + 4 );
275 if ( $endPos === false ) {
276 // Unclosed comment in input, runs to end
277 $inner = substr( $text, $i );
278 $accum->addNodeWithText( 'comment', $inner );
279 $i = $lengthText;
280 } else {
281 // Search backwards for leading whitespace
282 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
284 // Search forwards for trailing whitespace
285 // $wsEnd will be the position of the last space (or the '>' if there's none)
286 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
288 // Keep looking forward as long as we're finding more
289 // comments.
290 $comments = array( array( $wsStart, $wsEnd ) );
291 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
292 $c = strpos( $text, '-->', $wsEnd + 4 );
293 if ( $c === false ) {
294 break;
296 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
297 $comments[] = array( $wsEnd + 1, $c );
298 $wsEnd = $c;
301 // Eat the line if possible
302 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
303 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
304 // it's a possible beneficial b/c break.
305 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
306 && substr( $text, $wsEnd + 1, 1 ) == "\n"
308 // Remove leading whitespace from the end of the accumulator
309 // Sanity check first though
310 $wsLength = $i - $wsStart;
311 if ( $wsLength > 0
312 && $accum->lastNode instanceof PPNode_Hash_Text
313 && strspn( $accum->lastNode->value, " \t", -$wsLength ) === $wsLength
315 $accum->lastNode->value = substr( $accum->lastNode->value, 0, -$wsLength );
318 // Dump all but the last comment to the accumulator
319 foreach ( $comments as $j => $com ) {
320 $startPos = $com[0];
321 $endPos = $com[1] + 1;
322 if ( $j == ( count( $comments ) - 1 ) ) {
323 break;
325 $inner = substr( $text, $startPos, $endPos - $startPos );
326 $accum->addNodeWithText( 'comment', $inner );
329 // Do a line-start run next time to look for headings after the comment
330 $fakeLineStart = true;
331 } else {
332 // No line to eat, just take the comment itself
333 $startPos = $i;
334 $endPos += 2;
337 if ( $stack->top ) {
338 $part = $stack->top->getCurrentPart();
339 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
340 $part->visualEnd = $wsStart;
342 // Else comments abutting, no change in visual end
343 $part->commentEnd = $endPos;
345 $i = $endPos + 1;
346 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
347 $accum->addNodeWithText( 'comment', $inner );
349 continue;
351 $name = $matches[1];
352 $lowerName = strtolower( $name );
353 $attrStart = $i + strlen( $name ) + 1;
355 // Find end of tag
356 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
357 if ( $tagEndPos === false ) {
358 // Infinite backtrack
359 // Disable tag search to prevent worst-case O(N^2) performance
360 $noMoreGT = true;
361 $accum->addLiteral( '<' );
362 ++$i;
363 continue;
366 // Handle ignored tags
367 if ( in_array( $lowerName, $ignoredTags ) ) {
368 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i + 1 ) );
369 $i = $tagEndPos + 1;
370 continue;
373 $tagStartPos = $i;
374 if ( $text[$tagEndPos - 1] == '/' ) {
375 // Short end tag
376 $attrEnd = $tagEndPos - 1;
377 $inner = null;
378 $i = $tagEndPos + 1;
379 $close = null;
380 } else {
381 $attrEnd = $tagEndPos;
382 // Find closing tag
383 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
384 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
386 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
387 $i = $matches[0][1] + strlen( $matches[0][0] );
388 $close = $matches[0][0];
389 } else {
390 // No end tag -- let it run out to the end of the text.
391 $inner = substr( $text, $tagEndPos + 1 );
392 $i = $lengthText;
393 $close = null;
396 // <includeonly> and <noinclude> just become <ignore> tags
397 if ( in_array( $lowerName, $ignoredElements ) ) {
398 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
399 continue;
402 if ( $attrEnd <= $attrStart ) {
403 $attr = '';
404 } else {
405 // Note that the attr element contains the whitespace between name and attribute,
406 // this is necessary for precise reconstruction during pre-save transform.
407 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
410 $extNode = new PPNode_Hash_Tree( 'ext' );
411 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'name', $name ) );
412 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'attr', $attr ) );
413 if ( $inner !== null ) {
414 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'inner', $inner ) );
416 if ( $close !== null ) {
417 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'close', $close ) );
419 $accum->addNode( $extNode );
420 } elseif ( $found == 'line-start' ) {
421 // Is this the start of a heading?
422 // Line break belongs before the heading element in any case
423 if ( $fakeLineStart ) {
424 $fakeLineStart = false;
425 } else {
426 $accum->addLiteral( $curChar );
427 $i++;
430 $count = strspn( $text, '=', $i, 6 );
431 if ( $count == 1 && $findEquals ) {
432 // DWIM: This looks kind of like a name/value separator.
433 // Let's let the equals handler have it and break the potential
434 // heading. This is heuristic, but AFAICT the methods for
435 // completely correct disambiguation are very complex.
436 } elseif ( $count > 0 ) {
437 $piece = array(
438 'open' => "\n",
439 'close' => "\n",
440 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
441 'startPos' => $i,
442 'count' => $count );
443 $stack->push( $piece );
444 $accum =& $stack->getAccum();
445 extract( $stack->getFlags() );
446 $i += $count;
448 } elseif ( $found == 'line-end' ) {
449 $piece = $stack->top;
450 // A heading must be open, otherwise \n wouldn't have been in the search list
451 assert( '$piece->open == "\n"' );
452 $part = $piece->getCurrentPart();
453 // Search back through the input to see if it has a proper close.
454 // Do this using the reversed string since the other solutions
455 // (end anchor, etc.) are inefficient.
456 $wsLength = strspn( $revText, " \t", $lengthText - $i );
457 $searchStart = $i - $wsLength;
458 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
459 // Comment found at line end
460 // Search for equals signs before the comment
461 $searchStart = $part->visualEnd;
462 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
464 $count = $piece->count;
465 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
466 if ( $equalsLength > 0 ) {
467 if ( $searchStart - $equalsLength == $piece->startPos ) {
468 // This is just a single string of equals signs on its own line
469 // Replicate the doHeadings behavior /={count}(.+)={count}/
470 // First find out how many equals signs there really are (don't stop at 6)
471 $count = $equalsLength;
472 if ( $count < 3 ) {
473 $count = 0;
474 } else {
475 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
477 } else {
478 $count = min( $equalsLength, $count );
480 if ( $count > 0 ) {
481 // Normal match, output <h>
482 $element = new PPNode_Hash_Tree( 'possible-h' );
483 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
484 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
485 $element->lastChild->nextSibling = $accum->firstNode;
486 $element->lastChild = $accum->lastNode;
487 } else {
488 // Single equals sign on its own line, count=0
489 $element = $accum;
491 } else {
492 // No match, no <h>, just pass down the inner text
493 $element = $accum;
495 // Unwind the stack
496 $stack->pop();
497 $accum =& $stack->getAccum();
498 extract( $stack->getFlags() );
500 // Append the result to the enclosing accumulator
501 if ( $element instanceof PPNode ) {
502 $accum->addNode( $element );
503 } else {
504 $accum->addAccum( $element );
506 // Note that we do NOT increment the input pointer.
507 // This is because the closing linebreak could be the opening linebreak of
508 // another heading. Infinite loops are avoided because the next iteration MUST
509 // hit the heading open case above, which unconditionally increments the
510 // input pointer.
511 } elseif ( $found == 'open' ) {
512 # count opening brace characters
513 $count = strspn( $text, $curChar, $i );
515 # we need to add to stack only if opening brace count is enough for one of the rules
516 if ( $count >= $rule['min'] ) {
517 # Add it to the stack
518 $piece = array(
519 'open' => $curChar,
520 'close' => $rule['end'],
521 'count' => $count,
522 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
525 $stack->push( $piece );
526 $accum =& $stack->getAccum();
527 extract( $stack->getFlags() );
528 } else {
529 # Add literal brace(s)
530 $accum->addLiteral( str_repeat( $curChar, $count ) );
532 $i += $count;
533 } elseif ( $found == 'close' ) {
534 $piece = $stack->top;
535 # lets check if there are enough characters for closing brace
536 $maxCount = $piece->count;
537 $count = strspn( $text, $curChar, $i, $maxCount );
539 # check for maximum matching characters (if there are 5 closing
540 # characters, we will probably need only 3 - depending on the rules)
541 $rule = $this->rules[$piece->open];
542 if ( $count > $rule['max'] ) {
543 # The specified maximum exists in the callback array, unless the caller
544 # has made an error
545 $matchingCount = $rule['max'];
546 } else {
547 # Count is less than the maximum
548 # Skip any gaps in the callback array to find the true largest match
549 # Need to use array_key_exists not isset because the callback can be null
550 $matchingCount = $count;
551 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
552 --$matchingCount;
556 if ( $matchingCount <= 0 ) {
557 # No matching element found in callback array
558 # Output a literal closing brace and continue
559 $accum->addLiteral( str_repeat( $curChar, $count ) );
560 $i += $count;
561 continue;
563 $name = $rule['names'][$matchingCount];
564 if ( $name === null ) {
565 // No element, just literal text
566 $element = $piece->breakSyntax( $matchingCount );
567 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
568 } else {
569 # Create XML element
570 # Note: $parts is already XML, does not need to be encoded further
571 $parts = $piece->parts;
572 $titleAccum = $parts[0]->out;
573 unset( $parts[0] );
575 $element = new PPNode_Hash_Tree( $name );
577 # The invocation is at the start of the line if lineStart is set in
578 # the stack, and all opening brackets are used up.
579 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
580 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
582 $titleNode = new PPNode_Hash_Tree( 'title' );
583 $titleNode->firstChild = $titleAccum->firstNode;
584 $titleNode->lastChild = $titleAccum->lastNode;
585 $element->addChild( $titleNode );
586 $argIndex = 1;
587 foreach ( $parts as $part ) {
588 if ( isset( $part->eqpos ) ) {
589 // Find equals
590 $lastNode = false;
591 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
592 if ( $node === $part->eqpos ) {
593 break;
595 $lastNode = $node;
597 if ( !$node ) {
598 // if ( $cacheable ) { ... }
599 throw new MWException( __METHOD__ . ': eqpos not found' );
601 if ( $node->name !== 'equals' ) {
602 // if ( $cacheable ) { ... }
603 throw new MWException( __METHOD__ . ': eqpos is not equals' );
605 $equalsNode = $node;
607 // Construct name node
608 $nameNode = new PPNode_Hash_Tree( 'name' );
609 if ( $lastNode !== false ) {
610 $lastNode->nextSibling = false;
611 $nameNode->firstChild = $part->out->firstNode;
612 $nameNode->lastChild = $lastNode;
615 // Construct value node
616 $valueNode = new PPNode_Hash_Tree( 'value' );
617 if ( $equalsNode->nextSibling !== false ) {
618 $valueNode->firstChild = $equalsNode->nextSibling;
619 $valueNode->lastChild = $part->out->lastNode;
621 $partNode = new PPNode_Hash_Tree( 'part' );
622 $partNode->addChild( $nameNode );
623 $partNode->addChild( $equalsNode->firstChild );
624 $partNode->addChild( $valueNode );
625 $element->addChild( $partNode );
626 } else {
627 $partNode = new PPNode_Hash_Tree( 'part' );
628 $nameNode = new PPNode_Hash_Tree( 'name' );
629 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
630 $valueNode = new PPNode_Hash_Tree( 'value' );
631 $valueNode->firstChild = $part->out->firstNode;
632 $valueNode->lastChild = $part->out->lastNode;
633 $partNode->addChild( $nameNode );
634 $partNode->addChild( $valueNode );
635 $element->addChild( $partNode );
640 # Advance input pointer
641 $i += $matchingCount;
643 # Unwind the stack
644 $stack->pop();
645 $accum =& $stack->getAccum();
647 # Re-add the old stack element if it still has unmatched opening characters remaining
648 if ( $matchingCount < $piece->count ) {
649 $piece->parts = array( new PPDPart_Hash );
650 $piece->count -= $matchingCount;
651 # do we still qualify for any callback with remaining count?
652 $min = $this->rules[$piece->open]['min'];
653 if ( $piece->count >= $min ) {
654 $stack->push( $piece );
655 $accum =& $stack->getAccum();
656 } else {
657 $accum->addLiteral( str_repeat( $piece->open, $piece->count ) );
661 extract( $stack->getFlags() );
663 # Add XML element to the enclosing accumulator
664 if ( $element instanceof PPNode ) {
665 $accum->addNode( $element );
666 } else {
667 $accum->addAccum( $element );
669 } elseif ( $found == 'pipe' ) {
670 $findEquals = true; // shortcut for getFlags()
671 $stack->addPart();
672 $accum =& $stack->getAccum();
673 ++$i;
674 } elseif ( $found == 'equals' ) {
675 $findEquals = false; // shortcut for getFlags()
676 $accum->addNodeWithText( 'equals', '=' );
677 $stack->getCurrentPart()->eqpos = $accum->lastNode;
678 ++$i;
682 # Output any remaining unclosed brackets
683 foreach ( $stack->stack as $piece ) {
684 $stack->rootAccum->addAccum( $piece->breakSyntax() );
687 # Enable top-level headings
688 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
689 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
690 $node->name = 'h';
694 $rootNode = new PPNode_Hash_Tree( 'root' );
695 $rootNode->firstChild = $stack->rootAccum->firstNode;
696 $rootNode->lastChild = $stack->rootAccum->lastNode;
698 // Cache
699 $this->cacheSetTree( $text, $flags, serialize( $rootNode ) );
701 return $rootNode;
706 * Stack class to help Preprocessor::preprocessToObj()
707 * @ingroup Parser
709 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
710 class PPDStack_Hash extends PPDStack {
711 // @codingStandardsIgnoreEnd
713 public function __construct() {
714 $this->elementClass = 'PPDStackElement_Hash';
715 parent::__construct();
716 $this->rootAccum = new PPDAccum_Hash;
721 * @ingroup Parser
723 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
724 class PPDStackElement_Hash extends PPDStackElement {
725 // @codingStandardsIgnoreENd
727 public function __construct( $data = array() ) {
728 $this->partClass = 'PPDPart_Hash';
729 parent::__construct( $data );
733 * Get the accumulator that would result if the close is not found.
735 * @param int|bool $openingCount
736 * @return PPDAccum_Hash
738 public function breakSyntax( $openingCount = false ) {
739 if ( $this->open == "\n" ) {
740 $accum = $this->parts[0]->out;
741 } else {
742 if ( $openingCount === false ) {
743 $openingCount = $this->count;
745 $accum = new PPDAccum_Hash;
746 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
747 $first = true;
748 foreach ( $this->parts as $part ) {
749 if ( $first ) {
750 $first = false;
751 } else {
752 $accum->addLiteral( '|' );
754 $accum->addAccum( $part->out );
757 return $accum;
762 * @ingroup Parser
764 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
765 class PPDPart_Hash extends PPDPart {
766 // @codingStandardsIgnoreEnd
768 public function __construct( $out = '' ) {
769 $accum = new PPDAccum_Hash;
770 if ( $out !== '' ) {
771 $accum->addLiteral( $out );
773 parent::__construct( $accum );
778 * @ingroup Parser
780 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
781 class PPDAccum_Hash {
782 // @codingStandardsIgnoreEnd
784 public $firstNode, $lastNode;
786 public function __construct() {
787 $this->firstNode = $this->lastNode = false;
791 * Append a string literal
792 * @param string $s
794 public function addLiteral( $s ) {
795 if ( $this->lastNode === false ) {
796 $this->firstNode = $this->lastNode = new PPNode_Hash_Text( $s );
797 } elseif ( $this->lastNode instanceof PPNode_Hash_Text ) {
798 $this->lastNode->value .= $s;
799 } else {
800 $this->lastNode->nextSibling = new PPNode_Hash_Text( $s );
801 $this->lastNode = $this->lastNode->nextSibling;
806 * Append a PPNode
807 * @param PPNode $node
809 public function addNode( PPNode $node ) {
810 if ( $this->lastNode === false ) {
811 $this->firstNode = $this->lastNode = $node;
812 } else {
813 $this->lastNode->nextSibling = $node;
814 $this->lastNode = $node;
819 * Append a tree node with text contents
820 * @param string $name
821 * @param string $value
823 public function addNodeWithText( $name, $value ) {
824 $node = PPNode_Hash_Tree::newWithText( $name, $value );
825 $this->addNode( $node );
829 * Append a PPDAccum_Hash
830 * Takes over ownership of the nodes in the source argument. These nodes may
831 * subsequently be modified, especially nextSibling.
832 * @param PPDAccum_Hash $accum
834 public function addAccum( $accum ) {
835 if ( $accum->lastNode === false ) {
836 // nothing to add
837 } elseif ( $this->lastNode === false ) {
838 $this->firstNode = $accum->firstNode;
839 $this->lastNode = $accum->lastNode;
840 } else {
841 $this->lastNode->nextSibling = $accum->firstNode;
842 $this->lastNode = $accum->lastNode;
848 * An expansion frame, used as a context to expand the result of preprocessToObj()
849 * @ingroup Parser
851 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
852 class PPFrame_Hash implements PPFrame {
853 // @codingStandardsIgnoreEnd
856 * @var Parser
858 public $parser;
861 * @var Preprocessor
863 public $preprocessor;
866 * @var Title
868 public $title;
869 public $titleCache;
872 * Hashtable listing templates which are disallowed for expansion in this frame,
873 * having been encountered previously in parent frames.
875 public $loopCheckHash;
878 * Recursion depth of this frame, top = 0
879 * Note that this is NOT the same as expansion depth in expand()
881 public $depth;
883 private $volatile = false;
884 private $ttl = null;
887 * @var array
889 protected $childExpansionCache;
892 * Construct a new preprocessor frame.
893 * @param Preprocessor $preprocessor The parent preprocessor
895 public function __construct( $preprocessor ) {
896 $this->preprocessor = $preprocessor;
897 $this->parser = $preprocessor->parser;
898 $this->title = $this->parser->mTitle;
899 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
900 $this->loopCheckHash = array();
901 $this->depth = 0;
902 $this->childExpansionCache = array();
906 * Create a new child frame
907 * $args is optionally a multi-root PPNode or array containing the template arguments
909 * @param array|bool|PPNode_Hash_Array $args
910 * @param Title|bool $title
911 * @param int $indexOffset
912 * @throws MWException
913 * @return PPTemplateFrame_Hash
915 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
916 $namedArgs = array();
917 $numberedArgs = array();
918 if ( $title === false ) {
919 $title = $this->title;
921 if ( $args !== false ) {
922 if ( $args instanceof PPNode_Hash_Array ) {
923 $args = $args->value;
924 } elseif ( !is_array( $args ) ) {
925 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
927 foreach ( $args as $arg ) {
928 $bits = $arg->splitArg();
929 if ( $bits['index'] !== '' ) {
930 // Numbered parameter
931 $index = $bits['index'] - $indexOffset;
932 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
933 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
934 wfEscapeWikiText( $this->title ),
935 wfEscapeWikiText( $title ),
936 wfEscapeWikiText( $index ) )->text() );
937 $this->parser->addTrackingCategory( 'duplicate-args-category' );
939 $numberedArgs[$index] = $bits['value'];
940 unset( $namedArgs[$index] );
941 } else {
942 // Named parameter
943 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
944 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
945 $this->parser->getOutput()->addWarning( wfMessage( 'duplicate-args-warning',
946 wfEscapeWikiText( $this->title ),
947 wfEscapeWikiText( $title ),
948 wfEscapeWikiText( $name ) )->text() );
949 $this->parser->addTrackingCategory( 'duplicate-args-category' );
951 $namedArgs[$name] = $bits['value'];
952 unset( $numberedArgs[$name] );
956 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
960 * @throws MWException
961 * @param string|int $key
962 * @param string|PPNode $root
963 * @param int $flags
964 * @return string
966 public function cachedExpand( $key, $root, $flags = 0 ) {
967 // we don't have a parent, so we don't have a cache
968 return $this->expand( $root, $flags );
972 * @throws MWException
973 * @param string|PPNode $root
974 * @param int $flags
975 * @return string
977 public function expand( $root, $flags = 0 ) {
978 static $expansionDepth = 0;
979 if ( is_string( $root ) ) {
980 return $root;
983 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
984 $this->parser->limitationWarn( 'node-count-exceeded',
985 $this->parser->mPPNodeCount,
986 $this->parser->mOptions->getMaxPPNodeCount()
988 return '<span class="error">Node-count limit exceeded</span>';
990 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
991 $this->parser->limitationWarn( 'expansion-depth-exceeded',
992 $expansionDepth,
993 $this->parser->mOptions->getMaxPPExpandDepth()
995 return '<span class="error">Expansion depth limit exceeded</span>';
997 ++$expansionDepth;
998 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
999 $this->parser->mHighestExpansionDepth = $expansionDepth;
1002 $outStack = array( '', '' );
1003 $iteratorStack = array( false, $root );
1004 $indexStack = array( 0, 0 );
1006 while ( count( $iteratorStack ) > 1 ) {
1007 $level = count( $outStack ) - 1;
1008 $iteratorNode =& $iteratorStack[$level];
1009 $out =& $outStack[$level];
1010 $index =& $indexStack[$level];
1012 if ( is_array( $iteratorNode ) ) {
1013 if ( $index >= count( $iteratorNode ) ) {
1014 // All done with this iterator
1015 $iteratorStack[$level] = false;
1016 $contextNode = false;
1017 } else {
1018 $contextNode = $iteratorNode[$index];
1019 $index++;
1021 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
1022 if ( $index >= $iteratorNode->getLength() ) {
1023 // All done with this iterator
1024 $iteratorStack[$level] = false;
1025 $contextNode = false;
1026 } else {
1027 $contextNode = $iteratorNode->item( $index );
1028 $index++;
1030 } else {
1031 // Copy to $contextNode and then delete from iterator stack,
1032 // because this is not an iterator but we do have to execute it once
1033 $contextNode = $iteratorStack[$level];
1034 $iteratorStack[$level] = false;
1037 $newIterator = false;
1039 if ( $contextNode === false ) {
1040 // nothing to do
1041 } elseif ( is_string( $contextNode ) ) {
1042 $out .= $contextNode;
1043 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
1044 $newIterator = $contextNode;
1045 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
1046 // No output
1047 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
1048 $out .= $contextNode->value;
1049 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
1050 if ( $contextNode->name == 'template' ) {
1051 # Double-brace expansion
1052 $bits = $contextNode->splitTemplate();
1053 if ( $flags & PPFrame::NO_TEMPLATES ) {
1054 $newIterator = $this->virtualBracketedImplode(
1055 '{{', '|', '}}',
1056 $bits['title'],
1057 $bits['parts']
1059 } else {
1060 $ret = $this->parser->braceSubstitution( $bits, $this );
1061 if ( isset( $ret['object'] ) ) {
1062 $newIterator = $ret['object'];
1063 } else {
1064 $out .= $ret['text'];
1067 } elseif ( $contextNode->name == 'tplarg' ) {
1068 # Triple-brace expansion
1069 $bits = $contextNode->splitTemplate();
1070 if ( $flags & PPFrame::NO_ARGS ) {
1071 $newIterator = $this->virtualBracketedImplode(
1072 '{{{', '|', '}}}',
1073 $bits['title'],
1074 $bits['parts']
1076 } else {
1077 $ret = $this->parser->argSubstitution( $bits, $this );
1078 if ( isset( $ret['object'] ) ) {
1079 $newIterator = $ret['object'];
1080 } else {
1081 $out .= $ret['text'];
1084 } elseif ( $contextNode->name == 'comment' ) {
1085 # HTML-style comment
1086 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1087 # Not in RECOVER_COMMENTS mode (msgnw) though.
1088 if ( ( $this->parser->ot['html']
1089 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1090 || ( $flags & PPFrame::STRIP_COMMENTS )
1091 ) && !( $flags & PPFrame::RECOVER_COMMENTS )
1093 $out .= '';
1094 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1095 # Add a strip marker in PST mode so that pstPass2() can
1096 # run some old-fashioned regexes on the result.
1097 # Not in RECOVER_COMMENTS mode (extractSections) though.
1098 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1099 } else {
1100 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1101 $out .= $contextNode->firstChild->value;
1103 } elseif ( $contextNode->name == 'ignore' ) {
1104 # Output suppression used by <includeonly> etc.
1105 # OT_WIKI will only respect <ignore> in substed templates.
1106 # The other output types respect it unless NO_IGNORE is set.
1107 # extractSections() sets NO_IGNORE and so never respects it.
1108 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1109 || ( $flags & PPFrame::NO_IGNORE )
1111 $out .= $contextNode->firstChild->value;
1112 } else {
1113 // $out .= '';
1115 } elseif ( $contextNode->name == 'ext' ) {
1116 # Extension tag
1117 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1118 if ( $flags & PPFrame::NO_TAGS ) {
1119 $s = '<' . $bits['name']->firstChild->value;
1120 if ( $bits['attr'] ) {
1121 $s .= $bits['attr']->firstChild->value;
1123 if ( $bits['inner'] ) {
1124 $s .= '>' . $bits['inner']->firstChild->value;
1125 if ( $bits['close'] ) {
1126 $s .= $bits['close']->firstChild->value;
1128 } else {
1129 $s .= '/>';
1131 $out .= $s;
1132 } else {
1133 $out .= $this->parser->extensionSubstitution( $bits, $this );
1135 } elseif ( $contextNode->name == 'h' ) {
1136 # Heading
1137 if ( $this->parser->ot['html'] ) {
1138 # Expand immediately and insert heading index marker
1139 $s = '';
1140 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1141 $s .= $this->expand( $node, $flags );
1144 $bits = $contextNode->splitHeading();
1145 $titleText = $this->title->getPrefixedDBkey();
1146 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1147 $serial = count( $this->parser->mHeadings ) - 1;
1148 $marker = Parser::MARKER_PREFIX . "-h-$serial-" . Parser::MARKER_SUFFIX;
1149 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1150 $this->parser->mStripState->addGeneral( $marker, '' );
1151 $out .= $s;
1152 } else {
1153 # Expand in virtual stack
1154 $newIterator = $contextNode->getChildren();
1156 } else {
1157 # Generic recursive expansion
1158 $newIterator = $contextNode->getChildren();
1160 } else {
1161 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1164 if ( $newIterator !== false ) {
1165 $outStack[] = '';
1166 $iteratorStack[] = $newIterator;
1167 $indexStack[] = 0;
1168 } elseif ( $iteratorStack[$level] === false ) {
1169 // Return accumulated value to parent
1170 // With tail recursion
1171 while ( $iteratorStack[$level] === false && $level > 0 ) {
1172 $outStack[$level - 1] .= $out;
1173 array_pop( $outStack );
1174 array_pop( $iteratorStack );
1175 array_pop( $indexStack );
1176 $level--;
1180 --$expansionDepth;
1181 return $outStack[0];
1185 * @param string $sep
1186 * @param int $flags
1187 * @param string|PPNode $args,...
1188 * @return string
1190 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1191 $args = array_slice( func_get_args(), 2 );
1193 $first = true;
1194 $s = '';
1195 foreach ( $args as $root ) {
1196 if ( $root instanceof PPNode_Hash_Array ) {
1197 $root = $root->value;
1199 if ( !is_array( $root ) ) {
1200 $root = array( $root );
1202 foreach ( $root as $node ) {
1203 if ( $first ) {
1204 $first = false;
1205 } else {
1206 $s .= $sep;
1208 $s .= $this->expand( $node, $flags );
1211 return $s;
1215 * Implode with no flags specified
1216 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1217 * @param string $sep
1218 * @param string|PPNode $args,...
1219 * @return string
1221 public function implode( $sep /*, ... */ ) {
1222 $args = array_slice( func_get_args(), 1 );
1224 $first = true;
1225 $s = '';
1226 foreach ( $args as $root ) {
1227 if ( $root instanceof PPNode_Hash_Array ) {
1228 $root = $root->value;
1230 if ( !is_array( $root ) ) {
1231 $root = array( $root );
1233 foreach ( $root as $node ) {
1234 if ( $first ) {
1235 $first = false;
1236 } else {
1237 $s .= $sep;
1239 $s .= $this->expand( $node );
1242 return $s;
1246 * Makes an object that, when expand()ed, will be the same as one obtained
1247 * with implode()
1249 * @param string $sep
1250 * @param string|PPNode $args,...
1251 * @return PPNode_Hash_Array
1253 public function virtualImplode( $sep /*, ... */ ) {
1254 $args = array_slice( func_get_args(), 1 );
1255 $out = array();
1256 $first = true;
1258 foreach ( $args as $root ) {
1259 if ( $root instanceof PPNode_Hash_Array ) {
1260 $root = $root->value;
1262 if ( !is_array( $root ) ) {
1263 $root = array( $root );
1265 foreach ( $root as $node ) {
1266 if ( $first ) {
1267 $first = false;
1268 } else {
1269 $out[] = $sep;
1271 $out[] = $node;
1274 return new PPNode_Hash_Array( $out );
1278 * Virtual implode with brackets
1280 * @param string $start
1281 * @param string $sep
1282 * @param string $end
1283 * @param string|PPNode $args,...
1284 * @return PPNode_Hash_Array
1286 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1287 $args = array_slice( func_get_args(), 3 );
1288 $out = array( $start );
1289 $first = true;
1291 foreach ( $args as $root ) {
1292 if ( $root instanceof PPNode_Hash_Array ) {
1293 $root = $root->value;
1295 if ( !is_array( $root ) ) {
1296 $root = array( $root );
1298 foreach ( $root as $node ) {
1299 if ( $first ) {
1300 $first = false;
1301 } else {
1302 $out[] = $sep;
1304 $out[] = $node;
1307 $out[] = $end;
1308 return new PPNode_Hash_Array( $out );
1311 public function __toString() {
1312 return 'frame{}';
1316 * @param bool $level
1317 * @return array|bool|string
1319 public function getPDBK( $level = false ) {
1320 if ( $level === false ) {
1321 return $this->title->getPrefixedDBkey();
1322 } else {
1323 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1328 * @return array
1330 public function getArguments() {
1331 return array();
1335 * @return array
1337 public function getNumberedArguments() {
1338 return array();
1342 * @return array
1344 public function getNamedArguments() {
1345 return array();
1349 * Returns true if there are no arguments in this frame
1351 * @return bool
1353 public function isEmpty() {
1354 return true;
1358 * @param string $name
1359 * @return bool
1361 public function getArgument( $name ) {
1362 return false;
1366 * Returns true if the infinite loop check is OK, false if a loop is detected
1368 * @param Title $title
1370 * @return bool
1372 public function loopCheck( $title ) {
1373 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1377 * Return true if the frame is a template frame
1379 * @return bool
1381 public function isTemplate() {
1382 return false;
1386 * Get a title of frame
1388 * @return Title
1390 public function getTitle() {
1391 return $this->title;
1395 * Set the volatile flag
1397 * @param bool $flag
1399 public function setVolatile( $flag = true ) {
1400 $this->volatile = $flag;
1404 * Get the volatile flag
1406 * @return bool
1408 public function isVolatile() {
1409 return $this->volatile;
1413 * Set the TTL
1415 * @param int $ttl
1417 public function setTTL( $ttl ) {
1418 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1419 $this->ttl = $ttl;
1424 * Get the TTL
1426 * @return int|null
1428 public function getTTL() {
1429 return $this->ttl;
1434 * Expansion frame with template arguments
1435 * @ingroup Parser
1437 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1438 class PPTemplateFrame_Hash extends PPFrame_Hash {
1439 // @codingStandardsIgnoreEnd
1441 public $numberedArgs, $namedArgs, $parent;
1442 public $numberedExpansionCache, $namedExpansionCache;
1445 * @param Preprocessor $preprocessor
1446 * @param bool|PPFrame $parent
1447 * @param array $numberedArgs
1448 * @param array $namedArgs
1449 * @param bool|Title $title
1451 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1452 $namedArgs = array(), $title = false
1454 parent::__construct( $preprocessor );
1456 $this->parent = $parent;
1457 $this->numberedArgs = $numberedArgs;
1458 $this->namedArgs = $namedArgs;
1459 $this->title = $title;
1460 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1461 $this->titleCache = $parent->titleCache;
1462 $this->titleCache[] = $pdbk;
1463 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1464 if ( $pdbk !== false ) {
1465 $this->loopCheckHash[$pdbk] = true;
1467 $this->depth = $parent->depth + 1;
1468 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1471 public function __toString() {
1472 $s = 'tplframe{';
1473 $first = true;
1474 $args = $this->numberedArgs + $this->namedArgs;
1475 foreach ( $args as $name => $value ) {
1476 if ( $first ) {
1477 $first = false;
1478 } else {
1479 $s .= ', ';
1481 $s .= "\"$name\":\"" .
1482 str_replace( '"', '\\"', $value->__toString() ) . '"';
1484 $s .= '}';
1485 return $s;
1489 * @throws MWException
1490 * @param string|int $key
1491 * @param string|PPNode $root
1492 * @param int $flags
1493 * @return string
1495 public function cachedExpand( $key, $root, $flags = 0 ) {
1496 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1497 return $this->parent->childExpansionCache[$key];
1499 $retval = $this->expand( $root, $flags );
1500 if ( !$this->isVolatile() ) {
1501 $this->parent->childExpansionCache[$key] = $retval;
1503 return $retval;
1507 * Returns true if there are no arguments in this frame
1509 * @return bool
1511 public function isEmpty() {
1512 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1516 * @return array
1518 public function getArguments() {
1519 $arguments = array();
1520 foreach ( array_merge(
1521 array_keys( $this->numberedArgs ),
1522 array_keys( $this->namedArgs ) ) as $key ) {
1523 $arguments[$key] = $this->getArgument( $key );
1525 return $arguments;
1529 * @return array
1531 public function getNumberedArguments() {
1532 $arguments = array();
1533 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1534 $arguments[$key] = $this->getArgument( $key );
1536 return $arguments;
1540 * @return array
1542 public function getNamedArguments() {
1543 $arguments = array();
1544 foreach ( array_keys( $this->namedArgs ) as $key ) {
1545 $arguments[$key] = $this->getArgument( $key );
1547 return $arguments;
1551 * @param int $index
1552 * @return array|bool
1554 public function getNumberedArgument( $index ) {
1555 if ( !isset( $this->numberedArgs[$index] ) ) {
1556 return false;
1558 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1559 # No trimming for unnamed arguments
1560 $this->numberedExpansionCache[$index] = $this->parent->expand(
1561 $this->numberedArgs[$index],
1562 PPFrame::STRIP_COMMENTS
1565 return $this->numberedExpansionCache[$index];
1569 * @param string $name
1570 * @return bool
1572 public function getNamedArgument( $name ) {
1573 if ( !isset( $this->namedArgs[$name] ) ) {
1574 return false;
1576 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1577 # Trim named arguments post-expand, for backwards compatibility
1578 $this->namedExpansionCache[$name] = trim(
1579 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1581 return $this->namedExpansionCache[$name];
1585 * @param string $name
1586 * @return array|bool
1588 public function getArgument( $name ) {
1589 $text = $this->getNumberedArgument( $name );
1590 if ( $text === false ) {
1591 $text = $this->getNamedArgument( $name );
1593 return $text;
1597 * Return true if the frame is a template frame
1599 * @return bool
1601 public function isTemplate() {
1602 return true;
1605 public function setVolatile( $flag = true ) {
1606 parent::setVolatile( $flag );
1607 $this->parent->setVolatile( $flag );
1610 public function setTTL( $ttl ) {
1611 parent::setTTL( $ttl );
1612 $this->parent->setTTL( $ttl );
1617 * Expansion frame with custom arguments
1618 * @ingroup Parser
1620 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1621 class PPCustomFrame_Hash extends PPFrame_Hash {
1622 // @codingStandardsIgnoreEnd
1624 public $args;
1626 public function __construct( $preprocessor, $args ) {
1627 parent::__construct( $preprocessor );
1628 $this->args = $args;
1631 public function __toString() {
1632 $s = 'cstmframe{';
1633 $first = true;
1634 foreach ( $this->args as $name => $value ) {
1635 if ( $first ) {
1636 $first = false;
1637 } else {
1638 $s .= ', ';
1640 $s .= "\"$name\":\"" .
1641 str_replace( '"', '\\"', $value->__toString() ) . '"';
1643 $s .= '}';
1644 return $s;
1648 * @return bool
1650 public function isEmpty() {
1651 return !count( $this->args );
1655 * @param int $index
1656 * @return bool
1658 public function getArgument( $index ) {
1659 if ( !isset( $this->args[$index] ) ) {
1660 return false;
1662 return $this->args[$index];
1665 public function getArguments() {
1666 return $this->args;
1671 * @ingroup Parser
1673 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1674 class PPNode_Hash_Tree implements PPNode {
1675 // @codingStandardsIgnoreEnd
1677 public $name, $firstChild, $lastChild, $nextSibling;
1679 public function __construct( $name ) {
1680 $this->name = $name;
1681 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1684 public function __toString() {
1685 $inner = '';
1686 $attribs = '';
1687 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1688 if ( $node instanceof PPNode_Hash_Attr ) {
1689 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1690 } else {
1691 $inner .= $node->__toString();
1694 if ( $inner === '' ) {
1695 return "<{$this->name}$attribs/>";
1696 } else {
1697 return "<{$this->name}$attribs>$inner</{$this->name}>";
1702 * @param string $name
1703 * @param string $text
1704 * @return PPNode_Hash_Tree
1706 public static function newWithText( $name, $text ) {
1707 $obj = new self( $name );
1708 $obj->addChild( new PPNode_Hash_Text( $text ) );
1709 return $obj;
1712 public function addChild( $node ) {
1713 if ( $this->lastChild === false ) {
1714 $this->firstChild = $this->lastChild = $node;
1715 } else {
1716 $this->lastChild->nextSibling = $node;
1717 $this->lastChild = $node;
1722 * @return PPNode_Hash_Array
1724 public function getChildren() {
1725 $children = array();
1726 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1727 $children[] = $child;
1729 return new PPNode_Hash_Array( $children );
1732 public function getFirstChild() {
1733 return $this->firstChild;
1736 public function getNextSibling() {
1737 return $this->nextSibling;
1740 public function getChildrenOfType( $name ) {
1741 $children = array();
1742 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1743 if ( isset( $child->name ) && $child->name === $name ) {
1744 $children[] = $child;
1747 return new PPNode_Hash_Array( $children );
1751 * @return bool
1753 public function getLength() {
1754 return false;
1758 * @param int $i
1759 * @return bool
1761 public function item( $i ) {
1762 return false;
1766 * @return string
1768 public function getName() {
1769 return $this->name;
1773 * Split a "<part>" node into an associative array containing:
1774 * - name PPNode name
1775 * - index String index
1776 * - value PPNode value
1778 * @throws MWException
1779 * @return array
1781 public function splitArg() {
1782 $bits = array();
1783 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1784 if ( !isset( $child->name ) ) {
1785 continue;
1787 if ( $child->name === 'name' ) {
1788 $bits['name'] = $child;
1789 if ( $child->firstChild instanceof PPNode_Hash_Attr
1790 && $child->firstChild->name === 'index'
1792 $bits['index'] = $child->firstChild->value;
1794 } elseif ( $child->name === 'value' ) {
1795 $bits['value'] = $child;
1799 if ( !isset( $bits['name'] ) ) {
1800 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1802 if ( !isset( $bits['index'] ) ) {
1803 $bits['index'] = '';
1805 return $bits;
1809 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1810 * All values in the resulting array are PPNodes. Inner and close are optional.
1812 * @throws MWException
1813 * @return array
1815 public function splitExt() {
1816 $bits = array();
1817 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1818 if ( !isset( $child->name ) ) {
1819 continue;
1821 if ( $child->name == 'name' ) {
1822 $bits['name'] = $child;
1823 } elseif ( $child->name == 'attr' ) {
1824 $bits['attr'] = $child;
1825 } elseif ( $child->name == 'inner' ) {
1826 $bits['inner'] = $child;
1827 } elseif ( $child->name == 'close' ) {
1828 $bits['close'] = $child;
1831 if ( !isset( $bits['name'] ) ) {
1832 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1834 return $bits;
1838 * Split an "<h>" node
1840 * @throws MWException
1841 * @return array
1843 public function splitHeading() {
1844 if ( $this->name !== 'h' ) {
1845 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1847 $bits = array();
1848 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1849 if ( !isset( $child->name ) ) {
1850 continue;
1852 if ( $child->name == 'i' ) {
1853 $bits['i'] = $child->value;
1854 } elseif ( $child->name == 'level' ) {
1855 $bits['level'] = $child->value;
1858 if ( !isset( $bits['i'] ) ) {
1859 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1861 return $bits;
1865 * Split a "<template>" or "<tplarg>" node
1867 * @throws MWException
1868 * @return array
1870 public function splitTemplate() {
1871 $parts = array();
1872 $bits = array( 'lineStart' => '' );
1873 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1874 if ( !isset( $child->name ) ) {
1875 continue;
1877 if ( $child->name == 'title' ) {
1878 $bits['title'] = $child;
1880 if ( $child->name == 'part' ) {
1881 $parts[] = $child;
1883 if ( $child->name == 'lineStart' ) {
1884 $bits['lineStart'] = '1';
1887 if ( !isset( $bits['title'] ) ) {
1888 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1890 $bits['parts'] = new PPNode_Hash_Array( $parts );
1891 return $bits;
1896 * @ingroup Parser
1898 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1899 class PPNode_Hash_Text implements PPNode {
1900 // @codingStandardsIgnoreEnd
1902 public $value, $nextSibling;
1904 public function __construct( $value ) {
1905 if ( is_object( $value ) ) {
1906 throw new MWException( __CLASS__ . ' given object instead of string' );
1908 $this->value = $value;
1911 public function __toString() {
1912 return htmlspecialchars( $this->value );
1915 public function getNextSibling() {
1916 return $this->nextSibling;
1919 public function getChildren() {
1920 return false;
1923 public function getFirstChild() {
1924 return false;
1927 public function getChildrenOfType( $name ) {
1928 return false;
1931 public function getLength() {
1932 return false;
1935 public function item( $i ) {
1936 return false;
1939 public function getName() {
1940 return '#text';
1943 public function splitArg() {
1944 throw new MWException( __METHOD__ . ': not supported' );
1947 public function splitExt() {
1948 throw new MWException( __METHOD__ . ': not supported' );
1951 public function splitHeading() {
1952 throw new MWException( __METHOD__ . ': not supported' );
1957 * @ingroup Parser
1959 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
1960 class PPNode_Hash_Array implements PPNode {
1961 // @codingStandardsIgnoreEnd
1963 public $value, $nextSibling;
1965 public function __construct( $value ) {
1966 $this->value = $value;
1969 public function __toString() {
1970 return var_export( $this, true );
1973 public function getLength() {
1974 return count( $this->value );
1977 public function item( $i ) {
1978 return $this->value[$i];
1981 public function getName() {
1982 return '#nodelist';
1985 public function getNextSibling() {
1986 return $this->nextSibling;
1989 public function getChildren() {
1990 return false;
1993 public function getFirstChild() {
1994 return false;
1997 public function getChildrenOfType( $name ) {
1998 return false;
2001 public function splitArg() {
2002 throw new MWException( __METHOD__ . ': not supported' );
2005 public function splitExt() {
2006 throw new MWException( __METHOD__ . ': not supported' );
2009 public function splitHeading() {
2010 throw new MWException( __METHOD__ . ': not supported' );
2015 * @ingroup Parser
2017 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
2018 class PPNode_Hash_Attr implements PPNode {
2019 // @codingStandardsIgnoreEnd
2021 public $name, $value, $nextSibling;
2023 public function __construct( $name, $value ) {
2024 $this->name = $name;
2025 $this->value = $value;
2028 public function __toString() {
2029 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
2032 public function getName() {
2033 return $this->name;
2036 public function getNextSibling() {
2037 return $this->nextSibling;
2040 public function getChildren() {
2041 return false;
2044 public function getFirstChild() {
2045 return false;
2048 public function getChildrenOfType( $name ) {
2049 return false;
2052 public function getLength() {
2053 return false;
2056 public function item( $i ) {
2057 return false;
2060 public function splitArg() {
2061 throw new MWException( __METHOD__ . ': not supported' );
2064 public function splitExt() {
2065 throw new MWException( __METHOD__ . ': not supported' );
2068 public function splitHeading() {
2069 throw new MWException( __METHOD__ . ': not supported' );