4 * @file include/oembed.php
7 use \Friendica\ParseUrl;
8 use \Friendica\Core\Config;
10 function oembed_replacecb($matches){
11 $embedurl=$matches[1];
12 $j = oembed_fetch_url($embedurl);
13 $s = oembed_format_object($j);
19 * @brief Get data from an URL to embed its content.
21 * @param string $embedurl The URL from which the data should be fetched.
22 * @param bool $no_rich_type If set to true rich type content won't be fetched.
24 * @return bool|object Returns object with embed content or false if no embedable
27 function oembed_fetch_url($embedurl, $no_rich_type = false){
28 $embedurl = trim($embedurl, "'");
29 $embedurl = trim($embedurl, '"');
33 $r = q("SELECT * FROM `oembed` WHERE `url` = '%s'",
34 dbesc(normalise_link($embedurl)));
36 if (dbm::is_result($r)) {
37 $txt = $r[0]["content"];
39 $txt = Cache::get($a->videowidth . $embedurl);
41 // These media files should now be caught in bbcode.php
42 // left here as a fallback in case this is called from another source
44 $noexts = array("mp3","mp4","ogg","ogv","oga","ogm","webm");
45 $ext = pathinfo(strtolower($embedurl),PATHINFO_EXTENSION);
51 if (!in_array($ext, $noexts)){
52 // try oembed autodiscovery
54 $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
56 $dom = @DOMDocument::loadHTML($html_text);
58 $xpath = new DOMXPath($dom);
60 $xattr = oe_build_xpath("class","oembed");
61 $entries = $xpath->query("//link[@type='application/json+oembed']");
62 foreach ($entries as $e) {
63 $href = $e->getAttributeNode("href")->nodeValue;
64 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
67 $entries = $xpath->query("//link[@type='text/json+oembed']");
68 foreach ($entries as $e) {
69 $href = $e->getAttributeNode("href")->nodeValue;
70 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
77 if ($txt==false || $txt=="") {
78 $embedly = Config::get("system", "embedly");
80 // try embedly service
81 $ourl = "https://api.embed.ly/1/oembed?key=".$embedly."&url=".urlencode($embedurl);
82 $txt = fetch_url($ourl);
84 logger("oembed_fetch_url: ".$txt, LOGGER_DEBUG);
91 $txt='{"type":"error"}';
92 } else { //save in cache
93 $j = json_decode($txt);
94 if ($j->type != "error") {
95 q("INSERT INTO `oembed` (`url`, `content`, `created`) VALUES ('%s', '%s', '%s')
96 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
97 dbesc(normalise_link($embedurl)),
98 dbesc($txt), dbesc(datetime_convert()),
99 dbesc($txt), dbesc(datetime_convert()));
102 Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
106 $j = json_decode($txt);
108 if (!is_object($j)) {
112 // Always embed the SSL version
113 if (isset($j->html)) {
114 $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
115 array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
118 $j->embedurl = $embedurl;
120 // If fetching information doesn't work, then improve via internal functions
121 if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
122 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
123 $j->type = $data["type"];
125 if ($j->type == "photo") {
126 $j->url = $data["url"];
127 //$j->width = $data["images"][0]["width"];
128 //$j->height = $data["images"][0]["height"];
131 if (isset($data["title"])) {
132 $j->title = $data["title"];
135 if (isset($data["text"])) {
136 $j->description = $data["text"];
139 if (is_array($data["images"])) {
140 $j->thumbnail_url = $data["images"][0]["src"];
141 $j->thumbnail_width = $data["images"][0]["width"];
142 $j->thumbnail_height = $data["images"][0]["height"];
146 call_hooks('oembed_fetch_url', $embedurl, $j);
151 function oembed_format_object($j){
152 require_once("mod/proxy.php");
154 $embedurl = $j->embedurl;
155 $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
156 $ret="<span class='oembed ".$j->type."'>";
159 if (isset($j->thumbnail_url)) {
160 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
161 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
162 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
163 $tr = (($th) ? $tw/$th : 1);
165 $th=120; $tw = $th*$tr;
166 $tpl=get_markup_template('oembed_video.tpl');
167 $ret.=replace_macros($tpl, array(
168 '$baseurl' => App::get_baseurl(),
169 '$embedurl' => $embedurl,
170 '$escapedhtml' => base64_encode($jhtml),
173 '$turl' => $j->thumbnail_url,
182 $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
188 if (!Config::get("system","no_oembed_rich_content")) {
189 $ret.= proxy_parse_html($jhtml);
194 // add link to source if not present in "rich" type
195 if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
197 if (isset($j->title)) {
198 if (isset($j->provider_name)) {
199 $ret .= $j->provider_name.": ";
202 $embedlink = (isset($j->title))?$j->title:$embedurl;
203 $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
204 if (isset($j->author_name)) {
205 $ret.=" (".$j->author_name.")";
207 } elseif (isset($j->provider_name) OR isset($j->author_name)) {
209 if (isset($j->provider_name)) {
210 $embedlink .= $j->provider_name;
213 if (isset($j->author_name)) {
214 if ($embedlink != "") {
218 $embedlink .= $j->author_name;
220 if (trim($embedlink) == "") {
221 $embedlink = $embedurl;
224 $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
226 //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
227 //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
230 // add <a> for html2bbcode conversion
231 $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
234 $ret = str_replace("\n","",$ret);
235 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
239 * @brief Generates the iframe HTML for an oembed attachment.
241 * Width and height are given by the remote, and are regularly too small for
242 * the generated iframe.
244 * The width is entirely discarded for the actual width of the post, while fixed
245 * height is used as a starting point before the inevitable resizing.
247 * Since the iframe is automatically resized on load, there are no need for ugly
248 * and impractical scrollbars.
250 * @param string $src Original remote URL to embed
251 * @param string $width
252 * @param string $height
253 * @return string formatted HTML
255 * @see oembed_format_object()
257 function oembed_iframe($src, $width, $height) {
260 if (!$height || strstr($height,'%')) {
265 $s = App::get_baseurl() . '/oembed/' . base64url_encode($src);
266 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
271 function oembed_bbcode2html($text){
272 $stopoembed = Config::get("system","no_oembed");
273 if ($stopoembed == true){
274 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
276 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
280 function oe_build_xpath($attr, $value){
281 // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
282 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'";
285 function oe_get_inner_html($node) {
287 $children = $node->childNodes;
288 foreach ($children as $child) {
289 $innerHTML .= $child->ownerDocument->saveXML($child);
295 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
296 * and replace it with [embed]url[/embed]
298 function oembed_html2bbcode($text) {
299 // start parser only if 'oembed' is in text
300 if (strpos($text, "oembed")) {
302 // convert non ascii chars to html entities
303 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
305 // If it doesn't parse at all, just return the text.
306 $dom = @DOMDocument::loadHTML($html_text);
310 $xpath = new DOMXPath($dom);
313 $xattr = oe_build_xpath("class","oembed");
314 $entries = $xpath->query("//span[$xattr]");
316 $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
317 foreach($entries as $e) {
318 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
319 if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
321 return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );