Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

315 lines
9.1 KiB

  1. <?php
  2. /**
  3. * @file include/oembed.php
  4. */
  5. use Friendica\App;
  6. use Friendica\ParseUrl;
  7. use Friendica\Core\Config;
  8. function oembed_replacecb($matches){
  9. $embedurl=$matches[1];
  10. $j = oembed_fetch_url($embedurl);
  11. $s = oembed_format_object($j);
  12. return $s;
  13. }
  14. /**
  15. * @brief Get data from an URL to embed its content.
  16. *
  17. * @param string $embedurl The URL from which the data should be fetched.
  18. * @param bool $no_rich_type If set to true rich type content won't be fetched.
  19. *
  20. * @return bool|object Returns object with embed content or false if no embedable
  21. * content exists
  22. */
  23. function oembed_fetch_url($embedurl, $no_rich_type = false){
  24. $embedurl = trim($embedurl, "'");
  25. $embedurl = trim($embedurl, '"');
  26. $a = get_app();
  27. $r = q("SELECT * FROM `oembed` WHERE `url` = '%s'",
  28. dbesc(normalise_link($embedurl)));
  29. if (dbm::is_result($r)) {
  30. $txt = $r[0]["content"];
  31. } else {
  32. $txt = Cache::get($a->videowidth . $embedurl);
  33. }
  34. // These media files should now be caught in bbcode.php
  35. // left here as a fallback in case this is called from another source
  36. $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
  37. $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
  38. if (is_null($txt)) {
  39. $txt = "";
  40. if (!in_array($ext, $noexts)){
  41. // try oembed autodiscovery
  42. $redirects = 0;
  43. $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
  44. if ($html_text) {
  45. $dom = @DOMDocument::loadHTML($html_text);
  46. if ($dom) {
  47. $xpath = new DOMXPath($dom);
  48. $attr = "oembed";
  49. $xattr = oe_build_xpath("class","oembed");
  50. $entries = $xpath->query("//link[@type='application/json+oembed']");
  51. foreach ($entries as $e) {
  52. $href = $e->getAttributeNode("href")->nodeValue;
  53. $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
  54. break;
  55. }
  56. $entries = $xpath->query("//link[@type='text/json+oembed']");
  57. foreach ($entries as $e) {
  58. $href = $e->getAttributeNode("href")->nodeValue;
  59. $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
  60. break;
  61. }
  62. }
  63. }
  64. }
  65. $txt = trim($txt);
  66. if ($txt[0] != "{") {
  67. $txt = '{"type":"error"}';
  68. } else { //save in cache
  69. $j = json_decode($txt);
  70. if ($j->type != "error") {
  71. q("INSERT INTO `oembed` (`url`, `content`, `created`) VALUES ('%s', '%s', '%s')
  72. ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
  73. dbesc(normalise_link($embedurl)),
  74. dbesc($txt), dbesc(datetime_convert()),
  75. dbesc($txt), dbesc(datetime_convert()));
  76. }
  77. Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
  78. }
  79. }
  80. $j = json_decode($txt);
  81. if (!is_object($j)) {
  82. return false;
  83. }
  84. // Always embed the SSL version
  85. if (isset($j->html)) {
  86. $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
  87. array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
  88. }
  89. $j->embedurl = $embedurl;
  90. // If fetching information doesn't work, then improve via internal functions
  91. if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
  92. $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
  93. $j->type = $data["type"];
  94. if ($j->type == "photo") {
  95. $j->url = $data["url"];
  96. //$j->width = $data["images"][0]["width"];
  97. //$j->height = $data["images"][0]["height"];
  98. }
  99. if (isset($data["title"])) {
  100. $j->title = $data["title"];
  101. }
  102. if (isset($data["text"])) {
  103. $j->description = $data["text"];
  104. }
  105. if (is_array($data["images"])) {
  106. $j->thumbnail_url = $data["images"][0]["src"];
  107. $j->thumbnail_width = $data["images"][0]["width"];
  108. $j->thumbnail_height = $data["images"][0]["height"];
  109. }
  110. }
  111. call_hooks('oembed_fetch_url', $embedurl, $j);
  112. return $j;
  113. }
  114. function oembed_format_object($j){
  115. require_once("mod/proxy.php");
  116. $embedurl = $j->embedurl;
  117. $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
  118. $ret="<span class='oembed ".$j->type."'>";
  119. switch ($j->type) {
  120. case "video":
  121. if (isset($j->thumbnail_url)) {
  122. $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
  123. $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
  124. // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
  125. $tr = (($th) ? $tw/$th : 1);
  126. $th=120; $tw = $th*$tr;
  127. $tpl=get_markup_template('oembed_video.tpl');
  128. $ret.=replace_macros($tpl, array(
  129. '$baseurl' => App::get_baseurl(),
  130. '$embedurl' => $embedurl,
  131. '$escapedhtml' => base64_encode($jhtml),
  132. '$tw' => $tw,
  133. '$th' => $th,
  134. '$turl' => $j->thumbnail_url,
  135. ));
  136. } else {
  137. $ret=$jhtml;
  138. }
  139. //$ret.="<br>";
  140. break;
  141. case "photo":
  142. $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
  143. break;
  144. case "link":
  145. break;
  146. case "rich":
  147. // not so safe..
  148. if (!Config::get("system","no_oembed_rich_content")) {
  149. $ret.= proxy_parse_html($jhtml);
  150. }
  151. break;
  152. }
  153. // add link to source if not present in "rich" type
  154. if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
  155. $ret .= "<h4>";
  156. if (isset($j->title)) {
  157. if (isset($j->provider_name)) {
  158. $ret .= $j->provider_name.": ";
  159. }
  160. $embedlink = (isset($j->title))?$j->title:$embedurl;
  161. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  162. if (isset($j->author_name)) {
  163. $ret.=" (".$j->author_name.")";
  164. }
  165. } elseif (isset($j->provider_name) OR isset($j->author_name)) {
  166. $embedlink = "";
  167. if (isset($j->provider_name)) {
  168. $embedlink .= $j->provider_name;
  169. }
  170. if (isset($j->author_name)) {
  171. if ($embedlink != "") {
  172. $embedlink .= ": ";
  173. }
  174. $embedlink .= $j->author_name;
  175. }
  176. if (trim($embedlink) == "") {
  177. $embedlink = $embedurl;
  178. }
  179. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  180. }
  181. //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
  182. //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
  183. $ret .= "</h4>";
  184. } else {
  185. // add <a> for html2bbcode conversion
  186. $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
  187. }
  188. $ret.="</span>";
  189. $ret = str_replace("\n","",$ret);
  190. return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
  191. }
  192. /**
  193. * @brief Generates the iframe HTML for an oembed attachment.
  194. *
  195. * Width and height are given by the remote, and are regularly too small for
  196. * the generated iframe.
  197. *
  198. * The width is entirely discarded for the actual width of the post, while fixed
  199. * height is used as a starting point before the inevitable resizing.
  200. *
  201. * Since the iframe is automatically resized on load, there are no need for ugly
  202. * and impractical scrollbars.
  203. *
  204. * @param string $src Original remote URL to embed
  205. * @param string $width
  206. * @param string $height
  207. * @return string formatted HTML
  208. *
  209. * @see oembed_format_object()
  210. */
  211. function oembed_iframe($src, $width, $height) {
  212. $a = get_app();
  213. if (!$height || strstr($height,'%')) {
  214. $height = '200';
  215. }
  216. $width = '100%';
  217. $s = App::get_baseurl() . '/oembed/' . base64url_encode($src);
  218. return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
  219. }
  220. function oembed_bbcode2html($text){
  221. $stopoembed = Config::get("system","no_oembed");
  222. if ($stopoembed == true){
  223. return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
  224. }
  225. return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
  226. }
  227. function oe_build_xpath($attr, $value){
  228. // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
  229. return "contains( normalize-space( @$attr ), ' $value ' ) or substring( normalize-space( @$attr ), 1, string-length( '$value' ) + 1 ) = '$value ' or substring( normalize-space( @$attr ), string-length( @$attr ) - string-length( '$value' ) ) = ' $value' or @$attr = '$value'";
  230. }
  231. function oe_get_inner_html($node) {
  232. $innerHTML= '';
  233. $children = $node->childNodes;
  234. foreach ($children as $child) {
  235. $innerHTML .= $child->ownerDocument->saveXML($child);
  236. }
  237. return $innerHTML;
  238. }
  239. /**
  240. * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
  241. * and replace it with [embed]url[/embed]
  242. */
  243. function oembed_html2bbcode($text) {
  244. // start parser only if 'oembed' is in text
  245. if (strpos($text, "oembed")) {
  246. // convert non ascii chars to html entities
  247. $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
  248. // If it doesn't parse at all, just return the text.
  249. $dom = @DOMDocument::loadHTML($html_text);
  250. if (! $dom) {
  251. return $text;
  252. }
  253. $xpath = new DOMXPath($dom);
  254. $attr = "oembed";
  255. $xattr = oe_build_xpath("class","oembed");
  256. $entries = $xpath->query("//span[$xattr]");
  257. $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
  258. foreach($entries as $e) {
  259. $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
  260. if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
  261. }
  262. return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
  263. } else {
  264. return $text;
  265. }
  266. }