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