]> git.mxchange.org Git - friendica.git/blob - src/Content/OEmbed.php
Add rel="tag" to the HTML Purifier allow list in BBCode::convert
[friendica.git] / src / Content / OEmbed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content;
23
24 use DOMDocument;
25 use DOMNode;
26 use DOMText;
27 use DOMXPath;
28 use Exception;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Hook;
31 use Friendica\Core\Renderer;
32 use Friendica\Database\Database;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\ParseUrl;
38 use Friendica\Util\Proxy;
39 use Friendica\Util\Strings;
40
41 /**
42  * Handles all OEmbed content fetching and replacement
43  *
44  * OEmbed is a standard used to allow an embedded representation of a URL on
45  * third party sites
46  *
47  * @see https://oembed.com
48  */
49 class OEmbed
50 {
51         public static function replaceCallback($matches)
52         {
53                 $embedurl = $matches[1];
54                 $j = self::fetchURL($embedurl, !self::isAllowedURL($embedurl));
55                 $s = self::formatObject($j);
56
57                 return $s;
58         }
59
60         /**
61          * Get data from an URL to embed its content.
62          *
63          * @param string $embedurl     The URL from which the data should be fetched.
64          * @param bool   $no_rich_type If set to true rich type content won't be fetched.
65          * @param bool   $use_parseurl Use the "ParseUrl" functionality to add additional data
66          *
67          * @return \Friendica\Object\OEmbed
68          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69          */
70         public static function fetchURL($embedurl, bool $no_rich_type = false, bool $use_parseurl = true)
71         {
72                 $embedurl = trim($embedurl, '\'"');
73
74                 $a = DI::app();
75
76                 $cache_key = 'oembed:' . $a->getThemeInfoValue('videowidth') . ':' . $embedurl;
77
78                 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->getThemeInfoValue('videowidth')];
79                 $oembed_record = DBA::selectFirst('oembed', ['content'], $condition);
80                 if (DBA::isResult($oembed_record)) {
81                         $json_string = $oembed_record['content'];
82                 } else {
83                         $json_string = DI::cache()->get($cache_key);
84                 }
85
86                 // These media files should now be caught in bbcode.php
87                 // left here as a fallback in case this is called from another source
88                 $noexts = ['mp3', 'mp4', 'ogg', 'ogv', 'oga', 'ogm', 'webm'];
89                 $ext = pathinfo(strtolower($embedurl), PATHINFO_EXTENSION);
90
91                 $oembed = new \Friendica\Object\OEmbed($embedurl);
92
93                 if ($json_string) {
94                         $oembed->parseJSON($json_string);
95                 } else {
96                         $json_string = '';
97
98                         if (!in_array($ext, $noexts)) {
99                                 // try oembed autodiscovery
100                                 $html_text = DI::httpClient()->fetch($embedurl, 15, 'text/*');
101                                 if (!empty($html_text)) {
102                                         $dom = new DOMDocument();
103                                         if (@$dom->loadHTML($html_text)) {
104                                                 $xpath = new DOMXPath($dom);
105                                                 foreach (
106                                                         $xpath->query("//link[@type='application/json+oembed'] | //link[@type='text/json+oembed']")
107                                                         as $link)
108                                                 {
109                                                         $href = $link->getAttributeNode('href')->nodeValue;
110                                                         // Both Youtube and Vimeo output OEmbed endpoint URL with HTTP
111                                                         // but their OEmbed endpoint is only accessible by HTTPS ¯\_(ツ)_/¯
112                                                         $href = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'],
113                                                                 ['https://www.youtube.com/', 'https://player.vimeo.com/'], $href);
114                                                         $result = DI::httpClient()->fetchFull($href . '&maxwidth=' . $a->getThemeInfoValue('videowidth'));
115                                                         if ($result->getReturnCode() === 200) {
116                                                                 $json_string = $result->getBody();
117                                                                 break;
118                                                         }
119                                                 }
120                                         }
121                                 }
122                         }
123
124                         $json_string = trim($json_string);
125
126                         if (!$json_string || $json_string[0] != '{') {
127                                 $json_string = '{"type":"error"}';
128                         }
129
130                         $oembed->parseJSON($json_string);
131
132                         if (!empty($oembed->type) && $oembed->type != 'error') {
133                                 DBA::insert('oembed', [
134                                         'url' => Strings::normaliseLink($embedurl),
135                                         'maxwidth' => $a->getThemeInfoValue('videowidth'),
136                                         'content' => $json_string,
137                                         'created' => DateTimeFormat::utcNow()
138                                 ], Database::INSERT_UPDATE);
139                                 $cache_ttl = Duration::DAY;
140                         } else {
141                                 $cache_ttl = Duration::FIVE_MINUTES;
142                         }
143
144                         DI::cache()->set($cache_key, $json_string, $cache_ttl);
145                 }
146
147                 // Always embed the SSL version
148                 if (!empty($oembed->html)) {
149                         $oembed->html = str_replace(['http://www.youtube.com/', 'http://player.vimeo.com/'], ['https://www.youtube.com/', 'https://player.vimeo.com/'], $oembed->html);
150                 }
151
152                 // Improve the OEmbed data with data from OpenGraph, Twitter cards and other sources
153                 if ($use_parseurl) {
154                         $data = ParseUrl::getSiteinfoCached($embedurl, false);
155
156                         if (($oembed->type == 'error') && empty($data['title']) && empty($data['text'])) {
157                                 return $oembed;
158                         }
159
160                         if ($no_rich_type || ($oembed->type == 'error')) {
161                                 $oembed->html = '';
162                                 $oembed->type = $data['type'];
163
164                                 if ($oembed->type == 'photo') {
165                                         if (!empty($data['images'])) {
166                                                 $oembed->url = $data['images'][0]['src'];
167                                                 $oembed->width = $data['images'][0]['width'];
168                                                 $oembed->height = $data['images'][0]['height'];
169                                         } else {
170                                                 $oembed->type = 'link';
171                                         }
172                                 }
173                         }
174
175                         if (!empty($data['title'])) {
176                                 $oembed->title = $data['title'];
177                         }
178
179                         if (!empty($data['text'])) {
180                                 $oembed->description = $data['text'];
181                         }
182
183                         if (!empty($data['publisher_name'])) {
184                                 $oembed->provider_name = $data['publisher_name'];
185                         }
186
187                         if (!empty($data['publisher_url'])) {
188                                 $oembed->provider_url = $data['publisher_url'];
189                         }
190
191                         if (!empty($data['author_name'])) {
192                                 $oembed->author_name = $data['author_name'];
193                         }
194
195                         if (!empty($data['author_url'])) {
196                                 $oembed->author_url = $data['author_url'];
197                         }
198
199                         if (!empty($data['images']) && ($oembed->type != 'photo')) {
200                                 $oembed->thumbnail_url = $data['images'][0]['src'];
201                                 $oembed->thumbnail_width = $data['images'][0]['width'];
202                                 $oembed->thumbnail_height = $data['images'][0]['height'];
203                         }
204                 }
205
206                 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
207
208                 return $oembed;
209         }
210
211         private static function formatObject(\Friendica\Object\OEmbed $oembed)
212         {
213                 $ret = '<div class="oembed ' . $oembed->type . '">';
214
215                 switch ($oembed->type) {
216                         case "video":
217                                 if ($oembed->thumbnail_url) {
218                                         $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
219                                         $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
220                                         // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
221                                         $tr = (($th) ? $tw / $th : 1);
222
223                                         $th = 120;
224                                         $tw = $th * $tr;
225                                         $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
226                                         $ret .= Renderer::replaceMacros($tpl, [
227                                                 '$embedurl' => $oembed->embed_url,
228                                                 '$escapedhtml' => base64_encode($oembed->html),
229                                                 '$tw' => $tw,
230                                                 '$th' => $th,
231                                                 '$turl' => $oembed->thumbnail_url,
232                                         ]);
233                                 } else {
234                                         $ret = $oembed->html;
235                                 }
236                                 break;
237
238                         case "photo":
239                                 $ret .= '<img width="' . $oembed->width . '" src="' . Proxy::proxifyUrl($oembed->url) . '">';
240                                 break;
241
242                         case "link":
243                                 break;
244
245                         case "rich":
246                                 $ret .= Proxy::proxifyHtml($oembed->html);
247                                 break;
248                 }
249
250                 // add link to source if not present in "rich" type
251                 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
252                         $ret .= '<h4>';
253                         if (!empty($oembed->title)) {
254                                 if (!empty($oembed->provider_name)) {
255                                         $ret .= $oembed->provider_name . ": ";
256                                 }
257
258                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
259                                 if (!empty($oembed->author_name)) {
260                                         $ret .= ' (' . $oembed->author_name . ')';
261                                 }
262                         } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
263                                 $embedlink = "";
264                                 if (!empty($oembed->provider_name)) {
265                                         $embedlink .= $oembed->provider_name;
266                                 }
267
268                                 if (!empty($oembed->author_name)) {
269                                         if ($embedlink != "") {
270                                                 $embedlink .= ": ";
271                                         }
272
273                                         $embedlink .= $oembed->author_name;
274                                 }
275                                 if (trim($embedlink) == "") {
276                                         $embedlink = $oembed->embed_url;
277                                 }
278
279                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
280                         } else {
281                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
282                         }
283                         $ret .= "</h4>";
284                 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
285                         // add <a> for html2bbcode conversion
286                         $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
287                 }
288
289                 $ret .= '</div>';
290
291                 return str_replace("\n", "", $ret);
292         }
293
294         public static function BBCode2HTML($text)
295         {
296                 $stopoembed = DI::config()->get("system", "no_oembed");
297                 if ($stopoembed == true) {
298                         return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
299                 }
300                 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
301         }
302
303         /**
304          * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
305          * and replace it with [embed]url[/embed]
306          *
307          * @param $text
308          * @return string
309          */
310         public static function HTML2BBCode($text)
311         {
312                 // start parser only if 'oembed' is in text
313                 if (strpos($text, "oembed")) {
314
315                         // convert non ascii chars to html entities
316                         $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
317
318                         // If it doesn't parse at all, just return the text.
319                         $dom = @DOMDocument::loadHTML($html_text);
320                         if (!$dom) {
321                                 return $text;
322                         }
323                         $xpath = new DOMXPath($dom);
324
325                         $xattr = self::buildXPath("class", "oembed");
326                         $entries = $xpath->query("//div[$xattr]");
327
328                         $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
329                         foreach ($entries as $e) {
330                                 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
331                                 if (!is_null($href)) {
332                                         $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
333                                 }
334                         }
335                         return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
336                 } else {
337                         return $text;
338                 }
339         }
340
341         /**
342          * Determines if rich content OEmbed is allowed for the provided URL
343          *
344          * @param string $url
345          * @return boolean
346          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347          */
348         public static function isAllowedURL($url)
349         {
350                 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
351                         return true;
352                 }
353
354                 $domain = parse_url($url, PHP_URL_HOST);
355                 if (empty($domain)) {
356                         return false;
357                 }
358
359                 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
360                 if (empty($str_allowed)) {
361                         return false;
362                 }
363
364                 $allowed = explode(',', $str_allowed);
365
366                 return Network::isDomainAllowed($domain, $allowed);
367         }
368
369         public static function getHTML($url, $title = null)
370         {
371                 $o = self::fetchURL($url, !self::isAllowedURL($url));
372
373                 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
374                         throw new Exception('OEmbed failed for URL: ' . $url);
375                 }
376
377                 if (!empty($title)) {
378                         $o->title = $title;
379                 }
380
381                 $html = self::formatObject($o);
382
383                 return $html;
384         }
385
386         /**
387          * Generates the iframe HTML for an oembed attachment.
388          *
389          * Width and height are given by the remote, and are regularly too small for
390          * the generated iframe.
391          *
392          * The width is entirely discarded for the actual width of the post, while fixed
393          * height is used as a starting point before the inevitable resizing.
394          *
395          * Since the iframe is automatically resized on load, there are no need for ugly
396          * and impractical scrollbars.
397          *
398          * @todo  This function is currently unused until someone™ adds support for a separate OEmbed domain
399          *
400          * @param string $src Original remote URL to embed
401          * @param string $width
402          * @param string $height
403          * @return string formatted HTML
404          *
405          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406          * @see   oembed_format_object()
407          */
408         private static function iframe($src, $width, $height)
409         {
410                 if (!$height || strstr($height, '%')) {
411                         $height = '200';
412                 }
413                 $width = '100%';
414
415                 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
416                 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>';
417         }
418
419         /**
420          * Generates attribute search XPath string
421          *
422          * Generates an XPath query to select elements whose provided attribute contains
423          * the provided value in a space-separated list.
424          *
425          * @param string $attr Name of the attribute to seach
426          * @param string $value Value to search in a space-separated list
427          * @return string
428          */
429         private static function buildXPath($attr, $value)
430         {
431                 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
432                 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'";
433         }
434
435         /**
436          * Returns the inner XML string of a provided DOMNode
437          *
438          * @param DOMNode $node
439          * @return string
440          */
441         private static function getInnerHTML(DOMNode $node)
442         {
443                 $innerHTML = '';
444                 $children = $node->childNodes;
445                 foreach ($children as $child) {
446                         $innerHTML .= $child->ownerDocument->saveXML($child);
447                 }
448                 return $innerHTML;
449         }
450
451 }