]> git.mxchange.org Git - friendica.git/blob - include/oembed.php
Merge acl-var into develop
[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                                         $xattr = oe_build_xpath("class","oembed");
41                                         $entries = $xpath->query("//link[@type='application/json+oembed']");
42                                         foreach($entries as $e){
43                                                 $href = $e->getAttributeNode("href")->nodeValue;
44                                                 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
45                                                 break;
46                                         }
47                                         $entries = $xpath->query("//link[@type='text/json+oembed']");
48                                         foreach($entries as $e){
49                                                 $href = $e->getAttributeNode("href")->nodeValue;
50                                                 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
51                                                 break;
52                                         }
53                                 }
54                         }
55                 }
56
57                 if ($txt==false || $txt==""){
58                         $embedly = get_config("system", "embedly");
59                         if ($embedly == "") {
60                                 // try oohembed service
61                                 $ourl = "http://oohembed.com/oohembed/?url=".urlencode($embedurl).'&maxwidth=' . $a->videowidth;
62                                 $txt = fetch_url($ourl);
63                         } else {
64                                 // try embedly service
65                                 $ourl = "https://api.embed.ly/1/oembed?key=".$embedly."&url=".urlencode($embedurl);
66                                 $txt = fetch_url($ourl);
67                         }
68
69                         logger("oembed_fetch_url: ".$txt, LOGGER_DEBUG);
70                 }
71
72                 $txt=trim($txt);
73                 if ($txt[0]!="{") $txt='{"type":"error"}';
74
75                 //save in cache
76                 Cache::set($a->videowidth . $embedurl,$txt);
77
78         }
79
80         $j = json_decode($txt);
81
82         if (!is_object($j))
83                 return false;
84
85         // Always embed the SSL version
86         if (isset($j->html))
87                 $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
88                         array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
89
90         $j->embedurl = $embedurl;
91
92         // If fetching information doesn't work, then improve via internal functions
93         if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
94                 require_once("mod/parse_url.php");
95                 $data = parseurl_getsiteinfo($embedurl, true, false);
96                 $j->type = $data["type"];
97
98                 if ($j->type == "photo") {
99                         $j->url = $data["url"];
100                         //$j->width = $data["images"][0]["width"];
101                         //$j->height = $data["images"][0]["height"];
102                 }
103
104                 if (isset($data["title"]))
105                         $j->title = $data["title"];
106
107                 if (isset($data["text"]))
108                         $j->description = $data["text"];
109
110                 if (is_array($data["images"])) {
111                         $j->thumbnail_url = $data["images"][0]["src"];
112                         $j->thumbnail_width = $data["images"][0]["width"];
113                         $j->thumbnail_height = $data["images"][0]["height"];
114                 }
115         }
116
117         call_hooks('oembed_fetch_url', $embedurl, $j);
118
119         return $j;
120 }
121
122 function oembed_format_object($j){
123         require_once("mod/proxy.php");
124
125         $a = get_app();
126         $embedurl = $j->embedurl;
127         $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
128         $ret="<span class='oembed ".$j->type."'>";
129         switch ($j->type) {
130                 case "video": {
131                         if (isset($j->thumbnail_url)) {
132                                 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
133                                 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
134                                 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
135                                 $tr = (($th) ? $tw/$th : 1);
136
137                                 $th=120; $tw = $th*$tr;
138                                 $tpl=get_markup_template('oembed_video.tpl');
139                                 $ret.=replace_macros($tpl, array(
140                                 '$baseurl' => $a->get_baseurl(),
141                                         '$embedurl'=>$embedurl,
142                                         '$escapedhtml'=>base64_encode($jhtml),
143                                         '$tw'=>$tw,
144                                         '$th'=>$th,
145                                         '$turl'=>$j->thumbnail_url,
146                                 ));
147
148                         } else {
149                                 $ret=$jhtml;
150                         }
151                         $ret.="<br>";
152                 }; break;
153                 case "photo": {
154                         $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
155                         //$ret.= "<img width='".$j->width."' height='".$j->height."' src='".proxy_url($j->url)."'>";
156                         $ret.="<br>";
157                 }; break;
158                 case "link": {
159                         //$ret = "<a href='".$embedurl."'>".$j->title."</a>";
160                 }; break;
161                 case "rich": {
162                         // not so safe..
163                         if (!get_config("system","no_oembed_rich_content"))
164                                 $ret.= $jhtml;
165                 }; break;
166         }
167
168         // add link to source if not present in "rich" type
169         if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
170                 $ret .= "<h4>";
171                 if (isset($j->title)) {
172                         if (isset($j->provider_name))
173                                 $ret .= $j->provider_name.": ";
174
175                         $embedlink = (isset($j->title))?$j->title:$embedurl;
176                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
177                         if (isset($j->author_name))
178                                 $ret.=" (".$j->author_name.")";
179                 } elseif (isset($j->provider_name) OR isset($j->author_name)) {
180                         $embedlink = "";
181                         if (isset($j->provider_name))
182                                 $embedlink .= $j->provider_name;
183
184                         if (isset($j->author_name)) {
185                                 if ($embedlink != "")
186                                         $embedlink .= ": ";
187
188                                 $embedlink .= $j->author_name;
189                         }
190                         if (trim($embedlink) == "")
191                                 $embedlink = $embedurl;
192
193                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
194                 }
195                 //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
196                 //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
197                 $ret .= "</h4>";
198         } else {
199                 // add <a> for html2bbcode conversion
200                 $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
201                 $ret .= "<br style='clear:left'>";
202         }
203         $ret.="</span>";
204         return  mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
205 }
206
207 function oembed_iframe($src,$width,$height) {
208
209         if(! $width || strstr($width,'%'))
210                 $width = '640';
211         if(! $height || strstr($height,'%')) {
212                 $height = '300';
213                 $resize = 'onload="resizeIframe(this);"';
214         } else
215                 $resize = '';
216
217         // try and leave some room for the description line.
218         $height = intval($height) + 80;
219         $width  = intval($width) + 40;
220
221         $a = get_app();
222
223         $s = $a->get_baseurl()."/oembed/".base64url_encode($src);
224         return '<iframe '.$resize.' class="embed_rich" height="'.$height.'" width="'.$width.'" src="'.$s.'" frameborder="no">'.t('Embedded content').'</iframe>';
225
226 }
227
228
229
230 function oembed_bbcode2html($text){
231         $stopoembed = get_config("system","no_oembed");
232         if ($stopoembed == true){
233                 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
234         }
235         return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
236 }
237
238
239 function oe_build_xpath($attr, $value){
240         // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
241         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'";
242 }
243
244 function oe_get_inner_html( $node ) {
245     $innerHTML= '';
246     $children = $node->childNodes;
247     foreach ($children as $child) {
248         $innerHTML .= $child->ownerDocument->saveXML( $child );
249     }
250     return $innerHTML;
251 }
252
253 /**
254  * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
255  * and replace it with [embed]url[/embed]
256  */
257 function oembed_html2bbcode($text) {
258         // start parser only if 'oembed' is in text
259         if (strpos($text, "oembed")){
260
261                 // convert non ascii chars to html entities
262                 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
263
264                 // If it doesn't parse at all, just return the text.
265                 $dom = @DOMDocument::loadHTML($html_text);
266                 if(! $dom)
267                         return $text;
268                 $xpath = new DOMXPath($dom);
269                 $attr = "oembed";
270
271                 $xattr = oe_build_xpath("class","oembed");
272                 $entries = $xpath->query("//span[$xattr]");
273
274                 $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
275                 foreach($entries as $e) {
276                         $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
277                         if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
278                 }
279                 return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
280         } else {
281                 return $text;
282         }
283 }