4 * @file src/Content/OEmbed.php
6 namespace Friendica\Content;
13 use Friendica\Core\Addon;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Network;
21 use Friendica\Util\ParseUrl;
22 use Friendica\Util\Proxy as ProxyUtils;
24 require_once 'include/dba.php';
27 * Handles all OEmbed content fetching and replacement
29 * OEmbed is a standard used to allow an embedded representation of a URL on
32 * @see https://oembed.com
34 * @author Hypolite Petovan <mrpetovan@gmail.com>
38 public static function replaceCallback($matches)
40 $embedurl = $matches[1];
41 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
42 $s = self::formatObject($j);
48 * @brief Get data from an URL to embed its content.
50 * @param string $embedurl The URL from which the data should be fetched.
51 * @param bool $no_rich_type If set to true rich type content won't be fetched.
53 * @return \Friendica\Object\OEmbed
55 public static function fetchURL($embedurl, $no_rich_type = false)
57 $embedurl = trim($embedurl, '\'"');
61 $cache_key = 'oembed:' . $a->videowidth . ':' . $embedurl;
63 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
64 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
65 if (DBA::isResult($oembed_record)) {
66 $json_string = $oembed_record['content'];
68 $json_string = Cache::get($cache_key);
71 // These media files should now be caught in bbcode.php
72 // left here as a fallback in case this is called from another source
73 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
74 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
76 $oembed = new \Friendica\Object\OEmbed($embedurl);
79 $oembed->parseJSON($json_string);
83 if (!in_array($ext, $noexts)) {
84 // try oembed autodiscovery
86 $html_text = Network::fetchUrl($embedurl, false, $redirects, 15, 'text/*');
88 $dom = @DOMDocument::loadHTML($html_text);
90 $xpath = new DOMXPath($dom);
91 $entries = $xpath->query("//link[@type='application/json+oembed']");
92 foreach ($entries as $e) {
93 $href = $e->getAttributeNode('href')->nodeValue;
94 $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
98 $entries = $xpath->query("//link[@type='text/json+oembed']");
99 foreach ($entries as $e) {
100 $href = $e->getAttributeNode('href')->nodeValue;
101 $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
108 $json_string = trim($json_string);
110 if (!$json_string || $json_string[0] != '{') {
111 $json_string = '{"type":"error"}';
114 $oembed->parseJSON($json_string);
116 if (!empty($oembed->type) && $oembed->type != 'error') {
117 DBA::insert('oembed', [
118 'url' => normalise_link($embedurl),
119 'maxwidth' => $a->videowidth,
120 'content' => $json_string,
121 'created' => DateTimeFormat::utcNow()
123 $cache_ttl = CACHE_DAY;
125 $cache_ttl = CACHE_FIVE_MINUTES;
128 Cache::set($cache_key, $json_string, $cache_ttl);
131 if ($oembed->type == 'error') {
135 // Always embed the SSL version
136 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
138 // If fetching information doesn't work, then improve via internal functions
139 if ($no_rich_type && ($oembed->type == 'rich')) {
140 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
141 $oembed->type = $data['type'];
143 if ($oembed->type == 'photo') {
144 $oembed->url = $data['url'];
147 if (isset($data['title'])) {
148 $oembed->title = $data['title'];
151 if (isset($data['text'])) {
152 $oembed->description = $data['text'];
155 if (!empty($data['images'])) {
156 $oembed->thumbnail_url = $data['images'][0]['src'];
157 $oembed->thumbnail_width = $data['images'][0]['width'];
158 $oembed->thumbnail_height = $data['images'][0]['height'];
162 Addon::callHooks('oembed_fetch_url', $embedurl, $oembed);
167 private static function formatObject(\Friendica\Object\OEmbed $oembed)
169 $ret = '<div class="oembed ' . $oembed->type . '">';
171 switch ($oembed->type) {
173 if ($oembed->thumbnail_url) {
174 $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
175 $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
176 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
177 $tr = (($th) ? $tw / $th : 1);
181 $tpl = get_markup_template('oembed_video.tpl');
182 $ret .= replace_macros($tpl, [
183 '$baseurl' => System::baseUrl(),
184 '$embedurl' => $oembed->embed_url,
185 '$escapedhtml' => base64_encode($oembed->html),
188 '$turl' => $oembed->thumbnail_url,
191 $ret = $oembed->html;
196 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
203 $ret .= ProxyUtils::proxifyHtml($oembed->html);
207 // add link to source if not present in "rich" type
208 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
210 if (!empty($oembed->title)) {
211 if (!empty($oembed->provider_name)) {
212 $ret .= $oembed->provider_name . ": ";
215 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
216 if (!empty($oembed->author_name)) {
217 $ret .= ' (' . $oembed->author_name . ')';
219 } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
221 if (!empty($oembed->provider_name)) {
222 $embedlink .= $oembed->provider_name;
225 if (!empty($oembed->author_name)) {
226 if ($embedlink != "") {
230 $embedlink .= $oembed->author_name;
232 if (trim($embedlink) == "") {
233 $embedlink = $oembed->embed_url;
236 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
238 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
241 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
242 // add <a> for html2bbcode conversion
243 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
248 $ret = str_replace("\n", "", $ret);
249 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
252 public static function BBCode2HTML($text)
254 $stopoembed = Config::get("system", "no_oembed");
255 if ($stopoembed == true) {
256 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . L10n::t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
258 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
262 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
263 * and replace it with [embed]url[/embed]
265 public static function HTML2BBCode($text)
267 // start parser only if 'oembed' is in text
268 if (strpos($text, "oembed")) {
270 // convert non ascii chars to html entities
271 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
273 // If it doesn't parse at all, just return the text.
274 $dom = @DOMDocument::loadHTML($html_text);
278 $xpath = new DOMXPath($dom);
280 $xattr = self::buildXPath("class", "oembed");
281 $entries = $xpath->query("//div[$xattr]");
283 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
284 foreach ($entries as $e) {
285 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
286 if (!is_null($href)) {
287 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
290 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
297 * Determines if rich content OEmbed is allowed for the provided URL
299 * @brief Determines if rich content OEmbed is allowed for the provided URL
303 public static function isAllowedURL($url)
305 if (!Config::get('system', 'no_oembed_rich_content')) {
309 $domain = parse_url($url, PHP_URL_HOST);
314 $str_allowed = Config::get('system', 'allowed_oembed', '');
315 if (!x($str_allowed)) {
319 $allowed = explode(',', $str_allowed);
321 return Network::isDomainAllowed($domain, $allowed);
324 public static function getHTML($url, $title = null)
326 // Always embed the SSL version
327 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
328 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
330 $o = self::fetchURL($url, !self::isAllowedURL($url));
332 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
333 throw new Exception('OEmbed failed for URL: ' . $url);
340 $html = self::formatObject($o);
346 * @brief Generates the iframe HTML for an oembed attachment.
348 * Width and height are given by the remote, and are regularly too small for
349 * the generated iframe.
351 * The width is entirely discarded for the actual width of the post, while fixed
352 * height is used as a starting point before the inevitable resizing.
354 * Since the iframe is automatically resized on load, there are no need for ugly
355 * and impractical scrollbars.
357 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
359 * @param string $src Original remote URL to embed
360 * @param string $width
361 * @param string $height
362 * @return string formatted HTML
364 * @see oembed_format_object()
366 private static function iframe($src, $width, $height)
370 if (!$height || strstr($height, '%')) {
375 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
376 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . L10n::t('Embedded content') . '</iframe>';
380 * Generates an XPath query to select elements whose provided attribute contains
381 * the provided value in a space-separated list.
383 * @brief Generates attribute search XPath string
385 * @param string $attr Name of the attribute to seach
386 * @param string $value Value to search in a space-separated list
389 private static function buildXPath($attr, $value)
391 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
392 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'";
396 * Returns the inner XML string of a provided DOMNode
398 * @brief Returns the inner XML string of a provided DOMNode
400 * @param DOMNode $node
403 private static function getInnerHTML(DOMNode $node)
406 $children = $node->childNodes;
407 foreach ($children as $child) {
408 $innerHTML .= $child->ownerDocument->saveXML($child);