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 = new DOMDocument();
102 if (@$dom->loadHTML($html_text)) {
103 $xpath = new DOMXPath($dom);
105 $xpath->query("//link[@type='application/json+oembed'] | //link[@type='text/json+oembed']")
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();
123 $json_string = trim($json_string);
125 if (!$json_string || $json_string[0] != '{') {
126 $json_string = '{"type":"error"}';
129 $oembed->parseJSON($json_string);
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;
140 $cache_ttl = Duration::FIVE_MINUTES;
143 DI::cache()->set($cache_key, $json_string, $cache_ttl);
146 if ($oembed->type == 'error') {
150 // Always embed the SSL version
151 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
153 // If fetching information doesn't work, then improve via internal functions
154 if ($no_rich_type && ($oembed->type == 'rich')) {
155 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
156 $oembed->type = $data['type'];
158 if ($oembed->type == 'photo') {
159 $oembed->url = $data['url'];
162 if (isset($data['title'])) {
163 $oembed->title = $data['title'];
166 if (isset($data['text'])) {
167 $oembed->description = $data['text'];
170 if (!empty($data['images'])) {
171 $oembed->thumbnail_url = $data['images'][0]['src'];
172 $oembed->thumbnail_width = $data['images'][0]['width'];
173 $oembed->thumbnail_height = $data['images'][0]['height'];
177 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
182 private static function formatObject(\Friendica\Object\OEmbed $oembed)
184 $ret = '<div class="oembed ' . $oembed->type . '">';
186 switch ($oembed->type) {
188 if ($oembed->thumbnail_url) {
189 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
190 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
191 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
192 $tr = (($th) ? $tw / $th : 1);
196 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
197 $ret .= Renderer::replaceMacros($tpl, [
198 '$embedurl' => $oembed->embed_url,
199 '$escapedhtml' => base64_encode($oembed->html),
202 '$turl' => $oembed->thumbnail_url,
205 $ret = $oembed->html;
210 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
217 $ret .= ProxyUtils::proxifyHtml($oembed->html);
221 // add link to source if not present in "rich" type
222 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
224 if (!empty($oembed->title)) {
225 if (!empty($oembed->provider_name)) {
226 $ret .= $oembed->provider_name . ": ";
229 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
230 if (!empty($oembed->author_name)) {
231 $ret .= ' (' . $oembed->author_name . ')';
233 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
235 if (!empty($oembed->provider_name)) {
236 $embedlink .= $oembed->provider_name;
239 if (!empty($oembed->author_name)) {
240 if ($embedlink != "") {
244 $embedlink .= $oembed->author_name;
246 if (trim($embedlink) == "") {
247 $embedlink = $oembed->embed_url;
250 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
252 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
255 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
256 // add <a> for html2bbcode conversion
257 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
262 return str_replace("\n", "", $ret);
265 public static function BBCode2HTML($text)
267 $stopoembed = DI::config()->get("system", "no_oembed");
268 if ($stopoembed == true) {
269 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
271 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
275 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
276 * and replace it with [embed]url[/embed]
281 public static function HTML2BBCode($text)
283 // start parser only if 'oembed' is in text
284 if (strpos($text, "oembed")) {
286 // convert non ascii chars to html entities
287 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
289 // If it doesn't parse at all, just return the text.
290 $dom = @DOMDocument::loadHTML($html_text);
294 $xpath = new DOMXPath($dom);
296 $xattr = self::buildXPath("class", "oembed");
297 $entries = $xpath->query("//div[$xattr]");
299 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
300 foreach ($entries as $e) {
301 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
302 if (!is_null($href)) {
303 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
306 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
313 * Determines if rich content OEmbed is allowed for the provided URL
317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
319 public static function isAllowedURL($url)
321 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
325 $domain = parse_url($url, PHP_URL_HOST);
326 if (empty($domain)) {
330 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
331 if (empty($str_allowed)) {
335 $allowed = explode(',', $str_allowed);
337 return Network::isDomainAllowed($domain, $allowed);
340 public static function getHTML($url, $title = null)
342 $o = self::fetchURL($url, !self::isAllowedURL($url));
344 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
345 throw new Exception('OEmbed failed for URL: ' . $url);
348 if (!empty($title)) {
352 $html = self::formatObject($o);
358 * Generates the iframe HTML for an oembed attachment.
360 * Width and height are given by the remote, and are regularly too small for
361 * the generated iframe.
363 * The width is entirely discarded for the actual width of the post, while fixed
364 * height is used as a starting point before the inevitable resizing.
366 * Since the iframe is automatically resized on load, there are no need for ugly
367 * and impractical scrollbars.
369 * @todo This function is currently unused until someone™ adds support for a separate OEmbed domain
371 * @param string $src Original remote URL to embed
372 * @param string $width
373 * @param string $height
374 * @return string formatted HTML
376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 * @see oembed_format_object()
379 private static function iframe($src, $width, $height)
381 if (!$height || strstr($height, '%')) {
386 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
387 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>';
391 * Generates attribute search XPath string
393 * Generates an XPath query to select elements whose provided attribute contains
394 * the provided value in a space-separated list.
396 * @param string $attr Name of the attribute to seach
397 * @param string $value Value to search in a space-separated list
400 private static function buildXPath($attr, $value)
402 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
403 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'";
407 * Returns the inner XML string of a provided DOMNode
409 * @param DOMNode $node
412 private static function getInnerHTML(DOMNode $node)
415 $children = $node->childNodes;
416 foreach ($children as $child) {
417 $innerHTML .= $child->ownerDocument->saveXML($child);