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