]> git.mxchange.org Git - friendica.git/blob - include/oembed.php
Merge pull request #932 from annando/master
[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){
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         $j->embedurl = $embedurl;
82         return $j;
83 }
84
85 function oembed_format_object($j){
86         $a = get_app();
87         $embedurl = $j->embedurl;
88         $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
89         $ret="<span class='oembed ".$j->type."'>";
90         switch ($j->type) {
91                 case "video": {
92                         if (isset($j->thumbnail_url)) {
93                                 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
94                                 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
95                                 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
96                                 $tr = (($th) ? $tw/$th : 1);
97
98                                 $th=120; $tw = $th*$tr;
99                                 $tpl=get_markup_template('oembed_video.tpl');
100                                 $ret.=replace_macros($tpl, array(
101                                 '$baseurl' => $a->get_baseurl(),
102                                         '$embedurl'=>$embedurl,
103                                         '$escapedhtml'=>base64_encode($jhtml),
104                                         '$tw'=>$tw,
105                                         '$th'=>$th,
106                                         '$turl'=>$j->thumbnail_url,
107                                 ));
108
109                         } else {
110                                 $ret=$jhtml;
111                         }
112                         $ret.="<br>";
113                 }; break;
114                 case "photo": {
115                         $ret.= "<img width='".$j->width."' src='".$j->url."'>";
116                         //$ret.= "<img width='".$j->width."' height='".$j->height."' src='".$j->url."'>";
117                         $ret.="<br>";
118                 }; break;
119                 case "link": {
120                         //$ret = "<a href='".$embedurl."'>".$j->title."</a>";
121                 }; break;
122                 case "rich": {
123                         // not so safe..
124                         if (!get_config("system","no_oembed_rich_content"))
125                                 $ret.= $jhtml;
126                 }; break;
127         }
128
129         // add link to source if not present in "rich" type
130         if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
131                 if (isset($j->title)) {
132                         if (isset($j->provider_name))
133                                 $ret .= $j->provider_name.": ";
134
135                         $embedlink = (isset($j->title))?$j->title:$embedurl;
136                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
137                         if (isset($j->author_name))
138                                 $ret.=" (".$j->author_name.")";
139                 } elseif (isset($j->provider_name) OR isset($j->author_name)) {
140                         $embedlink = "";
141                         if (isset($j->provider_name))
142                                 $embedlink .= $j->provider_name;
143
144                         if (isset($j->author_name)) {
145                                 if ($embedlink != "")
146                                         $embedlink .= ": ";
147
148                                 $embedlink .= $j->author_name;
149                         }
150                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
151                 }
152                 //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
153                 //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
154         } else {
155                 // add <a> for html2bbcode conversion
156                 $ret .= "<a href='$embedurl' rel='oembed'></a>";
157         }
158         $ret.="<br style='clear:left'></span>";
159         return  mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
160 }
161
162 function oembed_iframe($src,$width,$height) {
163         if(! $width || strstr($width,'%'))
164                 $width = '640';
165         if(! $height || strstr($height,'%'))
166                 $height = '300';
167         // try and leave some room for the description line.
168         $height = intval($height) + 80;
169         $width  = intval($width) + 40;
170
171         $a = get_app();
172
173         $s = $a->get_baseurl()."/oembed/".base64url_encode($src);
174         return '<iframe height="' . $height . '" width="' . $width . '" src="' . $s . '" frameborder="no" >' . t('Embedded content') . '</iframe>';
175
176 }
177
178
179
180 function oembed_bbcode2html($text){
181         $stopoembed = get_config("system","no_oembed");
182         if ($stopoembed == true){
183                 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
184         }
185         return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
186 }
187
188
189 function oe_build_xpath($attr, $value){
190         // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
191         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'";
192 }
193
194 function oe_get_inner_html( $node ) {
195     $innerHTML= '';
196     $children = $node->childNodes;
197     foreach ($children as $child) {
198         $innerHTML .= $child->ownerDocument->saveXML( $child );
199     }
200     return $innerHTML;
201 }
202
203 /**
204  * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
205  * and replace it with [embed]url[/embed]
206  */
207 function oembed_html2bbcode($text) {
208         // start parser only if 'oembed' is in text
209         if (strpos($text, "oembed")){
210
211                 // convert non ascii chars to html entities
212                 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
213
214                 // If it doesn't parse at all, just return the text.
215                 $dom = @DOMDocument::loadHTML($html_text);
216                 if(! $dom)
217                         return $text;
218                 $xpath = new DOMXPath($dom);
219                 $attr = "oembed";
220
221                 $xattr = oe_build_xpath("class","oembed");
222                 $entries = $xpath->query("//span[$xattr]");
223
224                 $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
225                 foreach($entries as $e) {
226                         $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
227                         if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
228                 }
229                 return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
230         } else {
231                 return $text;
232         }
233 }