You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

102 lines
2.8 KiB

  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. {
  13. /** @var string variable to parse from the file */
  14. protected $varname = 'conf';
  15. /** @var string the key to mark sub arrays */
  16. protected $keymarker = Configuration::KEYMARKER;
  17. /**
  18. * Parse the given PHP file into an array
  19. *
  20. * When the given files does not exist, this returns an empty array
  21. *
  22. * @param string $file
  23. * @return array
  24. */
  25. public function parse($file)
  26. {
  27. if (!file_exists($file)) return [];
  28. $config = [];
  29. $contents = @php_strip_whitespace($file);
  30. // fallback to simply including the file #3271
  31. if ($contents === null) {
  32. $conf = [];
  33. include $file;
  34. return $conf;
  35. }
  36. $pattern = '/\$' . $this->varname . '\[[\'"]([^=]+)[\'"]\] ?= ?(.*?);(?=[^;]*(?:\$' . $this->varname . '|$))/s';
  37. $matches = [];
  38. preg_match_all($pattern, $contents, $matches, PREG_SET_ORDER);
  39. $counter = count($matches);
  40. for ($i = 0; $i < $counter; $i++) {
  41. $value = $matches[$i][2];
  42. // merge multi-dimensional array indices using the keymarker
  43. $key = preg_replace('/.\]\[./', $this->keymarker, $matches[$i][1]);
  44. // handle arrays
  45. if (preg_match('/^array ?\((.*)\)/', $value, $match)) {
  46. $arr = explode(',', $match[1]);
  47. // remove quotes from quoted strings & unescape escaped data
  48. $len = count($arr);
  49. for ($j = 0; $j < $len; $j++) {
  50. $arr[$j] = trim($arr[$j]);
  51. $arr[$j] = $this->readValue($arr[$j]);
  52. }
  53. $value = $arr;
  54. } else {
  55. $value = $this->readValue($value);
  56. }
  57. $config[$key] = $value;
  58. }
  59. return $config;
  60. }
  61. /**
  62. * Convert php string into value
  63. *
  64. * @param string $value
  65. * @return bool|string
  66. */
  67. protected function readValue($value)
  68. {
  69. $removequotes_pattern = '/^(\'|")(.*)(?<!\\\\)\1$/s';
  70. $unescape_pairs = [
  71. '\\\\' => '\\',
  72. '\\\'' => '\'',
  73. '\\"' => '"'
  74. ];
  75. if ($value == 'true') {
  76. $value = true;
  77. } elseif ($value == 'false') {
  78. $value = false;
  79. } else {
  80. // remove quotes from quoted strings & unescape escaped data
  81. $value = preg_replace($removequotes_pattern, '$2', $value);
  82. $value = strtr($value, $unescape_pairs);
  83. }
  84. return $value;
  85. }
  86. }