dcd11747bd19e6e9197f15b513b1b3d316194b05
[lhc/web/wiklou.git] / tests / phpunit / includes / parser / NewParserTest.php
1 <?php
2
3 /**
4 * @group Database
5 */
6 class NewParserTest extends MediaWikiTestCase {
7
8 public $uploadDir;
9 public $keepUploads = false;
10 public $runDisabled = false;
11 public $regex = '';
12 public $showProgress = true;
13 public $savedInitialGlobals = array();
14 public $savedWeirdGlobals = array();
15 public $savedGlobals = array();
16 public $hooks = array();
17 public $functionHooks = array();
18
19 //Fuzz test
20 public $maxFuzzTestLength = 300;
21 public $fuzzSeed = 0;
22 public $memoryLimit = 50;
23
24
25
26 //PHPUnit + MediaWikiTestCase functions
27
28 function setUp() {
29 global $wgContLang, $wgUseDatabaseMessages, $wgMsgCacheExpiry, $wgNamespaceProtection, $wgNamespaceAliases, $IP;
30 $wgContLang = Language::factory( 'en' );
31
32 //Setup CLI arguments
33 if ( $this->getCliArg( 'regex=' ) ) {
34 $this->regex = $this->getCliArg( 'regex=' );
35 } else {
36 # Matches anything
37 $this->regex = '';
38 }
39
40 $this->keepUploads = $this->getCliArg( 'keep-uploads' );
41
42 $tmpGlobals = array();
43
44 $tmpGlobals['wgScript'] = '/index.php';
45 $tmpGlobals['wgScriptPath'] = '/';
46 $tmpGlobals['wgArticlePath'] = '/wiki/$1';
47 $tmpGlobals['wgStyleSheetPath'] = '/skins';
48 $tmpGlobals['wgStylePath'] = '/skins';
49 $tmpGlobals['wgThumbnailScriptPath'] = false;
50 $tmpGlobals['wgLocalFileRepo'] = array(
51 'class' => 'LocalRepo',
52 'name' => 'local',
53 'directory' => wfTempDir() . '/test-repo',
54 'url' => 'http://example.com/images',
55 'deletedDir' => wfTempDir() . '/test-repo/delete',
56 'hashLevels' => 2,
57 'transformVia404' => false,
58 );
59
60 $tmpGlobals['wgEnableParserCache'] = false;
61 $tmpGlobals['wgDeferredUpdateList'] = array();
62 $tmpGlobals['wgMemc'] = &wfGetMainCache();
63 $messageMemc = &wfGetMessageCacheStorage();
64 $tmpGlobals['parserMemc'] = &wfGetParserCacheStorage();
65
66 // $tmpGlobals['wgContLang'] = new StubContLang;
67 $tmpGlobals['wgUser'] = new User;
68 $tmpGlobals['wgLang'] = new StubUserLang;
69 $tmpGlobals['wgOut'] = new StubObject( 'wgOut', 'OutputPage' );
70 $tmpGlobals['wgParser'] = new StubObject( 'wgParser', $GLOBALS['wgParserConf']['class'], array( $GLOBALS['wgParserConf'] ) );
71 $tmpGlobals['wgRequest'] = new WebRequest;
72
73 $tmpGlobals['wgMessageCache'] = new StubObject( 'wgMessageCache', 'MessageCache',
74 array( $messageMemc, $wgUseDatabaseMessages,
75 $wgMsgCacheExpiry ) );
76 if ( $GLOBALS['wgStyleDirectory'] === false ) {
77 $tmpGlobals['wgStyleDirectory'] = "$IP/skins";
78 }
79
80
81 foreach ( $tmpGlobals as $var => $val ) {
82 if ( array_key_exists( $var, $GLOBALS ) ) {
83 $this->savedInitialGlobals[$var] = $GLOBALS[$var];
84 }
85
86 $GLOBALS[$var] = $val;
87 }
88
89 $this->savedWeirdGlobals['mw_namespace_protection'] = $wgNamespaceProtection[NS_MEDIAWIKI];
90 $this->savedWeirdGlobals['image_alias'] = $wgNamespaceAliases['Image'];
91 $this->savedWeirdGlobals['image_talk_alias'] = $wgNamespaceAliases['Image_talk'];
92
93 $wgNamespaceProtection[NS_MEDIAWIKI] = 'editinterface';
94 $wgNamespaceAliases['Image'] = NS_FILE;
95 $wgNamespaceAliases['Image_talk'] = NS_FILE_TALK;
96
97 }
98
99 public function tearDown() {
100
101 foreach ( $this->savedInitialGlobals as $var => $val ) {
102 $GLOBALS[$var] = $val;
103 }
104
105 global $wgNamespaceProtection, $wgNamespaceAliases;
106
107 $wgNamespaceProtection[NS_MEDIAWIKI] = $this->savedWeirdGlobals['mw_namespace_protection'];
108 $wgNamespaceAliases['Image'] = $this->savedWeirdGlobals['image_alias'];
109 $wgNamespaceAliases['Image_talk'] = $this->savedWeirdGlobals['image_talk_alias'];
110 }
111
112 function addDBData() {
113 # Hack: insert a few Wikipedia in-project interwiki prefixes,
114 # for testing inter-language links
115 $this->db->insert( 'interwiki', array(
116 array( 'iw_prefix' => 'wikipedia',
117 'iw_url' => 'http://en.wikipedia.org/wiki/$1',
118 'iw_api' => '',
119 'iw_wikiid' => '',
120 'iw_local' => 0 ),
121 array( 'iw_prefix' => 'meatball',
122 'iw_url' => 'http://www.usemod.com/cgi-bin/mb.pl?$1',
123 'iw_api' => '',
124 'iw_wikiid' => '',
125 'iw_local' => 0 ),
126 array( 'iw_prefix' => 'zh',
127 'iw_url' => 'http://zh.wikipedia.org/wiki/$1',
128 'iw_api' => '',
129 'iw_wikiid' => '',
130 'iw_local' => 1 ),
131 array( 'iw_prefix' => 'es',
132 'iw_url' => 'http://es.wikipedia.org/wiki/$1',
133 'iw_api' => '',
134 'iw_wikiid' => '',
135 'iw_local' => 1 ),
136 array( 'iw_prefix' => 'fr',
137 'iw_url' => 'http://fr.wikipedia.org/wiki/$1',
138 'iw_api' => '',
139 'iw_wikiid' => '',
140 'iw_local' => 1 ),
141 array( 'iw_prefix' => 'ru',
142 'iw_url' => 'http://ru.wikipedia.org/wiki/$1',
143 'iw_api' => '',
144 'iw_wikiid' => '',
145 'iw_local' => 1 ),
146 ) );
147
148
149 # Update certain things in site_stats
150 $this->db->insert( 'site_stats', array( 'ss_row_id' => 1, 'ss_images' => 2, 'ss_good_articles' => 1 ) );
151
152 # Reinitialise the LocalisationCache to match the database state
153 Language::getLocalisationCache()->unloadAll();
154
155 # Make a new message cache
156 global $wgMessageCache, $wgMemc;
157 $wgMessageCache = new MessageCache( $wgMemc, true, 3600 );
158
159 $this->uploadDir = $this->setupUploadDir();
160
161 $user = User::newFromId( 0 );
162
163 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Foobar.jpg' ) );
164 $image->recordUpload2( '', 'Upload of some lame file', 'Some lame file', array(
165 'size' => 12345,
166 'width' => 1941,
167 'height' => 220,
168 'bits' => 24,
169 'media_type' => MEDIATYPE_BITMAP,
170 'mime' => 'image/jpeg',
171 'metadata' => serialize( array() ),
172 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
173 'fileExists' => true
174 ), $this->db->timestamp( '20010115123500' ), $user );
175
176 # This image will be blacklisted in [[MediaWiki:Bad image list]]
177 $image = wfLocalFile( Title::makeTitle( NS_FILE, 'Bad.jpg' ) );
178 $image->recordUpload2( '', 'zomgnotcensored', 'Borderline image', array(
179 'size' => 12345,
180 'width' => 320,
181 'height' => 240,
182 'bits' => 24,
183 'media_type' => MEDIATYPE_BITMAP,
184 'mime' => 'image/jpeg',
185 'metadata' => serialize( array() ),
186 'sha1' => wfBaseConvert( '', 16, 36, 31 ),
187 'fileExists' => true
188 ), $this->db->timestamp( '20010115123500' ), $user );
189
190 }
191
192
193
194
195 //ParserTest setup/teardown functions
196
197 /**
198 * Set up the global variables for a consistent environment for each test.
199 * Ideally this should replace the global configuration entirely.
200 */
201 protected function setupGlobals( $opts = '', $config = '' ) {
202 # Find out values for some special options.
203 $lang =
204 self::getOptionValue( 'language', $opts, 'en' );
205 $variant =
206 self::getOptionValue( 'variant', $opts, false );
207 $maxtoclevel =
208 self::getOptionValue( 'wgMaxTocLevel', $opts, 999 );
209 $linkHolderBatchSize =
210 self::getOptionValue( 'wgLinkHolderBatchSize', $opts, 1000 );
211
212 $settings = array(
213 'wgServer' => 'http://Britney-Spears',
214 'wgScript' => '/index.php',
215 'wgScriptPath' => '/',
216 'wgArticlePath' => '/wiki/$1',
217 'wgActionPaths' => array(),
218 'wgLocalFileRepo' => array(
219 'class' => 'LocalRepo',
220 'name' => 'local',
221 'directory' => $this->uploadDir,
222 'url' => 'http://example.com/images',
223 'hashLevels' => 2,
224 'transformVia404' => false,
225 ),
226 'wgEnableUploads' => self::getOptionValue( 'wgEnableUploads', $opts, true ),
227 'wgStylePath' => '/skins',
228 'wgStyleSheetPath' => '/skins',
229 'wgSitename' => 'MediaWiki',
230 'wgLanguageCode' => $lang,
231 'wgDBprefix' => $this->db->getType() != 'oracle' ? 'unittest_' : 'ut_',
232 'wgRawHtml' => isset( $opts['rawhtml'] ),
233 'wgLang' => null,
234 'wgContLang' => null,
235 'wgNamespacesWithSubpages' => array( 0 => isset( $opts['subpage'] ) ),
236 'wgMaxTocLevel' => $maxtoclevel,
237 'wgCapitalLinks' => true,
238 'wgNoFollowLinks' => true,
239 'wgNoFollowDomainExceptions' => array(),
240 'wgThumbnailScriptPath' => false,
241 'wgUseImageResize' => false,
242 'wgUseTeX' => isset( $opts['math'] ),
243 'wgMathDirectory' => $this->uploadDir . '/math',
244 'wgLocaltimezone' => 'UTC',
245 'wgAllowExternalImages' => true,
246 'wgUseTidy' => false,
247 'wgDefaultLanguageVariant' => $variant,
248 'wgVariantArticlePath' => false,
249 'wgGroupPermissions' => array( '*' => array(
250 'createaccount' => true,
251 'read' => true,
252 'edit' => true,
253 'createpage' => true,
254 'createtalk' => true,
255 ) ),
256 'wgNamespaceProtection' => array( NS_MEDIAWIKI => 'editinterface' ),
257 'wgDefaultExternalStore' => array(),
258 'wgForeignFileRepos' => array(),
259 'wgLinkHolderBatchSize' => $linkHolderBatchSize,
260 'wgExperimentalHtmlIds' => false,
261 'wgExternalLinkTarget' => false,
262 'wgAlwaysUseTidy' => false,
263 'wgHtml5' => true,
264 'wgWellFormedXml' => true,
265 'wgAllowMicrodataAttributes' => true,
266 'wgAdaptiveMessageCache' => true
267 );
268
269 if ( $config ) {
270 $configLines = explode( "\n", $config );
271
272 foreach ( $configLines as $line ) {
273 list( $var, $value ) = explode( '=', $line, 2 );
274
275 $settings[$var] = eval( "return $value;" ); //???
276 }
277 }
278
279 $this->savedGlobals = array();
280
281 foreach ( $settings as $var => $val ) {
282 if ( array_key_exists( $var, $GLOBALS ) ) {
283 $this->savedGlobals[$var] = $GLOBALS[$var];
284 }
285
286 $GLOBALS[$var] = $val;
287 }
288
289 $langObj = Language::factory( $lang );
290 $GLOBALS['wgLang'] = $langObj;
291 $GLOBALS['wgContLang'] = $langObj;
292 $GLOBALS['wgMemc'] = new FakeMemCachedClient;
293 $GLOBALS['wgOut'] = new OutputPage;
294
295 global $wgHooks;
296
297 $wgHooks['ParserTestParser'][] = 'ParserTestParserHook::setup';
298 $wgHooks['ParserTestParser'][] = 'ParserTestStaticParserHook::setup';
299 $wgHooks['ParserGetVariableValueTs'][] = 'ParserTest::getFakeTimestamp';
300
301 MagicWord::clearCache();
302
303 global $wgUser;
304 $wgUser = new User();
305 }
306
307 /**
308 * Restore default values and perform any necessary clean-up
309 * after each test runs.
310 */
311 protected function teardownGlobals() {
312 RepoGroup::destroySingleton();
313 LinkCache::singleton()->clear();
314
315 foreach ( $this->savedGlobals as $var => $val ) {
316 $GLOBALS[$var] = $val;
317 }
318 }
319
320 /**
321 * Create a dummy uploads directory which will contain a couple
322 * of files in order to pass existence tests.
323 *
324 * @return String: the directory
325 */
326 protected function setupUploadDir() {
327 global $IP;
328
329 if ( $this->keepUploads ) {
330 $dir = wfTempDir() . '/mwParser-images';
331
332 if ( is_dir( $dir ) ) {
333 return $dir;
334 }
335 } else {
336 $dir = wfTempDir() . "/mwParser-" . mt_rand() . "-images";
337 }
338
339 // wfDebug( "Creating upload directory $dir\n" );
340 if ( file_exists( $dir ) ) {
341 wfDebug( "Already exists!\n" );
342 return $dir;
343 }
344
345 wfMkdirParents( $dir . '/3/3a' );
346 copy( "$IP/skins/monobook/headbg.jpg", "$dir/3/3a/Foobar.jpg" );
347 wfMkdirParents( $dir . '/0/09' );
348 copy( "$IP/skins/monobook/headbg.jpg", "$dir/0/09/Bad.jpg" );
349
350 return $dir;
351 }
352
353
354
355
356
357 //Actual test suites
358
359 public function testParserTests() {
360
361 global $wgParserTestFiles;
362
363 $files = $wgParserTestFiles;
364
365 if( $this->getCliArg( 'file=' ) ) {
366 $files = array( $this->getCliArg( 'file=' ) );
367 }
368
369 foreach( $files as $file ) {
370
371 $iter = new ParserTestFileIterator( $file, $this );
372
373 foreach ( $iter as $t ) {
374
375 try {
376
377 $desc = $t['test'];
378 $input = $t['input'];
379 $result = $t['result'];
380 $opts = $t['options'];
381 $config = $t['config'];
382
383
384 $opts = $this->parseOptions( $opts );
385 $this->setupGlobals( $opts, $config );
386
387 $user = new User();
388 $options = ParserOptions::newFromUser( $user );
389
390 if ( isset( $opts['title'] ) ) {
391 $titleText = $opts['title'];
392 }
393 else {
394 $titleText = 'Parser test';
395 }
396
397 $local = isset( $opts['local'] );
398 $preprocessor = isset( $opts['preprocessor'] ) ? $opts['preprocessor'] : null;
399 $parser = $this->getParser( $preprocessor );
400 $title = Title::newFromText( $titleText );
401
402 if ( isset( $opts['pst'] ) ) {
403 $out = $parser->preSaveTransform( $input, $title, $user, $options );
404 } elseif ( isset( $opts['msg'] ) ) {
405 $out = $parser->transformMsg( $input, $options );
406 } elseif ( isset( $opts['section'] ) ) {
407 $section = $opts['section'];
408 $out = $parser->getSection( $input, $section );
409 } elseif ( isset( $opts['replace'] ) ) {
410 $section = $opts['replace'][0];
411 $replace = $opts['replace'][1];
412 $out = $parser->replaceSection( $input, $section, $replace );
413 } elseif ( isset( $opts['comment'] ) ) {
414 $linker = $user->getSkin();
415 $out = $linker->formatComment( $input, $title, $local );
416 } elseif ( isset( $opts['preload'] ) ) {
417 $out = $parser->getpreloadText( $input, $title, $options );
418 } else {
419 $output = $parser->parse( $input, $title, $options, true, true, 1337 );
420 $out = $output->getText();
421
422 if ( isset( $opts['showtitle'] ) ) {
423 if ( $output->getTitleText() ) {
424 $title = $output->getTitleText();
425 }
426
427 $out = "$title\n$out";
428 }
429
430 if ( isset( $opts['ill'] ) ) {
431 $out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
432 } elseif ( isset( $opts['cat'] ) ) {
433 global $wgOut;
434
435 $wgOut->addCategoryLinks( $output->getCategories() );
436 $cats = $wgOut->getCategoryLinks();
437
438 if ( isset( $cats['normal'] ) ) {
439 $out = $this->tidy( implode( ' ', $cats['normal'] ) );
440 } else {
441 $out = '';
442 }
443 }
444
445 $result = $this->tidy( $result );
446 }
447
448 $this->teardownGlobals();
449
450 $this->assertEquals( $result, $out, $desc );
451
452 }
453 catch( Exception $e ) {
454 $this->assertTrue( false, $t['test'] . ' (failed: ' . $e->getMessage() . ')' );
455 }
456
457 }
458
459 }
460
461 }
462
463 /**
464 * Run a fuzz test series
465 * Draw input from a set of test files
466 */
467 function testFuzzTests() {
468
469 $this->markTestIncomplete( 'Breaks tesla due to memory restrictions' );
470
471 global $wgParserTestFiles;
472
473 $files = $wgParserTestFiles;
474
475 if( $this->getCliArg( 'file=' ) ) {
476 $files = array( $this->getCliArg( 'file=' ) );
477 }
478
479 $dict = $this->getFuzzInput( $files );
480 $dictSize = strlen( $dict );
481 $logMaxLength = log( $this->maxFuzzTestLength );
482
483 ini_set( 'memory_limit', $this->memoryLimit * 1048576 );
484
485 $user = new User;
486 $opts = ParserOptions::newFromUser( $user );
487 $title = Title::makeTitle( NS_MAIN, 'Parser_test' );
488
489 $id = 1;
490
491 while ( true ) {
492
493 // Generate test input
494 mt_srand( ++$this->fuzzSeed );
495 $totalLength = mt_rand( 1, $this->maxFuzzTestLength );
496 $input = '';
497
498 while ( strlen( $input ) < $totalLength ) {
499 $logHairLength = mt_rand( 0, 1000000 ) / 1000000 * $logMaxLength;
500 $hairLength = min( intval( exp( $logHairLength ) ), $dictSize );
501 $offset = mt_rand( 0, $dictSize - $hairLength );
502 $input .= substr( $dict, $offset, $hairLength );
503 }
504
505 $this->setupGlobals();
506 $parser = $this->getParser();
507
508 // Run the test
509 try {
510 $parser->parse( $input, $title, $opts );
511 $this->assertTrue( true, "Test $id, fuzz seed {$this->fuzzSeed}" );
512 } catch ( Exception $exception ) {
513
514 ob_start();
515 var_dump( $input );
516 $input_dump = ob_get_contents();
517 ob_end_clean();
518
519 $this->assertTrue( false, "Test $id, fuzz seed {$this->fuzzSeed}. \n\nInput: $input_dump\n\nError: {$exception->getMessage()}\n\nBacktrace: {$exception->getTraceAsString()}" );
520 }
521
522 $this->teardownGlobals();
523 $parser->__destruct();
524
525 if ( $id % 100 == 0 ) {
526 $usage = intval( memory_get_usage( true ) / $this->memoryLimit / 1048576 * 100 );
527 //echo "{$this->fuzzSeed}: $numSuccess/$numTotal (mem: $usage%)\n";
528 if ( $usage > 90 ) {
529 $ret = "Out of memory:\n";
530 $memStats = $this->getMemoryBreakdown();
531
532 foreach ( $memStats as $name => $usage ) {
533 $ret .= "$name: $usage\n";
534 }
535
536 throw new MWException( $ret );
537 }
538 }
539
540 $id++;
541
542 }
543 }
544
545
546
547
548
549
550
551 //Various getter functions
552
553 /**
554 * Get an input dictionary from a set of parser test files
555 */
556 function getFuzzInput( $filenames ) {
557 $dict = '';
558
559 foreach ( $filenames as $filename ) {
560 $contents = file_get_contents( $filename );
561 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
562
563 foreach ( $matches[1] as $match ) {
564 $dict .= $match . "\n";
565 }
566 }
567
568 return $dict;
569 }
570
571 /**
572 * Get a memory usage breakdown
573 */
574 function getMemoryBreakdown() {
575 $memStats = array();
576
577 foreach ( $GLOBALS as $name => $value ) {
578 $memStats['$' . $name] = strlen( serialize( $value ) );
579 }
580
581 $classes = get_declared_classes();
582
583 foreach ( $classes as $class ) {
584 $rc = new ReflectionClass( $class );
585 $props = $rc->getStaticProperties();
586 $memStats[$class] = strlen( serialize( $props ) );
587 $methods = $rc->getMethods();
588
589 foreach ( $methods as $method ) {
590 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
591 }
592 }
593
594 $functions = get_defined_functions();
595
596 foreach ( $functions['user'] as $function ) {
597 $rf = new ReflectionFunction( $function );
598 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
599 }
600
601 asort( $memStats );
602
603 return $memStats;
604 }
605
606 /**
607 * Get a Parser object
608 */
609 function getParser( $preprocessor = null ) {
610 global $wgParserConf;
611
612 $class = $wgParserConf['class'];
613 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
614
615 foreach ( $this->hooks as $tag => $callback ) {
616 $parser->setHook( $tag, $callback );
617 }
618
619 foreach ( $this->functionHooks as $tag => $bits ) {
620 list( $callback, $flags ) = $bits;
621 $parser->setFunctionHook( $tag, $callback, $flags );
622 }
623
624 wfRunHooks( 'ParserTestParser', array( &$parser ) );
625
626 return $parser;
627 }
628
629
630
631
632
633
634
635 //Various action functions
636
637 /**
638 * Insert a temporary test article
639 * @param $name String: the title, including any prefix
640 * @param $text String: the article text
641 * @param $line Integer: the input line number, for reporting errors
642 */
643 public function addArticle( $name, $text, $line = 'unknown' ) {
644 global $wgCapitalLinks;
645
646 $text = $this->removeEndingNewline($text);
647
648 $oldCapitalLinks = $wgCapitalLinks;
649 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
650
651 $name = $this->removeEndingNewline( $name );
652 $title = Title::newFromText( $name );
653
654 if ( is_null( $title ) ) {
655 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
656 }
657
658 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
659
660 if ( $aid != 0 ) {
661 debug_print_backtrace();
662 throw new MWException( "duplicate article '$name' at line $line\n" );
663 }
664
665 $art = new Article( $title );
666 $art->doEdit( $text, '', EDIT_NEW );
667
668 $wgCapitalLinks = $oldCapitalLinks;
669 }
670
671 /**
672 * Steal a callback function from the primary parser, save it for
673 * application to our scary parser. If the hook is not installed,
674 * abort processing of this file.
675 *
676 * @param $name String
677 * @return Bool true if tag hook is present
678 */
679 public function requireHook( $name ) {
680 global $wgParser;
681
682 $wgParser->firstCallInit( ); // make sure hooks are loaded.
683
684 if ( isset( $wgParser->mTagHooks[$name] ) ) {
685 $this->hooks[$name] = $wgParser->mTagHooks[$name];
686 } else {
687 echo " This test suite requires the '$name' hook extension, skipping.\n";
688 return false;
689 }
690
691 return true;
692 }
693
694
695
696
697
698 //Various "cleanup" functions
699
700 /*
701 * Run the "tidy" command on text if the $wgUseTidy
702 * global is true
703 *
704 * @param $text String: the text to tidy
705 * @return String
706 * @static
707 */
708 protected function tidy( $text ) {
709 global $wgUseTidy;
710
711 if ( $wgUseTidy ) {
712 $text = MWTidy::tidy( $text );
713 }
714
715 return $text;
716 }
717
718 /**
719 * Remove last character if it is a newline
720 */
721 public function removeEndingNewline( $s ) {
722 if ( substr( $s, -1 ) === "\n" ) {
723 return substr( $s, 0, -1 );
724 }
725 else {
726 return $s;
727 }
728 }
729
730
731
732
733
734
735 //Test options parser functions
736
737 protected function parseOptions( $instring ) {
738 $opts = array();
739 // foo
740 // foo=bar
741 // foo="bar baz"
742 // foo=[[bar baz]]
743 // foo=bar,"baz quux"
744 $regex = '/\b
745 ([\w-]+) # Key
746 \b
747 (?:\s*
748 = # First sub-value
749 \s*
750 (
751 "
752 [^"]* # Quoted val
753 "
754 |
755 \[\[
756 [^]]* # Link target
757 \]\]
758 |
759 [\w-]+ # Plain word
760 )
761 (?:\s*
762 , # Sub-vals 1..N
763 \s*
764 (
765 "[^"]*" # Quoted val
766 |
767 \[\[[^]]*\]\] # Link target
768 |
769 [\w-]+ # Plain word
770 )
771 )*
772 )?
773 /x';
774
775 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
776 foreach ( $matches as $bits ) {
777 array_shift( $bits );
778 $key = strtolower( array_shift( $bits ) );
779 if ( count( $bits ) == 0 ) {
780 $opts[$key] = true;
781 } elseif ( count( $bits ) == 1 ) {
782 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
783 } else {
784 // Array!
785 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
786 }
787 }
788 }
789 return $opts;
790 }
791
792 protected function cleanupOption( $opt ) {
793 if ( substr( $opt, 0, 1 ) == '"' ) {
794 return substr( $opt, 1, -1 );
795 }
796
797 if ( substr( $opt, 0, 2 ) == '[[' ) {
798 return substr( $opt, 2, -2 );
799 }
800 return $opt;
801 }
802
803 /**
804 * Use a regex to find out the value of an option
805 * @param $key String: name of option val to retrieve
806 * @param $opts Options array to look in
807 * @param $default Mixed: default value returned if not found
808 */
809 protected static function getOptionValue( $key, $opts, $default ) {
810 $key = strtolower( $key );
811
812 if ( isset( $opts[$key] ) ) {
813 return $opts[$key];
814 } else {
815 return $default;
816 }
817 }
818 }
819