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