595dd7df1b12ef24d275591bd8e789379ee6c82d
[lhc/web/wiklou.git] / tests / parser / parserTest.inc
1 <?php
2 /**
3 * Helper code for the MediaWiki parser test suite. Some code is duplicated
4 * in PHPUnit's NewParserTests.php, so you'll probably want to update both
5 * at the same time.
6 *
7 * Copyright © 2004, 2010 Brion Vibber <brion@pobox.com>
8 * https://www.mediawiki.org/
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @todo Make this more independent of the configuration (and if possible the database)
26 * @todo document
27 * @file
28 * @ingroup Testing
29 */
30
31 /**
32 * @ingroup Testing
33 */
34 class ParserTest {
35 /**
36 * @var bool $color whereas output should be colorized
37 */
38 private $color;
39
40 /**
41 * @var bool $showOutput Show test output
42 */
43 private $showOutput;
44
45 /**
46 * @var bool $useTemporaryTables Use temporary tables for the temporary database
47 */
48 private $useTemporaryTables = true;
49
50 /**
51 * @var bool $databaseSetupDone True if the database has been set up
52 */
53 private $databaseSetupDone = false;
54
55 /**
56 * Our connection to the database
57 * @var DatabaseBase
58 */
59 private $db;
60
61 /**
62 * Database clone helper
63 * @var CloneDatabase
64 */
65 private $dbClone;
66
67 /**
68 * @var string $oldTablePrefix Original table prefix
69 */
70 private $oldTablePrefix;
71
72 private $maxFuzzTestLength = 300;
73 private $fuzzSeed = 0;
74 private $memoryLimit = 50;
75 private $uploadDir = null;
76
77 public $regex = "";
78 private $savedGlobals = array();
79
80 /**
81 * Sets terminal colorization and diff/quick modes depending on OS and
82 * command-line options (--color and --quick).
83 */
84 public function __construct( $options = array() ) {
85 # Only colorize output if stdout is a terminal.
86 $this->color = !wfIsWindows() && Maintenance::posix_isatty( 1 );
87
88 if ( isset( $options['color'] ) ) {
89 switch ( $options['color'] ) {
90 case 'no':
91 $this->color = false;
92 break;
93 case 'yes':
94 default:
95 $this->color = true;
96 break;
97 }
98 }
99
100 $this->term = $this->color
101 ? new AnsiTermColorer()
102 : new DummyTermColorer();
103
104 $this->showDiffs = !isset( $options['quick'] );
105 $this->showProgress = !isset( $options['quiet'] );
106 $this->showFailure = !(
107 isset( $options['quiet'] )
108 && ( isset( $options['record'] )
109 || isset( $options['compare'] ) ) ); // redundant output
110
111 $this->showOutput = isset( $options['show-output'] );
112
113 if ( isset( $options['filter'] ) ) {
114 $options['regex'] = $options['filter'];
115 }
116
117 if ( isset( $options['regex'] ) ) {
118 if ( isset( $options['record'] ) ) {
119 echo "Warning: --record cannot be used with --regex, disabling --record\n";
120 unset( $options['record'] );
121 }
122 $this->regex = $options['regex'];
123 } else {
124 # Matches anything
125 $this->regex = '';
126 }
127
128 $this->setupRecorder( $options );
129 $this->keepUploads = isset( $options['keep-uploads'] );
130
131 if ( isset( $options['seed'] ) ) {
132 $this->fuzzSeed = intval( $options['seed'] ) - 1;
133 }
134
135 $this->runDisabled = isset( $options['run-disabled'] );
136 $this->runParsoid = isset( $options['run-parsoid'] );
137
138 $this->hooks = array();
139 $this->functionHooks = array();
140 self::setUp();
141 }
142
143 static function setUp() {
144 global $wgParser, $wgParserConf, $IP, $messageMemc, $wgMemc,
145 $wgUser, $wgLang, $wgOut, $wgRequest, $wgStyleDirectory, $wgEnableParserCache,
146 $wgExtraNamespaces, $wgNamespaceAliases, $wgNamespaceProtection, $wgLocalFileRepo,
147 $parserMemc, $wgThumbnailScriptPath, $wgScriptPath,
148 $wgArticlePath, $wgScript, $wgStylePath, $wgExtensionAssetsPath,
149 $wgMainCacheType, $wgMessageCacheType, $wgParserCacheType, $wgLockManagers;
150
151 $wgScript = '/index.php';
152 $wgScriptPath = '/';
153 $wgArticlePath = '/wiki/$1';
154 $wgStylePath = '/skins';
155 $wgExtensionAssetsPath = '/extensions';
156 $wgThumbnailScriptPath = false;
157 $wgLockManagers = array( array(
158 'name' => 'fsLockManager',
159 'class' => 'FSLockManager',
160 'lockDirectory' => wfTempDir() . '/test-repo/lockdir',
161 ), array(
162 'name' => 'nullLockManager',
163 'class' => 'NullLockManager',
164 ) );
165 $wgLocalFileRepo = array(
166 'class' => 'LocalRepo',
167 'name' => 'local',
168 'url' => 'http://example.com/images',
169 'hashLevels' => 2,
170 'transformVia404' => false,
171 'backend' => new FSFileBackend( array(
172 'name' => 'local-backend',
173 'wikiId' => wfWikiId(),
174 'containerPaths' => array(
175 'local-public' => wfTempDir() . '/test-repo/public',
176 'local-thumb' => wfTempDir() . '/test-repo/thumb',
177 'local-temp' => wfTempDir() . '/test-repo/temp',
178 'local-deleted' => wfTempDir() . '/test-repo/deleted',
179 )
180 ) )
181 );
182 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
183 $wgNamespaceAliases['Image'] = NS_FILE;
184 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
185 # add a namespace shadowing a interwiki link, to test
186 # proper precedence when resolving links. (bug 51680)
187 $wgExtraNamespaces[100] = 'MemoryAlpha';
188
189 // XXX: tests won't run without this (for CACHE_DB)
190 if ( $wgMainCacheType === CACHE_DB ) {
191 $wgMainCacheType = CACHE_NONE;
192 }
193 if ( $wgMessageCacheType === CACHE_DB ) {
194 $wgMessageCacheType = CACHE_NONE;
195 }
196 if ( $wgParserCacheType === CACHE_DB ) {
197 $wgParserCacheType = CACHE_NONE;
198 }
199
200 $wgEnableParserCache = false;
201 DeferredUpdates::clearPendingUpdates();
202 $wgMemc = wfGetMainCache(); // checks $wgMainCacheType
203 $messageMemc = wfGetMessageCacheStorage();
204 $parserMemc = wfGetParserCacheStorage();
205
206 // $wgContLang = new StubContLang;
207 $wgUser = new User;
208 $context = new RequestContext;
209 $wgLang = $context->getLanguage();
210 $wgOut = $context->getOutput();
211 $wgParser = new StubObject( 'wgParser', $wgParserConf['class'], array( $wgParserConf ) );
212 $wgRequest = $context->getRequest();
213
214 if ( $wgStyleDirectory === false ) {
215 $wgStyleDirectory = "$IP/skins";
216 }
217
218 self::setupInterwikis();
219 }
220
221 /**
222 * Insert hardcoded interwiki in the lookup table.
223 *
224 * This function insert a set of well known interwikis that are used in
225 * the parser tests. They can be considered has fixtures are injected in
226 * the interwiki cache by using the 'InterwikiLoadPrefix' hook.
227 * Since we are not interested in looking up interwikis in the database,
228 * the hook completely replace the existing mechanism (hook returns false).
229 */
230 public static function setupInterwikis() {
231 # Hack: insert a few Wikipedia in-project interwiki prefixes,
232 # for testing inter-language links
233 Hooks::register( 'InterwikiLoadPrefix', function ( $prefix, &$iwData ) {
234 static $testInterwikis = array(
235 'wikipedia' => array(
236 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
237 'iw_api' => '',
238 'iw_wikiid' => '',
239 'iw_local' => 0 ),
240 'meatball' => array(
241 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
242 'iw_api' => '',
243 'iw_wikiid' => '',
244 'iw_local' => 0 ),
245 'memoryalpha' => array(
246 'iw_url' => 'http://www.memory-alpha.org/en/index.php/$1',
247 'iw_api' => '',
248 'iw_wikiid' => '',
249 'iw_local' => 0 ),
250 'zh' => array(
251 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
252 'iw_api' => '',
253 'iw_wikiid' => '',
254 'iw_local' => 1 ),
255 'es' => array(
256 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
257 'iw_api' => '',
258 'iw_wikiid' => '',
259 'iw_local' => 1 ),
260 'fr' => array(
261 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
262 'iw_api' => '',
263 'iw_wikiid' => '',
264 'iw_local' => 1 ),
265 'ru' => array(
266 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
267 'iw_api' => '',
268 'iw_wikiid' => '',
269 'iw_local' => 1 ),
270 );
271 if ( array_key_exists( $prefix, $testInterwikis ) ) {
272 $iwData = $testInterwikis[$prefix];
273 }
274
275 // We only want to rely on the above fixtures
276 return false;
277 } );// hooks::register
278 }
279
280 /**
281 * Remove the hardcoded interwiki lookup table.
282 */
283 public static function tearDownInterwikis() {
284 Hooks::clear( 'InterwikiLoadPrefix' );
285 }
286
287 public function setupRecorder( $options ) {
288 if ( isset( $options['record'] ) ) {
289 $this->recorder = new DbTestRecorder( $this );
290 $this->recorder->version = isset( $options['setversion'] ) ?
291 $options['setversion'] : SpecialVersion::getVersion();
292 } elseif ( isset( $options['compare'] ) ) {
293 $this->recorder = new DbTestPreviewer( $this );
294 } else {
295 $this->recorder = new TestRecorder( $this );
296 }
297 }
298
299 /**
300 * Remove last character if it is a newline
301 * @group utility
302 */
303 public static function chomp( $s ) {
304 if ( substr( $s, -1 ) === "\n" ) {
305 return substr( $s, 0, -1 );
306 } else {
307 return $s;
308 }
309 }
310
311 /**
312 * Run a fuzz test series
313 * Draw input from a set of test files
314 */
315 function fuzzTest( $filenames ) {
316 $GLOBALS['wgContLang'] = Language::factory( 'en' );
317 $dict = $this->getFuzzInput( $filenames );
318 $dictSize = strlen( $dict );
319 $logMaxLength = log( $this->maxFuzzTestLength );
320 $this->setupDatabase();
321 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
322
323 $numTotal = 0;
324 $numSuccess = 0;
325 $user = new User;
326 $opts = ParserOptions::newFromUser( $user );
327 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
328
329 while ( true ) {
330 // Generate test input
331 mt_srand( ++$this->fuzzSeed );
332 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
333 $input = '';
334
335 while ( strlen( $input ) < $totalLength ) {
336 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
337 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
338 $offset = mt_rand( 0, $dictSize - $hairLength );
339 $input .= substr( $dict, $offset, $hairLength );
340 }
341
342 $this->setupGlobals();
343 $parser = $this->getParser();
344
345 // Run the test
346 try {
347 $parser->parse( $input, $title, $opts );
348 $fail = false;
349 } catch ( Exception $exception ) {
350 $fail = true;
351 }
352
353 if ( $fail ) {
354 echo "Test failed with seed {$this->fuzzSeed}\n";
355 echo "Input:\n";
356 printf( "string(%d) \"%s\"\n\n", strlen( $input ), $input );
357 echo "$exception\n";
358 } else {
359 $numSuccess++;
360 }
361
362 $numTotal++;
363 $this->teardownGlobals();
364 $parser->__destruct();
365
366 if ( $numTotal % 100 == 0 ) {
367 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
368 echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
369 if ( $usage > 90 ) {
370 echo "Out of memory:\n";
371 $memStats = $this->getMemoryBreakdown();
372
373 foreach ( $memStats as $name => $usage ) {
374 echo "$name: $usage\n";
375 }
376 $this->abort();
377 }
378 }
379 }
380 }
381
382 /**
383 * Get an input dictionary from a set of parser test files
384 */
385 function getFuzzInput( $filenames ) {
386 $dict = '';
387
388 foreach ( $filenames as $filename ) {
389 $contents = file_get_contents( $filename );
390 preg_match_all( '/!!\s*(input|wikitext)\n(.*?)\n!!\s*(result|html|html\/\*|html\/php)/s', $contents, $matches );
391
392 foreach ( $matches[1] as $match ) {
393 $dict .= $match . "\n";
394 }
395 }
396
397 return $dict;
398 }
399
400 /**
401 * Get a memory usage breakdown
402 */
403 function getMemoryBreakdown() {
404 $memStats = array();
405
406 foreach ( $GLOBALS as $name => $value ) {
407 $memStats['$' . $name] = strlen( serialize( $value ) );
408 }
409
410 $classes = get_declared_classes();
411
412 foreach ( $classes as $class ) {
413 $rc = new ReflectionClass( $class );
414 $props = $rc->getStaticProperties();
415 $memStats[$class] = strlen( serialize( $props ) );
416 $methods = $rc->getMethods();
417
418 foreach ( $methods as $method ) {
419 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
420 }
421 }
422
423 $functions = get_defined_functions();
424
425 foreach ( $functions['user'] as $function ) {
426 $rf = new ReflectionFunction( $function );
427 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
428 }
429
430 asort( $memStats );
431
432 return $memStats;
433 }
434
435 function abort() {
436 $this->abort();
437 }
438
439 /**
440 * Run a series of tests listed in the given text files.
441 * Each test consists of a brief description, wikitext input,
442 * and the expected HTML output.
443 *
444 * Prints status updates on stdout and counts up the total
445 * number and percentage of passed tests.
446 *
447 * @param $filenames Array of strings
448 * @return Boolean: true if passed all tests, false if any tests failed.
449 */
450 public function runTestsFromFiles( $filenames ) {
451 $ok = false;
452
453 // be sure, ParserTest::addArticle has correct language set,
454 // so that system messages gets into the right language cache
455 $GLOBALS['wgLanguageCode'] = 'en';
456 $GLOBALS['wgContLang'] = Language::factory( 'en' );
457
458 $this->recorder->start();
459 try {
460 $this->setupDatabase();
461 $ok = true;
462
463 foreach ( $filenames as $filename ) {
464 $tests = new TestFileIterator( $filename, $this );
465 $ok = $this->runTests( $tests ) && $ok;
466 }
467
468 $this->teardownDatabase();
469 $this->recorder->report();
470 } catch ( DBError $e ) {
471 echo $e->getMessage();
472 }
473 $this->recorder->end();
474
475 return $ok;
476 }
477
478 function runTests( $tests ) {
479 $ok = true;
480
481 foreach ( $tests as $t ) {
482 $result =
483 $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
484 $ok = $ok && $result;
485 $this->recorder->record( $t['test'], $result );
486 }
487
488 if ( $this->showProgress ) {
489 print "\n";
490 }
491
492 return $ok;
493 }
494
495 /**
496 * Get a Parser object
497 *
498 * @param string $preprocessor
499 * @return Parser
500 */
501 function getParser( $preprocessor = null ) {
502 global $wgParserConf;
503
504 $class = $wgParserConf['class'];
505 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
506
507 foreach ( $this->hooks as $tag => $callback ) {
508 $parser->setHook( $tag, $callback );
509 }
510
511 foreach ( $this->functionHooks as $tag => $bits ) {
512 list( $callback, $flags ) = $bits;
513 $parser->setFunctionHook( $tag, $callback, $flags );
514 }
515
516 wfRunHooks( 'ParserTestParser', array( &$parser ) );
517
518 return $parser;
519 }
520
521 /**
522 * Run a given wikitext input through a freshly-constructed wiki parser,
523 * and compare the output against the expected results.
524 * Prints status and explanatory messages to stdout.
525 *
526 * @param $desc String: test's description
527 * @param $input String: wikitext to try rendering
528 * @param $result String: result to output
529 * @param $opts Array: test's options
530 * @param $config String: overrides for global variables, one per line
531 * @return Boolean
532 */
533 public function runTest( $desc, $input, $result, $opts, $config ) {
534 if ( $this->showProgress ) {
535 $this->showTesting( $desc );
536 }
537
538 $opts = $this->parseOptions( $opts );
539 $context = $this->setupGlobals( $opts, $config );
540
541 $user = $context->getUser();
542 $options = ParserOptions::newFromContext( $context );
543
544 if ( isset( $opts['title'] ) ) {
545 $titleText = $opts['title'];
546 } else {
547 $titleText = 'Parser test';
548 }
549
550 $local = isset( $opts['local'] );
551 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
552 $parser = $this->getParser( $preprocessor );
553 $title = Title::newFromText( $titleText );
554
555 if ( isset( $opts['pst'] ) ) {
556 $out = $parser->preSaveTransform( $input, $title, $user, $options );
557 } elseif ( isset( $opts['msg'] ) ) {
558 $out = $parser->transformMsg( $input, $options, $title );
559 } elseif ( isset( $opts['section'] ) ) {
560 $section = $opts['section'];
561 $out = $parser->getSection( $input, $section );
562 } elseif ( isset( $opts['replace'] ) ) {
563 $section = $opts['replace'][0];
564 $replace = $opts['replace'][1];
565 $out = $parser->replaceSection( $input, $section, $replace );
566 } elseif ( isset( $opts['comment'] ) ) {
567 $out = Linker::formatComment( $input, $title, $local );
568 } elseif ( isset( $opts['preload'] ) ) {
569 $out = $parser->getPreloadText( $input, $title, $options );
570 } else {
571 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
572 $output->setTOCEnabled( !isset( $opts['notoc'] ) );
573 $out = $output->getText();
574
575 if ( isset( $opts['showtitle'] ) ) {
576 if ( $output->getTitleText() ) {
577 $title = $output->getTitleText();
578 }
579
580 $out = "$title\n$out";
581 }
582
583 if ( isset( $opts['ill'] ) ) {
584 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
585 } elseif ( isset( $opts['cat'] ) ) {
586 $outputPage = $context->getOutput();
587 $outputPage->addCategoryLinks( $output->getCategories() );
588 $cats = $outputPage->getCategoryLinks();
589
590 if ( isset( $cats['normal'] ) ) {
591 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
592 } else {
593 $out = '';
594 }
595 }
596
597 $result = $this->tidy( $result );
598 }
599
600 $this->teardownGlobals();
601
602 $testResult = new ParserTestResult( $desc );
603 $testResult->expected = $result;
604 $testResult->actual = $out;
605
606 return $this->showTestResult( $testResult );
607 }
608
609 /**
610 * Refactored in 1.22 to use ParserTestResult
611 */
612 function showTestResult( ParserTestResult $testResult ) {
613 if ( $testResult->isSuccess() ) {
614 $this->showSuccess( $testResult );
615 return true;
616 } else {
617 $this->showFailure( $testResult );
618 return false;
619 }
620 }
621
622 /**
623 * Use a regex to find out the value of an option
624 * @param $key String: name of option val to retrieve
625 * @param $opts array: Options array to look in
626 * @param $default Mixed: default value returned if not found
627 */
628 private static function getOptionValue( $key, $opts, $default ) {
629 $key = strtolower( $key );
630
631 if ( isset( $opts[$key] ) ) {
632 return $opts[$key];
633 } else {
634 return $default;
635 }
636 }
637
638 private function parseOptions( $instring ) {
639 $opts = array();
640 // foo
641 // foo=bar
642 // foo="bar baz"
643 // foo=[[bar baz]]
644 // foo=bar,"baz quux"
645 // foo={...json...}
646 $defs = '(?(DEFINE)
647 (?<qstr> # Quoted string
648 "
649 (?:[^\\\\"] | \\\\.)*
650 "
651 )
652 (?<json>
653 \{ # Open bracket
654 (?:
655 [^"{}] | # Not a quoted string or object, or
656 (?&qstr) | # A quoted string, or
657 (?&json) # A json object (recursively)
658 )*
659 \} # Close bracket
660 )
661 (?<value>
662 (?:
663 (?&qstr) # Quoted val
664 |
665 \[\[
666 [^]]* # Link target
667 \]\]
668 |
669 [\w-]+ # Plain word
670 |
671 (?&json) # JSON object
672 )
673 )
674 )';
675 $regex = '/'.$defs.'\b
676 (?<k>[\w-]+) # Key
677 \b
678 (?:\s*
679 = # First sub-value
680 \s*
681 (?<v>
682 (?&value)
683 (?:\s*
684 , # Sub-vals 1..N
685 \s*
686 (?&value)
687 )*
688 )
689 )?
690 /x';
691 $valueregex = '/'.$defs.'(?&value)/x';
692
693 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
694 foreach ( $matches as $bits ) {
695 $key = strtolower( $bits[ 'k' ] );
696 if ( !isset( $bits[ 'v' ] ) ) {
697 $opts[$key] = true;
698 } else {
699 preg_match_all( $valueregex, $bits[ 'v' ], $vmatches );
700 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $vmatches[0] );
701 if ( count( $opts[$key] ) == 1 ) {
702 $opts[$key] = $opts[$key][0];
703 }
704 }
705 }
706 }
707 return $opts;
708 }
709
710 private function cleanupOption( $opt ) {
711 if ( substr( $opt, 0, 1 ) == '"' ) {
712 return stripcslashes( substr( $opt, 1, -1 ) );
713 }
714
715 if ( substr( $opt, 0, 2 ) == '[[' ) {
716 return substr( $opt, 2, -2 );
717 }
718
719 if ( substr( $opt, 0, 1 ) == '{' ) {
720 return FormatJson::decode( $opt, true );
721 }
722 return $opt;
723 }
724
725 /**
726 * Set up the global variables for a consistent environment for each test.
727 * Ideally this should replace the global configuration entirely.
728 */
729 private function setupGlobals( $opts = '', $config = '' ) {
730 # Find out values for some special options.
731 $lang =
732 self::getOptionValue( 'language', $opts, 'en' );
733 $variant =
734 self::getOptionValue( 'variant', $opts, false );
735 $maxtoclevel =
736 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
737 $linkHolderBatchSize =
738 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
739
740 $settings = array(
741 'wgServer' => 'http://example.org',
742 'wgScript' => '/index.php',
743 'wgScriptPath' => '/',
744 'wgArticlePath' => '/wiki/$1',
745 'wgActionPaths' => array(),
746 'wgLockManagers' => array( array(
747 'name' => 'fsLockManager',
748 'class' => 'FSLockManager',
749 'lockDirectory' => $this->uploadDir . '/lockdir',
750 ), array(
751 'name' => 'nullLockManager',
752 'class' => 'NullLockManager',
753 ) ),
754 'wgLocalFileRepo' => array(
755 'class' => 'LocalRepo',
756 'name' => 'local',
757 'url' => 'http://example.com/images',
758 'hashLevels' => 2,
759 'transformVia404' => false,
760 'backend' => new FSFileBackend( array(
761 'name' => 'local-backend',
762 'wikiId' => wfWikiId(),
763 'containerPaths' => array(
764 'local-public' => $this->uploadDir,
765 'local-thumb' => $this->uploadDir . '/thumb',
766 'local-temp' => $this->uploadDir . '/temp',
767 'local-deleted' => $this->uploadDir . '/delete',
768 )
769 ) )
770 ),
771 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
772 'wgStylePath' => '/skins',
773 'wgSitename' => 'MediaWiki',
774 'wgLanguageCode' => $lang,
775 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
776 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
777 'wgLang' => null,
778 'wgContLang' => null,
779 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
780 'wgMaxTocLevel' => $maxtoclevel,
781 'wgCapitalLinks' => true,
782 'wgNoFollowLinks' => true,
783 'wgNoFollowDomainExceptions' => array(),
784 'wgThumbnailScriptPath' => false,
785 'wgUseImageResize' => true,
786 'wgSVGConverter' => 'null',
787 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
788 'wgLocaltimezone' => 'UTC',
789 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
790 'wgThumbLimits' => array( self::getOptionValue( 'thumbsize', $opts, 180 ) ),
791 'wgUseTidy' => false,
792 'wgDefaultLanguageVariant' => $variant,
793 'wgVariantArticlePath' => false,
794 'wgGroupPermissions' => array( '*' => array(
795 'createaccount' => true,
796 'read' => true,
797 'edit' => true,
798 'createpage' => true,
799 'createtalk' => true,
800 ) ),
801 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
802 'wgDefaultExternalStore' => array(),
803 'wgForeignFileRepos' => array(),
804 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
805 'wgExperimentalHtmlIds' => false,
806 'wgExternalLinkTarget' => false,
807 'wgAlwaysUseTidy' => false,
808 'wgHtml5' => true,
809 'wgWellFormedXml' => true,
810 'wgAllowMicrodataAttributes' => true,
811 'wgAdaptiveMessageCache' => true,
812 'wgDisableLangConversion' => false,
813 'wgDisableTitleConversion' => false,
814 );
815
816 if ( $config ) {
817 $configLines = explode( "\n", $config );
818
819 foreach ( $configLines as $line ) {
820 list( $var, $value ) = explode( '=', $line, 2 );
821
822 $settings[$var] = eval( "return $value;" );
823 }
824 }
825
826 $this->savedGlobals = array();
827
828 /** @since 1.20 */
829 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
830
831 foreach ( $settings as $var => $val ) {
832 if ( array_key_exists( $var, $GLOBALS ) ) {
833 $this->savedGlobals[$var] = $GLOBALS[$var];
834 }
835
836 $GLOBALS[$var] = $val;
837 }
838
839 $GLOBALS['wgContLang'] = Language::factory( $lang );
840 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
841
842 $context = new RequestContext();
843 $GLOBALS['wgLang'] = $context->getLanguage();
844 $GLOBALS['wgOut'] = $context->getOutput();
845 $GLOBALS['wgUser'] = $context->getUser();
846
847 // We (re)set $wgThumbLimits to a single-element array above.
848 $context->getUser()->setOption( 'thumbsize', 0 );
849
850 global $wgHooks;
851
852 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
853 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
854
855 MagicWord::clearCache();
856
857 return $context;
858 }
859
860 /**
861 * List of temporary tables to create, without prefix.
862 * Some of these probably aren't necessary.
863 */
864 private function listTables() {
865 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
866 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
867 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
868 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
869 'recentchanges', 'watchlist', 'interwiki', 'logging',
870 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
871 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
872 );
873
874 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
875 array_push( $tables, 'searchindex' );
876 }
877
878 // Allow extensions to add to the list of tables to duplicate;
879 // may be necessary if they hook into page save or other code
880 // which will require them while running tests.
881 wfRunHooks( 'ParserTestTables', array( &$tables ) );
882
883 return $tables;
884 }
885
886 /**
887 * Set up a temporary set of wiki tables to work with for the tests.
888 * Currently this will only be done once per run, and any changes to
889 * the db will be visible to later tests in the run.
890 */
891 public function setupDatabase() {
892 global $wgDBprefix;
893
894 if ( $this->databaseSetupDone ) {
895 return;
896 }
897
898 $this->db = wfGetDB( DB_MASTER );
899 $dbType = $this->db->getType();
900
901 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
902 throw new MWException( 'setupDatabase should be called before setupGlobals' );
903 }
904
905 $this->databaseSetupDone = true;
906 $this->oldTablePrefix = $wgDBprefix;
907
908 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
909 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
910 # This works around it for now...
911 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
912
913 # CREATE TEMPORARY TABLE breaks if there is more than one server
914 if ( wfGetLB()->getServerCount() != 1 ) {
915 $this->useTemporaryTables = false;
916 }
917
918 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
919 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
920
921 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
922 $this->dbClone->useTemporaryTables( $temporary );
923 $this->dbClone->cloneTableStructure();
924
925 if ( $dbType == 'oracle' ) {
926 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
927 # Insert 0 user to prevent FK violations
928
929 # Anonymous user
930 $this->db->insert( 'user', array(
931 'user_id' => 0,
932 'user_name' => 'Anonymous' ) );
933 }
934
935 # Update certain things in site_stats
936 $this->db->insert( 'site_stats',
937 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
938
939 # Reinitialise the LocalisationCache to match the database state
940 Language::getLocalisationCache()->unloadAll();
941
942 # Clear the message cache
943 MessageCache::singleton()->clear();
944
945 // Remember to update newParserTests.php after changing the below
946 // (and it uses a slightly different syntax just for teh lulz)
947 $this->uploadDir = $this->setupUploadDir();
948 $user = User::createNew( 'WikiSysop' );
949 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
950 # note that the size/width/height/bits/etc of the file
951 # are actually set by inspecting the file itself; the arguments
952 # to recordUpload2 have no effect. That said, we try to make things
953 # match up so it is less confusing to readers of the code & tests.
954 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
955 'size' => 7881,
956 'width' => 1941,
957 'height' => 220,
958 'bits' => 8,
959 'media_type' => MEDIATYPE_BITMAP,
960 'mime' => 'image/jpeg',
961 'metadata' => serialize( array() ),
962 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
963 'fileExists' => true
964 ), $this->db->timestamp( '20010115123500' ), $user );
965
966 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
967 # again, note that size/width/height below are ignored; see above.
968 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
969 'size' => 22589,
970 'width' => 135,
971 'height' => 135,
972 'bits' => 8,
973 'media_type' => MEDIATYPE_BITMAP,
974 'mime' => 'image/png',
975 'metadata' => serialize( array() ),
976 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
977 'fileExists' => true
978 ), $this->db->timestamp( '20130225203040' ), $user );
979
980 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
981 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
982 'size' => 12345,
983 'width' => 240,
984 'height' => 180,
985 'bits' => 24,
986 'media_type' => MEDIATYPE_DRAWING,
987 'mime' => 'image/svg+xml',
988 'metadata' => serialize( array() ),
989 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
990 'fileExists' => true
991 ), $this->db->timestamp( '20010115123500' ), $user );
992
993 # This image will be blacklisted in [[MediaWiki:Bad image list]]
994 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
995 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
996 'size' => 12345,
997 'width' => 320,
998 'height' => 240,
999 'bits' => 24,
1000 'media_type' => MEDIATYPE_BITMAP,
1001 'mime' => 'image/jpeg',
1002 'metadata' => serialize( array() ),
1003 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
1004 'fileExists' => true
1005 ), $this->db->timestamp( '20010115123500' ), $user );
1006 }
1007
1008 public function teardownDatabase() {
1009 if ( !$this->databaseSetupDone ) {
1010 $this->teardownGlobals();
1011 return;
1012 }
1013 $this->teardownUploadDir( $this->uploadDir );
1014
1015 $this->dbClone->destroy();
1016 $this->databaseSetupDone = false;
1017
1018 if ( $this->useTemporaryTables ) {
1019 if ( $this->db->getType() == 'sqlite' ) {
1020 # Under SQLite the searchindex table is virtual and need
1021 # to be explicitly destroyed. See bug 29912
1022 # See also MediaWikiTestCase::destroyDB()
1023 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
1024 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
1025 }
1026 # Don't need to do anything
1027 $this->teardownGlobals();
1028 return;
1029 }
1030
1031 $tables = $this->listTables();
1032
1033 foreach ( $tables as $table ) {
1034 if ( $this->db->getType() == 'oracle' ) {
1035 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1036 } else {
1037 $this->db->query( "DROP TABLE `parsertest_$table`" );
1038 }
1039 }
1040
1041 if ( $this->db->getType() == 'oracle' ) {
1042 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1043 }
1044
1045 $this->teardownGlobals();
1046 }
1047
1048 /**
1049 * Create a dummy uploads directory which will contain a couple
1050 * of files in order to pass existence tests.
1051 *
1052 * @return String: the directory
1053 */
1054 private function setupUploadDir() {
1055 global $IP;
1056
1057 if ( $this->keepUploads ) {
1058 $dir = wfTempDir() . '/mwParser-images';
1059
1060 if ( is_dir( $dir ) ) {
1061 return $dir;
1062 }
1063 } else {
1064 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1065 }
1066
1067 // wfDebug( "Creating upload directory $dir\n" );
1068 if ( file_exists( $dir ) ) {
1069 wfDebug( "Already exists!\n" );
1070 return $dir;
1071 }
1072
1073 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1074 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1075 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1076 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1077 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1078 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1079 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1080 file_put_contents( "$dir/f/ff/Foobar.svg",
1081 '<?xml version="1.0" encoding="utf-8"?>' .
1082 '<svg xmlns="http://www.w3.org/2000/svg"' .
1083 ' version="1.1" width="240" height="180"/>' );
1084 return $dir;
1085 }
1086
1087 /**
1088 * Restore default values and perform any necessary clean-up
1089 * after each test runs.
1090 */
1091 private function teardownGlobals() {
1092 RepoGroup::destroySingleton();
1093 FileBackendGroup::destroySingleton();
1094 LockManagerGroup::destroySingletons();
1095 LinkCache::singleton()->clear();
1096
1097 foreach ( $this->savedGlobals as $var => $val ) {
1098 $GLOBALS[$var] = $val;
1099 }
1100 }
1101
1102 /**
1103 * Remove the dummy uploads directory
1104 */
1105 private function teardownUploadDir( $dir ) {
1106 if ( $this->keepUploads ) {
1107 return;
1108 }
1109
1110 // delete the files first, then the dirs.
1111 self::deleteFiles(
1112 array(
1113 "$dir/3/3a/Foobar.jpg",
1114 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1115 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1116 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1117 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1118 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1119 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1120 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1121 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1122 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1123 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1124 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1125 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1126 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1127 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1128
1129 "$dir/e/ea/Thumb.png",
1130
1131 "$dir/0/09/Bad.jpg",
1132
1133 "$dir/f/ff/Foobar.svg",
1134 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1135 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1136 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1137 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1138 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1139 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1140
1141 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1142 )
1143 );
1144
1145 self::deleteDirs(
1146 array(
1147 "$dir/3/3a",
1148 "$dir/3",
1149 "$dir/thumb/6/65",
1150 "$dir/thumb/6",
1151 "$dir/thumb/3/3a/Foobar.jpg",
1152 "$dir/thumb/3/3a",
1153 "$dir/thumb/3",
1154 "$dir/e/ea",
1155 "$dir/e",
1156 "$dir/f/ff/",
1157 "$dir/f/",
1158 "$dir/thumb/f/ff/Foobar.svg",
1159 "$dir/thumb/f/ff/",
1160 "$dir/thumb/f/",
1161 "$dir/0/09/",
1162 "$dir/0/",
1163 "$dir/thumb",
1164 "$dir/math/f/a/5",
1165 "$dir/math/f/a",
1166 "$dir/math/f",
1167 "$dir/math",
1168 "$dir",
1169 )
1170 );
1171 }
1172
1173 /**
1174 * Delete the specified files, if they exist.
1175 * @param $files Array: full paths to files to delete.
1176 */
1177 private static function deleteFiles( $files ) {
1178 foreach ( $files as $file ) {
1179 if ( file_exists( $file ) ) {
1180 unlink( $file );
1181 }
1182 }
1183 }
1184
1185 /**
1186 * Delete the specified directories, if they exist. Must be empty.
1187 * @param $dirs Array: full paths to directories to delete.
1188 */
1189 private static function deleteDirs( $dirs ) {
1190 foreach ( $dirs as $dir ) {
1191 if ( is_dir( $dir ) ) {
1192 rmdir( $dir );
1193 }
1194 }
1195 }
1196
1197 /**
1198 * "Running test $desc..."
1199 */
1200 protected function showTesting( $desc ) {
1201 print "Running test $desc... ";
1202 }
1203
1204 /**
1205 * Print a happy success message.
1206 *
1207 * Refactored in 1.22 to use ParserTestResult
1208 *
1209 * @param $testResult ParserTestResult
1210 * @return Boolean
1211 */
1212 protected function showSuccess( ParserTestResult $testResult ) {
1213 if ( $this->showProgress ) {
1214 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1215 }
1216
1217 return true;
1218 }
1219
1220 /**
1221 * Print a failure message and provide some explanatory output
1222 * about what went wrong if so configured.
1223 *
1224 * Refactored in 1.22 to use ParserTestResult
1225 *
1226 * @param $testResult ParserTestResult
1227 * @return Boolean
1228 */
1229 protected function showFailure( ParserTestResult $testResult ) {
1230 if ( $this->showFailure ) {
1231 if ( !$this->showProgress ) {
1232 # In quiet mode we didn't show the 'Testing' message before the
1233 # test, in case it succeeded. Show it now:
1234 $this->showTesting( $testResult->description );
1235 }
1236
1237 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1238
1239 if ( $this->showOutput ) {
1240 print "--- Expected ---\n{$testResult->expected}\n";
1241 print "--- Actual ---\n{$testResult->actual}\n";
1242 }
1243
1244 if ( $this->showDiffs ) {
1245 print $this->quickDiff( $testResult->expected, $testResult->actual );
1246 if ( !$this->wellFormed( $testResult->actual ) ) {
1247 print "XML error: $this->mXmlError\n";
1248 }
1249 }
1250 }
1251
1252 return false;
1253 }
1254
1255 /**
1256 * Run given strings through a diff and return the (colorized) output.
1257 * Requires writable /tmp directory and a 'diff' command in the PATH.
1258 *
1259 * @param $input String
1260 * @param $output String
1261 * @param $inFileTail String: tailing for the input file name
1262 * @param $outFileTail String: tailing for the output file name
1263 * @return String
1264 */
1265 protected function quickDiff( $input, $output,
1266 $inFileTail = 'expected', $outFileTail = 'actual'
1267 ) {
1268 # Windows, or at least the fc utility, is retarded
1269 $slash = wfIsWindows() ? '\\' : '/';
1270 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1271
1272 $infile = "$prefix-$inFileTail";
1273 $this->dumpToFile( $input, $infile );
1274
1275 $outfile = "$prefix-$outFileTail";
1276 $this->dumpToFile( $output, $outfile );
1277
1278 $shellInfile = wfEscapeShellArg( $infile );
1279 $shellOutfile = wfEscapeShellArg( $outfile );
1280
1281 global $wgDiff3;
1282 // we assume that people with diff3 also have usual diff
1283 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1284
1285 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1286
1287 unlink( $infile );
1288 unlink( $outfile );
1289
1290 return $this->colorDiff( $diff );
1291 }
1292
1293 /**
1294 * Write the given string to a file, adding a final newline.
1295 *
1296 * @param $data String
1297 * @param $filename String
1298 */
1299 private function dumpToFile( $data, $filename ) {
1300 $file = fopen( $filename, "wt" );
1301 fwrite( $file, $data . "\n" );
1302 fclose( $file );
1303 }
1304
1305 /**
1306 * Colorize unified diff output if set for ANSI color output.
1307 * Subtractions are colored blue, additions red.
1308 *
1309 * @param $text String
1310 * @return String
1311 */
1312 protected function colorDiff( $text ) {
1313 return preg_replace(
1314 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1315 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1316 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1317 $text );
1318 }
1319
1320 /**
1321 * Show "Reading tests from ..."
1322 *
1323 * @param $path String
1324 */
1325 public function showRunFile( $path ) {
1326 print $this->term->color( 1 ) .
1327 "Reading tests from \"$path\"..." .
1328 $this->term->reset() .
1329 "\n";
1330 }
1331
1332 /**
1333 * Insert a temporary test article
1334 * @param $name String: the title, including any prefix
1335 * @param $text String: the article text
1336 * @param $line Integer: the input line number, for reporting errors
1337 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1338 */
1339 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1340 global $wgCapitalLinks;
1341
1342 $oldCapitalLinks = $wgCapitalLinks;
1343 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1344
1345 $text = self::chomp( $text );
1346 $name = self::chomp( $name );
1347
1348 $title = Title::newFromText( $name );
1349
1350 if ( is_null( $title ) ) {
1351 throw new MWException( "invalid title '$name' at line $line\n" );
1352 }
1353
1354 $page = WikiPage::factory( $title );
1355 $page->loadPageData( 'fromdbmaster' );
1356
1357 if ( $page->exists() ) {
1358 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1359 return;
1360 } else {
1361 throw new MWException( "duplicate article '$name' at line $line\n" );
1362 }
1363 }
1364
1365 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1366
1367 $wgCapitalLinks = $oldCapitalLinks;
1368 }
1369
1370 /**
1371 * Steal a callback function from the primary parser, save it for
1372 * application to our scary parser. If the hook is not installed,
1373 * abort processing of this file.
1374 *
1375 * @param $name String
1376 * @return Bool true if tag hook is present
1377 */
1378 public function requireHook( $name ) {
1379 global $wgParser;
1380
1381 $wgParser->firstCallInit(); // make sure hooks are loaded.
1382
1383 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1384 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1385 } else {
1386 echo " This test suite requires the '$name' hook extension, skipping.\n";
1387 return false;
1388 }
1389
1390 return true;
1391 }
1392
1393 /**
1394 * Steal a callback function from the primary parser, save it for
1395 * application to our scary parser. If the hook is not installed,
1396 * abort processing of this file.
1397 *
1398 * @param $name String
1399 * @return Bool true if function hook is present
1400 */
1401 public function requireFunctionHook( $name ) {
1402 global $wgParser;
1403
1404 $wgParser->firstCallInit(); // make sure hooks are loaded.
1405
1406 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1407 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1408 } else {
1409 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1410 return false;
1411 }
1412
1413 return true;
1414 }
1415
1416 /**
1417 * Run the "tidy" command on text if the $wgUseTidy
1418 * global is true
1419 *
1420 * @param $text String: the text to tidy
1421 * @return String
1422 */
1423 private function tidy( $text ) {
1424 global $wgUseTidy;
1425
1426 if ( $wgUseTidy ) {
1427 $text = MWTidy::tidy( $text );
1428 }
1429
1430 return $text;
1431 }
1432
1433 private function wellFormed( $text ) {
1434 $html =
1435 Sanitizer::hackDocType() .
1436 '<html>' .
1437 $text .
1438 '</html>';
1439
1440 $parser = xml_parser_create( "UTF-8" );
1441
1442 # case folding violates XML standard, turn it off
1443 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1444
1445 if ( !xml_parse( $parser, $html, true ) ) {
1446 $err = xml_error_string( xml_get_error_code( $parser ) );
1447 $position = xml_get_current_byte_index( $parser );
1448 $fragment = $this->extractFragment( $html, $position );
1449 $this->mXmlError = "$err at byte $position:\n$fragment";
1450 xml_parser_free( $parser );
1451
1452 return false;
1453 }
1454
1455 xml_parser_free( $parser );
1456
1457 return true;
1458 }
1459
1460 private function extractFragment( $text, $position ) {
1461 $start = max( 0, $position - 10 );
1462 $before = $position - $start;
1463 $fragment = '...' .
1464 $this->term->color( 34 ) .
1465 substr( $text, $start, $before ) .
1466 $this->term->color( 0 ) .
1467 $this->term->color( 31 ) .
1468 $this->term->color( 1 ) .
1469 substr( $text, $position, 1 ) .
1470 $this->term->color( 0 ) .
1471 $this->term->color( 34 ) .
1472 substr( $text, $position + 1, 9 ) .
1473 $this->term->color( 0 ) .
1474 '...';
1475 $display = str_replace( "\n", ' ', $fragment );
1476 $caret = ' ' .
1477 str_repeat( ' ', $before ) .
1478 $this->term->color( 31 ) .
1479 '^' .
1480 $this->term->color( 0 );
1481
1482 return "$display\n$caret";
1483 }
1484
1485 static function getFakeTimestamp( &$parser, &$ts ) {
1486 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1487 return true;
1488 }
1489 }