Issue 10019: Fix embedding of media objects
[friendica.git/.git] / src / Util / ParseUrl.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\Util;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\OEmbed;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Network\HTTPException;
33
34 /**
35  * Get information about a given URL
36  *
37  * Class with methods for extracting certain content from an url
38  */
39 class ParseUrl
40 {
41         const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42         const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
43
44         /**
45          * Maximum number of characters for the description
46          */
47         const MAX_DESC_COUNT = 250;
48
49         /**
50          * Minimum number of characters for the description
51          */
52         const MIN_DESC_COUNT = 100;
53
54         /**
55          * Fetch the content type of the given url
56          * @param string $url URL of the page
57          * @return string content type 
58          */
59         public static function getContentType(string $url)
60         {
61                 $curlResult = DI::httpRequest()->head($url);
62                 if (!$curlResult->isSuccess()) {
63                         return '';
64                 }
65
66                 $contenttype =  $curlResult->getHeader('Content-Type');
67                 if (empty($contenttype)) {
68                         return '';
69                 }
70                 
71                 if (!preg_match('#(image|video|audio)/#i', $contenttype, $matches)) {
72                         return '';
73                 }
74
75                 return array_pop($matches);
76         }
77
78         /**
79          * Search for chached embeddable data of an url otherwise fetch it
80          *
81          * @param string $url         The url of the page which should be scraped
82          * @param bool   $no_guessing If true the parse doens't search for
83          *                            preview pictures
84          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
85          *                            to avoid endless loops
86          *
87          * @return array which contains needed data for embedding
88          *    string 'url'      => The url of the parsed page
89          *    string 'type'     => Content type
90          *    string 'title'    => (optional) The title of the content
91          *    string 'text'     => (optional) The description for the content
92          *    string 'image'    => (optional) A preview image of the content (only available if $no_geuessing = false)
93          *    array  'images'   => (optional) Array of preview pictures
94          *    string 'keywords' => (optional) The tags which belong to the content
95          *
96          * @throws HTTPException\InternalServerErrorException
97          * @see   ParseUrl::getSiteinfo() for more information about scraping
98          * embeddable content
99          */
100         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
101         {
102                 if (empty($url)) {
103                         return [
104                                 'url' => '',
105                                 'type' => 'error',
106                         ];
107                 }
108
109                 $urlHash = hash('sha256', $url);
110
111                 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
112                         ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
113                 );
114                 if (!empty($parsed_url['content'])) {
115                         $data = unserialize($parsed_url['content']);
116                         return $data;
117                 }
118
119                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
120
121                 $expires = $data['expires'];
122
123                 unset($data['expires']);
124
125                 DI::dba()->insert(
126                         'parsed_url',
127                         [
128                                 'url_hash' => $urlHash,
129                                 'guessing' => !$no_guessing,
130                                 'oembed'   => $do_oembed,
131                                 'url'      => $url,
132                                 'content'  => serialize($data),
133                                 'created'  => DateTimeFormat::utcNow(),
134                                 'expires'  => $expires,
135                         ],
136                         Database::INSERT_UPDATE
137                 );
138
139                 return $data;
140         }
141
142         /**
143          * Parse a page for embeddable content information
144          *
145          * This method parses to url for meta data which can be used to embed
146          * the content. If available it prioritizes Open Graph meta tags.
147          * If this is not available it uses the twitter cards meta tags.
148          * As fallback it uses standard html elements with meta informations
149          * like \<title\>Awesome Title\</title\> or
150          * \<meta name="description" content="An awesome description"\>
151          *
152          * @param string $url         The url of the page which should be scraped
153          * @param bool   $no_guessing If true the parse doens't search for
154          *                            preview pictures
155          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
156          *                            to avoid endless loops
157          * @param int    $count       Internal counter to avoid endless loops
158          *
159          * @return array which contains needed data for embedding
160          *    string 'url'      => The url of the parsed page
161          *    string 'type'     => Content type (error, link, photo, image, audio, video)
162          *    string 'title'    => (optional) The title of the content
163          *    string 'text'     => (optional) The description for the content
164          *    string 'image'    => (optional) A preview image of the content (only available if $no_guessing = false)
165          *    array  'images'   => (optional) Array of preview pictures
166          *    string 'keywords' => (optional) The tags which belong to the content
167          *
168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169          * @todo  https://developers.google.com/+/plugins/snippet/
170          * @verbatim
171          * <meta itemprop="name" content="Awesome title">
172          * <meta itemprop="description" content="An awesome description">
173          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
174          *
175          * <body itemscope itemtype="http://schema.org/Product">
176          *   <h1 itemprop="name">Shiny Trinket</h1>
177          *   <img itemprop="image" src="{image-url}" />
178          *   <p itemprop="description">Shiny trinkets are shiny.</p>
179          * </body>
180          * @endverbatim
181          */
182         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
183         {
184                 if (empty($url)) {
185                         return [
186                                 'url' => '',
187                                 'type' => 'error',
188                         ];
189                 }
190
191                 // Check if the URL does contain a scheme
192                 $scheme = parse_url($url, PHP_URL_SCHEME);
193
194                 if ($scheme == '') {
195                         $url = 'http://' . ltrim($url, '/');
196                 }
197
198                 $url = trim($url, "'\"");
199
200                 $url = Network::stripTrackingQueryParams($url);
201
202                 $siteinfo = [
203                         'url' => $url,
204                         'type' => 'link',
205                         'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
206                 ];
207
208                 if ($count > 10) {
209                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
210                         return $siteinfo;
211                 }
212
213                 $curlResult = DI::httpRequest()->get($url);
214                 if (!$curlResult->isSuccess()) {
215                         return $siteinfo;
216                 }
217
218                 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
219
220                 // If the file is too large then exit
221                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
222                         return $siteinfo;
223                 }
224
225                 // Native media type, no need for HTML parsing
226                 $type = $curlResult->getHeader('Content-Type');
227                 if ($type) {
228                         preg_match('#(image|video|audio)/#i', $type, $matches);
229                         if ($matches) {
230                                 $siteinfo['type'] = array_pop($matches);
231                                 return $siteinfo;
232                         }
233                 }
234
235                 // If it isn't a HTML file then exit
236                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
237                         return $siteinfo;
238                 }
239
240                 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
241                         if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
242                                 $maxAge = max(86400, (int)array_pop($matches));
243                                 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
244                         }
245                 }
246
247                 $header = $curlResult->getHeader();
248                 $body = $curlResult->getBody();
249
250                 if ($do_oembed) {
251                         $oembed_data = OEmbed::fetchURL($url);
252
253                         if (!empty($oembed_data->type)) {
254                                 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
255                                         $siteinfo['type'] = $oembed_data->type;
256                                 }
257
258                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
259                                 if ($siteinfo['type'] != 'photo') {
260                                         if (isset($oembed_data->title)) {
261                                                 $siteinfo['title'] = trim($oembed_data->title);
262                                         }
263                                         if (isset($oembed_data->description)) {
264                                                 $siteinfo['text'] = trim($oembed_data->description);
265                                         }
266                                         if (isset($oembed_data->thumbnail_url)) {
267                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
268                                         }
269                                 }
270                         }
271                 }
272
273                 $charset = '';
274                 // Look for a charset, first in headers
275                 // Expected form: Content-Type: text/html; charset=ISO-8859-4
276                 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
277                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
278                 }
279
280                 // Then in body that gets precedence
281                 // Expected forms:
282                 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
283                 // - <meta charset="utf-8">
284                 // - <meta charset=utf-8>
285                 // - <meta charSet="utf-8">
286                 // We escape <style> and <script> tags since they can contain irrelevant charset information
287                 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
288                 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
289                         if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
290                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
291                         }
292                 });
293
294                 $siteinfo['charset'] = $charset;
295
296                 if ($charset && strtoupper($charset) != 'UTF-8') {
297                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
298                         $charset = str_ireplace('latin-1', 'latin1', $charset);
299
300                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
301                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
302                 }
303
304                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
305
306                 $doc = new DOMDocument();
307                 @$doc->loadHTML($body);
308
309                 XML::deleteNode($doc, 'style');
310                 XML::deleteNode($doc, 'script');
311                 XML::deleteNode($doc, 'option');
312                 XML::deleteNode($doc, 'h1');
313                 XML::deleteNode($doc, 'h2');
314                 XML::deleteNode($doc, 'h3');
315                 XML::deleteNode($doc, 'h4');
316                 XML::deleteNode($doc, 'h5');
317                 XML::deleteNode($doc, 'h6');
318                 XML::deleteNode($doc, 'ol');
319                 XML::deleteNode($doc, 'ul');
320
321                 $xpath = new DOMXPath($doc);
322
323                 $list = $xpath->query('//meta[@content]');
324                 foreach ($list as $node) {
325                         $meta_tag = [];
326                         if ($node->attributes->length) {
327                                 foreach ($node->attributes as $attribute) {
328                                         $meta_tag[$attribute->name] = $attribute->value;
329                                 }
330                         }
331
332                         if (@$meta_tag['http-equiv'] == 'refresh') {
333                                 $path = $meta_tag['content'];
334                                 $pathinfo = explode(';', $path);
335                                 $content = '';
336                                 foreach ($pathinfo as $value) {
337                                         if (substr(strtolower($value), 0, 4) == 'url=') {
338                                                 $content = substr($value, 4);
339                                         }
340                                 }
341                                 if ($content != '') {
342                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
343                                         return $siteinfo;
344                                 }
345                         }
346                 }
347
348                 $list = $xpath->query('//title');
349                 if ($list->length > 0) {
350                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
351                 }
352
353                 $list = $xpath->query('//meta[@name]');
354                 foreach ($list as $node) {
355                         $meta_tag = [];
356                         if ($node->attributes->length) {
357                                 foreach ($node->attributes as $attribute) {
358                                         $meta_tag[$attribute->name] = $attribute->value;
359                                 }
360                         }
361
362                         if (empty($meta_tag['content'])) {
363                                 continue;
364                         }
365
366                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
367
368                         switch (strtolower($meta_tag['name'])) {
369                                 case 'fulltitle':
370                                         $siteinfo['title'] = trim($meta_tag['content']);
371                                         break;
372                                 case 'description':
373                                         $siteinfo['text'] = trim($meta_tag['content']);
374                                         break;
375                                 case 'thumbnail':
376                                         $siteinfo['image'] = $meta_tag['content'];
377                                         break;
378                                 case 'twitter:image':
379                                         $siteinfo['image'] = $meta_tag['content'];
380                                         break;
381                                 case 'twitter:image:src':
382                                         $siteinfo['image'] = $meta_tag['content'];
383                                         break;
384                                 case 'twitter:card':
385                                         // Detect photo pages
386                                         if ($meta_tag['content'] == 'summary_large_image') {
387                                                 $siteinfo['type'] = 'photo';
388                                         }
389                                         break;
390                                 case 'twitter:description':
391                                         $siteinfo['text'] = trim($meta_tag['content']);
392                                         break;
393                                 case 'twitter:title':
394                                         $siteinfo['title'] = trim($meta_tag['content']);
395                                         break;
396                                 case 'dc.title':
397                                         $siteinfo['title'] = trim($meta_tag['content']);
398                                         break;
399                                 case 'dc.description':
400                                         $siteinfo['text'] = trim($meta_tag['content']);
401                                         break;
402                                 case 'keywords':
403                                         $keywords = explode(',', $meta_tag['content']);
404                                         break;
405                                 case 'news_keywords':
406                                         $keywords = explode(',', $meta_tag['content']);
407                                         break;
408                         }
409                 }
410
411                 if (isset($keywords)) {
412                         $siteinfo['keywords'] = [];
413                         foreach ($keywords as $keyword) {
414                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
415                                         $siteinfo['keywords'][] = trim($keyword);
416                                 }
417                         }
418                 }
419
420                 $list = $xpath->query('//meta[@property]');
421                 foreach ($list as $node) {
422                         $meta_tag = [];
423                         if ($node->attributes->length) {
424                                 foreach ($node->attributes as $attribute) {
425                                         $meta_tag[$attribute->name] = $attribute->value;
426                                 }
427                         }
428
429                         if (!empty($meta_tag['content'])) {
430                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
431
432                                 switch (strtolower($meta_tag['property'])) {
433                                         case 'og:image':
434                                                 $siteinfo['image'] = $meta_tag['content'];
435                                                 break;
436                                         case 'og:title':
437                                                 $siteinfo['title'] = trim($meta_tag['content']);
438                                                 break;
439                                         case 'og:description':
440                                                 $siteinfo['text'] = trim($meta_tag['content']);
441                                                 break;
442                                 }
443                         }
444                 }
445
446                 // Prevent to have a photo type without an image
447                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
448                         $siteinfo['type'] = 'link';
449                 }
450
451                 if (!empty($siteinfo['image'])) {
452                         $src = self::completeUrl($siteinfo['image'], $url);
453
454                         unset($siteinfo['image']);
455
456                         $photodata = Images::getInfoFromURLCached($src);
457
458                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
459                                 $siteinfo['images'][] = ['src' => $src,
460                                         'width' => $photodata[0],
461                                         'height' => $photodata[1]];
462                         }
463                 }
464
465                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
466                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
467                         $pos = mb_strrpos($siteinfo['text'], '.');
468                         if ($pos > self::MIN_DESC_COUNT) {
469                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
470                         }
471                 }
472
473                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
474
475                 Hook::callAll('getsiteinfo', $siteinfo);
476
477                 return $siteinfo;
478         }
479
480         /**
481          * Convert tags from CSV to an array
482          *
483          * @param string $string Tags
484          * @return array with formatted Hashtags
485          */
486         public static function convertTagsToArray($string)
487         {
488                 $arr_tags = str_getcsv($string);
489                 if (count($arr_tags)) {
490                         // add the # sign to every tag
491                         array_walk($arr_tags, ["self", "arrAddHashes"]);
492
493                         return $arr_tags;
494                 }
495         }
496
497         /**
498          * Add a hasht sign to a string
499          *
500          * This method is used as callback function
501          *
502          * @param string $tag The pure tag name
503          * @param int    $k   Counter for internal use
504          * @return void
505          */
506         private static function arrAddHashes(&$tag, $k)
507         {
508                 $tag = "#" . $tag;
509         }
510
511         /**
512          * Add a scheme to an url
513          *
514          * The src attribute of some html elements (e.g. images)
515          * can miss the scheme so we need to add the correct
516          * scheme
517          *
518          * @param string $url    The url which possibly does have
519          *                       a missing scheme (a link to an image)
520          * @param string $scheme The url with a correct scheme
521          *                       (e.g. the url from the webpage which does contain the image)
522          *
523          * @return string The url with a scheme
524          */
525         private static function completeUrl($url, $scheme)
526         {
527                 $urlarr = parse_url($url);
528
529                 // If the url does allready have an scheme
530                 // we can stop the process here
531                 if (isset($urlarr["scheme"])) {
532                         return($url);
533                 }
534
535                 $schemearr = parse_url($scheme);
536
537                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
538
539                 if (!empty($schemearr["port"])) {
540                         $complete .= ":".$schemearr["port"];
541                 }
542
543                 if (!empty($urlarr["path"])) {
544                         if (strpos($urlarr["path"], "/") !== 0) {
545                                 $complete .= "/";
546                         }
547
548                         $complete .= $urlarr["path"];
549                 }
550
551                 if (!empty($urlarr["query"])) {
552                         $complete .= "?".$urlarr["query"];
553                 }
554
555                 if (!empty($urlarr["fragment"])) {
556                         $complete .= "#".$urlarr["fragment"];
557                 }
558
559                 return($complete);
560         }
561 }