added newPartNodeArray for creating a node with a list of parts form a php array...
[lhc/web/wiklou.git] / includes / parser / Preprocessor_Hash.php
1 <?php
2
3 /**
4 * Differences from DOM schema:
5 * * attribute nodes are children
6 * * <h> nodes that aren't at the top are replaced with <possible-h>
7 * @ingroup Parser
8 */
9 class Preprocessor_Hash implements Preprocessor {
10 var $parser;
11
12 const CACHE_VERSION = 1;
13
14 function __construct( $parser ) {
15 $this->parser = $parser;
16 }
17
18 function newFrame() {
19 return new PPFrame_Hash( $this );
20 }
21
22 function newCustomFrame( $args ) {
23 return new PPCustomFrame_Hash( $this, $args );
24 }
25
26 function newPartNodeArray( $values ) {
27 $list = array();
28
29 foreach ( $values as $k => $val ) {
30 $partNode = new PPNode_Hash_Tree( 'part' );
31 $nameNode = new PPNode_Hash_Tree( 'name' );
32
33 if ( is_int( $k ) ) {
34 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $k ) );
35 $partNode->addChild( $nameNode );
36 } else {
37 $nameNode->addChild( new PPNode_Hash_Text( $k ) );
38 $partNode->addChild( $nameNode );
39 $partNode->addChild( new PPNode_Hash_Text( '=' ) );
40 }
41
42 $valueNode = new PPNode_Hash_Tree( 'value' );
43 $valueNode->addChild( new PPNode_Hash_Text( $val ) );
44 $partNode->addChild( $valueNode );
45
46 $list[] = $partNode;
47 }
48
49 $node = new PPNode_Hash_Array( $list );
50 return $node;
51 }
52
53 /**
54 * Preprocess some wikitext and return the document tree.
55 * This is the ghost of Parser::replace_variables().
56 *
57 * @param $text String: the text to parse
58 * @param $flags Integer: bitwise combination of:
59 * Parser::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
60 * included. Default is to assume a direct page view.
61 *
62 * The generated DOM tree must depend only on the input text and the flags.
63 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
64 *
65 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
66 * change in the DOM tree for a given text, must be passed through the section identifier
67 * in the section edit link and thus back to extractSections().
68 *
69 * The output of this function is currently only cached in process memory, but a persistent
70 * cache may be implemented at a later date which takes further advantage of these strict
71 * dependency requirements.
72 *
73 * @private
74 */
75 function preprocessToObj( $text, $flags = 0 ) {
76 wfProfileIn( __METHOD__ );
77
78
79 // Check cache.
80 global $wgMemc, $wgPreprocessorCacheThreshold;
81
82 $cacheable = strlen( $text ) > $wgPreprocessorCacheThreshold;
83 if ( $cacheable ) {
84 wfProfileIn( __METHOD__.'-cacheable' );
85
86 $cacheKey = wfMemcKey( 'preprocess-hash', md5($text), $flags );
87 $cacheValue = $wgMemc->get( $cacheKey );
88 if ( $cacheValue ) {
89 $version = substr( $cacheValue, 0, 8 );
90 if ( intval( $version ) == self::CACHE_VERSION ) {
91 $hash = unserialize( substr( $cacheValue, 8 ) );
92 // From the cache
93 wfDebugLog( "Preprocessor",
94 "Loaded preprocessor hash from memcached (key $cacheKey)" );
95 wfProfileOut( __METHOD__.'-cacheable' );
96 wfProfileOut( __METHOD__ );
97 return $hash;
98 }
99 }
100 wfProfileIn( __METHOD__.'-cache-miss' );
101 }
102
103 $rules = array(
104 '{' => array(
105 'end' => '}',
106 'names' => array(
107 2 => 'template',
108 3 => 'tplarg',
109 ),
110 'min' => 2,
111 'max' => 3,
112 ),
113 '[' => array(
114 'end' => ']',
115 'names' => array( 2 => null ),
116 'min' => 2,
117 'max' => 2,
118 )
119 );
120
121 $forInclusion = $flags & Parser::PTD_FOR_INCLUSION;
122
123 $xmlishElements = $this->parser->getStripList();
124 $enableOnlyinclude = false;
125 if ( $forInclusion ) {
126 $ignoredTags = array( 'includeonly', '/includeonly' );
127 $ignoredElements = array( 'noinclude' );
128 $xmlishElements[] = 'noinclude';
129 if ( strpos( $text, '<onlyinclude>' ) !== false && strpos( $text, '</onlyinclude>' ) !== false ) {
130 $enableOnlyinclude = true;
131 }
132 } else {
133 $ignoredTags = array( 'noinclude', '/noinclude', 'onlyinclude', '/onlyinclude' );
134 $ignoredElements = array( 'includeonly' );
135 $xmlishElements[] = 'includeonly';
136 }
137 $xmlishRegex = implode( '|', array_merge( $xmlishElements, $ignoredTags ) );
138
139 // Use "A" modifier (anchored) instead of "^", because ^ doesn't work with an offset
140 $elementsRegex = "~($xmlishRegex)(?:\s|\/>|>)|(!--)~iA";
141
142 $stack = new PPDStack_Hash;
143
144 $searchBase = "[{<\n";
145 $revText = strrev( $text ); // For fast reverse searches
146
147 $i = 0; # Input pointer, starts out pointing to a pseudo-newline before the start
148 $accum =& $stack->getAccum(); # Current accumulator
149 $findEquals = false; # True to find equals signs in arguments
150 $findPipe = false; # True to take notice of pipe characters
151 $headingIndex = 1;
152 $inHeading = false; # True if $i is inside a possible heading
153 $noMoreGT = false; # True if there are no more greater-than (>) signs right of $i
154 $findOnlyinclude = $enableOnlyinclude; # True to ignore all input up to the next <onlyinclude>
155 $fakeLineStart = true; # Do a line-start run without outputting an LF character
156
157 while ( true ) {
158 //$this->memCheck();
159
160 if ( $findOnlyinclude ) {
161 // Ignore all input up to the next <onlyinclude>
162 $startPos = strpos( $text, '<onlyinclude>', $i );
163 if ( $startPos === false ) {
164 // Ignored section runs to the end
165 $accum->addNodeWithText( 'ignore', substr( $text, $i ) );
166 break;
167 }
168 $tagEndPos = $startPos + strlen( '<onlyinclude>' ); // past-the-end
169 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i ) );
170 $i = $tagEndPos;
171 $findOnlyinclude = false;
172 }
173
174 if ( $fakeLineStart ) {
175 $found = 'line-start';
176 $curChar = '';
177 } else {
178 # Find next opening brace, closing brace or pipe
179 $search = $searchBase;
180 if ( $stack->top === false ) {
181 $currentClosing = '';
182 } else {
183 $currentClosing = $stack->top->close;
184 $search .= $currentClosing;
185 }
186 if ( $findPipe ) {
187 $search .= '|';
188 }
189 if ( $findEquals ) {
190 // First equals will be for the template
191 $search .= '=';
192 }
193 $rule = null;
194 # Output literal section, advance input counter
195 $literalLength = strcspn( $text, $search, $i );
196 if ( $literalLength > 0 ) {
197 $accum->addLiteral( substr( $text, $i, $literalLength ) );
198 $i += $literalLength;
199 }
200 if ( $i >= strlen( $text ) ) {
201 if ( $currentClosing == "\n" ) {
202 // Do a past-the-end run to finish off the heading
203 $curChar = '';
204 $found = 'line-end';
205 } else {
206 # All done
207 break;
208 }
209 } else {
210 $curChar = $text[$i];
211 if ( $curChar == '|' ) {
212 $found = 'pipe';
213 } elseif ( $curChar == '=' ) {
214 $found = 'equals';
215 } elseif ( $curChar == '<' ) {
216 $found = 'angle';
217 } elseif ( $curChar == "\n" ) {
218 if ( $inHeading ) {
219 $found = 'line-end';
220 } else {
221 $found = 'line-start';
222 }
223 } elseif ( $curChar == $currentClosing ) {
224 $found = 'close';
225 } elseif ( isset( $rules[$curChar] ) ) {
226 $found = 'open';
227 $rule = $rules[$curChar];
228 } else {
229 # Some versions of PHP have a strcspn which stops on null characters
230 # Ignore and continue
231 ++$i;
232 continue;
233 }
234 }
235 }
236
237 if ( $found == 'angle' ) {
238 $matches = false;
239 // Handle </onlyinclude>
240 if ( $enableOnlyinclude && substr( $text, $i, strlen( '</onlyinclude>' ) ) == '</onlyinclude>' ) {
241 $findOnlyinclude = true;
242 continue;
243 }
244
245 // Determine element name
246 if ( !preg_match( $elementsRegex, $text, $matches, 0, $i + 1 ) ) {
247 // Element name missing or not listed
248 $accum->addLiteral( '<' );
249 ++$i;
250 continue;
251 }
252 // Handle comments
253 if ( isset( $matches[2] ) && $matches[2] == '!--' ) {
254 // To avoid leaving blank lines, when a comment is both preceded
255 // and followed by a newline (ignoring spaces), trim leading and
256 // trailing spaces and one of the newlines.
257
258 // Find the end
259 $endPos = strpos( $text, '-->', $i + 4 );
260 if ( $endPos === false ) {
261 // Unclosed comment in input, runs to end
262 $inner = substr( $text, $i );
263 $accum->addNodeWithText( 'comment', $inner );
264 $i = strlen( $text );
265 } else {
266 // Search backwards for leading whitespace
267 $wsStart = $i ? ( $i - strspn( $revText, ' ', strlen( $text ) - $i ) ) : 0;
268 // Search forwards for trailing whitespace
269 // $wsEnd will be the position of the last space
270 $wsEnd = $endPos + 2 + strspn( $text, ' ', $endPos + 3 );
271 // Eat the line if possible
272 // TODO: This could theoretically be done if $wsStart == 0, i.e. for comments at
273 // the overall start. That's not how Sanitizer::removeHTMLcomments() did it, but
274 // it's a possible beneficial b/c break.
275 if ( $wsStart > 0 && substr( $text, $wsStart - 1, 1 ) == "\n"
276 && substr( $text, $wsEnd + 1, 1 ) == "\n" )
277 {
278 $startPos = $wsStart;
279 $endPos = $wsEnd + 1;
280 // Remove leading whitespace from the end of the accumulator
281 // Sanity check first though
282 $wsLength = $i - $wsStart;
283 if ( $wsLength > 0
284 && $accum->lastNode instanceof PPNode_Hash_Text
285 && substr( $accum->lastNode->value, -$wsLength ) === str_repeat( ' ', $wsLength ) )
286 {
287 $accum->lastNode->value = substr( $accum->lastNode->value, 0, -$wsLength );
288 }
289 // Do a line-start run next time to look for headings after the comment
290 $fakeLineStart = true;
291 } else {
292 // No line to eat, just take the comment itself
293 $startPos = $i;
294 $endPos += 2;
295 }
296
297 if ( $stack->top ) {
298 $part = $stack->top->getCurrentPart();
299 if ( isset( $part->commentEnd ) && $part->commentEnd == $wsStart - 1 ) {
300 // Comments abutting, no change in visual end
301 $part->commentEnd = $wsEnd;
302 } else {
303 $part->visualEnd = $wsStart;
304 $part->commentEnd = $endPos;
305 }
306 }
307 $i = $endPos + 1;
308 $inner = substr( $text, $startPos, $endPos - $startPos + 1 );
309 $accum->addNodeWithText( 'comment', $inner );
310 }
311 continue;
312 }
313 $name = $matches[1];
314 $lowerName = strtolower( $name );
315 $attrStart = $i + strlen( $name ) + 1;
316
317 // Find end of tag
318 $tagEndPos = $noMoreGT ? false : strpos( $text, '>', $attrStart );
319 if ( $tagEndPos === false ) {
320 // Infinite backtrack
321 // Disable tag search to prevent worst-case O(N^2) performance
322 $noMoreGT = true;
323 $accum->addLiteral( '<' );
324 ++$i;
325 continue;
326 }
327
328 // Handle ignored tags
329 if ( in_array( $lowerName, $ignoredTags ) ) {
330 $accum->addNodeWithText( 'ignore', substr( $text, $i, $tagEndPos - $i + 1 ) );
331 $i = $tagEndPos + 1;
332 continue;
333 }
334
335 $tagStartPos = $i;
336 if ( $text[$tagEndPos-1] == '/' ) {
337 // Short end tag
338 $attrEnd = $tagEndPos - 1;
339 $inner = null;
340 $i = $tagEndPos + 1;
341 $close = null;
342 } else {
343 $attrEnd = $tagEndPos;
344 // Find closing tag
345 if ( preg_match( "/<\/" . preg_quote( $name, '/' ) . "\s*>/i",
346 $text, $matches, PREG_OFFSET_CAPTURE, $tagEndPos + 1 ) )
347 {
348 $inner = substr( $text, $tagEndPos + 1, $matches[0][1] - $tagEndPos - 1 );
349 $i = $matches[0][1] + strlen( $matches[0][0] );
350 $close = $matches[0][0];
351 } else {
352 // No end tag -- let it run out to the end of the text.
353 $inner = substr( $text, $tagEndPos + 1 );
354 $i = strlen( $text );
355 $close = null;
356 }
357 }
358 // <includeonly> and <noinclude> just become <ignore> tags
359 if ( in_array( $lowerName, $ignoredElements ) ) {
360 $accum->addNodeWithText( 'ignore', substr( $text, $tagStartPos, $i - $tagStartPos ) );
361 continue;
362 }
363
364 if ( $attrEnd <= $attrStart ) {
365 $attr = '';
366 } else {
367 // Note that the attr element contains the whitespace between name and attribute,
368 // this is necessary for precise reconstruction during pre-save transform.
369 $attr = substr( $text, $attrStart, $attrEnd - $attrStart );
370 }
371
372 $extNode = new PPNode_Hash_Tree( 'ext' );
373 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'name', $name ) );
374 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'attr', $attr ) );
375 if ( $inner !== null ) {
376 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'inner', $inner ) );
377 }
378 if ( $close !== null ) {
379 $extNode->addChild( PPNode_Hash_Tree::newWithText( 'close', $close ) );
380 }
381 $accum->addNode( $extNode );
382 }
383
384 elseif ( $found == 'line-start' ) {
385 // Is this the start of a heading?
386 // Line break belongs before the heading element in any case
387 if ( $fakeLineStart ) {
388 $fakeLineStart = false;
389 } else {
390 $accum->addLiteral( $curChar );
391 $i++;
392 }
393
394 $count = strspn( $text, '=', $i, 6 );
395 if ( $count == 1 && $findEquals ) {
396 // DWIM: This looks kind of like a name/value separator
397 // Let's let the equals handler have it and break the potential heading
398 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
399 } elseif ( $count > 0 ) {
400 $piece = array(
401 'open' => "\n",
402 'close' => "\n",
403 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
404 'startPos' => $i,
405 'count' => $count );
406 $stack->push( $piece );
407 $accum =& $stack->getAccum();
408 extract( $stack->getFlags() );
409 $i += $count;
410 }
411 }
412
413 elseif ( $found == 'line-end' ) {
414 $piece = $stack->top;
415 // A heading must be open, otherwise \n wouldn't have been in the search list
416 assert( $piece->open == "\n" );
417 $part = $piece->getCurrentPart();
418 // Search back through the input to see if it has a proper close
419 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
420 $wsLength = strspn( $revText, " \t", strlen( $text ) - $i );
421 $searchStart = $i - $wsLength;
422 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
423 // Comment found at line end
424 // Search for equals signs before the comment
425 $searchStart = $part->visualEnd;
426 $searchStart -= strspn( $revText, " \t", strlen( $text ) - $searchStart );
427 }
428 $count = $piece->count;
429 $equalsLength = strspn( $revText, '=', strlen( $text ) - $searchStart );
430 if ( $equalsLength > 0 ) {
431 if ( $i - $equalsLength == $piece->startPos ) {
432 // This is just a single string of equals signs on its own line
433 // Replicate the doHeadings behaviour /={count}(.+)={count}/
434 // First find out how many equals signs there really are (don't stop at 6)
435 $count = $equalsLength;
436 if ( $count < 3 ) {
437 $count = 0;
438 } else {
439 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
440 }
441 } else {
442 $count = min( $equalsLength, $count );
443 }
444 if ( $count > 0 ) {
445 // Normal match, output <h>
446 $element = new PPNode_Hash_Tree( 'possible-h' );
447 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
448 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
449 $element->lastChild->nextSibling = $accum->firstNode;
450 $element->lastChild = $accum->lastNode;
451 } else {
452 // Single equals sign on its own line, count=0
453 $element = $accum;
454 }
455 } else {
456 // No match, no <h>, just pass down the inner text
457 $element = $accum;
458 }
459 // Unwind the stack
460 $stack->pop();
461 $accum =& $stack->getAccum();
462 extract( $stack->getFlags() );
463
464 // Append the result to the enclosing accumulator
465 if ( $element instanceof PPNode ) {
466 $accum->addNode( $element );
467 } else {
468 $accum->addAccum( $element );
469 }
470 // Note that we do NOT increment the input pointer.
471 // This is because the closing linebreak could be the opening linebreak of
472 // another heading. Infinite loops are avoided because the next iteration MUST
473 // hit the heading open case above, which unconditionally increments the
474 // input pointer.
475 }
476
477 elseif ( $found == 'open' ) {
478 # count opening brace characters
479 $count = strspn( $text, $curChar, $i );
480
481 # we need to add to stack only if opening brace count is enough for one of the rules
482 if ( $count >= $rule['min'] ) {
483 # Add it to the stack
484 $piece = array(
485 'open' => $curChar,
486 'close' => $rule['end'],
487 'count' => $count,
488 'lineStart' => ($i > 0 && $text[$i-1] == "\n"),
489 );
490
491 $stack->push( $piece );
492 $accum =& $stack->getAccum();
493 extract( $stack->getFlags() );
494 } else {
495 # Add literal brace(s)
496 $accum->addLiteral( str_repeat( $curChar, $count ) );
497 }
498 $i += $count;
499 }
500
501 elseif ( $found == 'close' ) {
502 $piece = $stack->top;
503 # lets check if there are enough characters for closing brace
504 $maxCount = $piece->count;
505 $count = strspn( $text, $curChar, $i, $maxCount );
506
507 # check for maximum matching characters (if there are 5 closing
508 # characters, we will probably need only 3 - depending on the rules)
509 $matchingCount = 0;
510 $rule = $rules[$piece->open];
511 if ( $count > $rule['max'] ) {
512 # The specified maximum exists in the callback array, unless the caller
513 # has made an error
514 $matchingCount = $rule['max'];
515 } else {
516 # Count is less than the maximum
517 # Skip any gaps in the callback array to find the true largest match
518 # Need to use array_key_exists not isset because the callback can be null
519 $matchingCount = $count;
520 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
521 --$matchingCount;
522 }
523 }
524
525 if ($matchingCount <= 0) {
526 # No matching element found in callback array
527 # Output a literal closing brace and continue
528 $accum->addLiteral( str_repeat( $curChar, $count ) );
529 $i += $count;
530 continue;
531 }
532 $name = $rule['names'][$matchingCount];
533 if ( $name === null ) {
534 // No element, just literal text
535 $element = $piece->breakSyntax( $matchingCount );
536 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
537 } else {
538 # Create XML element
539 # Note: $parts is already XML, does not need to be encoded further
540 $parts = $piece->parts;
541 $titleAccum = $parts[0]->out;
542 unset( $parts[0] );
543
544 $element = new PPNode_Hash_Tree( $name );
545
546 # The invocation is at the start of the line if lineStart is set in
547 # the stack, and all opening brackets are used up.
548 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
549 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
550 }
551 $titleNode = new PPNode_Hash_Tree( 'title' );
552 $titleNode->firstChild = $titleAccum->firstNode;
553 $titleNode->lastChild = $titleAccum->lastNode;
554 $element->addChild( $titleNode );
555 $argIndex = 1;
556 foreach ( $parts as $partIndex => $part ) {
557 if ( isset( $part->eqpos ) ) {
558 // Find equals
559 $lastNode = false;
560 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
561 if ( $node === $part->eqpos ) {
562 break;
563 }
564 $lastNode = $node;
565 }
566 if ( !$node ) {
567 throw new MWException( __METHOD__. ': eqpos not found' );
568 }
569 if ( $node->name !== 'equals' ) {
570 throw new MWException( __METHOD__ .': eqpos is not equals' );
571 }
572 $equalsNode = $node;
573
574 // Construct name node
575 $nameNode = new PPNode_Hash_Tree( 'name' );
576 if ( $lastNode !== false ) {
577 $lastNode->nextSibling = false;
578 $nameNode->firstChild = $part->out->firstNode;
579 $nameNode->lastChild = $lastNode;
580 }
581
582 // Construct value node
583 $valueNode = new PPNode_Hash_Tree( 'value' );
584 if ( $equalsNode->nextSibling !== false ) {
585 $valueNode->firstChild = $equalsNode->nextSibling;
586 $valueNode->lastChild = $part->out->lastNode;
587 }
588 $partNode = new PPNode_Hash_Tree( 'part' );
589 $partNode->addChild( $nameNode );
590 $partNode->addChild( $equalsNode->firstChild );
591 $partNode->addChild( $valueNode );
592 $element->addChild( $partNode );
593 } else {
594 $partNode = new PPNode_Hash_Tree( 'part' );
595 $nameNode = new PPNode_Hash_Tree( 'name' );
596 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
597 $valueNode = new PPNode_Hash_Tree( 'value' );
598 $valueNode->firstChild = $part->out->firstNode;
599 $valueNode->lastChild = $part->out->lastNode;
600 $partNode->addChild( $nameNode );
601 $partNode->addChild( $valueNode );
602 $element->addChild( $partNode );
603 }
604 }
605 }
606
607 # Advance input pointer
608 $i += $matchingCount;
609
610 # Unwind the stack
611 $stack->pop();
612 $accum =& $stack->getAccum();
613
614 # Re-add the old stack element if it still has unmatched opening characters remaining
615 if ($matchingCount < $piece->count) {
616 $piece->parts = array( new PPDPart_Hash );
617 $piece->count -= $matchingCount;
618 # do we still qualify for any callback with remaining count?
619 $names = $rules[$piece->open]['names'];
620 $skippedBraces = 0;
621 $enclosingAccum =& $accum;
622 while ( $piece->count ) {
623 if ( array_key_exists( $piece->count, $names ) ) {
624 $stack->push( $piece );
625 $accum =& $stack->getAccum();
626 break;
627 }
628 --$piece->count;
629 $skippedBraces ++;
630 }
631 $enclosingAccum->addLiteral( str_repeat( $piece->open, $skippedBraces ) );
632 }
633
634 extract( $stack->getFlags() );
635
636 # Add XML element to the enclosing accumulator
637 if ( $element instanceof PPNode ) {
638 $accum->addNode( $element );
639 } else {
640 $accum->addAccum( $element );
641 }
642 }
643
644 elseif ( $found == 'pipe' ) {
645 $findEquals = true; // shortcut for getFlags()
646 $stack->addPart();
647 $accum =& $stack->getAccum();
648 ++$i;
649 }
650
651 elseif ( $found == 'equals' ) {
652 $findEquals = false; // shortcut for getFlags()
653 $accum->addNodeWithText( 'equals', '=' );
654 $stack->getCurrentPart()->eqpos = $accum->lastNode;
655 ++$i;
656 }
657 }
658
659 # Output any remaining unclosed brackets
660 foreach ( $stack->stack as $piece ) {
661 $stack->rootAccum->addAccum( $piece->breakSyntax() );
662 }
663
664 # Enable top-level headings
665 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
666 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
667 $node->name = 'h';
668 }
669 }
670
671 $rootNode = new PPNode_Hash_Tree( 'root' );
672 $rootNode->firstChild = $stack->rootAccum->firstNode;
673 $rootNode->lastChild = $stack->rootAccum->lastNode;
674
675 // Cache
676 if ($cacheable) {
677 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . serialize( $rootNode );;
678 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
679 wfProfileOut( __METHOD__.'-cache-miss' );
680 wfProfileOut( __METHOD__.'-cacheable' );
681 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
682 }
683
684 wfProfileOut( __METHOD__ );
685 return $rootNode;
686 }
687 }
688
689 /**
690 * Stack class to help Preprocessor::preprocessToObj()
691 * @ingroup Parser
692 */
693 class PPDStack_Hash extends PPDStack {
694 function __construct() {
695 $this->elementClass = 'PPDStackElement_Hash';
696 parent::__construct();
697 $this->rootAccum = new PPDAccum_Hash;
698 }
699 }
700
701 /**
702 * @ingroup Parser
703 */
704 class PPDStackElement_Hash extends PPDStackElement {
705 function __construct( $data = array() ) {
706 $this->partClass = 'PPDPart_Hash';
707 parent::__construct( $data );
708 }
709
710 /**
711 * Get the accumulator that would result if the close is not found.
712 */
713 function breakSyntax( $openingCount = false ) {
714 if ( $this->open == "\n" ) {
715 $accum = $this->parts[0]->out;
716 } else {
717 if ( $openingCount === false ) {
718 $openingCount = $this->count;
719 }
720 $accum = new PPDAccum_Hash;
721 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
722 $first = true;
723 foreach ( $this->parts as $part ) {
724 if ( $first ) {
725 $first = false;
726 } else {
727 $accum->addLiteral( '|' );
728 }
729 $accum->addAccum( $part->out );
730 }
731 }
732 return $accum;
733 }
734 }
735
736 /**
737 * @ingroup Parser
738 */
739 class PPDPart_Hash extends PPDPart {
740 function __construct( $out = '' ) {
741 $accum = new PPDAccum_Hash;
742 if ( $out !== '' ) {
743 $accum->addLiteral( $out );
744 }
745 parent::__construct( $accum );
746 }
747 }
748
749 /**
750 * @ingroup Parser
751 */
752 class PPDAccum_Hash {
753 var $firstNode, $lastNode;
754
755 function __construct() {
756 $this->firstNode = $this->lastNode = false;
757 }
758
759 /**
760 * Append a string literal
761 */
762 function addLiteral( $s ) {
763 if ( $this->lastNode === false ) {
764 $this->firstNode = $this->lastNode = new PPNode_Hash_Text( $s );
765 } elseif ( $this->lastNode instanceof PPNode_Hash_Text ) {
766 $this->lastNode->value .= $s;
767 } else {
768 $this->lastNode->nextSibling = new PPNode_Hash_Text( $s );
769 $this->lastNode = $this->lastNode->nextSibling;
770 }
771 }
772
773 /**
774 * Append a PPNode
775 */
776 function addNode( PPNode $node ) {
777 if ( $this->lastNode === false ) {
778 $this->firstNode = $this->lastNode = $node;
779 } else {
780 $this->lastNode->nextSibling = $node;
781 $this->lastNode = $node;
782 }
783 }
784
785 /**
786 * Append a tree node with text contents
787 */
788 function addNodeWithText( $name, $value ) {
789 $node = PPNode_Hash_Tree::newWithText( $name, $value );
790 $this->addNode( $node );
791 }
792
793 /**
794 * Append a PPAccum_Hash
795 * Takes over ownership of the nodes in the source argument. These nodes may
796 * subsequently be modified, especially nextSibling.
797 */
798 function addAccum( $accum ) {
799 if ( $accum->lastNode === false ) {
800 // nothing to add
801 } elseif ( $this->lastNode === false ) {
802 $this->firstNode = $accum->firstNode;
803 $this->lastNode = $accum->lastNode;
804 } else {
805 $this->lastNode->nextSibling = $accum->firstNode;
806 $this->lastNode = $accum->lastNode;
807 }
808 }
809 }
810
811 /**
812 * An expansion frame, used as a context to expand the result of preprocessToObj()
813 * @ingroup Parser
814 */
815 class PPFrame_Hash implements PPFrame {
816 var $preprocessor, $parser, $title;
817 var $titleCache;
818
819 /**
820 * Hashtable listing templates which are disallowed for expansion in this frame,
821 * having been encountered previously in parent frames.
822 */
823 var $loopCheckHash;
824
825 /**
826 * Recursion depth of this frame, top = 0
827 * Note that this is NOT the same as expansion depth in expand()
828 */
829 var $depth;
830
831
832 /**
833 * Construct a new preprocessor frame.
834 * @param $preprocessor Preprocessor: the parent preprocessor
835 */
836 function __construct( $preprocessor ) {
837 $this->preprocessor = $preprocessor;
838 $this->parser = $preprocessor->parser;
839 $this->title = $this->parser->mTitle;
840 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
841 $this->loopCheckHash = array();
842 $this->depth = 0;
843 }
844
845 /**
846 * Create a new child frame
847 * $args is optionally a multi-root PPNode or array containing the template arguments
848 */
849 function newChild( $args = false, $title = false ) {
850 $namedArgs = array();
851 $numberedArgs = array();
852 if ( $title === false ) {
853 $title = $this->title;
854 }
855 if ( $args !== false ) {
856 $xpath = false;
857 if ( $args instanceof PPNode_Hash_Array ) {
858 $args = $args->value;
859 } elseif ( !is_array( $args ) ) {
860 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
861 }
862 foreach ( $args as $arg ) {
863 $bits = $arg->splitArg();
864 if ( $bits['index'] !== '' ) {
865 // Numbered parameter
866 $numberedArgs[$bits['index']] = $bits['value'];
867 unset( $namedArgs[$bits['index']] );
868 } else {
869 // Named parameter
870 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
871 $namedArgs[$name] = $bits['value'];
872 unset( $numberedArgs[$name] );
873 }
874 }
875 }
876 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
877 }
878
879 function expand( $root, $flags = 0 ) {
880 static $expansionDepth = 0;
881 if ( is_string( $root ) ) {
882 return $root;
883 }
884
885 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->mMaxPPNodeCount )
886 {
887 return '<span class="error">Node-count limit exceeded</span>';
888 }
889 if ( $expansionDepth > $this->parser->mOptions->mMaxPPExpandDepth ) {
890 return '<span class="error">Expansion depth limit exceeded</span>';
891 }
892 ++$expansionDepth;
893
894 $outStack = array( '', '' );
895 $iteratorStack = array( false, $root );
896 $indexStack = array( 0, 0 );
897
898 while ( count( $iteratorStack ) > 1 ) {
899 $level = count( $outStack ) - 1;
900 $iteratorNode =& $iteratorStack[ $level ];
901 $out =& $outStack[$level];
902 $index =& $indexStack[$level];
903
904 if ( is_array( $iteratorNode ) ) {
905 if ( $index >= count( $iteratorNode ) ) {
906 // All done with this iterator
907 $iteratorStack[$level] = false;
908 $contextNode = false;
909 } else {
910 $contextNode = $iteratorNode[$index];
911 $index++;
912 }
913 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
914 if ( $index >= $iteratorNode->getLength() ) {
915 // All done with this iterator
916 $iteratorStack[$level] = false;
917 $contextNode = false;
918 } else {
919 $contextNode = $iteratorNode->item( $index );
920 $index++;
921 }
922 } else {
923 // Copy to $contextNode and then delete from iterator stack,
924 // because this is not an iterator but we do have to execute it once
925 $contextNode = $iteratorStack[$level];
926 $iteratorStack[$level] = false;
927 }
928
929 $newIterator = false;
930
931 if ( $contextNode === false ) {
932 // nothing to do
933 } elseif ( is_string( $contextNode ) ) {
934 $out .= $contextNode;
935 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
936 $newIterator = $contextNode;
937 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
938 // No output
939 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
940 $out .= $contextNode->value;
941 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
942 if ( $contextNode->name == 'template' ) {
943 # Double-brace expansion
944 $bits = $contextNode->splitTemplate();
945 if ( $flags & self::NO_TEMPLATES ) {
946 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
947 } else {
948 $ret = $this->parser->braceSubstitution( $bits, $this );
949 if ( isset( $ret['object'] ) ) {
950 $newIterator = $ret['object'];
951 } else {
952 $out .= $ret['text'];
953 }
954 }
955 } elseif ( $contextNode->name == 'tplarg' ) {
956 # Triple-brace expansion
957 $bits = $contextNode->splitTemplate();
958 if ( $flags & self::NO_ARGS ) {
959 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
960 } else {
961 $ret = $this->parser->argSubstitution( $bits, $this );
962 if ( isset( $ret['object'] ) ) {
963 $newIterator = $ret['object'];
964 } else {
965 $out .= $ret['text'];
966 }
967 }
968 } elseif ( $contextNode->name == 'comment' ) {
969 # HTML-style comment
970 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
971 if ( $this->parser->ot['html']
972 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
973 || ( $flags & self::STRIP_COMMENTS ) )
974 {
975 $out .= '';
976 }
977 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
978 # Not in RECOVER_COMMENTS mode (extractSections) though
979 elseif ( $this->parser->ot['wiki'] && ! ( $flags & self::RECOVER_COMMENTS ) ) {
980 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
981 }
982 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
983 else {
984 $out .= $contextNode->firstChild->value;
985 }
986 } elseif ( $contextNode->name == 'ignore' ) {
987 # Output suppression used by <includeonly> etc.
988 # OT_WIKI will only respect <ignore> in substed templates.
989 # The other output types respect it unless NO_IGNORE is set.
990 # extractSections() sets NO_IGNORE and so never respects it.
991 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & self::NO_IGNORE ) ) {
992 $out .= $contextNode->firstChild->value;
993 } else {
994 //$out .= '';
995 }
996 } elseif ( $contextNode->name == 'ext' ) {
997 # Extension tag
998 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
999 $out .= $this->parser->extensionSubstitution( $bits, $this );
1000 } elseif ( $contextNode->name == 'h' ) {
1001 # Heading
1002 if ( $this->parser->ot['html'] ) {
1003 # Expand immediately and insert heading index marker
1004 $s = '';
1005 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1006 $s .= $this->expand( $node, $flags );
1007 }
1008
1009 $bits = $contextNode->splitHeading();
1010 $titleText = $this->title->getPrefixedDBkey();
1011 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1012 $serial = count( $this->parser->mHeadings ) - 1;
1013 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1014 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1015 $this->parser->mStripState->general->setPair( $marker, '' );
1016 $out .= $s;
1017 } else {
1018 # Expand in virtual stack
1019 $newIterator = $contextNode->getChildren();
1020 }
1021 } else {
1022 # Generic recursive expansion
1023 $newIterator = $contextNode->getChildren();
1024 }
1025 } else {
1026 throw new MWException( __METHOD__.': Invalid parameter type' );
1027 }
1028
1029 if ( $newIterator !== false ) {
1030 $outStack[] = '';
1031 $iteratorStack[] = $newIterator;
1032 $indexStack[] = 0;
1033 } elseif ( $iteratorStack[$level] === false ) {
1034 // Return accumulated value to parent
1035 // With tail recursion
1036 while ( $iteratorStack[$level] === false && $level > 0 ) {
1037 $outStack[$level - 1] .= $out;
1038 array_pop( $outStack );
1039 array_pop( $iteratorStack );
1040 array_pop( $indexStack );
1041 $level--;
1042 }
1043 }
1044 }
1045 --$expansionDepth;
1046 return $outStack[0];
1047 }
1048
1049 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1050 $args = array_slice( func_get_args(), 2 );
1051
1052 $first = true;
1053 $s = '';
1054 foreach ( $args as $root ) {
1055 if ( $root instanceof PPNode_Hash_Array ) {
1056 $root = $root->value;
1057 }
1058 if ( !is_array( $root ) ) {
1059 $root = array( $root );
1060 }
1061 foreach ( $root as $node ) {
1062 if ( $first ) {
1063 $first = false;
1064 } else {
1065 $s .= $sep;
1066 }
1067 $s .= $this->expand( $node, $flags );
1068 }
1069 }
1070 return $s;
1071 }
1072
1073 /**
1074 * Implode with no flags specified
1075 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1076 */
1077 function implode( $sep /*, ... */ ) {
1078 $args = array_slice( func_get_args(), 1 );
1079
1080 $first = true;
1081 $s = '';
1082 foreach ( $args as $root ) {
1083 if ( $root instanceof PPNode_Hash_Array ) {
1084 $root = $root->value;
1085 }
1086 if ( !is_array( $root ) ) {
1087 $root = array( $root );
1088 }
1089 foreach ( $root as $node ) {
1090 if ( $first ) {
1091 $first = false;
1092 } else {
1093 $s .= $sep;
1094 }
1095 $s .= $this->expand( $node );
1096 }
1097 }
1098 return $s;
1099 }
1100
1101 /**
1102 * Makes an object that, when expand()ed, will be the same as one obtained
1103 * with implode()
1104 */
1105 function virtualImplode( $sep /*, ... */ ) {
1106 $args = array_slice( func_get_args(), 1 );
1107 $out = array();
1108 $first = true;
1109
1110 foreach ( $args as $root ) {
1111 if ( $root instanceof PPNode_Hash_Array ) {
1112 $root = $root->value;
1113 }
1114 if ( !is_array( $root ) ) {
1115 $root = array( $root );
1116 }
1117 foreach ( $root as $node ) {
1118 if ( $first ) {
1119 $first = false;
1120 } else {
1121 $out[] = $sep;
1122 }
1123 $out[] = $node;
1124 }
1125 }
1126 return new PPNode_Hash_Array( $out );
1127 }
1128
1129 /**
1130 * Virtual implode with brackets
1131 */
1132 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1133 $args = array_slice( func_get_args(), 3 );
1134 $out = array( $start );
1135 $first = true;
1136
1137 foreach ( $args as $root ) {
1138 if ( $root instanceof PPNode_Hash_Array ) {
1139 $root = $root->value;
1140 }
1141 if ( !is_array( $root ) ) {
1142 $root = array( $root );
1143 }
1144 foreach ( $root as $node ) {
1145 if ( $first ) {
1146 $first = false;
1147 } else {
1148 $out[] = $sep;
1149 }
1150 $out[] = $node;
1151 }
1152 }
1153 $out[] = $end;
1154 return new PPNode_Hash_Array( $out );
1155 }
1156
1157 function __toString() {
1158 return 'frame{}';
1159 }
1160
1161 function getPDBK( $level = false ) {
1162 if ( $level === false ) {
1163 return $this->title->getPrefixedDBkey();
1164 } else {
1165 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1166 }
1167 }
1168
1169 function getArguments() {
1170 return array();
1171 }
1172
1173 function getNumberedArguments() {
1174 return array();
1175 }
1176
1177 function getNamedArguments() {
1178 return array();
1179 }
1180
1181 /**
1182 * Returns true if there are no arguments in this frame
1183 */
1184 function isEmpty() {
1185 return true;
1186 }
1187
1188 function getArgument( $name ) {
1189 return false;
1190 }
1191
1192 /**
1193 * Returns true if the infinite loop check is OK, false if a loop is detected
1194 */
1195 function loopCheck( $title ) {
1196 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1197 }
1198
1199 /**
1200 * Return true if the frame is a template frame
1201 */
1202 function isTemplate() {
1203 return false;
1204 }
1205 }
1206
1207 /**
1208 * Expansion frame with template arguments
1209 * @ingroup Parser
1210 */
1211 class PPTemplateFrame_Hash extends PPFrame_Hash {
1212 var $numberedArgs, $namedArgs, $parent;
1213 var $numberedExpansionCache, $namedExpansionCache;
1214
1215 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1216 PPFrame_Hash::__construct( $preprocessor );
1217 $this->parent = $parent;
1218 $this->numberedArgs = $numberedArgs;
1219 $this->namedArgs = $namedArgs;
1220 $this->title = $title;
1221 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1222 $this->titleCache = $parent->titleCache;
1223 $this->titleCache[] = $pdbk;
1224 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1225 if ( $pdbk !== false ) {
1226 $this->loopCheckHash[$pdbk] = true;
1227 }
1228 $this->depth = $parent->depth + 1;
1229 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1230 }
1231
1232 function __toString() {
1233 $s = 'tplframe{';
1234 $first = true;
1235 $args = $this->numberedArgs + $this->namedArgs;
1236 foreach ( $args as $name => $value ) {
1237 if ( $first ) {
1238 $first = false;
1239 } else {
1240 $s .= ', ';
1241 }
1242 $s .= "\"$name\":\"" .
1243 str_replace( '"', '\\"', $value->__toString() ) . '"';
1244 }
1245 $s .= '}';
1246 return $s;
1247 }
1248 /**
1249 * Returns true if there are no arguments in this frame
1250 */
1251 function isEmpty() {
1252 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1253 }
1254
1255 function getArguments() {
1256 $arguments = array();
1257 foreach ( array_merge(
1258 array_keys($this->numberedArgs),
1259 array_keys($this->namedArgs)) as $key ) {
1260 $arguments[$key] = $this->getArgument($key);
1261 }
1262 return $arguments;
1263 }
1264
1265 function getNumberedArguments() {
1266 $arguments = array();
1267 foreach ( array_keys($this->numberedArgs) as $key ) {
1268 $arguments[$key] = $this->getArgument($key);
1269 }
1270 return $arguments;
1271 }
1272
1273 function getNamedArguments() {
1274 $arguments = array();
1275 foreach ( array_keys($this->namedArgs) as $key ) {
1276 $arguments[$key] = $this->getArgument($key);
1277 }
1278 return $arguments;
1279 }
1280
1281 function getNumberedArgument( $index ) {
1282 if ( !isset( $this->numberedArgs[$index] ) ) {
1283 return false;
1284 }
1285 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1286 # No trimming for unnamed arguments
1287 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], self::STRIP_COMMENTS );
1288 }
1289 return $this->numberedExpansionCache[$index];
1290 }
1291
1292 function getNamedArgument( $name ) {
1293 if ( !isset( $this->namedArgs[$name] ) ) {
1294 return false;
1295 }
1296 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1297 # Trim named arguments post-expand, for backwards compatibility
1298 $this->namedExpansionCache[$name] = trim(
1299 $this->parent->expand( $this->namedArgs[$name], self::STRIP_COMMENTS ) );
1300 }
1301 return $this->namedExpansionCache[$name];
1302 }
1303
1304 function getArgument( $name ) {
1305 $text = $this->getNumberedArgument( $name );
1306 if ( $text === false ) {
1307 $text = $this->getNamedArgument( $name );
1308 }
1309 return $text;
1310 }
1311
1312 /**
1313 * Return true if the frame is a template frame
1314 */
1315 function isTemplate() {
1316 return true;
1317 }
1318 }
1319
1320 /**
1321 * Expansion frame with custom arguments
1322 * @ingroup Parser
1323 */
1324 class PPCustomFrame_Hash extends PPFrame_Hash {
1325 var $args;
1326
1327 function __construct( $preprocessor, $args ) {
1328 PPFrame_Hash::__construct( $preprocessor );
1329 $this->args = $args;
1330 }
1331
1332 function __toString() {
1333 $s = 'cstmframe{';
1334 $first = true;
1335 foreach ( $this->args as $name => $value ) {
1336 if ( $first ) {
1337 $first = false;
1338 } else {
1339 $s .= ', ';
1340 }
1341 $s .= "\"$name\":\"" .
1342 str_replace( '"', '\\"', $value->__toString() ) . '"';
1343 }
1344 $s .= '}';
1345 return $s;
1346 }
1347
1348 function isEmpty() {
1349 return !count( $this->args );
1350 }
1351
1352 function getArgument( $index ) {
1353 if ( !isset( $this->args[$index] ) ) {
1354 return false;
1355 }
1356 return $this->args[$index];
1357 }
1358 }
1359
1360 /**
1361 * @ingroup Parser
1362 */
1363 class PPNode_Hash_Tree implements PPNode {
1364 var $name, $firstChild, $lastChild, $nextSibling;
1365
1366 function __construct( $name ) {
1367 $this->name = $name;
1368 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1369 }
1370
1371 function __toString() {
1372 $inner = '';
1373 $attribs = '';
1374 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1375 if ( $node instanceof PPNode_Hash_Attr ) {
1376 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1377 } else {
1378 $inner .= $node->__toString();
1379 }
1380 }
1381 if ( $inner === '' ) {
1382 return "<{$this->name}$attribs/>";
1383 } else {
1384 return "<{$this->name}$attribs>$inner</{$this->name}>";
1385 }
1386 }
1387
1388 static function newWithText( $name, $text ) {
1389 $obj = new self( $name );
1390 $obj->addChild( new PPNode_Hash_Text( $text ) );
1391 return $obj;
1392 }
1393
1394 function addChild( $node ) {
1395 if ( $this->lastChild === false ) {
1396 $this->firstChild = $this->lastChild = $node;
1397 } else {
1398 $this->lastChild->nextSibling = $node;
1399 $this->lastChild = $node;
1400 }
1401 }
1402
1403 function getChildren() {
1404 $children = array();
1405 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1406 $children[] = $child;
1407 }
1408 return new PPNode_Hash_Array( $children );
1409 }
1410
1411 function getFirstChild() {
1412 return $this->firstChild;
1413 }
1414
1415 function getNextSibling() {
1416 return $this->nextSibling;
1417 }
1418
1419 function getChildrenOfType( $name ) {
1420 $children = array();
1421 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1422 if ( isset( $child->name ) && $child->name === $name ) {
1423 $children[] = $name;
1424 }
1425 }
1426 return $children;
1427 }
1428
1429 function getLength() { return false; }
1430 function item( $i ) { return false; }
1431
1432 function getName() {
1433 return $this->name;
1434 }
1435
1436 /**
1437 * Split a <part> node into an associative array containing:
1438 * name PPNode name
1439 * index String index
1440 * value PPNode value
1441 */
1442 function splitArg() {
1443 $bits = array();
1444 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1445 if ( !isset( $child->name ) ) {
1446 continue;
1447 }
1448 if ( $child->name === 'name' ) {
1449 $bits['name'] = $child;
1450 if ( $child->firstChild instanceof PPNode_Hash_Attr
1451 && $child->firstChild->name === 'index' )
1452 {
1453 $bits['index'] = $child->firstChild->value;
1454 }
1455 } elseif ( $child->name === 'value' ) {
1456 $bits['value'] = $child;
1457 }
1458 }
1459
1460 if ( !isset( $bits['name'] ) ) {
1461 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1462 }
1463 if ( !isset( $bits['index'] ) ) {
1464 $bits['index'] = '';
1465 }
1466 return $bits;
1467 }
1468
1469 /**
1470 * Split an <ext> node into an associative array containing name, attr, inner and close
1471 * All values in the resulting array are PPNodes. Inner and close are optional.
1472 */
1473 function splitExt() {
1474 $bits = array();
1475 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1476 if ( !isset( $child->name ) ) {
1477 continue;
1478 }
1479 if ( $child->name == 'name' ) {
1480 $bits['name'] = $child;
1481 } elseif ( $child->name == 'attr' ) {
1482 $bits['attr'] = $child;
1483 } elseif ( $child->name == 'inner' ) {
1484 $bits['inner'] = $child;
1485 } elseif ( $child->name == 'close' ) {
1486 $bits['close'] = $child;
1487 }
1488 }
1489 if ( !isset( $bits['name'] ) ) {
1490 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1491 }
1492 return $bits;
1493 }
1494
1495 /**
1496 * Split an <h> node
1497 */
1498 function splitHeading() {
1499 if ( $this->name !== 'h' ) {
1500 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1501 }
1502 $bits = array();
1503 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1504 if ( !isset( $child->name ) ) {
1505 continue;
1506 }
1507 if ( $child->name == 'i' ) {
1508 $bits['i'] = $child->value;
1509 } elseif ( $child->name == 'level' ) {
1510 $bits['level'] = $child->value;
1511 }
1512 }
1513 if ( !isset( $bits['i'] ) ) {
1514 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1515 }
1516 return $bits;
1517 }
1518
1519 /**
1520 * Split a <template> or <tplarg> node
1521 */
1522 function splitTemplate() {
1523 $parts = array();
1524 $bits = array( 'lineStart' => '' );
1525 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1526 if ( !isset( $child->name ) ) {
1527 continue;
1528 }
1529 if ( $child->name == 'title' ) {
1530 $bits['title'] = $child;
1531 }
1532 if ( $child->name == 'part' ) {
1533 $parts[] = $child;
1534 }
1535 if ( $child->name == 'lineStart' ) {
1536 $bits['lineStart'] = '1';
1537 }
1538 }
1539 if ( !isset( $bits['title'] ) ) {
1540 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1541 }
1542 $bits['parts'] = new PPNode_Hash_Array( $parts );
1543 return $bits;
1544 }
1545 }
1546
1547 /**
1548 * @ingroup Parser
1549 */
1550 class PPNode_Hash_Text implements PPNode {
1551 var $value, $nextSibling;
1552
1553 function __construct( $value ) {
1554 if ( is_object( $value ) ) {
1555 throw new MWException( __CLASS__ . ' given object instead of string' );
1556 }
1557 $this->value = $value;
1558 }
1559
1560 function __toString() {
1561 return htmlspecialchars( $this->value );
1562 }
1563
1564 function getNextSibling() {
1565 return $this->nextSibling;
1566 }
1567
1568 function getChildren() { return false; }
1569 function getFirstChild() { return false; }
1570 function getChildrenOfType( $name ) { return false; }
1571 function getLength() { return false; }
1572 function item( $i ) { return false; }
1573 function getName() { return '#text'; }
1574 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1575 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1576 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1577 }
1578
1579 /**
1580 * @ingroup Parser
1581 */
1582 class PPNode_Hash_Array implements PPNode {
1583 var $value, $nextSibling;
1584
1585 function __construct( $value ) {
1586 $this->value = $value;
1587 }
1588
1589 function __toString() {
1590 return var_export( $this, true );
1591 }
1592
1593 function getLength() {
1594 return count( $this->value );
1595 }
1596
1597 function item( $i ) {
1598 return $this->value[$i];
1599 }
1600
1601 function getName() { return '#nodelist'; }
1602
1603 function getNextSibling() {
1604 return $this->nextSibling;
1605 }
1606
1607 function getChildren() { return false; }
1608 function getFirstChild() { return false; }
1609 function getChildrenOfType( $name ) { return false; }
1610 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1611 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1612 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1613 }
1614
1615 /**
1616 * @ingroup Parser
1617 */
1618 class PPNode_Hash_Attr implements PPNode {
1619 var $name, $value, $nextSibling;
1620
1621 function __construct( $name, $value ) {
1622 $this->name = $name;
1623 $this->value = $value;
1624 }
1625
1626 function __toString() {
1627 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1628 }
1629
1630 function getName() {
1631 return $this->name;
1632 }
1633
1634 function getNextSibling() {
1635 return $this->nextSibling;
1636 }
1637
1638 function getChildren() { return false; }
1639 function getFirstChild() { return false; }
1640 function getChildrenOfType( $name ) { return false; }
1641 function getLength() { return false; }
1642 function item( $i ) { return false; }
1643 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1644 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1645 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1646 }