Plugin.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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\Data\Blueprint;
  10. use Grav\Common\Data\Data;
  11. use Grav\Common\Page\Interfaces\PageInterface;
  12. use Grav\Common\Config\Config;
  13. use RocketTheme\Toolbox\Event\EventDispatcher;
  14. use RocketTheme\Toolbox\Event\EventSubscriberInterface;
  15. use RocketTheme\Toolbox\File\YamlFile;
  16. class Plugin implements EventSubscriberInterface, \ArrayAccess
  17. {
  18. /**
  19. * @var string
  20. */
  21. public $name;
  22. /**
  23. * @var array
  24. */
  25. public $features = [];
  26. /**
  27. * @var Grav
  28. */
  29. protected $grav;
  30. /**
  31. * @var Config
  32. */
  33. protected $config;
  34. protected $active = true;
  35. protected $blueprint;
  36. /**
  37. * By default assign all methods as listeners using the default priority.
  38. *
  39. * @return array
  40. */
  41. public static function getSubscribedEvents()
  42. {
  43. $methods = get_class_methods(get_called_class());
  44. $list = [];
  45. foreach ($methods as $method) {
  46. if (strpos($method, 'on') === 0) {
  47. $list[$method] = [$method, 0];
  48. }
  49. }
  50. return $list;
  51. }
  52. /**
  53. * Constructor.
  54. *
  55. * @param string $name
  56. * @param Grav $grav
  57. * @param Config $config
  58. */
  59. public function __construct($name, Grav $grav, Config $config = null)
  60. {
  61. $this->name = $name;
  62. $this->grav = $grav;
  63. if ($config) {
  64. $this->setConfig($config);
  65. }
  66. }
  67. /**
  68. * @param Config $config
  69. * @return $this
  70. */
  71. public function setConfig(Config $config)
  72. {
  73. $this->config = $config;
  74. return $this;
  75. }
  76. /**
  77. * Get configuration of the plugin.
  78. *
  79. * @return array
  80. */
  81. public function config()
  82. {
  83. return $this->config["plugins.{$this->name}"];
  84. }
  85. /**
  86. * Determine if plugin is running under the admin
  87. *
  88. * @return bool
  89. */
  90. public function isAdmin()
  91. {
  92. return Utils::isAdminPlugin();
  93. }
  94. /**
  95. * Determine if plugin is running under the CLI
  96. *
  97. * @return bool
  98. */
  99. public function isCli()
  100. {
  101. return \defined('GRAV_CLI');
  102. }
  103. /**
  104. * Determine if this route is in Admin and active for the plugin
  105. *
  106. * @param string $plugin_route
  107. * @return bool
  108. */
  109. protected function isPluginActiveAdmin($plugin_route)
  110. {
  111. $should_run = false;
  112. $uri = $this->grav['uri'];
  113. if (strpos($uri->path(), $this->config->get('plugins.admin.route') . '/' . $plugin_route) === false) {
  114. $should_run = false;
  115. } elseif (isset($uri->paths()[1]) && $uri->paths()[1] === $plugin_route) {
  116. $should_run = true;
  117. }
  118. return $should_run;
  119. }
  120. /**
  121. * @param array $events
  122. */
  123. protected function enable(array $events)
  124. {
  125. /** @var EventDispatcher $dispatcher */
  126. $dispatcher = $this->grav['events'];
  127. foreach ($events as $eventName => $params) {
  128. if (\is_string($params)) {
  129. $dispatcher->addListener($eventName, [$this, $params]);
  130. } elseif (\is_string($params[0])) {
  131. $dispatcher->addListener($eventName, [$this, $params[0]], $params[1] ?? 0);
  132. } else {
  133. foreach ($params as $listener) {
  134. $dispatcher->addListener($eventName, [$this, $listener[0]], $listener[1] ?? 0);
  135. }
  136. }
  137. }
  138. }
  139. /**
  140. * @param array $events
  141. */
  142. protected function disable(array $events)
  143. {
  144. /** @var EventDispatcher $dispatcher */
  145. $dispatcher = $this->grav['events'];
  146. foreach ($events as $eventName => $params) {
  147. if (\is_string($params)) {
  148. $dispatcher->removeListener($eventName, [$this, $params]);
  149. } elseif (\is_string($params[0])) {
  150. $dispatcher->removeListener($eventName, [$this, $params[0]]);
  151. } else {
  152. foreach ($params as $listener) {
  153. $dispatcher->removeListener($eventName, [$this, $listener[0]]);
  154. }
  155. }
  156. }
  157. }
  158. /**
  159. * Whether or not an offset exists.
  160. *
  161. * @param string $offset An offset to check for.
  162. * @return bool Returns TRUE on success or FALSE on failure.
  163. */
  164. public function offsetExists($offset)
  165. {
  166. $this->loadBlueprint();
  167. if ($offset === 'title') {
  168. $offset = 'name';
  169. }
  170. return isset($this->blueprint[$offset]);
  171. }
  172. /**
  173. * Returns the value at specified offset.
  174. *
  175. * @param string $offset The offset to retrieve.
  176. * @return mixed Can return all value types.
  177. */
  178. public function offsetGet($offset)
  179. {
  180. $this->loadBlueprint();
  181. if ($offset === 'title') {
  182. $offset = 'name';
  183. }
  184. return $this->blueprint[$offset] ?? null;
  185. }
  186. /**
  187. * Assigns a value to the specified offset.
  188. *
  189. * @param string $offset The offset to assign the value to.
  190. * @param mixed $value The value to set.
  191. * @throws \LogicException
  192. */
  193. public function offsetSet($offset, $value)
  194. {
  195. throw new \LogicException(__CLASS__ . ' blueprints cannot be modified.');
  196. }
  197. /**
  198. * Unsets an offset.
  199. *
  200. * @param string $offset The offset to unset.
  201. * @throws \LogicException
  202. */
  203. public function offsetUnset($offset)
  204. {
  205. throw new \LogicException(__CLASS__ . ' blueprints cannot be modified.');
  206. }
  207. /**
  208. * This function will search a string for markdown links in a specific format. The link value can be
  209. * optionally compared against via the $internal_regex and operated on by the callback $function
  210. * provided.
  211. *
  212. * format: [plugin:myplugin_name](function_data)
  213. *
  214. * @param string $content The string to perform operations upon
  215. * @param callable $function The anonymous callback function
  216. * @param string $internal_regex Optional internal regex to extra data from
  217. *
  218. * @return string
  219. */
  220. protected function parseLinks($content, $function, $internal_regex = '(.*)')
  221. {
  222. $regex = '/\[plugin:(?:' . $this->name . ')\]\(' . $internal_regex . '\)/i';
  223. return preg_replace_callback($regex, $function, $content);
  224. }
  225. /**
  226. * Merge global and page configurations.
  227. *
  228. * @param PageInterface $page The page to merge the configurations with the
  229. * plugin settings.
  230. * @param mixed $deep false = shallow|true = recursive|merge = recursive+unique
  231. * @param array $params Array of additional configuration options to
  232. * merge with the plugin settings.
  233. * @param string $type Is this 'plugins' or 'themes'
  234. *
  235. * @return Data
  236. */
  237. protected function mergeConfig(PageInterface $page, $deep = false, $params = [], $type = 'plugins')
  238. {
  239. $class_name = $this->name;
  240. $class_name_merged = $class_name . '.merged';
  241. $defaults = $this->config->get($type . '.' . $class_name, []);
  242. $page_header = $page->header();
  243. $header = [];
  244. if (!isset($page_header->{$class_name_merged}) && isset($page_header->{$class_name})) {
  245. // Get default plugin configurations and retrieve page header configuration
  246. $config = $page_header->{$class_name};
  247. if (\is_bool($config)) {
  248. // Overwrite enabled option with boolean value in page header
  249. $config = ['enabled' => $config];
  250. }
  251. // Merge page header settings using deep or shallow merging technique
  252. $header = $this->mergeArrays($deep, $defaults, $config);
  253. // Create new config object and set it on the page object so it's cached for next time
  254. $page->modifyHeader($class_name_merged, new Data($header));
  255. } else if (isset($page_header->{$class_name_merged})) {
  256. $merged = $page_header->{$class_name_merged};
  257. $header = $merged->toArray();
  258. }
  259. if (empty($header)) {
  260. $header = $defaults;
  261. }
  262. // Merge additional parameter with configuration options
  263. $header = $this->mergeArrays($deep, $header, $params);
  264. // Return configurations as a new data config class
  265. return new Data($header);
  266. }
  267. /**
  268. * Merge arrays based on deepness
  269. *
  270. * @param string|bool $deep
  271. * @param array $array1
  272. * @param array $array2
  273. * @return array
  274. */
  275. private function mergeArrays($deep, $array1, $array2)
  276. {
  277. if ($deep === 'merge') {
  278. return Utils::arrayMergeRecursiveUnique($array1, $array2);
  279. }
  280. if ($deep === true) {
  281. return array_replace_recursive($array1, $array2);
  282. }
  283. return array_merge($array1, $array2);
  284. }
  285. /**
  286. * Persists to disk the plugin parameters currently stored in the Grav Config object
  287. *
  288. * @param string $plugin_name The name of the plugin whose config it should store.
  289. *
  290. * @return bool
  291. */
  292. public static function saveConfig($plugin_name)
  293. {
  294. if (!$plugin_name) {
  295. return false;
  296. }
  297. $grav = Grav::instance();
  298. $locator = $grav['locator'];
  299. $filename = 'config://plugins/' . $plugin_name . '.yaml';
  300. $file = YamlFile::instance($locator->findResource($filename, true, true));
  301. $content = $grav['config']->get('plugins.' . $plugin_name);
  302. $file->save($content);
  303. $file->free();
  304. return true;
  305. }
  306. /**
  307. * Simpler getter for the plugin blueprint
  308. *
  309. * @return Blueprint
  310. */
  311. public function getBlueprint()
  312. {
  313. if (!$this->blueprint) {
  314. $this->loadBlueprint();
  315. }
  316. return $this->blueprint;
  317. }
  318. /**
  319. * Load blueprints.
  320. */
  321. protected function loadBlueprint()
  322. {
  323. if (!$this->blueprint) {
  324. $grav = Grav::instance();
  325. $plugins = $grav['plugins'];
  326. $this->blueprint = $plugins->get($this->name)->blueprints();
  327. }
  328. }
  329. }