3 * @copyright Copyright (C) 2020, Friendica
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\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 as ProxyUtils;
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.
66 * @return \Friendica\Object\OEmbed
67 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 public static function fetchURL($embedurl, $no_rich_type = false)
71 $embedurl = trim($embedurl, '\'"');
75 $cache_key = 'oembed:' . $a->videowidth . ':' . $embedurl;
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'];
82 $json_string = DI::cache()->get($cache_key);
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);
90 $oembed = new \Friendica\Object\OEmbed($embedurl);
93 $oembed->parseJSON($json_string);
97 if (!in_array($ext, $noexts)) {
98 // try oembed autodiscovery
99 $html_text = DI::httpRequest()->fetch($embedurl, 15, 'text/*');
101 $dom = @DOMDocument::loadHTML($html_text);
103 $xpath = new DOMXPath($dom);
104 $entries = $xpath->query("//link[@type='application/json+oembed']");
105 foreach ($entries as $e) {
106 $href = $e->getAttributeNode('href')->nodeValue;
107 $json_string = DI::httpRequest()->fetch($href . '&maxwidth=' . $a->videowidth);
111 $entries = $xpath->query("//link[@type='text/json+oembed']");
112 foreach ($entries as $e) {
113 $href = $e->getAttributeNode('href')->nodeValue;
114 $json_string = DI::httpRequest()->fetch($href . '&maxwidth=' . $a->videowidth);
121 $json_string = trim($json_string);
123 if (!$json_string || $json_string[0] != '{') {
124 $json_string = '{"type":"error"}';
127 $oembed->parseJSON($json_string);
129 if (!empty($oembed->type) && $oembed->type != 'error') {
130 DBA::insert('oembed', [
131 'url' => Strings::normaliseLink($embedurl),
132 'maxwidth' => $a->videowidth,
133 'content' => $json_string,
134 'created' => DateTimeFormat::utcNow()
135 ], Database::INSERT_UPDATE);
136 $cache_ttl = Duration::DAY;
138 $cache_ttl = Duration::FIVE_MINUTES;
141 DI::cache()->set($cache_key, $json_string, $cache_ttl);
144 if ($oembed->type == 'error') {
148 // Always embed the SSL version
149 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
151 // If fetching information doesn't work, then improve via internal functions
152 if ($no_rich_type && ($oembed->type == 'rich')) {
153 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
154 $oembed->type = $data['type'];
156 if ($oembed->type == 'photo') {
157 $oembed->url = $data['url'];
160 if (isset($data['title'])) {
161 $oembed->title = $data['title'];
164 if (isset($data['text'])) {
165 $oembed->description = $data['text'];
168 if (!empty($data['images'])) {
169 $oembed->thumbnail_url = $data['images'][0]['src'];
170 $oembed->thumbnail_width = $data['images'][0]['width'];
171 $oembed->thumbnail_height = $data['images'][0]['height'];
175 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
180 private static function formatObject(\Friendica\Object\OEmbed $oembed)
182 $ret = '<div class="oembed ' . $oembed->type . '">';
184 switch ($oembed->type) {
186 if ($oembed->thumbnail_url) {
187 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
188 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
189 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
190 $tr = (($th) ? $tw / $th : 1);
194 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
195 $ret .= Renderer::replaceMacros($tpl, [
196 '$embedurl' => $oembed->embed_url,
197 '$escapedhtml' => base64_encode($oembed->html),
200 '$turl' => $oembed->thumbnail_url,
203 $ret = $oembed->html;
208 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
215 $ret .= ProxyUtils::proxifyHtml($oembed->html);
219 // add link to source if not present in "rich" type
220 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
222 if (!empty($oembed->title)) {
223 if (!empty($oembed->provider_name)) {
224 $ret .= $oembed->provider_name . ": ";
227 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
228 if (!empty($oembed->author_name)) {
229 $ret .= ' (' . $oembed->author_name . ')';
231 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
233 if (!empty($oembed->provider_name)) {
234 $embedlink .= $oembed->provider_name;
237 if (!empty($oembed->author_name)) {
238 if ($embedlink != "") {
242 $embedlink .= $oembed->author_name;
244 if (trim($embedlink) == "") {
245 $embedlink = $oembed->embed_url;
248 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
250 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
253 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
254 // add <a> for html2bbcode conversion
255 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
260 return str_replace("\n", "", $ret);
263 public static function BBCode2HTML($text)
265 $stopoembed = DI::config()->get("system", "no_oembed");
266 if ($stopoembed == true) {
267 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
269 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
273 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
274 * and replace it with [embed]url[/embed]
279 public static function HTML2BBCode($text)
281 // start parser only if 'oembed' is in text
282 if (strpos($text, "oembed")) {
284 // convert non ascii chars to html entities
285 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
287 // If it doesn't parse at all, just return the text.
288 $dom = @DOMDocument::loadHTML($html_text);
292 $xpath = new DOMXPath($dom);
294 $xattr = self::buildXPath("class", "oembed");
295 $entries = $xpath->query("//div[$xattr]");
297 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
298 foreach ($entries as $e) {
299 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
300 if (!is_null($href)) {
301 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
304 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
311 * Determines if rich content OEmbed is allowed for the provided URL
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
317 public static function isAllowedURL($url)
319 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
323 $domain = parse_url($url, PHP_URL_HOST);
324 if (empty($domain)) {
328 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
329 if (empty($str_allowed)) {
333 $allowed = explode(',', $str_allowed);
335 return Network::isDomainAllowed($domain, $allowed);
338 public static function getHTML($url, $title = null)
340 // Always embed the SSL version
341 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
342 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
344 $o = self::fetchURL($url, !self::isAllowedURL($url));
346 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
347 throw new Exception('OEmbed failed for URL: ' . $url);
350 if (!empty($title)) {
354 $html = self::formatObject($o);
360 * Generates the iframe HTML for an oembed attachment.
362 * Width and height are given by the remote, and are regularly too small for
363 * the generated iframe.
365 * The width is entirely discarded for the actual width of the post, while fixed
366 * height is used as a starting point before the inevitable resizing.
368 * Since the iframe is automatically resized on load, there are no need for ugly
369 * and impractical scrollbars.
371 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
373 * @param string $src Original remote URL to embed
374 * @param string $width
375 * @param string $height
376 * @return string formatted HTML
378 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
379 * @see oembed_format_object()
381 private static function iframe($src, $width, $height)
383 if (!$height || strstr($height, '%')) {
388 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
389 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>';
393 * Generates attribute search XPath string
395 * Generates an XPath query to select elements whose provided attribute contains
396 * the provided value in a space-separated list.
398 * @param string $attr Name of the attribute to seach
399 * @param string $value Value to search in a space-separated list
402 private static function buildXPath($attr, $value)
404 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
405 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'";
409 * Returns the inner XML string of a provided DOMNode
411 * @param DOMNode $node
414 private static function getInnerHTML(DOMNode $node)
417 $children = $node->childNodes;
418 foreach ($children as $child) {
419 $innerHTML .= $child->ownerDocument->saveXML($child);