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