4 * @file src/Content/OEmbed.php
6 namespace Friendica\Content;
13 use Friendica\Core\Cache\Duration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Renderer;
16 use Friendica\Database\DBA;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Network;
20 use Friendica\Util\ParseUrl;
21 use Friendica\Util\Proxy as ProxyUtils;
22 use Friendica\Util\Strings;
25 * Handles all OEmbed content fetching and replacement
27 * OEmbed is a standard used to allow an embedded representation of a URL on
30 * @see https://oembed.com
32 * @author Hypolite Petovan <hypolite@mrpetovan.com>
36 public static function replaceCallback($matches)
38 $embedurl = $matches[1];
39 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
40 $s = self::formatObject($j);
46 * Get data from an URL to embed its content.
48 * @param string $embedurl The URL from which the data should be fetched.
49 * @param bool $no_rich_type If set to true rich type content won't be fetched.
51 * @return \Friendica\Object\OEmbed
52 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54 public static function fetchURL($embedurl, $no_rich_type = false)
56 $embedurl = trim($embedurl, '\'"');
60 $cache_key = 'oembed:' . $a->videowidth . ':' . $embedurl;
62 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->videowidth];
63 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
64 if (DBA::isResult($oembed_record)) {
65 $json_string = $oembed_record['content'];
67 $json_string = DI::cache()->get($cache_key);
70 // These media files should now be caught in bbcode.php
71 // left here as a fallback in case this is called from another source
72 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
73 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
75 $oembed = new \Friendica\Object\OEmbed($embedurl);
78 $oembed->parseJSON($json_string);
82 if (!in_array($ext, $noexts)) {
83 // try oembed autodiscovery
84 $html_text = Network::fetchUrl($embedurl, false, 15, 'text/*');
86 $dom = @DOMDocument::loadHTML($html_text);
88 $xpath = new DOMXPath($dom);
89 $entries = $xpath->query("//link[@type='application/json+oembed']");
90 foreach ($entries as $e) {
91 $href = $e->getAttributeNode('href')->nodeValue;
92 $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
96 $entries = $xpath->query("//link[@type='text/json+oembed']");
97 foreach ($entries as $e) {
98 $href = $e->getAttributeNode('href')->nodeValue;
99 $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
106 $json_string = trim($json_string);
108 if (!$json_string || $json_string[0] != '{') {
109 $json_string = '{"type":"error"}';
112 $oembed->parseJSON($json_string);
114 if (!empty($oembed->type) && $oembed->type != 'error') {
115 DBA::insert('oembed', [
116 'url' => Strings::normaliseLink($embedurl),
117 'maxwidth' => $a->videowidth,
118 'content' => $json_string,
119 'created' => DateTimeFormat::utcNow()
121 $cache_ttl = Duration::DAY;
123 $cache_ttl = Duration::FIVE_MINUTES;
126 DI::cache()->set($cache_key, $json_string, $cache_ttl);
129 if ($oembed->type == 'error') {
133 // Always embed the SSL version
134 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
136 // If fetching information doesn't work, then improve via internal functions
137 if ($no_rich_type && ($oembed->type == 'rich')) {
138 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
139 $oembed->type = $data['type'];
141 if ($oembed->type == 'photo') {
142 $oembed->url = $data['url'];
145 if (isset($data['title'])) {
146 $oembed->title = $data['title'];
149 if (isset($data['text'])) {
150 $oembed->description = $data['text'];
153 if (!empty($data['images'])) {
154 $oembed->thumbnail_url = $data['images'][0]['src'];
155 $oembed->thumbnail_width = $data['images'][0]['width'];
156 $oembed->thumbnail_height = $data['images'][0]['height'];
160 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
165 private static function formatObject(\Friendica\Object\OEmbed $oembed)
167 $ret = '<div class="oembed ' . $oembed->type . '">';
169 switch ($oembed->type) {
171 if ($oembed->thumbnail_url) {
172 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
173 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
174 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
175 $tr = (($th) ? $tw / $th : 1);
179 $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
180 $ret .= Renderer::replaceMacros($tpl, [
181 '$embedurl' => $oembed->embed_url,
182 '$escapedhtml' => base64_encode($oembed->html),
185 '$turl' => $oembed->thumbnail_url,
188 $ret = $oembed->html;
193 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
200 $ret .= ProxyUtils::proxifyHtml($oembed->html);
204 // add link to source if not present in "rich" type
205 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
207 if (!empty($oembed->title)) {
208 if (!empty($oembed->provider_name)) {
209 $ret .= $oembed->provider_name . ": ";
212 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
213 if (!empty($oembed->author_name)) {
214 $ret .= ' (' . $oembed->author_name . ')';
216 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
218 if (!empty($oembed->provider_name)) {
219 $embedlink .= $oembed->provider_name;
222 if (!empty($oembed->author_name)) {
223 if ($embedlink != "") {
227 $embedlink .= $oembed->author_name;
229 if (trim($embedlink) == "") {
230 $embedlink = $oembed->embed_url;
233 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
235 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
238 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
239 // add <a> for html2bbcode conversion
240 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
245 return str_replace("\n", "", $ret);
248 public static function BBCode2HTML($text)
250 $stopoembed = DI::config()->get("system", "no_oembed");
251 if ($stopoembed == true) {
252 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
254 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
258 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
259 * and replace it with [embed]url[/embed]
264 public static function HTML2BBCode($text)
266 // start parser only if 'oembed' is in text
267 if (strpos($text, "oembed")) {
269 // convert non ascii chars to html entities
270 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
272 // If it doesn't parse at all, just return the text.
273 $dom = @DOMDocument::loadHTML($html_text);
277 $xpath = new DOMXPath($dom);
279 $xattr = self::buildXPath("class", "oembed");
280 $entries = $xpath->query("//div[$xattr]");
282 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
283 foreach ($entries as $e) {
284 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
285 if (!is_null($href)) {
286 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
289 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
296 * Determines if rich content OEmbed is allowed for the provided URL
300 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302 public static function isAllowedURL($url)
304 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
308 $domain = parse_url($url, PHP_URL_HOST);
309 if (empty($domain)) {
313 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
314 if (empty($str_allowed)) {
318 $allowed = explode(',', $str_allowed);
320 return Network::isDomainAllowed($domain, $allowed);
323 public static function getHTML($url, $title = null)
325 // Always embed the SSL version
326 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
327 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
329 $o = self::fetchURL($url, !self::isAllowedURL($url));
331 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
332 throw new Exception('OEmbed failed for URL: ' . $url);
335 if (!empty($title)) {
339 $html = self::formatObject($o);
345 * Generates the iframe HTML for an oembed attachment.
347 * Width and height are given by the remote, and are regularly too small for
348 * the generated iframe.
350 * The width is entirely discarded for the actual width of the post, while fixed
351 * height is used as a starting point before the inevitable resizing.
353 * Since the iframe is automatically resized on load, there are no need for ugly
354 * and impractical scrollbars.
356 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
358 * @param string $src Original remote URL to embed
359 * @param string $width
360 * @param string $height
361 * @return string formatted HTML
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 * @see oembed_format_object()
366 private static function iframe($src, $width, $height)
368 if (!$height || strstr($height, '%')) {
373 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
374 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>';
378 * Generates attribute search XPath string
380 * Generates an XPath query to select elements whose provided attribute contains
381 * the provided value in a space-separated list.
383 * @param string $attr Name of the attribute to seach
384 * @param string $value Value to search in a space-separated list
387 private static function buildXPath($attr, $value)
389 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
390 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'";
394 * Returns the inner XML string of a provided DOMNode
396 * @param DOMNode $node
399 private static function getInnerHTML(DOMNode $node)
402 $children = $node->childNodes;
403 foreach ($children as $child) {
404 $innerHTML .= $child->ownerDocument->saveXML($child);