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\DateTimeFormat;
15 use Friendica\Util\Network;
16 use Friendica\Util\ParseUrl;
25 require_once 'include/dba.php';
26 require_once 'mod/proxy.php';
29 * Handles all OEmbed content fetching and replacement
31 * OEmbed is a standard used to allow an embedded representation of a URL on
34 * @see https://oembed.com
36 * @author Hypolite Petovan <mrpetovan@gmail.com>
40 public static function replaceCallback($matches)
42 $embedurl = $matches[1];
43 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
44 $s = self::formatObject($j);
50 * @brief Get data from an URL to embed its content.
52 * @param string $embedurl The URL from which the data should be fetched.
53 * @param bool $no_rich_type If set to true rich type content won't be fetched.
55 * @return bool|object Returns object with embed content or false if no embeddable
58 public static function fetchURL($embedurl, $no_rich_type = false)
60 $embedurl = trim($embedurl, "'");
61 $embedurl = trim($embedurl, '"');
65 $condition = ['url' => normalise_link($embedurl), 'maxwidth' => $a->videowidth];
66 $oembed = dba::selectFirst('oembed', ['content'], $condition);
67 if (DBM::is_result($oembed)) {
68 $txt = $oembed["content"];
70 $txt = Cache::get($a->videowidth . $embedurl);
72 // These media files should now be caught in bbcode.php
73 // left here as a fallback in case this is called from another source
75 $noexts = ["mp3", "mp4", "ogg", "ogv", "oga", "ogm", "webm"];
76 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
82 if (!in_array($ext, $noexts)) {
83 // try oembed autodiscovery
85 $html_text = Network::fetchUrl($embedurl, false, $redirects, 15, "text/*");
87 $dom = @DOMDocument::loadHTML($html_text);
89 $xpath = new DOMXPath($dom);
90 $entries = $xpath->query("//link[@type='application/json+oembed']");
91 foreach ($entries as $e) {
92 $href = $e->getAttributeNode("href")->nodeValue;
93 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
96 $entries = $xpath->query("//link[@type='text/json+oembed']");
97 foreach ($entries as $e) {
98 $href = $e->getAttributeNode("href")->nodeValue;
99 $txt = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
108 if (!$txt || $txt[0] != "{") {
109 $txt = '{"type":"error"}';
110 } else { //save in cache
111 $j = json_decode($txt);
112 if (!empty($j->type) && $j->type != "error") {
113 dba::insert('oembed', [
114 'url' => normalise_link($embedurl),
115 'maxwidth' => $a->videowidth,
117 'created' => DateTimeFormat::utcNow()
121 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
125 $j = json_decode($txt);
127 if (!is_object($j)) {
131 // Always embed the SSL version
132 if (isset($j->html)) {
133 $j->html = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"], ["https://www.youtube.com/", "https://player.vimeo.com/"], $j->html);
136 $j->embedurl = $embedurl;
138 // If fetching information doesn't work, then improve via internal functions
139 if ($no_rich_type && ($j->type == "rich")) {
140 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
141 $j->type = $data["type"];
143 if ($j->type == "photo") {
144 $j->url = $data["url"];
147 if (isset($data["title"])) {
148 $j->title = $data["title"];
151 if (isset($data["text"])) {
152 $j->description = $data["text"];
155 if (is_array($data["images"])) {
156 $j->thumbnail_url = $data["images"][0]["src"];
157 $j->thumbnail_width = $data["images"][0]["width"];
158 $j->thumbnail_height = $data["images"][0]["height"];
162 Addon::callHooks('oembed_fetch_url', $embedurl, $j);
167 private static function formatObject(stdClass $j)
169 $embedurl = $j->embedurl;
171 $ret = '<div class="oembed ' . $j->type . '">';
175 if (isset($j->thumbnail_url)) {
176 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
177 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;
178 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
179 $tr = (($th) ? $tw / $th : 1);
183 $tpl = get_markup_template('oembed_video.tpl');
184 $ret .= replace_macros($tpl, [
185 '$baseurl' => System::baseUrl(),
186 '$embedurl' => $embedurl,
187 '$escapedhtml' => base64_encode($jhtml),
190 '$turl' => $j->thumbnail_url,
197 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
202 $ret .= proxy_parse_html($jhtml);
206 // add link to source if not present in "rich" type
207 if ($j->type != 'rich' || !strpos($j->html, $embedurl)) {
209 if (!empty($j->title)) {
210 if (!empty($j->provider_name)) {
211 $ret .= $j->provider_name . ": ";
214 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
215 if (!empty($j->author_name)) {
216 $ret .= ' (' . $j->author_name . ')';
218 } elseif (!empty($j->provider_name) || !empty($j->author_name)) {
220 if (!empty($j->provider_name)) {
221 $embedlink .= $j->provider_name;
224 if (!empty($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>';
237 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedurl . '</a>';
240 } elseif (!strpos($j->html, $embedurl)) {
241 // add <a> for html2bbcode conversion
242 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
247 $ret = str_replace("\n", "", $ret);
248 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
251 public static function BBCode2HTML($text)
253 $stopoembed = Config::get("system", "no_oembed");
254 if ($stopoembed == true) {
255 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . L10n::t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
257 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
261 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
262 * and replace it with [embed]url[/embed]
264 public static function HTML2BBCode($text)
266 // start parser only if 'oembed' is in text
267 if (strpos($text, "oembed")) {
269 // convert non ascii chars to html entities
270 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
272 // If it doesn't parse at all, just return the text.
273 $dom = @DOMDocument::loadHTML($html_text);
277 $xpath = new DOMXPath($dom);
279 $xattr = self::buildXPath("class", "oembed");
280 $entries = $xpath->query("//div[$xattr]");
282 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
283 foreach ($entries as $e) {
284 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
285 if (!is_null($href)) {
286 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
289 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
296 * Determines if rich content OEmbed is allowed for the provided URL
298 * @brief Determines if rich content OEmbed is allowed for the provided URL
302 public static function isAllowedURL($url)
304 if (!Config::get('system', 'no_oembed_rich_content')) {
308 $domain = parse_url($url, PHP_URL_HOST);
313 $str_allowed = Config::get('system', 'allowed_oembed', '');
314 if (!x($str_allowed)) {
318 $allowed = explode(',', $str_allowed);
320 return Network::isDomainAllowed($domain, $allowed);
323 public static function getHTML($url, $title = null)
325 // Always embed the SSL version
326 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
327 ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
329 $o = self::fetchURL($url, !self::isAllowedURL($url));
331 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
332 throw new Exception('OEmbed failed for URL: ' . $url);
339 $html = self::formatObject($o);
345 * @brief Generates the iframe HTML for an oembed attachment.
347 * Width and height are given by the remote, and are regularly too small for
348 * the generated iframe.
350 * The width is entirely discarded for the actual width of the post, while fixed
351 * height is used as a starting point before the inevitable resizing.
353 * Since the iframe is automatically resized on load, there are no need for ugly
354 * and impractical scrollbars.
356 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
358 * @param string $src Original remote URL to embed
359 * @param string $width
360 * @param string $height
361 * @return string formatted HTML
363 * @see oembed_format_object()
365 private static function iframe($src, $width, $height)
369 if (!$height || strstr($height, '%')) {
374 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
375 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . L10n::t('Embedded content') . '</iframe>';
379 * Generates an XPath query to select elements whose provided attribute contains
380 * the provided value in a space-separated list.
382 * @brief Generates attribute search XPath string
384 * @param string $attr Name of the attribute to seach
385 * @param string $value Value to search in a space-separated list
388 private static function buildXPath($attr, $value)
390 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
391 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'";
395 * Returns the inner XML string of a provided DOMNode
397 * @brief Returns the inner XML string of a provided DOMNode
399 * @param DOMNode $node
402 private static function getInnerHTML(DOMNode $node)
405 $children = $node->childNodes;
406 foreach ($children as $child) {
407 $innerHTML .= $child->ownerDocument->saveXML($child);