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