3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Content;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Renderer;
32 use Friendica\Database\Database;
33 use Friendica\Database\DBA;
35 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Network;
38 use Friendica\Util\ParseUrl;
39 use Friendica\Util\Proxy;
40 use Friendica\Util\Strings;
43 * Handles all OEmbed content fetching and replacement
45 * OEmbed is a standard used to allow an embedded representation of a URL on
48 * @see https://oembed.com
53 * Callback for fetching URL, checking allowance and returning formatted HTML
55 * @param array $matches
56 * @return string Formatted HTML
58 public static function replaceCallback(array $matches): string
60 $embedurl = $matches[1];
61 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
62 $s = self::formatObject($j);
68 * Get data from an URL to embed its content.
70 * @param string $embedurl The URL from which the data should be fetched.
71 * @param bool $no_rich_type If set to true rich type content won't be fetched.
72 * @param bool $use_parseurl Use the "ParseUrl" functionality to add additional data
74 * @return \Friendica\Object\OEmbed
75 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
77 public static function fetchURL(string $embedurl, bool $no_rich_type = false, bool $use_parseurl = true): \Friendica\Object\OEmbed
79 $embedurl = trim($embedurl, '\'"');
83 $cache_key = 'oembed:' . $a->getThemeInfoValue('videowidth') . ':' . $embedurl;
85 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->getThemeInfoValue('videowidth')];
86 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
87 if (DBA::isResult($oembed_record)) {
88 $json_string = $oembed_record['content'];
90 $json_string = DI::cache()->get($cache_key);
93 // These media files should now be caught in bbcode.php
94 // left here as a fallback in case this is called from another source
95 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
96 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
98 $oembed = new \Friendica\Object\OEmbed($embedurl);
101 $oembed->parseJSON($json_string);
105 if (!in_array($ext, $noexts)) {
106 // try oembed autodiscovery
107 $html_text = DI::httpClient()->fetch($embedurl, HttpClientAccept::HTML, 15);
108 if (!empty($html_text)) {
109 $dom = new DOMDocument();
110 if (@$dom->loadHTML($html_text)) {
111 $xpath = new DOMXPath($dom);
113 $xpath->query("//link[@type='application/json+oembed'] | //link[@type='text/json+oembed']")
116 $href = $link->getAttributeNode('href')->nodeValue;
117 // Both Youtube and Vimeo output OEmbed endpoint URL with HTTP
118 // but their OEmbed endpoint is only accessible by HTTPS ¯\_(ツ)_/¯
119 $href = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'],
120 ['https://www.youtube.com/', 'https://player.vimeo.com/'], $href);
121 $result = DI::httpClient()->fetchFull($href . '&maxwidth=' . $a->getThemeInfoValue('videowidth'));
122 if ($result->getReturnCode() === 200) {
123 $json_string = $result->getBody();
131 $json_string = trim($json_string);
133 if (!$json_string || $json_string[0] != '{') {
134 $json_string = '{"type":"error"}';
137 $oembed->parseJSON($json_string);
139 if (!empty($oembed->type) && $oembed->type != 'error') {
140 DBA::insert('oembed', [
141 'url' => Strings::normaliseLink($embedurl),
142 'maxwidth' => $a->getThemeInfoValue('videowidth'),
143 'content' => $json_string,
144 'created' => DateTimeFormat::utcNow()
145 ], Database::INSERT_UPDATE);
146 $cache_ttl = Duration::DAY;
148 $cache_ttl = Duration::FIVE_MINUTES;
151 DI::cache()->set($cache_key, $json_string, $cache_ttl);
154 // Always embed the SSL version
155 if (!empty($oembed->html)) {
156 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
159 // Improve the OEmbed data with data from OpenGraph, Twitter cards and other sources
161 $data = ParseUrl::getSiteinfoCached($embedurl, false);
163 if (($oembed->type == 'error') && empty($data['title']) && empty($data['text'])) {
167 if ($no_rich_type || ($oembed->type == 'error')) {
169 $oembed->type = $data['type'];
171 if ($oembed->type == 'photo') {
172 if (!empty($data['images'])) {
173 $oembed->url = $data['images'][0]['src'];
174 $oembed->width = $data['images'][0]['width'];
175 $oembed->height = $data['images'][0]['height'];
177 $oembed->type = 'link';
182 if (!empty($data['title'])) {
183 $oembed->title = $data['title'];
186 if (!empty($data['text'])) {
187 $oembed->description = $data['text'];
190 if (!empty($data['publisher_name'])) {
191 $oembed->provider_name = $data['publisher_name'];
194 if (!empty($data['publisher_url'])) {
195 $oembed->provider_url = $data['publisher_url'];
198 if (!empty($data['author_name'])) {
199 $oembed->author_name = $data['author_name'];
202 if (!empty($data['author_url'])) {
203 $oembed->author_url = $data['author_url'];
206 if (!empty($data['images']) && ($oembed->type != 'photo')) {
207 $oembed->thumbnail_url = $data['images'][0]['src'];
208 $oembed->thumbnail_width = $data['images'][0]['width'];
209 $oembed->thumbnail_height = $data['images'][0]['height'];
213 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
219 * Returns a formatted string from OEmbed object
221 * @param \Friendica\Object\OEmbed $oembed
224 private static function formatObject(\Friendica\Object\OEmbed $oembed): string
226 $ret = '<div class="oembed ' . $oembed->type . '">';
228 switch ($oembed->type) {
230 if ($oembed->thumbnail_url) {
231 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
232 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
233 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
234 $tr = (($th) ? $tw / $th : 1);
238 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
239 $ret .= Renderer::replaceMacros($tpl, [
240 '$embedurl' => $oembed->embed_url,
241 '$escapedhtml' => base64_encode($oembed->html),
244 '$turl' => $oembed->thumbnail_url,
247 $ret = $oembed->html;
252 $ret .= '<img width="' . $oembed->width . '" src="' . Proxy::proxifyUrl($oembed->url) . '">';
259 $ret .= Proxy::proxifyHtml($oembed->html);
263 // add link to source if not present in "rich" type
264 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
266 if (!empty($oembed->title)) {
267 if (!empty($oembed->provider_name)) {
268 $ret .= $oembed->provider_name . ": ";
271 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
272 if (!empty($oembed->author_name)) {
273 $ret .= ' (' . $oembed->author_name . ')';
275 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
277 if (!empty($oembed->provider_name)) {
278 $embedlink .= $oembed->provider_name;
281 if (!empty($oembed->author_name)) {
282 if ($embedlink != "") {
286 $embedlink .= $oembed->author_name;
288 if (trim($embedlink) == "") {
289 $embedlink = $oembed->embed_url;
292 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
294 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
297 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
298 // add <a> for html2bbcode conversion
299 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
304 return str_replace("\n", "", $ret);
308 * Converts BBCode to HTML code
310 * @param string $text
313 public static function BBCode2HTML(string $text): string
315 $stopoembed = DI::config()->get('system', 'no_oembed');
316 if ($stopoembed == true) {
317 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
319 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", [self::class, 'replaceCallback'], $text);
323 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
324 * and replace it with [embed]url[/embed]
326 * @param string $text
329 public static function HTML2BBCode(string $text): string
331 // start parser only if 'oembed' is in text
332 if (strpos($text, 'oembed')) {
333 // convert non ascii chars to html entities
334 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
336 // If it doesn't parse at all, just return the text.
337 $dom = @DOMDocument::loadHTML($html_text);
341 $xpath = new DOMXPath($dom);
343 $xattr = self::buildXPath('class', 'oembed');
344 $entries = $xpath->query("//div[$xattr]");
346 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
347 foreach ($entries as $e) {
348 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
349 if (!is_null($href)) {
350 $e->parentNode->replaceChild(new DOMText('[embed]' . $href . '[/embed]'), $e);
353 return self::getInnerHTML($dom->getElementsByTagName('body')->item(0));
360 * Determines if rich content OEmbed is allowed for the provided URL
364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
366 public static function isAllowedURL(string $url): bool
368 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
372 $domain = parse_url($url, PHP_URL_HOST);
373 if (empty($domain)) {
377 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
378 if (empty($str_allowed)) {
382 $allowed = explode(',', $str_allowed);
384 return Network::isDomainAllowed($domain, $allowed);
388 * Returns a formatted HTML code from given URL and sets optional title
390 * @param string $url URL to fetch
391 * @param string $title Optional title (default: what comes from OEmbed object)
392 * @return string Formatted HTML
394 public static function getHTML(string $url, string $title = ''): string
396 $o = self::fetchURL($url, !self::isAllowedURL($url));
398 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
399 throw new Exception('OEmbed failed for URL: ' . $url);
402 if (!empty($title)) {
406 $html = self::formatObject($o);
412 * Generates the iframe HTML for an oembed attachment.
414 * Width and height are given by the remote, and are regularly too small for
415 * the generated iframe.
417 * The width is entirely discarded for the actual width of the post, while fixed
418 * height is used as a starting point before the inevitable resizing.
420 * Since the iframe is automatically resized on load, there are no need for ugly
421 * and impractical scrollbars.
423 * @todo This function is currently unused until someone™ adds support for a separate OEmbed domain
425 * @param string $src Original remote URL to embed
426 * @param string $width
427 * @param string $height
428 * @return string Formatted HTML
430 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
431 * @see oembed_format_object()
433 private static function iframe(string $src, string $width, string $height): string
435 if (!$height || strstr($height, '%')) {
440 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
441 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>';
445 * Generates attribute search XPath string
447 * Generates an XPath query to select elements whose provided attribute contains
448 * the provided value in a space-separated list.
450 * @param string $attr Name of the attribute to seach
451 * @param string $value Value to search in a space-separated list
454 private static function buildXPath(string $attr, $value): string
456 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
457 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'";
461 * Returns the inner XML string of a provided DOMNode
463 * @param DOMNode $node
466 private static function getInnerHTML(DOMNode $node): string
469 $children = $node->childNodes;
470 foreach ($children as $child) {
471 $innerHTML .= $child->ownerDocument->saveXML($child);