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.

315 Zeilen
9.1KB

  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. $txt = trim($txt);
  65. if ($txt[0] != "{") {
  66. $txt = '{"type":"error"}';
  67. } else { //save in cache
  68. $j = json_decode($txt);
  69. if ($j->type != "error") {
  70. q("INSERT INTO `oembed` (`url`, `content`, `created`) VALUES ('%s', '%s', '%s')
  71. ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
  72. dbesc(normalise_link($embedurl)),
  73. dbesc($txt), dbesc(datetime_convert()),
  74. dbesc($txt), dbesc(datetime_convert()));
  75. }
  76. Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
  77. }
  78. }
  79. $j = json_decode($txt);
  80. if (!is_object($j)) {
  81. return false;
  82. }
  83. // Always embed the SSL version
  84. if (isset($j->html)) {
  85. $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
  86. array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
  87. }
  88. $j->embedurl = $embedurl;
  89. // If fetching information doesn't work, then improve via internal functions
  90. if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
  91. $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
  92. $j->type = $data["type"];
  93. if ($j->type == "photo") {
  94. $j->url = $data["url"];
  95. //$j->width = $data["images"][0]["width"];
  96. //$j->height = $data["images"][0]["height"];
  97. }
  98. if (isset($data["title"])) {
  99. $j->title = $data["title"];
  100. }
  101. if (isset($data["text"])) {
  102. $j->description = $data["text"];
  103. }
  104. if (is_array($data["images"])) {
  105. $j->thumbnail_url = $data["images"][0]["src"];
  106. $j->thumbnail_width = $data["images"][0]["width"];
  107. $j->thumbnail_height = $data["images"][0]["height"];
  108. }
  109. }
  110. call_hooks('oembed_fetch_url', $embedurl, $j);
  111. return $j;
  112. }
  113. function oembed_format_object($j){
  114. require_once("mod/proxy.php");
  115. $embedurl = $j->embedurl;
  116. $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
  117. $ret="<span class='oembed ".$j->type."'>";
  118. switch ($j->type) {
  119. case "video":
  120. if (isset($j->thumbnail_url)) {
  121. $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
  122. $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
  123. // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
  124. $tr = (($th) ? $tw/$th : 1);
  125. $th=120; $tw = $th*$tr;
  126. $tpl=get_markup_template('oembed_video.tpl');
  127. $ret.=replace_macros($tpl, array(
  128. '$baseurl' => App::get_baseurl(),
  129. '$embedurl' => $embedurl,
  130. '$escapedhtml' => base64_encode($jhtml),
  131. '$tw' => $tw,
  132. '$th' => $th,
  133. '$turl' => $j->thumbnail_url,
  134. ));
  135. } else {
  136. $ret=$jhtml;
  137. }
  138. //$ret.="<br>";
  139. break;
  140. case "photo":
  141. $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
  142. break;
  143. case "link":
  144. break;
  145. case "rich":
  146. // not so safe..
  147. if (!Config::get("system","no_oembed_rich_content")) {
  148. $ret.= proxy_parse_html($jhtml);
  149. }
  150. break;
  151. }
  152. // add link to source if not present in "rich" type
  153. if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
  154. $ret .= "<h4>";
  155. if (isset($j->title)) {
  156. if (isset($j->provider_name)) {
  157. $ret .= $j->provider_name.": ";
  158. }
  159. $embedlink = (isset($j->title))?$j->title:$embedurl;
  160. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  161. if (isset($j->author_name)) {
  162. $ret.=" (".$j->author_name.")";
  163. }
  164. } elseif (isset($j->provider_name) OR isset($j->author_name)) {
  165. $embedlink = "";
  166. if (isset($j->provider_name)) {
  167. $embedlink .= $j->provider_name;
  168. }
  169. if (isset($j->author_name)) {
  170. if ($embedlink != "") {
  171. $embedlink .= ": ";
  172. }
  173. $embedlink .= $j->author_name;
  174. }
  175. if (trim($embedlink) == "") {
  176. $embedlink = $embedurl;
  177. }
  178. $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
  179. }
  180. //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
  181. //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
  182. $ret .= "</h4>";
  183. } else {
  184. // add <a> for html2bbcode conversion
  185. $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
  186. }
  187. $ret.="</span>";
  188. $ret = str_replace("\n","",$ret);
  189. return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
  190. }
  191. /**
  192. * @brief Generates the iframe HTML for an oembed attachment.
  193. *
  194. * Width and height are given by the remote, and are regularly too small for
  195. * the generated iframe.
  196. *
  197. * The width is entirely discarded for the actual width of the post, while fixed
  198. * height is used as a starting point before the inevitable resizing.
  199. *
  200. * Since the iframe is automatically resized on load, there are no need for ugly
  201. * and impractical scrollbars.
  202. *
  203. * @param string $src Original remote URL to embed
  204. * @param string $width
  205. * @param string $height
  206. * @return string formatted HTML
  207. *
  208. * @see oembed_format_object()
  209. */
  210. function oembed_iframe($src, $width, $height) {
  211. $a = get_app();
  212. if (!$height || strstr($height,'%')) {
  213. $height = '200';
  214. }
  215. $width = '100%';
  216. $s = App::get_baseurl() . '/oembed/' . base64url_encode($src);
  217. return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
  218. }
  219. function oembed_bbcode2html($text){
  220. $stopoembed = Config::get("system","no_oembed");
  221. if ($stopoembed == true){
  222. return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
  223. }
  224. return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
  225. }
  226. function oe_build_xpath($attr, $value){
  227. // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
  228. 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'";
  229. }
  230. function oe_get_inner_html($node) {
  231. $innerHTML= '';
  232. $children = $node->childNodes;
  233. foreach ($children as $child) {
  234. $innerHTML .= $child->ownerDocument->saveXML($child);
  235. }
  236. return $innerHTML;
  237. }
  238. /**
  239. * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
  240. * and replace it with [embed]url[/embed]
  241. */
  242. function oembed_html2bbcode($text) {
  243. // start parser only if 'oembed' is in text
  244. if (strpos($text, "oembed")) {
  245. // convert non ascii chars to html entities
  246. $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
  247. // If it doesn't parse at all, just return the text.
  248. $dom = @DOMDocument::loadHTML($html_text);
  249. if (! $dom) {
  250. return $text;
  251. }
  252. $xpath = new DOMXPath($dom);
  253. $attr = "oembed";
  254. $xattr = oe_build_xpath("class","oembed");
  255. $entries = $xpath->query("//span[$xattr]");
  256. $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
  257. foreach($entries as $e) {
  258. $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
  259. if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
  260. }
  261. return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
  262. } else {
  263. return $text;
  264. }
  265. }