]> git.mxchange.org Git - friendica.git/blob - include/oembed.php
Opps, this has vanished by accident, thanks to @annando
[friendica.git] / include / oembed.php
1 <?php
2
3 /**
4  * @file include/oembed.php
5  */
6
7 use \Friendica\ParseUrl;
8 use \Friendica\Core\Config;
9
10 function oembed_replacecb($matches){
11         $embedurl=$matches[1];
12         $j = oembed_fetch_url($embedurl);
13         $s =  oembed_format_object($j);
14
15         return $s;
16 }
17
18 /**
19  * @brief Get data from an URL to embed its content.
20  * 
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.
23  * 
24  * @return bool|object Returns object with embed content or false if no embedable
25  *       content exists
26  */
27 function oembed_fetch_url($embedurl, $no_rich_type = false){
28         $embedurl = trim($embedurl, "'");
29         $embedurl = trim($embedurl, '"');
30
31         $a = get_app();
32
33         $r = q("SELECT * FROM `oembed` WHERE `url` = '%s'",
34                 dbesc(normalise_link($embedurl)));
35
36         if (dbm::is_result($r)) {
37                 $txt = $r[0]["content"];
38         } else {
39                 $txt = Cache::get($a->videowidth . $embedurl);
40         }
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
43
44         $noexts = array("mp3","mp4","ogg","ogv","oga","ogm","webm");
45         $ext = pathinfo(strtolower($embedurl),PATHINFO_EXTENSION);
46
47
48         if (is_null($txt)) {
49                 $txt = "";
50
51                 if (!in_array($ext, $noexts)){
52                         // try oembed autodiscovery
53                         $redirects = 0;
54                         $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
55                         if ($html_text) {
56                                 $dom = @DOMDocument::loadHTML($html_text);
57                                 if ($dom) {
58                                         $xpath = new DOMXPath($dom);
59                                         $attr = "oembed";
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);
65                                                 break;
66                                         }
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);
71                                                 break;
72                                         }
73                                 }
74                         }
75                 }
76
77                 if ($txt==false || $txt=="") {
78                         $embedly = Config::get("system", "embedly");
79                         if ($embedly != "") {
80                                 // try embedly service
81                                 $ourl = "https://api.embed.ly/1/oembed?key=".$embedly."&url=".urlencode($embedurl);
82                                 $txt = fetch_url($ourl);
83
84                                 logger("oembed_fetch_url: ".$txt, LOGGER_DEBUG);
85                         }
86                 }
87
88                 $txt=trim($txt);
89
90                 if ($txt[0]!="{") {
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()));
100                         }
101
102                         Cache::set($a->videowidth.$embedurl, $txt, CACHE_DAY);
103                 }
104         }
105
106         $j = json_decode($txt);
107
108         if (!is_object($j)) {
109                 return false;
110         }
111
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);
116         }
117
118         $j->embedurl = $embedurl;
119
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"];
124
125                 if ($j->type == "photo") {
126                         $j->url = $data["url"];
127                         //$j->width = $data["images"][0]["width"];
128                         //$j->height = $data["images"][0]["height"];
129                 }
130
131                 if (isset($data["title"])) {
132                         $j->title = $data["title"];
133                 }
134
135                 if (isset($data["text"])) {
136                         $j->description = $data["text"];
137                 }
138
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"];
143                 }
144         }
145
146         call_hooks('oembed_fetch_url', $embedurl, $j);
147
148         return $j;
149 }
150
151 function oembed_format_object($j){
152         $a = get_app();
153
154         require_once("mod/proxy.php");
155
156         $embedurl = $j->embedurl;
157         $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
158         $ret="<span class='oembed ".$j->type."'>";
159         switch ($j->type) {
160                 case "video":
161                         if (isset($j->thumbnail_url)) {
162                                 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
163                                 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
164                                 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
165                                 $tr = (($th) ? $tw/$th : 1);
166
167                                 $th=120; $tw = $th*$tr;
168                                 $tpl=get_markup_template('oembed_video.tpl');
169                                 $ret.=replace_macros($tpl, array(
170                                         '$baseurl' => $a->get_baseurl(),
171                                         '$embedurl'=>$embedurl,
172                                         '$escapedhtml'=>base64_encode($jhtml),
173                                         '$tw'=>$tw,
174                                         '$th'=>$th,
175                                         '$turl'=>$j->thumbnail_url,
176                                 ));
177
178                         } else {
179                                 $ret=$jhtml;
180                         }
181                         //$ret.="<br>";
182                         break;
183                 case "photo":
184                         $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
185                         break;
186                 case "link":
187                         break;
188                 case "rich":
189                         // not so safe..
190                         if (!Config::get("system","no_oembed_rich_content")) {
191                                 $ret.= proxy_parse_html($jhtml);
192                         }
193                         break;
194         }
195
196         // add link to source if not present in "rich" type
197         if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
198                 $ret .= "<h4>";
199                 if (isset($j->title)) {
200                         if (isset($j->provider_name)) {
201                                 $ret .= $j->provider_name.": ";
202                         }
203
204                         $embedlink = (isset($j->title))?$j->title:$embedurl;
205                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
206                         if (isset($j->author_name)) {
207                                 $ret.=" (".$j->author_name.")";
208                         }
209                 } elseif (isset($j->provider_name) OR isset($j->author_name)) {
210                         $embedlink = "";
211                         if (isset($j->provider_name)) {
212                                 $embedlink .= $j->provider_name;
213                         }
214
215                         if (isset($j->author_name)) {
216                                 if ($embedlink != "") {
217                                         $embedlink .= ": ";
218                                 }
219
220                                 $embedlink .= $j->author_name;
221                         }
222                         if (trim($embedlink) == "") {
223                                 $embedlink = $embedurl;
224                         }
225
226                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
227                 }
228                 //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
229                 //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
230                 $ret .= "</h4>";
231         } else {
232                 // add <a> for html2bbcode conversion
233                 $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
234         }
235         $ret.="</span>";
236         $ret = str_replace("\n","",$ret);
237         return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
238 }
239
240 /**
241  * @brief Generates the iframe HTML for an oembed attachment.
242  *
243  * Width and height are given by the remote, and are regularly too small for
244  * the generated iframe.
245  *
246  * The width is entirely discarded for the actual width of the post, while fixed
247  * height is used as a starting point before the inevitable resizing.
248  *
249  * Since the iframe is automatically resized on load, there are no need for ugly
250  * and impractical scrollbars.
251  *
252  * @param string $src Original remote URL to embed
253  * @param string $width
254  * @param string $height
255  * @return string formatted HTML
256  *
257  * @see oembed_format_object()
258  */
259 function oembed_iframe($src, $width, $height) {
260         $a = get_app();
261
262         if (!$height || strstr($height,'%')) {
263                 $height = '200';
264         }
265         $width = '100%';
266
267         $s = App::get_baseurl() . '/oembed/' . base64url_encode($src);
268         return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
269 }
270
271
272
273 function oembed_bbcode2html($text){
274         $stopoembed = Config::get("system","no_oembed");
275         if ($stopoembed == true){
276                 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
277         }
278         return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
279 }
280
281
282 function oe_build_xpath($attr, $value){
283         // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
284         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 }
286
287 function oe_get_inner_html($node) {
288         $innerHTML= '';
289         $children = $node->childNodes;
290         foreach ($children as $child) {
291                 $innerHTML .= $child->ownerDocument->saveXML($child);
292         }
293         return $innerHTML;
294 }
295
296 /**
297  * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
298  * and replace it with [embed]url[/embed]
299  */
300 function oembed_html2bbcode($text) {
301         // start parser only if 'oembed' is in text
302         if (strpos($text, "oembed")) {
303
304                 // convert non ascii chars to html entities
305                 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
306
307                 // If it doesn't parse at all, just return the text.
308                 $dom = @DOMDocument::loadHTML($html_text);
309                 if (! $dom) {
310                         return $text;
311                 }
312                 $xpath = new DOMXPath($dom);
313                 $attr = "oembed";
314
315                 $xattr = oe_build_xpath("class","oembed");
316                 $entries = $xpath->query("//span[$xattr]");
317
318                 $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
319                 foreach($entries as $e) {
320                         $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
321                         if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
322                 }
323                 return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
324         } else {
325                 return $text;
326         }
327 }