Config.php 7.6 KB

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