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