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