4 * @file src/Content/OEmbed.php
7 namespace Friendica\Content;
9 use Friendica\Core\Cache;
10 use Friendica\Core\System;
11 use Friendica\Core\Config;
12 use Friendica\Database\DBM;
13 use Friendica\Util\ParseUrl;
20 require_once 'include/dba.php';
21 require_once 'mod/proxy.php';
24 * Handles all OEmbed content fetching and replacement
26 * OEmbed is a standard used to allow an embedded representation of a URL on
29 * @see https://oembed.com
31 * @author Hypolite Petovan <mrpetovan@gmail.com>
35 public static function replaceCallback($matches)
37 $embedurl = $matches[1];
38 $j = self::fetchURL($embedurl);
39 $s = self::formatObject($j);
45 * @brief Get data from an URL to embed its content.
47 * @param string $embedurl The URL from which the data should be fetched.
48 * @param bool $no_rich_type If set to true rich type content won't be fetched.
50 * @return bool|object Returns object with embed content or false if no embeddable
53 public static function fetchURL($embedurl, $no_rich_type = false)
55 $embedurl = trim($embedurl, "'");
56 $embedurl = trim($embedurl, '"');
60 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
61 $r = dba::selectFirst('oembed', ['content'], $condition);
62 if (DBM::is_result($r)) {
65 $txt = Cache::get($a->videowidth . $embedurl);
67 // These media files should now be caught in bbcode.php
68 // left here as a fallback in case this is called from another source
70 $noexts = array("mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm");
71 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
77 if (!in_array($ext, $noexts)) {
78 // try oembed autodiscovery
80 $html_text = fetch_url($embedurl, false, $redirects, 15, "text/*");
82 $dom = @DOMDocument::loadHTML($html_text);
84 $xpath = new DOMXPath($dom);
85 $entries = $xpath->query("//link[@type='application/json+oembed']");
86 foreach ($entries as $e) {
87 $href = $e->getAttributeNode("href")->nodeValue;
88 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
91 $entries = $xpath->query("//link[@type='text/json+oembed']");
92 foreach ($entries as $e) {
93 $href = $e->getAttributeNode("href")->nodeValue;
94 $txt = fetch_url($href . '&maxwidth=' . $a->videowidth);
103 if (!$txt || $txt[0] != "{") {
104 $txt = '{"type":"error"}';
105 } else { //save in cache
106 $j = json_decode($txt);
107 if ($j->type != "error") {
108 dba::insert('oembed', [
109 'url' => normalise_link($embedurl),
110 'maxwidth' => $a->videowidth,
112 'created' => datetime_convert()
116 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
120 $j = json_decode($txt);
122 if (!is_object($j)) {
126 // Always embed the SSL version
127 if (isset($j->html)) {
128 $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
131 $j->embedurl = $embedurl;
133 // If fetching information doesn't work, then improve via internal functions
134 if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
135 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
136 $j->type = $data["type"];
138 if ($j->type == "photo") {
139 $j->url = $data["url"];
140 //$j->width = $data["images"][0]["width"];
141 //$j->height = $data["images"][0]["height"];
144 if (isset($data["title"])) {
145 $j->title = $data["title"];
148 if (isset($data["text"])) {
149 $j->description = $data["text"];
152 if (is_array($data["images"])) {
153 $j->thumbnail_url = $data["images"][0]["src"];
154 $j->thumbnail_width = $data["images"][0]["width"];
155 $j->thumbnail_height = $data["images"][0]["height"];
159 call_hooks('oembed_fetch_url', $embedurl, $j);
164 public static function formatObject($j)
166 $embedurl = $j->embedurl;
168 $ret = '<div class="oembed ' . $j->type . '">';
171 if (isset($j->thumbnail_url)) {
172 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
173 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->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 = get_markup_template('oembed_video.tpl');
180 $ret .= replace_macros($tpl, array(
181 '$baseurl' => System::baseUrl(),
182 '$embedurl' => $embedurl,
183 '$escapedhtml' => base64_encode($jhtml),
186 '$turl' => $j->thumbnail_url,
193 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
198 if (self::isAllowedURL($embedurl)) {
199 $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 (isset($j->title)) {
209 if (isset($j->provider_name)) {
210 $ret .= $j->provider_name . ": ";
213 $embedlink = (isset($j->title)) ? $j->title : $embedurl;
214 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
215 if (isset($j->author_name)) {
216 $ret .= ' (' . $j->author_name . ')';
218 } elseif (isset($j->provider_name) || isset($j->author_name)) {
220 if (isset($j->provider_name)) {
221 $embedlink .= $j->provider_name;
224 if (isset($j->author_name)) {
225 if ($embedlink != "") {
229 $embedlink .= $j->author_name;
231 if (trim($embedlink) == "") {
232 $embedlink = $embedurl;
235 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
238 } elseif (!strpos($j->html, $embedurl)) {
239 // add <a> for html2bbcode conversion
240 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
243 $ret = str_replace("\n", "", $ret);
244 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
247 public static function BBCode2HTML($text)
249 $stopoembed = Config::get("system", "no_oembed");
250 if ($stopoembed == true) {
251 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
253 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
257 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
258 * and replace it with [embed]url[/embed]
260 public static function HTML2BBCode($text)
262 // start parser only if 'oembed' is in text
263 if (strpos($text, "oembed")) {
265 // convert non ascii chars to html entities
266 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
268 // If it doesn't parse at all, just return the text.
269 $dom = @DOMDocument::loadHTML($html_text);
273 $xpath = new DOMXPath($dom);
275 $xattr = self::buildXPath("class", "oembed");
276 $entries = $xpath->query("//div[$xattr]");
278 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
279 foreach ($entries as $e) {
280 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
281 if (!is_null($href)) {
282 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
285 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
292 * Determines if rich content OEmbed is allowed for the provided URL
294 * @brief Determines if rich content OEmbed is allowed for the provided URL
298 public static function isAllowedURL($url)
300 if (!Config::get('system', 'no_oembed_rich_content')) {
304 $domain = parse_url($url, PHP_URL_HOST);
309 $str_allowed = Config::get('system', 'allowed_oembed', '');
310 if (!x($str_allowed)) {
314 $allowed = explode(',', $str_allowed);
316 return allowed_domain($domain, $allowed);
319 public static function getHTML($url, $title = null)
321 // Always embed the SSL version
322 $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
323 array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
325 $o = OEmbed::fetchURL($url);
327 if (!is_object($o) || $o->type == 'error') {
328 throw new Exception('OEmbed failed for URL: ' . $url);
335 $html = OEmbed::formatObject($o);
341 * @brief Generates the iframe HTML for an oembed attachment.
343 * Width and height are given by the remote, and are regularly too small for
344 * the generated iframe.
346 * The width is entirely discarded for the actual width of the post, while fixed
347 * height is used as a starting point before the inevitable resizing.
349 * Since the iframe is automatically resized on load, there are no need for ugly
350 * and impractical scrollbars.
352 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
354 * @param string $src Original remote URL to embed
355 * @param string $width
356 * @param string $height
357 * @return string formatted HTML
359 * @see oembed_format_object()
361 private static function iframe($src, $width, $height)
365 if (!$height || strstr($height, '%')) {
370 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
371 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
375 * Generates an XPath query to select elements whose provided attribute contains
376 * the provided value in a space-separated list.
378 * @brief Generates attribute search XPath string
380 * @param string $attr Name of the attribute to seach
381 * @param string $value Value to search in a space-separated list
384 private static function buildXPath($attr, $value)
386 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
387 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'";
391 * Returns the inner XML string of a provided DOMNode
393 * @brief Returns the inner XML string of a provided DOMNode
395 * @param DOMNode $node
398 private static function getInnerHTML(DOMNode $node)
401 $children = $node->childNodes;
402 foreach ($children as $child) {
403 $innerHTML .= $child->ownerDocument->saveXML($child);