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