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.

271 lines
7.4 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Adam Williamson <awilliam@redhat.com>
  6. * @author Aldo "xoen" Giambelluca <xoen@xoen.org>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Brice Maron <brice@bmaron.net>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Frank Karlitschek <frank@karlitschek.de>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  14. * @author Joas Schilling <coding@schilljs.com>
  15. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Philipp Schaffrath <github@philipp.schaffrath.email>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OC;
  39. /**
  40. * This class is responsible for reading and writing config.php, the very basic
  41. * configuration file of Nextcloud.
  42. */
  43. class Config {
  44. public const ENV_PREFIX = 'NC_';
  45. /** @var array Associative array ($key => $value) */
  46. protected $cache = [];
  47. /** @var string */
  48. protected $configDir;
  49. /** @var string */
  50. protected $configFilePath;
  51. /** @var string */
  52. protected $configFileName;
  53. /**
  54. * @param string $configDir Path to the config dir, needs to end with '/'
  55. * @param string $fileName (Optional) Name of the config file. Defaults to config.php
  56. */
  57. public function __construct($configDir, $fileName = 'config.php') {
  58. $this->configDir = $configDir;
  59. $this->configFilePath = $this->configDir.$fileName;
  60. $this->configFileName = $fileName;
  61. $this->readData();
  62. }
  63. /**
  64. * Lists all available config keys
  65. *
  66. * Please note that it does not return the values.
  67. *
  68. * @return array an array of key names
  69. */
  70. public function getKeys() {
  71. return array_keys($this->cache);
  72. }
  73. /**
  74. * Returns a config value
  75. *
  76. * gets its value from an `NC_` prefixed environment variable
  77. * if it doesn't exist from config.php
  78. * if this doesn't exist either, it will return the given `$default`
  79. *
  80. * @param string $key key
  81. * @param mixed $default = null default value
  82. * @return mixed the value or $default
  83. */
  84. public function getValue($key, $default = null) {
  85. $envValue = getenv(self::ENV_PREFIX . $key);
  86. if ($envValue !== false) {
  87. return $envValue;
  88. }
  89. if (isset($this->cache[$key])) {
  90. return $this->cache[$key];
  91. }
  92. return $default;
  93. }
  94. /**
  95. * Sets and deletes values and writes the config.php
  96. *
  97. * @param array $configs Associative array with `key => value` pairs
  98. * If value is null, the config key will be deleted
  99. */
  100. public function setValues(array $configs) {
  101. $needsUpdate = false;
  102. foreach ($configs as $key => $value) {
  103. if ($value !== null) {
  104. $needsUpdate |= $this->set($key, $value);
  105. } else {
  106. $needsUpdate |= $this->delete($key);
  107. }
  108. }
  109. if ($needsUpdate) {
  110. // Write changes
  111. $this->writeData();
  112. }
  113. }
  114. /**
  115. * Sets the value and writes it to config.php if required
  116. *
  117. * @param string $key key
  118. * @param mixed $value value
  119. */
  120. public function setValue($key, $value) {
  121. if ($this->set($key, $value)) {
  122. // Write changes
  123. $this->writeData();
  124. }
  125. }
  126. /**
  127. * This function sets the value
  128. *
  129. * @param string $key key
  130. * @param mixed $value value
  131. * @return bool True if the file needs to be updated, false otherwise
  132. */
  133. protected function set($key, $value) {
  134. if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
  135. // Add change
  136. $this->cache[$key] = $value;
  137. return true;
  138. }
  139. return false;
  140. }
  141. /**
  142. * Removes a key from the config and removes it from config.php if required
  143. * @param string $key
  144. */
  145. public function deleteKey($key) {
  146. if ($this->delete($key)) {
  147. // Write changes
  148. $this->writeData();
  149. }
  150. }
  151. /**
  152. * This function removes a key from the config
  153. *
  154. * @param string $key
  155. * @return bool True if the file needs to be updated, false otherwise
  156. */
  157. protected function delete($key) {
  158. if (isset($this->cache[$key])) {
  159. // Delete key from cache
  160. unset($this->cache[$key]);
  161. return true;
  162. }
  163. return false;
  164. }
  165. /**
  166. * Loads the config file
  167. *
  168. * Reads the config file and saves it to the cache
  169. *
  170. * @throws \Exception If no lock could be acquired or the config file has not been found
  171. */
  172. private function readData() {
  173. // Default config should always get loaded
  174. $configFiles = [$this->configFilePath];
  175. // Add all files in the config dir ending with the same file name
  176. $extra = glob($this->configDir.'*.'.$this->configFileName);
  177. if (is_array($extra)) {
  178. natsort($extra);
  179. $configFiles = array_merge($configFiles, $extra);
  180. }
  181. // Include file and merge config
  182. foreach ($configFiles as $file) {
  183. $fileExistsAndIsReadable = file_exists($file) && is_readable($file);
  184. $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
  185. if ($file === $this->configFilePath &&
  186. $filePointer === false) {
  187. // Opening the main config might not be possible, e.g. if the wrong
  188. // permissions are set (likely on a new installation)
  189. continue;
  190. }
  191. // Try to acquire a file lock
  192. if (!flock($filePointer, LOCK_SH)) {
  193. throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
  194. }
  195. unset($CONFIG);
  196. include $file;
  197. if (isset($CONFIG) && is_array($CONFIG)) {
  198. $this->cache = array_merge($this->cache, $CONFIG);
  199. }
  200. // Close the file pointer and release the lock
  201. flock($filePointer, LOCK_UN);
  202. fclose($filePointer);
  203. }
  204. }
  205. /**
  206. * Writes the config file
  207. *
  208. * Saves the config to the config file.
  209. *
  210. * @throws HintException If the config file cannot be written to
  211. * @throws \Exception If no file lock can be acquired
  212. */
  213. private function writeData() {
  214. // Create a php file ...
  215. $content = "<?php\n";
  216. $content .= '$CONFIG = ';
  217. $content .= var_export($this->cache, true);
  218. $content .= ";\n";
  219. touch($this->configFilePath);
  220. $filePointer = fopen($this->configFilePath, 'r+');
  221. // Prevent others not to read the config
  222. chmod($this->configFilePath, 0640);
  223. // File does not exist, this can happen when doing a fresh install
  224. if (!is_resource($filePointer)) {
  225. throw new HintException(
  226. "Can't write into config directory!",
  227. 'This can usually be fixed by giving the webserver write access to the config directory.');
  228. }
  229. // Try to acquire a file lock
  230. if (!flock($filePointer, LOCK_EX)) {
  231. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  232. }
  233. // Write the config and release the lock
  234. ftruncate($filePointer, 0);
  235. fwrite($filePointer, $content);
  236. fflush($filePointer);
  237. flock($filePointer, LOCK_UN);
  238. fclose($filePointer);
  239. if (function_exists('opcache_invalidate')) {
  240. @opcache_invalidate($this->configFilePath, true);
  241. }
  242. }
  243. }