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.

285 lines
8.3 KiB

10 years ago
  1. <?php
  2. function oembed_replacecb($matches){
  3. $embedurl=$matches[1];
  4. $j = oembed_fetch_url($embedurl);
  5. $s = oembed_format_object($j);
  6. return $s;
  7. }
  8. function oembed_fetch_url($embedurl, $no_rich_type = false){
  9. $embedurl = trim($embedurl, "'");
  10. $embedurl = trim($embedurl, '"');
  11. $a = get_app();
  12. $r = q("SELECT * FROM `oembed` WHERE `url` = '%s'",
  13. dbesc(normalise_link($embedurl)));
  14. if ($r)
  15. $txt = $r[0]["content"];
  16. else
  17. $txt = Cache::get($a->videowidth . $embedurl);
  18. // These media files should now be caught in bbcode.php
  19. // left here as a fallback in case this is called from another source
  20. $noexts = array("mp3","mp4","ogg","ogv","oga","ogm","webm");
  21. $ext = pathinfo(strtolower($embedurl),PATHINFO_EXTENSION);
  22. if(is_null($txt)){
  23. $txt = "";
  24. if (!in_array($ext, $noexts)){
  25. // try oembed autodiscovery
  26. $redirects = 0;
  27. $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*"); /**/
  28. if($html_text){
  29. $dom = @DOMDocument::loadHTML($html_text);
  30. if ($dom){
  31. $xpath = new DOMXPath($dom);
  32. $attr = "oembed";
  33. $xattr = oe_build_xpath("class","oembed");
  34. $entries = $xpath->query("//link[@type='application/json+oembed']");
  35. foreach($entries as $e){
  36. $href = $e->getAttributeNode("href")->nodeValue;
  37. $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
  38. break;
  39. }
  40. $entries = $xpath->query("//link[@type='text/json+oembed']");
  41. foreach($entries as $e){
  42. $href = $e->getAttributeNode("href")->nodeValue;
  43. $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
  44. break;
  45. }
  46. }
  47. }
  48. }
  49. if ($txt==false || $txt==""){
  50. $embedly = get_config("system", "embedly");
  51. if ($embedly != "") {
  52. // try embedly service
  53. $ourl = "https://api.embed.ly/1/oembed?key=".$embedly."&url=".urlencode($embedurl);
  54. $txt = fetch_url($ourl);
  55. logger("oembed_fetch_url: ".$txt, LOGGER_DEBUG);
  56. }
  57. }
  58. $txt=trim($txt);
  59. if ($txt[0]!="{")
  60. $txt='{"type":"error"}';
  61. else { //save in cache
  62. $j = json_decode($txt);
  63. if ($j->type != "error")
  64. q("INSERT INTO `oembed` (`url`, `content`) VALUES ('%s', '%s')",
  65. dbesc(normalise_link($embedurl)), dbesc($txt));
  66. Cache::set($a->videowidth . $embedurl,$txt, CACHE_DAY);
  67. }
  68. }
  69. $j = json_decode($txt);
  70. if (!is_object($j))
  71. return false;
  72. // Always embed the SSL version
  73. if (isset($j->html))
  74. $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
  75. array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
  76. $j->embedurl = $embedurl;
  77. // If fetching information doesn't work, then improve via internal functions
  78. if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
  79. require_once("mod/parse_url.php");
  80. $data = parseurl_getsiteinfo_cached($embedurl, true, false);
  81. $j->type = $data["type"];
  82. if ($j->type == "photo") {
  83. $j->url = $data["url"];
  84. //$j->width = $data["images"][0]["width"];
  85. //$j->height = $data["images"][0]["height"];
  86. }
  87. if (isset($data["title"]))
  88. $j->title = $data["title"];
  89. if (isset($data["text"]))
  90. $j->description = $data["text"];
  91. if (is_array($data["images"])) {
  92. $j->thumbnail_url = $data["images"][0]["src"];
  93. $j->thumbnail_width = $data["images"][0]["width"];
  94. $j->thumbnail_height = $data["images"][0]["height"];
  95. }
  96. }
  97. call_hooks('oembed_fetch_url', $embedurl, $j);
  98. return $j;
  99. }
  100. function oembed_format_object($j){
  101. require_once("mod/proxy.php");
  102. $a = get_app();
  103. $embedurl = $j->embedurl;
  104. $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
  105. $ret="<span class='oembed ".$j->type."'>";
  106. switch ($j->type) {
  107. case "video": {
  108. if (isset($j->thumbnail_url)) {
  109. $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
  110. $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
  111. // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
  112. $tr = (($th) ? $tw/$th : 1);
  113. $th=120; $tw = $th*$tr;
  114. $tpl=get_markup_template('oembed_video.tpl');
  115. $ret.=replace_macros($tpl, array(
  116. '$baseurl' => $a->get_baseurl(),
  117. '$embedurl'=>$embedurl,
  118. '$escapedhtml'=>base64_encode($jhtml),
  119. '$tw'=>$tw,
  120. '$th'=>$th,
  121. '$turl'=>$j->thumbnail_url,
  122. ));
  123. } else {
  124. $ret=$jhtml;
  125. }
  126. //$ret.="<br>";
  127. }; break;
  128. case "photo": {
  129. $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
  130. }; break;
  131. case "link": {
  132. }; break;
  133. case "rich": {
  134. // not so safe..
  135. if (!get_config("system","no_oembed_rich_content"))
  136. $ret.= proxy_parse_html($jhtml);
  137. }; break;
  138. }
  139. // add link to source if not present in "rich" type
  140. if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
  141. $ret .= "<h4>";
  142. if (isset($j->title)) {
  143. if (isset($j->provider_name))
  144. $ret .= $j->provider_name.": ";
  145. $embedlink = (isset($j->title))?$j->title:$embedurl;
  146. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  147. if (isset($j->author_name))
  148. $ret.=" (".$j->author_name.")";
  149. } elseif (isset($j->provider_name) OR isset($j->author_name)) {
  150. $embedlink = "";
  151. if (isset($j->provider_name))
  152. $embedlink .= $j->provider_name;
  153. if (isset($j->author_name)) {
  154. if ($embedlink != "")
  155. $embedlink .= ": ";
  156. $embedlink .= $j->author_name;
  157. }
  158. if (trim($embedlink) == "")
  159. $embedlink = $embedurl;
  160. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  161. }
  162. //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
  163. //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
  164. $ret .= "</h4>";
  165. } else {
  166. // add <a> for html2bbcode conversion
  167. $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
  168. }
  169. $ret.="</span>";
  170. $ret = str_replace("\n","",$ret);
  171. return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
  172. }
  173. function oembed_iframe($src,$width,$height) {
  174. if(! $width || strstr($width,'%'))
  175. $width = '640';
  176. if(! $height || strstr($height,'%')) {
  177. $height = '300';
  178. $resize = 'onload="resizeIframe(this);"';
  179. } else
  180. $resize = '';
  181. // try and leave some room for the description line.
  182. $height = intval($height) + 80;
  183. $width = intval($width) + 40;
  184. $a = get_app();
  185. $s = $a->get_baseurl()."/oembed/".base64url_encode($src);
  186. return '<iframe '.$resize.' class="embed_rich" height="'.$height.'" width="'.$width.'" src="'.$s.'" frameborder="no">'.t('Embedded content').'</iframe>';
  187. }
  188. function oembed_bbcode2html($text){
  189. $stopoembed = get_config("system","no_oembed");
  190. if ($stopoembed == true){
  191. return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
  192. }
  193. return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
  194. }
  195. function oe_build_xpath($attr, $value){
  196. // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
  197. 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'";
  198. }
  199. function oe_get_inner_html( $node ) {
  200. $innerHTML= '';
  201. $children = $node->childNodes;
  202. foreach ($children as $child) {
  203. $innerHTML .= $child->ownerDocument->saveXML( $child );
  204. }
  205. return $innerHTML;
  206. }
  207. /**
  208. * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
  209. * and replace it with [embed]url[/embed]
  210. */
  211. function oembed_html2bbcode($text) {
  212. // start parser only if 'oembed' is in text
  213. if (strpos($text, "oembed")){
  214. // convert non ascii chars to html entities
  215. $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
  216. // If it doesn't parse at all, just return the text.
  217. $dom = @DOMDocument::loadHTML($html_text);
  218. if(! $dom)
  219. return $text;
  220. $xpath = new DOMXPath($dom);
  221. $attr = "oembed";
  222. $xattr = oe_build_xpath("class","oembed");
  223. $entries = $xpath->query("//span[$xattr]");
  224. $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
  225. foreach($entries as $e) {
  226. $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
  227. if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
  228. }
  229. return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
  230. } else {
  231. return $text;
  232. }
  233. }