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\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\ParseUrl;
38 use Friendica\Util\Proxy;
39 use Friendica\Util\Strings;
42 * Handles all OEmbed content fetching and replacement
44 * OEmbed is a standard used to allow an embedded representation of a URL on
47 * @see https://oembed.com
51 public static function replaceCallback($matches)
53 $embedurl = $matches[1];
54 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
55 $s = self::formatObject($j);
61 * Get data from an URL to embed its content.
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 * @param bool $use_parseurl Use the "ParseUrl" functionality to add additional data
67 * @return \Friendica\Object\OEmbed
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
70 public static function fetchURL($embedurl, bool $no_rich_type = false, bool $use_parseurl = true)
72 $embedurl = trim($embedurl, '\'"');
76 $cache_key = 'oembed:' . $a->getThemeInfoValue('videowidth') . ':' . $embedurl;
78 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->getThemeInfoValue('videowidth')];
79 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
80 if (DBA::isResult($oembed_record)) {
81 $json_string = $oembed_record['content'];
83 $json_string = DI::cache()->get($cache_key);
86 // These media files should now be caught in bbcode.php
87 // left here as a fallback in case this is called from another source
88 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
89 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
91 $oembed = new \Friendica\Object\OEmbed($embedurl);
94 $oembed->parseJSON($json_string);
98 if (!in_array($ext, $noexts)) {
99 // try oembed autodiscovery
100 $html_text = DI::httpClient()->fetch($embedurl, 15, 'text/*');
101 if (!empty($html_text)) {
102 $dom = new DOMDocument();
103 if (@$dom->loadHTML($html_text)) {
104 $xpath = new DOMXPath($dom);
106 $xpath->query("//link[@type='application/json+oembed'] | //link[@type='text/json+oembed']")
109 $href = $link->getAttributeNode('href')->nodeValue;
110 // Both Youtube and Vimeo output OEmbed endpoint URL with HTTP
111 // but their OEmbed endpoint is only accessible by HTTPS ¯\_(ツ)_/¯
112 $href = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'],
113 ['https://www.youtube.com/', 'https://player.vimeo.com/'], $href);
114 $result = DI::httpClient()->fetchFull($href . '&maxwidth=' . $a->getThemeInfoValue('videowidth'));
115 if ($result->getReturnCode() === 200) {
116 $json_string = $result->getBody();
124 $json_string = trim($json_string);
126 if (!$json_string || $json_string[0] != '{') {
127 $json_string = '{"type":"error"}';
130 $oembed->parseJSON($json_string);
132 if (!empty($oembed->type) && $oembed->type != 'error') {
133 DBA::insert('oembed', [
134 'url' => Strings::normaliseLink($embedurl),
135 'maxwidth' => $a->getThemeInfoValue('videowidth'),
136 'content' => $json_string,
137 'created' => DateTimeFormat::utcNow()
138 ], Database::INSERT_UPDATE);
139 $cache_ttl = Duration::DAY;
141 $cache_ttl = Duration::FIVE_MINUTES;
144 DI::cache()->set($cache_key, $json_string, $cache_ttl);
147 // Always embed the SSL version
148 if (!empty($oembed->html)) {
149 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
152 // Improve the OEmbed data with data from OpenGraph, Twitter cards and other sources
154 $data = ParseUrl::getSiteinfoCached($embedurl, false);
156 if (($oembed->type == 'error') && empty($data['title']) && empty($data['text'])) {
160 if ($no_rich_type || ($oembed->type == 'error')) {
162 $oembed->type = $data['type'];
164 if ($oembed->type == 'photo') {
165 if (!empty($data['images'])) {
166 $oembed->url = $data['images'][0]['src'];
167 $oembed->width = $data['images'][0]['width'];
168 $oembed->height = $data['images'][0]['height'];
170 $oembed->type = 'link';
175 if (!empty($data['title'])) {
176 $oembed->title = $data['title'];
179 if (!empty($data['text'])) {
180 $oembed->description = $data['text'];
183 if (!empty($data['publisher_name'])) {
184 $oembed->provider_name = $data['publisher_name'];
187 if (!empty($data['publisher_url'])) {
188 $oembed->provider_url = $data['publisher_url'];
191 if (!empty($data['author_name'])) {
192 $oembed->author_name = $data['author_name'];
195 if (!empty($data['author_url'])) {
196 $oembed->author_url = $data['author_url'];
199 if (!empty($data['images']) && ($oembed->type != 'photo')) {
200 $oembed->thumbnail_url = $data['images'][0]['src'];
201 $oembed->thumbnail_width = $data['images'][0]['width'];
202 $oembed->thumbnail_height = $data['images'][0]['height'];
206 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
211 private static function formatObject(\Friendica\Object\OEmbed $oembed)
213 $ret = '<div class="oembed ' . $oembed->type . '">';
215 switch ($oembed->type) {
217 if ($oembed->thumbnail_url) {
218 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
219 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
220 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
221 $tr = (($th) ? $tw / $th : 1);
225 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
226 $ret .= Renderer::replaceMacros($tpl, [
227 '$embedurl' => $oembed->embed_url,
228 '$escapedhtml' => base64_encode($oembed->html),
231 '$turl' => $oembed->thumbnail_url,
234 $ret = $oembed->html;
239 $ret .= '<img width="' . $oembed->width . '" src="' . Proxy::proxifyUrl($oembed->url) . '">';
246 $ret .= Proxy::proxifyHtml($oembed->html);
250 // add link to source if not present in "rich" type
251 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
253 if (!empty($oembed->title)) {
254 if (!empty($oembed->provider_name)) {
255 $ret .= $oembed->provider_name . ": ";
258 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
259 if (!empty($oembed->author_name)) {
260 $ret .= ' (' . $oembed->author_name . ')';
262 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
264 if (!empty($oembed->provider_name)) {
265 $embedlink .= $oembed->provider_name;
268 if (!empty($oembed->author_name)) {
269 if ($embedlink != "") {
273 $embedlink .= $oembed->author_name;
275 if (trim($embedlink) == "") {
276 $embedlink = $oembed->embed_url;
279 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
281 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
284 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
285 // add <a> for html2bbcode conversion
286 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
291 return str_replace("\n", "", $ret);
294 public static function BBCode2HTML($text)
296 $stopoembed = DI::config()->get("system", "no_oembed");
297 if ($stopoembed == true) {
298 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
300 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
304 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
305 * and replace it with [embed]url[/embed]
310 public static function HTML2BBCode($text)
312 // start parser only if 'oembed' is in text
313 if (strpos($text, "oembed")) {
315 // convert non ascii chars to html entities
316 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
318 // If it doesn't parse at all, just return the text.
319 $dom = @DOMDocument::loadHTML($html_text);
323 $xpath = new DOMXPath($dom);
325 $xattr = self::buildXPath("class", "oembed");
326 $entries = $xpath->query("//div[$xattr]");
328 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
329 foreach ($entries as $e) {
330 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
331 if (!is_null($href)) {
332 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
335 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
342 * Determines if rich content OEmbed is allowed for the provided URL
346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
348 public static function isAllowedURL($url)
350 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
354 $domain = parse_url($url, PHP_URL_HOST);
355 if (empty($domain)) {
359 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
360 if (empty($str_allowed)) {
364 $allowed = explode(',', $str_allowed);
366 return Network::isDomainAllowed($domain, $allowed);
369 public static function getHTML($url, $title = null)
371 $o = self::fetchURL($url, !self::isAllowedURL($url));
373 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
374 throw new Exception('OEmbed failed for URL: ' . $url);
377 if (!empty($title)) {
381 $html = self::formatObject($o);
387 * Generates the iframe HTML for an oembed attachment.
389 * Width and height are given by the remote, and are regularly too small for
390 * the generated iframe.
392 * The width is entirely discarded for the actual width of the post, while fixed
393 * height is used as a starting point before the inevitable resizing.
395 * Since the iframe is automatically resized on load, there are no need for ugly
396 * and impractical scrollbars.
398 * @todo This function is currently unused until someone™ adds support for a separate OEmbed domain
400 * @param string $src Original remote URL to embed
401 * @param string $width
402 * @param string $height
403 * @return string formatted HTML
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 * @see oembed_format_object()
408 private static function iframe($src, $width, $height)
410 if (!$height || strstr($height, '%')) {
415 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
416 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>';
420 * Generates attribute search XPath string
422 * Generates an XPath query to select elements whose provided attribute contains
423 * the provided value in a space-separated list.
425 * @param string $attr Name of the attribute to seach
426 * @param string $value Value to search in a space-separated list
429 private static function buildXPath($attr, $value)
431 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
432 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'";
436 * Returns the inner XML string of a provided DOMNode
438 * @param DOMNode $node
441 private static function getInnerHTML(DOMNode $node)
444 $children = $node->childNodes;
445 foreach ($children as $child) {
446 $innerHTML .= $child->ownerDocument->saveXML($child);