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