]> git.mxchange.org Git - friendica.git/blob - include/oembed.php
fix @brief in doxygen for function oembed_iframe()
[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                                         ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
80                                         dbesc(normalise_link($embedurl)),
81                                         dbesc($txt), dbesc(datetime_convert()),
82                                         dbesc($txt), dbesc(datetime_convert()));
83
84                         Cache::set($a->videowidth.$embedurl,$txt, CACHE_DAY);
85                 }
86         }
87
88         $j = json_decode($txt);
89
90         if (!is_object($j))
91                 return false;
92
93         // Always embed the SSL version
94         if (isset($j->html))
95                 $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
96                         array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
97
98         $j->embedurl = $embedurl;
99
100         // If fetching information doesn't work, then improve via internal functions
101         if (($j->type == "error") OR ($no_rich_type AND ($j->type == "rich"))) {
102                 require_once("mod/parse_url.php");
103                 $data = parseurl_getsiteinfo_cached($embedurl, true, false);
104                 $j->type = $data["type"];
105
106                 if ($j->type == "photo") {
107                         $j->url = $data["url"];
108                         //$j->width = $data["images"][0]["width"];
109                         //$j->height = $data["images"][0]["height"];
110                 }
111
112                 if (isset($data["title"]))
113                         $j->title = $data["title"];
114
115                 if (isset($data["text"]))
116                         $j->description = $data["text"];
117
118                 if (is_array($data["images"])) {
119                         $j->thumbnail_url = $data["images"][0]["src"];
120                         $j->thumbnail_width = $data["images"][0]["width"];
121                         $j->thumbnail_height = $data["images"][0]["height"];
122                 }
123         }
124
125         call_hooks('oembed_fetch_url', $embedurl, $j);
126
127         return $j;
128 }
129
130 function oembed_format_object($j){
131         require_once("mod/proxy.php");
132
133         $a = get_app();
134         $embedurl = $j->embedurl;
135         $jhtml = oembed_iframe($j->embedurl,(isset($j->width) ? $j->width : null), (isset($j->height) ? $j->height : null) );
136         $ret="<span class='oembed ".$j->type."'>";
137         switch ($j->type) {
138                 case "video": {
139                         if (isset($j->thumbnail_url)) {
140                                 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width:200;
141                                 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height:180;
142                                 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
143                                 $tr = (($th) ? $tw/$th : 1);
144
145                                 $th=120; $tw = $th*$tr;
146                                 $tpl=get_markup_template('oembed_video.tpl');
147                                 $ret.=replace_macros($tpl, array(
148                                 '$baseurl' => $a->get_baseurl(),
149                                         '$embedurl'=>$embedurl,
150                                         '$escapedhtml'=>base64_encode($jhtml),
151                                         '$tw'=>$tw,
152                                         '$th'=>$th,
153                                         '$turl'=>$j->thumbnail_url,
154                                 ));
155
156                         } else {
157                                 $ret=$jhtml;
158                         }
159                         //$ret.="<br>";
160                 }; break;
161                 case "photo": {
162                         $ret.= "<img width='".$j->width."' src='".proxy_url($j->url)."'>";
163                 }; break;
164                 case "link": {
165                 }; break;
166                 case "rich": {
167                         // not so safe..
168                         if (!get_config("system","no_oembed_rich_content"))
169                                 $ret.= proxy_parse_html($jhtml);
170                 }; break;
171         }
172
173         // add link to source if not present in "rich" type
174         if ($j->type!='rich' || !strpos($j->html,$embedurl) ){
175                 $ret .= "<h4>";
176                 if (isset($j->title)) {
177                         if (isset($j->provider_name))
178                                 $ret .= $j->provider_name.": ";
179
180                         $embedlink = (isset($j->title))?$j->title:$embedurl;
181                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
182                         if (isset($j->author_name))
183                                 $ret.=" (".$j->author_name.")";
184                 } elseif (isset($j->provider_name) OR isset($j->author_name)) {
185                         $embedlink = "";
186                         if (isset($j->provider_name))
187                                 $embedlink .= $j->provider_name;
188
189                         if (isset($j->author_name)) {
190                                 if ($embedlink != "")
191                                         $embedlink .= ": ";
192
193                                 $embedlink .= $j->author_name;
194                         }
195                         if (trim($embedlink) == "")
196                                 $embedlink = $embedurl;
197
198                         $ret .= "<a href='$embedurl' rel='oembed'>$embedlink</a>";
199                 }
200                 //if (isset($j->author_name)) $ret.=" by ".$j->author_name;
201                 //if (isset($j->provider_name)) $ret.=" on ".$j->provider_name;
202                 $ret .= "</h4>";
203         } else {
204                 // add <a> for html2bbcode conversion
205                 $ret .= "<a href='$embedurl' rel='oembed'>$embedurl</a>";
206         }
207         $ret.="</span>";
208         $ret = str_replace("\n","",$ret);
209         return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
210 }
211
212 /**
213  * @brief Generates the iframe HTML for an oembed attachment.
214  *
215  * Width and height are given by the remote, and are regularly too small for
216  * the generated iframe.
217  *
218  * The width is entirely discarded for the actual width of the post, while fixed
219  * height is used as a starting point before the inevitable resizing.
220  *
221  * Since the iframe is automatically resized on load, there are no need for ugly
222  * and impractical scrollbars.
223  *
224  * @param string $src Original remote URL to embed
225  * @param string $width
226  * @param string $height
227  * @return string formatted HTML
228  *
229  * @see oembed_format_object()
230  */
231 function oembed_iframe($src, $width, $height) {
232         if (!$height || strstr($height,'%')) {
233                 $height = '200';
234         }
235         $width = '100%';
236
237         $a = get_app();
238         $s = $a->get_baseurl() . '/oembed/'.base64url_encode($src);
239         return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $s . '" scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
240 }
241
242
243
244 function oembed_bbcode2html($text){
245         $stopoembed = get_config("system","no_oembed");
246         if ($stopoembed == true){
247                 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>". t('Embedding disabled') ." : $1</i><!-- /oembed $1 -->" ,$text);
248         }
249         return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", 'oembed_replacecb' ,$text);
250 }
251
252
253 function oe_build_xpath($attr, $value){
254         // http://westhoffswelt.de/blog/0036_xpath_to_select_html_by_class.html
255         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'";
256 }
257
258 function oe_get_inner_html( $node ) {
259     $innerHTML= '';
260     $children = $node->childNodes;
261     foreach ($children as $child) {
262         $innerHTML .= $child->ownerDocument->saveXML( $child );
263     }
264     return $innerHTML;
265 }
266
267 /**
268  * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
269  * and replace it with [embed]url[/embed]
270  */
271 function oembed_html2bbcode($text) {
272         // start parser only if 'oembed' is in text
273         if (strpos($text, "oembed")){
274
275                 // convert non ascii chars to html entities
276                 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
277
278                 // If it doesn't parse at all, just return the text.
279                 $dom = @DOMDocument::loadHTML($html_text);
280                 if(! $dom)
281                         return $text;
282                 $xpath = new DOMXPath($dom);
283                 $attr = "oembed";
284
285                 $xattr = oe_build_xpath("class","oembed");
286                 $entries = $xpath->query("//span[$xattr]");
287
288                 $xattr = "@rel='oembed'";//oe_build_xpath("rel","oembed");
289                 foreach($entries as $e) {
290                         $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
291                         if(!is_null($href)) $e->parentNode->replaceChild(new DOMText("[embed]".$href."[/embed]"), $e);
292                 }
293                 return oe_get_inner_html( $dom->getElementsByTagName("body")->item(0) );
294         } else {
295                 return $text;
296         }
297 }