]> git.mxchange.org Git - friendica.git/blob - src/Content/OEmbed.php
Remove unused parameter
[friendica.git] / src / Content / OEmbed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\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 as ProxyUtils;
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->videowidth . ':' . $embedurl;
77
78                 $condition = ['url' => Strings::normaliseLink($embedurl), 'maxwidth' => $a->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::httpRequest()->fetch($embedurl, 15, 'text/*');
101                                 if ($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::httpRequest()->fetchFull($href . '&maxwidth=' . $a->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->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                                         $oembed->url = $data['url'];
166                                 }
167                         }
168
169                         if (!empty($data['title'])) {
170                                 $oembed->title = $data['title'];
171                         }
172
173                         if (!empty($data['text'])) {
174                                 $oembed->description = $data['text'];
175                         }
176
177                         if (!empty($data['publisher_name'])) {
178                                 $oembed->provider_name = $data['publisher_name'];
179                         }
180
181                         if (!empty($data['publisher_url'])) {
182                                 $oembed->provider_url = $data['publisher_url'];
183                         }
184
185                         if (!empty($data['author_name'])) {
186                                 $oembed->author_name = $data['author_name'];
187                         }
188
189                         if (!empty($data['author_url'])) {
190                                 $oembed->author_url = $data['author_url'];
191                         }
192
193                         if (!empty($data['images'])) {
194                                 $oembed->thumbnail_url = $data['images'][0]['src'];
195                                 $oembed->thumbnail_width = $data['images'][0]['width'];
196                                 $oembed->thumbnail_height = $data['images'][0]['height'];
197                         }
198                 }
199
200                 Hook::callAll('oembed_fetch_url', $embedurl, $oembed);
201
202                 return $oembed;
203         }
204
205         private static function formatObject(\Friendica\Object\OEmbed $oembed)
206         {
207                 $ret = '<div class="oembed ' . $oembed->type . '">';
208
209                 switch ($oembed->type) {
210                         case "video":
211                                 if ($oembed->thumbnail_url) {
212                                         $tw = (isset($oembed->thumbnail_width) && intval($oembed->thumbnail_width)) ? $oembed->thumbnail_width : 200;
213                                         $th = (isset($oembed->thumbnail_height) && intval($oembed->thumbnail_height)) ? $oembed->thumbnail_height : 180;
214                                         // make sure we don't attempt divide by zero, fallback is a 1:1 ratio
215                                         $tr = (($th) ? $tw / $th : 1);
216
217                                         $th = 120;
218                                         $tw = $th * $tr;
219                                         $tpl = Renderer::getMarkupTemplate('oembed_video.tpl');
220                                         $ret .= Renderer::replaceMacros($tpl, [
221                                                 '$embedurl' => $oembed->embed_url,
222                                                 '$escapedhtml' => base64_encode($oembed->html),
223                                                 '$tw' => $tw,
224                                                 '$th' => $th,
225                                                 '$turl' => $oembed->thumbnail_url,
226                                         ]);
227                                 } else {
228                                         $ret = $oembed->html;
229                                 }
230                                 break;
231
232                         case "photo":
233                                 $ret .= '<img width="' . $oembed->width . '" src="' . ProxyUtils::proxifyUrl($oembed->url) . '">';
234                                 break;
235
236                         case "link":
237                                 break;
238
239                         case "rich":
240                                 $ret .= ProxyUtils::proxifyHtml($oembed->html);
241                                 break;
242                 }
243
244                 // add link to source if not present in "rich" type
245                 if ($oembed->type != 'rich' || !strpos($oembed->html, $oembed->embed_url)) {
246                         $ret .= '<h4>';
247                         if (!empty($oembed->title)) {
248                                 if (!empty($oembed->provider_name)) {
249                                         $ret .= $oembed->provider_name . ": ";
250                                 }
251
252                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
253                                 if (!empty($oembed->author_name)) {
254                                         $ret .= ' (' . $oembed->author_name . ')';
255                                 }
256                         } elseif (!empty($oembed->provider_name) || !empty($oembed->author_name)) {
257                                 $embedlink = "";
258                                 if (!empty($oembed->provider_name)) {
259                                         $embedlink .= $oembed->provider_name;
260                                 }
261
262                                 if (!empty($oembed->author_name)) {
263                                         if ($embedlink != "") {
264                                                 $embedlink .= ": ";
265                                         }
266
267                                         $embedlink .= $oembed->author_name;
268                                 }
269                                 if (trim($embedlink) == "") {
270                                         $embedlink = $oembed->embed_url;
271                                 }
272
273                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $embedlink . '</a>';
274                         } else {
275                                 $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->embed_url . '</a>';
276                         }
277                         $ret .= "</h4>";
278                 } elseif (!strpos($oembed->html, $oembed->embed_url)) {
279                         // add <a> for html2bbcode conversion
280                         $ret .= '<a href="' . $oembed->embed_url . '" rel="oembed">' . $oembed->title . '</a>';
281                 }
282
283                 $ret .= '</div>';
284
285                 return str_replace("\n", "", $ret);
286         }
287
288         public static function BBCode2HTML($text)
289         {
290                 $stopoembed = DI::config()->get("system", "no_oembed");
291                 if ($stopoembed == true) {
292                         return preg_replace("/\[embed\](.+?)\[\/embed\]/is", "<!-- oembed $1 --><i>" . DI::l10n()->t('Embedding disabled') . " : $1</i><!-- /oembed $1 -->", $text);
293                 }
294                 return preg_replace_callback("/\[embed\](.+?)\[\/embed\]/is", ['self', 'replaceCallback'], $text);
295         }
296
297         /**
298          * Find <span class='oembed'>..<a href='url' rel='oembed'>..</a></span>
299          * and replace it with [embed]url[/embed]
300          *
301          * @param $text
302          * @return string
303          */
304         public static function HTML2BBCode($text)
305         {
306                 // start parser only if 'oembed' is in text
307                 if (strpos($text, "oembed")) {
308
309                         // convert non ascii chars to html entities
310                         $html_text = mb_convert_encoding($text, 'HTML-ENTITIES', mb_detect_encoding($text));
311
312                         // If it doesn't parse at all, just return the text.
313                         $dom = @DOMDocument::loadHTML($html_text);
314                         if (!$dom) {
315                                 return $text;
316                         }
317                         $xpath = new DOMXPath($dom);
318
319                         $xattr = self::buildXPath("class", "oembed");
320                         $entries = $xpath->query("//div[$xattr]");
321
322                         $xattr = "@rel='oembed'"; //oe_build_xpath("rel","oembed");
323                         foreach ($entries as $e) {
324                                 $href = $xpath->evaluate("a[$xattr]/@href", $e)->item(0)->nodeValue;
325                                 if (!is_null($href)) {
326                                         $e->parentNode->replaceChild(new DOMText("[embed]" . $href . "[/embed]"), $e);
327                                 }
328                         }
329                         return self::getInnerHTML($dom->getElementsByTagName("body")->item(0));
330                 } else {
331                         return $text;
332                 }
333         }
334
335         /**
336          * Determines if rich content OEmbed is allowed for the provided URL
337          *
338          * @param string $url
339          * @return boolean
340          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
341          */
342         public static function isAllowedURL($url)
343         {
344                 if (!DI::config()->get('system', 'no_oembed_rich_content')) {
345                         return true;
346                 }
347
348                 $domain = parse_url($url, PHP_URL_HOST);
349                 if (empty($domain)) {
350                         return false;
351                 }
352
353                 $str_allowed = DI::config()->get('system', 'allowed_oembed', '');
354                 if (empty($str_allowed)) {
355                         return false;
356                 }
357
358                 $allowed = explode(',', $str_allowed);
359
360                 return Network::isDomainAllowed($domain, $allowed);
361         }
362
363         public static function getHTML($url, $title = null)
364         {
365                 $o = self::fetchURL($url, !self::isAllowedURL($url));
366
367                 if (!is_object($o) || property_exists($o, 'type') && $o->type == 'error') {
368                         throw new Exception('OEmbed failed for URL: ' . $url);
369                 }
370
371                 if (!empty($title)) {
372                         $o->title = $title;
373                 }
374
375                 $html = self::formatObject($o);
376
377                 return $html;
378         }
379
380         /**
381          * Generates the iframe HTML for an oembed attachment.
382          *
383          * Width and height are given by the remote, and are regularly too small for
384          * the generated iframe.
385          *
386          * The width is entirely discarded for the actual width of the post, while fixed
387          * height is used as a starting point before the inevitable resizing.
388          *
389          * Since the iframe is automatically resized on load, there are no need for ugly
390          * and impractical scrollbars.
391          *
392          * @todo  This function is currently unused until someone™ adds support for a separate OEmbed domain
393          *
394          * @param string $src Original remote URL to embed
395          * @param string $width
396          * @param string $height
397          * @return string formatted HTML
398          *
399          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400          * @see   oembed_format_object()
401          */
402         private static function iframe($src, $width, $height)
403         {
404                 if (!$height || strstr($height, '%')) {
405                         $height = '200';
406                 }
407                 $width = '100%';
408
409                 $src = DI::baseUrl() . '/oembed/' . Strings::base64UrlEncode($src);
410                 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>';
411         }
412
413         /**
414          * Generates attribute search XPath string
415          *
416          * Generates an XPath query to select elements whose provided attribute contains
417          * the provided value in a space-separated list.
418          *
419          * @param string $attr Name of the attribute to seach
420          * @param string $value Value to search in a space-separated list
421          * @return string
422          */
423         private static function buildXPath($attr, $value)
424         {
425                 // https://www.westhoffswelt.de/blog/2009/6/9/select-html-elements-with-more-than-one-css-class-using-xpath
426                 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'";
427         }
428
429         /**
430          * Returns the inner XML string of a provided DOMNode
431          *
432          * @param DOMNode $node
433          * @return string
434          */
435         private static function getInnerHTML(DOMNode $node)
436         {
437                 $innerHTML = '';
438                 $children = $node->childNodes;
439                 foreach ($children as $child) {
440                         $innerHTML .= $child->ownerDocument->saveXML($child);
441                 }
442                 return $innerHTML;
443         }
444
445 }