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