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