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