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