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