rm big whitespace
[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, $messageMemc;
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 //Various getter functions
546
547 /**
548 * Get an input dictionary from a set of parser test files
549 */
550 function getFuzzInput( $filenames ) {
551 $dict = '';
552
553 foreach ( $filenames as $filename ) {
554 $contents = file_get_contents( $filename );
555 preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
556
557 foreach ( $matches[1] as $match ) {
558 $dict .= $match . "\n";
559 }
560 }
561
562 return $dict;
563 }
564
565 /**
566 * Get a memory usage breakdown
567 */
568 function getMemoryBreakdown() {
569 $memStats = array();
570
571 foreach ( $GLOBALS as $name => $value ) {
572 $memStats['$' . $name] = strlen( serialize( $value ) );
573 }
574
575 $classes = get_declared_classes();
576
577 foreach ( $classes as $class ) {
578 $rc = new ReflectionClass( $class );
579 $props = $rc->getStaticProperties();
580 $memStats[$class] = strlen( serialize( $props ) );
581 $methods = $rc->getMethods();
582
583 foreach ( $methods as $method ) {
584 $memStats[$class] += strlen( serialize( $method->getStaticVariables() ) );
585 }
586 }
587
588 $functions = get_defined_functions();
589
590 foreach ( $functions['user'] as $function ) {
591 $rf = new ReflectionFunction( $function );
592 $memStats["$function()"] = strlen( serialize( $rf->getStaticVariables() ) );
593 }
594
595 asort( $memStats );
596
597 return $memStats;
598 }
599
600 /**
601 * Get a Parser object
602 */
603 function getParser( $preprocessor = null ) {
604 global $wgParserConf;
605
606 $class = $wgParserConf['class'];
607 $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
608
609 foreach ( $this->hooks as $tag => $callback ) {
610 $parser->setHook( $tag, $callback );
611 }
612
613 foreach ( $this->functionHooks as $tag => $bits ) {
614 list( $callback, $flags ) = $bits;
615 $parser->setFunctionHook( $tag, $callback, $flags );
616 }
617
618 wfRunHooks( 'ParserTestParser', array( &$parser ) );
619
620 return $parser;
621 }
622
623
624
625
626
627
628
629 //Various action functions
630
631 /**
632 * Insert a temporary test article
633 * @param $name String: the title, including any prefix
634 * @param $text String: the article text
635 * @param $line Integer: the input line number, for reporting errors
636 */
637 public function addArticle( $name, $text, $line = 'unknown' ) {
638 global $wgCapitalLinks;
639
640 $text = $this->removeEndingNewline($text);
641
642 $oldCapitalLinks = $wgCapitalLinks;
643 $wgCapitalLinks = true; // We only need this from SetupGlobals() See r70917#c8637
644
645 $name = $this->removeEndingNewline( $name );
646 $title = Title::newFromText( $name );
647
648 if ( is_null( $title ) ) {
649 throw new MWException( "invalid title ('$name' => '$title') at line $line\n" );
650 }
651
652 $aid = $title->getArticleID( Title::GAID_FOR_UPDATE );
653
654 if ( $aid != 0 ) {
655 debug_print_backtrace();
656 throw new MWException( "duplicate article '$name' at line $line\n" );
657 }
658
659 $art = new Article( $title );
660 $art->doEdit( $text, '', EDIT_NEW );
661
662 $wgCapitalLinks = $oldCapitalLinks;
663 }
664
665 /**
666 * Steal a callback function from the primary parser, save it for
667 * application to our scary parser. If the hook is not installed,
668 * abort processing of this file.
669 *
670 * @param $name String
671 * @return Bool true if tag hook is present
672 */
673 public function requireHook( $name ) {
674 global $wgParser;
675
676 $wgParser->firstCallInit( ); // make sure hooks are loaded.
677
678 if ( isset( $wgParser->mTagHooks[$name] ) ) {
679 $this->hooks[$name] = $wgParser->mTagHooks[$name];
680 } else {
681 echo " This test suite requires the '$name' hook extension, skipping.\n";
682 return false;
683 }
684
685 return true;
686 }
687
688
689
690
691
692 //Various "cleanup" functions
693
694 /*
695 * Run the "tidy" command on text if the $wgUseTidy
696 * global is true
697 *
698 * @param $text String: the text to tidy
699 * @return String
700 * @static
701 */
702 protected function tidy( $text ) {
703 global $wgUseTidy;
704
705 if ( $wgUseTidy ) {
706 $text = MWTidy::tidy( $text );
707 }
708
709 return $text;
710 }
711
712 /**
713 * Remove last character if it is a newline
714 */
715 public function removeEndingNewline( $s ) {
716 if ( substr( $s, -1 ) === "\n" ) {
717 return substr( $s, 0, -1 );
718 }
719 else {
720 return $s;
721 }
722 }
723
724
725
726
727
728
729 //Test options parser functions
730
731 protected function parseOptions( $instring ) {
732 $opts = array();
733 // foo
734 // foo=bar
735 // foo="bar baz"
736 // foo=[[bar baz]]
737 // foo=bar,"baz quux"
738 $regex = '/\b
739 ([\w-]+) # Key
740 \b
741 (?:\s*
742 = # First sub-value
743 \s*
744 (
745 "
746 [^"]* # Quoted val
747 "
748 |
749 \[\[
750 [^]]* # Link target
751 \]\]
752 |
753 [\w-]+ # Plain word
754 )
755 (?:\s*
756 , # Sub-vals 1..N
757 \s*
758 (
759 "[^"]*" # Quoted val
760 |
761 \[\[[^]]*\]\] # Link target
762 |
763 [\w-]+ # Plain word
764 )
765 )*
766 )?
767 /x';
768
769 if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
770 foreach ( $matches as $bits ) {
771 array_shift( $bits );
772 $key = strtolower( array_shift( $bits ) );
773 if ( count( $bits ) == 0 ) {
774 $opts[$key] = true;
775 } elseif ( count( $bits ) == 1 ) {
776 $opts[$key] = $this->cleanupOption( array_shift( $bits ) );
777 } else {
778 // Array!
779 $opts[$key] = array_map( array( $this, 'cleanupOption' ), $bits );
780 }
781 }
782 }
783 return $opts;
784 }
785
786 protected function cleanupOption( $opt ) {
787 if ( substr( $opt, 0, 1 ) == '"' ) {
788 return substr( $opt, 1, -1 );
789 }
790
791 if ( substr( $opt, 0, 2 ) == '[[' ) {
792 return substr( $opt, 2, -2 );
793 }
794 return $opt;
795 }
796
797 /**
798 * Use a regex to find out the value of an option
799 * @param $key String: name of option val to retrieve
800 * @param $opts Options array to look in
801 * @param $default Mixed: default value returned if not found
802 */
803 protected static function getOptionValue( $key, $opts, $default ) {
804 $key = strtolower( $key );
805
806 if ( isset( $opts[$key] ) ) {
807 return $opts[$key];
808 } else {
809 return $default;
810 }
811 }
812 }
813