1<?php 2 3namespace dokuwiki\plugin\config\core; 4 5/** 6 * A naive PHP file parser 7 * 8 * This parses our very simple config file in PHP format. We use this instead of simply including 9 * the file, because we want to keep expressions such as 24*60*60 as is. 10 * 11 * @author Chris Smith <chris@jalakai.co.uk> 12 */ 13class ConfigParser { 14 /** @var string variable to parse from the file */ 15 protected $varname = 'conf'; 16 /** @var string the key to mark sub arrays */ 17 protected $keymarker = Configuration::KEYMARKER; 18 19 /** 20 * Parse the given PHP file into an array 21 * 22 * When the given files does not exist, this returns an empty array 23 * 24 * @param string $file 25 * @return array 26 */ 27 public function parse($file) { 28 if(!file_exists($file)) return array(); 29 30 $config = array(); 31 $contents = @php_strip_whitespace($file); 32 $pattern = '/\$' . $this->varname . '\[[\'"]([^=]+)[\'"]\] ?= ?(.*?);(?=[^;]*(?:\$' . $this->varname . '|$))/s'; 33 $matches = array(); 34 preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER); 35 36 for($i = 0; $i < count($matches); $i++) { 37 $value = $matches[$i][2]; 38 39 // merge multi-dimensional array indices using the keymarker 40 $key = preg_replace('/.\]\[./', $this->keymarker, $matches[$i][1]); 41 42 // handle arrays 43 if(preg_match('/^array ?\((.*)\)/', $value, $match)) { 44 $arr = explode(',', $match[1]); 45 46 // remove quotes from quoted strings & unescape escaped data 47 $len = count($arr); 48 for($j = 0; $j < $len; $j++) { 49 $arr[$j] = trim($arr[$j]); 50 $arr[$j] = $this->readValue($arr[$j]); 51 } 52 53 $value = $arr; 54 } else { 55 $value = $this->readValue($value); 56 } 57 58 $config[$key] = $value; 59 } 60 61 return $config; 62 } 63 64 /** 65 * Convert php string into value 66 * 67 * @param string $value 68 * @return bool|string 69 */ 70 protected function readValue($value) { 71 $removequotes_pattern = '/^(\'|")(.*)(?<!\\\\)\1$/s'; 72 $unescape_pairs = array( 73 '\\\\' => '\\', 74 '\\\'' => '\'', 75 '\\"' => '"' 76 ); 77 78 if($value == 'true') { 79 $value = true; 80 } elseif($value == 'false') { 81 $value = false; 82 } else { 83 // remove quotes from quoted strings & unescape escaped data 84 $value = preg_replace($removequotes_pattern, '$2', $value); 85 $value = strtr($value, $unescape_pairs); 86 } 87 return $value; 88 } 89 90} 91