]> git.mxchange.org Git - friendica.git/blob - src/Content/OEmbed.php
Add Trending Tags widget + template
[friendica.git] / src / Content / OEmbed.php
1 <?php
2
3 /**
4  * @file src/Content/OEmbed.php
5  */
6 namespace Friendica\Content;
7
8 use DOMDocument;
9 use DOMNode;
10 use DOMText;
11 use DOMXPath;
12 use Exception;
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Renderer;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Network;
22 use Friendica\Util\ParseUrl;
23 use Friendica\Util\Proxy as ProxyUtils;
24 use Friendica\Util\Strings;
25
26 /**
27  * Handles all OEmbed content fetching and replacement
28  *
29  * OEmbed is a standard used to allow an embedded representation of a URL on
30  * third party sites
31  *
32  * @see https://oembed.com
33  *
34  * @author Hypolite Petovan <hypolite@mrpetovan.com>
35  */
36 class OEmbed
37 {
38         public static function replaceCallback($matches)
39         {
40                 $embedurl = $matches[1];
41                 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
42                 $s = self::formatObject($j);
43
44                 return $s;
45         }
46
47         /**
48          * @brief Get data from an URL to embed its content.
49          *
50          * @param string $embedurl     The URL from which the data should be fetched.
51          * @param bool   $no_rich_type If set to true rich type content won't be fetched.
52          *
53          * @return \Friendica\Object\OEmbed
54          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55          */
56         public static function fetchURL($embedurl, $no_rich_type = false)
57         {
58                 $embedurl = trim($embedurl, '\'"');
59
60                 $a = \get_app();
61
62                 $cache_key = 'oembed:' . $a->videowidth . ':' . $embedurl;
63
64                 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->videowidth];
65                 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
66                 if (DBA::isResult($oembed_record)) {
67                         $json_string = $oembed_record['content'];
68                 } else {
69                         $json_string = Cache::get($cache_key);
70                 }
71
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
74                 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
75                 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
76
77                 $oembed = new \Friendica\Object\OEmbed($embedurl);
78
79                 if ($json_string) {
80                         $oembed->parseJSON($json_string);
81                 } else {
82                         $json_string = '';
83
84                         if (!in_array($ext, $noexts)) {
85                                 // try oembed autodiscovery
86                                 $html_text = Network::fetchUrl($embedurl, false, 15, 'text/*');
87                                 if ($html_text) {
88                                         $dom = @DOMDocument::loadHTML($html_text);
89                                         if ($dom) {
90                                                 $xpath = new DOMXPath($dom);
91                                                 $entries = $xpath->query("//link[@type='application/json+oembed']");
92                                                 foreach ($entries as $e) {
93                                                         $href = $e->getAttributeNode('href')->nodeValue;
94                                                         $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
95                                                         break;
96                                                 }
97
98                                                 $entries = $xpath->query("//link[@type='text/json+oembed']");
99                                                 foreach ($entries as $e) {
100                                                         $href = $e->getAttributeNode('href')->nodeValue;
101                                                         $json_string = Network::fetchUrl($href . '&maxwidth=' . $a->videowidth);
102                                                         break;
103                                                 }
104                                         }
105                                 }
106                         }
107
108                         $json_string = trim($json_string);
109
110                         if (!$json_string || $json_string[0] != '{') {
111                                 $json_string = '{"type":"error"}';
112                         }
113
114                         $oembed->parseJSON($json_string);
115
116                         if (!empty($oembed->type) && $oembed->type != 'error') {
117                                 DBA::insert('oembed', [
118                                         'url' => Strings::normaliseLink($embedurl),
119                                         'maxwidth' => $a->videowidth,
120                                         'content' => $json_string,
121                                         'created' => DateTimeFormat::utcNow()
122                                 ], true);
123                                 $cache_ttl = Cache::DAY;
124                         } else {
125                                 $cache_ttl = Cache::FIVE_MINUTES;
126                         }
127
128                         Cache::set($cache_key, $json_string, $cache_ttl);
129                 }
130
131                 if ($oembed->type == 'error') {
132                         return $oembed;
133                 }
134
135                 // Always embed the SSL version
136                 $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
137
138                 // If fetching information doesn't work, then improve via internal functions
139                 if ($no_rich_type && ($oembed->type == 'rich')) {
140                         $data = ParseUrl::getSiteinfoCached($embedurl, true, false);
141                         $oembed->type = $data['type'];
142
143                         if ($oembed->type == 'photo') {
144                                 $oembed->url = $data['url'];
145                         }
146
147                         if (isset($data['title'])) {
148                                 $oembed->title = $data['title'];
149                         }
150
151                         if (isset($data['text'])) {
152                                 $oembed->description = $data['text'];
153                         }
154
155                         if (!empty($data['images'])) {
156                                 $oembed->thumbnail_url = $data['images'][0]['src'];
157                                 $oembed->thumbnail_width = $data['images'][0]['width'];
158                                 $oembed->thumbnail_height = $data['images'][0]['height'];
159                         }
160                 }
161
162                 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
163
164                 return $oembed;
165         }
166
167         private static function formatObject(\Friendica\Object\OEmbed $oembed)
168         {
169                 $ret = '<div class="oembed ' . $oembed->type . '">';
170
171                 switch ($oembed->type) {
172                         case "video":
173                                 if ($oembed->thumbnail_url) {
174                                         $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
175                                         $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->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);
178
179                                         $th = 120;
180                                         $tw = $th * $tr;
181                                         $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
182                                         $ret .= Renderer::replaceMacros($tpl, [
183                                                 '$embedurl' => $oembed->embed_url,
184                                                 '$escapedhtml' => base64_encode($oembed->html),
185                                                 '$tw' => $tw,
186                                                 '$th' => $th,
187                                                 '$turl' => $oembed->thumbnail_url,
188                                         ]);
189                                 } else {
190                                         $ret = $oembed->html;
191                                 }
192                                 break;
193
194                         case "photo":
195                                 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
196                                 break;
197
198                         case "link":
199                                 break;
200
201                         case "rich":
202                                 $ret .= ProxyUtils::proxifyHtml($oembed->html);
203                                 break;
204                 }
205
206                 // add link to source if not present in "rich" type
207                 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
208                         $ret .= '<h4>';
209                         if (!empty($oembed->title)) {
210                                 if (!empty($oembed->provider_name)) {
211                                         $ret .= $oembed->provider_name . ": ";
212                                 }
213
214                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
215                                 if (!empty($oembed->author_name)) {
216                                         $ret .= ' (' . $oembed->author_name . ')';
217                                 }
218                         } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
219                                 $embedlink = "";
220                                 if (!empty($oembed->provider_name)) {
221                                         $embedlink .= $oembed->provider_name;
222                                 }
223
224                                 if (!empty($oembed->author_name)) {
225                                         if ($embedlink != "") {
226                                                 $embedlink .= ": ";
227                                         }
228
229                                         $embedlink .= $oembed->author_name;
230                                 }
231                                 if (trim($embedlink) == "") {
232                                         $embedlink = $oembed->embed_url;
233                                 }
234
235                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
236                         } else {
237                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
238                         }
239                         $ret .= "</h4>";
240                 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
241                         // add <a> for html2bbcode conversion
242                         $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
243                 }
244
245                 $ret .= '</div>';
246
247                 return str_replace("\n", "", $ret);
248         }
249
250         public static function BBCode2HTML($text)
251         {
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);
255                 }
256                 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
257         }
258
259         /**
260          * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
261          * and replace it with [embed]url[/embed]
262          *
263          * @param $text
264          * @return string
265          */
266         public static function HTML2BBCode($text)
267         {
268                 // start parser only if 'oembed' is in text
269                 if (strpos($text, "oembed")) {
270
271                         // convert non ascii chars to html entities
272                         $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
273
274                         // If it doesn't parse at all, just return the text.
275                         $dom = @DOMDocument::loadHTML($html_text);
276                         if (!$dom) {
277                                 return $text;
278                         }
279                         $xpath = new DOMXPath($dom);
280
281                         $xattr = self::buildXPath("class", "oembed");
282                         $entries = $xpath->query("//div[$xattr]");
283
284                         $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
285                         foreach ($entries as $e) {
286                                 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
287                                 if (!is_null($href)) {
288                                         $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
289                                 }
290                         }
291                         return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
292                 } else {
293                         return $text;
294                 }
295         }
296
297         /**
298          * Determines if rich content OEmbed is allowed for the provided URL
299          *
300          * @brief Determines if rich content OEmbed is allowed for the provided URL
301          * @param string $url
302          * @return boolean
303          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
304          */
305         public static function isAllowedURL($url)
306         {
307                 if (!Config::get('system', 'no_oembed_rich_content')) {
308                         return true;
309                 }
310
311                 $domain = parse_url($url, PHP_URL_HOST);
312                 if (empty($domain)) {
313                         return false;
314                 }
315
316                 $str_allowed = Config::get('system', 'allowed_oembed', '');
317                 if (empty($str_allowed)) {
318                         return false;
319                 }
320
321                 $allowed = explode(',', $str_allowed);
322
323                 return Network::isDomainAllowed($domain, $allowed);
324         }
325
326         public static function getHTML($url, $title = null)
327         {
328                 // Always embed the SSL version
329                 $url = str_replace(["http://www.youtube.com/", "http://player.vimeo.com/"],
330                                         ["https://www.youtube.com/", "https://player.vimeo.com/"], $url);
331
332                 $o = self::fetchURL($url, !self::isAllowedURL($url));
333
334                 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
335                         throw new Exception('OEmbed failed for URL: ' . $url);
336                 }
337
338                 if (!empty($title)) {
339                         $o->title = $title;
340                 }
341
342                 $html = self::formatObject($o);
343
344                 return $html;
345         }
346
347         /**
348          * @brief Generates the iframe HTML for an oembed attachment.
349          *
350          * Width and height are given by the remote, and are regularly too small for
351          * the generated iframe.
352          *
353          * The width is entirely discarded for the actual width of the post, while fixed
354          * height is used as a starting point before the inevitable resizing.
355          *
356          * Since the iframe is automatically resized on load, there are no need for ugly
357          * and impractical scrollbars.
358          *
359          * @todo  This function is currently unused until someoneā„¢ adds support for a separate OEmbed domain
360          *
361          * @param string $src Original remote URL to embed
362          * @param string $width
363          * @param string $height
364          * @return string formatted HTML
365          *
366          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367          * @see   oembed_format_object()
368          */
369         private static function iframe($src, $width, $height)
370         {
371                 if (!$height || strstr($height, '%')) {
372                         $height = '200';
373                 }
374                 $width = '100%';
375
376                 $src = System::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
377                 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         }
379
380         /**
381          * Generates an XPath query to select elements whose provided attribute contains
382          * the provided value in a space-separated list.
383          *
384          * @brief Generates attribute search XPath string
385          *
386          * @param string $attr Name of the attribute to seach
387          * @param string $value Value to search in a space-separated list
388          * @return string
389          */
390         private static function buildXPath($attr, $value)
391         {
392                 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
393                 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         }
395
396         /**
397          * Returns the inner XML string of a provided DOMNode
398          *
399          * @brief Returns the inner XML string of a provided DOMNode
400          *
401          * @param DOMNode $node
402          * @return string
403          */
404         private static function getInnerHTML(DOMNode $node)
405         {
406                 $innerHTML = '';
407                 $children = $node->childNodes;
408                 foreach ($children as $child) {
409                         $innerHTML .= $child->ownerDocument->saveXML($child);
410                 }
411                 return $innerHTML;
412         }
413
414 }