Themes.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. /**
  3. * @package Grav\Common
  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;
  9. use DirectoryIterator;
  10. use Exception;
  11. use Grav\Common\Config\Config;
  12. use Grav\Common\File\CompiledYamlFile;
  13. use Grav\Common\Data\Blueprints;
  14. use Grav\Common\Data\Data;
  15. use Grav\Framework\Psr7\Response;
  16. use InvalidArgumentException;
  17. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  18. use RuntimeException;
  19. use Symfony\Component\EventDispatcher\EventDispatcher;
  20. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  21. use function defined;
  22. use function in_array;
  23. use function strlen;
  24. /**
  25. * Class Themes
  26. * @package Grav\Common
  27. */
  28. class Themes extends Iterator
  29. {
  30. /** @var Grav */
  31. protected $grav;
  32. /** @var Config */
  33. protected $config;
  34. /** @var bool */
  35. protected $inited = false;
  36. /**
  37. * Themes constructor.
  38. *
  39. * @param Grav $grav
  40. */
  41. public function __construct(Grav $grav)
  42. {
  43. parent::__construct();
  44. $this->grav = $grav;
  45. $this->config = $grav['config'];
  46. // Register instance as autoloader for theme inheritance
  47. spl_autoload_register([$this, 'autoloadTheme']);
  48. }
  49. /**
  50. * @return void
  51. */
  52. public function init()
  53. {
  54. /** @var Themes $themes */
  55. $themes = $this->grav['themes'];
  56. $themes->configure();
  57. $this->initTheme();
  58. }
  59. /**
  60. * @return void
  61. */
  62. public function initTheme()
  63. {
  64. if ($this->inited === false) {
  65. /** @var Themes $themes */
  66. $themes = $this->grav['themes'];
  67. try {
  68. $instance = $themes->load();
  69. } catch (InvalidArgumentException $e) {
  70. throw new RuntimeException($this->current() . ' theme could not be found');
  71. }
  72. // Register autoloader.
  73. if (method_exists($instance, 'autoload')) {
  74. $instance->autoload();
  75. }
  76. // Register event listeners.
  77. if ($instance instanceof EventSubscriberInterface) {
  78. /** @var EventDispatcher $events */
  79. $events = $this->grav['events'];
  80. $events->addSubscriber($instance);
  81. }
  82. // Register blueprints.
  83. if (is_dir('theme://blueprints/pages')) {
  84. /** @var UniformResourceLocator $locator */
  85. $locator = $this->grav['locator'];
  86. $locator->addPath('blueprints', '', ['theme://blueprints'], ['user', 'blueprints']);
  87. }
  88. // Register form fields.
  89. if (method_exists($instance, 'getFormFieldTypes')) {
  90. /** @var Plugins $plugins */
  91. $plugins = $this->grav['plugins'];
  92. $plugins->formFieldTypes = $instance->getFormFieldTypes() + $plugins->formFieldTypes;
  93. }
  94. $this->grav['theme'] = $instance;
  95. $this->grav->fireEvent('onThemeInitialized');
  96. $this->inited = true;
  97. }
  98. }
  99. /**
  100. * Return list of all theme data with their blueprints.
  101. *
  102. * @return array
  103. */
  104. public function all()
  105. {
  106. $list = [];
  107. /** @var UniformResourceLocator $locator */
  108. $locator = $this->grav['locator'];
  109. $iterator = $locator->getIterator('themes://');
  110. /** @var DirectoryIterator $directory */
  111. foreach ($iterator as $directory) {
  112. if (!$directory->isDir() || $directory->isDot()) {
  113. continue;
  114. }
  115. $theme = $directory->getFilename();
  116. try {
  117. $result = $this->get($theme);
  118. } catch (Exception $e) {
  119. $exception = new RuntimeException(sprintf('Theme %s: %s', $theme, $e->getMessage()), $e->getCode(), $e);
  120. /** @var Debugger $debugger */
  121. $debugger = $this->grav['debugger'];
  122. $debugger->addMessage("Theme {$theme} cannot be loaded, please check Exceptions tab", 'error');
  123. $debugger->addException($exception);
  124. continue;
  125. }
  126. if ($result) {
  127. $list[$theme] = $result;
  128. }
  129. }
  130. ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
  131. return $list;
  132. }
  133. /**
  134. * Get theme configuration or throw exception if it cannot be found.
  135. *
  136. * @param string $name
  137. * @return Data|null
  138. * @throws RuntimeException
  139. */
  140. public function get($name)
  141. {
  142. if (!$name) {
  143. throw new RuntimeException('Theme name not provided.');
  144. }
  145. $blueprints = new Blueprints('themes://');
  146. $blueprint = $blueprints->get("{$name}/blueprints");
  147. // Load default configuration.
  148. $file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT);
  149. // ensure this is a valid theme
  150. if (!$file->exists()) {
  151. return null;
  152. }
  153. // Find thumbnail.
  154. $thumb = "themes://{$name}/thumbnail.jpg";
  155. $path = $this->grav['locator']->findResource($thumb, false);
  156. if ($path) {
  157. $blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path);
  158. }
  159. $obj = new Data((array)$file->content(), $blueprint);
  160. // Override with user configuration.
  161. $obj->merge($this->config->get('themes.' . $name) ?: []);
  162. // Save configuration always to user/config.
  163. $file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT);
  164. $obj->file($file);
  165. return $obj;
  166. }
  167. /**
  168. * Return name of the current theme.
  169. *
  170. * @return string
  171. */
  172. public function current()
  173. {
  174. return (string)$this->config->get('system.pages.theme');
  175. }
  176. /**
  177. * Load current theme.
  178. *
  179. * @return Theme
  180. */
  181. public function load()
  182. {
  183. // NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
  184. $grav = $this->grav;
  185. $config = $this->config;
  186. $name = $this->current();
  187. $class = null;
  188. /** @var UniformResourceLocator $locator */
  189. $locator = $grav['locator'];
  190. // Start by attempting to load the theme.php file.
  191. $file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
  192. if ($file) {
  193. // Local variables available in the file: $grav, $config, $name, $file
  194. $class = include $file;
  195. if (!\is_object($class) || !is_subclass_of($class, Theme::class, true)) {
  196. $class = null;
  197. }
  198. } elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
  199. $response = new Response(500, [], "Theme '$name' does not exist, unable to display page.");
  200. $grav->close($response);
  201. }
  202. // If the class hasn't been initialized yet, guess the class name and create a new instance.
  203. if (null === $class) {
  204. $themeClassFormat = [
  205. 'Grav\\Theme\\' . Inflector::camelize($name),
  206. 'Grav\\Theme\\' . ucfirst($name)
  207. ];
  208. foreach ($themeClassFormat as $themeClass) {
  209. if (is_subclass_of($themeClass, Theme::class, true)) {
  210. $class = new $themeClass($grav, $config, $name);
  211. break;
  212. }
  213. }
  214. }
  215. // Finally if everything else fails, just create a new instance from the default Theme class.
  216. if (null === $class) {
  217. $class = new Theme($grav, $config, $name);
  218. }
  219. $this->config->set('theme', $config->get('themes.' . $name));
  220. return $class;
  221. }
  222. /**
  223. * Configure and prepare streams for current template.
  224. *
  225. * @return void
  226. * @throws InvalidArgumentException
  227. */
  228. public function configure()
  229. {
  230. $name = $this->current();
  231. $config = $this->config;
  232. $this->loadConfiguration($name, $config);
  233. /** @var UniformResourceLocator $locator */
  234. $locator = $this->grav['locator'];
  235. $registered = stream_get_wrappers();
  236. $schemes = $config->get("themes.{$name}.streams.schemes", []);
  237. $schemes += [
  238. 'theme' => [
  239. 'type' => 'ReadOnlyStream',
  240. 'paths' => $locator->findResources("themes://{$name}", false)
  241. ]
  242. ];
  243. foreach ($schemes as $scheme => $config) {
  244. if (isset($config['paths'])) {
  245. $locator->addPath($scheme, '', $config['paths']);
  246. }
  247. if (isset($config['prefixes'])) {
  248. foreach ($config['prefixes'] as $prefix => $paths) {
  249. $locator->addPath($scheme, $prefix, $paths);
  250. }
  251. }
  252. if (in_array($scheme, $registered, true)) {
  253. stream_wrapper_unregister($scheme);
  254. }
  255. $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
  256. if ($type[0] !== '\\') {
  257. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  258. }
  259. if (!stream_wrapper_register($scheme, $type)) {
  260. throw new InvalidArgumentException("Stream '{$type}' could not be initialized.");
  261. }
  262. }
  263. // Load languages after streams has been properly initialized
  264. $this->loadLanguages($this->config);
  265. }
  266. /**
  267. * Load theme configuration.
  268. *
  269. * @param string $name Theme name
  270. * @param Config $config Configuration class
  271. * @return void
  272. */
  273. protected function loadConfiguration($name, Config $config)
  274. {
  275. $themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
  276. $config->joinDefaults("themes.{$name}", $themeConfig);
  277. }
  278. /**
  279. * Load theme languages.
  280. * Reads ALL language files from theme stream and merges them.
  281. *
  282. * @param Config $config Configuration class
  283. * @return void
  284. */
  285. protected function loadLanguages(Config $config)
  286. {
  287. /** @var UniformResourceLocator $locator */
  288. $locator = $this->grav['locator'];
  289. if ($config->get('system.languages.translations', true)) {
  290. $language_files = array_reverse($locator->findResources('theme://languages' . YAML_EXT));
  291. foreach ($language_files as $language_file) {
  292. $language = CompiledYamlFile::instance($language_file)->content();
  293. $this->grav['languages']->mergeRecursive($language);
  294. }
  295. $languages_folders = array_reverse($locator->findResources('theme://languages'));
  296. foreach ($languages_folders as $languages_folder) {
  297. $languages = [];
  298. $iterator = new DirectoryIterator($languages_folder);
  299. foreach ($iterator as $file) {
  300. if ($file->getExtension() !== 'yaml') {
  301. continue;
  302. }
  303. $languages[$file->getBasename('.yaml')] = CompiledYamlFile::instance($file->getPathname())->content();
  304. }
  305. $this->grav['languages']->mergeRecursive($languages);
  306. }
  307. }
  308. }
  309. /**
  310. * Autoload theme classes for inheritance
  311. *
  312. * @param string $class Class name
  313. * @return mixed|false FALSE if unable to load $class; Class name if
  314. * $class is successfully loaded
  315. */
  316. protected function autoloadTheme($class)
  317. {
  318. $prefix = 'Grav\\Theme\\';
  319. if (false !== strpos($class, $prefix)) {
  320. // Remove prefix from class
  321. $class = substr($class, strlen($prefix));
  322. $locator = $this->grav['locator'];
  323. // First try lowercase version of the classname.
  324. $path = strtolower($class);
  325. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  326. if ($file) {
  327. return include_once $file;
  328. }
  329. // Replace namespace tokens to directory separators
  330. $path = $this->grav['inflector']->hyphenize($class);
  331. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  332. // Load class
  333. if ($file) {
  334. return include_once $file;
  335. }
  336. // Try Old style theme classes
  337. $path = preg_replace('#\\\|_(?!.+\\\)#', '/', $class);
  338. \assert(null !== $path);
  339. $path = strtolower($path);
  340. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  341. // Load class
  342. if ($file) {
  343. return include_once $file;
  344. }
  345. }
  346. return false;
  347. }
  348. }