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;
24 require_once 'include/dba.php';
25 require_once 'mod/proxy.php';
28 * Handles all OEmbed content fetching and replacement
30 * OEmbed is a standard used to allow an embedded representation of a URL on
33 * @see https://oembed.com
35 * @author Hypolite Petovan <mrpetovan@gmail.com>
39 public static function replaceCallback($matches)
41 $embedurl = $matches[1];
42 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
43 $s = self::formatObject($j);
49 * @brief Get data from an URL to embed its content.
51 * @param string $embedurl The URL from which the data should be fetched.
52 * @param bool $no_rich_type If set to true rich type content won't be fetched.
54 * @return bool|object Returns object with embed content or false if no embeddable
57 public static function fetchURL($embedurl, $no_rich_type = false)
59 $embedurl = trim($embedurl, "'");
60 $embedurl = trim($embedurl, '"');
64 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
65 $oembed = DBA::selectFirst('oembed', ['content'], $condition);
66 if (DBA::is_result($oembed)) {
67 $txt = $oembed["content"];
69 $txt = Cache::get($a->videowidth . $embedurl);
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
74 $noexts = ["mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm"];
75 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
81 if (!in_array($ext, $noexts)) {
82 // try oembed autodiscovery
84 $html_text = Network::fetchUrl($embedurl, false, $redirects, 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 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
95 $entries = $xpath->query("//link[@type='text/json+oembed']");
96 foreach ($entries as $e) {
97 $href = $e->getAttributeNode("href")->nodeValue;
98 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
107 if (!$txt || $txt[0] != "{") {
108 $txt = '{"type":"error"}';
109 } else { //save in cache
110 $j = json_decode($txt);
111 if (!empty($j->type) && $j->type != "error") {
112 DBA::insert('oembed', [
113 'url' => normalise_link($embedurl),
114 'maxwidth' => $a->videowidth,
116 'created' => DateTimeFormat::utcNow()
120 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
124 $j = json_decode($txt);
126 if (!is_object($j)) {
130 // Always embed the SSL version
131 if (isset($j->html)) {
132 $j->html = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"], ["https://www.youtube.com/", "https://player.vimeo.com/"], $j->html);
135 $j->embedurl = $embedurl;
137 // If fetching information doesn't work, then improve via internal functions
138 if ($no_rich_type && ($j->type == "rich")) {
139 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
140 $j->type = $data["type"];
142 if ($j->type == "photo") {
143 $j->url = $data["url"];
146 if (isset($data["title"])) {
147 $j->title = $data["title"];
150 if (isset($data["text"])) {
151 $j->description = $data["text"];
154 if (is_array($data["images"])) {
155 $j->thumbnail_url = $data["images"][0]["src"];
156 $j->thumbnail_width = $data["images"][0]["width"];
157 $j->thumbnail_height = $data["images"][0]["height"];
161 Addon::callHooks('oembed_fetch_url', $embedurl, $j);
166 private static function formatObject(stdClass $j)
168 $embedurl = $j->embedurl;
170 $ret = '<div class="oembed ' . $j->type . '">';
174 if (isset($j->thumbnail_url)) {
175 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
176 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;
177 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
178 $tr = (($th) ? $tw / $th : 1);
182 $tpl = get_markup_template('oembed_video.tpl');
183 $ret .= replace_macros($tpl, [
184 '$baseurl' => System::baseUrl(),
185 '$embedurl' => $embedurl,
186 '$escapedhtml' => base64_encode($jhtml),
189 '$turl' => $j->thumbnail_url,
196 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
201 $ret .= proxy_parse_html($jhtml);
205 // add link to source if not present in "rich" type
206 if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
208 if (!empty($j->title)) {
209 if (!empty($j->provider_name)) {
210 $ret .= $j->provider_name . ": ";
213 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
214 if (!empty($j->author_name)) {
215 $ret .= ' (' . $j->author_name . ')';
217 } elseif (!empty($j->provider_name) || !empty($j->author_name)) {
219 if (!empty($j->provider_name)) {
220 $embedlink .= $j->provider_name;
223 if (!empty($j->author_name)) {
224 if ($embedlink != "") {
228 $embedlink .= $j->author_name;
230 if (trim($embedlink) == "") {
231 $embedlink = $embedurl;
234 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
236 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedurl . '</a>';
239 } elseif (!strpos($j->html, $embedurl)) {
240 // add <a> for html2bbcode conversion
241 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
246 $ret = str_replace("\n", "", $ret);
247 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
250 public static function BBCode2HTML($text)
252 $stopoembed = Config::get("system", "no_oembed");
253 if ($stopoembed == true) {
254 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . L10n::t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
256 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
260 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
261 * and replace it with [embed]url[/embed]
263 public static function HTML2BBCode($text)
265 // start parser only if 'oembed' is in text
266 if (strpos($text, "oembed")) {
268 // convert non ascii chars to html entities
269 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
271 // If it doesn't parse at all, just return the text.
272 $dom = @DOMDocument::loadHTML($html_text);
276 $xpath = new DOMXPath($dom);
278 $xattr = self::buildXPath("class", "oembed");
279 $entries = $xpath->query("//div[$xattr]");
281 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
282 foreach ($entries as $e) {
283 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
284 if (!is_null($href)) {
285 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
288 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
295 * Determines if rich content OEmbed is allowed for the provided URL
297 * @brief Determines if rich content OEmbed is allowed for the provided URL
301 public static function isAllowedURL($url)
303 if (!Config::get('system', 'no_oembed_rich_content')) {
307 $domain = parse_url($url, PHP_URL_HOST);
312 $str_allowed = Config::get('system', 'allowed_oembed', '');
313 if (!x($str_allowed)) {
317 $allowed = explode(',', $str_allowed);
319 return Network::isDomainAllowed($domain, $allowed);
322 public static function getHTML($url, $title = null)
324 // Always embed the SSL version
325 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
326 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
328 $o = self::fetchURL($url, !self::isAllowedURL($url));
330 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
331 throw new Exception('OEmbed failed for URL: ' . $url);
338 $html = self::formatObject($o);
344 * @brief Generates the iframe HTML for an oembed attachment.
346 * Width and height are given by the remote, and are regularly too small for
347 * the generated iframe.
349 * The width is entirely discarded for the actual width of the post, while fixed
350 * height is used as a starting point before the inevitable resizing.
352 * Since the iframe is automatically resized on load, there are no need for ugly
353 * and impractical scrollbars.
355 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
357 * @param string $src Original remote URL to embed
358 * @param string $width
359 * @param string $height
360 * @return string formatted HTML
362 * @see oembed_format_object()
364 private static function iframe($src, $width, $height)
368 if (!$height || strstr($height, '%')) {
373 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
374 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . L10n::t('Embedded content') . '</iframe>';
378 * Generates an XPath query to select elements whose provided attribute contains
379 * the provided value in a space-separated list.
381 * @brief Generates attribute search XPath string
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 * @brief Returns the inner XML string of a provided DOMNode
398 * @param DOMNode $node
401 private static function getInnerHTML(DOMNode $node)
404 $children = $node->childNodes;
405 foreach ($children as $child) {
406 $innerHTML .= $child->ownerDocument->saveXML($child);