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