Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

328 Zeilen
9.3KB

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