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