Excerpts.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. /**
  3. * @package Grav\Common\Page
  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\Page\Markdown;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Page\Interfaces\PageInterface;
  11. use Grav\Common\Page\Medium\Link;
  12. use Grav\Common\Page\Pages;
  13. use Grav\Common\Uri;
  14. use Grav\Common\Page\Medium\Medium;
  15. use Grav\Common\Utils;
  16. use RocketTheme\Toolbox\Event\Event;
  17. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  18. use function array_key_exists;
  19. use function call_user_func_array;
  20. use function count;
  21. use function dirname;
  22. use function in_array;
  23. use function is_bool;
  24. use function is_string;
  25. /**
  26. * Class Excerpts
  27. * @package Grav\Common\Page\Markdown
  28. */
  29. class Excerpts
  30. {
  31. /** @var PageInterface|null */
  32. protected $page;
  33. /** @var array */
  34. protected $config;
  35. /**
  36. * Excerpts constructor.
  37. * @param PageInterface|null $page
  38. * @param array|null $config
  39. */
  40. public function __construct(PageInterface $page = null, array $config = null)
  41. {
  42. $this->page = $page ?? Grav::instance()['page'] ?? null;
  43. // Add defaults to the configuration.
  44. if (null === $config || !isset($config['markdown'], $config['images'])) {
  45. $c = Grav::instance()['config'];
  46. $config = $config ?? [];
  47. $config += [
  48. 'markdown' => $c->get('system.pages.markdown', []),
  49. 'images' => $c->get('system.images', [])
  50. ];
  51. }
  52. $this->config = $config;
  53. }
  54. /**
  55. * @return PageInterface|null
  56. */
  57. public function getPage(): ?PageInterface
  58. {
  59. return $this->page;
  60. }
  61. /**
  62. * @return array
  63. */
  64. public function getConfig(): array
  65. {
  66. return $this->config;
  67. }
  68. /**
  69. * @param object $markdown
  70. * @return void
  71. */
  72. public function fireInitializedEvent($markdown): void
  73. {
  74. $grav = Grav::instance();
  75. $grav->fireEvent('onMarkdownInitialized', new Event(['markdown' => $markdown, 'page' => $this->page]));
  76. }
  77. /**
  78. * Process a Link excerpt
  79. *
  80. * @param array $excerpt
  81. * @param string $type
  82. * @return array
  83. */
  84. public function processLinkExcerpt(array $excerpt, string $type = 'link'): array
  85. {
  86. $url = htmlspecialchars_decode(rawurldecode($excerpt['element']['attributes']['href']));
  87. $url_parts = $this->parseUrl($url);
  88. // If there is a query, then parse it and build action calls.
  89. if (isset($url_parts['query'])) {
  90. $actions = array_reduce(
  91. explode('&', $url_parts['query']),
  92. static function ($carry, $item) {
  93. $parts = explode('=', $item, 2);
  94. $value = isset($parts[1]) ? rawurldecode($parts[1]) : true;
  95. $carry[$parts[0]] = $value;
  96. return $carry;
  97. },
  98. []
  99. );
  100. // Valid attributes supported.
  101. $valid_attributes = Grav::instance()['config']->get('system.pages.markdown.valid_link_attributes');
  102. $skip = [];
  103. // Unless told to not process, go through actions.
  104. if (array_key_exists('noprocess', $actions)) {
  105. $skip = is_bool($actions['noprocess']) ? $actions : explode(',', $actions['noprocess']);
  106. unset($actions['noprocess']);
  107. }
  108. // Loop through actions for the image and call them.
  109. foreach ($actions as $attrib => $value) {
  110. if (!in_array($attrib, $skip)) {
  111. $key = $attrib;
  112. if (in_array($attrib, $valid_attributes, true)) {
  113. // support both class and classes.
  114. if ($attrib === 'classes') {
  115. $attrib = 'class';
  116. }
  117. $excerpt['element']['attributes'][$attrib] = str_replace(',', ' ', $value);
  118. unset($actions[$key]);
  119. }
  120. }
  121. }
  122. $url_parts['query'] = http_build_query($actions, '', '&', PHP_QUERY_RFC3986);
  123. }
  124. // If no query elements left, unset query.
  125. if (empty($url_parts['query'])) {
  126. unset($url_parts['query']);
  127. }
  128. // Set path to / if not set.
  129. if (empty($url_parts['path'])) {
  130. $url_parts['path'] = '';
  131. }
  132. // If scheme isn't http(s)..
  133. if (!empty($url_parts['scheme']) && !in_array($url_parts['scheme'], ['http', 'https'])) {
  134. // Handle custom streams.
  135. if ($type !== 'image' && !empty($url_parts['stream']) && !empty($url_parts['path'])) {
  136. $grav = Grav::instance();
  137. $url_parts['path'] = $grav['base_url_relative'] . '/' . $this->resolveStream("{$url_parts['scheme']}://{$url_parts['path']}");
  138. unset($url_parts['stream'], $url_parts['scheme']);
  139. }
  140. $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);
  141. return $excerpt;
  142. }
  143. // Handle paths and such.
  144. $url_parts = Uri::convertUrl($this->page, $url_parts, $type);
  145. // Build the URL from the component parts and set it on the element.
  146. $excerpt['element']['attributes']['href'] = Uri::buildUrl($url_parts);
  147. return $excerpt;
  148. }
  149. /**
  150. * Process an image excerpt
  151. *
  152. * @param array $excerpt
  153. * @return array
  154. */
  155. public function processImageExcerpt(array $excerpt): array
  156. {
  157. $url = htmlspecialchars_decode(urldecode($excerpt['element']['attributes']['src']));
  158. $url_parts = $this->parseUrl($url);
  159. $media = null;
  160. $filename = null;
  161. if (!empty($url_parts['stream'])) {
  162. $filename = $url_parts['scheme'] . '://' . ($url_parts['path'] ?? '');
  163. $media = $this->page->getMedia();
  164. } else {
  165. $grav = Grav::instance();
  166. /** @var Pages $pages */
  167. $pages = $grav['pages'];
  168. // File is also local if scheme is http(s) and host matches.
  169. $local_file = isset($url_parts['path'])
  170. && (empty($url_parts['scheme']) || in_array($url_parts['scheme'], ['http', 'https'], true))
  171. && (empty($url_parts['host']) || $url_parts['host'] === $grav['uri']->host());
  172. if ($local_file) {
  173. $filename = basename($url_parts['path']);
  174. $folder = dirname($url_parts['path']);
  175. // Get the local path to page media if possible.
  176. if ($this->page && $folder === $this->page->url(false, false, false)) {
  177. // Get the media objects for this page.
  178. $media = $this->page->getMedia();
  179. } else {
  180. // see if this is an external page to this one
  181. $base_url = rtrim($grav['base_url_relative'] . $pages->base(), '/');
  182. $page_route = '/' . ltrim(str_replace($base_url, '', $folder), '/');
  183. $ext_page = $pages->find($page_route, true);
  184. if ($ext_page) {
  185. $media = $ext_page->getMedia();
  186. } else {
  187. $grav->fireEvent('onMediaLocate', new Event(['route' => $page_route, 'media' => &$media]));
  188. }
  189. }
  190. }
  191. }
  192. // If there is a media file that matches the path referenced..
  193. if ($media && $filename && isset($media[$filename])) {
  194. // Get the medium object.
  195. /** @var Medium $medium */
  196. $medium = $media[$filename];
  197. // Process operations
  198. $medium = $this->processMediaActions($medium, $url_parts);
  199. $element_excerpt = $excerpt['element']['attributes'];
  200. $alt = $element_excerpt['alt'] ?? '';
  201. $title = $element_excerpt['title'] ?? '';
  202. $class = $element_excerpt['class'] ?? '';
  203. $id = $element_excerpt['id'] ?? '';
  204. $excerpt['element'] = $medium->parsedownElement($title, $alt, $class, $id, true);
  205. } else {
  206. // Not a current page media file, see if it needs converting to relative.
  207. $excerpt['element']['attributes']['src'] = Uri::buildUrl($url_parts);
  208. }
  209. return $excerpt;
  210. }
  211. /**
  212. * Process media actions
  213. *
  214. * @param Medium $medium
  215. * @param string|array $url
  216. * @return Medium|Link
  217. */
  218. public function processMediaActions($medium, $url)
  219. {
  220. $url_parts = is_string($url) ? $this->parseUrl($url) : $url;
  221. $actions = [];
  222. // if there is a query, then parse it and build action calls
  223. if (isset($url_parts['query'])) {
  224. $actions = array_reduce(
  225. explode('&', $url_parts['query']),
  226. static function ($carry, $item) {
  227. $parts = explode('=', $item, 2);
  228. $value = $parts[1] ?? null;
  229. $carry[] = ['method' => $parts[0], 'params' => $value];
  230. return $carry;
  231. },
  232. []
  233. );
  234. }
  235. $defaults = $this->config['images']['defaults'] ?? [];
  236. if (count($defaults)) {
  237. foreach ($defaults as $method => $params) {
  238. if (array_search($method, array_column($actions, 'method')) === false) {
  239. $actions[] = [
  240. 'method' => $method,
  241. 'params' => $params,
  242. ];
  243. }
  244. }
  245. }
  246. // loop through actions for the image and call them
  247. foreach ($actions as $action) {
  248. $matches = [];
  249. if (preg_match('/\[(.*)\]/', $action['params'], $matches)) {
  250. $args = [explode(',', $matches[1])];
  251. } else {
  252. $args = explode(',', $action['params']);
  253. }
  254. $medium = call_user_func_array([$medium, $action['method']], $args);
  255. }
  256. if (isset($url_parts['fragment'])) {
  257. $medium->urlHash($url_parts['fragment']);
  258. }
  259. return $medium;
  260. }
  261. /**
  262. * Variation of parse_url() which works also with local streams.
  263. *
  264. * @param string $url
  265. * @return array
  266. */
  267. protected function parseUrl(string $url)
  268. {
  269. $url_parts = Utils::multibyteParseUrl($url);
  270. if (isset($url_parts['scheme'])) {
  271. /** @var UniformResourceLocator $locator */
  272. $locator = Grav::instance()['locator'];
  273. // Special handling for the streams.
  274. if ($locator->schemeExists($url_parts['scheme'])) {
  275. if (isset($url_parts['host'])) {
  276. // Merge host and path into a path.
  277. $url_parts['path'] = $url_parts['host'] . (isset($url_parts['path']) ? '/' . $url_parts['path'] : '');
  278. unset($url_parts['host']);
  279. }
  280. $url_parts['stream'] = true;
  281. }
  282. }
  283. return $url_parts;
  284. }
  285. /**
  286. * @param string $url
  287. * @return string
  288. */
  289. protected function resolveStream(string $url)
  290. {
  291. /** @var UniformResourceLocator $locator */
  292. $locator = Grav::instance()['locator'];
  293. if ($locator->isStream($url)) {
  294. return $locator->findResource($url, false) ?: $locator->findResource($url, false, true);
  295. }
  296. return $url;
  297. }
  298. }