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