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