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