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