Themes.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. namespace Grav\Common;
  3. use Grav\Common\Config\Config;
  4. use Grav\Common\File\CompiledYamlFile;
  5. use Grav\Common\Data\Blueprints;
  6. use Grav\Common\Data\Data;
  7. use RocketTheme\Toolbox\Event\EventDispatcher;
  8. use RocketTheme\Toolbox\Event\EventSubscriberInterface;
  9. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  10. /**
  11. * The Themes object holds an array of all the theme objects that Grav knows about.
  12. *
  13. * @author RocketTheme
  14. * @license MIT
  15. */
  16. class Themes extends Iterator
  17. {
  18. /** @var Grav */
  19. protected $grav;
  20. /** @var Config */
  21. protected $config;
  22. public function __construct(Grav $grav)
  23. {
  24. $this->grav = $grav;
  25. $this->config = $grav['config'];
  26. // Register instance as autoloader for theme inheritance
  27. spl_autoload_register([$this, 'autoloadTheme']);
  28. }
  29. public function init()
  30. {
  31. /** @var EventDispatcher $events */
  32. $events = $this->grav['events'];
  33. /** @var Themes $themes */
  34. $themes = $this->grav['themes'];
  35. $themes->configure();
  36. try {
  37. $instance = $themes->load();
  38. } catch (\InvalidArgumentException $e) {
  39. throw new \RuntimeException($this->current(). ' theme could not be found');
  40. }
  41. if ($instance instanceof EventSubscriberInterface) {
  42. $events->addSubscriber($instance);
  43. }
  44. $this->grav['theme'] = $instance;
  45. }
  46. /**
  47. * Return list of all theme data with their blueprints.
  48. *
  49. * @return array
  50. */
  51. public function all()
  52. {
  53. $list = array();
  54. $locator = Grav::instance()['locator'];
  55. $themes = (array) $locator->findResources('themes://', false);
  56. foreach ($themes as $path) {
  57. $iterator = new \DirectoryIterator($path);
  58. /** @var \DirectoryIterator $directory */
  59. foreach ($iterator as $directory) {
  60. if (!$directory->isDir() || $directory->isDot()) {
  61. continue;
  62. }
  63. $type = $directory->getBasename();
  64. $list[$type] = self::get($type);
  65. }
  66. }
  67. ksort($list);
  68. return $list;
  69. }
  70. /**
  71. * Get theme configuration or throw exception if it cannot be found.
  72. *
  73. * @param string $name
  74. * @return Data
  75. * @throws \RuntimeException
  76. */
  77. public function get($name)
  78. {
  79. if (!$name) {
  80. throw new \RuntimeException('Theme name not provided.');
  81. }
  82. $blueprints = new Blueprints('themes://');
  83. $blueprint = $blueprints->get("{$name}/blueprints");
  84. $blueprint->name = $name;
  85. // Find thumbnail.
  86. $thumb = "themes://{$name}/thumbnail.jpg";
  87. if ($path = $this->grav['locator']->findResource($thumb, false)) {
  88. $blueprint->set('thumbnail', $this->grav['base_url'] . '/' . $path);
  89. }
  90. // Load default configuration.
  91. $file = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT);
  92. $obj = new Data($file->content(), $blueprint);
  93. // Override with user configuration.
  94. $obj->merge($this->grav['config']->get('themes.' . $name) ?: []);
  95. // Save configuration always to user/config.
  96. $file = CompiledYamlFile::instance("config://themes/{$name}" . YAML_EXT);
  97. $obj->file($file);
  98. return $obj;
  99. }
  100. /**
  101. * Return name of the current theme.
  102. *
  103. * @return string
  104. */
  105. public function current()
  106. {
  107. return (string) $this->config->get('system.pages.theme');
  108. }
  109. /**
  110. * Load current theme.
  111. *
  112. * @return Theme|object
  113. */
  114. public function load()
  115. {
  116. // NOTE: ALL THE LOCAL VARIABLES ARE USED INSIDE INCLUDED FILE, DO NOT REMOVE THEM!
  117. $grav = $this->grav;
  118. $config = $this->config;
  119. $name = $this->current();
  120. /** @var UniformResourceLocator $locator */
  121. $locator = $grav['locator'];
  122. $file = $locator('theme://theme.php') ?: $locator("theme://{$name}.php");
  123. $inflector = $grav['inflector'];
  124. if ($file) {
  125. // Local variables available in the file: $grav, $config, $name, $file
  126. $class = include $file;
  127. if (!is_object($class)) {
  128. $themeClassFormat = [
  129. 'Grav\\Theme\\'.ucfirst($name),
  130. 'Grav\\Theme\\'.$inflector->camelize($name)
  131. ];
  132. $themeClassName = false;
  133. foreach ($themeClassFormat as $themeClass) {
  134. if (class_exists($themeClass)) {
  135. $themeClassName = $themeClass;
  136. $class = new $themeClassName($grav, $config, $name);
  137. break;
  138. }
  139. }
  140. }
  141. } elseif (!$locator('theme://') && !defined('GRAV_CLI')) {
  142. exit("Theme '$name' does not exist, unable to display page.");
  143. }
  144. if (empty($class)) {
  145. $class = new Theme($grav, $config, $name);
  146. }
  147. return $class;
  148. }
  149. /**
  150. * Configure and prepare streams for current template.
  151. *
  152. * @throws \InvalidArgumentException
  153. */
  154. public function configure()
  155. {
  156. $name = $this->current();
  157. $config = $this->config;
  158. $this->loadConfiguration($name, $config);
  159. /** @var UniformResourceLocator $locator */
  160. $locator = $this->grav['locator'];
  161. $registered = stream_get_wrappers();
  162. $schemes = $config->get(
  163. "themes.{$name}.streams.schemes",
  164. ['theme' => ['paths' => $locator->findResources("themes://{$name}", false)]]
  165. );
  166. foreach ($schemes as $scheme => $config) {
  167. if (isset($config['paths'])) {
  168. $locator->addPath($scheme, '', $config['paths']);
  169. }
  170. if (isset($config['prefixes'])) {
  171. foreach ($config['prefixes'] as $prefix => $paths) {
  172. $locator->addPath($scheme, $prefix, $paths);
  173. }
  174. }
  175. if (in_array($scheme, $registered)) {
  176. stream_wrapper_unregister($scheme);
  177. }
  178. $type = !empty($config['type']) ? $config['type'] : 'ReadOnlyStream';
  179. if ($type[0] != '\\') {
  180. $type = '\\RocketTheme\\Toolbox\\StreamWrapper\\' . $type;
  181. }
  182. if (!stream_wrapper_register($scheme, $type)) {
  183. throw new \InvalidArgumentException("Stream '{$type}' could not be initialized.");
  184. }
  185. }
  186. // Load languages after streams has been properly initialized
  187. $this->loadLanguages($this->config);
  188. }
  189. /**
  190. * Load theme configuration.
  191. *
  192. * @param string $name Theme name
  193. * @param Config $config Configuration class
  194. */
  195. protected function loadConfiguration($name, Config $config)
  196. {
  197. $themeConfig = CompiledYamlFile::instance("themes://{$name}/{$name}" . YAML_EXT)->content();
  198. $config->joinDefaults("themes.{$name}", $themeConfig);
  199. }
  200. /**
  201. * Load theme languages.
  202. *
  203. * @param Config $config Configuration class
  204. */
  205. protected function loadLanguages(Config $config)
  206. {
  207. /** @var UniformResourceLocator $locator */
  208. $locator = $this->grav['locator'];
  209. if ($config->get('system.languages.translations', true)) {
  210. $languageFiles = array_reverse($locator->findResources("theme://languages" . YAML_EXT));
  211. $languages = [];
  212. foreach ($languageFiles as $language) {
  213. $languages[] = CompiledYamlFile::instance($language)->content();
  214. }
  215. if ($languages) {
  216. $languages = call_user_func_array('array_replace_recursive', $languages);
  217. $config->getLanguages()->mergeRecursive($languages);
  218. }
  219. }
  220. }
  221. /**
  222. * Autoload theme classes for inheritance
  223. *
  224. * @param string $class Class name
  225. *
  226. * @return mixed false FALSE if unable to load $class; Class name if
  227. * $class is successfully loaded
  228. */
  229. protected function autoloadTheme($class)
  230. {
  231. /** @var UniformResourceLocator $locator */
  232. $locator = $this->grav['locator'];
  233. $prefix = "Grav\\Theme";
  234. if (false !== strpos($class, $prefix)) {
  235. // Remove prefix from class
  236. $class = substr($class, strlen($prefix));
  237. // Replace namespace tokens to directory separators
  238. $path = ltrim(preg_replace('#\\\|_(?!.+\\\)#', '/', $class), '/');
  239. $file = $locator->findResource("themes://{$path}/{$path}.php");
  240. // Load class
  241. if (stream_resolve_include_path($file)) {
  242. return include_once($file);
  243. }
  244. }
  245. return false;
  246. }
  247. }