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