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