3 * @copyright Copyright (C) 2010-2022, 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
52 public static function replaceCallback($matches)
54 $embedurl = $matches[1];
55 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
56 $s = self::formatObject($j);
62 * Get data from an URL to embed its content.
64 * @param string $embedurl The URL from which the data should be fetched.
65 * @param bool $no_rich_type If set to true rich type content won't be fetched.
66 * @param bool $use_parseurl Use the "ParseUrl" functionality to add additional data
68 * @return \Friendica\Object\OEmbed
69 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
71 public static function fetchURL($embedurl, bool $no_rich_type = false, bool $use_parseurl = true)
73 $embedurl = trim($embedurl, '\'"');
77 $cache_key = 'oembed:' . $a->getThemeInfoValue('videowidth') . ':' . $embedurl;
79 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->getThemeInfoValue('videowidth')];
80 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
81 if (DBA::isResult($oembed_record)) {
82 $json_string = $oembed_record['content'];
84 $json_string = DI::cache()->get($cache_key);
87 // These media files should now be caught in bbcode.php
88 // left here as a fallback in case this is called from another source
89 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
90 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
92 $oembed = new \Friendica\Object\OEmbed($embedurl);
95 $oembed->parseJSON($json_string);
99 if (!in_array($ext, $noexts)) {
100 // try oembed autodiscovery
101 $html_text = DI::httpClient()->fetch($embedurl, HttpClientAccept::HTML, 15);
102 if (!empty($html_text)) {
103 $dom = new DOMDocument();
104 if (@$dom->loadHTML($html_text)) {
105 $xpath = new DOMXPath($dom);
107 $xpath->query("//link[@type='application/json+oembed'] | //link[@type='text/json+oembed']")
110 $href = $link->getAttributeNode('href')->nodeValue;
111 // Both Youtube and Vimeo output OEmbed endpoint URL with HTTP
112 // but their OEmbed endpoint is only accessible by HTTPS ¯\_(ツ)_/¯
113 $href = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'],
114 ['https://www.youtube.com/', 'https://player.vimeo.com/'], $href);
115 $result = DI::httpClient()->fetchFull($href . '&maxwidth=' . $a->getThemeInfoValue('videowidth'));
116 if ($result->getReturnCode() === 200) {
117 $json_string = $result->getBody();
125 $json_string = trim($json_string);
127 if (!$json_string || $json_string[0] != '{') {
128 $json_string = '{"type":"error"}';
131 $oembed->parseJSON($json_string);
133 if (!empty($oembed->type) && $oembed->type != 'error') {
134 DBA::insert('oembed', [
135 'url' => Strings::normaliseLink($embedurl),
136 'maxwidth' => $a->getThemeInfoValue('videowidth'),
137 'content' => $json_string,
138 'created' => DateTimeFormat::utcNow()
139 ], Database::INSERT_UPDATE);
140 $cache_ttl = Duration::DAY;
142 $cache_ttl = Duration::FIVE_MINUTES;
145 DI::cache()->set($cache_key, $json_string, $cache_ttl);
148 // Always embed the SSL version
149 if (!empty($oembed->html)) {
150 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
153 // Improve the OEmbed data with data from OpenGraph, Twitter cards and other sources
155 $data = ParseUrl::getSiteinfoCached($embedurl, false);
157 if (($oembed->type == 'error') && empty($data['title']) && empty($data['text'])) {
161 if ($no_rich_type || ($oembed->type == 'error')) {
163 $oembed->type = $data['type'];
165 if ($oembed->type == 'photo') {
166 if (!empty($data['images'])) {
167 $oembed->url = $data['images'][0]['src'];
168 $oembed->width = $data['images'][0]['width'];
169 $oembed->height = $data['images'][0]['height'];
171 $oembed->type = 'link';
176 if (!empty($data['title'])) {
177 $oembed->title = $data['title'];
180 if (!empty($data['text'])) {
181 $oembed->description = $data['text'];
184 if (!empty($data['publisher_name'])) {
185 $oembed->provider_name = $data['publisher_name'];
188 if (!empty($data['publisher_url'])) {
189 $oembed->provider_url = $data['publisher_url'];
192 if (!empty($data['author_name'])) {
193 $oembed->author_name = $data['author_name'];
196 if (!empty($data['author_url'])) {
197 $oembed->author_url = $data['author_url'];
200 if (!empty($data['images']) && ($oembed->type != 'photo')) {
201 $oembed->thumbnail_url = $data['images'][0]['src'];
202 $oembed->thumbnail_width = $data['images'][0]['width'];
203 $oembed->thumbnail_height = $data['images'][0]['height'];
207 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
212 private static function formatObject(\Friendica\Object\OEmbed $oembed)
214 $ret = '<div class="oembed ' . $oembed->type . '">';
216 switch ($oembed->type) {
218 if ($oembed->thumbnail_url) {
219 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
220 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
221 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
222 $tr = (($th) ? $tw / $th : 1);
226 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
227 $ret .= Renderer::replaceMacros($tpl, [
228 '$embedurl' => $oembed->embed_url,
229 '$escapedhtml' => base64_encode($oembed->html),
232 '$turl' => $oembed->thumbnail_url,
235 $ret = $oembed->html;
240 $ret .= '<img width="' . $oembed->width . '" src="' . Proxy::proxifyUrl($oembed->url) . '">';
247 $ret .= Proxy::proxifyHtml($oembed->html);
251 // add link to source if not present in "rich" type
252 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
254 if (!empty($oembed->title)) {
255 if (!empty($oembed->provider_name)) {
256 $ret .= $oembed->provider_name . ": ";
259 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
260 if (!empty($oembed->author_name)) {
261 $ret .= ' (' . $oembed->author_name . ')';
263 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
265 if (!empty($oembed->provider_name)) {
266 $embedlink .= $oembed->provider_name;
269 if (!empty($oembed->author_name)) {
270 if ($embedlink != "") {
274 $embedlink .= $oembed->author_name;
276 if (trim($embedlink) == "") {
277 $embedlink = $oembed->embed_url;
280 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
282 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
285 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
286 // add <a> for html2bbcode conversion
287 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
292 return str_replace("\n", "", $ret);
295 public static function BBCode2HTML($text)
297 $stopoembed = DI::config()->get("system", "no_oembed");
298 if ($stopoembed == true) {
299 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
301 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
305 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
306 * and replace it with [embed]url[/embed]
311 public static function HTML2BBCode($text)
313 // start parser only if 'oembed' is in text
314 if (strpos($text, "oembed")) {
316 // convert non ascii chars to html entities
317 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
319 // If it doesn't parse at all, just return the text.
320 $dom = @DOMDocument::loadHTML($html_text);
324 $xpath = new DOMXPath($dom);
326 $xattr = self::buildXPath("class", "oembed");
327 $entries = $xpath->query("//div[$xattr]");
329 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
330 foreach ($entries as $e) {
331 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
332 if (!is_null($href)) {
333 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
336 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
343 * Determines if rich content OEmbed is allowed for the provided URL
347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
349 public static function isAllowedURL($url)
351 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
355 $domain = parse_url($url, PHP_URL_HOST);
356 if (empty($domain)) {
360 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
361 if (empty($str_allowed)) {
365 $allowed = explode(',', $str_allowed);
367 return Network::isDomainAllowed($domain, $allowed);
370 public static function getHTML($url, $title = null)
372 $o = self::fetchURL($url, !self::isAllowedURL($url));
374 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
375 throw new Exception('OEmbed failed for URL: ' . $url);
378 if (!empty($title)) {
382 $html = self::formatObject($o);
388 * Generates the iframe HTML for an oembed attachment.
390 * Width and height are given by the remote, and are regularly too small for
391 * the generated iframe.
393 * The width is entirely discarded for the actual width of the post, while fixed
394 * height is used as a starting point before the inevitable resizing.
396 * Since the iframe is automatically resized on load, there are no need for ugly
397 * and impractical scrollbars.
399 * @todo This function is currently unused until someone™ adds support for a separate OEmbed domain
401 * @param string $src Original remote URL to embed
402 * @param string $width
403 * @param string $height
404 * @return string formatted HTML
406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407 * @see oembed_format_object()
409 private static function iframe($src, $width, $height)
411 if (!$height || strstr($height, '%')) {
416 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
417 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>';
421 * Generates attribute search XPath string
423 * Generates an XPath query to select elements whose provided attribute contains
424 * the provided value in a space-separated list.
426 * @param string $attr Name of the attribute to seach
427 * @param string $value Value to search in a space-separated list
430 private static function buildXPath($attr, $value)
432 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
433 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'";
437 * Returns the inner XML string of a provided DOMNode
439 * @param DOMNode $node
442 private static function getInnerHTML(DOMNode $node)
445 $children = $node->childNodes;
446 foreach ($children as $child) {
447 $innerHTML .= $child->ownerDocument->saveXML($child);