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