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