Add DROP INDEX support to DatabaseSqlite::replaceVars method
[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 * http://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 * boolean $color whereas output should be colorized
37 */
38 private $color;
39
40 /**
41 * boolean $showOutput Show test output
42 */
43 private $showOutput;
44
45 /**
46 * boolean $useTemporaryTables Use temporary tables for the temporary database
47 */
48 private $useTemporaryTables = true;
49
50 /**
51 * boolean $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 * 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 'lockManager' => 'fsLockManager',
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\n(.*?)\n!!\s*result/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 function getParser( $preprocessor = null ) {
499 global $wgParserConf;
500
501 $class = $wgParserConf['class'];
502 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
503
504 foreach ( $this->hooks as $tag => $callback ) {
505 $parser->setHook( $tag, $callback );
506 }
507
508 foreach ( $this->functionHooks as $tag => $bits ) {
509 list( $callback, $flags ) = $bits;
510 $parser->setFunctionHook( $tag, $callback, $flags );
511 }
512
513 wfRunHooks( 'ParserTestParser', array( &$parser ) );
514
515 return $parser;
516 }
517
518 /**
519 * Run a given wikitext input through a freshly-constructed wiki parser,
520 * and compare the output against the expected results.
521 * Prints status and explanatory messages to stdout.
522 *
523 * @param $desc String: test's description
524 * @param $input String: wikitext to try rendering
525 * @param $result String: result to output
526 * @param $opts Array: test's options
527 * @param $config String: overrides for global variables, one per line
528 * @return Boolean
529 */
530 public function runTest( $desc, $input, $result, $opts, $config ) {
531 if ( $this->showProgress ) {
532 $this->showTesting( $desc );
533 }
534
535 $opts = $this->parseOptions( $opts );
536 $context = $this->setupGlobals( $opts, $config );
537
538 $user = $context->getUser();
539 $options = ParserOptions::newFromContext( $context );
540
541 if ( isset( $opts['title'] ) ) {
542 $titleText = $opts['title'];
543 } else {
544 $titleText = 'Parser test';
545 }
546
547 $local = isset( $opts['local'] );
548 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
549 $parser = $this->getParser( $preprocessor );
550 $title = Title::newFromText( $titleText );
551
552 if ( isset( $opts['pst'] ) ) {
553 $out = $parser->preSaveTransform( $input, $title, $user, $options );
554 } elseif ( isset( $opts['msg'] ) ) {
555 $out = $parser->transformMsg( $input, $options, $title );
556 } elseif ( isset( $opts['section'] ) ) {
557 $section = $opts['section'];
558 $out = $parser->getSection( $input, $section );
559 } elseif ( isset( $opts['replace'] ) ) {
560 $section = $opts['replace'][0];
561 $replace = $opts['replace'][1];
562 $out = $parser->replaceSection( $input, $section, $replace );
563 } elseif ( isset( $opts['comment'] ) ) {
564 $out = Linker::formatComment( $input, $title, $local );
565 } elseif ( isset( $opts['preload'] ) ) {
566 $out = $parser->getPreloadText( $input, $title, $options );
567 } else {
568 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
569 $out = $output->getText();
570
571 if ( isset( $opts['showtitle'] ) ) {
572 if ( $output->getTitleText() ) {
573 $title = $output->getTitleText();
574 }
575
576 $out = "$title\n$out";
577 }
578
579 if ( isset( $opts['ill'] ) ) {
580 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
581 } elseif ( isset( $opts['cat'] ) ) {
582 $outputPage = $context->getOutput();
583 $outputPage->addCategoryLinks( $output->getCategories() );
584 $cats = $outputPage->getCategoryLinks();
585
586 if ( isset( $cats['normal'] ) ) {
587 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
588 } else {
589 $out = '';
590 }
591 }
592
593 $result = $this->tidy( $result );
594 }
595
596 $this->teardownGlobals();
597
598 $testResult = new ParserTestResult( $desc );
599 $testResult->expected = $result;
600 $testResult->actual = $out;
601
602 return $this->showTestResult( $testResult );
603 }
604
605 /**
606 * Refactored in 1.22 to use ParserTestResult
607 */
608 function showTestResult( ParserTestResult $testResult ) {
609 if ( $testResult->isSuccess() ) {
610 $this->showSuccess( $testResult );
611 return true;
612 } else {
613 $this->showFailure( $testResult );
614 return false;
615 }
616 }
617
618 /**
619 * Use a regex to find out the value of an option
620 * @param $key String: name of option val to retrieve
621 * @param $opts Options array to look in
622 * @param $default Mixed: default value returned if not found
623 */
624 private static function getOptionValue( $key, $opts, $default ) {
625 $key = strtolower( $key );
626
627 if ( isset( $opts[$key] ) ) {
628 return $opts[$key];
629 } else {
630 return $default;
631 }
632 }
633
634 private function parseOptions( $instring ) {
635 $opts = array();
636 // foo
637 // foo=bar
638 // foo="bar baz"
639 // foo=[[bar baz]]
640 // foo=bar,"baz quux"
641 $regex = '/\b
642 ([\w-]+) # Key
643 \b
644 (?:\s*
645 = # First sub-value
646 \s*
647 (
648 "
649 [^"]* # Quoted val
650 "
651 |
652 \[\[
653 [^]]* # Link target
654 \]\]
655 |
656 [\w-]+ # Plain word
657 )
658 (?:\s*
659 , # Sub-vals 1..N
660 \s*
661 (
662 "[^"]*" # Quoted val
663 |
664 \[\[[^]]*\]\] # Link target
665 |
666 [\w-]+ # Plain word
667 )
668 )*
669 )?
670 /x';
671
672 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
673 foreach ( $matches as $bits ) {
674 array_shift( $bits );
675 $key = strtolower( array_shift( $bits ) );
676 if ( count( $bits ) == 0 ) {
677 $opts[$key] = true;
678 } elseif ( count( $bits ) == 1 ) {
679 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
680 } else {
681 // Array!
682 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
683 }
684 }
685 }
686 return $opts;
687 }
688
689 private function cleanupOption( $opt ) {
690 if ( substr( $opt, 0, 1 ) == '"' ) {
691 return substr( $opt, 1, -1 );
692 }
693
694 if ( substr( $opt, 0, 2 ) == '[[' ) {
695 return substr( $opt, 2, -2 );
696 }
697 return $opt;
698 }
699
700 /**
701 * Set up the global variables for a consistent environment for each test.
702 * Ideally this should replace the global configuration entirely.
703 */
704 private function setupGlobals( $opts = '', $config = '' ) {
705 # Find out values for some special options.
706 $lang =
707 self::getOptionValue( 'language', $opts, 'en' );
708 $variant =
709 self::getOptionValue( 'variant', $opts, false );
710 $maxtoclevel =
711 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
712 $linkHolderBatchSize =
713 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
714
715 $settings = array(
716 'wgServer' => 'http://example.org',
717 'wgScript' => '/index.php',
718 'wgScriptPath' => '/',
719 'wgArticlePath' => '/wiki/$1',
720 'wgActionPaths' => array(),
721 'wgLockManagers' => array( array(
722 'name' => 'fsLockManager',
723 'class' => 'FSLockManager',
724 'lockDirectory' => $this->uploadDir . '/lockdir',
725 ), array(
726 'name' => 'nullLockManager',
727 'class' => 'NullLockManager',
728 ) ),
729 'wgLocalFileRepo' => array(
730 'class' => 'LocalRepo',
731 'name' => 'local',
732 'url' => 'http://example.com/images',
733 'hashLevels' => 2,
734 'transformVia404' => false,
735 'backend' => new FSFileBackend( array(
736 'name' => 'local-backend',
737 'lockManager' => 'fsLockManager',
738 'containerPaths' => array(
739 'local-public' => $this->uploadDir,
740 'local-thumb' => $this->uploadDir . '/thumb',
741 'local-temp' => $this->uploadDir . '/temp',
742 'local-deleted' => $this->uploadDir . '/delete',
743 )
744 ) )
745 ),
746 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
747 'wgStylePath' => '/skins',
748 'wgSitename' => 'MediaWiki',
749 'wgLanguageCode' => $lang,
750 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'parsertest_' : 'pt_',
751 'wgRawHtml' => self::getOptionValue( 'wgRawHtml', $opts, false ),
752 'wgLang' => null,
753 'wgContLang' => null,
754 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
755 'wgMaxTocLevel' => $maxtoclevel,
756 'wgCapitalLinks' => true,
757 'wgNoFollowLinks' => true,
758 'wgNoFollowDomainExceptions' => array(),
759 'wgThumbnailScriptPath' => false,
760 'wgUseImageResize' => true,
761 'wgSVGConverter' => 'null',
762 'wgSVGConverters' => array( 'null' => 'echo "1">$output' ),
763 'wgLocaltimezone' => 'UTC',
764 'wgAllowExternalImages' => self::getOptionValue( 'wgAllowExternalImages', $opts, true ),
765 'wgUseTidy' => false,
766 'wgDefaultLanguageVariant' => $variant,
767 'wgVariantArticlePath' => false,
768 'wgGroupPermissions' => array( '*' => array(
769 'createaccount' => true,
770 'read' => true,
771 'edit' => true,
772 'createpage' => true,
773 'createtalk' => true,
774 ) ),
775 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
776 'wgDefaultExternalStore' => array(),
777 'wgForeignFileRepos' => array(),
778 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
779 'wgExperimentalHtmlIds' => false,
780 'wgExternalLinkTarget' => false,
781 'wgAlwaysUseTidy' => false,
782 'wgHtml5' => true,
783 'wgWellFormedXml' => true,
784 'wgAllowMicrodataAttributes' => true,
785 'wgAdaptiveMessageCache' => true,
786 'wgDisableLangConversion' => false,
787 'wgDisableTitleConversion' => false,
788 );
789
790 if ( $config ) {
791 $configLines = explode( "\n", $config );
792
793 foreach ( $configLines as $line ) {
794 list( $var, $value ) = explode( '=', $line, 2 );
795
796 $settings[$var] = eval( "return $value;" );
797 }
798 }
799
800 $this->savedGlobals = array();
801
802 /** @since 1.20 */
803 wfRunHooks( 'ParserTestGlobals', array( &$settings ) );
804
805 foreach ( $settings as $var => $val ) {
806 if ( array_key_exists( $var, $GLOBALS ) ) {
807 $this->savedGlobals[$var] = $GLOBALS[$var];
808 }
809
810 $GLOBALS[$var] = $val;
811 }
812
813 $GLOBALS['wgContLang'] = Language::factory( $lang );
814 $GLOBALS['wgMemc'] = new EmptyBagOStuff;
815
816 $context = new RequestContext();
817 $GLOBALS['wgLang'] = $context->getLanguage();
818 $GLOBALS['wgOut'] = $context->getOutput();
819
820 $GLOBALS['wgUser'] = new User();
821
822 global $wgHooks;
823
824 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
825 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
826
827 MagicWord::clearCache();
828
829 return $context;
830 }
831
832 /**
833 * List of temporary tables to create, without prefix.
834 * Some of these probably aren't necessary.
835 */
836 private function listTables() {
837 $tables = array( 'user', 'user_properties', 'user_former_groups', 'page', 'page_restrictions',
838 'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
839 'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
840 'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
841 'recentchanges', 'watchlist', 'interwiki', 'logging',
842 'querycache', 'objectcache', 'job', 'l10n_cache', 'redirect', 'querycachetwo',
843 'archive', 'user_groups', 'page_props', 'category', 'msg_resource', 'msg_resource_links'
844 );
845
846 if ( in_array( $this->db->getType(), array( 'mysql', 'sqlite', 'oracle' ) ) ) {
847 array_push( $tables, 'searchindex' );
848 }
849
850 // Allow extensions to add to the list of tables to duplicate;
851 // may be necessary if they hook into page save or other code
852 // which will require them while running tests.
853 wfRunHooks( 'ParserTestTables', array( &$tables ) );
854
855 return $tables;
856 }
857
858 /**
859 * Set up a temporary set of wiki tables to work with for the tests.
860 * Currently this will only be done once per run, and any changes to
861 * the db will be visible to later tests in the run.
862 */
863 public function setupDatabase() {
864 global $wgDBprefix;
865
866 if ( $this->databaseSetupDone ) {
867 return;
868 }
869
870 $this->db = wfGetDB( DB_MASTER );
871 $dbType = $this->db->getType();
872
873 if ( $wgDBprefix === 'parsertest_' || ( $dbType == 'oracle' && $wgDBprefix === 'pt_' ) ) {
874 throw new MWException( 'setupDatabase should be called before setupGlobals' );
875 }
876
877 $this->databaseSetupDone = true;
878 $this->oldTablePrefix = $wgDBprefix;
879
880 # SqlBagOStuff broke when using temporary tables on r40209 (bug 15892).
881 # It seems to have been fixed since (r55079?), but regressed at some point before r85701.
882 # This works around it for now...
883 ObjectCache::$instances[CACHE_DB] = new HashBagOStuff;
884
885 # CREATE TEMPORARY TABLE breaks if there is more than one server
886 if ( wfGetLB()->getServerCount() != 1 ) {
887 $this->useTemporaryTables = false;
888 }
889
890 $temporary = $this->useTemporaryTables || $dbType == 'postgres';
891 $prefix = $dbType != 'oracle' ? 'parsertest_' : 'pt_';
892
893 $this->dbClone = new CloneDatabase( $this->db, $this->listTables(), $prefix );
894 $this->dbClone->useTemporaryTables( $temporary );
895 $this->dbClone->cloneTableStructure();
896
897 if ( $dbType == 'oracle' ) {
898 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
899 # Insert 0 user to prevent FK violations
900
901 # Anonymous user
902 $this->db->insert( 'user', array(
903 'user_id' => 0,
904 'user_name' => 'Anonymous' ) );
905 }
906
907 # Update certain things in site_stats
908 $this->db->insert( 'site_stats',
909 array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
910
911 # Reinitialise the LocalisationCache to match the database state
912 Language::getLocalisationCache()->unloadAll();
913
914 # Clear the message cache
915 MessageCache::singleton()->clear();
916
917 // Remember to update newParserTests.php after changing the below
918 // (and it uses a slightly different syntax just for teh lulz)
919 $this->uploadDir = $this->setupUploadDir();
920 $user = User::createNew( 'WikiSysop' );
921 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
922 # note that the size/width/height/bits/etc of the file
923 # are actually set by inspecting the file itself; the arguments
924 # to recordUpload2 have no effect. That said, we try to make things
925 # match up so it is less confusing to readers of the code & tests.
926 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
927 'size' => 7881,
928 'width' => 1941,
929 'height' => 220,
930 'bits' => 8,
931 'media_type' => MEDIATYPE_BITMAP,
932 'mime' => 'image/jpeg',
933 'metadata' => serialize( array() ),
934 'sha1' => wfBaseConvert( '1', 16, 36, 31 ),
935 'fileExists' => true
936 ), $this->db->timestamp( '20010115123500' ), $user );
937
938 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Thumb.png' ) );
939 # again, note that size/width/height below are ignored; see above.
940 $image->recordUpload2( '', 'Upload of some lame thumbnail', 'Some lame thumbnail', array(
941 'size' => 22589,
942 'width' => 135,
943 'height' => 135,
944 'bits' => 8,
945 'media_type' => MEDIATYPE_BITMAP,
946 'mime' => 'image/png',
947 'metadata' => serialize( array() ),
948 'sha1' => wfBaseConvert( '2', 16, 36, 31 ),
949 'fileExists' => true
950 ), $this->db->timestamp( '20130225203040' ), $user );
951
952 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.svg' ) );
953 $image->recordUpload2( '', 'Upload of some lame SVG', 'Some lame SVG', array(
954 'size' => 12345,
955 'width' => 240,
956 'height' => 180,
957 'bits' => 24,
958 'media_type' => MEDIATYPE_DRAWING,
959 'mime' => 'image/svg+xml',
960 'metadata' => serialize( array() ),
961 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
962 'fileExists' => true
963 ), $this->db->timestamp( '20010115123500' ), $user );
964
965 # This image will be blacklisted in [[MediaWiki:Bad image list]]
966 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
967 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
968 'size' => 12345,
969 'width' => 320,
970 'height' => 240,
971 'bits' => 24,
972 'media_type' => MEDIATYPE_BITMAP,
973 'mime' => 'image/jpeg',
974 'metadata' => serialize( array() ),
975 'sha1' => wfBaseConvert( '3', 16, 36, 31 ),
976 'fileExists' => true
977 ), $this->db->timestamp( '20010115123500' ), $user );
978 }
979
980 public function teardownDatabase() {
981 if ( !$this->databaseSetupDone ) {
982 $this->teardownGlobals();
983 return;
984 }
985 $this->teardownUploadDir( $this->uploadDir );
986
987 $this->dbClone->destroy();
988 $this->databaseSetupDone = false;
989
990 if ( $this->useTemporaryTables ) {
991 if ( $this->db->getType() == 'sqlite' ) {
992 # Under SQLite the searchindex table is virtual and need
993 # to be explicitly destroyed. See bug 29912
994 # See also MediaWikiTestCase::destroyDB()
995 wfDebug( __METHOD__ . " explicitly destroying sqlite virtual table parsertest_searchindex\n" );
996 $this->db->query( "DROP TABLE `parsertest_searchindex`" );
997 }
998 # Don't need to do anything
999 $this->teardownGlobals();
1000 return;
1001 }
1002
1003 $tables = $this->listTables();
1004
1005 foreach ( $tables as $table ) {
1006 if ( $this->db->getType() == 'oracle' ) {
1007 $this->db->query( "DROP TABLE pt_$table DROP CONSTRAINTS" );
1008 } else {
1009 $this->db->query( "DROP TABLE `parsertest_$table`" );
1010 }
1011 }
1012
1013 if ( $this->db->getType() == 'oracle' ) {
1014 $this->db->query( 'BEGIN FILL_WIKI_INFO; END;' );
1015 }
1016
1017 $this->teardownGlobals();
1018 }
1019
1020 /**
1021 * Create a dummy uploads directory which will contain a couple
1022 * of files in order to pass existence tests.
1023 *
1024 * @return String: the directory
1025 */
1026 private function setupUploadDir() {
1027 global $IP;
1028
1029 if ( $this->keepUploads ) {
1030 $dir = wfTempDir() . '/mwParser-images';
1031
1032 if ( is_dir( $dir ) ) {
1033 return $dir;
1034 }
1035 } else {
1036 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
1037 }
1038
1039 // wfDebug( "Creating upload directory $dir\n" );
1040 if ( file_exists( $dir ) ) {
1041 wfDebug( "Already exists!\n" );
1042 return $dir;
1043 }
1044
1045 wfMkdirParents( $dir . '/3/3a', null, __METHOD__ );
1046 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
1047 wfMkdirParents( $dir . '/e/ea', null, __METHOD__ );
1048 copy( "$IP/skins/monobook/wiki.png", "$dir/e/ea/Thumb.png" );
1049 wfMkdirParents( $dir . '/0/09', null, __METHOD__ );
1050 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
1051 wfMkdirParents( $dir . '/f/ff', null, __METHOD__ );
1052 copy( "$IP/skins/monobook/headbg.jpg", "$dir/f/ff/Foobar.svg" );
1053 file_put_contents( "$dir/f/ff/Foobar.svg",
1054 '<?xml version="1.0" encoding="utf-8"?>' .
1055 '<svg xmlns="http://www.w3.org/2000/svg" />' );
1056 return $dir;
1057 }
1058
1059 /**
1060 * Restore default values and perform any necessary clean-up
1061 * after each test runs.
1062 */
1063 private function teardownGlobals() {
1064 RepoGroup::destroySingleton();
1065 FileBackendGroup::destroySingleton();
1066 LockManagerGroup::destroySingletons();
1067 LinkCache::singleton()->clear();
1068
1069 foreach ( $this->savedGlobals as $var => $val ) {
1070 $GLOBALS[$var] = $val;
1071 }
1072 }
1073
1074 /**
1075 * Remove the dummy uploads directory
1076 */
1077 private function teardownUploadDir( $dir ) {
1078 if ( $this->keepUploads ) {
1079 return;
1080 }
1081
1082 // delete the files first, then the dirs.
1083 self::deleteFiles(
1084 array(
1085 "$dir/3/3a/Foobar.jpg",
1086 "$dir/thumb/3/3a/Foobar.jpg/180px-Foobar.jpg",
1087 "$dir/thumb/3/3a/Foobar.jpg/200px-Foobar.jpg",
1088 "$dir/thumb/3/3a/Foobar.jpg/640px-Foobar.jpg",
1089 "$dir/thumb/3/3a/Foobar.jpg/120px-Foobar.jpg",
1090 "$dir/thumb/3/3a/Foobar.jpg/1280px-Foobar.jpg",
1091 "$dir/thumb/3/3a/Foobar.jpg/20px-Foobar.jpg",
1092 "$dir/thumb/3/3a/Foobar.jpg/270px-Foobar.jpg",
1093 "$dir/thumb/3/3a/Foobar.jpg/300px-Foobar.jpg",
1094 "$dir/thumb/3/3a/Foobar.jpg/30px-Foobar.jpg",
1095 "$dir/thumb/3/3a/Foobar.jpg/360px-Foobar.jpg",
1096 "$dir/thumb/3/3a/Foobar.jpg/400px-Foobar.jpg",
1097 "$dir/thumb/3/3a/Foobar.jpg/40px-Foobar.jpg",
1098 "$dir/thumb/3/3a/Foobar.jpg/70px-Foobar.jpg",
1099 "$dir/thumb/3/3a/Foobar.jpg/960px-Foobar.jpg",
1100
1101 "$dir/e/ea/Thumb.png",
1102
1103 "$dir/0/09/Bad.jpg",
1104
1105 "$dir/f/ff/Foobar.svg",
1106 "$dir/thumb/f/ff/Foobar.svg/180px-Foobar.svg.png",
1107 "$dir/thumb/f/ff/Foobar.svg/360px-Foobar.svg.png",
1108 "$dir/thumb/f/ff/Foobar.svg/langde-270px-Foobar.svg.png",
1109 "$dir/thumb/f/ff/Foobar.svg/270px-Foobar.svg.png",
1110 "$dir/thumb/f/ff/Foobar.svg/langde-180px-Foobar.svg.png",
1111 "$dir/thumb/f/ff/Foobar.svg/langde-360px-Foobar.svg.png",
1112
1113 "$dir/math/f/a/5/fa50b8b616463173474302ca3e63586b.png",
1114 )
1115 );
1116
1117 self::deleteDirs(
1118 array(
1119 "$dir/3/3a",
1120 "$dir/3",
1121 "$dir/thumb/6/65",
1122 "$dir/thumb/6",
1123 "$dir/thumb/3/3a/Foobar.jpg",
1124 "$dir/thumb/3/3a",
1125 "$dir/thumb/3",
1126 "$dir/e/ea",
1127 "$dir/e",
1128 "$dir/f/ff/",
1129 "$dir/f/",
1130 "$dir/thumb/f/ff/Foobar.svg",
1131 "$dir/thumb/f/ff/",
1132 "$dir/thumb/f/",
1133 "$dir/0/09/",
1134 "$dir/0/",
1135 "$dir/thumb",
1136 "$dir/math/f/a/5",
1137 "$dir/math/f/a",
1138 "$dir/math/f",
1139 "$dir/math",
1140 "$dir",
1141 )
1142 );
1143 }
1144
1145 /**
1146 * Delete the specified files, if they exist.
1147 * @param $files Array: full paths to files to delete.
1148 */
1149 private static function deleteFiles( $files ) {
1150 foreach ( $files as $file ) {
1151 if ( file_exists( $file ) ) {
1152 unlink( $file );
1153 }
1154 }
1155 }
1156
1157 /**
1158 * Delete the specified directories, if they exist. Must be empty.
1159 * @param $dirs Array: full paths to directories to delete.
1160 */
1161 private static function deleteDirs( $dirs ) {
1162 foreach ( $dirs as $dir ) {
1163 if ( is_dir( $dir ) ) {
1164 rmdir( $dir );
1165 }
1166 }
1167 }
1168
1169 /**
1170 * "Running test $desc..."
1171 */
1172 protected function showTesting( $desc ) {
1173 print "Running test $desc... ";
1174 }
1175
1176 /**
1177 * Print a happy success message.
1178 *
1179 * Refactored in 1.22 to use ParserTestResult
1180 *
1181 * @param $testResult ParserTestResult
1182 * @return Boolean
1183 */
1184 protected function showSuccess( ParserTestResult $testResult ) {
1185 if ( $this->showProgress ) {
1186 print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
1187 }
1188
1189 return true;
1190 }
1191
1192 /**
1193 * Print a failure message and provide some explanatory output
1194 * about what went wrong if so configured.
1195 *
1196 * Refactored in 1.22 to use ParserTestResult
1197 *
1198 * @param $testResult ParserTestResult
1199 * @return Boolean
1200 */
1201 protected function showFailure( ParserTestResult $testResult ) {
1202 if ( $this->showFailure ) {
1203 if ( !$this->showProgress ) {
1204 # In quiet mode we didn't show the 'Testing' message before the
1205 # test, in case it succeeded. Show it now:
1206 $this->showTesting( $testResult->description );
1207 }
1208
1209 print $this->term->color( '31' ) . 'FAILED!' . $this->term->reset() . "\n";
1210
1211 if ( $this->showOutput ) {
1212 print "--- Expected ---\n{$testResult->expected}\n";
1213 print "--- Actual ---\n{$testResult->actual}\n";
1214 }
1215
1216 if ( $this->showDiffs ) {
1217 print $this->quickDiff( $testResult->expected, $testResult->actual );
1218 if ( !$this->wellFormed( $testResult->actual ) ) {
1219 print "XML error: $this->mXmlError\n";
1220 }
1221 }
1222 }
1223
1224 return false;
1225 }
1226
1227 /**
1228 * Run given strings through a diff and return the (colorized) output.
1229 * Requires writable /tmp directory and a 'diff' command in the PATH.
1230 *
1231 * @param $input String
1232 * @param $output String
1233 * @param $inFileTail String: tailing for the input file name
1234 * @param $outFileTail String: tailing for the output file name
1235 * @return String
1236 */
1237 protected function quickDiff( $input, $output,
1238 $inFileTail = 'expected', $outFileTail = 'actual'
1239 ) {
1240 # Windows, or at least the fc utility, is retarded
1241 $slash = wfIsWindows() ? '\\' : '/';
1242 $prefix = wfTempDir() . "{$slash}mwParser-" . mt_rand();
1243
1244 $infile = "$prefix-$inFileTail";
1245 $this->dumpToFile( $input, $infile );
1246
1247 $outfile = "$prefix-$outFileTail";
1248 $this->dumpToFile( $output, $outfile );
1249
1250 $shellInfile = wfEscapeShellArg( $infile );
1251 $shellOutfile = wfEscapeShellArg( $outfile );
1252
1253 global $wgDiff3;
1254 // we assume that people with diff3 also have usual diff
1255 $shellCommand = ( wfIsWindows() && !$wgDiff3 ) ? 'fc' : 'diff -au';
1256
1257 $diff = wfShellExec( "$shellCommand $shellInfile $shellOutfile" );
1258
1259 unlink( $infile );
1260 unlink( $outfile );
1261
1262 return $this->colorDiff( $diff );
1263 }
1264
1265 /**
1266 * Write the given string to a file, adding a final newline.
1267 *
1268 * @param $data String
1269 * @param $filename String
1270 */
1271 private function dumpToFile( $data, $filename ) {
1272 $file = fopen( $filename, "wt" );
1273 fwrite( $file, $data . "\n" );
1274 fclose( $file );
1275 }
1276
1277 /**
1278 * Colorize unified diff output if set for ANSI color output.
1279 * Subtractions are colored blue, additions red.
1280 *
1281 * @param $text String
1282 * @return String
1283 */
1284 protected function colorDiff( $text ) {
1285 return preg_replace(
1286 array( '/^(-.*)$/m', '/^(\+.*)$/m' ),
1287 array( $this->term->color( 34 ) . '$1' . $this->term->reset(),
1288 $this->term->color( 31 ) . '$1' . $this->term->reset() ),
1289 $text );
1290 }
1291
1292 /**
1293 * Show "Reading tests from ..."
1294 *
1295 * @param $path String
1296 */
1297 public function showRunFile( $path ) {
1298 print $this->term->color( 1 ) .
1299 "Reading tests from \"$path\"..." .
1300 $this->term->reset() .
1301 "\n";
1302 }
1303
1304 /**
1305 * Insert a temporary test article
1306 * @param $name String: the title, including any prefix
1307 * @param $text String: the article text
1308 * @param $line Integer: the input line number, for reporting errors
1309 * @param $ignoreDuplicate Boolean: whether to silently ignore duplicate pages
1310 */
1311 public static function addArticle( $name, $text, $line = 'unknown', $ignoreDuplicate = '' ) {
1312 global $wgCapitalLinks;
1313
1314 $oldCapitalLinks = $wgCapitalLinks;
1315 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
1316
1317 $text = self::chomp( $text );
1318 $name = self::chomp( $name );
1319
1320 $title = Title::newFromText( $name );
1321
1322 if ( is_null( $title ) ) {
1323 throw new MWException( "invalid title '$name' at line $line\n" );
1324 }
1325
1326 $page = WikiPage::factory( $title );
1327 $page->loadPageData( 'fromdbmaster' );
1328
1329 if ( $page->exists() ) {
1330 if ( $ignoreDuplicate == 'ignoreduplicate' ) {
1331 return;
1332 } else {
1333 throw new MWException( "duplicate article '$name' at line $line\n" );
1334 }
1335 }
1336
1337 $page->doEditContent( ContentHandler::makeContent( $text, $title ), '', EDIT_NEW );
1338
1339 $wgCapitalLinks = $oldCapitalLinks;
1340 }
1341
1342 /**
1343 * Steal a callback function from the primary parser, save it for
1344 * application to our scary parser. If the hook is not installed,
1345 * abort processing of this file.
1346 *
1347 * @param $name String
1348 * @return Bool true if tag hook is present
1349 */
1350 public function requireHook( $name ) {
1351 global $wgParser;
1352
1353 $wgParser->firstCallInit(); // make sure hooks are loaded.
1354
1355 if ( isset( $wgParser->mTagHooks[$name] ) ) {
1356 $this->hooks[$name] = $wgParser->mTagHooks[$name];
1357 } else {
1358 echo " This test suite requires the '$name' hook extension, skipping.\n";
1359 return false;
1360 }
1361
1362 return true;
1363 }
1364
1365 /**
1366 * Steal a callback function from the primary parser, save it for
1367 * application to our scary parser. If the hook is not installed,
1368 * abort processing of this file.
1369 *
1370 * @param $name String
1371 * @return Bool true if function hook is present
1372 */
1373 public function requireFunctionHook( $name ) {
1374 global $wgParser;
1375
1376 $wgParser->firstCallInit(); // make sure hooks are loaded.
1377
1378 if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
1379 $this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
1380 } else {
1381 echo " This test suite requires the '$name' function hook extension, skipping.\n";
1382 return false;
1383 }
1384
1385 return true;
1386 }
1387
1388 /**
1389 * Run the "tidy" command on text if the $wgUseTidy
1390 * global is true
1391 *
1392 * @param $text String: the text to tidy
1393 * @return String
1394 */
1395 private function tidy( $text ) {
1396 global $wgUseTidy;
1397
1398 if ( $wgUseTidy ) {
1399 $text = MWTidy::tidy( $text );
1400 }
1401
1402 return $text;
1403 }
1404
1405 private function wellFormed( $text ) {
1406 $html =
1407 Sanitizer::hackDocType() .
1408 '<html>' .
1409 $text .
1410 '</html>';
1411
1412 $parser = xml_parser_create( "UTF-8" );
1413
1414 # case folding violates XML standard, turn it off
1415 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
1416
1417 if ( !xml_parse( $parser, $html, true ) ) {
1418 $err = xml_error_string( xml_get_error_code( $parser ) );
1419 $position = xml_get_current_byte_index( $parser );
1420 $fragment = $this->extractFragment( $html, $position );
1421 $this->mXmlError = "$err at byte $position:\n$fragment";
1422 xml_parser_free( $parser );
1423
1424 return false;
1425 }
1426
1427 xml_parser_free( $parser );
1428
1429 return true;
1430 }
1431
1432 private function extractFragment( $text, $position ) {
1433 $start = max( 0, $position - 10 );
1434 $before = $position - $start;
1435 $fragment = '...' .
1436 $this->term->color( 34 ) .
1437 substr( $text, $start, $before ) .
1438 $this->term->color( 0 ) .
1439 $this->term->color( 31 ) .
1440 $this->term->color( 1 ) .
1441 substr( $text, $position, 1 ) .
1442 $this->term->color( 0 ) .
1443 $this->term->color( 34 ) .
1444 substr( $text, $position + 1, 9 ) .
1445 $this->term->color( 0 ) .
1446 '...';
1447 $display = str_replace( "\n", ' ', $fragment );
1448 $caret = ' ' .
1449 str_repeat( ' ', $before ) .
1450 $this->term->color( 31 ) .
1451 '^' .
1452 $this->term->color( 0 );
1453
1454 return "$display\n$caret";
1455 }
1456
1457 static function getFakeTimestamp( &$parser, &$ts ) {
1458 $ts = 123; //parsed as '1970-01-01T00:02:03Z'
1459 return true;
1460 }
1461 }