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