3 * @file src/Content/OEmbed.php
5 namespace Friendica\Content;
7 use Friendica\Core\Addon;
8 use Friendica\Core\Cache;
9 use Friendica\Core\L10n;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Database\DBM;
13 use Friendica\Util\Network;
14 use Friendica\Util\ParseUrl;
21 require_once 'include/dba.php';
22 require_once 'mod/proxy.php';
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 <mrpetovan@gmail.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 * @brief 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 bool|object Returns object with embed content or false if no embeddable
54 public static function fetchURL($embedurl, $no_rich_type = false)
56 $embedurl = trim($embedurl, "'");
57 $embedurl = trim($embedurl, '"');
61 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
62 $oembed = dba::selectFirst('oembed', ['content'], $condition);
63 if (DBM::is_result($oembed)) {
64 $txt = $oembed["content"];
66 $txt = Cache::get($a->videowidth . $embedurl);
68 // These media files should now be caught in bbcode.php
69 // left here as a fallback in case this is called from another source
71 $noexts = ["mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm"];
72 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
78 if (!in_array($ext, $noexts)) {
79 // try oembed autodiscovery
81 $html_text = Network::fetchUrl($embedurl, false, $redirects, 15, "text/*");
83 $dom = @DOMDocument::loadHTML($html_text);
85 $xpath = new DOMXPath($dom);
86 $entries = $xpath->query("//link[@type='application/json+oembed']");
87 foreach ($entries as $e) {
88 $href = $e->getAttributeNode("href")->nodeValue;
89 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
92 $entries = $xpath->query("//link[@type='text/json+oembed']");
93 foreach ($entries as $e) {
94 $href = $e->getAttributeNode("href")->nodeValue;
95 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
104 if (!$txt || $txt[0] != "{") {
105 $txt = '{"type":"error"}';
106 } else { //save in cache
107 $j = json_decode($txt);
108 if ($j->type != "error") {
109 dba::insert('oembed', [
110 'url' => normalise_link($embedurl),
111 'maxwidth' => $a->videowidth,
113 'created' => datetime_convert()
117 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
121 $j = json_decode($txt);
123 if (!is_object($j)) {
127 // Always embed the SSL version
128 if (isset($j->html)) {
129 $j->html = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"], ["https://www.youtube.com/", "https://player.vimeo.com/"], $j->html);
132 $j->embedurl = $embedurl;
134 // If fetching information doesn't work, then improve via internal functions
135 if ($no_rich_type && ($j->type == "rich")) {
136 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
137 $j->type = $data["type"];
139 if ($j->type == "photo") {
140 $j->url = $data["url"];
143 if (isset($data["title"])) {
144 $j->title = $data["title"];
147 if (isset($data["text"])) {
148 $j->description = $data["text"];
151 if (is_array($data["images"])) {
152 $j->thumbnail_url = $data["images"][0]["src"];
153 $j->thumbnail_width = $data["images"][0]["width"];
154 $j->thumbnail_height = $data["images"][0]["height"];
158 Addon::callHooks('oembed_fetch_url', $embedurl, $j);
163 private static function formatObject($j)
165 $embedurl = $j->embedurl;
167 $ret = '<div class="oembed ' . $j->type . '">';
170 if (isset($j->thumbnail_url)) {
171 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
172 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;
173 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
174 $tr = (($th) ? $tw / $th : 1);
178 $tpl = get_markup_template('oembed_video.tpl');
179 $ret .= replace_macros($tpl, [
180 '$baseurl' => System::baseUrl(),
181 '$embedurl' => $embedurl,
182 '$escapedhtml' => base64_encode($jhtml),
185 '$turl' => $j->thumbnail_url,
192 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
197 $ret .= proxy_parse_html($jhtml);
201 // add link to source if not present in "rich" type
202 if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
204 if (!empty($j->title)) {
205 if (!empty($j->provider_name)) {
206 $ret .= $j->provider_name . ": ";
209 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
210 if (!empty($j->author_name)) {
211 $ret .= ' (' . $j->author_name . ')';
213 } elseif (!empty($j->provider_name) || !empty($j->author_name)) {
215 if (!empty($j->provider_name)) {
216 $embedlink .= $j->provider_name;
219 if (!empty($j->author_name)) {
220 if ($embedlink != "") {
224 $embedlink .= $j->author_name;
226 if (trim($embedlink) == "") {
227 $embedlink = $embedurl;
230 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
232 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedurl . '</a>';
235 } elseif (!strpos($j->html, $embedurl)) {
236 // add <a> for html2bbcode conversion
237 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
242 $ret = str_replace("\n", "", $ret);
243 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
246 public static function BBCode2HTML($text)
248 $stopoembed = Config::get("system", "no_oembed");
249 if ($stopoembed == true) {
250 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . L10n::t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
252 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
256 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
257 * and replace it with [embed]url[/embed]
259 public static function HTML2BBCode($text)
261 // start parser only if 'oembed' is in text
262 if (strpos($text, "oembed")) {
264 // convert non ascii chars to html entities
265 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
267 // If it doesn't parse at all, just return the text.
268 $dom = @DOMDocument::loadHTML($html_text);
272 $xpath = new DOMXPath($dom);
274 $xattr = self::buildXPath("class", "oembed");
275 $entries = $xpath->query("//div[$xattr]");
277 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
278 foreach ($entries as $e) {
279 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
280 if (!is_null($href)) {
281 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
284 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
291 * Determines if rich content OEmbed is allowed for the provided URL
293 * @brief Determines if rich content OEmbed is allowed for the provided URL
297 public static function isAllowedURL($url)
299 if (!Config::get('system', 'no_oembed_rich_content')) {
303 $domain = parse_url($url, PHP_URL_HOST);
308 $str_allowed = Config::get('system', 'allowed_oembed', '');
309 if (!x($str_allowed)) {
313 $allowed = explode(',', $str_allowed);
315 return Network::isDomainAllowed($domain, $allowed);
318 public static function getHTML($url, $title = null)
320 // Always embed the SSL version
321 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
322 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
324 $o = self::fetchURL($url, !self::isAllowedURL($url));
326 if (!is_object($o) || $o->type == 'error') {
327 throw new Exception('OEmbed failed for URL: ' . $url);
334 $html = self::formatObject($o);
340 * @brief Generates the iframe HTML for an oembed attachment.
342 * Width and height are given by the remote, and are regularly too small for
343 * the generated iframe.
345 * The width is entirely discarded for the actual width of the post, while fixed
346 * height is used as a starting point before the inevitable resizing.
348 * Since the iframe is automatically resized on load, there are no need for ugly
349 * and impractical scrollbars.
351 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
353 * @param string $src Original remote URL to embed
354 * @param string $width
355 * @param string $height
356 * @return string formatted HTML
358 * @see oembed_format_object()
360 private static function iframe($src, $width, $height)
364 if (!$height || strstr($height, '%')) {
369 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
370 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . L10n::t('Embedded content') . '</iframe>';
374 * Generates an XPath query to select elements whose provided attribute contains
375 * the provided value in a space-separated list.
377 * @brief Generates attribute search XPath string
379 * @param string $attr Name of the attribute to seach
380 * @param string $value Value to search in a space-separated list
383 private static function buildXPath($attr, $value)
385 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
386 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'";
390 * Returns the inner XML string of a provided DOMNode
392 * @brief Returns the inner XML string of a provided DOMNode
394 * @param DOMNode $node
397 private static function getInnerHTML(DOMNode $node)
400 $children = $node->childNodes;
401 foreach ($children as $child) {
402 $innerHTML .= $child->ownerDocument->saveXML($child);