4 * @file src/Content/OEmbed.php
6 namespace Friendica\Content;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Util\Network;
15 use Friendica\Util\ParseUrl;
16 use Friendica\Util\Temporal;
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 (DBM::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 ($j->type != "error") {
112 dba::insert('oembed', [
113 'url' => normalise_link($embedurl),
114 'maxwidth' => $a->videowidth,
116 'created' => Temporal::convert()
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($j)
168 $embedurl = $j->embedurl;
170 $ret = '<div class="oembed ' . $j->type . '">';
173 if (isset($j->thumbnail_url)) {
174 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
175 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->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' => $embedurl,
185 '$escapedhtml' => base64_encode($jhtml),
188 '$turl' => $j->thumbnail_url,
195 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
200 $ret .= proxy_parse_html($jhtml);
204 // add link to source if not present in "rich" type
205 if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
207 if (!empty($j->title)) {
208 if (!empty($j->provider_name)) {
209 $ret .= $j->provider_name . ": ";
212 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
213 if (!empty($j->author_name)) {
214 $ret .= ' (' . $j->author_name . ')';
216 } elseif (!empty($j->provider_name) || !empty($j->author_name)) {
218 if (!empty($j->provider_name)) {
219 $embedlink .= $j->provider_name;
222 if (!empty($j->author_name)) {
223 if ($embedlink != "") {
227 $embedlink .= $j->author_name;
229 if (trim($embedlink) == "") {
230 $embedlink = $embedurl;
233 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
235 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedurl . '</a>';
238 } elseif (!strpos($j->html, $embedurl)) {
239 // add <a> for html2bbcode conversion
240 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
245 $ret = str_replace("\n", "", $ret);
246 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
249 public static function BBCode2HTML($text)
251 $stopoembed = Config::get("system", "no_oembed");
252 if ($stopoembed == true) {
253 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . L10n::t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
255 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
259 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
260 * and replace it with [embed]url[/embed]
262 public static function HTML2BBCode($text)
264 // start parser only if 'oembed' is in text
265 if (strpos($text, "oembed")) {
267 // convert non ascii chars to html entities
268 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
270 // If it doesn't parse at all, just return the text.
271 $dom = @DOMDocument::loadHTML($html_text);
275 $xpath = new DOMXPath($dom);
277 $xattr = self::buildXPath("class", "oembed");
278 $entries = $xpath->query("//div[$xattr]");
280 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
281 foreach ($entries as $e) {
282 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
283 if (!is_null($href)) {
284 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
287 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
294 * Determines if rich content OEmbed is allowed for the provided URL
296 * @brief Determines if rich content OEmbed is allowed for the provided URL
300 public static function isAllowedURL($url)
302 if (!Config::get('system', 'no_oembed_rich_content')) {
306 $domain = parse_url($url, PHP_URL_HOST);
311 $str_allowed = Config::get('system', 'allowed_oembed', '');
312 if (!x($str_allowed)) {
316 $allowed = explode(',', $str_allowed);
318 return Network::isDomainAllowed($domain, $allowed);
321 public static function getHTML($url, $title = null)
323 // Always embed the SSL version
324 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
325 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
327 $o = self::fetchURL($url, !self::isAllowedURL($url));
329 if (!is_object($o) || $o->type == 'error') {
330 throw new Exception('OEmbed failed for URL: ' . $url);
337 $html = self::formatObject($o);
343 * @brief Generates the iframe HTML for an oembed attachment.
345 * Width and height are given by the remote, and are regularly too small for
346 * the generated iframe.
348 * The width is entirely discarded for the actual width of the post, while fixed
349 * height is used as a starting point before the inevitable resizing.
351 * Since the iframe is automatically resized on load, there are no need for ugly
352 * and impractical scrollbars.
354 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
356 * @param string $src Original remote URL to embed
357 * @param string $width
358 * @param string $height
359 * @return string formatted HTML
361 * @see oembed_format_object()
363 private static function iframe($src, $width, $height)
367 if (!$height || strstr($height, '%')) {
372 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
373 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . L10n::t('Embedded content') . '</iframe>';
377 * Generates an XPath query to select elements whose provided attribute contains
378 * the provided value in a space-separated list.
380 * @brief Generates attribute search XPath string
382 * @param string $attr Name of the attribute to seach
383 * @param string $value Value to search in a space-separated list
386 private static function buildXPath($attr, $value)
388 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
389 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'";
393 * Returns the inner XML string of a provided DOMNode
395 * @brief Returns the inner XML string of a provided DOMNode
397 * @param DOMNode $node
400 private static function getInnerHTML(DOMNode $node)
403 $children = $node->childNodes;
404 foreach ($children as $child) {
405 $innerHTML .= $child->ownerDocument->saveXML($child);