ConfigParser.php 2.8 KB

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