Service.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. /**
  3. * Service
  4. *
  5. * This file is part of Grav MediaEmbed plugin.
  6. *
  7. * Dual licensed under the MIT or GPL Version 3 licenses, see LICENSE.
  8. * http://benjamin-regler.de/license/
  9. */
  10. namespace Grav\Plugin\MediaEmbed;
  11. use Grav\Common\Grav;
  12. use Grav\Common\GravTrait;
  13. use RocketTheme\Toolbox\Event\Event;
  14. /**
  15. * Service
  16. */
  17. class Service
  18. {
  19. /**
  20. * @var Service
  21. */
  22. use GravTrait;
  23. /** ---------------------------
  24. * Private/protected properties
  25. * ----------------------------
  26. */
  27. /**
  28. * @var Grav\Plugin\MediaEmbed\ServiceProvider
  29. */
  30. protected $services = [];
  31. /**
  32. * @var array
  33. */
  34. protected $domains;
  35. /** -------------
  36. * Public methods
  37. * --------------
  38. */
  39. public function __construct()
  40. {
  41. // Fire event
  42. self::getGrav()->fireEvent('onMediaEmbed', new Event(['service' => $this]));
  43. }
  44. public function call($method, $params = [])
  45. {
  46. $result = [];
  47. foreach ($this->services as $key => $service) {
  48. if (method_exists($service['provider'], $method)) {
  49. $data = call_user_method_array([$service['provider'], $method], $params);
  50. if ($data) {
  51. $result[] = $data;
  52. }
  53. }
  54. }
  55. return $result;
  56. }
  57. public function match($url, $embedCode = null)
  58. {
  59. $embed_key = 'embed';
  60. if ($embedCode && (strtolower($embedCode) !== $embed_key)) {
  61. return false;
  62. }
  63. $parts = $this->parseUrl($url);
  64. if ($parts['host'] == $embed_key) {
  65. return false;
  66. }
  67. return isset($this->domains[$parts['host']]);
  68. }
  69. public function embed($embedCode, $options = [])
  70. {
  71. if (!$this->match($embedCode)) {
  72. throw new \Exception('Unknown embed code "' . htmlspecialchars($embedCode) . '".');
  73. }
  74. // Extract domain from embed code
  75. $domain = strtolower($this->parseUrl($embedCode)['host']);
  76. $key = $this->domains[$domain];
  77. // Call OEmbed service provider
  78. $provider = $this->services[$key]['provider'];
  79. $provider->init($embedCode, $options);
  80. // Return initialized provider
  81. return $provider;
  82. // // Get type of media
  83. // $type = ucfirst($provider->type());
  84. // // Get the default properties of the response class
  85. // $class = __NAMESPACE__ . "\\Response\\{$type}Response";
  86. // // Repopulate properties
  87. // $vars = [
  88. // 'raw' => $embedCode,
  89. // 'options' => $provider->attributes(),
  90. // 'url' => $provider->getEmbedCode(,
  91. // ] + get_class_vars($class);
  92. // // Enrich properties with media resource informations
  93. // foreach ($vars as $key => $value) {
  94. // if (!$value) {
  95. // $vars[$key] = $provider->{$key}();
  96. // }
  97. // }
  98. // // Create response
  99. // $response = new $class($vars);
  100. // return [$provider, $response];
  101. // try {
  102. // // Call ServiceProvider
  103. // $provider->init($embedCode);
  104. // $embed += array(
  105. // // Get unique id of video
  106. // 'id' => $provider->canonicalize($embedCode),
  107. // // Templates are stored in the templates/partials folder
  108. // 'assets' => $provider->getAssets(),
  109. // 'template' => $provider->getTemplatePaths(),
  110. // 'variables' => $provider->getTemplateVariables(),
  111. // // Store embed status of ServiceProvider call
  112. // 'success' => true,
  113. // 'message' => '',
  114. // );
  115. // } catch (\Exception $e) {
  116. // $embed['success'] = false;
  117. // $embed['message'] = $e->getMessage();
  118. // }
  119. // }
  120. // return $embed;
  121. }
  122. public function getDomains()
  123. {
  124. $allDomains = [];
  125. foreach ($this->services as $key => $service) {
  126. $allDomains[] = $service['domains'];
  127. }
  128. // Flatten multidimensional array of domains
  129. $domains = [];
  130. array_walk($allDomains, function($domain) use (&$domains) {
  131. $domains[] = $domain;
  132. });
  133. // Return unique array of domains
  134. return array_unique($domains);
  135. }
  136. public function getProviders()
  137. {
  138. // Get providers sorted by priority
  139. $classes = $this->collectProviders(function($key, $service) {
  140. return true;
  141. }, true, 'class');
  142. // Replace names with provider classes
  143. $providers = [];
  144. foreach ($classes as $class) {
  145. $name = substr($class, strrpos($class, '\\') + 1);
  146. $provider = $this->services[$class]['provider'];
  147. if ( isset($providers[$name]) ) {
  148. $providers[$name] = array($providers[$name], $provider);
  149. } else {
  150. $providers[$name][] = $provider;
  151. }
  152. }
  153. return $providers;
  154. }
  155. public function getProviderByName($name, $all = false)
  156. {
  157. $providers = $this->collectProviders(
  158. function($key, $service) use ($name) {
  159. return preg_match("~^$name$~i", $service['name']);
  160. }, $all);
  161. return $providers;
  162. }
  163. public function getProviderByDomain($domain, $all = false)
  164. {
  165. $providers = $this->collectProviders(
  166. function($key, $service) use ($domain) {
  167. return in_array($domain, $service['domains']);
  168. }, $all);
  169. return $providers;
  170. }
  171. public function register($provider, $priority = 0)
  172. {
  173. if ($provider instanceof \Grav\Plugin\MediaEmbed\OEmbed\OEmbed) {
  174. $key = md5(spl_object_hash($provider));
  175. $domains = $provider->getDomains();
  176. $this->services[$key] = array(
  177. 'priority' => $priority,
  178. 'domains' => $domains,
  179. 'provider' => $provider,
  180. 'name' => $provider->name(),
  181. 'class' => $key,
  182. );
  183. foreach ($domains as $domain) {
  184. if (!isset($this->domains[$domain]) || ($priority > $this->services[$domain]['priority'])) {
  185. $this->domains[$domain] = $key;
  186. }
  187. }
  188. }
  189. }
  190. public function unregister($provider)
  191. {
  192. if ($provider instanceof \Grav\Plugin\MediaEmbed\OEmbed\OEmbed) {
  193. $key = md5(spl_object_hash($provider));
  194. if (isset($this->services[$key])) {
  195. $domains = $this->services[$key]['domains'];
  196. unset($this->services[$key]);
  197. // Unset and repopulate domain keys, if possible
  198. foreach ($domains as $domain) {
  199. if ($provider = $this->getProviderByDomain($domain)) {
  200. $this->domains[$domain] = get_class($provider);
  201. } else {
  202. unset($this->domains[$domain]);
  203. }
  204. }
  205. }
  206. }
  207. }
  208. protected function collectProviders($callback, $all, $id = 'provider')
  209. {
  210. $services = [];
  211. foreach ($this->services as $key => $service) {
  212. if ($callback($key, $service)) {
  213. $services[] = $service;
  214. }
  215. }
  216. // Sort providers based on priority
  217. uasort($services, function ($a, $b) {
  218. // Priority is first sort criterion
  219. $cmp = $a['priority'] - $b['priority'];
  220. // Text string is second criterion (in case of two equal priorities)
  221. if ( $cmp == 0 ) {
  222. $cmp = strnatcmp($a['name'], $b['name']);
  223. }
  224. return $cmp;
  225. });
  226. // Strip additional service informations
  227. $providers = array_map(function($service) use ($id) {
  228. return $service[$id];
  229. }, $services);
  230. if (count($providers)) {
  231. // Return providers
  232. return ($all ? $providers : $providers[0]);
  233. }
  234. return [];
  235. }
  236. /** -------------------------------
  237. * Private/protected helper methods
  238. * --------------------------------
  239. */
  240. protected function parseUrl($url)
  241. {
  242. if (!filter_var($url, FILTER_VALIDATE_URL)) {
  243. return [];
  244. }
  245. // Parse URL
  246. $url = html_entity_decode($url, ENT_COMPAT | ENT_HTML401, 'UTF-8');
  247. $parts = parse_url($url);
  248. $parts['url'] = $url;
  249. $parts['host'] = preg_replace("/^www\./", '', $parts['host']);
  250. // Get top-level domain from URL
  251. $parts['domain'] = isset($parts['host']) ? $parts['host'] : '';
  252. if ( preg_match('~(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$~i', $parts['domain'], $match) ) {
  253. $parts['domain'] = $match['domain'];
  254. }
  255. if (isset($parts['query'])) {
  256. parse_str(urldecode($parts['query']), $parts['query']);
  257. }
  258. $parts['query'] = [];
  259. return $parts;
  260. }
  261. }