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