Merge "Begin exposing SiteConfiguration via site contexts"
[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 $args array
51 * @return PPCustomFrame_Hash
52 */
53 function newCustomFrame( $args ) {
54 return new PPCustomFrame_Hash( $this, $args );
55 }
56
57 /**
58 * @param $values array
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 $flags Integer: bitwise combination of:
94 * Parser::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
95 * included. Default is to assume a direct page view.
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 }
444
445 elseif ( $found == 'line-start' ) {
446 // Is this the start of a heading?
447 // Line break belongs before the heading element in any case
448 if ( $fakeLineStart ) {
449 $fakeLineStart = false;
450 } else {
451 $accum->addLiteral( $curChar );
452 $i++;
453 }
454
455 $count = strspn( $text, '=', $i, 6 );
456 if ( $count == 1 && $findEquals ) {
457 // DWIM: This looks kind of like a name/value separator
458 // Let's let the equals handler have it and break the potential heading
459 // This is heuristic, but AFAICT the methods for completely correct disambiguation are very complex.
460 } elseif ( $count > 0 ) {
461 $piece = array(
462 'open' => "\n",
463 'close' => "\n",
464 'parts' => array( new PPDPart_Hash( str_repeat( '=', $count ) ) ),
465 'startPos' => $i,
466 'count' => $count );
467 $stack->push( $piece );
468 $accum =& $stack->getAccum();
469 extract( $stack->getFlags() );
470 $i += $count;
471 }
472 } elseif ( $found == 'line-end' ) {
473 $piece = $stack->top;
474 // A heading must be open, otherwise \n wouldn't have been in the search list
475 assert( '$piece->open == "\n"' );
476 $part = $piece->getCurrentPart();
477 // Search back through the input to see if it has a proper close
478 // Do this using the reversed string since the other solutions (end anchor, etc.) are inefficient
479 $wsLength = strspn( $revText, " \t", $lengthText - $i );
480 $searchStart = $i - $wsLength;
481 if ( isset( $part->commentEnd ) && $searchStart - 1 == $part->commentEnd ) {
482 // Comment found at line end
483 // Search for equals signs before the comment
484 $searchStart = $part->visualEnd;
485 $searchStart -= strspn( $revText, " \t", $lengthText - $searchStart );
486 }
487 $count = $piece->count;
488 $equalsLength = strspn( $revText, '=', $lengthText - $searchStart );
489 if ( $equalsLength > 0 ) {
490 if ( $searchStart - $equalsLength == $piece->startPos ) {
491 // This is just a single string of equals signs on its own line
492 // Replicate the doHeadings behavior /={count}(.+)={count}/
493 // First find out how many equals signs there really are (don't stop at 6)
494 $count = $equalsLength;
495 if ( $count < 3 ) {
496 $count = 0;
497 } else {
498 $count = min( 6, intval( ( $count - 1 ) / 2 ) );
499 }
500 } else {
501 $count = min( $equalsLength, $count );
502 }
503 if ( $count > 0 ) {
504 // Normal match, output <h>
505 $element = new PPNode_Hash_Tree( 'possible-h' );
506 $element->addChild( new PPNode_Hash_Attr( 'level', $count ) );
507 $element->addChild( new PPNode_Hash_Attr( 'i', $headingIndex++ ) );
508 $element->lastChild->nextSibling = $accum->firstNode;
509 $element->lastChild = $accum->lastNode;
510 } else {
511 // Single equals sign on its own line, count=0
512 $element = $accum;
513 }
514 } else {
515 // No match, no <h>, just pass down the inner text
516 $element = $accum;
517 }
518 // Unwind the stack
519 $stack->pop();
520 $accum =& $stack->getAccum();
521 extract( $stack->getFlags() );
522
523 // Append the result to the enclosing accumulator
524 if ( $element instanceof PPNode ) {
525 $accum->addNode( $element );
526 } else {
527 $accum->addAccum( $element );
528 }
529 // Note that we do NOT increment the input pointer.
530 // This is because the closing linebreak could be the opening linebreak of
531 // another heading. Infinite loops are avoided because the next iteration MUST
532 // hit the heading open case above, which unconditionally increments the
533 // input pointer.
534 } elseif ( $found == 'open' ) {
535 # count opening brace characters
536 $count = strspn( $text, $curChar, $i );
537
538 # we need to add to stack only if opening brace count is enough for one of the rules
539 if ( $count >= $rule['min'] ) {
540 # Add it to the stack
541 $piece = array(
542 'open' => $curChar,
543 'close' => $rule['end'],
544 'count' => $count,
545 'lineStart' => ( $i > 0 && $text[$i - 1] == "\n" ),
546 );
547
548 $stack->push( $piece );
549 $accum =& $stack->getAccum();
550 extract( $stack->getFlags() );
551 } else {
552 # Add literal brace(s)
553 $accum->addLiteral( str_repeat( $curChar, $count ) );
554 }
555 $i += $count;
556 } elseif ( $found == 'close' ) {
557 $piece = $stack->top;
558 # lets check if there are enough characters for closing brace
559 $maxCount = $piece->count;
560 $count = strspn( $text, $curChar, $i, $maxCount );
561
562 # check for maximum matching characters (if there are 5 closing
563 # characters, we will probably need only 3 - depending on the rules)
564 $rule = $rules[$piece->open];
565 if ( $count > $rule['max'] ) {
566 # The specified maximum exists in the callback array, unless the caller
567 # has made an error
568 $matchingCount = $rule['max'];
569 } else {
570 # Count is less than the maximum
571 # Skip any gaps in the callback array to find the true largest match
572 # Need to use array_key_exists not isset because the callback can be null
573 $matchingCount = $count;
574 while ( $matchingCount > 0 && !array_key_exists( $matchingCount, $rule['names'] ) ) {
575 --$matchingCount;
576 }
577 }
578
579 if ( $matchingCount <= 0 ) {
580 # No matching element found in callback array
581 # Output a literal closing brace and continue
582 $accum->addLiteral( str_repeat( $curChar, $count ) );
583 $i += $count;
584 continue;
585 }
586 $name = $rule['names'][$matchingCount];
587 if ( $name === null ) {
588 // No element, just literal text
589 $element = $piece->breakSyntax( $matchingCount );
590 $element->addLiteral( str_repeat( $rule['end'], $matchingCount ) );
591 } else {
592 # Create XML element
593 # Note: $parts is already XML, does not need to be encoded further
594 $parts = $piece->parts;
595 $titleAccum = $parts[0]->out;
596 unset( $parts[0] );
597
598 $element = new PPNode_Hash_Tree( $name );
599
600 # The invocation is at the start of the line if lineStart is set in
601 # the stack, and all opening brackets are used up.
602 if ( $maxCount == $matchingCount && !empty( $piece->lineStart ) ) {
603 $element->addChild( new PPNode_Hash_Attr( 'lineStart', 1 ) );
604 }
605 $titleNode = new PPNode_Hash_Tree( 'title' );
606 $titleNode->firstChild = $titleAccum->firstNode;
607 $titleNode->lastChild = $titleAccum->lastNode;
608 $element->addChild( $titleNode );
609 $argIndex = 1;
610 foreach ( $parts as $part ) {
611 if ( isset( $part->eqpos ) ) {
612 // Find equals
613 $lastNode = false;
614 for ( $node = $part->out->firstNode; $node; $node = $node->nextSibling ) {
615 if ( $node === $part->eqpos ) {
616 break;
617 }
618 $lastNode = $node;
619 }
620 if ( !$node ) {
621 if ( $cacheable ) {
622 wfProfileOut( __METHOD__ . '-cache-miss' );
623 wfProfileOut( __METHOD__ . '-cacheable' );
624 }
625 wfProfileOut( __METHOD__ );
626 throw new MWException( __METHOD__ . ': eqpos not found' );
627 }
628 if ( $node->name !== 'equals' ) {
629 if ( $cacheable ) {
630 wfProfileOut( __METHOD__ . '-cache-miss' );
631 wfProfileOut( __METHOD__ . '-cacheable' );
632 }
633 wfProfileOut( __METHOD__ );
634 throw new MWException( __METHOD__ . ': eqpos is not equals' );
635 }
636 $equalsNode = $node;
637
638 // Construct name node
639 $nameNode = new PPNode_Hash_Tree( 'name' );
640 if ( $lastNode !== false ) {
641 $lastNode->nextSibling = false;
642 $nameNode->firstChild = $part->out->firstNode;
643 $nameNode->lastChild = $lastNode;
644 }
645
646 // Construct value node
647 $valueNode = new PPNode_Hash_Tree( 'value' );
648 if ( $equalsNode->nextSibling !== false ) {
649 $valueNode->firstChild = $equalsNode->nextSibling;
650 $valueNode->lastChild = $part->out->lastNode;
651 }
652 $partNode = new PPNode_Hash_Tree( 'part' );
653 $partNode->addChild( $nameNode );
654 $partNode->addChild( $equalsNode->firstChild );
655 $partNode->addChild( $valueNode );
656 $element->addChild( $partNode );
657 } else {
658 $partNode = new PPNode_Hash_Tree( 'part' );
659 $nameNode = new PPNode_Hash_Tree( 'name' );
660 $nameNode->addChild( new PPNode_Hash_Attr( 'index', $argIndex++ ) );
661 $valueNode = new PPNode_Hash_Tree( 'value' );
662 $valueNode->firstChild = $part->out->firstNode;
663 $valueNode->lastChild = $part->out->lastNode;
664 $partNode->addChild( $nameNode );
665 $partNode->addChild( $valueNode );
666 $element->addChild( $partNode );
667 }
668 }
669 }
670
671 # Advance input pointer
672 $i += $matchingCount;
673
674 # Unwind the stack
675 $stack->pop();
676 $accum =& $stack->getAccum();
677
678 # Re-add the old stack element if it still has unmatched opening characters remaining
679 if ( $matchingCount < $piece->count ) {
680 $piece->parts = array( new PPDPart_Hash );
681 $piece->count -= $matchingCount;
682 # do we still qualify for any callback with remaining count?
683 $min = $rules[$piece->open]['min'];
684 if ( $piece->count >= $min ) {
685 $stack->push( $piece );
686 $accum =& $stack->getAccum();
687 } else {
688 $accum->addLiteral( str_repeat( $piece->open, $piece->count ) );
689 }
690 }
691
692 extract( $stack->getFlags() );
693
694 # Add XML element to the enclosing accumulator
695 if ( $element instanceof PPNode ) {
696 $accum->addNode( $element );
697 } else {
698 $accum->addAccum( $element );
699 }
700 } elseif ( $found == 'pipe' ) {
701 $findEquals = true; // shortcut for getFlags()
702 $stack->addPart();
703 $accum =& $stack->getAccum();
704 ++$i;
705 } elseif ( $found == 'equals' ) {
706 $findEquals = false; // shortcut for getFlags()
707 $accum->addNodeWithText( 'equals', '=' );
708 $stack->getCurrentPart()->eqpos = $accum->lastNode;
709 ++$i;
710 }
711 }
712
713 # Output any remaining unclosed brackets
714 foreach ( $stack->stack as $piece ) {
715 $stack->rootAccum->addAccum( $piece->breakSyntax() );
716 }
717
718 # Enable top-level headings
719 for ( $node = $stack->rootAccum->firstNode; $node; $node = $node->nextSibling ) {
720 if ( isset( $node->name ) && $node->name === 'possible-h' ) {
721 $node->name = 'h';
722 }
723 }
724
725 $rootNode = new PPNode_Hash_Tree( 'root' );
726 $rootNode->firstChild = $stack->rootAccum->firstNode;
727 $rootNode->lastChild = $stack->rootAccum->lastNode;
728
729 // Cache
730 if ( $cacheable ) {
731 $cacheValue = sprintf( "%08d", self::CACHE_VERSION ) . serialize( $rootNode );
732 $wgMemc->set( $cacheKey, $cacheValue, 86400 );
733 wfProfileOut( __METHOD__ . '-cache-miss' );
734 wfProfileOut( __METHOD__ . '-cacheable' );
735 wfDebugLog( "Preprocessor", "Saved preprocessor Hash to memcached (key $cacheKey)" );
736 }
737
738 wfProfileOut( __METHOD__ );
739 return $rootNode;
740 }
741 }
742
743 /**
744 * Stack class to help Preprocessor::preprocessToObj()
745 * @ingroup Parser
746 */
747 class PPDStack_Hash extends PPDStack {
748 function __construct() {
749 $this->elementClass = 'PPDStackElement_Hash';
750 parent::__construct();
751 $this->rootAccum = new PPDAccum_Hash;
752 }
753 }
754
755 /**
756 * @ingroup Parser
757 */
758 class PPDStackElement_Hash extends PPDStackElement {
759 function __construct( $data = array() ) {
760 $this->partClass = 'PPDPart_Hash';
761 parent::__construct( $data );
762 }
763
764 /**
765 * Get the accumulator that would result if the close is not found.
766 *
767 * @return PPDAccum_Hash
768 */
769 function breakSyntax( $openingCount = false ) {
770 if ( $this->open == "\n" ) {
771 $accum = $this->parts[0]->out;
772 } else {
773 if ( $openingCount === false ) {
774 $openingCount = $this->count;
775 }
776 $accum = new PPDAccum_Hash;
777 $accum->addLiteral( str_repeat( $this->open, $openingCount ) );
778 $first = true;
779 foreach ( $this->parts as $part ) {
780 if ( $first ) {
781 $first = false;
782 } else {
783 $accum->addLiteral( '|' );
784 }
785 $accum->addAccum( $part->out );
786 }
787 }
788 return $accum;
789 }
790 }
791
792 /**
793 * @ingroup Parser
794 */
795 class PPDPart_Hash extends PPDPart {
796 function __construct( $out = '' ) {
797 $accum = new PPDAccum_Hash;
798 if ( $out !== '' ) {
799 $accum->addLiteral( $out );
800 }
801 parent::__construct( $accum );
802 }
803 }
804
805 /**
806 * @ingroup Parser
807 */
808 class PPDAccum_Hash {
809 var $firstNode, $lastNode;
810
811 function __construct() {
812 $this->firstNode = $this->lastNode = false;
813 }
814
815 /**
816 * Append a string literal
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 */
832 function addNode( PPNode $node ) {
833 if ( $this->lastNode === false ) {
834 $this->firstNode = $this->lastNode = $node;
835 } else {
836 $this->lastNode->nextSibling = $node;
837 $this->lastNode = $node;
838 }
839 }
840
841 /**
842 * Append a tree node with text contents
843 */
844 function addNodeWithText( $name, $value ) {
845 $node = PPNode_Hash_Tree::newWithText( $name, $value );
846 $this->addNode( $node );
847 }
848
849 /**
850 * Append a PPAccum_Hash
851 * Takes over ownership of the nodes in the source argument. These nodes may
852 * subsequently be modified, especially nextSibling.
853 */
854 function addAccum( $accum ) {
855 if ( $accum->lastNode === false ) {
856 // nothing to add
857 } elseif ( $this->lastNode === false ) {
858 $this->firstNode = $accum->firstNode;
859 $this->lastNode = $accum->lastNode;
860 } else {
861 $this->lastNode->nextSibling = $accum->firstNode;
862 $this->lastNode = $accum->lastNode;
863 }
864 }
865 }
866
867 /**
868 * An expansion frame, used as a context to expand the result of preprocessToObj()
869 * @ingroup Parser
870 */
871 class PPFrame_Hash implements PPFrame {
872
873 /**
874 * @var Parser
875 */
876 var $parser;
877
878 /**
879 * @var Preprocessor
880 */
881 var $preprocessor;
882
883 /**
884 * @var Title
885 */
886 var $title;
887 var $titleCache;
888
889 /**
890 * Hashtable listing templates which are disallowed for expansion in this frame,
891 * having been encountered previously in parent frames.
892 */
893 var $loopCheckHash;
894
895 /**
896 * Recursion depth of this frame, top = 0
897 * Note that this is NOT the same as expansion depth in expand()
898 */
899 var $depth;
900
901 /**
902 * Construct a new preprocessor frame.
903 * @param $preprocessor Preprocessor: the parent preprocessor
904 */
905 function __construct( $preprocessor ) {
906 $this->preprocessor = $preprocessor;
907 $this->parser = $preprocessor->parser;
908 $this->title = $this->parser->mTitle;
909 $this->titleCache = array( $this->title ? $this->title->getPrefixedDBkey() : false );
910 $this->loopCheckHash = array();
911 $this->depth = 0;
912 }
913
914 /**
915 * Create a new child frame
916 * $args is optionally a multi-root PPNode or array containing the template arguments
917 *
918 * @param array|bool|\PPNode_Hash_Array $args PPNode_Hash_Array|array
919 * @param $title Title|bool
920 *
921 * @param int $indexOffset
922 * @throws MWException
923 * @return PPTemplateFrame_Hash
924 */
925 function newChild( $args = false, $title = false, $indexOffset = 0 ) {
926 $namedArgs = array();
927 $numberedArgs = array();
928 if ( $title === false ) {
929 $title = $this->title;
930 }
931 if ( $args !== false ) {
932 if ( $args instanceof PPNode_Hash_Array ) {
933 $args = $args->value;
934 } elseif ( !is_array( $args ) ) {
935 throw new MWException( __METHOD__ . ': $args must be array or PPNode_Hash_Array' );
936 }
937 foreach ( $args as $arg ) {
938 $bits = $arg->splitArg();
939 if ( $bits['index'] !== '' ) {
940 // Numbered parameter
941 $index = $bits['index'] - $indexOffset;
942 $numberedArgs[$index] = $bits['value'];
943 unset( $namedArgs[$index] );
944 } else {
945 // Named parameter
946 $name = trim( $this->expand( $bits['name'], PPFrame::STRIP_COMMENTS ) );
947 $namedArgs[$name] = $bits['value'];
948 unset( $numberedArgs[$name] );
949 }
950 }
951 }
952 return new PPTemplateFrame_Hash( $this->preprocessor, $this, $numberedArgs, $namedArgs, $title );
953 }
954
955 /**
956 * @throws MWException
957 * @param $root
958 * @param $flags int
959 * @return string
960 */
961 function expand( $root, $flags = 0 ) {
962 static $expansionDepth = 0;
963 if ( is_string( $root ) ) {
964 return $root;
965 }
966
967 if ( ++$this->parser->mPPNodeCount > $this->parser->mOptions->getMaxPPNodeCount() ) {
968 $this->parser->limitationWarn( 'node-count-exceeded',
969 $this->parser->mPPNodeCount,
970 $this->parser->mOptions->getMaxPPNodeCount()
971 );
972 return '<span class="error">Node-count limit exceeded</span>';
973 }
974 if ( $expansionDepth > $this->parser->mOptions->getMaxPPExpandDepth() ) {
975 $this->parser->limitationWarn( 'expansion-depth-exceeded',
976 $expansionDepth,
977 $this->parser->mOptions->getMaxPPExpandDepth()
978 );
979 return '<span class="error">Expansion depth limit exceeded</span>';
980 }
981 ++$expansionDepth;
982 if ( $expansionDepth > $this->parser->mHighestExpansionDepth ) {
983 $this->parser->mHighestExpansionDepth = $expansionDepth;
984 }
985
986 $outStack = array( '', '' );
987 $iteratorStack = array( false, $root );
988 $indexStack = array( 0, 0 );
989
990 while ( count( $iteratorStack ) > 1 ) {
991 $level = count( $outStack ) - 1;
992 $iteratorNode =& $iteratorStack[$level];
993 $out =& $outStack[$level];
994 $index =& $indexStack[$level];
995
996 if ( is_array( $iteratorNode ) ) {
997 if ( $index >= count( $iteratorNode ) ) {
998 // All done with this iterator
999 $iteratorStack[$level] = false;
1000 $contextNode = false;
1001 } else {
1002 $contextNode = $iteratorNode[$index];
1003 $index++;
1004 }
1005 } elseif ( $iteratorNode instanceof PPNode_Hash_Array ) {
1006 if ( $index >= $iteratorNode->getLength() ) {
1007 // All done with this iterator
1008 $iteratorStack[$level] = false;
1009 $contextNode = false;
1010 } else {
1011 $contextNode = $iteratorNode->item( $index );
1012 $index++;
1013 }
1014 } else {
1015 // Copy to $contextNode and then delete from iterator stack,
1016 // because this is not an iterator but we do have to execute it once
1017 $contextNode = $iteratorStack[$level];
1018 $iteratorStack[$level] = false;
1019 }
1020
1021 $newIterator = false;
1022
1023 if ( $contextNode === false ) {
1024 // nothing to do
1025 } elseif ( is_string( $contextNode ) ) {
1026 $out .= $contextNode;
1027 } elseif ( is_array( $contextNode ) || $contextNode instanceof PPNode_Hash_Array ) {
1028 $newIterator = $contextNode;
1029 } elseif ( $contextNode instanceof PPNode_Hash_Attr ) {
1030 // No output
1031 } elseif ( $contextNode instanceof PPNode_Hash_Text ) {
1032 $out .= $contextNode->value;
1033 } elseif ( $contextNode instanceof PPNode_Hash_Tree ) {
1034 if ( $contextNode->name == 'template' ) {
1035 # Double-brace expansion
1036 $bits = $contextNode->splitTemplate();
1037 if ( $flags & PPFrame::NO_TEMPLATES ) {
1038 $newIterator = $this->virtualBracketedImplode( '{{', '|', '}}', $bits['title'], $bits['parts'] );
1039 } else {
1040 $ret = $this->parser->braceSubstitution( $bits, $this );
1041 if ( isset( $ret['object'] ) ) {
1042 $newIterator = $ret['object'];
1043 } else {
1044 $out .= $ret['text'];
1045 }
1046 }
1047 } elseif ( $contextNode->name == 'tplarg' ) {
1048 # Triple-brace expansion
1049 $bits = $contextNode->splitTemplate();
1050 if ( $flags & PPFrame::NO_ARGS ) {
1051 $newIterator = $this->virtualBracketedImplode( '{{{', '|', '}}}', $bits['title'], $bits['parts'] );
1052 } else {
1053 $ret = $this->parser->argSubstitution( $bits, $this );
1054 if ( isset( $ret['object'] ) ) {
1055 $newIterator = $ret['object'];
1056 } else {
1057 $out .= $ret['text'];
1058 }
1059 }
1060 } elseif ( $contextNode->name == 'comment' ) {
1061 # HTML-style comment
1062 # Remove it in HTML, pre+remove and STRIP_COMMENTS modes
1063 if ( $this->parser->ot['html']
1064 || ( $this->parser->ot['pre'] && $this->parser->mOptions->getRemoveComments() )
1065 || ( $flags & PPFrame::STRIP_COMMENTS )
1066 ) {
1067 $out .= '';
1068 }
1069 # Add a strip marker in PST mode so that pstPass2() can run some old-fashioned regexes on the result
1070 # Not in RECOVER_COMMENTS mode (extractSections) though
1071 elseif ( $this->parser->ot['wiki'] && !( $flags & PPFrame::RECOVER_COMMENTS ) ) {
1072 $out .= $this->parser->insertStripItem( $contextNode->firstChild->value );
1073 }
1074 # Recover the literal comment in RECOVER_COMMENTS and pre+no-remove
1075 else {
1076 $out .= $contextNode->firstChild->value;
1077 }
1078 } elseif ( $contextNode->name == 'ignore' ) {
1079 # Output suppression used by <includeonly> etc.
1080 # OT_WIKI will only respect <ignore> in substed templates.
1081 # The other output types respect it unless NO_IGNORE is set.
1082 # extractSections() sets NO_IGNORE and so never respects it.
1083 if ( ( !isset( $this->parent ) && $this->parser->ot['wiki'] ) || ( $flags & PPFrame::NO_IGNORE ) ) {
1084 $out .= $contextNode->firstChild->value;
1085 } else {
1086 //$out .= '';
1087 }
1088 } elseif ( $contextNode->name == 'ext' ) {
1089 # Extension tag
1090 $bits = $contextNode->splitExt() + array( 'attr' => null, 'inner' => null, 'close' => null );
1091 $out .= $this->parser->extensionSubstitution( $bits, $this );
1092 } elseif ( $contextNode->name == 'h' ) {
1093 # Heading
1094 if ( $this->parser->ot['html'] ) {
1095 # Expand immediately and insert heading index marker
1096 $s = '';
1097 for ( $node = $contextNode->firstChild; $node; $node = $node->nextSibling ) {
1098 $s .= $this->expand( $node, $flags );
1099 }
1100
1101 $bits = $contextNode->splitHeading();
1102 $titleText = $this->title->getPrefixedDBkey();
1103 $this->parser->mHeadings[] = array( $titleText, $bits['i'] );
1104 $serial = count( $this->parser->mHeadings ) - 1;
1105 $marker = "{$this->parser->mUniqPrefix}-h-$serial-" . Parser::MARKER_SUFFIX;
1106 $s = substr( $s, 0, $bits['level'] ) . $marker . substr( $s, $bits['level'] );
1107 $this->parser->mStripState->addGeneral( $marker, '' );
1108 $out .= $s;
1109 } else {
1110 # Expand in virtual stack
1111 $newIterator = $contextNode->getChildren();
1112 }
1113 } else {
1114 # Generic recursive expansion
1115 $newIterator = $contextNode->getChildren();
1116 }
1117 } else {
1118 throw new MWException( __METHOD__ . ': Invalid parameter type' );
1119 }
1120
1121 if ( $newIterator !== false ) {
1122 $outStack[] = '';
1123 $iteratorStack[] = $newIterator;
1124 $indexStack[] = 0;
1125 } elseif ( $iteratorStack[$level] === false ) {
1126 // Return accumulated value to parent
1127 // With tail recursion
1128 while ( $iteratorStack[$level] === false && $level > 0 ) {
1129 $outStack[$level - 1] .= $out;
1130 array_pop( $outStack );
1131 array_pop( $iteratorStack );
1132 array_pop( $indexStack );
1133 $level--;
1134 }
1135 }
1136 }
1137 --$expansionDepth;
1138 return $outStack[0];
1139 }
1140
1141 /**
1142 * @param $sep
1143 * @param $flags
1144 * @return string
1145 */
1146 function implodeWithFlags( $sep, $flags /*, ... */ ) {
1147 $args = array_slice( func_get_args(), 2 );
1148
1149 $first = true;
1150 $s = '';
1151 foreach ( $args as $root ) {
1152 if ( $root instanceof PPNode_Hash_Array ) {
1153 $root = $root->value;
1154 }
1155 if ( !is_array( $root ) ) {
1156 $root = array( $root );
1157 }
1158 foreach ( $root as $node ) {
1159 if ( $first ) {
1160 $first = false;
1161 } else {
1162 $s .= $sep;
1163 }
1164 $s .= $this->expand( $node, $flags );
1165 }
1166 }
1167 return $s;
1168 }
1169
1170 /**
1171 * Implode with no flags specified
1172 * This previously called implodeWithFlags but has now been inlined to reduce stack depth
1173 * @return string
1174 */
1175 function implode( $sep /*, ... */ ) {
1176 $args = array_slice( func_get_args(), 1 );
1177
1178 $first = true;
1179 $s = '';
1180 foreach ( $args as $root ) {
1181 if ( $root instanceof PPNode_Hash_Array ) {
1182 $root = $root->value;
1183 }
1184 if ( !is_array( $root ) ) {
1185 $root = array( $root );
1186 }
1187 foreach ( $root as $node ) {
1188 if ( $first ) {
1189 $first = false;
1190 } else {
1191 $s .= $sep;
1192 }
1193 $s .= $this->expand( $node );
1194 }
1195 }
1196 return $s;
1197 }
1198
1199 /**
1200 * Makes an object that, when expand()ed, will be the same as one obtained
1201 * with implode()
1202 *
1203 * @return PPNode_Hash_Array
1204 */
1205 function virtualImplode( $sep /*, ... */ ) {
1206 $args = array_slice( func_get_args(), 1 );
1207 $out = array();
1208 $first = true;
1209
1210 foreach ( $args as $root ) {
1211 if ( $root instanceof PPNode_Hash_Array ) {
1212 $root = $root->value;
1213 }
1214 if ( !is_array( $root ) ) {
1215 $root = array( $root );
1216 }
1217 foreach ( $root as $node ) {
1218 if ( $first ) {
1219 $first = false;
1220 } else {
1221 $out[] = $sep;
1222 }
1223 $out[] = $node;
1224 }
1225 }
1226 return new PPNode_Hash_Array( $out );
1227 }
1228
1229 /**
1230 * Virtual implode with brackets
1231 *
1232 * @return PPNode_Hash_Array
1233 */
1234 function virtualBracketedImplode( $start, $sep, $end /*, ... */ ) {
1235 $args = array_slice( func_get_args(), 3 );
1236 $out = array( $start );
1237 $first = true;
1238
1239 foreach ( $args as $root ) {
1240 if ( $root instanceof PPNode_Hash_Array ) {
1241 $root = $root->value;
1242 }
1243 if ( !is_array( $root ) ) {
1244 $root = array( $root );
1245 }
1246 foreach ( $root as $node ) {
1247 if ( $first ) {
1248 $first = false;
1249 } else {
1250 $out[] = $sep;
1251 }
1252 $out[] = $node;
1253 }
1254 }
1255 $out[] = $end;
1256 return new PPNode_Hash_Array( $out );
1257 }
1258
1259 function __toString() {
1260 return 'frame{}';
1261 }
1262
1263 /**
1264 * @param $level bool
1265 * @return array|bool|String
1266 */
1267 function getPDBK( $level = false ) {
1268 if ( $level === false ) {
1269 return $this->title->getPrefixedDBkey();
1270 } else {
1271 return isset( $this->titleCache[$level] ) ? $this->titleCache[$level] : false;
1272 }
1273 }
1274
1275 /**
1276 * @return array
1277 */
1278 function getArguments() {
1279 return array();
1280 }
1281
1282 /**
1283 * @return array
1284 */
1285 function getNumberedArguments() {
1286 return array();
1287 }
1288
1289 /**
1290 * @return array
1291 */
1292 function getNamedArguments() {
1293 return array();
1294 }
1295
1296 /**
1297 * Returns true if there are no arguments in this frame
1298 *
1299 * @return bool
1300 */
1301 function isEmpty() {
1302 return true;
1303 }
1304
1305 /**
1306 * @param $name
1307 * @return bool
1308 */
1309 function getArgument( $name ) {
1310 return false;
1311 }
1312
1313 /**
1314 * Returns true if the infinite loop check is OK, false if a loop is detected
1315 *
1316 * @param $title Title
1317 *
1318 * @return bool
1319 */
1320 function loopCheck( $title ) {
1321 return !isset( $this->loopCheckHash[$title->getPrefixedDBkey()] );
1322 }
1323
1324 /**
1325 * Return true if the frame is a template frame
1326 *
1327 * @return bool
1328 */
1329 function isTemplate() {
1330 return false;
1331 }
1332
1333 /**
1334 * Get a title of frame
1335 *
1336 * @return Title
1337 */
1338 function getTitle() {
1339 return $this->title;
1340 }
1341 }
1342
1343 /**
1344 * Expansion frame with template arguments
1345 * @ingroup Parser
1346 */
1347 class PPTemplateFrame_Hash extends PPFrame_Hash {
1348 var $numberedArgs, $namedArgs, $parent;
1349 var $numberedExpansionCache, $namedExpansionCache;
1350
1351 /**
1352 * @param $preprocessor
1353 * @param $parent
1354 * @param $numberedArgs array
1355 * @param $namedArgs array
1356 * @param $title Title
1357 */
1358 function __construct( $preprocessor, $parent = false, $numberedArgs = array(), $namedArgs = array(), $title = false ) {
1359 parent::__construct( $preprocessor );
1360
1361 $this->parent = $parent;
1362 $this->numberedArgs = $numberedArgs;
1363 $this->namedArgs = $namedArgs;
1364 $this->title = $title;
1365 $pdbk = $title ? $title->getPrefixedDBkey() : false;
1366 $this->titleCache = $parent->titleCache;
1367 $this->titleCache[] = $pdbk;
1368 $this->loopCheckHash = /*clone*/ $parent->loopCheckHash;
1369 if ( $pdbk !== false ) {
1370 $this->loopCheckHash[$pdbk] = true;
1371 }
1372 $this->depth = $parent->depth + 1;
1373 $this->numberedExpansionCache = $this->namedExpansionCache = array();
1374 }
1375
1376 function __toString() {
1377 $s = 'tplframe{';
1378 $first = true;
1379 $args = $this->numberedArgs + $this->namedArgs;
1380 foreach ( $args as $name => $value ) {
1381 if ( $first ) {
1382 $first = false;
1383 } else {
1384 $s .= ', ';
1385 }
1386 $s .= "\"$name\":\"" .
1387 str_replace( '"', '\\"', $value->__toString() ) . '"';
1388 }
1389 $s .= '}';
1390 return $s;
1391 }
1392 /**
1393 * Returns true if there are no arguments in this frame
1394 *
1395 * @return bool
1396 */
1397 function isEmpty() {
1398 return !count( $this->numberedArgs ) && !count( $this->namedArgs );
1399 }
1400
1401 /**
1402 * @return array
1403 */
1404 function getArguments() {
1405 $arguments = array();
1406 foreach ( array_merge(
1407 array_keys( $this->numberedArgs ),
1408 array_keys( $this->namedArgs ) ) as $key ) {
1409 $arguments[$key] = $this->getArgument( $key );
1410 }
1411 return $arguments;
1412 }
1413
1414 /**
1415 * @return array
1416 */
1417 function getNumberedArguments() {
1418 $arguments = array();
1419 foreach ( array_keys( $this->numberedArgs ) as $key ) {
1420 $arguments[$key] = $this->getArgument( $key );
1421 }
1422 return $arguments;
1423 }
1424
1425 /**
1426 * @return array
1427 */
1428 function getNamedArguments() {
1429 $arguments = array();
1430 foreach ( array_keys( $this->namedArgs ) as $key ) {
1431 $arguments[$key] = $this->getArgument( $key );
1432 }
1433 return $arguments;
1434 }
1435
1436 /**
1437 * @param $index
1438 * @return array|bool
1439 */
1440 function getNumberedArgument( $index ) {
1441 if ( !isset( $this->numberedArgs[$index] ) ) {
1442 return false;
1443 }
1444 if ( !isset( $this->numberedExpansionCache[$index] ) ) {
1445 # No trimming for unnamed arguments
1446 $this->numberedExpansionCache[$index] = $this->parent->expand( $this->numberedArgs[$index], PPFrame::STRIP_COMMENTS );
1447 }
1448 return $this->numberedExpansionCache[$index];
1449 }
1450
1451 /**
1452 * @param $name
1453 * @return bool
1454 */
1455 function getNamedArgument( $name ) {
1456 if ( !isset( $this->namedArgs[$name] ) ) {
1457 return false;
1458 }
1459 if ( !isset( $this->namedExpansionCache[$name] ) ) {
1460 # Trim named arguments post-expand, for backwards compatibility
1461 $this->namedExpansionCache[$name] = trim(
1462 $this->parent->expand( $this->namedArgs[$name], PPFrame::STRIP_COMMENTS ) );
1463 }
1464 return $this->namedExpansionCache[$name];
1465 }
1466
1467 /**
1468 * @param $name
1469 * @return array|bool
1470 */
1471 function getArgument( $name ) {
1472 $text = $this->getNumberedArgument( $name );
1473 if ( $text === false ) {
1474 $text = $this->getNamedArgument( $name );
1475 }
1476 return $text;
1477 }
1478
1479 /**
1480 * Return true if the frame is a template frame
1481 *
1482 * @return bool
1483 */
1484 function isTemplate() {
1485 return true;
1486 }
1487 }
1488
1489 /**
1490 * Expansion frame with custom arguments
1491 * @ingroup Parser
1492 */
1493 class PPCustomFrame_Hash extends PPFrame_Hash {
1494 var $args;
1495
1496 function __construct( $preprocessor, $args ) {
1497 parent::__construct( $preprocessor );
1498 $this->args = $args;
1499 }
1500
1501 function __toString() {
1502 $s = 'cstmframe{';
1503 $first = true;
1504 foreach ( $this->args as $name => $value ) {
1505 if ( $first ) {
1506 $first = false;
1507 } else {
1508 $s .= ', ';
1509 }
1510 $s .= "\"$name\":\"" .
1511 str_replace( '"', '\\"', $value->__toString() ) . '"';
1512 }
1513 $s .= '}';
1514 return $s;
1515 }
1516
1517 /**
1518 * @return bool
1519 */
1520 function isEmpty() {
1521 return !count( $this->args );
1522 }
1523
1524 /**
1525 * @param $index
1526 * @return bool
1527 */
1528 function getArgument( $index ) {
1529 if ( !isset( $this->args[$index] ) ) {
1530 return false;
1531 }
1532 return $this->args[$index];
1533 }
1534
1535 function getArguments() {
1536 return $this->args;
1537 }
1538 }
1539
1540 /**
1541 * @ingroup Parser
1542 */
1543 class PPNode_Hash_Tree implements PPNode {
1544 var $name, $firstChild, $lastChild, $nextSibling;
1545
1546 function __construct( $name ) {
1547 $this->name = $name;
1548 $this->firstChild = $this->lastChild = $this->nextSibling = false;
1549 }
1550
1551 function __toString() {
1552 $inner = '';
1553 $attribs = '';
1554 for ( $node = $this->firstChild; $node; $node = $node->nextSibling ) {
1555 if ( $node instanceof PPNode_Hash_Attr ) {
1556 $attribs .= ' ' . $node->name . '="' . htmlspecialchars( $node->value ) . '"';
1557 } else {
1558 $inner .= $node->__toString();
1559 }
1560 }
1561 if ( $inner === '' ) {
1562 return "<{$this->name}$attribs/>";
1563 } else {
1564 return "<{$this->name}$attribs>$inner</{$this->name}>";
1565 }
1566 }
1567
1568 /**
1569 * @param $name
1570 * @param $text
1571 * @return PPNode_Hash_Tree
1572 */
1573 static function newWithText( $name, $text ) {
1574 $obj = new self( $name );
1575 $obj->addChild( new PPNode_Hash_Text( $text ) );
1576 return $obj;
1577 }
1578
1579 function addChild( $node ) {
1580 if ( $this->lastChild === false ) {
1581 $this->firstChild = $this->lastChild = $node;
1582 } else {
1583 $this->lastChild->nextSibling = $node;
1584 $this->lastChild = $node;
1585 }
1586 }
1587
1588 /**
1589 * @return PPNode_Hash_Array
1590 */
1591 function getChildren() {
1592 $children = array();
1593 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1594 $children[] = $child;
1595 }
1596 return new PPNode_Hash_Array( $children );
1597 }
1598
1599 function getFirstChild() {
1600 return $this->firstChild;
1601 }
1602
1603 function getNextSibling() {
1604 return $this->nextSibling;
1605 }
1606
1607 function getChildrenOfType( $name ) {
1608 $children = array();
1609 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1610 if ( isset( $child->name ) && $child->name === $name ) {
1611 $children[] = $child;
1612 }
1613 }
1614 return $children;
1615 }
1616
1617 /**
1618 * @return bool
1619 */
1620 function getLength() {
1621 return false;
1622 }
1623
1624 /**
1625 * @param $i
1626 * @return bool
1627 */
1628 function item( $i ) {
1629 return false;
1630 }
1631
1632 /**
1633 * @return string
1634 */
1635 function getName() {
1636 return $this->name;
1637 }
1638
1639 /**
1640 * Split a "<part>" node into an associative array containing:
1641 * - name PPNode name
1642 * - index String index
1643 * - value PPNode value
1644 *
1645 * @throws MWException
1646 * @return array
1647 */
1648 function splitArg() {
1649 $bits = array();
1650 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1651 if ( !isset( $child->name ) ) {
1652 continue;
1653 }
1654 if ( $child->name === 'name' ) {
1655 $bits['name'] = $child;
1656 if ( $child->firstChild instanceof PPNode_Hash_Attr
1657 && $child->firstChild->name === 'index'
1658 ) {
1659 $bits['index'] = $child->firstChild->value;
1660 }
1661 } elseif ( $child->name === 'value' ) {
1662 $bits['value'] = $child;
1663 }
1664 }
1665
1666 if ( !isset( $bits['name'] ) ) {
1667 throw new MWException( 'Invalid brace node passed to ' . __METHOD__ );
1668 }
1669 if ( !isset( $bits['index'] ) ) {
1670 $bits['index'] = '';
1671 }
1672 return $bits;
1673 }
1674
1675 /**
1676 * Split an "<ext>" node into an associative array containing name, attr, inner and close
1677 * All values in the resulting array are PPNodes. Inner and close are optional.
1678 *
1679 * @throws MWException
1680 * @return array
1681 */
1682 function splitExt() {
1683 $bits = array();
1684 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1685 if ( !isset( $child->name ) ) {
1686 continue;
1687 }
1688 if ( $child->name == 'name' ) {
1689 $bits['name'] = $child;
1690 } elseif ( $child->name == 'attr' ) {
1691 $bits['attr'] = $child;
1692 } elseif ( $child->name == 'inner' ) {
1693 $bits['inner'] = $child;
1694 } elseif ( $child->name == 'close' ) {
1695 $bits['close'] = $child;
1696 }
1697 }
1698 if ( !isset( $bits['name'] ) ) {
1699 throw new MWException( 'Invalid ext node passed to ' . __METHOD__ );
1700 }
1701 return $bits;
1702 }
1703
1704 /**
1705 * Split an "<h>" node
1706 *
1707 * @throws MWException
1708 * @return array
1709 */
1710 function splitHeading() {
1711 if ( $this->name !== 'h' ) {
1712 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1713 }
1714 $bits = array();
1715 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1716 if ( !isset( $child->name ) ) {
1717 continue;
1718 }
1719 if ( $child->name == 'i' ) {
1720 $bits['i'] = $child->value;
1721 } elseif ( $child->name == 'level' ) {
1722 $bits['level'] = $child->value;
1723 }
1724 }
1725 if ( !isset( $bits['i'] ) ) {
1726 throw new MWException( 'Invalid h node passed to ' . __METHOD__ );
1727 }
1728 return $bits;
1729 }
1730
1731 /**
1732 * Split a "<template>" or "<tplarg>" node
1733 *
1734 * @throws MWException
1735 * @return array
1736 */
1737 function splitTemplate() {
1738 $parts = array();
1739 $bits = array( 'lineStart' => '' );
1740 for ( $child = $this->firstChild; $child; $child = $child->nextSibling ) {
1741 if ( !isset( $child->name ) ) {
1742 continue;
1743 }
1744 if ( $child->name == 'title' ) {
1745 $bits['title'] = $child;
1746 }
1747 if ( $child->name == 'part' ) {
1748 $parts[] = $child;
1749 }
1750 if ( $child->name == 'lineStart' ) {
1751 $bits['lineStart'] = '1';
1752 }
1753 }
1754 if ( !isset( $bits['title'] ) ) {
1755 throw new MWException( 'Invalid node passed to ' . __METHOD__ );
1756 }
1757 $bits['parts'] = new PPNode_Hash_Array( $parts );
1758 return $bits;
1759 }
1760 }
1761
1762 /**
1763 * @ingroup Parser
1764 */
1765 class PPNode_Hash_Text implements PPNode {
1766 var $value, $nextSibling;
1767
1768 function __construct( $value ) {
1769 if ( is_object( $value ) ) {
1770 throw new MWException( __CLASS__ . ' given object instead of string' );
1771 }
1772 $this->value = $value;
1773 }
1774
1775 function __toString() {
1776 return htmlspecialchars( $this->value );
1777 }
1778
1779 function getNextSibling() {
1780 return $this->nextSibling;
1781 }
1782
1783 function getChildren() { return false; }
1784 function getFirstChild() { return false; }
1785 function getChildrenOfType( $name ) { return false; }
1786 function getLength() { return false; }
1787 function item( $i ) { return false; }
1788 function getName() { return '#text'; }
1789 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1790 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1791 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1792 }
1793
1794 /**
1795 * @ingroup Parser
1796 */
1797 class PPNode_Hash_Array implements PPNode {
1798 var $value, $nextSibling;
1799
1800 function __construct( $value ) {
1801 $this->value = $value;
1802 }
1803
1804 function __toString() {
1805 return var_export( $this, true );
1806 }
1807
1808 function getLength() {
1809 return count( $this->value );
1810 }
1811
1812 function item( $i ) {
1813 return $this->value[$i];
1814 }
1815
1816 function getName() { return '#nodelist'; }
1817
1818 function getNextSibling() {
1819 return $this->nextSibling;
1820 }
1821
1822 function getChildren() { return false; }
1823 function getFirstChild() { return false; }
1824 function getChildrenOfType( $name ) { return false; }
1825 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1826 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1827 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1828 }
1829
1830 /**
1831 * @ingroup Parser
1832 */
1833 class PPNode_Hash_Attr implements PPNode {
1834 var $name, $value, $nextSibling;
1835
1836 function __construct( $name, $value ) {
1837 $this->name = $name;
1838 $this->value = $value;
1839 }
1840
1841 function __toString() {
1842 return "<@{$this->name}>" . htmlspecialchars( $this->value ) . "</@{$this->name}>";
1843 }
1844
1845 function getName() {
1846 return $this->name;
1847 }
1848
1849 function getNextSibling() {
1850 return $this->nextSibling;
1851 }
1852
1853 function getChildren() { return false; }
1854 function getFirstChild() { return false; }
1855 function getChildrenOfType( $name ) { return false; }
1856 function getLength() { return false; }
1857 function item( $i ) { return false; }
1858 function splitArg() { throw new MWException( __METHOD__ . ': not supported' ); }
1859 function splitExt() { throw new MWException( __METHOD__ . ': not supported' ); }
1860 function splitHeading() { throw new MWException( __METHOD__ . ': not supported' ); }
1861 }