Config.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 array */
  48. protected $envCache = [];
  49. /** @var string */
  50. protected $configDir;
  51. /** @var string */
  52. protected $configFilePath;
  53. /** @var string */
  54. protected $configFileName;
  55. /**
  56. * @param string $configDir Path to the config dir, needs to end with '/'
  57. * @param string $fileName (Optional) Name of the config file. Defaults to config.php
  58. */
  59. public function __construct($configDir, $fileName = 'config.php') {
  60. $this->configDir = $configDir;
  61. $this->configFilePath = $this->configDir.$fileName;
  62. $this->configFileName = $fileName;
  63. $this->readData();
  64. }
  65. /**
  66. * Lists all available config keys
  67. *
  68. * Please note that it does not return the values.
  69. *
  70. * @return array an array of key names
  71. */
  72. public function getKeys() {
  73. return array_keys($this->cache);
  74. }
  75. /**
  76. * Returns a config value
  77. *
  78. * gets its value from an `NC_` prefixed environment variable
  79. * if it doesn't exist from config.php
  80. * if this doesn't exist either, it will return the given `$default`
  81. *
  82. * @param string $key key
  83. * @param mixed $default = null default value
  84. * @return mixed the value or $default
  85. */
  86. public function getValue($key, $default = null) {
  87. $envKey = self::ENV_PREFIX . $key;
  88. if (isset($this->envCache[$envKey])) {
  89. return $this->envCache[$envKey];
  90. }
  91. if (isset($this->cache[$key])) {
  92. return $this->cache[$key];
  93. }
  94. return $default;
  95. }
  96. /**
  97. * Sets and deletes values and writes the config.php
  98. *
  99. * @param array $configs Associative array with `key => value` pairs
  100. * If value is null, the config key will be deleted
  101. */
  102. public function setValues(array $configs) {
  103. $needsUpdate = false;
  104. foreach ($configs as $key => $value) {
  105. if ($value !== null) {
  106. $needsUpdate |= $this->set($key, $value);
  107. } else {
  108. $needsUpdate |= $this->delete($key);
  109. }
  110. }
  111. if ($needsUpdate) {
  112. // Write changes
  113. $this->writeData();
  114. }
  115. }
  116. /**
  117. * Sets the value and writes it to config.php if required
  118. *
  119. * @param string $key key
  120. * @param mixed $value value
  121. */
  122. public function setValue($key, $value) {
  123. if ($this->set($key, $value)) {
  124. // Write changes
  125. $this->writeData();
  126. }
  127. }
  128. /**
  129. * This function sets the value
  130. *
  131. * @param string $key key
  132. * @param mixed $value value
  133. * @return bool True if the file needs to be updated, false otherwise
  134. */
  135. protected function set($key, $value) {
  136. if (!isset($this->cache[$key]) || $this->cache[$key] !== $value) {
  137. // Add change
  138. $this->cache[$key] = $value;
  139. return true;
  140. }
  141. return false;
  142. }
  143. /**
  144. * Removes a key from the config and removes it from config.php if required
  145. * @param string $key
  146. */
  147. public function deleteKey($key) {
  148. if ($this->delete($key)) {
  149. // Write changes
  150. $this->writeData();
  151. }
  152. }
  153. /**
  154. * This function removes a key from the config
  155. *
  156. * @param string $key
  157. * @return bool True if the file needs to be updated, false otherwise
  158. */
  159. protected function delete($key) {
  160. if (isset($this->cache[$key])) {
  161. // Delete key from cache
  162. unset($this->cache[$key]);
  163. return true;
  164. }
  165. return false;
  166. }
  167. /**
  168. * Loads the config file
  169. *
  170. * Reads the config file and saves it to the cache
  171. *
  172. * @throws \Exception If no lock could be acquired or the config file has not been found
  173. */
  174. private function readData() {
  175. // Default config should always get loaded
  176. $configFiles = [$this->configFilePath];
  177. // Add all files in the config dir ending with the same file name
  178. $extra = glob($this->configDir.'*.'.$this->configFileName);
  179. if (is_array($extra)) {
  180. natsort($extra);
  181. $configFiles = array_merge($configFiles, $extra);
  182. }
  183. // Include file and merge config
  184. foreach ($configFiles as $file) {
  185. $fileExistsAndIsReadable = file_exists($file) && is_readable($file);
  186. $filePointer = $fileExistsAndIsReadable ? fopen($file, 'r') : false;
  187. if ($file === $this->configFilePath &&
  188. $filePointer === false) {
  189. // Opening the main config might not be possible, e.g. if the wrong
  190. // permissions are set (likely on a new installation)
  191. continue;
  192. }
  193. // Try to acquire a file lock
  194. if (!flock($filePointer, LOCK_SH)) {
  195. throw new \Exception(sprintf('Could not acquire a shared lock on the config file %s', $file));
  196. }
  197. unset($CONFIG);
  198. include $file;
  199. if (isset($CONFIG) && is_array($CONFIG)) {
  200. $this->cache = array_merge($this->cache, $CONFIG);
  201. }
  202. // Close the file pointer and release the lock
  203. flock($filePointer, LOCK_UN);
  204. fclose($filePointer);
  205. }
  206. $this->envCache = getenv();
  207. }
  208. /**
  209. * Writes the config file
  210. *
  211. * Saves the config to the config file.
  212. *
  213. * @throws HintException If the config file cannot be written to
  214. * @throws \Exception If no file lock can be acquired
  215. */
  216. private function writeData() {
  217. // Create a php file ...
  218. $content = "<?php\n";
  219. $content .= '$CONFIG = ';
  220. $content .= var_export($this->cache, true);
  221. $content .= ";\n";
  222. touch($this->configFilePath);
  223. $filePointer = fopen($this->configFilePath, 'r+');
  224. // Prevent others not to read the config
  225. chmod($this->configFilePath, 0640);
  226. // File does not exist, this can happen when doing a fresh install
  227. if (!is_resource($filePointer)) {
  228. throw new HintException(
  229. "Can't write into config directory!",
  230. 'This can usually be fixed by giving the webserver write access to the config directory.');
  231. }
  232. // Try to acquire a file lock
  233. if (!flock($filePointer, LOCK_EX)) {
  234. throw new \Exception(sprintf('Could not acquire an exclusive lock on the config file %s', $this->configFilePath));
  235. }
  236. // Write the config and release the lock
  237. ftruncate($filePointer, 0);
  238. fwrite($filePointer, $content);
  239. fflush($filePointer);
  240. flock($filePointer, LOCK_UN);
  241. fclose($filePointer);
  242. if (function_exists('opcache_invalidate')) {
  243. @opcache_invalidate($this->configFilePath, true);
  244. }
  245. }
  246. }