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