]> git.mxchange.org Git - friendica.git/blob - src/Content/OEmbed.php
3ab5b4fea863a1a01a293ed16164ab0760b78d5f
[friendica.git] / src / Content / OEmbed.php
1 <?php
2
3 /**
4  * @file src/Content/OEmbed.php
5  */
6
7 namespace Friendica\Content;
8
9 use Friendica\Core\Cache;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Database\DBM;
13 use Friendica\Util\ParseUrl;
14 use dba;
15 use DOMDocument;
16 use DOMXPath;
17 use DOMNode;
18 use Exception;
19
20 require_once 'include/dba.php';
21 require_once 'mod/proxy.php';
22
23 /**
24  * Handles all OEmbed content fetching and replacement
25  *
26  * OEmbed is a standard used to allow an embedded representation of a URL on
27  * third party sites
28  *
29  * @see https://oembed.com
30  *
31  * @author Hypolite Petovan <mrpetovan@gmail.com>
32  */
33 class OEmbed
34 {
35         public static function replaceCallback($matches)
36         {
37                 $embedurl = $matches[1];
38                 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
39                 $s = self::formatObject($j);
40
41                 return $s;
42         }
43
44         /**
45          * @brief Get data from an URL to embed its content.
46          *
47          * @param string $embedurl The URL from which the data should be fetched.
48          * @param bool $no_rich_type If set to true rich type content won't be fetched.
49          *
50          * @return bool|object Returns object with embed content or false if no embeddable
51          *                         content exists
52          */
53         public static function fetchURL($embedurl, $no_rich_type = false)
54         {
55                 $embedurl = trim($embedurl, "'");
56                 $embedurl = trim($embedurl, '"');
57
58                 $a = get_app();
59
60                 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
61                 $oembed = dba::selectFirst('oembed', ['content'], $condition);
62                 if (DBM::is_result($oembed)) {
63                         $txt = $oembed["content"];
64                 } else {
65                         $txt = Cache::get($a->videowidth . $embedurl);
66                 }
67                 // These media files should now be caught in bbcode.php
68                 // left here as a fallback in case this is called from another source
69
70                 $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
71                 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
72
73
74                 if (is_null($txt)) {
75                         $txt = "";
76
77                         if (!in_array($ext, $noexts)) {
78                                 // try oembed autodiscovery
79                                 $redirects = 0;
80                                 $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
81                                 if ($html_text) {
82                                         $dom = @DOMDocument::loadHTML($html_text);
83                                         if ($dom) {
84                                                 $xpath = new DOMXPath($dom);
85                                                 $entries = $xpath->query("//link[@type='application/json+oembed']");
86                                                 foreach ($entries as $e) {
87                                                         $href = $e->getAttributeNode("href")->nodeValue;
88                                                         $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
89                                                         break;
90                                                 }
91                                                 $entries = $xpath->query("//link[@type='text/json+oembed']");
92                                                 foreach ($entries as $e) {
93                                                         $href = $e->getAttributeNode("href")->nodeValue;
94                                                         $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
95                                                         break;
96                                                 }
97                                         }
98                                 }
99                         }
100
101                         $txt = trim($txt);
102
103                         if (!$txt || $txt[0] != "{") {
104                                 $txt = '{"type":"error"}';
105                         } else { //save in cache
106                                 $j = json_decode($txt);
107                                 if ($j->type != "error") {
108                                         dba::insert('oembed', [
109                                                 'url' => normalise_link($embedurl),
110                                                 'maxwidth' => $a->videowidth,
111                                                 'content' => $txt,
112                                                 'created' => datetime_convert()
113                                         ], true);
114                                 }
115
116                                 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
117                         }
118                 }
119
120                 $j = json_decode($txt);
121
122                 if (!is_object($j)) {
123                         return false;
124                 }
125
126                 // Always embed the SSL version
127                 if (isset($j->html)) {
128                         $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
129                 }
130
131                 $j->embedurl = $embedurl;
132
133                 // If fetching information doesn't work, then improve via internal functions
134                 if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
135                         $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
136                         $j->type = $data["type"];
137
138                         if ($j->type == "photo") {
139                                 $j->url = $data["url"];
140                                 //$j->width = $data["images"][0]["width"];
141                                 //$j->height = $data["images"][0]["height"];
142                         }
143
144                         if (isset($data["title"])) {
145                                 $j->title = $data["title"];
146                         }
147
148                         if (isset($data["text"])) {
149                                 $j->description = $data["text"];
150                         }
151
152                         if (is_array($data["images"])) {
153                                 $j->thumbnail_url = $data["images"][0]["src"];
154                                 $j->thumbnail_width = $data["images"][0]["width"];
155                                 $j->thumbnail_height = $data["images"][0]["height"];
156                         }
157                 }
158
159                 call_hooks('oembed_fetch_url', $embedurl, $j);
160
161                 return $j;
162         }
163
164         private static function formatObject($j)
165         {
166                 $embedurl = $j->embedurl;
167                 $jhtml = $j->html;
168                 $ret = '<div class="oembed ' . $j->type . '">';
169                 switch ($j->type) {
170                         case "video":
171                                 if (isset($j->thumbnail_url)) {
172                                         $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
173                                         $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;
174                                         // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
175                                         $tr = (($th) ? $tw / $th : 1);
176
177                                         $th = 120;
178                                         $tw = $th * $tr;
179                                         $tpl = get_markup_template('oembed_video.tpl');
180                                         $ret .= replace_macros($tpl, array(
181                                                 '$baseurl' => System::baseUrl(),
182                                                 '$embedurl' => $embedurl,
183                                                 '$escapedhtml' => base64_encode($jhtml),
184                                                 '$tw' => $tw,
185                                                 '$th' => $th,
186                                                 '$turl' => $j->thumbnail_url,
187                                         ));
188                                 } else {
189                                         $ret = $jhtml;
190                                 }
191                                 break;
192                         case "photo":
193                                 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
194                                 break;
195                         case "link":
196                                 break;
197                         case "rich":
198                                 $ret .= proxy_parse_html($jhtml);
199                                 break;
200                 }
201
202                 // add link to source if not present in "rich" type
203                 if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
204                         $ret .= '<h4>';
205                         if (isset($j->title)) {
206                                 if (isset($j->provider_name)) {
207                                         $ret .= $j->provider_name . ": ";
208                                 }
209
210                                 $embedlink = (isset($j->title)) ? $j->title : $embedurl;
211                                 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
212                                 if (isset($j->author_name)) {
213                                         $ret .= ' (' . $j->author_name . ')';
214                                 }
215                         } elseif (isset($j->provider_name) || isset($j->author_name)) {
216                                 $embedlink = "";
217                                 if (isset($j->provider_name)) {
218                                         $embedlink .= $j->provider_name;
219                                 }
220
221                                 if (isset($j->author_name)) {
222                                         if ($embedlink != "") {
223                                                 $embedlink .= ": ";
224                                         }
225
226                                         $embedlink .= $j->author_name;
227                                 }
228                                 if (trim($embedlink) == "") {
229                                         $embedlink = $embedurl;
230                                 }
231
232                                 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
233                         }
234                         $ret .= "</h4>";
235                 } elseif (!strpos($j->html, $embedurl)) {
236                         // add <a> for html2bbcode conversion
237                         $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
238                 }
239
240                 $ret .= '</div>';
241
242                 $ret = str_replace("\n", "", $ret);
243                 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
244         }
245
246         public static function BBCode2HTML($text)
247         {
248                 $stopoembed = Config::get("system", "no_oembed");
249                 if ($stopoembed == true) {
250                         return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
251                 }
252                 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
253         }
254
255         /**
256          * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
257          * and replace it with [embed]url[/embed]
258          */
259         public static function HTML2BBCode($text)
260         {
261                 // start parser only if 'oembed' is in text
262                 if (strpos($text, "oembed")) {
263
264                         // convert non ascii chars to html entities
265                         $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
266
267                         // If it doesn't parse at all, just return the text.
268                         $dom = @DOMDocument::loadHTML($html_text);
269                         if (!$dom) {
270                                 return $text;
271                         }
272                         $xpath = new DOMXPath($dom);
273
274                         $xattr = self::buildXPath("class", "oembed");
275                         $entries = $xpath->query("//div[$xattr]");
276
277                         $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
278                         foreach ($entries as $e) {
279                                 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
280                                 if (!is_null($href)) {
281                                         $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
282                                 }
283                         }
284                         return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
285                 } else {
286                         return $text;
287                 }
288         }
289
290         /**
291          * Determines if rich content OEmbed is allowed for the provided URL
292          *
293          * @brief Determines if rich content OEmbed is allowed for the provided URL
294          * @param string $url
295          * @return boolean
296          */
297         public static function isAllowedURL($url)
298         {
299                 if (!Config::get('system', 'no_oembed_rich_content')) {
300                         return true;
301                 }
302
303                 $domain = parse_url($url, PHP_URL_HOST);
304                 if (!x($domain)) {
305                         return false;
306                 }
307
308                 $str_allowed = Config::get('system', 'allowed_oembed', '');
309                 if (!x($str_allowed)) {
310                         return false;
311                 }
312
313                 $allowed = explode(',', $str_allowed);
314
315                 return allowed_domain($domain, $allowed);
316         }
317
318         public static function getHTML($url, $title = null)
319         {
320                 // Always embed the SSL version
321                 $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
322                                         array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
323
324                 $o = self::fetchURL($url, !self::isAllowedURL($url));
325
326                 if (!is_object($o) || $o->type == 'error') {
327                         throw new Exception('OEmbed failed for URL: ' . $url);
328                 }
329
330                 if (x($title)) {
331                         $o->title = $title;
332                 }
333
334                 $html = self::formatObject($o);
335
336                 return $html;
337         }
338
339         /**
340          * @brief Generates the iframe HTML for an oembed attachment.
341          *
342          * Width and height are given by the remote, and are regularly too small for
343          * the generated iframe.
344          *
345          * The width is entirely discarded for the actual width of the post, while fixed
346          * height is used as a starting point before the inevitable resizing.
347          *
348          * Since the iframe is automatically resized on load, there are no need for ugly
349          * and impractical scrollbars.
350          *
351          * @todo This function is currently unused until someoneā„¢ adds support for a separate OEmbed domain
352          *
353          * @param string $src Original remote URL to embed
354          * @param string $width
355          * @param string $height
356          * @return string formatted HTML
357          *
358          * @see oembed_format_object()
359          */
360         private static function iframe($src, $width, $height)
361         {
362                 $a = get_app();
363
364                 if (!$height || strstr($height, '%')) {
365                         $height = '200';
366                 }
367                 $width = '100%';
368
369                 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
370                 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
371         }
372
373         /**
374          * Generates an XPath query to select elements whose provided attribute contains
375          * the provided value in a space-separated list.
376          *
377          * @brief Generates attribute search XPath string
378          *
379          * @param string $attr Name of the attribute to seach
380          * @param string $value Value to search in a space-separated list
381          * @return string
382          */
383         private static function buildXPath($attr, $value)
384         {
385                 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
386                 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'";
387         }
388
389         /**
390          * Returns the inner XML string of a provided DOMNode
391          *
392          * @brief Returns the inner XML string of a provided DOMNode
393          *
394          * @param DOMNode $node
395          * @return string
396          */
397         private static function getInnerHTML(DOMNode $node)
398         {
399                 $innerHTML = '';
400                 $children = $node->childNodes;
401                 foreach ($children as $child) {
402                         $innerHTML .= $child->ownerDocument->saveXML($child);
403                 }
404                 return $innerHTML;
405         }
406
407 }