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