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