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