Config.php 7.6 KB

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