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