Setup.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. /**
  3. * @package Grav\Common\Config
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 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. $request = null;
  176. $uri = null;
  177. $environment = 'cli';
  178. } else {
  179. /** @var ServerRequestInterface $request */
  180. $request = $container['request'];
  181. $uri = $request->getUri();
  182. $environment = $uri->getHost();
  183. }
  184. }
  185. // Resolve server aliases to the proper environment.
  186. static::$environment = static::$environments[$environment] ?? $environment;
  187. // Pre-load setup.php which contains our initial configuration.
  188. // Configuration may contain dynamic parts, which is why we need to always load it.
  189. // If GRAV_SETUP_PATH has been defined, use it, otherwise use defaults.
  190. $setupFile = defined('GRAV_SETUP_PATH') ? GRAV_SETUP_PATH : (getenv('GRAV_SETUP_PATH') ?: null);
  191. if (null !== $setupFile) {
  192. // Make sure that the custom setup file exists. Terminates the script if not.
  193. if (!str_starts_with($setupFile, '/')) {
  194. $setupFile = GRAV_WEBROOT . '/' . $setupFile;
  195. }
  196. if (!is_file($setupFile)) {
  197. echo 'GRAV_SETUP_PATH is defined but does not point to existing setup file.';
  198. exit(1);
  199. }
  200. } else {
  201. $setupFile = GRAV_WEBROOT . '/setup.php';
  202. if (!is_file($setupFile)) {
  203. $setupFile = GRAV_WEBROOT . '/' . GRAV_USER_PATH . '/setup.php';
  204. }
  205. if (!is_file($setupFile)) {
  206. $setupFile = null;
  207. }
  208. }
  209. $setup = $setupFile ? (array) include $setupFile : [];
  210. // Add default streams defined in beginning of the class.
  211. if (!isset($setup['streams']['schemes'])) {
  212. $setup['streams']['schemes'] = [];
  213. }
  214. $setup['streams']['schemes'] += $this->streams;
  215. // Initialize class.
  216. parent::__construct($setup);
  217. $this->def('environment', static::$environment);
  218. // Figure out path for the current environment.
  219. $envPath = defined('GRAV_ENVIRONMENT_PATH') ? GRAV_ENVIRONMENT_PATH : (getenv('GRAV_ENVIRONMENT_PATH') ?: null);
  220. if (null === $envPath) {
  221. // Find common path for all environments and append current environment into it.
  222. $envPath = defined('GRAV_ENVIRONMENTS_PATH') ? GRAV_ENVIRONMENTS_PATH : (getenv('GRAV_ENVIRONMENTS_PATH') ?: null);
  223. if (null !== $envPath) {
  224. $envPath .= '/';
  225. } else {
  226. // Use default location. Start with Grav 1.7 default.
  227. $envPath = GRAV_WEBROOT. '/' . GRAV_USER_PATH . '/env';
  228. if (is_dir($envPath)) {
  229. $envPath = 'user://env/';
  230. } else {
  231. // Fallback to Grav 1.6 default.
  232. $envPath = 'user://';
  233. }
  234. }
  235. $envPath .= $this->get('environment');
  236. }
  237. // Set up environment.
  238. $this->def('environment', static::$environment);
  239. $this->def('streams.schemes.environment.prefixes', ['' => [$envPath]]);
  240. }
  241. /**
  242. * @return $this
  243. * @throws RuntimeException
  244. * @throws InvalidArgumentException
  245. */
  246. public function init()
  247. {
  248. $locator = new UniformResourceLocator(GRAV_WEBROOT);
  249. $files = [];
  250. $guard = 5;
  251. do {
  252. $check = $files;
  253. $this->initializeLocator($locator);
  254. $files = $locator->findResources('config://streams.yaml');
  255. if ($check === $files) {
  256. break;
  257. }
  258. // Update streams.
  259. foreach (array_reverse($files) as $path) {
  260. $file = CompiledYamlFile::instance($path);
  261. $content = (array)$file->content();
  262. if (!empty($content['schemes'])) {
  263. $this->items['streams']['schemes'] = $content['schemes'] + $this->items['streams']['schemes'];
  264. }
  265. }
  266. } while (--$guard);
  267. if (!$guard) {
  268. throw new RuntimeException('Setup: Configuration reload loop detected!');
  269. }
  270. // Make sure we have valid setup.
  271. $this->check($locator);
  272. return $this;
  273. }
  274. /**
  275. * Initialize resource locator by using the configuration.
  276. *
  277. * @param UniformResourceLocator $locator
  278. * @return void
  279. * @throws BadMethodCallException
  280. */
  281. public function initializeLocator(UniformResourceLocator $locator)
  282. {
  283. $locator->reset();
  284. $schemes = (array) $this->get('streams.schemes', []);
  285. foreach ($schemes as $scheme => $config) {
  286. if (isset($config['paths'])) {
  287. $locator->addPath($scheme, '', $config['paths']);
  288. }
  289. $override = $config['override'] ?? false;
  290. $force = $config['force'] ?? false;
  291. if (isset($config['prefixes'])) {
  292. foreach ((array)$config['prefixes'] as $prefix => $paths) {
  293. $locator->addPath($scheme, $prefix, $paths, $override, $force);
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * Get available streams and their types from the configuration.
  300. *
  301. * @return array
  302. */
  303. public function getStreams()
  304. {
  305. $schemes = [];
  306. foreach ((array) $this->get('streams.schemes') as $scheme => $config) {
  307. $type = $config['type'] ?? 'ReadOnlyStream';
  308. if ($type[0] !== '\\') {
  309. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  310. }
  311. $schemes[$scheme] = $type;
  312. }
  313. return $schemes;
  314. }
  315. /**
  316. * @param UniformResourceLocator $locator
  317. * @return void
  318. * @throws InvalidArgumentException
  319. * @throws BadMethodCallException
  320. * @throws RuntimeException
  321. */
  322. protected function check(UniformResourceLocator $locator)
  323. {
  324. $streams = $this->items['streams']['schemes'] ?? null;
  325. if (!is_array($streams)) {
  326. throw new InvalidArgumentException('Configuration is missing streams.schemes!');
  327. }
  328. $diff = array_keys(array_diff_key($this->streams, $streams));
  329. if ($diff) {
  330. throw new InvalidArgumentException(
  331. sprintf('Configuration is missing keys %s from streams.schemes!', implode(', ', $diff))
  332. );
  333. }
  334. try {
  335. // If environment is found, remove all missing override locations (B/C compatibility).
  336. if ($locator->findResource('environment://', true)) {
  337. $force = $this->get('streams.schemes.environment.force', false);
  338. if (!$force) {
  339. $prefixes = $this->get('streams.schemes.environment.prefixes.');
  340. $update = false;
  341. foreach ($prefixes as $i => $prefix) {
  342. if ($locator->isStream($prefix)) {
  343. if ($locator->findResource($prefix, true)) {
  344. break;
  345. }
  346. } elseif (file_exists($prefix)) {
  347. break;
  348. }
  349. unset($prefixes[$i]);
  350. $update = true;
  351. }
  352. if ($update) {
  353. $this->set('streams.schemes.environment.prefixes', ['' => array_values($prefixes)]);
  354. $this->initializeLocator($locator);
  355. }
  356. }
  357. }
  358. if (!$locator->findResource('environment://config', true)) {
  359. // If environment does not have its own directory, remove it from the lookup.
  360. $prefixes = $this->get('streams.schemes.environment.prefixes');
  361. $prefixes['config'] = [];
  362. $this->set('streams.schemes.environment.prefixes', $prefixes);
  363. $this->initializeLocator($locator);
  364. }
  365. // Create security.yaml salt if it doesn't exist into existing configuration environment if possible.
  366. $securityFile = Utils::basename(static::$securityFile);
  367. $securityFolder = substr(static::$securityFile, 0, -\strlen($securityFile));
  368. $securityFolder = $locator->findResource($securityFolder, true) ?: $locator->findResource($securityFolder, true, true);
  369. $filename = "{$securityFolder}/{$securityFile}";
  370. $security_file = CompiledYamlFile::instance($filename);
  371. $security_content = (array)$security_file->content();
  372. if (!isset($security_content['salt'])) {
  373. $security_content = array_merge($security_content, ['salt' => Utils::generateRandomString(14)]);
  374. $security_file->content($security_content);
  375. $security_file->save();
  376. $security_file->free();
  377. }
  378. } catch (RuntimeException $e) {
  379. throw new RuntimeException(sprintf('Grav failed to initialize: %s', $e->getMessage()), 500, $e);
  380. }
  381. }
  382. }