Themes.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. <?php
  2. /**
  3. * @package Grav.Common
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 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. $result = self::get($theme);
  81. if ($result) {
  82. $list[$theme] = $result;
  83. }
  84. }
  85. ksort($list);
  86. return $list;
  87. }
  88. /**
  89. * Get theme configuration or throw exception if it cannot be found.
  90. *
  91. * @param string $name
  92. *
  93. * @return Data
  94. * @throws \RuntimeException
  95. */
  96. public function get($name)
  97. {
  98. if (!$name) {
  99. throw new \RuntimeException('Theme name not provided.');
  100. }
  101. $blueprints = new Blueprints('themes://');
  102. $blueprint = $blueprints->get("{$name}/blueprints");
  103. // Load default configuration.
  104. $file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT);
  105. // ensure this is a valid theme
  106. if (!$file->exists()) {
  107. return null;
  108. }
  109. // Find thumbnail.
  110. $thumb = "themes://{$name}/thumbnail.jpg";
  111. $path = $this->grav['locator']->findResource($thumb, false);
  112. if ($path) {
  113. $blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path);
  114. }
  115. $obj = new Data($file->content(), $blueprint);
  116. // Override with user configuration.
  117. $obj->merge($this->config->get('themes.' . $name) ?: []);
  118. // Save configuration always to user/config.
  119. $file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT);
  120. $obj->file($file);
  121. return $obj;
  122. }
  123. /**
  124. * Return name of the current theme.
  125. *
  126. * @return string
  127. */
  128. public function current()
  129. {
  130. return (string)$this->config->get('system.pages.theme');
  131. }
  132. /**
  133. * Load current theme.
  134. *
  135. * @return Theme
  136. */
  137. public function load()
  138. {
  139. // NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
  140. $grav = $this->grav;
  141. $config = $this->config;
  142. $name = $this->current();
  143. /** @var UniformResourceLocator $locator */
  144. $locator = $grav['locator'];
  145. $file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
  146. $inflector = $grav['inflector'];
  147. if ($file) {
  148. // Local variables available in the file: $grav, $config, $name, $file
  149. $class = include $file;
  150. if (!is_object($class)) {
  151. $themeClassFormat = [
  152. 'Grav\\Theme\\' . ucfirst($name),
  153. 'Grav\\Theme\\' . $inflector->camelize($name)
  154. ];
  155. foreach ($themeClassFormat as $themeClass) {
  156. if (class_exists($themeClass)) {
  157. $themeClassName = $themeClass;
  158. $class = new $themeClassName($grav, $config, $name);
  159. break;
  160. }
  161. }
  162. }
  163. } elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
  164. exit("Theme '$name' does not exist, unable to display page.");
  165. }
  166. $this->config->set('theme', $config->get('themes.' . $name));
  167. if (empty($class)) {
  168. $class = new Theme($grav, $config, $name);
  169. }
  170. return $class;
  171. }
  172. /**
  173. * Configure and prepare streams for current template.
  174. *
  175. * @throws \InvalidArgumentException
  176. */
  177. public function configure()
  178. {
  179. $name = $this->current();
  180. $config = $this->config;
  181. $this->loadConfiguration($name, $config);
  182. /** @var UniformResourceLocator $locator */
  183. $locator = $this->grav['locator'];
  184. $registered = stream_get_wrappers();
  185. $schemes = $config->get("themes.{$name}.streams.schemes", []);
  186. $schemes += [
  187. 'theme' => [
  188. 'type' => 'ReadOnlyStream',
  189. 'paths' => $locator->findResources("themes://{$name}", false)
  190. ]
  191. ];
  192. foreach ($schemes as $scheme => $config) {
  193. if (isset($config['paths'])) {
  194. $locator->addPath($scheme, '', $config['paths']);
  195. }
  196. if (isset($config['prefixes'])) {
  197. foreach ($config['prefixes'] as $prefix => $paths) {
  198. $locator->addPath($scheme, $prefix, $paths);
  199. }
  200. }
  201. if (in_array($scheme, $registered)) {
  202. stream_wrapper_unregister($scheme);
  203. }
  204. $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
  205. if ($type[0] !== '\\') {
  206. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  207. }
  208. if (!stream_wrapper_register($scheme, $type)) {
  209. throw new \InvalidArgumentException("Stream '{$type}' could not be initialized.");
  210. }
  211. }
  212. // Load languages after streams has been properly initialized
  213. $this->loadLanguages($this->config);
  214. }
  215. /**
  216. * Load theme configuration.
  217. *
  218. * @param string $name Theme name
  219. * @param Config $config Configuration class
  220. */
  221. protected function loadConfiguration($name, Config $config)
  222. {
  223. $themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
  224. $config->joinDefaults("themes.{$name}", $themeConfig);
  225. }
  226. /**
  227. * Load theme languages.
  228. *
  229. * @param Config $config Configuration class
  230. */
  231. protected function loadLanguages(Config $config)
  232. {
  233. /** @var UniformResourceLocator $locator */
  234. $locator = $this->grav['locator'];
  235. if ($config->get('system.languages.translations', true)) {
  236. $language_file = $locator->findResource("theme://languages" . YAML_EXT);
  237. if ($language_file) {
  238. $language = CompiledYamlFile::instance($language_file)->content();
  239. $this->grav['languages']->mergeRecursive($language);
  240. }
  241. $languages_folder = $locator->findResource("theme://languages/");
  242. if (file_exists($languages_folder)) {
  243. $languages = [];
  244. $iterator = new \DirectoryIterator($languages_folder);
  245. /** @var \DirectoryIterator $directory */
  246. foreach ($iterator as $file) {
  247. if ($file->getExtension() !== 'yaml') {
  248. continue;
  249. }
  250. $languages[$file->getBasename('.yaml')] = CompiledYamlFile::instance($file->getPathname())->content();
  251. }
  252. $this->grav['languages']->mergeRecursive($languages);
  253. }
  254. }
  255. }
  256. /**
  257. * Autoload theme classes for inheritance
  258. *
  259. * @param string $class Class name
  260. *
  261. * @return mixed false FALSE if unable to load $class; Class name if
  262. * $class is successfully loaded
  263. */
  264. protected function autoloadTheme($class)
  265. {
  266. $prefix = 'Grav\\Theme\\';
  267. if (false !== strpos($class, $prefix)) {
  268. // Remove prefix from class
  269. $class = substr($class, strlen($prefix));
  270. $locator = $this->grav['locator'];
  271. // First try lowercase version of the classname.
  272. $path = strtolower($class);
  273. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  274. if ($file) {
  275. return include_once $file;
  276. }
  277. // Replace namespace tokens to directory separators
  278. $path = $this->grav['inflector']->hyphenize($class);
  279. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  280. // Load class
  281. if ($file) {
  282. return include_once $file;
  283. }
  284. // Try Old style theme classes
  285. $path = strtolower(preg_replace('#\\\|_(?!.+\\\)#', '/', $class));
  286. $file = $locator("themes://{$path}/theme.php") ?: $locator("themes://{$path}/{$path}.php");
  287. // Load class
  288. if ($file) {
  289. return include_once $file;
  290. }
  291. }
  292. return false;
  293. }
  294. }