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