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