Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / parser / Preprocessor_Hash.php
blobaf91ad47fbfc0ecfe8fd56a63194efddcfc6ff7b
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
29 * @codingStandardsIgnoreStart
31 class Preprocessor_Hash implements Preprocessor {
32 // @codingStandardsIgnoreEnd
34 /**
35 * @var Parser
37 public $parser;
39 const CACHE_VERSION = 1;
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 ) {
116 // Check cache.
117 global $wgMemc, $wgPreprocessorCacheThreshold;
119 $cacheable = $wgPreprocessorCacheThreshold !== false
120 && strlen( $text ) > $wgPreprocessorCacheThreshold;
122 if ( $cacheable ) {
124 $cacheKey = wfMemcKey( 'preprocess-hash', md5( $text ), $flags );
125 $cacheValue = $wgMemc->get( $cacheKey );
126 if ( $cacheValue ) {
127 $version = substr( $cacheValue, 0, 8 );
128 if ( intval( $version ) == self::CACHE_VERSION ) {
129 $hash = unserialize( substr( $cacheValue, 8 ) );
130 // From the cache
131 wfDebugLog( "Preprocessor",
132 "Loaded preprocessor hash from memcached (key $cacheKey)" );
133 return $hash;
138 $rules = array(
139 '{' => array(
140 'end' => '}',
141 'names' => array(
142 2 => 'template',
143 3 => 'tplarg',
145 'min' => 2,
146 'max' => 3,
148 '[' => array(
149 'end' => ']',
150 'names' => array( 2 => null ),
151 'min' => 2,
152 'max' => 2,
156 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
158 $xmlishElements = $this->parser->getStripList();
159 $enableOnlyinclude = false;
160 if ( $forInclusion ) {
161 $ignoredTags = array( 'includeonly', '/includeonly' );
162 $ignoredElements = array( 'noinclude' );
163 $xmlishElements[] = 'noinclude';
164 if ( strpos( $text, '<onlyinclude>' ) !== false
165 && strpos( $text, '</onlyinclude>' ) !== false
167 $enableOnlyinclude = true;
169 } else {
170 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
171 $ignoredElements = array( 'includeonly' );
172 $xmlishElements[] = 'includeonly';
174 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
176 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
177 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
179 $stack = new PPDStack_Hash;
181 $searchBase = "[{<\n";
182 // For fast reverse searches
183 $revText = strrev( $text );
184 $lengthText = strlen( $text );
186 // Input pointer, starts out pointing to a pseudo-newline before the start
187 $i = 0;
188 // Current accumulator
189 $accum =& $stack->getAccum();
190 // True to find equals signs in arguments
191 $findEquals = false;
192 // True to take notice of pipe characters
193 $findPipe = false;
194 $headingIndex = 1;
195 // True if $i is inside a possible heading
196 $inHeading = false;
197 // True if there are no more greater-than (>) signs right of $i
198 $noMoreGT = false;
199 // True to ignore all input up to the next <onlyinclude>
200 $findOnlyinclude = $enableOnlyinclude;
201 // Do a line-start run without outputting an LF character
202 $fakeLineStart = true;
204 while ( true ) {
205 //$this->memCheck();
207 if ( $findOnlyinclude ) {
208 // Ignore all input up to the next <onlyinclude>
209 $startPos = strpos( $text, '<onlyinclude>', $i );
210 if ( $startPos === false ) {
211 // Ignored section runs to the end
212 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
213 break;
215 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
216 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
217 $i = $tagEndPos;
218 $findOnlyinclude = false;
221 if ( $fakeLineStart ) {
222 $found = 'line-start';
223 $curChar = '';
224 } else {
225 # Find next opening brace, closing brace or pipe
226 $search = $searchBase;
227 if ( $stack->top === false ) {
228 $currentClosing = '';
229 } else {
230 $currentClosing = $stack->top->close;
231 $search .= $currentClosing;
233 if ( $findPipe ) {
234 $search .= '|';
236 if ( $findEquals ) {
237 // First equals will be for the template
238 $search .= '=';
240 $rule = null;
241 # Output literal section, advance input counter
242 $literalLength = strcspn( $text, $search, $i );
243 if ( $literalLength > 0 ) {
244 $accum->addLiteral( substr( $text, $i, $literalLength ) );
245 $i += $literalLength;
247 if ( $i >= $lengthText ) {
248 if ( $currentClosing == "\n" ) {
249 // Do a past-the-end run to finish off the heading
250 $curChar = '';
251 $found = 'line-end';
252 } else {
253 # All done
254 break;
256 } else {
257 $curChar = $text[$i];
258 if ( $curChar == '|' ) {
259 $found = 'pipe';
260 } elseif ( $curChar == '=' ) {
261 $found = 'equals';
262 } elseif ( $curChar == '<' ) {
263 $found = 'angle';
264 } elseif ( $curChar == "\n" ) {
265 if ( $inHeading ) {
266 $found = 'line-end';
267 } else {
268 $found = 'line-start';
270 } elseif ( $curChar == $currentClosing ) {
271 $found = 'close';
272 } elseif ( isset( $rules[$curChar] ) ) {
273 $found = 'open';
274 $rule = $rules[$curChar];
275 } else {
276 # Some versions of PHP have a strcspn which stops on null characters
277 # Ignore and continue
278 ++$i;
279 continue;
284 if ( $found == 'angle' ) {
285 $matches = false;
286 // Handle </onlyinclude>
287 if ( $enableOnlyinclude
288 && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>'
290 $findOnlyinclude = true;
291 continue;
294 // Determine element name
295 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
296 // Element name missing or not listed
297 $accum->addLiteral( '<' );
298 ++$i;
299 continue;
301 // Handle comments
302 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
304 // To avoid leaving blank lines, when a sequence of
305 // space-separated comments is both preceded and followed by
306 // a newline (ignoring spaces), then
307 // trim leading and trailing spaces and the trailing newline.
309 // Find the end
310 $endPos = strpos( $text, '-->', $i + 4 );
311 if ( $endPos === false ) {
312 // Unclosed comment in input, runs to end
313 $inner = substr( $text, $i );
314 $accum->addNodeWithText( 'comment', $inner );
315 $i = $lengthText;
316 } else {
317 // Search backwards for leading whitespace
318 $wsStart = $i ? ( $i - strspn( $revText, " \t", $lengthText - $i ) ) : 0;
320 // Search forwards for trailing whitespace
321 // $wsEnd will be the position of the last space (or the '>' if there's none)
322 $wsEnd = $endPos + 2 + strspn( $text, " \t", $endPos + 3 );
324 // Keep looking forward as long as we're finding more
325 // comments.
326 $comments = array( array( $wsStart, $wsEnd ) );
327 while ( substr( $text, $wsEnd + 1, 4 ) == '<!--' ) {
328 $c = strpos( $text, '-->', $wsEnd + 4 );
329 if ( $c === false ) {
330 break;
332 $c = $c + 2 + strspn( $text, " \t", $c + 3 );
333 $comments[] = array( $wsEnd + 1, $c );
334 $wsEnd = $c;
337 // Eat the line if possible
338 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
339 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
340 // it's a possible beneficial b/c break.
341 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
342 && substr( $text, $wsEnd + 1, 1 ) == "\n"
344 // Remove leading whitespace from the end of the accumulator
345 // Sanity check first though
346 $wsLength = $i - $wsStart;
347 if ( $wsLength > 0
348 && $accum->lastNode instanceof PPNode_Hash_Text
349 && strspn( $accum->lastNode->value, " \t", -$wsLength ) === $wsLength
351 $accum->lastNode->value = substr( $accum->lastNode->value, 0, -$wsLength );
354 // Dump all but the last comment to the accumulator
355 foreach ( $comments as $j => $com ) {
356 $startPos = $com[0];
357 $endPos = $com[1] + 1;
358 if ( $j == ( count( $comments ) - 1 ) ) {
359 break;
361 $inner = substr( $text, $startPos, $endPos - $startPos );
362 $accum->addNodeWithText( 'comment', $inner );
365 // Do a line-start run next time to look for headings after the comment
366 $fakeLineStart = true;
367 } else {
368 // No line to eat, just take the comment itself
369 $startPos = $i;
370 $endPos += 2;
373 if ( $stack->top ) {
374 $part = $stack->top->getCurrentPart();
375 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
376 $part->visualEnd = $wsStart;
378 // Else comments abutting, no change in visual end
379 $part->commentEnd = $endPos;
381 $i = $endPos + 1;
382 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
383 $accum->addNodeWithText( 'comment', $inner );
385 continue;
387 $name = $matches[1];
388 $lowerName = strtolower( $name );
389 $attrStart = $i + strlen( $name ) + 1;
391 // Find end of tag
392 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
393 if ( $tagEndPos === false ) {
394 // Infinite backtrack
395 // Disable tag search to prevent worst-case O(N^2) performance
396 $noMoreGT = true;
397 $accum->addLiteral( '<' );
398 ++$i;
399 continue;
402 // Handle ignored tags
403 if ( in_array( $lowerName, $ignoredTags ) ) {
404 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i + 1 ) );
405 $i = $tagEndPos + 1;
406 continue;
409 $tagStartPos = $i;
410 if ( $text[$tagEndPos - 1] == '/' ) {
411 // Short end tag
412 $attrEnd = $tagEndPos - 1;
413 $inner = null;
414 $i = $tagEndPos + 1;
415 $close = null;
416 } else {
417 $attrEnd = $tagEndPos;
418 // Find closing tag
419 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
420 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 )
422 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
423 $i = $matches[0][1] + strlen( $matches[0][0] );
424 $close = $matches[0][0];
425 } else {
426 // No end tag -- let it run out to the end of the text.
427 $inner = substr( $text, $tagEndPos + 1 );
428 $i = $lengthText;
429 $close = null;
432 // <includeonly> and <noinclude> just become <ignore> tags
433 if ( in_array( $lowerName, $ignoredElements ) ) {
434 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
435 continue;
438 if ( $attrEnd <= $attrStart ) {
439 $attr = '';
440 } else {
441 // Note that the attr element contains the whitespace between name and attribute,
442 // this is necessary for precise reconstruction during pre-save transform.
443 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
446 $extNode = new PPNode_Hash_Tree( 'ext' );
447 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'name', $name ) );
448 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'attr', $attr ) );
449 if ( $inner !== null ) {
450 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'inner', $inner ) );
452 if ( $close !== null ) {
453 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'close', $close ) );
455 $accum->addNode( $extNode );
456 } elseif ( $found == 'line-start' ) {
457 // Is this the start of a heading?
458 // Line break belongs before the heading element in any case
459 if ( $fakeLineStart ) {
460 $fakeLineStart = false;
461 } else {
462 $accum->addLiteral( $curChar );
463 $i++;
466 $count = strspn( $text, '=', $i, 6 );
467 if ( $count == 1 && $findEquals ) {
468 // DWIM: This looks kind of like a name/value separator.
469 // Let's let the equals handler have it and break the potential
470 // heading. This is heuristic, but AFAICT the methods for
471 // completely correct disambiguation are very complex.
472 } elseif ( $count > 0 ) {
473 $piece = array(
474 'open' => "\n",
475 'close' => "\n",
476 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
477 'startPos' => $i,
478 'count' => $count );
479 $stack->push( $piece );
480 $accum =& $stack->getAccum();
481 extract( $stack->getFlags() );
482 $i += $count;
484 } elseif ( $found == 'line-end' ) {
485 $piece = $stack->top;
486 // A heading must be open, otherwise \n wouldn't have been in the search list
487 assert( '$piece->open == "\n"' );
488 $part = $piece->getCurrentPart();
489 // Search back through the input to see if it has a proper close.
490 // Do this using the reversed string since the other solutions
491 // (end anchor, etc.) are inefficient.
492 $wsLength = strspn( $revText, " \t", $lengthText - $i );
493 $searchStart = $i - $wsLength;
494 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
495 // Comment found at line end
496 // Search for equals signs before the comment
497 $searchStart = $part->visualEnd;
498 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
500 $count = $piece->count;
501 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
502 if ( $equalsLength > 0 ) {
503 if ( $searchStart - $equalsLength == $piece->startPos ) {
504 // This is just a single string of equals signs on its own line
505 // Replicate the doHeadings behavior /={count}(.+)={count}/
506 // First find out how many equals signs there really are (don't stop at 6)
507 $count = $equalsLength;
508 if ( $count < 3 ) {
509 $count = 0;
510 } else {
511 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
513 } else {
514 $count = min( $equalsLength, $count );
516 if ( $count > 0 ) {
517 // Normal match, output <h>
518 $element = new PPNode_Hash_Tree( 'possible-h' );
519 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
520 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
521 $element->lastChild->nextSibling = $accum->firstNode;
522 $element->lastChild = $accum->lastNode;
523 } else {
524 // Single equals sign on its own line, count=0
525 $element = $accum;
527 } else {
528 // No match, no <h>, just pass down the inner text
529 $element = $accum;
531 // Unwind the stack
532 $stack->pop();
533 $accum =& $stack->getAccum();
534 extract( $stack->getFlags() );
536 // Append the result to the enclosing accumulator
537 if ( $element instanceof PPNode ) {
538 $accum->addNode( $element );
539 } else {
540 $accum->addAccum( $element );
542 // Note that we do NOT increment the input pointer.
543 // This is because the closing linebreak could be the opening linebreak of
544 // another heading. Infinite loops are avoided because the next iteration MUST
545 // hit the heading open case above, which unconditionally increments the
546 // input pointer.
547 } elseif ( $found == 'open' ) {
548 # count opening brace characters
549 $count = strspn( $text, $curChar, $i );
551 # we need to add to stack only if opening brace count is enough for one of the rules
552 if ( $count >= $rule['min'] ) {
553 # Add it to the stack
554 $piece = array(
555 'open' => $curChar,
556 'close' => $rule['end'],
557 'count' => $count,
558 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
561 $stack->push( $piece );
562 $accum =& $stack->getAccum();
563 extract( $stack->getFlags() );
564 } else {
565 # Add literal brace(s)
566 $accum->addLiteral( str_repeat( $curChar, $count ) );
568 $i += $count;
569 } elseif ( $found == 'close' ) {
570 $piece = $stack->top;
571 # lets check if there are enough characters for closing brace
572 $maxCount = $piece->count;
573 $count = strspn( $text, $curChar, $i, $maxCount );
575 # check for maximum matching characters (if there are 5 closing
576 # characters, we will probably need only 3 - depending on the rules)
577 $rule = $rules[$piece->open];
578 if ( $count > $rule['max'] ) {
579 # The specified maximum exists in the callback array, unless the caller
580 # has made an error
581 $matchingCount = $rule['max'];
582 } else {
583 # Count is less than the maximum
584 # Skip any gaps in the callback array to find the true largest match
585 # Need to use array_key_exists not isset because the callback can be null
586 $matchingCount = $count;
587 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
588 --$matchingCount;
592 if ( $matchingCount <= 0 ) {
593 # No matching element found in callback array
594 # Output a literal closing brace and continue
595 $accum->addLiteral( str_repeat( $curChar, $count ) );
596 $i += $count;
597 continue;
599 $name = $rule['names'][$matchingCount];
600 if ( $name === null ) {
601 // No element, just literal text
602 $element = $piece->breakSyntax( $matchingCount );
603 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
604 } else {
605 # Create XML element
606 # Note: $parts is already XML, does not need to be encoded further
607 $parts = $piece->parts;
608 $titleAccum = $parts[0]->out;
609 unset( $parts[0] );
611 $element = new PPNode_Hash_Tree( $name );
613 # The invocation is at the start of the line if lineStart is set in
614 # the stack, and all opening brackets are used up.
615 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
616 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
618 $titleNode = new PPNode_Hash_Tree( 'title' );
619 $titleNode->firstChild = $titleAccum->firstNode;
620 $titleNode->lastChild = $titleAccum->lastNode;
621 $element->addChild( $titleNode );
622 $argIndex = 1;
623 foreach ( $parts as $part ) {
624 if ( isset( $part->eqpos ) ) {
625 // Find equals
626 $lastNode = false;
627 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
628 if ( $node === $part->eqpos ) {
629 break;
631 $lastNode = $node;
633 if ( !$node ) {
634 if ( $cacheable ) {
636 throw new MWException( __METHOD__ . ': eqpos not found' );
638 if ( $node->name !== 'equals' ) {
639 if ( $cacheable ) {
641 throw new MWException( __METHOD__ . ': eqpos is not equals' );
643 $equalsNode = $node;
645 // Construct name node
646 $nameNode = new PPNode_Hash_Tree( 'name' );
647 if ( $lastNode !== false ) {
648 $lastNode->nextSibling = false;
649 $nameNode->firstChild = $part->out->firstNode;
650 $nameNode->lastChild = $lastNode;
653 // Construct value node
654 $valueNode = new PPNode_Hash_Tree( 'value' );
655 if ( $equalsNode->nextSibling !== false ) {
656 $valueNode->firstChild = $equalsNode->nextSibling;
657 $valueNode->lastChild = $part->out->lastNode;
659 $partNode = new PPNode_Hash_Tree( 'part' );
660 $partNode->addChild( $nameNode );
661 $partNode->addChild( $equalsNode->firstChild );
662 $partNode->addChild( $valueNode );
663 $element->addChild( $partNode );
664 } else {
665 $partNode = new PPNode_Hash_Tree( 'part' );
666 $nameNode = new PPNode_Hash_Tree( 'name' );
667 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
668 $valueNode = new PPNode_Hash_Tree( 'value' );
669 $valueNode->firstChild = $part->out->firstNode;
670 $valueNode->lastChild = $part->out->lastNode;
671 $partNode->addChild( $nameNode );
672 $partNode->addChild( $valueNode );
673 $element->addChild( $partNode );
678 # Advance input pointer
679 $i += $matchingCount;
681 # Unwind the stack
682 $stack->pop();
683 $accum =& $stack->getAccum();
685 # Re-add the old stack element if it still has unmatched opening characters remaining
686 if ( $matchingCount < $piece->count ) {
687 $piece->parts = array( new PPDPart_Hash );
688 $piece->count -= $matchingCount;
689 # do we still qualify for any callback with remaining count?
690 $min = $rules[$piece->open]['min'];
691 if ( $piece->count >= $min ) {
692 $stack->push( $piece );
693 $accum =& $stack->getAccum();
694 } else {
695 $accum->addLiteral( str_repeat( $piece->open, $piece->count ) );
699 extract( $stack->getFlags() );
701 # Add XML element to the enclosing accumulator
702 if ( $element instanceof PPNode ) {
703 $accum->addNode( $element );
704 } else {
705 $accum->addAccum( $element );
707 } elseif ( $found == 'pipe' ) {
708 $findEquals = true; // shortcut for getFlags()
709 $stack->addPart();
710 $accum =& $stack->getAccum();
711 ++$i;
712 } elseif ( $found == 'equals' ) {
713 $findEquals = false; // shortcut for getFlags()
714 $accum->addNodeWithText( 'equals', '=' );
715 $stack->getCurrentPart()->eqpos = $accum->lastNode;
716 ++$i;
720 # Output any remaining unclosed brackets
721 foreach ( $stack->stack as $piece ) {
722 $stack->rootAccum->addAccum( $piece->breakSyntax() );
725 # Enable top-level headings
726 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
727 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
728 $node->name = 'h';
732 $rootNode = new PPNode_Hash_Tree( 'root' );
733 $rootNode->firstChild = $stack->rootAccum->firstNode;
734 $rootNode->lastChild = $stack->rootAccum->lastNode;
736 // Cache
737 if ( $cacheable ) {
738 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . serialize( $rootNode );
739 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
740 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
743 return $rootNode;
748 * Stack class to help Preprocessor::preprocessToObj()
749 * @ingroup Parser
750 * @codingStandardsIgnoreStart
752 class PPDStack_Hash extends PPDStack {
753 // @codingStandardsIgnoreEnd
755 public function __construct() {
756 $this->elementClass = 'PPDStackElement_Hash';
757 parent::__construct();
758 $this->rootAccum = new PPDAccum_Hash;
763 * @ingroup Parser
764 * @codingStandardsIgnoreStart
766 class PPDStackElement_Hash extends PPDStackElement {
767 // @codingStandardsIgnoreENd
769 public function __construct( $data = array() ) {
770 $this->partClass = 'PPDPart_Hash';
771 parent::__construct( $data );
775 * Get the accumulator that would result if the close is not found.
777 * @param int|bool $openingCount
778 * @return PPDAccum_Hash
780 public function breakSyntax( $openingCount = false ) {
781 if ( $this->open == "\n" ) {
782 $accum = $this->parts[0]->out;
783 } else {
784 if ( $openingCount === false ) {
785 $openingCount = $this->count;
787 $accum = new PPDAccum_Hash;
788 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
789 $first = true;
790 foreach ( $this->parts as $part ) {
791 if ( $first ) {
792 $first = false;
793 } else {
794 $accum->addLiteral( '|' );
796 $accum->addAccum( $part->out );
799 return $accum;
804 * @ingroup Parser
805 * @codingStandardsIgnoreStart
807 class PPDPart_Hash extends PPDPart {
808 // @codingStandardsIgnoreEnd
810 public function __construct( $out = '' ) {
811 $accum = new PPDAccum_Hash;
812 if ( $out !== '' ) {
813 $accum->addLiteral( $out );
815 parent::__construct( $accum );
820 * @ingroup Parser
821 * @codingStandardsIgnoreStart
823 class PPDAccum_Hash {
824 // @codingStandardsIgnoreEnd
826 public $firstNode, $lastNode;
828 public function __construct() {
829 $this->firstNode = $this->lastNode = false;
833 * Append a string literal
834 * @param string $s
836 public function addLiteral( $s ) {
837 if ( $this->lastNode === false ) {
838 $this->firstNode = $this->lastNode = new PPNode_Hash_Text( $s );
839 } elseif ( $this->lastNode instanceof PPNode_Hash_Text ) {
840 $this->lastNode->value .= $s;
841 } else {
842 $this->lastNode->nextSibling = new PPNode_Hash_Text( $s );
843 $this->lastNode = $this->lastNode->nextSibling;
848 * Append a PPNode
849 * @param PPNode $node
851 public function addNode( PPNode $node ) {
852 if ( $this->lastNode === false ) {
853 $this->firstNode = $this->lastNode = $node;
854 } else {
855 $this->lastNode->nextSibling = $node;
856 $this->lastNode = $node;
861 * Append a tree node with text contents
862 * @param string $name
863 * @param string $value
865 public function addNodeWithText( $name, $value ) {
866 $node = PPNode_Hash_Tree::newWithText( $name, $value );
867 $this->addNode( $node );
871 * Append a PPDAccum_Hash
872 * Takes over ownership of the nodes in the source argument. These nodes may
873 * subsequently be modified, especially nextSibling.
874 * @param PPDAccum_Hash $accum
876 public function addAccum( $accum ) {
877 if ( $accum->lastNode === false ) {
878 // nothing to add
879 } elseif ( $this->lastNode === false ) {
880 $this->firstNode = $accum->firstNode;
881 $this->lastNode = $accum->lastNode;
882 } else {
883 $this->lastNode->nextSibling = $accum->firstNode;
884 $this->lastNode = $accum->lastNode;
890 * An expansion frame, used as a context to expand the result of preprocessToObj()
891 * @ingroup Parser
892 * @codingStandardsIgnoreStart
894 class PPFrame_Hash implements PPFrame {
895 // @codingStandardsIgnoreEnd
898 * @var Parser
900 public $parser;
903 * @var Preprocessor
905 public $preprocessor;
908 * @var Title
910 public $title;
911 public $titleCache;
914 * Hashtable listing templates which are disallowed for expansion in this frame,
915 * having been encountered previously in parent frames.
917 public $loopCheckHash;
920 * Recursion depth of this frame, top = 0
921 * Note that this is NOT the same as expansion depth in expand()
923 public $depth;
925 private $volatile = false;
926 private $ttl = null;
929 * @var array
931 protected $childExpansionCache;
934 * Construct a new preprocessor frame.
935 * @param Preprocessor $preprocessor The parent preprocessor
937 public function __construct( $preprocessor ) {
938 $this->preprocessor = $preprocessor;
939 $this->parser = $preprocessor->parser;
940 $this->title = $this->parser->mTitle;
941 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
942 $this->loopCheckHash = array();
943 $this->depth = 0;
944 $this->childExpansionCache = array();
948 * Create a new child frame
949 * $args is optionally a multi-root PPNode or array containing the template arguments
951 * @param array|bool|PPNode_Hash_Array $args
952 * @param Title|bool $title
953 * @param int $indexOffset
954 * @throws MWException
955 * @return PPTemplateFrame_Hash
957 public function newChild( $args = false, $title = false, $indexOffset = 0 ) {
958 $namedArgs = array();
959 $numberedArgs = array();
960 if ( $title === false ) {
961 $title = $this->title;
963 if ( $args !== false ) {
964 if ( $args instanceof PPNode_Hash_Array ) {
965 $args = $args->value;
966 } elseif ( !is_array( $args ) ) {
967 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
969 foreach ( $args as $arg ) {
970 $bits = $arg->splitArg();
971 if ( $bits['index'] !== '' ) {
972 // Numbered parameter
973 $index = $bits['index'] - $indexOffset;
974 if ( isset( $namedArgs[$index] ) || isset( $numberedArgs[$index] ) ) {
975 $this->parser->addTrackingCategory( 'duplicate-args-category' );
977 $numberedArgs[$index] = $bits['value'];
978 unset( $namedArgs[$index] );
979 } else {
980 // Named parameter
981 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
982 if ( isset( $namedArgs[$name] ) || isset( $numberedArgs[$name] ) ) {
983 $this->parser->addTrackingCategory( 'duplicate-args-category' );
985 $namedArgs[$name] = $bits['value'];
986 unset( $numberedArgs[$name] );
990 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
994 * @throws MWException
995 * @param string|int $key
996 * @param string|PPNode $root
997 * @param int $flags
998 * @return string
1000 public function cachedExpand( $key, $root, $flags = 0 ) {
1001 // we don't have a parent, so we don't have a cache
1002 return $this->expand( $root, $flags );
1006 * @throws MWException
1007 * @param string|PPNode $root
1008 * @param int $flags
1009 * @return string
1011 public function expand( $root, $flags = 0 ) {
1012 static $expansionDepth = 0;
1013 if ( is_string( $root ) ) {
1014 return $root;
1017 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
1018 $this->parser->limitationWarn( 'node-count-exceeded',
1019 $this->parser->mPPNodeCount,
1020 $this->parser->mOptions->getMaxPPNodeCount()
1022 return '<span class="error">Node-count limit exceeded</span>';
1024 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
1025 $this->parser->limitationWarn( 'expansion-depth-exceeded',
1026 $expansionDepth,
1027 $this->parser->mOptions->getMaxPPExpandDepth()
1029 return '<span class="error">Expansion depth limit exceeded</span>';
1031 ++$expansionDepth;
1032 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
1033 $this->parser->mHighestExpansionDepth = $expansionDepth;
1036 $outStack = array( '', '' );
1037 $iteratorStack = array( false, $root );
1038 $indexStack = array( 0, 0 );
1040 while ( count( $iteratorStack ) > 1 ) {
1041 $level = count( $outStack ) - 1;
1042 $iteratorNode =& $iteratorStack[$level];
1043 $out =& $outStack[$level];
1044 $index =& $indexStack[$level];
1046 if ( is_array( $iteratorNode ) ) {
1047 if ( $index >= count( $iteratorNode ) ) {
1048 // All done with this iterator
1049 $iteratorStack[$level] = false;
1050 $contextNode = false;
1051 } else {
1052 $contextNode = $iteratorNode[$index];
1053 $index++;
1055 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
1056 if ( $index >= $iteratorNode->getLength() ) {
1057 // All done with this iterator
1058 $iteratorStack[$level] = false;
1059 $contextNode = false;
1060 } else {
1061 $contextNode = $iteratorNode->item( $index );
1062 $index++;
1064 } else {
1065 // Copy to $contextNode and then delete from iterator stack,
1066 // because this is not an iterator but we do have to execute it once
1067 $contextNode = $iteratorStack[$level];
1068 $iteratorStack[$level] = false;
1071 $newIterator = false;
1073 if ( $contextNode === false ) {
1074 // nothing to do
1075 } elseif ( is_string( $contextNode ) ) {
1076 $out .= $contextNode;
1077 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
1078 $newIterator = $contextNode;
1079 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
1080 // No output
1081 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
1082 $out .= $contextNode->value;
1083 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
1084 if ( $contextNode->name == 'template' ) {
1085 # Double-brace expansion
1086 $bits = $contextNode->splitTemplate();
1087 if ( $flags & PPFrame::NO_TEMPLATES ) {
1088 $newIterator = $this->virtualBracketedImplode(
1089 '{{', '|', '}}',
1090 $bits['title'],
1091 $bits['parts']
1093 } else {
1094 $ret = $this->parser->braceSubstitution( $bits, $this );
1095 if ( isset( $ret['object'] ) ) {
1096 $newIterator = $ret['object'];
1097 } else {
1098 $out .= $ret['text'];
1101 } elseif ( $contextNode->name == 'tplarg' ) {
1102 # Triple-brace expansion
1103 $bits = $contextNode->splitTemplate();
1104 if ( $flags & PPFrame::NO_ARGS ) {
1105 $newIterator = $this->virtualBracketedImplode(
1106 '{{{', '|', '}}}',
1107 $bits['title'],
1108 $bits['parts']
1110 } else {
1111 $ret = $this->parser->argSubstitution( $bits, $this );
1112 if ( isset( $ret['object'] ) ) {
1113 $newIterator = $ret['object'];
1114 } else {
1115 $out .= $ret['text'];
1118 } elseif ( $contextNode->name == 'comment' ) {
1119 # HTML-style comment
1120 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1121 if ( $this->parser->ot['html']
1122 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1123 || ( $flags & PPFrame::STRIP_COMMENTS )
1125 $out .= '';
1126 } elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1127 # Add a strip marker in PST mode so that pstPass2() can
1128 # run some old-fashioned regexes on the result.
1129 # Not in RECOVER_COMMENTS mode (extractSections) though.
1130 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1131 } else {
1132 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1133 $out .= $contextNode->firstChild->value;
1135 } elseif ( $contextNode->name == 'ignore' ) {
1136 # Output suppression used by <includeonly> etc.
1137 # OT_WIKI will only respect <ignore> in substed templates.
1138 # The other output types respect it unless NO_IGNORE is set.
1139 # extractSections() sets NO_IGNORE and so never respects it.
1140 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] )
1141 || ( $flags & PPFrame::NO_IGNORE )
1143 $out .= $contextNode->firstChild->value;
1144 } else {
1145 //$out .= '';
1147 } elseif ( $contextNode->name == 'ext' ) {
1148 # Extension tag
1149 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1150 if ( $flags & PPFrame::NO_TAGS ) {
1151 $s = '<' . $bits['name']->firstChild->value;
1152 if ( $bits['attr'] ) {
1153 $s .= $bits['attr']->firstChild->value;
1155 if ( $bits['inner'] ) {
1156 $s .= '>' . $bits['inner']->firstChild->value;
1157 if ( $bits['close'] ) {
1158 $s .= $bits['close']->firstChild->value;
1160 } else {
1161 $s .= '/>';
1163 $out .= $s;
1164 } else {
1165 $out .= $this->parser->extensionSubstitution( $bits, $this );
1167 } elseif ( $contextNode->name == 'h' ) {
1168 # Heading
1169 if ( $this->parser->ot['html'] ) {
1170 # Expand immediately and insert heading index marker
1171 $s = '';
1172 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1173 $s .= $this->expand( $node, $flags );
1176 $bits = $contextNode->splitHeading();
1177 $titleText = $this->title->getPrefixedDBkey();
1178 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1179 $serial = count( $this->parser->mHeadings ) - 1;
1180 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1181 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1182 $this->parser->mStripState->addGeneral( $marker, '' );
1183 $out .= $s;
1184 } else {
1185 # Expand in virtual stack
1186 $newIterator = $contextNode->getChildren();
1188 } else {
1189 # Generic recursive expansion
1190 $newIterator = $contextNode->getChildren();
1192 } else {
1193 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1196 if ( $newIterator !== false ) {
1197 $outStack[] = '';
1198 $iteratorStack[] = $newIterator;
1199 $indexStack[] = 0;
1200 } elseif ( $iteratorStack[$level] === false ) {
1201 // Return accumulated value to parent
1202 // With tail recursion
1203 while ( $iteratorStack[$level] === false && $level > 0 ) {
1204 $outStack[$level - 1] .= $out;
1205 array_pop( $outStack );
1206 array_pop( $iteratorStack );
1207 array_pop( $indexStack );
1208 $level--;
1212 --$expansionDepth;
1213 return $outStack[0];
1217 * @param string $sep
1218 * @param int $flags
1219 * @param string|PPNode $args,...
1220 * @return string
1222 public function implodeWithFlags( $sep, $flags /*, ... */ ) {
1223 $args = array_slice( func_get_args(), 2 );
1225 $first = true;
1226 $s = '';
1227 foreach ( $args as $root ) {
1228 if ( $root instanceof PPNode_Hash_Array ) {
1229 $root = $root->value;
1231 if ( !is_array( $root ) ) {
1232 $root = array( $root );
1234 foreach ( $root as $node ) {
1235 if ( $first ) {
1236 $first = false;
1237 } else {
1238 $s .= $sep;
1240 $s .= $this->expand( $node, $flags );
1243 return $s;
1247 * Implode with no flags specified
1248 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1249 * @param string $sep
1250 * @param string|PPNode $args,...
1251 * @return string
1253 public function implode( $sep /*, ... */ ) {
1254 $args = array_slice( func_get_args(), 1 );
1256 $first = true;
1257 $s = '';
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 $s .= $sep;
1271 $s .= $this->expand( $node );
1274 return $s;
1278 * Makes an object that, when expand()ed, will be the same as one obtained
1279 * with implode()
1281 * @param string $sep
1282 * @param string|PPNode $args,...
1283 * @return PPNode_Hash_Array
1285 public function virtualImplode( $sep /*, ... */ ) {
1286 $args = array_slice( func_get_args(), 1 );
1287 $out = array();
1288 $first = true;
1290 foreach ( $args as $root ) {
1291 if ( $root instanceof PPNode_Hash_Array ) {
1292 $root = $root->value;
1294 if ( !is_array( $root ) ) {
1295 $root = array( $root );
1297 foreach ( $root as $node ) {
1298 if ( $first ) {
1299 $first = false;
1300 } else {
1301 $out[] = $sep;
1303 $out[] = $node;
1306 return new PPNode_Hash_Array( $out );
1310 * Virtual implode with brackets
1312 * @param string $start
1313 * @param string $sep
1314 * @param string $end
1315 * @param string|PPNode $args,...
1316 * @return PPNode_Hash_Array
1318 public function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1319 $args = array_slice( func_get_args(), 3 );
1320 $out = array( $start );
1321 $first = true;
1323 foreach ( $args as $root ) {
1324 if ( $root instanceof PPNode_Hash_Array ) {
1325 $root = $root->value;
1327 if ( !is_array( $root ) ) {
1328 $root = array( $root );
1330 foreach ( $root as $node ) {
1331 if ( $first ) {
1332 $first = false;
1333 } else {
1334 $out[] = $sep;
1336 $out[] = $node;
1339 $out[] = $end;
1340 return new PPNode_Hash_Array( $out );
1343 public function __toString() {
1344 return 'frame{}';
1348 * @param bool $level
1349 * @return array|bool|string
1351 public function getPDBK( $level = false ) {
1352 if ( $level === false ) {
1353 return $this->title->getPrefixedDBkey();
1354 } else {
1355 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1360 * @return array
1362 public function getArguments() {
1363 return array();
1367 * @return array
1369 public function getNumberedArguments() {
1370 return array();
1374 * @return array
1376 public function getNamedArguments() {
1377 return array();
1381 * Returns true if there are no arguments in this frame
1383 * @return bool
1385 public function isEmpty() {
1386 return true;
1390 * @param string $name
1391 * @return bool
1393 public function getArgument( $name ) {
1394 return false;
1398 * Returns true if the infinite loop check is OK, false if a loop is detected
1400 * @param Title $title
1402 * @return bool
1404 public function loopCheck( $title ) {
1405 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1409 * Return true if the frame is a template frame
1411 * @return bool
1413 public function isTemplate() {
1414 return false;
1418 * Get a title of frame
1420 * @return Title
1422 public function getTitle() {
1423 return $this->title;
1427 * Set the volatile flag
1429 * @param bool $flag
1431 public function setVolatile( $flag = true ) {
1432 $this->volatile = $flag;
1436 * Get the volatile flag
1438 * @return bool
1440 public function isVolatile() {
1441 return $this->volatile;
1445 * Set the TTL
1447 * @param int $ttl
1449 public function setTTL( $ttl ) {
1450 if ( $ttl !== null && ( $this->ttl === null || $ttl < $this->ttl ) ) {
1451 $this->ttl = $ttl;
1456 * Get the TTL
1458 * @return int|null
1460 public function getTTL() {
1461 return $this->ttl;
1466 * Expansion frame with template arguments
1467 * @ingroup Parser
1468 * @codingStandardsIgnoreStart
1470 class PPTemplateFrame_Hash extends PPFrame_Hash {
1471 // @codingStandardsIgnoreEnd
1473 public $numberedArgs, $namedArgs, $parent;
1474 public $numberedExpansionCache, $namedExpansionCache;
1477 * @param Preprocessor $preprocessor
1478 * @param bool|PPFrame $parent
1479 * @param array $numberedArgs
1480 * @param array $namedArgs
1481 * @param bool|Title $title
1483 public function __construct( $preprocessor, $parent = false, $numberedArgs = array(),
1484 $namedArgs = array(), $title = false
1486 parent::__construct( $preprocessor );
1488 $this->parent = $parent;
1489 $this->numberedArgs = $numberedArgs;
1490 $this->namedArgs = $namedArgs;
1491 $this->title = $title;
1492 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1493 $this->titleCache = $parent->titleCache;
1494 $this->titleCache[] = $pdbk;
1495 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1496 if ( $pdbk !== false ) {
1497 $this->loopCheckHash[$pdbk] = true;
1499 $this->depth = $parent->depth + 1;
1500 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1503 public function __toString() {
1504 $s = 'tplframe{';
1505 $first = true;
1506 $args = $this->numberedArgs + $this->namedArgs;
1507 foreach ( $args as $name => $value ) {
1508 if ( $first ) {
1509 $first = false;
1510 } else {
1511 $s .= ', ';
1513 $s .= "\"$name\":\"" .
1514 str_replace( '"', '\\"', $value->__toString() ) . '"';
1516 $s .= '}';
1517 return $s;
1521 * @throws MWException
1522 * @param string|int $key
1523 * @param string|PPNode $root
1524 * @param int $flags
1525 * @return string
1527 public function cachedExpand( $key, $root, $flags = 0 ) {
1528 if ( isset( $this->parent->childExpansionCache[$key] ) ) {
1529 return $this->parent->childExpansionCache[$key];
1531 $retval = $this->expand( $root, $flags );
1532 if ( !$this->isVolatile() ) {
1533 $this->parent->childExpansionCache[$key] = $retval;
1535 return $retval;
1539 * Returns true if there are no arguments in this frame
1541 * @return bool
1543 public function isEmpty() {
1544 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1548 * @return array
1550 public function getArguments() {
1551 $arguments = array();
1552 foreach ( array_merge(
1553 array_keys( $this->numberedArgs ),
1554 array_keys( $this->namedArgs ) ) as $key ) {
1555 $arguments[$key] = $this->getArgument( $key );
1557 return $arguments;
1561 * @return array
1563 public function getNumberedArguments() {
1564 $arguments = array();
1565 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1566 $arguments[$key] = $this->getArgument( $key );
1568 return $arguments;
1572 * @return array
1574 public function getNamedArguments() {
1575 $arguments = array();
1576 foreach ( array_keys( $this->namedArgs ) as $key ) {
1577 $arguments[$key] = $this->getArgument( $key );
1579 return $arguments;
1583 * @param int $index
1584 * @return array|bool
1586 public function getNumberedArgument( $index ) {
1587 if ( !isset( $this->numberedArgs[$index] ) ) {
1588 return false;
1590 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1591 # No trimming for unnamed arguments
1592 $this->numberedExpansionCache[$index] = $this->parent->expand(
1593 $this->numberedArgs[$index],
1594 PPFrame::STRIP_COMMENTS
1597 return $this->numberedExpansionCache[$index];
1601 * @param string $name
1602 * @return bool
1604 public function getNamedArgument( $name ) {
1605 if ( !isset( $this->namedArgs[$name] ) ) {
1606 return false;
1608 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1609 # Trim named arguments post-expand, for backwards compatibility
1610 $this->namedExpansionCache[$name] = trim(
1611 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1613 return $this->namedExpansionCache[$name];
1617 * @param string $name
1618 * @return array|bool
1620 public function getArgument( $name ) {
1621 $text = $this->getNumberedArgument( $name );
1622 if ( $text === false ) {
1623 $text = $this->getNamedArgument( $name );
1625 return $text;
1629 * Return true if the frame is a template frame
1631 * @return bool
1633 public function isTemplate() {
1634 return true;
1637 public function setVolatile( $flag = true ) {
1638 parent::setVolatile( $flag );
1639 $this->parent->setVolatile( $flag );
1642 public function setTTL( $ttl ) {
1643 parent::setTTL( $ttl );
1644 $this->parent->setTTL( $ttl );
1649 * Expansion frame with custom arguments
1650 * @ingroup Parser
1651 * @codingStandardsIgnoreStart
1653 class PPCustomFrame_Hash extends PPFrame_Hash {
1654 // @codingStandardsIgnoreEnd
1656 public $args;
1658 public function __construct( $preprocessor, $args ) {
1659 parent::__construct( $preprocessor );
1660 $this->args = $args;
1663 public function __toString() {
1664 $s = 'cstmframe{';
1665 $first = true;
1666 foreach ( $this->args as $name => $value ) {
1667 if ( $first ) {
1668 $first = false;
1669 } else {
1670 $s .= ', ';
1672 $s .= "\"$name\":\"" .
1673 str_replace( '"', '\\"', $value->__toString() ) . '"';
1675 $s .= '}';
1676 return $s;
1680 * @return bool
1682 public function isEmpty() {
1683 return !count( $this->args );
1687 * @param int $index
1688 * @return bool
1690 public function getArgument( $index ) {
1691 if ( !isset( $this->args[$index] ) ) {
1692 return false;
1694 return $this->args[$index];
1697 public function getArguments() {
1698 return $this->args;
1703 * @ingroup Parser
1704 * @codingStandardsIgnoreStart
1706 class PPNode_Hash_Tree implements PPNode {
1707 // @codingStandardsIgnoreEnd
1709 public $name, $firstChild, $lastChild, $nextSibling;
1711 public function __construct( $name ) {
1712 $this->name = $name;
1713 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1716 public function __toString() {
1717 $inner = '';
1718 $attribs = '';
1719 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1720 if ( $node instanceof PPNode_Hash_Attr ) {
1721 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1722 } else {
1723 $inner .= $node->__toString();
1726 if ( $inner === '' ) {
1727 return "<{$this->name}$attribs/>";
1728 } else {
1729 return "<{$this->name}$attribs>$inner</{$this->name}>";
1734 * @param string $name
1735 * @param string $text
1736 * @return PPNode_Hash_Tree
1738 public static function newWithText( $name, $text ) {
1739 $obj = new self( $name );
1740 $obj->addChild( new PPNode_Hash_Text( $text ) );
1741 return $obj;
1744 public function addChild( $node ) {
1745 if ( $this->lastChild === false ) {
1746 $this->firstChild = $this->lastChild = $node;
1747 } else {
1748 $this->lastChild->nextSibling = $node;
1749 $this->lastChild = $node;
1754 * @return PPNode_Hash_Array
1756 public function getChildren() {
1757 $children = array();
1758 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1759 $children[] = $child;
1761 return new PPNode_Hash_Array( $children );
1764 public function getFirstChild() {
1765 return $this->firstChild;
1768 public function getNextSibling() {
1769 return $this->nextSibling;
1772 public function getChildrenOfType( $name ) {
1773 $children = array();
1774 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1775 if ( isset( $child->name ) && $child->name === $name ) {
1776 $children[] = $child;
1779 return $children;
1783 * @return bool
1785 public function getLength() {
1786 return false;
1790 * @param int $i
1791 * @return bool
1793 public function item( $i ) {
1794 return false;
1798 * @return string
1800 public function getName() {
1801 return $this->name;
1805 * Split a "<part>" node into an associative array containing:
1806 * - name PPNode name
1807 * - index String index
1808 * - value PPNode value
1810 * @throws MWException
1811 * @return array
1813 public function splitArg() {
1814 $bits = array();
1815 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1816 if ( !isset( $child->name ) ) {
1817 continue;
1819 if ( $child->name === 'name' ) {
1820 $bits['name'] = $child;
1821 if ( $child->firstChild instanceof PPNode_Hash_Attr
1822 && $child->firstChild->name === 'index'
1824 $bits['index'] = $child->firstChild->value;
1826 } elseif ( $child->name === 'value' ) {
1827 $bits['value'] = $child;
1831 if ( !isset( $bits['name'] ) ) {
1832 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1834 if ( !isset( $bits['index'] ) ) {
1835 $bits['index'] = '';
1837 return $bits;
1841 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1842 * All values in the resulting array are PPNodes. Inner and close are optional.
1844 * @throws MWException
1845 * @return array
1847 public function splitExt() {
1848 $bits = array();
1849 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1850 if ( !isset( $child->name ) ) {
1851 continue;
1853 if ( $child->name == 'name' ) {
1854 $bits['name'] = $child;
1855 } elseif ( $child->name == 'attr' ) {
1856 $bits['attr'] = $child;
1857 } elseif ( $child->name == 'inner' ) {
1858 $bits['inner'] = $child;
1859 } elseif ( $child->name == 'close' ) {
1860 $bits['close'] = $child;
1863 if ( !isset( $bits['name'] ) ) {
1864 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1866 return $bits;
1870 * Split an "<h>" node
1872 * @throws MWException
1873 * @return array
1875 public function splitHeading() {
1876 if ( $this->name !== 'h' ) {
1877 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1879 $bits = array();
1880 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1881 if ( !isset( $child->name ) ) {
1882 continue;
1884 if ( $child->name == 'i' ) {
1885 $bits['i'] = $child->value;
1886 } elseif ( $child->name == 'level' ) {
1887 $bits['level'] = $child->value;
1890 if ( !isset( $bits['i'] ) ) {
1891 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1893 return $bits;
1897 * Split a "<template>" or "<tplarg>" node
1899 * @throws MWException
1900 * @return array
1902 public function splitTemplate() {
1903 $parts = array();
1904 $bits = array( 'lineStart' => '' );
1905 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1906 if ( !isset( $child->name ) ) {
1907 continue;
1909 if ( $child->name == 'title' ) {
1910 $bits['title'] = $child;
1912 if ( $child->name == 'part' ) {
1913 $parts[] = $child;
1915 if ( $child->name == 'lineStart' ) {
1916 $bits['lineStart'] = '1';
1919 if ( !isset( $bits['title'] ) ) {
1920 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1922 $bits['parts'] = new PPNode_Hash_Array( $parts );
1923 return $bits;
1928 * @ingroup Parser
1929 * @codingStandardsIgnoreStart
1931 class PPNode_Hash_Text implements PPNode {
1932 // @codingStandardsIgnoreEnd
1934 public $value, $nextSibling;
1936 public function __construct( $value ) {
1937 if ( is_object( $value ) ) {
1938 throw new MWException( __CLASS__ . ' given object instead of string' );
1940 $this->value = $value;
1943 public function __toString() {
1944 return htmlspecialchars( $this->value );
1947 public function getNextSibling() {
1948 return $this->nextSibling;
1951 public function getChildren() {
1952 return false;
1955 public function getFirstChild() {
1956 return false;
1959 public function getChildrenOfType( $name ) {
1960 return false;
1963 public function getLength() {
1964 return false;
1967 public function item( $i ) {
1968 return false;
1971 public function getName() {
1972 return '#text';
1975 public function splitArg() {
1976 throw new MWException( __METHOD__ . ': not supported' );
1979 public function splitExt() {
1980 throw new MWException( __METHOD__ . ': not supported' );
1983 public function splitHeading() {
1984 throw new MWException( __METHOD__ . ': not supported' );
1989 * @ingroup Parser
1990 * @codingStandardsIgnoreStart
1992 class PPNode_Hash_Array implements PPNode {
1993 // @codingStandardsIgnoreEnd
1995 public $value, $nextSibling;
1997 public function __construct( $value ) {
1998 $this->value = $value;
2001 public function __toString() {
2002 return var_export( $this, true );
2005 public function getLength() {
2006 return count( $this->value );
2009 public function item( $i ) {
2010 return $this->value[$i];
2013 public function getName() {
2014 return '#nodelist';
2017 public function getNextSibling() {
2018 return $this->nextSibling;
2021 public function getChildren() {
2022 return false;
2025 public function getFirstChild() {
2026 return false;
2029 public function getChildrenOfType( $name ) {
2030 return false;
2033 public function splitArg() {
2034 throw new MWException( __METHOD__ . ': not supported' );
2037 public function splitExt() {
2038 throw new MWException( __METHOD__ . ': not supported' );
2041 public function splitHeading() {
2042 throw new MWException( __METHOD__ . ': not supported' );
2047 * @ingroup Parser
2048 * @codingStandardsIgnoreStart
2050 class PPNode_Hash_Attr implements PPNode {
2051 // @codingStandardsIgnoreEnd
2053 public $name, $value, $nextSibling;
2055 public function __construct( $name, $value ) {
2056 $this->name = $name;
2057 $this->value = $value;
2060 public function __toString() {
2061 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
2064 public function getName() {
2065 return $this->name;
2068 public function getNextSibling() {
2069 return $this->nextSibling;
2072 public function getChildren() {
2073 return false;
2076 public function getFirstChild() {
2077 return false;
2080 public function getChildrenOfType( $name ) {
2081 return false;
2084 public function getLength() {
2085 return false;
2088 public function item( $i ) {
2089 return false;
2092 public function splitArg() {
2093 throw new MWException( __METHOD__ . ': not supported' );
2096 public function splitExt() {
2097 throw new MWException( __METHOD__ . ': not supported' );
2100 public function splitHeading() {
2101 throw new MWException( __METHOD__ . ': not supported' );