Fixed spacing in db/debug/diff/externalstore/objectcache folder
[mediawiki.git] / includes / parser / Preprocessor_Hash.php
blob654a66e797e37b97abf68dfa0246fc82c7eabd72
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 class Preprocessor_Hash implements Preprocessor {
31 /**
32 * @var Parser
34 var $parser;
36 const CACHE_VERSION = 1;
38 function __construct( $parser ) {
39 $this->parser = $parser;
42 /**
43 * @return PPFrame_Hash
45 function newFrame() {
46 return new PPFrame_Hash( $this );
49 /**
50 * @param $args array
51 * @return PPCustomFrame_Hash
53 function newCustomFrame( $args ) {
54 return new PPCustomFrame_Hash( $this, $args );
57 /**
58 * @param $values array
59 * @return PPNode_Hash_Array
61 function newPartNodeArray( $values ) {
62 $list = array();
64 foreach ( $values as $k => $val ) {
65 $partNode = new PPNode_Hash_Tree( 'part' );
66 $nameNode = new PPNode_Hash_Tree( 'name' );
68 if ( is_int( $k ) ) {
69 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
70 $partNode->addChild( $nameNode );
71 } else {
72 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
73 $partNode->addChild( $nameNode );
74 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
77 $valueNode = new PPNode_Hash_Tree( 'value' );
78 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
79 $partNode->addChild( $valueNode );
81 $list[] = $partNode;
84 $node = new PPNode_Hash_Array( $list );
85 return $node;
88 /**
89 * Preprocess some wikitext and return the document tree.
90 * This is the ghost of Parser::replace_variables().
92 * @param string $text the text to parse
93 * @param $flags Integer: bitwise combination of:
94 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
95 * included. Default is to assume a direct page view.
97 * The generated DOM tree must depend only on the input text and the flags.
98 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
100 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
101 * change in the DOM tree for a given text, must be passed through the section identifier
102 * in the section edit link and thus back to extractSections().
104 * The output of this function is currently only cached in process memory, but a persistent
105 * cache may be implemented at a later date which takes further advantage of these strict
106 * dependency requirements.
108 * @throws MWException
109 * @return PPNode_Hash_Tree
111 function preprocessToObj( $text, $flags = 0 ) {
112 wfProfileIn( __METHOD__ );
114 // Check cache.
115 global $wgMemc, $wgPreprocessorCacheThreshold;
117 $cacheable = $wgPreprocessorCacheThreshold !== false && strlen( $text ) > $wgPreprocessorCacheThreshold;
118 if ( $cacheable ) {
119 wfProfileIn( __METHOD__ . '-cacheable' );
121 $cacheKey = wfMemcKey( 'preprocess-hash', md5( $text ), $flags );
122 $cacheValue = $wgMemc->get( $cacheKey );
123 if ( $cacheValue ) {
124 $version = substr( $cacheValue, 0, 8 );
125 if ( intval( $version ) == self::CACHE_VERSION ) {
126 $hash = unserialize( substr( $cacheValue, 8 ) );
127 // From the cache
128 wfDebugLog( "Preprocessor",
129 "Loaded preprocessor hash from memcached (key $cacheKey)" );
130 wfProfileOut( __METHOD__ . '-cacheable' );
131 wfProfileOut( __METHOD__ );
132 return $hash;
135 wfProfileIn( __METHOD__ . '-cache-miss' );
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 && strpos( $text, '</onlyinclude>' ) !== false ) {
165 $enableOnlyinclude = true;
167 } else {
168 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
169 $ignoredElements = array( 'includeonly' );
170 $xmlishElements[] = 'includeonly';
172 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
174 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
175 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
177 $stack = new PPDStack_Hash;
179 $searchBase = "[{<\n";
180 $revText = strrev( $text ); // For fast reverse searches
181 $lengthText = strlen( $text );
183 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
184 $accum =& $stack->getAccum(); # Current accumulator
185 $findEquals = false; # True to find equals signs in arguments
186 $findPipe = false; # True to take notice of pipe characters
187 $headingIndex = 1;
188 $inHeading = false; # True if $i is inside a possible heading
189 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
190 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
191 $fakeLineStart = true; # Do a line-start run without outputting an LF character
193 while ( true ) {
194 //$this->memCheck();
196 if ( $findOnlyinclude ) {
197 // Ignore all input up to the next <onlyinclude>
198 $startPos = strpos( $text, '<onlyinclude>', $i );
199 if ( $startPos === false ) {
200 // Ignored section runs to the end
201 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
202 break;
204 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
205 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
206 $i = $tagEndPos;
207 $findOnlyinclude = false;
210 if ( $fakeLineStart ) {
211 $found = 'line-start';
212 $curChar = '';
213 } else {
214 # Find next opening brace, closing brace or pipe
215 $search = $searchBase;
216 if ( $stack->top === false ) {
217 $currentClosing = '';
218 } else {
219 $currentClosing = $stack->top->close;
220 $search .= $currentClosing;
222 if ( $findPipe ) {
223 $search .= '|';
225 if ( $findEquals ) {
226 // First equals will be for the template
227 $search .= '=';
229 $rule = null;
230 # Output literal section, advance input counter
231 $literalLength = strcspn( $text, $search, $i );
232 if ( $literalLength > 0 ) {
233 $accum->addLiteral( substr( $text, $i, $literalLength ) );
234 $i += $literalLength;
236 if ( $i >= $lengthText ) {
237 if ( $currentClosing == "\n" ) {
238 // Do a past-the-end run to finish off the heading
239 $curChar = '';
240 $found = 'line-end';
241 } else {
242 # All done
243 break;
245 } else {
246 $curChar = $text[$i];
247 if ( $curChar == '|' ) {
248 $found = 'pipe';
249 } elseif ( $curChar == '=' ) {
250 $found = 'equals';
251 } elseif ( $curChar == '<' ) {
252 $found = 'angle';
253 } elseif ( $curChar == "\n" ) {
254 if ( $inHeading ) {
255 $found = 'line-end';
256 } else {
257 $found = 'line-start';
259 } elseif ( $curChar == $currentClosing ) {
260 $found = 'close';
261 } elseif ( isset( $rules[$curChar] ) ) {
262 $found = 'open';
263 $rule = $rules[$curChar];
264 } else {
265 # Some versions of PHP have a strcspn which stops on null characters
266 # Ignore and continue
267 ++$i;
268 continue;
273 if ( $found == 'angle' ) {
274 $matches = false;
275 // Handle </onlyinclude>
276 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
277 $findOnlyinclude = true;
278 continue;
281 // Determine element name
282 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
283 // Element name missing or not listed
284 $accum->addLiteral( '<' );
285 ++$i;
286 continue;
288 // Handle comments
289 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
290 // To avoid leaving blank lines, when a comment is both preceded
291 // and followed by a newline (ignoring spaces), trim leading and
292 // trailing spaces and one of the newlines.
294 // Find the end
295 $endPos = strpos( $text, '-->', $i + 4 );
296 if ( $endPos === false ) {
297 // Unclosed comment in input, runs to end
298 $inner = substr( $text, $i );
299 $accum->addNodeWithText( 'comment', $inner );
300 $i = $lengthText;
301 } else {
302 // Search backwards for leading whitespace
303 $wsStart = $i ? ( $i - strspn( $revText, ' ', $lengthText - $i ) ) : 0;
304 // Search forwards for trailing whitespace
305 // $wsEnd will be the position of the last space (or the '>' if there's none)
306 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
307 // Eat the line if possible
308 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
309 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
310 // it's a possible beneficial b/c break.
311 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
312 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
314 $startPos = $wsStart;
315 $endPos = $wsEnd + 1;
316 // Remove leading whitespace from the end of the accumulator
317 // Sanity check first though
318 $wsLength = $i - $wsStart;
319 if ( $wsLength > 0
320 && $accum->lastNode instanceof PPNode_Hash_Text
321 && substr( $accum->lastNode->value, -$wsLength ) === str_repeat( ' ', $wsLength ) )
323 $accum->lastNode->value = substr( $accum->lastNode->value, 0, -$wsLength );
325 // Do a line-start run next time to look for headings after the comment
326 $fakeLineStart = true;
327 } else {
328 // No line to eat, just take the comment itself
329 $startPos = $i;
330 $endPos += 2;
333 if ( $stack->top ) {
334 $part = $stack->top->getCurrentPart();
335 if ( !( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) ) {
336 $part->visualEnd = $wsStart;
338 // Else comments abutting, no change in visual end
339 $part->commentEnd = $endPos;
341 $i = $endPos + 1;
342 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
343 $accum->addNodeWithText( 'comment', $inner );
345 continue;
347 $name = $matches[1];
348 $lowerName = strtolower( $name );
349 $attrStart = $i + strlen( $name ) + 1;
351 // Find end of tag
352 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
353 if ( $tagEndPos === false ) {
354 // Infinite backtrack
355 // Disable tag search to prevent worst-case O(N^2) performance
356 $noMoreGT = true;
357 $accum->addLiteral( '<' );
358 ++$i;
359 continue;
362 // Handle ignored tags
363 if ( in_array( $lowerName, $ignoredTags ) ) {
364 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i + 1 ) );
365 $i = $tagEndPos + 1;
366 continue;
369 $tagStartPos = $i;
370 if ( $text[$tagEndPos - 1] == '/' ) {
371 // Short end tag
372 $attrEnd = $tagEndPos - 1;
373 $inner = null;
374 $i = $tagEndPos + 1;
375 $close = null;
376 } else {
377 $attrEnd = $tagEndPos;
378 // Find closing tag
379 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
380 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
382 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
383 $i = $matches[0][1] + strlen( $matches[0][0] );
384 $close = $matches[0][0];
385 } else {
386 // No end tag -- let it run out to the end of the text.
387 $inner = substr( $text, $tagEndPos + 1 );
388 $i = $lengthText;
389 $close = null;
392 // <includeonly> and <noinclude> just become <ignore> tags
393 if ( in_array( $lowerName, $ignoredElements ) ) {
394 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
395 continue;
398 if ( $attrEnd <= $attrStart ) {
399 $attr = '';
400 } else {
401 // Note that the attr element contains the whitespace between name and attribute,
402 // this is necessary for precise reconstruction during pre-save transform.
403 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
406 $extNode = new PPNode_Hash_Tree( 'ext' );
407 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'name', $name ) );
408 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'attr', $attr ) );
409 if ( $inner !== null ) {
410 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'inner', $inner ) );
412 if ( $close !== null ) {
413 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'close', $close ) );
415 $accum->addNode( $extNode );
418 elseif ( $found == 'line-start' ) {
419 // Is this the start of a heading?
420 // Line break belongs before the heading element in any case
421 if ( $fakeLineStart ) {
422 $fakeLineStart = false;
423 } else {
424 $accum->addLiteral( $curChar );
425 $i++;
428 $count = strspn( $text, '=', $i, 6 );
429 if ( $count == 1 && $findEquals ) {
430 // DWIM: This looks kind of like a name/value separator
431 // Let's let the equals handler have it and break the potential heading
432 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
433 } elseif ( $count > 0 ) {
434 $piece = array(
435 'open' => "\n",
436 'close' => "\n",
437 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
438 'startPos' => $i,
439 'count' => $count );
440 $stack->push( $piece );
441 $accum =& $stack->getAccum();
442 extract( $stack->getFlags() );
443 $i += $count;
445 } elseif ( $found == 'line-end' ) {
446 $piece = $stack->top;
447 // A heading must be open, otherwise \n wouldn't have been in the search list
448 assert( '$piece->open == "\n"' );
449 $part = $piece->getCurrentPart();
450 // Search back through the input to see if it has a proper close
451 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
452 $wsLength = strspn( $revText, " \t", $lengthText - $i );
453 $searchStart = $i - $wsLength;
454 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
455 // Comment found at line end
456 // Search for equals signs before the comment
457 $searchStart = $part->visualEnd;
458 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
460 $count = $piece->count;
461 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
462 if ( $equalsLength > 0 ) {
463 if ( $searchStart - $equalsLength == $piece->startPos ) {
464 // This is just a single string of equals signs on its own line
465 // Replicate the doHeadings behavior /={count}(.+)={count}/
466 // First find out how many equals signs there really are (don't stop at 6)
467 $count = $equalsLength;
468 if ( $count < 3 ) {
469 $count = 0;
470 } else {
471 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
473 } else {
474 $count = min( $equalsLength, $count );
476 if ( $count > 0 ) {
477 // Normal match, output <h>
478 $element = new PPNode_Hash_Tree( 'possible-h' );
479 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
480 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
481 $element->lastChild->nextSibling = $accum->firstNode;
482 $element->lastChild = $accum->lastNode;
483 } else {
484 // Single equals sign on its own line, count=0
485 $element = $accum;
487 } else {
488 // No match, no <h>, just pass down the inner text
489 $element = $accum;
491 // Unwind the stack
492 $stack->pop();
493 $accum =& $stack->getAccum();
494 extract( $stack->getFlags() );
496 // Append the result to the enclosing accumulator
497 if ( $element instanceof PPNode ) {
498 $accum->addNode( $element );
499 } else {
500 $accum->addAccum( $element );
502 // Note that we do NOT increment the input pointer.
503 // This is because the closing linebreak could be the opening linebreak of
504 // another heading. Infinite loops are avoided because the next iteration MUST
505 // hit the heading open case above, which unconditionally increments the
506 // input pointer.
507 } elseif ( $found == 'open' ) {
508 # count opening brace characters
509 $count = strspn( $text, $curChar, $i );
511 # we need to add to stack only if opening brace count is enough for one of the rules
512 if ( $count >= $rule['min'] ) {
513 # Add it to the stack
514 $piece = array(
515 'open' => $curChar,
516 'close' => $rule['end'],
517 'count' => $count,
518 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
521 $stack->push( $piece );
522 $accum =& $stack->getAccum();
523 extract( $stack->getFlags() );
524 } else {
525 # Add literal brace(s)
526 $accum->addLiteral( str_repeat( $curChar, $count ) );
528 $i += $count;
529 } elseif ( $found == 'close' ) {
530 $piece = $stack->top;
531 # lets check if there are enough characters for closing brace
532 $maxCount = $piece->count;
533 $count = strspn( $text, $curChar, $i, $maxCount );
535 # check for maximum matching characters (if there are 5 closing
536 # characters, we will probably need only 3 - depending on the rules)
537 $rule = $rules[$piece->open];
538 if ( $count > $rule['max'] ) {
539 # The specified maximum exists in the callback array, unless the caller
540 # has made an error
541 $matchingCount = $rule['max'];
542 } else {
543 # Count is less than the maximum
544 # Skip any gaps in the callback array to find the true largest match
545 # Need to use array_key_exists not isset because the callback can be null
546 $matchingCount = $count;
547 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
548 --$matchingCount;
552 if ( $matchingCount <= 0 ) {
553 # No matching element found in callback array
554 # Output a literal closing brace and continue
555 $accum->addLiteral( str_repeat( $curChar, $count ) );
556 $i += $count;
557 continue;
559 $name = $rule['names'][$matchingCount];
560 if ( $name === null ) {
561 // No element, just literal text
562 $element = $piece->breakSyntax( $matchingCount );
563 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
564 } else {
565 # Create XML element
566 # Note: $parts is already XML, does not need to be encoded further
567 $parts = $piece->parts;
568 $titleAccum = $parts[0]->out;
569 unset( $parts[0] );
571 $element = new PPNode_Hash_Tree( $name );
573 # The invocation is at the start of the line if lineStart is set in
574 # the stack, and all opening brackets are used up.
575 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
576 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
578 $titleNode = new PPNode_Hash_Tree( 'title' );
579 $titleNode->firstChild = $titleAccum->firstNode;
580 $titleNode->lastChild = $titleAccum->lastNode;
581 $element->addChild( $titleNode );
582 $argIndex = 1;
583 foreach ( $parts as $part ) {
584 if ( isset( $part->eqpos ) ) {
585 // Find equals
586 $lastNode = false;
587 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
588 if ( $node === $part->eqpos ) {
589 break;
591 $lastNode = $node;
593 if ( !$node ) {
594 if ( $cacheable ) {
595 wfProfileOut( __METHOD__ . '-cache-miss' );
596 wfProfileOut( __METHOD__ . '-cacheable' );
598 wfProfileOut( __METHOD__ );
599 throw new MWException( __METHOD__ . ': eqpos not found' );
601 if ( $node->name !== 'equals' ) {
602 if ( $cacheable ) {
603 wfProfileOut( __METHOD__ . '-cache-miss' );
604 wfProfileOut( __METHOD__ . '-cacheable' );
606 wfProfileOut( __METHOD__ );
607 throw new MWException( __METHOD__ . ': eqpos is not equals' );
609 $equalsNode = $node;
611 // Construct name node
612 $nameNode = new PPNode_Hash_Tree( 'name' );
613 if ( $lastNode !== false ) {
614 $lastNode->nextSibling = false;
615 $nameNode->firstChild = $part->out->firstNode;
616 $nameNode->lastChild = $lastNode;
619 // Construct value node
620 $valueNode = new PPNode_Hash_Tree( 'value' );
621 if ( $equalsNode->nextSibling !== false ) {
622 $valueNode->firstChild = $equalsNode->nextSibling;
623 $valueNode->lastChild = $part->out->lastNode;
625 $partNode = new PPNode_Hash_Tree( 'part' );
626 $partNode->addChild( $nameNode );
627 $partNode->addChild( $equalsNode->firstChild );
628 $partNode->addChild( $valueNode );
629 $element->addChild( $partNode );
630 } else {
631 $partNode = new PPNode_Hash_Tree( 'part' );
632 $nameNode = new PPNode_Hash_Tree( 'name' );
633 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
634 $valueNode = new PPNode_Hash_Tree( 'value' );
635 $valueNode->firstChild = $part->out->firstNode;
636 $valueNode->lastChild = $part->out->lastNode;
637 $partNode->addChild( $nameNode );
638 $partNode->addChild( $valueNode );
639 $element->addChild( $partNode );
644 # Advance input pointer
645 $i += $matchingCount;
647 # Unwind the stack
648 $stack->pop();
649 $accum =& $stack->getAccum();
651 # Re-add the old stack element if it still has unmatched opening characters remaining
652 if ( $matchingCount < $piece->count ) {
653 $piece->parts = array( new PPDPart_Hash );
654 $piece->count -= $matchingCount;
655 # do we still qualify for any callback with remaining count?
656 $min = $rules[$piece->open]['min'];
657 if ( $piece->count >= $min ) {
658 $stack->push( $piece );
659 $accum =& $stack->getAccum();
660 } else {
661 $accum->addLiteral( str_repeat( $piece->open, $piece->count ) );
665 extract( $stack->getFlags() );
667 # Add XML element to the enclosing accumulator
668 if ( $element instanceof PPNode ) {
669 $accum->addNode( $element );
670 } else {
671 $accum->addAccum( $element );
673 } elseif ( $found == 'pipe' ) {
674 $findEquals = true; // shortcut for getFlags()
675 $stack->addPart();
676 $accum =& $stack->getAccum();
677 ++$i;
678 } elseif ( $found == 'equals' ) {
679 $findEquals = false; // shortcut for getFlags()
680 $accum->addNodeWithText( 'equals', '=' );
681 $stack->getCurrentPart()->eqpos = $accum->lastNode;
682 ++$i;
686 # Output any remaining unclosed brackets
687 foreach ( $stack->stack as $piece ) {
688 $stack->rootAccum->addAccum( $piece->breakSyntax() );
691 # Enable top-level headings
692 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
693 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
694 $node->name = 'h';
698 $rootNode = new PPNode_Hash_Tree( 'root' );
699 $rootNode->firstChild = $stack->rootAccum->firstNode;
700 $rootNode->lastChild = $stack->rootAccum->lastNode;
702 // Cache
703 if ( $cacheable ) {
704 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . serialize( $rootNode );
705 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
706 wfProfileOut( __METHOD__ . '-cache-miss' );
707 wfProfileOut( __METHOD__ . '-cacheable' );
708 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
711 wfProfileOut( __METHOD__ );
712 return $rootNode;
717 * Stack class to help Preprocessor::preprocessToObj()
718 * @ingroup Parser
720 class PPDStack_Hash extends PPDStack {
721 function __construct() {
722 $this->elementClass = 'PPDStackElement_Hash';
723 parent::__construct();
724 $this->rootAccum = new PPDAccum_Hash;
729 * @ingroup Parser
731 class PPDStackElement_Hash extends PPDStackElement {
732 function __construct( $data = array() ) {
733 $this->partClass = 'PPDPart_Hash';
734 parent::__construct( $data );
738 * Get the accumulator that would result if the close is not found.
740 * @return PPDAccum_Hash
742 function breakSyntax( $openingCount = false ) {
743 if ( $this->open == "\n" ) {
744 $accum = $this->parts[0]->out;
745 } else {
746 if ( $openingCount === false ) {
747 $openingCount = $this->count;
749 $accum = new PPDAccum_Hash;
750 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
751 $first = true;
752 foreach ( $this->parts as $part ) {
753 if ( $first ) {
754 $first = false;
755 } else {
756 $accum->addLiteral( '|' );
758 $accum->addAccum( $part->out );
761 return $accum;
766 * @ingroup Parser
768 class PPDPart_Hash extends PPDPart {
769 function __construct( $out = '' ) {
770 $accum = new PPDAccum_Hash;
771 if ( $out !== '' ) {
772 $accum->addLiteral( $out );
774 parent::__construct( $accum );
779 * @ingroup Parser
781 class PPDAccum_Hash {
782 var $firstNode, $lastNode;
784 function __construct() {
785 $this->firstNode = $this->lastNode = false;
789 * Append a string literal
791 function addLiteral( $s ) {
792 if ( $this->lastNode === false ) {
793 $this->firstNode = $this->lastNode = new PPNode_Hash_Text( $s );
794 } elseif ( $this->lastNode instanceof PPNode_Hash_Text ) {
795 $this->lastNode->value .= $s;
796 } else {
797 $this->lastNode->nextSibling = new PPNode_Hash_Text( $s );
798 $this->lastNode = $this->lastNode->nextSibling;
803 * Append a PPNode
805 function addNode( PPNode $node ) {
806 if ( $this->lastNode === false ) {
807 $this->firstNode = $this->lastNode = $node;
808 } else {
809 $this->lastNode->nextSibling = $node;
810 $this->lastNode = $node;
815 * Append a tree node with text contents
817 function addNodeWithText( $name, $value ) {
818 $node = PPNode_Hash_Tree::newWithText( $name, $value );
819 $this->addNode( $node );
823 * Append a PPAccum_Hash
824 * Takes over ownership of the nodes in the source argument. These nodes may
825 * subsequently be modified, especially nextSibling.
827 function addAccum( $accum ) {
828 if ( $accum->lastNode === false ) {
829 // nothing to add
830 } elseif ( $this->lastNode === false ) {
831 $this->firstNode = $accum->firstNode;
832 $this->lastNode = $accum->lastNode;
833 } else {
834 $this->lastNode->nextSibling = $accum->firstNode;
835 $this->lastNode = $accum->lastNode;
841 * An expansion frame, used as a context to expand the result of preprocessToObj()
842 * @ingroup Parser
844 class PPFrame_Hash implements PPFrame {
847 * @var Parser
849 var $parser;
852 * @var Preprocessor
854 var $preprocessor;
857 * @var Title
859 var $title;
860 var $titleCache;
863 * Hashtable listing templates which are disallowed for expansion in this frame,
864 * having been encountered previously in parent frames.
866 var $loopCheckHash;
869 * Recursion depth of this frame, top = 0
870 * Note that this is NOT the same as expansion depth in expand()
872 var $depth;
875 * Construct a new preprocessor frame.
876 * @param $preprocessor Preprocessor: the parent preprocessor
878 function __construct( $preprocessor ) {
879 $this->preprocessor = $preprocessor;
880 $this->parser = $preprocessor->parser;
881 $this->title = $this->parser->mTitle;
882 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
883 $this->loopCheckHash = array();
884 $this->depth = 0;
888 * Create a new child frame
889 * $args is optionally a multi-root PPNode or array containing the template arguments
891 * @param array|bool|\PPNode_Hash_Array $args PPNode_Hash_Array|array
892 * @param $title Title|bool
894 * @param int $indexOffset
895 * @throws MWException
896 * @return PPTemplateFrame_Hash
898 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
899 $namedArgs = array();
900 $numberedArgs = array();
901 if ( $title === false ) {
902 $title = $this->title;
904 if ( $args !== false ) {
905 if ( $args instanceof PPNode_Hash_Array ) {
906 $args = $args->value;
907 } elseif ( !is_array( $args ) ) {
908 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
910 foreach ( $args as $arg ) {
911 $bits = $arg->splitArg();
912 if ( $bits['index'] !== '' ) {
913 // Numbered parameter
914 $index = $bits['index'] - $indexOffset;
915 $numberedArgs[$index] = $bits['value'];
916 unset( $namedArgs[$index] );
917 } else {
918 // Named parameter
919 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
920 $namedArgs[$name] = $bits['value'];
921 unset( $numberedArgs[$name] );
925 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
929 * @throws MWException
930 * @param $root
931 * @param $flags int
932 * @return string
934 function expand( $root, $flags = 0 ) {
935 static $expansionDepth = 0;
936 if ( is_string( $root ) ) {
937 return $root;
940 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
941 $this->parser->limitationWarn( 'node-count-exceeded',
942 $this->parser->mPPNodeCount,
943 $this->parser->mOptions->getMaxPPNodeCount()
945 return '<span class="error">Node-count limit exceeded</span>';
947 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
948 $this->parser->limitationWarn( 'expansion-depth-exceeded',
949 $expansionDepth,
950 $this->parser->mOptions->getMaxPPExpandDepth()
952 return '<span class="error">Expansion depth limit exceeded</span>';
954 ++$expansionDepth;
955 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
956 $this->parser->mHighestExpansionDepth = $expansionDepth;
959 $outStack = array( '', '' );
960 $iteratorStack = array( false, $root );
961 $indexStack = array( 0, 0 );
963 while ( count( $iteratorStack ) > 1 ) {
964 $level = count( $outStack ) - 1;
965 $iteratorNode =& $iteratorStack[$level];
966 $out =& $outStack[$level];
967 $index =& $indexStack[$level];
969 if ( is_array( $iteratorNode ) ) {
970 if ( $index >= count( $iteratorNode ) ) {
971 // All done with this iterator
972 $iteratorStack[$level] = false;
973 $contextNode = false;
974 } else {
975 $contextNode = $iteratorNode[$index];
976 $index++;
978 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
979 if ( $index >= $iteratorNode->getLength() ) {
980 // All done with this iterator
981 $iteratorStack[$level] = false;
982 $contextNode = false;
983 } else {
984 $contextNode = $iteratorNode->item( $index );
985 $index++;
987 } else {
988 // Copy to $contextNode and then delete from iterator stack,
989 // because this is not an iterator but we do have to execute it once
990 $contextNode = $iteratorStack[$level];
991 $iteratorStack[$level] = false;
994 $newIterator = false;
996 if ( $contextNode === false ) {
997 // nothing to do
998 } elseif ( is_string( $contextNode ) ) {
999 $out .= $contextNode;
1000 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
1001 $newIterator = $contextNode;
1002 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
1003 // No output
1004 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
1005 $out .= $contextNode->value;
1006 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
1007 if ( $contextNode->name == 'template' ) {
1008 # Double-brace expansion
1009 $bits = $contextNode->splitTemplate();
1010 if ( $flags & PPFrame::NO_TEMPLATES ) {
1011 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1012 } else {
1013 $ret = $this->parser->braceSubstitution( $bits, $this );
1014 if ( isset( $ret['object'] ) ) {
1015 $newIterator = $ret['object'];
1016 } else {
1017 $out .= $ret['text'];
1020 } elseif ( $contextNode->name == 'tplarg' ) {
1021 # Triple-brace expansion
1022 $bits = $contextNode->splitTemplate();
1023 if ( $flags & PPFrame::NO_ARGS ) {
1024 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1025 } else {
1026 $ret = $this->parser->argSubstitution( $bits, $this );
1027 if ( isset( $ret['object'] ) ) {
1028 $newIterator = $ret['object'];
1029 } else {
1030 $out .= $ret['text'];
1033 } elseif ( $contextNode->name == 'comment' ) {
1034 # HTML-style comment
1035 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1036 if ( $this->parser->ot['html']
1037 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1038 || ( $flags & PPFrame::STRIP_COMMENTS ) )
1040 $out .= '';
1042 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1043 # Not in RECOVER_COMMENTS mode (extractSections) though
1044 elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1045 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1047 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1048 else {
1049 $out .= $contextNode->firstChild->value;
1051 } elseif ( $contextNode->name == 'ignore' ) {
1052 # Output suppression used by <includeonly> etc.
1053 # OT_WIKI will only respect <ignore> in substed templates.
1054 # The other output types respect it unless NO_IGNORE is set.
1055 # extractSections() sets NO_IGNORE and so never respects it.
1056 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1057 $out .= $contextNode->firstChild->value;
1058 } else {
1059 //$out .= '';
1061 } elseif ( $contextNode->name == 'ext' ) {
1062 # Extension tag
1063 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1064 $out .= $this->parser->extensionSubstitution( $bits, $this );
1065 } elseif ( $contextNode->name == 'h' ) {
1066 # Heading
1067 if ( $this->parser->ot['html'] ) {
1068 # Expand immediately and insert heading index marker
1069 $s = '';
1070 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1071 $s .= $this->expand( $node, $flags );
1074 $bits = $contextNode->splitHeading();
1075 $titleText = $this->title->getPrefixedDBkey();
1076 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1077 $serial = count( $this->parser->mHeadings ) - 1;
1078 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1079 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1080 $this->parser->mStripState->addGeneral( $marker, '' );
1081 $out .= $s;
1082 } else {
1083 # Expand in virtual stack
1084 $newIterator = $contextNode->getChildren();
1086 } else {
1087 # Generic recursive expansion
1088 $newIterator = $contextNode->getChildren();
1090 } else {
1091 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1094 if ( $newIterator !== false ) {
1095 $outStack[] = '';
1096 $iteratorStack[] = $newIterator;
1097 $indexStack[] = 0;
1098 } elseif ( $iteratorStack[$level] === false ) {
1099 // Return accumulated value to parent
1100 // With tail recursion
1101 while ( $iteratorStack[$level] === false && $level > 0 ) {
1102 $outStack[$level - 1] .= $out;
1103 array_pop( $outStack );
1104 array_pop( $iteratorStack );
1105 array_pop( $indexStack );
1106 $level--;
1110 --$expansionDepth;
1111 return $outStack[0];
1115 * @param $sep
1116 * @param $flags
1117 * @return string
1119 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1120 $args = array_slice( func_get_args(), 2 );
1122 $first = true;
1123 $s = '';
1124 foreach ( $args as $root ) {
1125 if ( $root instanceof PPNode_Hash_Array ) {
1126 $root = $root->value;
1128 if ( !is_array( $root ) ) {
1129 $root = array( $root );
1131 foreach ( $root as $node ) {
1132 if ( $first ) {
1133 $first = false;
1134 } else {
1135 $s .= $sep;
1137 $s .= $this->expand( $node, $flags );
1140 return $s;
1144 * Implode with no flags specified
1145 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1146 * @return string
1148 function implode( $sep /*, ... */ ) {
1149 $args = array_slice( func_get_args(), 1 );
1151 $first = true;
1152 $s = '';
1153 foreach ( $args as $root ) {
1154 if ( $root instanceof PPNode_Hash_Array ) {
1155 $root = $root->value;
1157 if ( !is_array( $root ) ) {
1158 $root = array( $root );
1160 foreach ( $root as $node ) {
1161 if ( $first ) {
1162 $first = false;
1163 } else {
1164 $s .= $sep;
1166 $s .= $this->expand( $node );
1169 return $s;
1173 * Makes an object that, when expand()ed, will be the same as one obtained
1174 * with implode()
1176 * @return PPNode_Hash_Array
1178 function virtualImplode( $sep /*, ... */ ) {
1179 $args = array_slice( func_get_args(), 1 );
1180 $out = array();
1181 $first = true;
1183 foreach ( $args as $root ) {
1184 if ( $root instanceof PPNode_Hash_Array ) {
1185 $root = $root->value;
1187 if ( !is_array( $root ) ) {
1188 $root = array( $root );
1190 foreach ( $root as $node ) {
1191 if ( $first ) {
1192 $first = false;
1193 } else {
1194 $out[] = $sep;
1196 $out[] = $node;
1199 return new PPNode_Hash_Array( $out );
1203 * Virtual implode with brackets
1205 * @return PPNode_Hash_Array
1207 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1208 $args = array_slice( func_get_args(), 3 );
1209 $out = array( $start );
1210 $first = true;
1212 foreach ( $args as $root ) {
1213 if ( $root instanceof PPNode_Hash_Array ) {
1214 $root = $root->value;
1216 if ( !is_array( $root ) ) {
1217 $root = array( $root );
1219 foreach ( $root as $node ) {
1220 if ( $first ) {
1221 $first = false;
1222 } else {
1223 $out[] = $sep;
1225 $out[] = $node;
1228 $out[] = $end;
1229 return new PPNode_Hash_Array( $out );
1232 function __toString() {
1233 return 'frame{}';
1237 * @param $level bool
1238 * @return array|bool|String
1240 function getPDBK( $level = false ) {
1241 if ( $level === false ) {
1242 return $this->title->getPrefixedDBkey();
1243 } else {
1244 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1249 * @return array
1251 function getArguments() {
1252 return array();
1256 * @return array
1258 function getNumberedArguments() {
1259 return array();
1263 * @return array
1265 function getNamedArguments() {
1266 return array();
1270 * Returns true if there are no arguments in this frame
1272 * @return bool
1274 function isEmpty() {
1275 return true;
1279 * @param $name
1280 * @return bool
1282 function getArgument( $name ) {
1283 return false;
1287 * Returns true if the infinite loop check is OK, false if a loop is detected
1289 * @param $title Title
1291 * @return bool
1293 function loopCheck( $title ) {
1294 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1298 * Return true if the frame is a template frame
1300 * @return bool
1302 function isTemplate() {
1303 return false;
1307 * Get a title of frame
1309 * @return Title
1311 function getTitle() {
1312 return $this->title;
1317 * Expansion frame with template arguments
1318 * @ingroup Parser
1320 class PPTemplateFrame_Hash extends PPFrame_Hash {
1321 var $numberedArgs, $namedArgs, $parent;
1322 var $numberedExpansionCache, $namedExpansionCache;
1325 * @param $preprocessor
1326 * @param $parent
1327 * @param $numberedArgs array
1328 * @param $namedArgs array
1329 * @param $title Title
1331 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1332 parent::__construct( $preprocessor );
1334 $this->parent = $parent;
1335 $this->numberedArgs = $numberedArgs;
1336 $this->namedArgs = $namedArgs;
1337 $this->title = $title;
1338 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1339 $this->titleCache = $parent->titleCache;
1340 $this->titleCache[] = $pdbk;
1341 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1342 if ( $pdbk !== false ) {
1343 $this->loopCheckHash[$pdbk] = true;
1345 $this->depth = $parent->depth + 1;
1346 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1349 function __toString() {
1350 $s = 'tplframe{';
1351 $first = true;
1352 $args = $this->numberedArgs + $this->namedArgs;
1353 foreach ( $args as $name => $value ) {
1354 if ( $first ) {
1355 $first = false;
1356 } else {
1357 $s .= ', ';
1359 $s .= "\"$name\":\"" .
1360 str_replace( '"', '\\"', $value->__toString() ) . '"';
1362 $s .= '}';
1363 return $s;
1366 * Returns true if there are no arguments in this frame
1368 * @return bool
1370 function isEmpty() {
1371 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1375 * @return array
1377 function getArguments() {
1378 $arguments = array();
1379 foreach ( array_merge(
1380 array_keys( $this->numberedArgs ),
1381 array_keys( $this->namedArgs ) ) as $key ) {
1382 $arguments[$key] = $this->getArgument( $key );
1384 return $arguments;
1388 * @return array
1390 function getNumberedArguments() {
1391 $arguments = array();
1392 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1393 $arguments[$key] = $this->getArgument( $key );
1395 return $arguments;
1399 * @return array
1401 function getNamedArguments() {
1402 $arguments = array();
1403 foreach ( array_keys( $this->namedArgs ) as $key ) {
1404 $arguments[$key] = $this->getArgument( $key );
1406 return $arguments;
1410 * @param $index
1411 * @return array|bool
1413 function getNumberedArgument( $index ) {
1414 if ( !isset( $this->numberedArgs[$index] ) ) {
1415 return false;
1417 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1418 # No trimming for unnamed arguments
1419 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1421 return $this->numberedExpansionCache[$index];
1425 * @param $name
1426 * @return bool
1428 function getNamedArgument( $name ) {
1429 if ( !isset( $this->namedArgs[$name] ) ) {
1430 return false;
1432 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1433 # Trim named arguments post-expand, for backwards compatibility
1434 $this->namedExpansionCache[$name] = trim(
1435 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1437 return $this->namedExpansionCache[$name];
1441 * @param $name
1442 * @return array|bool
1444 function getArgument( $name ) {
1445 $text = $this->getNumberedArgument( $name );
1446 if ( $text === false ) {
1447 $text = $this->getNamedArgument( $name );
1449 return $text;
1453 * Return true if the frame is a template frame
1455 * @return bool
1457 function isTemplate() {
1458 return true;
1463 * Expansion frame with custom arguments
1464 * @ingroup Parser
1466 class PPCustomFrame_Hash extends PPFrame_Hash {
1467 var $args;
1469 function __construct( $preprocessor, $args ) {
1470 parent::__construct( $preprocessor );
1471 $this->args = $args;
1474 function __toString() {
1475 $s = 'cstmframe{';
1476 $first = true;
1477 foreach ( $this->args as $name => $value ) {
1478 if ( $first ) {
1479 $first = false;
1480 } else {
1481 $s .= ', ';
1483 $s .= "\"$name\":\"" .
1484 str_replace( '"', '\\"', $value->__toString() ) . '"';
1486 $s .= '}';
1487 return $s;
1491 * @return bool
1493 function isEmpty() {
1494 return !count( $this->args );
1498 * @param $index
1499 * @return bool
1501 function getArgument( $index ) {
1502 if ( !isset( $this->args[$index] ) ) {
1503 return false;
1505 return $this->args[$index];
1508 function getArguments() {
1509 return $this->args;
1514 * @ingroup Parser
1516 class PPNode_Hash_Tree implements PPNode {
1517 var $name, $firstChild, $lastChild, $nextSibling;
1519 function __construct( $name ) {
1520 $this->name = $name;
1521 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1524 function __toString() {
1525 $inner = '';
1526 $attribs = '';
1527 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1528 if ( $node instanceof PPNode_Hash_Attr ) {
1529 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1530 } else {
1531 $inner .= $node->__toString();
1534 if ( $inner === '' ) {
1535 return "<{$this->name}$attribs/>";
1536 } else {
1537 return "<{$this->name}$attribs>$inner</{$this->name}>";
1542 * @param $name
1543 * @param $text
1544 * @return PPNode_Hash_Tree
1546 static function newWithText( $name, $text ) {
1547 $obj = new self( $name );
1548 $obj->addChild( new PPNode_Hash_Text( $text ) );
1549 return $obj;
1552 function addChild( $node ) {
1553 if ( $this->lastChild === false ) {
1554 $this->firstChild = $this->lastChild = $node;
1555 } else {
1556 $this->lastChild->nextSibling = $node;
1557 $this->lastChild = $node;
1562 * @return PPNode_Hash_Array
1564 function getChildren() {
1565 $children = array();
1566 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1567 $children[] = $child;
1569 return new PPNode_Hash_Array( $children );
1572 function getFirstChild() {
1573 return $this->firstChild;
1576 function getNextSibling() {
1577 return $this->nextSibling;
1580 function getChildrenOfType( $name ) {
1581 $children = array();
1582 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1583 if ( isset( $child->name ) && $child->name === $name ) {
1584 $children[] = $child;
1587 return $children;
1591 * @return bool
1593 function getLength() {
1594 return false;
1598 * @param $i
1599 * @return bool
1601 function item( $i ) {
1602 return false;
1606 * @return string
1608 function getName() {
1609 return $this->name;
1613 * Split a "<part>" node into an associative array containing:
1614 * - name PPNode name
1615 * - index String index
1616 * - value PPNode value
1618 * @throws MWException
1619 * @return array
1621 function splitArg() {
1622 $bits = array();
1623 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1624 if ( !isset( $child->name ) ) {
1625 continue;
1627 if ( $child->name === 'name' ) {
1628 $bits['name'] = $child;
1629 if ( $child->firstChild instanceof PPNode_Hash_Attr
1630 && $child->firstChild->name === 'index' )
1632 $bits['index'] = $child->firstChild->value;
1634 } elseif ( $child->name === 'value' ) {
1635 $bits['value'] = $child;
1639 if ( !isset( $bits['name'] ) ) {
1640 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1642 if ( !isset( $bits['index'] ) ) {
1643 $bits['index'] = '';
1645 return $bits;
1649 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1650 * All values in the resulting array are PPNodes. Inner and close are optional.
1652 * @throws MWException
1653 * @return array
1655 function splitExt() {
1656 $bits = array();
1657 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1658 if ( !isset( $child->name ) ) {
1659 continue;
1661 if ( $child->name == 'name' ) {
1662 $bits['name'] = $child;
1663 } elseif ( $child->name == 'attr' ) {
1664 $bits['attr'] = $child;
1665 } elseif ( $child->name == 'inner' ) {
1666 $bits['inner'] = $child;
1667 } elseif ( $child->name == 'close' ) {
1668 $bits['close'] = $child;
1671 if ( !isset( $bits['name'] ) ) {
1672 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1674 return $bits;
1678 * Split an "<h>" node
1680 * @throws MWException
1681 * @return array
1683 function splitHeading() {
1684 if ( $this->name !== 'h' ) {
1685 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1687 $bits = array();
1688 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1689 if ( !isset( $child->name ) ) {
1690 continue;
1692 if ( $child->name == 'i' ) {
1693 $bits['i'] = $child->value;
1694 } elseif ( $child->name == 'level' ) {
1695 $bits['level'] = $child->value;
1698 if ( !isset( $bits['i'] ) ) {
1699 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1701 return $bits;
1705 * Split a "<template>" or "<tplarg>" node
1707 * @throws MWException
1708 * @return array
1710 function splitTemplate() {
1711 $parts = array();
1712 $bits = array( 'lineStart' => '' );
1713 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1714 if ( !isset( $child->name ) ) {
1715 continue;
1717 if ( $child->name == 'title' ) {
1718 $bits['title'] = $child;
1720 if ( $child->name == 'part' ) {
1721 $parts[] = $child;
1723 if ( $child->name == 'lineStart' ) {
1724 $bits['lineStart'] = '1';
1727 if ( !isset( $bits['title'] ) ) {
1728 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1730 $bits['parts'] = new PPNode_Hash_Array( $parts );
1731 return $bits;
1736 * @ingroup Parser
1738 class PPNode_Hash_Text implements PPNode {
1739 var $value, $nextSibling;
1741 function __construct( $value ) {
1742 if ( is_object( $value ) ) {
1743 throw new MWException( __CLASS__ . ' given object instead of string' );
1745 $this->value = $value;
1748 function __toString() {
1749 return htmlspecialchars( $this->value );
1752 function getNextSibling() {
1753 return $this->nextSibling;
1756 function getChildren() { return false; }
1757 function getFirstChild() { return false; }
1758 function getChildrenOfType( $name ) { return false; }
1759 function getLength() { return false; }
1760 function item( $i ) { return false; }
1761 function getName() { return '#text'; }
1762 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1763 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1764 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1768 * @ingroup Parser
1770 class PPNode_Hash_Array implements PPNode {
1771 var $value, $nextSibling;
1773 function __construct( $value ) {
1774 $this->value = $value;
1777 function __toString() {
1778 return var_export( $this, true );
1781 function getLength() {
1782 return count( $this->value );
1785 function item( $i ) {
1786 return $this->value[$i];
1789 function getName() { return '#nodelist'; }
1791 function getNextSibling() {
1792 return $this->nextSibling;
1795 function getChildren() { return false; }
1796 function getFirstChild() { return false; }
1797 function getChildrenOfType( $name ) { return false; }
1798 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1799 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1800 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1804 * @ingroup Parser
1806 class PPNode_Hash_Attr implements PPNode {
1807 var $name, $value, $nextSibling;
1809 function __construct( $name, $value ) {
1810 $this->name = $name;
1811 $this->value = $value;
1814 function __toString() {
1815 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1818 function getName() {
1819 return $this->name;
1822 function getNextSibling() {
1823 return $this->nextSibling;
1826 function getChildren() { return false; }
1827 function getFirstChild() { return false; }
1828 function getChildrenOfType( $name ) { return false; }
1829 function getLength() { return false; }
1830 function item( $i ) { return false; }
1831 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1832 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1833 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }