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