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 embedable
53 public static function fetchURL($embedurl, $no_rich_type = false)
55 $embedurl = trim($embedurl, "'");
56 $embedurl = trim($embedurl, '"');
60 $condition = ['url' => normalise_link($embedurl)];
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', array('url' => normalise_link($embedurl),
109 'content' => $txt, 'created' => datetime_convert()), true);
112 Cache::set($a->videowidth . $embedurl, $txt, CACHE_DAY);
116 $j = json_decode($txt);
118 if (!is_object($j)) {
122 // Always embed the SSL version
123 if (isset($j->html)) {
124 $j->html = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"), array("https://www.youtube.com/", "https://player.vimeo.com/"), $j->html);
127 $j->embedurl = $embedurl;
129 // If fetching information doesn't work, then improve via internal functions
130 if (($j->type == "error") || ($no_rich_type && ($j->type == "rich"))) {
131 $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
132 $j->type = $data["type"];
134 if ($j->type == "photo") {
135 $j->url = $data["url"];
136 //$j->width = $data["images"][0]["width"];
137 //$j->height = $data["images"][0]["height"];
140 if (isset($data["title"])) {
141 $j->title = $data["title"];
144 if (isset($data["text"])) {
145 $j->description = $data["text"];
148 if (is_array($data["images"])) {
149 $j->thumbnail_url = $data["images"][0]["src"];
150 $j->thumbnail_width = $data["images"][0]["width"];
151 $j->thumbnail_height = $data["images"][0]["height"];
155 call_hooks('oembed_fetch_url', $embedurl, $j);
160 public static function formatObject($j)
162 $embedurl = $j->embedurl;
164 $ret = '<div class="oembed ' . $j->type . '">';
167 if (isset($j->thumbnail_url)) {
168 $tw = (isset($j->thumbnail_width) && intval($j->thumbnail_width)) ? $j->thumbnail_width : 200;
169 $th = (isset($j->thumbnail_height) && intval($j->thumbnail_height)) ? $j->thumbnail_height : 180;
170 // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
171 $tr = (($th) ? $tw / $th : 1);
175 $tpl = get_markup_template('oembed_video.tpl');
176 $ret .= replace_macros($tpl, array(
177 '$baseurl' => System::baseUrl(),
178 '$embedurl' => $embedurl,
179 '$escapedhtml' => base64_encode($jhtml),
182 '$turl' => $j->thumbnail_url,
189 $ret .= '<img width="' . $j->width . '" src="' . proxy_url($j->url) . '">';
194 if (self::isAllowedURL($embedurl)) {
195 $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 (isset($j->title)) {
205 if (isset($j->provider_name)) {
206 $ret .= $j->provider_name . ": ";
209 $embedlink = (isset($j->title)) ? $j->title : $embedurl;
210 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
211 if (isset($j->author_name)) {
212 $ret .= ' (' . $j->author_name . ')';
214 } elseif (isset($j->provider_name) || isset($j->author_name)) {
216 if (isset($j->provider_name)) {
217 $embedlink .= $j->provider_name;
220 if (isset($j->author_name)) {
221 if ($embedlink != "") {
225 $embedlink .= $j->author_name;
227 if (trim($embedlink) == "") {
228 $embedlink = $embedurl;
231 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $embedlink . '</a>';
234 } elseif (!strpos($j->html, $embedurl)) {
235 // add <a> for html2bbcode conversion
236 $ret .= '<a href="' . $embedurl . '" rel="oembed">' . $j->title . '</a>';
239 $ret = str_replace("\n", "", $ret);
240 return mb_convert_encoding($ret, 'HTML-ENTITIES', mb_detect_encoding($ret));
243 public static function BBCode2HTML($text)
245 $stopoembed = Config::get("system", "no_oembed");
246 if ($stopoembed == true) {
247 return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
249 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
253 * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
254 * and replace it with [embed]url[/embed]
256 public static function HTML2BBCode($text)
258 // start parser only if 'oembed' is in text
259 if (strpos($text, "oembed")) {
261 // convert non ascii chars to html entities
262 $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
264 // If it doesn't parse at all, just return the text.
265 $dom = @DOMDocument::loadHTML($html_text);
269 $xpath = new DOMXPath($dom);
271 $xattr = self::buildXPath("class", "oembed");
272 $entries = $xpath->query("//div[$xattr]");
274 $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
275 foreach ($entries as $e) {
276 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
277 if (!is_null($href)) {
278 $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
281 return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
288 * Determines if rich content OEmbed is allowed for the provided URL
290 * @brief Determines if rich content OEmbed is allowed for the provided URL
294 public static function isAllowedURL($url)
296 if (!Config::get('system', 'no_oembed_rich_content')) {
300 $domain = parse_url($url, PHP_URL_HOST);
305 $str_allowed = Config::get('system', 'allowed_oembed', '');
306 if (!x($str_allowed)) {
310 $allowed = explode(',', $str_allowed);
312 return allowed_domain($domain, $allowed);
315 public static function getHTML($url, $title = null)
317 // Always embed the SSL version
318 $url = str_replace(array("http://www.youtube.com/", "http://player.vimeo.com/"),
319 array("https://www.youtube.com/", "https://player.vimeo.com/"), $url);
321 $o = OEmbed::fetchURL($url);
323 if (!is_object($o) || $o->type == 'error') {
324 throw new Exception('OEmbed failed for URL: ' . $url);
331 $html = OEmbed::formatObject($o);
337 * @brief Generates the iframe HTML for an oembed attachment.
339 * Width and height are given by the remote, and are regularly too small for
340 * the generated iframe.
342 * The width is entirely discarded for the actual width of the post, while fixed
343 * height is used as a starting point before the inevitable resizing.
345 * Since the iframe is automatically resized on load, there are no need for ugly
346 * and impractical scrollbars.
348 * @todo This function is currently unused until someoneā¢ adds support for a separate OEmbed domain
350 * @param string $src Original remote URL to embed
351 * @param string $width
352 * @param string $height
353 * @return string formatted HTML
355 * @see oembed_format_object()
357 private static function iframe($src, $width, $height)
361 if (!$height || strstr($height, '%')) {
366 $src = System::baseUrl() . '/oembed/' . base64url_encode($src);
367 return '<iframe onload="resizeIframe(this);" class="embed_rich" height="' . $height . '" width="' . $width . '" src="' . $src . '" allowfullscreen scrolling="no" frameborder="no">' . t('Embedded content') . '</iframe>';
371 * Generates an XPath query to select elements whose provided attribute contains
372 * the provided value in a space-separated list.
374 * @brief Generates attribute search XPath string
376 * @param string $attr Name of the attribute to seach
377 * @param string $value Value to search in a space-separated list
380 private static function buildXPath($attr, $value)
382 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
383 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'";
387 * Returns the inner XML string of a provided DOMNode
389 * @brief Returns the inner XML string of a provided DOMNode
391 * @param DOMNode $node
394 private static function getInnerHTML(DOMNode $node)
397 $children = $node->childNodes;
398 foreach ($children as $child) {
399 $innerHTML .= $child->ownerDocument->saveXML($child);