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