Themes.php 11 KB

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