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