Setup.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. /**
  3. * @package Grav\Common\Config
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Config;
  9. use BadMethodCallException;
  10. use Grav\Common\File\CompiledYamlFile;
  11. use Grav\Common\Data\Data;
  12. use Grav\Common\Utils;
  13. use InvalidArgumentException;
  14. use Pimple\Container;
  15. use Psr\Http\Message\ServerRequestInterface;
  16. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  17. use RuntimeException;
  18. use function defined;
  19. use function is_array;
  20. /**
  21. * Class Setup
  22. * @package Grav\Common\Config
  23. */
  24. class Setup extends Data
  25. {
  26. /**
  27. * @var array Environment aliases normalized to lower case.
  28. */
  29. public static $environments = [
  30. '' => 'unknown',
  31. '127.0.0.1' => 'localhost',
  32. '::1' => 'localhost'
  33. ];
  34. /**
  35. * @var string|null Current environment normalized to lower case.
  36. */
  37. public static $environment;
  38. /** @var string */
  39. public static $securityFile = 'config://security.yaml';
  40. /** @var array */
  41. protected $streams = [
  42. 'user' => [
  43. 'type' => 'ReadOnlyStream',
  44. 'force' => true,
  45. 'prefixes' => [
  46. '' => [] // Set in constructor
  47. ]
  48. ],
  49. 'cache' => [
  50. 'type' => 'Stream',
  51. 'force' => true,
  52. 'prefixes' => [
  53. '' => [], // Set in constructor
  54. 'images' => ['images']
  55. ]
  56. ],
  57. 'log' => [
  58. 'type' => 'Stream',
  59. 'force' => true,
  60. 'prefixes' => [
  61. '' => [] // Set in constructor
  62. ]
  63. ],
  64. 'tmp' => [
  65. 'type' => 'Stream',
  66. 'force' => true,
  67. 'prefixes' => [
  68. '' => [] // Set in constructor
  69. ]
  70. ],
  71. 'backup' => [
  72. 'type' => 'Stream',
  73. 'force' => true,
  74. 'prefixes' => [
  75. '' => [] // Set in constructor
  76. ]
  77. ],
  78. 'environment' => [
  79. 'type' => 'ReadOnlyStream'
  80. // If not defined, environment will be set up in the constructor.
  81. ],
  82. 'system' => [
  83. 'type' => 'ReadOnlyStream',
  84. 'prefixes' => [
  85. '' => ['system'],
  86. ]
  87. ],
  88. 'asset' => [
  89. 'type' => 'Stream',
  90. 'prefixes' => [
  91. '' => ['assets'],
  92. ]
  93. ],
  94. 'blueprints' => [
  95. 'type' => 'ReadOnlyStream',
  96. 'prefixes' => [
  97. '' => ['environment://blueprints', 'user://blueprints', 'system://blueprints'],
  98. ]
  99. ],
  100. 'config' => [
  101. 'type' => 'ReadOnlyStream',
  102. 'prefixes' => [
  103. '' => ['environment://config', 'user://config', 'system://config'],
  104. ]
  105. ],
  106. 'plugins' => [
  107. 'type' => 'ReadOnlyStream',
  108. 'prefixes' => [
  109. '' => ['user://plugins'],
  110. ]
  111. ],
  112. 'plugin' => [
  113. 'type' => 'ReadOnlyStream',
  114. 'prefixes' => [
  115. '' => ['user://plugins'],
  116. ]
  117. ],
  118. 'themes' => [
  119. 'type' => 'ReadOnlyStream',
  120. 'prefixes' => [
  121. '' => ['user://themes'],
  122. ]
  123. ],
  124. 'languages' => [
  125. 'type' => 'ReadOnlyStream',
  126. 'prefixes' => [
  127. '' => ['environment://languages', 'user://languages', 'system://languages'],
  128. ]
  129. ],
  130. 'image' => [
  131. 'type' => 'Stream',
  132. 'prefixes' => [
  133. '' => ['user://images', 'system://images']
  134. ]
  135. ],
  136. 'page' => [
  137. 'type' => 'ReadOnlyStream',
  138. 'prefixes' => [
  139. '' => ['user://pages']
  140. ]
  141. ],
  142. 'user-data' => [
  143. 'type' => 'Stream',
  144. 'force' => true,
  145. 'prefixes' => [
  146. '' => ['user://data']
  147. ]
  148. ],
  149. 'account' => [
  150. 'type' => 'ReadOnlyStream',
  151. 'prefixes' => [
  152. '' => ['user://accounts']
  153. ]
  154. ],
  155. ];
  156. /**
  157. * @param Container|array $container
  158. */
  159. public function __construct($container)
  160. {
  161. // Configure main streams.
  162. $abs = str_starts_with(GRAV_SYSTEM_PATH, '/');
  163. $this->streams['system']['prefixes'][''] = $abs ? ['system', GRAV_SYSTEM_PATH] : ['system'];
  164. $this->streams['user']['prefixes'][''] = [GRAV_USER_PATH];
  165. $this->streams['cache']['prefixes'][''] = [GRAV_CACHE_PATH];
  166. $this->streams['log']['prefixes'][''] = [GRAV_LOG_PATH];
  167. $this->streams['tmp']['prefixes'][''] = [GRAV_TMP_PATH];
  168. $this->streams['backup']['prefixes'][''] = [GRAV_BACKUP_PATH];
  169. // If environment is not set, look for the environment variable and then the constant.
  170. $environment = static::$environment ??
  171. (defined('GRAV_ENVIRONMENT') ? GRAV_ENVIRONMENT : (getenv('GRAV_ENVIRONMENT') ?: null));
  172. // If no environment is set, make sure we get one (CLI or hostname).
  173. if (null === $environment) {
  174. if (defined('GRAV_CLI')) {
  175. $environment = 'cli';
  176. } else {
  177. /** @var ServerRequestInterface $request */
  178. $request = $container['request'];
  179. $host = $request->getUri()->getHost();
  180. $environment = Utils::substrToString($host, ':');
  181. }
  182. }
  183. // Resolve server aliases to the proper environment.
  184. static::$environment = static::$environments[$environment] ?? $environment;
  185. // Pre-load setup.php which contains our initial configuration.
  186. // Configuration may contain dynamic parts, which is why we need to always load it.
  187. // If GRAV_SETUP_PATH has been defined, use it, otherwise use defaults.
  188. $setupFile = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : (getenv('GRAV_SETUP_PATH') ?: null);
  189. if (null !== $setupFile) {
  190. // Make sure that the custom setup file exists. Terminates the script if not.
  191. if (!str_starts_with($setupFile, '/')) {
  192. $setupFile = GRAV_WEBROOT . '/' . $setupFile;
  193. }
  194. if (!is_file($setupFile)) {
  195. echo 'GRAV_SETUP_PATH is defined but does not point to existing setup file.';
  196. exit(1);
  197. }
  198. } else {
  199. $setupFile = GRAV_WEBROOT . '/setup.php';
  200. if (!is_file($setupFile)) {
  201. $setupFile = GRAV_WEBROOT . '/' . GRAV_USER_PATH . '/setup.php';
  202. }
  203. if (!is_file($setupFile)) {
  204. $setupFile = null;
  205. }
  206. }
  207. $setup = $setupFile ? (array) include $setupFile : [];
  208. // Add default streams defined in beginning of the class.
  209. if (!isset($setup['streams']['schemes'])) {
  210. $setup['streams']['schemes'] = [];
  211. }
  212. $setup['streams']['schemes'] += $this->streams;
  213. // Initialize class.
  214. parent::__construct($setup);
  215. $this->def('environment', static::$environment);
  216. // Figure out path for the current environment.
  217. $envPath = defined('GRAV_ENVIRONMENT_PATH') ? GRAV_ENVIRONMENT_PATH : (getenv('GRAV_ENVIRONMENT_PATH') ?: null);
  218. if (null === $envPath) {
  219. // Find common path for all environments and append current environment into it.
  220. $envPath = defined('GRAV_ENVIRONMENTS_PATH') ? GRAV_ENVIRONMENTS_PATH : (getenv('GRAV_ENVIRONMENTS_PATH') ?: null);
  221. if (null !== $envPath) {
  222. $envPath .= '/';
  223. } else {
  224. // Use default location. Start with Grav 1.7 default.
  225. $envPath = GRAV_WEBROOT. '/' . GRAV_USER_PATH . '/env';
  226. if (is_dir($envPath)) {
  227. $envPath = 'user://env/';
  228. } else {
  229. // Fallback to Grav 1.6 default.
  230. $envPath = 'user://';
  231. }
  232. }
  233. $envPath .= $this->get('environment');
  234. }
  235. // Set up environment.
  236. $this->def('environment', static::$environment);
  237. $this->def('streams.schemes.environment.prefixes', ['' => [$envPath]]);
  238. }
  239. /**
  240. * @return $this
  241. * @throws RuntimeException
  242. * @throws InvalidArgumentException
  243. */
  244. public function init()
  245. {
  246. $locator = new UniformResourceLocator(GRAV_WEBROOT);
  247. $files = [];
  248. $guard = 5;
  249. do {
  250. $check = $files;
  251. $this->initializeLocator($locator);
  252. $files = $locator->findResources('config://streams.yaml');
  253. if ($check === $files) {
  254. break;
  255. }
  256. // Update streams.
  257. foreach (array_reverse($files) as $path) {
  258. $file = CompiledYamlFile::instance($path);
  259. $content = (array)$file->content();
  260. if (!empty($content['schemes'])) {
  261. $this->items['streams']['schemes'] = $content['schemes'] + $this->items['streams']['schemes'];
  262. }
  263. }
  264. } while (--$guard);
  265. if (!$guard) {
  266. throw new RuntimeException('Setup: Configuration reload loop detected!');
  267. }
  268. // Make sure we have valid setup.
  269. $this->check($locator);
  270. return $this;
  271. }
  272. /**
  273. * Initialize resource locator by using the configuration.
  274. *
  275. * @param UniformResourceLocator $locator
  276. * @return void
  277. * @throws BadMethodCallException
  278. */
  279. public function initializeLocator(UniformResourceLocator $locator)
  280. {
  281. $locator->reset();
  282. $schemes = (array) $this->get('streams.schemes', []);
  283. foreach ($schemes as $scheme => $config) {
  284. if (isset($config['paths'])) {
  285. $locator->addPath($scheme, '', $config['paths']);
  286. }
  287. $override = $config['override'] ?? false;
  288. $force = $config['force'] ?? false;
  289. if (isset($config['prefixes'])) {
  290. foreach ((array)$config['prefixes'] as $prefix => $paths) {
  291. $locator->addPath($scheme, $prefix, $paths, $override, $force);
  292. }
  293. }
  294. }
  295. }
  296. /**
  297. * Get available streams and their types from the configuration.
  298. *
  299. * @return array
  300. */
  301. public function getStreams()
  302. {
  303. $schemes = [];
  304. foreach ((array) $this->get('streams.schemes') as $scheme => $config) {
  305. $type = $config['type'] ?? 'ReadOnlyStream';
  306. if ($type[0] !== '\\') {
  307. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  308. }
  309. $schemes[$scheme] = $type;
  310. }
  311. return $schemes;
  312. }
  313. /**
  314. * @param UniformResourceLocator $locator
  315. * @return void
  316. * @throws InvalidArgumentException
  317. * @throws BadMethodCallException
  318. * @throws RuntimeException
  319. */
  320. protected function check(UniformResourceLocator $locator)
  321. {
  322. $streams = $this->items['streams']['schemes'] ?? null;
  323. if (!is_array($streams)) {
  324. throw new InvalidArgumentException('Configuration is missing streams.schemes!');
  325. }
  326. $diff = array_keys(array_diff_key($this->streams, $streams));
  327. if ($diff) {
  328. throw new InvalidArgumentException(
  329. sprintf('Configuration is missing keys %s from streams.schemes!', implode(', ', $diff))
  330. );
  331. }
  332. try {
  333. // If environment is found, remove all missing override locations (B/C compatibility).
  334. if ($locator->findResource('environment://', true)) {
  335. $force = $this->get('streams.schemes.environment.force', false);
  336. if (!$force) {
  337. $prefixes = $this->get('streams.schemes.environment.prefixes.');
  338. $update = false;
  339. foreach ($prefixes as $i => $prefix) {
  340. if ($locator->isStream($prefix)) {
  341. if ($locator->findResource($prefix, true)) {
  342. break;
  343. }
  344. } elseif (file_exists($prefix)) {
  345. break;
  346. }
  347. unset($prefixes[$i]);
  348. $update = true;
  349. }
  350. if ($update) {
  351. $this->set('streams.schemes.environment.prefixes', ['' => array_values($prefixes)]);
  352. $this->initializeLocator($locator);
  353. }
  354. }
  355. }
  356. if (!$locator->findResource('environment://config', true)) {
  357. // If environment does not have its own directory, remove it from the lookup.
  358. $prefixes = $this->get('streams.schemes.environment.prefixes');
  359. $prefixes['config'] = [];
  360. $this->set('streams.schemes.environment.prefixes', $prefixes);
  361. $this->initializeLocator($locator);
  362. }
  363. // Create security.yaml salt if it doesn't exist into existing configuration environment if possible.
  364. $securityFile = Utils::basename(static::$securityFile);
  365. $securityFolder = substr(static::$securityFile, 0, -\strlen($securityFile));
  366. $securityFolder = $locator->findResource($securityFolder, true) ?: $locator->findResource($securityFolder, true, true);
  367. $filename = "{$securityFolder}/{$securityFile}";
  368. $security_file = CompiledYamlFile::instance($filename);
  369. $security_content = (array)$security_file->content();
  370. if (!isset($security_content['salt'])) {
  371. $security_content = array_merge($security_content, ['salt' => Utils::generateRandomString(14)]);
  372. $security_file->content($security_content);
  373. $security_file->save();
  374. $security_file->free();
  375. }
  376. } catch (RuntimeException $e) {
  377. throw new RuntimeException(sprintf('Grav failed to initialize: %s', $e->getMessage()), 500, $e);
  378. }
  379. }
  380. }