Themes.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. <?php
  2. /**
  3. * @package Grav\Common
  4. *
  5. * @copyright Copyright (c) 2015 - 2021 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. /** @var UniformResourceLocator $locator */
  188. $locator = $grav['locator'];
  189. $file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
  190. if ($file) {
  191. // Local variables available in the file: $grav, $config, $name, $file
  192. $class = include $file;
  193. if (!$class || !is_subclass_of($class, Plugin::class, true)) {
  194. $className = Inflector::camelize($name);
  195. $themeClassFormat = [
  196. 'Grav\\Theme\\' . $className,
  197. 'Grav\\Theme\\' . ucfirst($name)
  198. ];
  199. foreach ($themeClassFormat as $themeClass) {
  200. if (is_subclass_of($themeClass, Theme::class, true)) {
  201. $class = new $themeClass($grav, $config, $name);
  202. break;
  203. }
  204. }
  205. }
  206. } elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
  207. $response = new Response(500, [], "Theme '$name' does not exist, unable to display page.");
  208. $grav->close($response);
  209. }
  210. $this->config->set('theme', $config->get('themes.' . $name));
  211. if (empty($class)) {
  212. $class = new Theme($grav, $config, $name);
  213. }
  214. return $class;
  215. }
  216. /**
  217. * Configure and prepare streams for current template.
  218. *
  219. * @return void
  220. * @throws InvalidArgumentException
  221. */
  222. public function configure()
  223. {
  224. $name = $this->current();
  225. $config = $this->config;
  226. $this->loadConfiguration($name, $config);
  227. /** @var UniformResourceLocator $locator */
  228. $locator = $this->grav['locator'];
  229. $registered = stream_get_wrappers();
  230. $schemes = $config->get("themes.{$name}.streams.schemes", []);
  231. $schemes += [
  232. 'theme' => [
  233. 'type' => 'ReadOnlyStream',
  234. 'paths' => $locator->findResources("themes://{$name}", false)
  235. ]
  236. ];
  237. foreach ($schemes as $scheme => $config) {
  238. if (isset($config['paths'])) {
  239. $locator->addPath($scheme, '', $config['paths']);
  240. }
  241. if (isset($config['prefixes'])) {
  242. foreach ($config['prefixes'] as $prefix => $paths) {
  243. $locator->addPath($scheme, $prefix, $paths);
  244. }
  245. }
  246. if (in_array($scheme, $registered, true)) {
  247. stream_wrapper_unregister($scheme);
  248. }
  249. $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
  250. if ($type[0] !== '\\') {
  251. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  252. }
  253. if (!stream_wrapper_register($scheme, $type)) {
  254. throw new InvalidArgumentException("Stream '{$type}' could not be initialized.");
  255. }
  256. }
  257. // Load languages after streams has been properly initialized
  258. $this->loadLanguages($this->config);
  259. }
  260. /**
  261. * Load theme configuration.
  262. *
  263. * @param string $name Theme name
  264. * @param Config $config Configuration class
  265. * @return void
  266. */
  267. protected function loadConfiguration($name, Config $config)
  268. {
  269. $themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
  270. $config->joinDefaults("themes.{$name}", $themeConfig);
  271. }
  272. /**
  273. * Load theme languages.
  274. * Reads ALL language files from theme stream and merges them.
  275. *
  276. * @param Config $config Configuration class
  277. * @return void
  278. */
  279. protected function loadLanguages(Config $config)
  280. {
  281. /** @var UniformResourceLocator $locator */
  282. $locator = $this->grav['locator'];
  283. if ($config->get('system.languages.translations', true)) {
  284. $language_files = array_reverse($locator->findResources('theme://languages' . YAML_EXT));
  285. foreach ($language_files as $language_file) {
  286. $language = CompiledYamlFile::instance($language_file)->content();
  287. $this->grav['languages']->mergeRecursive($language);
  288. }
  289. $languages_folders = array_reverse($locator->findResources('theme://languages'));
  290. foreach ($languages_folders as $languages_folder) {
  291. $languages = [];
  292. $iterator = new DirectoryIterator($languages_folder);
  293. foreach ($iterator as $file) {
  294. if ($file->getExtension() !== 'yaml') {
  295. continue;
  296. }
  297. $languages[$file->getBasename('.yaml')] = CompiledYamlFile::instance($file->getPathname())->content();
  298. }
  299. $this->grav['languages']->mergeRecursive($languages);
  300. }
  301. }
  302. }
  303. /**
  304. * Autoload theme classes for inheritance
  305. *
  306. * @param string $class Class name
  307. * @return mixed|false FALSE if unable to load $class; Class name if
  308. * $class is successfully loaded
  309. */
  310. protected function autoloadTheme($class)
  311. {
  312. $prefix = 'Grav\\Theme\\';
  313. if (false !== strpos($class, $prefix)) {
  314. // Remove prefix from class
  315. $class = substr($class, strlen($prefix));
  316. $locator = $this->grav['locator'];
  317. // First try lowercase version of the classname.
  318. $path = strtolower($class);
  319. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  320. if ($file) {
  321. return include_once $file;
  322. }
  323. // Replace namespace tokens to directory separators
  324. $path = $this->grav['inflector']->hyphenize($class);
  325. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  326. // Load class
  327. if ($file) {
  328. return include_once $file;
  329. }
  330. // Try Old style theme classes
  331. $path = preg_replace('#\\\|_(?!.+\\\)#', '/', $class);
  332. \assert(null !== $path);
  333. $path = strtolower($path);
  334. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  335. // Load class
  336. if ($file) {
  337. return include_once $file;
  338. }
  339. }
  340. return false;
  341. }
  342. }