]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
9ce9b0e9f9510cac664df737d795a0990897c16d
[friendica.git] / src / Util / ParseUrl.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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 array 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                 return explode('/', current(explode(';', $contenttype)));
72         }
73
74         /**
75          * Search for chached embeddable data of an url otherwise fetch it
76          *
77          * @param string $url         The url of the page which should be scraped
78          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
79          *                            to avoid endless loops
80          *
81          * @return array which contains needed data for embedding
82          *    string 'url'      => The url of the parsed page
83          *    string 'type'     => Content type
84          *    string 'title'    => (optional) The title of the content
85          *    string 'text'     => (optional) The description for the content
86          *    string 'image'    => (optional) A preview image of the content
87          *    array  'images'   => (optional) Array of preview pictures
88          *    string 'keywords' => (optional) The tags which belong to the content
89          *
90          * @throws HTTPException\InternalServerErrorException
91          * @see   ParseUrl::getSiteinfo() for more information about scraping
92          * embeddable content
93          */
94         public static function getSiteinfoCached($url, $do_oembed = true): array
95         {
96                 if (empty($url)) {
97                         return [
98                                 'url' => '',
99                                 'type' => 'error',
100                         ];
101                 }
102
103                 $urlHash = hash('sha256', $url);
104
105                 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
106                         ['url_hash' => $urlHash, 'oembed' => $do_oembed]
107                 );
108                 if (!empty($parsed_url['content'])) {
109                         $data = unserialize($parsed_url['content']);
110                         return $data;
111                 }
112
113                 $data = self::getSiteinfo($url, $do_oembed);
114
115                 $expires = $data['expires'];
116
117                 unset($data['expires']);
118
119                 DI::dba()->insert(
120                         'parsed_url',
121                         [
122                                 'url_hash' => $urlHash,
123                                 'oembed'   => $do_oembed,
124                                 'url'      => $url,
125                                 'content'  => serialize($data),
126                                 'created'  => DateTimeFormat::utcNow(),
127                                 'expires'  => $expires,
128                         ],
129                         Database::INSERT_UPDATE
130                 );
131
132                 return $data;
133         }
134
135         /**
136          * Parse a page for embeddable content information
137          *
138          * This method parses to url for meta data which can be used to embed
139          * the content. If available it prioritizes Open Graph meta tags.
140          * If this is not available it uses the twitter cards meta tags.
141          * As fallback it uses standard html elements with meta informations
142          * like \<title\>Awesome Title\</title\> or
143          * \<meta name="description" content="An awesome description"\>
144          *
145          * @param string $url         The url of the page which should be scraped
146          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
147          *                            to avoid endless loops
148          * @param int    $count       Internal counter to avoid endless loops
149          *
150          * @return array which contains needed data for embedding
151          *    string 'url'      => The url of the parsed page
152          *    string 'type'     => Content type (error, link, photo, image, audio, video)
153          *    string 'title'    => (optional) The title of the content
154          *    string 'text'     => (optional) The description for the content
155          *    string 'image'    => (optional) A preview image of the content
156          *    array  'images'   => (optional) Array of preview pictures
157          *    string 'keywords' => (optional) The tags which belong to the content
158          *
159          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
160          * @todo  https://developers.google.com/+/plugins/snippet/
161          * @verbatim
162          * <meta itemprop="name" content="Awesome title">
163          * <meta itemprop="description" content="An awesome description">
164          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
165          *
166          * <body itemscope itemtype="http://schema.org/Product">
167          *   <h1 itemprop="name">Shiny Trinket</h1>
168          *   <img itemprop="image" src="{image-url}" />
169          *   <p itemprop="description">Shiny trinkets are shiny.</p>
170          * </body>
171          * @endverbatim
172          */
173         public static function getSiteinfo($url, $do_oembed = true, $count = 1)
174         {
175                 if (empty($url)) {
176                         return [
177                                 'url' => '',
178                                 'type' => 'error',
179                         ];
180                 }
181
182                 // Check if the URL does contain a scheme
183                 $scheme = parse_url($url, PHP_URL_SCHEME);
184
185                 if ($scheme == '') {
186                         $url = 'http://' . ltrim($url, '/');
187                 }
188
189                 $url = trim($url, "'\"");
190
191                 $url = Network::stripTrackingQueryParams($url);
192
193                 $siteinfo = [
194                         'url' => $url,
195                         'type' => 'link',
196                         'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
197                 ];
198
199                 if ($count > 10) {
200                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
201                         return $siteinfo;
202                 }
203
204                 $type = self::getContentType($url);
205                 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
206                 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
207                         $siteinfo['type'] = $type[0];
208                         return $siteinfo;
209                 }
210
211                 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
212                         Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
213                         return $siteinfo;
214                 }
215
216                 $curlResult = DI::httpRequest()->get($url);
217                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
218                         return $siteinfo;
219                 }
220
221                 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
222
223                 // If the file is too large then exit
224                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
225                         return $siteinfo;
226                 }
227
228                 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
229                         if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
230                                 $maxAge = max(86400, (int)array_pop($matches));
231                                 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
232                         }
233                 }
234
235                 $header = $curlResult->getHeader();
236                 $body = $curlResult->getBody();
237
238                 if ($do_oembed) {
239                         $oembed_data = OEmbed::fetchURL($url, false, false);
240
241                         if (!empty($oembed_data->type)) {
242                                 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
243                                         $siteinfo['type'] = $oembed_data->type;
244                                 }
245
246                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
247                                 if ($siteinfo['type'] != 'photo') {
248                                         if (!empty($oembed_data->title)) {
249                                                 $siteinfo['title'] = trim($oembed_data->title);
250                                         }
251                                         if (!empty($oembed_data->description)) {
252                                                 $siteinfo['text'] = trim($oembed_data->description);
253                                         }
254                                         if (!empty($oembed_data->author_name)) {
255                                                 $siteinfo['author_name'] = trim($oembed_data->author_name);
256                                         }
257                                         if (!empty($oembed_data->author_url)) {
258                                                 $siteinfo['author_url'] = trim($oembed_data->author_url);
259                                         }
260                                         if (!empty($oembed_data->provider_name)) {
261                                                 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
262                                         }
263                                         if (!empty($oembed_data->provider_url)) {
264                                                 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
265                                         }
266                                         if (!empty($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, 'option');
311                 XML::deleteNode($doc, 'h1');
312                 XML::deleteNode($doc, 'h2');
313                 XML::deleteNode($doc, 'h3');
314                 XML::deleteNode($doc, 'h4');
315                 XML::deleteNode($doc, 'h5');
316                 XML::deleteNode($doc, 'h6');
317                 XML::deleteNode($doc, 'ol');
318                 XML::deleteNode($doc, 'ul');
319
320                 $xpath = new DOMXPath($doc);
321
322                 $list = $xpath->query('//meta[@content]');
323                 foreach ($list as $node) {
324                         $meta_tag = [];
325                         if ($node->attributes->length) {
326                                 foreach ($node->attributes as $attribute) {
327                                         $meta_tag[$attribute->name] = $attribute->value;
328                                 }
329                         }
330
331                         if (@$meta_tag['http-equiv'] == 'refresh') {
332                                 $path = $meta_tag['content'];
333                                 $pathinfo = explode(';', $path);
334                                 $content = '';
335                                 foreach ($pathinfo as $value) {
336                                         if (substr(strtolower($value), 0, 4) == 'url=') {
337                                                 $content = substr($value, 4);
338                                         }
339                                 }
340                                 if ($content != '') {
341                                         $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
342                                         return $siteinfo;
343                                 }
344                         }
345                 }
346
347                 $list = $xpath->query('//title');
348                 if ($list->length > 0) {
349                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
350                 }
351
352                 $twitter_card = false;
353                 $twitter_image = false;
354
355                 $list = $xpath->query('//meta[@name]');
356                 foreach ($list as $node) {
357                         $meta_tag = [];
358                         if ($node->attributes->length) {
359                                 foreach ($node->attributes as $attribute) {
360                                         $meta_tag[$attribute->name] = $attribute->value;
361                                 }
362                         }
363
364                         if (empty($meta_tag['content'])) {
365                                 continue;
366                         }
367
368                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
369
370                         switch (strtolower($meta_tag['name'])) {
371                                 case 'fulltitle':
372                                         $siteinfo['title'] = trim($meta_tag['content']);
373                                         break;
374                                 case 'description':
375                                         $siteinfo['text'] = trim($meta_tag['content']);
376                                         break;
377                                 case 'thumbnail':
378                                         $siteinfo['image'] = $meta_tag['content'];
379                                         break;
380                                 case 'twitter:image':
381                                         $siteinfo['image'] = $meta_tag['content'];
382                                         $twitter_image = true;
383                                         break;
384                                 case 'twitter:image:src':
385                                         $siteinfo['image'] = $meta_tag['content'];
386                                         break;
387                                 case 'twitter:card':
388                                         // Detect photo pages
389                                         if ($meta_tag['content'] == 'summary_large_image') {
390                                                 $twitter_card = true;
391                                         }
392                                         break;
393                                 case 'twitter:description':
394                                         $siteinfo['text'] = trim($meta_tag['content']);
395                                         break;
396                                 case 'twitter:title':
397                                         $siteinfo['title'] = trim($meta_tag['content']);
398                                         break;
399                                 case 'dc.title':
400                                         $siteinfo['title'] = trim($meta_tag['content']);
401                                         break;
402                                 case 'dc.description':
403                                         $siteinfo['text'] = trim($meta_tag['content']);
404                                         break;
405                                 case 'dc.creator':
406                                         $siteinfo['publisher_name'] = trim($meta_tag['content']);
407                                         break;
408                                 case 'keywords':
409                                         $keywords = explode(',', $meta_tag['content']);
410                                         break;
411                                 case 'news_keywords':
412                                         $keywords = explode(',', $meta_tag['content']);
413                                         break;
414                         }
415                 }
416
417                 if (isset($keywords)) {
418                         $siteinfo['keywords'] = [];
419                         foreach ($keywords as $keyword) {
420                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
421                                         $siteinfo['keywords'][] = trim($keyword);
422                                 }
423                         }
424                 }
425
426                 $list = $xpath->query('//meta[@property]');
427                 foreach ($list as $node) {
428                         $meta_tag = [];
429                         if ($node->attributes->length) {
430                                 foreach ($node->attributes as $attribute) {
431                                         $meta_tag[$attribute->name] = $attribute->value;
432                                 }
433                         }
434
435                         if (!empty($meta_tag['content'])) {
436                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
437
438                                 switch (strtolower($meta_tag['property'])) {
439                                         case 'og:image':
440                                                 $siteinfo['image'] = $meta_tag['content'];
441                                                 break;
442                                         case 'og:image:url':
443                                                 $siteinfo['image'] = $meta_tag['content'];
444                                                 break;
445                                         case 'og:image:secure_url':
446                                                 $siteinfo['image'] = $meta_tag['content'];
447                                                 break;
448                                         case 'og:title':
449                                                 $siteinfo['title'] = trim($meta_tag['content']);
450                                                 break;
451                                         case 'og:description':
452                                                 $siteinfo['text'] = trim($meta_tag['content']);
453                                                 break;
454                                         case 'og:site_name':
455                                                 $siteinfo['publisher_name'] = trim($meta_tag['content']);
456                                                 break;
457                                         case 'twitter:description':
458                                                 $siteinfo['text'] = trim($meta_tag['content']);
459                                                 break;
460                                         case 'twitter:title':
461                                                 $siteinfo['title'] = trim($meta_tag['content']);
462                                                 break;
463                                         case 'twitter:image':
464                                                 $siteinfo['image'] = $meta_tag['content'];
465                                                 $twitter_image = true;
466                                                 break;
467                                 }
468                         }
469                 }
470
471                 $list = $xpath->query("//script[@type='application/ld+json']");
472                 foreach ($list as $node) {
473                         if (!empty($node->nodeValue)) {
474                                 if ($jsonld = json_decode($node->nodeValue, true)) {
475                                         $siteinfo = self::parseParts($siteinfo, $jsonld);
476                                 }
477                         }
478                 }
479
480 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658          
481                 // Prevent to have a photo type without an image
482 //              if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
483 //                      $siteinfo['type'] = 'photo';
484 //              }
485
486                 if (!empty($siteinfo['image'])) {
487                         $siteinfo['images'] = $siteinfo['images'] ?? [];
488                         array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
489                         unset($siteinfo['image']);
490                 }
491
492                 $siteinfo = self::checkMedia($url, $siteinfo);
493
494                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
495                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
496                         $pos = mb_strrpos($siteinfo['text'], '.');
497                         if ($pos > self::MIN_DESC_COUNT) {
498                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
499                         }
500                 }
501
502                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
503
504                 Hook::callAll('getsiteinfo', $siteinfo);
505
506                 return $siteinfo;
507         }
508
509         /**
510          * Check the attached media elements.
511          * Fix existing data and add missing data.
512          *
513          * @param string $page_url
514          * @param array $siteinfo
515          * @return void
516          */
517         private static function checkMedia(string $page_url, array $siteinfo)
518         {
519                 if (!empty($siteinfo['images'])) {
520                         array_walk($siteinfo['images'], function (&$image) use ($page_url) {
521                                 // According to the specifications someone could place a picture url into the content field as well.
522                                 // But this doesn't seem to happen in the wild, so we don't cover it here.
523                                 if (!empty($image['url'])) {
524                                         $image['url'] = self::completeUrl($image['url'], $page_url);
525                                         $photodata = Images::getInfoFromURLCached($image['url']);
526                                         if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
527                                                 $image['src'] = $image['url'];
528                                                 $image['width'] = $photodata[0];
529                                                 $image['height'] = $photodata[1];
530                                                 $image['contenttype'] = $photodata['mime'];
531                                                 unset($image['url']);
532                                                 ksort($image);
533                                         } else {
534                                                 $image = [];
535                                         }
536                                 } else {
537                                         $image = [];
538                                 }
539                         });
540
541                         $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
542                 }
543
544                 foreach (['audio', 'video'] as $element) {
545                         if (!empty($siteinfo[$element])) {
546                                 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
547                                         $url = '';
548                                         $embed = '';
549                                         $content = '';
550                                         $contenttype = '';
551                                         foreach (['embed', 'content', 'url'] as $field) {
552                                                 if (!empty($media[$field])) {
553                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
554                                                         $type = self::getContentType($media[$field]);
555                                                         if (($type[0] ?? '') == 'text') {
556                                                                 if ($field == 'embed') {
557                                                                         $embed = $media[$field];
558                                                                 } else {
559                                                                         $url = $media[$field];
560                                                                 }
561                                                         } elseif (!empty($type[0])) {
562                                                                 $content = $media[$field];
563                                                                 $contenttype = implode('/', $type);
564                                                         }
565                                                 }
566                                                 unset($media[$field]);
567                                         }
568
569                                         foreach (['image', 'preview'] as $field) {
570                                                 if (!empty($media[$field])) {
571                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
572                                                 }
573                                         }
574
575                                         if (!empty($url)) {
576                                                 $media['url'] = $url;
577                                         }
578                                         if (!empty($embed)) {
579                                                 $media['embed'] = $embed;
580                                                 if (!empty($media['main'])) {
581                                                         $siteinfo['embed'] = $embed;
582                                                 }
583                                         }
584                                         if (!empty($content)) {
585                                                 $media['src'] = $content;
586                                         }
587                                         if (!empty($contenttype)) {
588                                                 $media['contenttype'] = $contenttype;
589                                         }
590                                         if (empty($url) && empty($content) && empty($embed)) {
591                                                 $media = [];
592                                         }
593                                         ksort($media);
594                                 });
595
596                                 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
597                         }
598                         if (empty($siteinfo[$element])) {
599                                 unset($siteinfo[$element]);
600                         }
601                 }
602                 return $siteinfo;
603         }
604
605         /**
606          * Convert tags from CSV to an array
607          *
608          * @param string $string Tags
609          * @return array with formatted Hashtags
610          */
611         public static function convertTagsToArray($string)
612         {
613                 $arr_tags = str_getcsv($string);
614                 if (count($arr_tags)) {
615                         // add the # sign to every tag
616                         array_walk($arr_tags, ["self", "arrAddHashes"]);
617
618                         return $arr_tags;
619                 }
620         }
621
622         /**
623          * Add a hasht sign to a string
624          *
625          * This method is used as callback function
626          *
627          * @param string $tag The pure tag name
628          * @param int    $k   Counter for internal use
629          * @return void
630          */
631         private static function arrAddHashes(&$tag, $k)
632         {
633                 $tag = "#" . $tag;
634         }
635
636         /**
637          * Add a scheme to an url
638          *
639          * The src attribute of some html elements (e.g. images)
640          * can miss the scheme so we need to add the correct
641          * scheme
642          *
643          * @param string $url    The url which possibly does have
644          *                       a missing scheme (a link to an image)
645          * @param string $scheme The url with a correct scheme
646          *                       (e.g. the url from the webpage which does contain the image)
647          *
648          * @return string The url with a scheme
649          */
650         private static function completeUrl($url, $scheme)
651         {
652                 $urlarr = parse_url($url);
653
654                 // If the url does allready have an scheme
655                 // we can stop the process here
656                 if (isset($urlarr["scheme"])) {
657                         return($url);
658                 }
659
660                 $schemearr = parse_url($scheme);
661
662                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
663
664                 if (!empty($schemearr["port"])) {
665                         $complete .= ":".$schemearr["port"];
666                 }
667
668                 if (!empty($urlarr["path"])) {
669                         if (strpos($urlarr["path"], "/") !== 0) {
670                                 $complete .= "/";
671                         }
672
673                         $complete .= $urlarr["path"];
674                 }
675
676                 if (!empty($urlarr["query"])) {
677                         $complete .= "?".$urlarr["query"];
678                 }
679
680                 if (!empty($urlarr["fragment"])) {
681                         $complete .= "#".$urlarr["fragment"];
682                 }
683
684                 return($complete);
685         }
686
687         /**
688          * Parse the Json-Ld parts of a web page
689          *
690          * @param array $siteinfo
691          * @param array $jsonld
692          * @return array siteinfo
693          */
694         private static function parseParts(array $siteinfo, array $jsonld)
695         {
696                 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
697                         foreach ($jsonld['@graph'] as $part) {
698                                 if (!empty($part)) {
699                                         $siteinfo = self::parseParts($siteinfo, $part);
700                                 }
701                         }
702                 } elseif (!empty($jsonld['@type'])) {
703                         $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
704                 } elseif (!empty($jsonld)) {
705                         $keys = array_keys($jsonld);
706                         $numeric_keys = true;
707                         foreach ($keys as $key) {
708                                 if (!is_int($key)) {
709                                         $numeric_keys = false;
710                                 }
711                         }
712                         if ($numeric_keys) {
713                                 foreach ($jsonld as $part) {
714                                         if (!empty($part)) {
715                                                 $siteinfo = self::parseParts($siteinfo, $part);
716                                         }
717                                 }
718                         }
719                 }
720
721                 array_walk_recursive($siteinfo, function (&$element) {
722                         if (is_string($element)) {
723                                 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
724                         }
725                 });
726
727                 return $siteinfo;
728         }
729
730         /**
731          * Improve the siteinfo with information from the provided JSON-LD information
732          * @see https://jsonld.com/
733          * @see https://schema.org/
734          *
735          * @param array $siteinfo
736          * @param array $jsonld
737          * @return array siteinfo
738          */
739         private static function parseJsonLd(array $siteinfo, array $jsonld)
740         {
741                 $type = JsonLD::fetchElement($jsonld, '@type');
742                 if (empty($type)) {
743                         Logger::info('Empty type', ['url' => $siteinfo['url']]);
744                         return $siteinfo;
745                 }
746
747                 // Silently ignore some types that aren't processed
748                 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
749                         'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
750                         'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
751                         return $siteinfo;
752                 }
753
754                 switch ($type) {
755                         case 'Article':
756                         case 'AdvertiserContentArticle':
757                         case 'NewsArticle':
758                         case 'Report':
759                         case 'SatiricalArticle':
760                         case 'ScholarlyArticle':
761                         case 'SocialMediaPosting':
762                         case 'TechArticle':
763                         case 'ReportageNewsArticle':
764                         case 'SocialMediaPosting':
765                         case 'BlogPosting':
766                         case 'LiveBlogPosting':
767                         case 'DiscussionForumPosting':
768                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
769                         case 'WebPage':
770                         case 'AboutPage':
771                         case 'CheckoutPage':
772                         case 'CollectionPage':
773                         case 'ContactPage':
774                         case 'FAQPage':
775                         case 'ItemPage':
776                         case 'MedicalWebPage':
777                         case 'ProfilePage':
778                         case 'QAPage':
779                         case 'RealEstateListing':
780                         case 'SearchResultsPage':
781                         case 'MediaGallery':                    
782                         case 'ImageGallery':
783                         case 'VideoGallery':
784                         case 'RadioEpisode':
785                         case 'Event':
786                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
787                         case 'WebSite':
788                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
789                         case 'Organization':
790                         case 'Airline':
791                         case 'Consortium':
792                         case 'Corporation':
793                         case 'EducationalOrganization':
794                         case 'FundingScheme':
795                         case 'GovernmentOrganization':
796                         case 'LibrarySystem':
797                         case 'LocalBusiness':
798                         case 'MedicalOrganization':
799                         case 'NGO':
800                         case 'NewsMediaOrganization':
801                         case 'Project':
802                         case 'SportsOrganization':
803                         case 'WorkersUnion':
804                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
805                         case 'Person':
806                         case 'Patient':
807                         case 'PerformingGroup':
808                         case 'DanceGroup';
809                         case 'MusicGroup':
810                         case 'TheaterGroup':                    
811                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
812                         case 'AudioObject':
813                         case 'Audio':
814                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
815                         case 'VideoObject':
816                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
817                         case 'ImageObject':
818                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
819                         default:
820                                 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
821                                 return $siteinfo;
822                 }
823         }
824
825         /**
826          * Fetch author and publisher data
827          *
828          * @param array $siteinfo
829          * @param array $jsonld
830          * @return array siteinfo
831          */
832         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
833         {
834                 $jsonldinfo = [];
835
836                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
837                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
838                         if (!empty($content) && is_string($content)) {
839                                 $jsonldinfo['publisher_name'] = trim($content);
840                         }
841
842                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
843                         if (!empty($content) && is_string($content)) {
844                                 $jsonldinfo['publisher_url'] = trim($content);
845                         }
846
847                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
848                         if (!empty($brand) && is_array($brand)) {
849                                 $content = JsonLD::fetchElement($brand, 'name');
850                                 if (!empty($content) && is_string($content)) {
851                                         $jsonldinfo['publisher_name'] = trim($content);
852                                 }
853
854                                 $content = JsonLD::fetchElement($brand, 'url');
855                                 if (!empty($content) && is_string($content)) {
856                                         $jsonldinfo['publisher_url'] = trim($content);
857                                 }
858
859                                 $content = JsonLD::fetchElement($brand, 'logo', 'url');
860                                 if (!empty($content) && is_string($content)) {
861                                         $jsonldinfo['publisher_img'] = trim($content);
862                                 }
863                         }
864
865                         $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
866                         if (!empty($logo) && is_array($logo)) {
867                                 $content = JsonLD::fetchElement($logo, 'url');
868                                 if (!empty($content) && is_string($content)) {
869                                         $jsonldinfo['publisher_img'] = trim($content);
870                                 }
871                         }
872                 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
873                         $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
874                 }
875
876                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
877                         $content = JsonLD::fetchElement($jsonld, 'author', 'name');
878                         if (!empty($content) && is_string($content)) {
879                                 $jsonldinfo['author_name'] = trim($content);
880                         }
881
882                         $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
883                         if (!empty($content) && is_string($content)) {
884                                 $jsonldinfo['author_url'] = trim($content);
885                         }
886
887                         $content = JsonLD::fetchElement($jsonld, 'author', 'url');
888                         if (!empty($content) && is_string($content)) {
889                                 $jsonldinfo['author_url'] = trim($content);
890                         }
891
892                         $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
893                         if (!empty($logo) && is_array($logo)) {
894                                 $content = JsonLD::fetchElement($logo, 'url');
895                                 if (!empty($content) && is_string($content)) {
896                                         $jsonldinfo['author_img'] = trim($content);
897                                 }
898                         }
899                 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
900                         $jsonldinfo['author_name'] = trim($jsonld['author']);
901                 }
902
903                 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
904
905                 return array_merge($siteinfo, $jsonldinfo);
906         }
907
908         /**
909          * Fetch data from the provided JSON-LD Article type
910          * @see https://schema.org/Article
911          *
912          * @param array $siteinfo
913          * @param array $jsonld
914          * @return array siteinfo
915          */
916         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
917         {
918                 $jsonldinfo = [];
919
920                 $content = JsonLD::fetchElement($jsonld, 'headline');
921                 if (!empty($content) && is_string($content)) {
922                         $jsonldinfo['title'] = trim($content);
923                 }
924
925                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
926                 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
927                         $jsonldinfo['alternative_title'] = trim($content);
928                 }
929
930                 $content = JsonLD::fetchElement($jsonld, 'description');
931                 if (!empty($content) && is_string($content)) {
932                         $jsonldinfo['text'] = trim($content);
933                 }
934
935                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
936                 if (!empty($content)) {
937                         $jsonldinfo['image'] = trim($content);
938                 }
939
940                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
941                 if (!empty($content) && is_string($content)) {
942                         $jsonldinfo['image'] = trim($content);
943                 }
944
945                 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
946                         $content = JsonLD::fetchElement($jsonld, 'keywords');
947                         if (!empty($content)) {
948                                 $siteinfo['keywords'] = [];
949                                 $keywords = explode(',', $content);
950                                 foreach ($keywords as $keyword) {
951                                         $siteinfo['keywords'][] = trim($keyword);
952                                 }
953                         }
954                 } elseif (!empty($jsonld['keywords'])) {
955                         $content = JsonLD::fetchElementArray($jsonld, 'keywords');
956                         if (!empty($content) && is_array($content)) {
957                                 $jsonldinfo['keywords'] = $content;
958                         }
959                 }
960
961                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
962
963                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
964
965                 return array_merge($siteinfo, $jsonldinfo);
966         }
967
968         /**
969          * Fetch data from the provided JSON-LD WebPage type
970          * @see https://schema.org/WebPage
971          *
972          * @param array $siteinfo
973          * @param array $jsonld
974          * @return array siteinfo
975          */
976         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
977         {
978                 $jsonldinfo = [];
979
980                 $content = JsonLD::fetchElement($jsonld, 'name');
981                 if (!empty($content)) {
982                         $jsonldinfo['title'] = trim($content);
983                 }
984
985                 $content = JsonLD::fetchElement($jsonld, 'description');
986                 if (!empty($content)) {
987                         $jsonldinfo['text'] = trim($content);
988                 }
989
990                 $content = JsonLD::fetchElement($jsonld, 'image');
991                 if (!empty($content)) {
992                         $jsonldinfo['image'] = trim($content);
993                 }
994
995                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
996                 if (!empty($content)) {
997                         $jsonldinfo['image'] = trim($content);
998                 }
999
1000                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1001
1002                 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1003
1004                 return array_merge($siteinfo, $jsonldinfo);
1005         }
1006
1007         /**
1008          * Fetch data from the provided JSON-LD WebSite type
1009          * @see https://schema.org/WebSite
1010          *
1011          * @param array $siteinfo
1012          * @param array $jsonld
1013          * @return array siteinfo
1014          */
1015         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1016         {
1017                 $jsonldinfo = [];
1018
1019                 $content = JsonLD::fetchElement($jsonld, 'name');
1020                 if (!empty($content)) {
1021                         $jsonldinfo['publisher_name'] = trim($content);
1022                 }
1023
1024                 $content = JsonLD::fetchElement($jsonld, 'description');
1025                 if (!empty($content)) {
1026                         $jsonldinfo['publisher_description'] = trim($content);
1027                 }
1028
1029                 $content = JsonLD::fetchElement($jsonld, 'url');
1030                 if (!empty($content)) {
1031                         $jsonldinfo['publisher_url'] = trim($content);
1032                 }
1033
1034                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1035                 if (!empty($content)) {
1036                         $jsonldinfo['image'] = trim($content);
1037                 }
1038
1039                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1040
1041                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1042                 return array_merge($siteinfo, $jsonldinfo);
1043         }
1044
1045         /**
1046          * Fetch data from the provided JSON-LD Organization type
1047          * @see https://schema.org/Organization
1048          *
1049          * @param array $siteinfo
1050          * @param array $jsonld
1051          * @return array siteinfo
1052          */
1053         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1054         {
1055                 $jsonldinfo = [];
1056
1057                 $content = JsonLD::fetchElement($jsonld, 'name');
1058                 if (!empty($content)) {
1059                         $jsonldinfo['publisher_name'] = trim($content);
1060                 }
1061
1062                 $content = JsonLD::fetchElement($jsonld, 'description');
1063                 if (!empty($content)) {
1064                         $jsonldinfo['publisher_description'] = trim($content);
1065                 }
1066
1067                 $content = JsonLD::fetchElement($jsonld, 'url');
1068                 if (!empty($content)) {
1069                         $jsonldinfo['publisher_url'] = trim($content);
1070                 }
1071
1072                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1073                 if (!empty($content)) {
1074                         $jsonldinfo['publisher_img'] = trim($content);
1075                 }
1076
1077                 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1078                 if (!empty($content)) {
1079                         $jsonldinfo['publisher_name'] = trim($content);
1080                 }
1081
1082                 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1083                 if (!empty($content)) {
1084                         $jsonldinfo['publisher_url'] = trim($content);
1085                 }
1086
1087                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1088                 return array_merge($siteinfo, $jsonldinfo);
1089         }
1090
1091         /**
1092          * Fetch data from the provided JSON-LD Person type
1093          * @see https://schema.org/Person
1094          *
1095          * @param array $siteinfo
1096          * @param array $jsonld
1097          * @return array siteinfo
1098          */
1099         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1100         {
1101                 $jsonldinfo = [];
1102
1103                 $content = JsonLD::fetchElement($jsonld, 'name');
1104                 if (!empty($content)) {
1105                         $jsonldinfo['author_name'] = trim($content);
1106                 }
1107
1108                 $content = JsonLD::fetchElement($jsonld, 'description');
1109                 if (!empty($content)) {
1110                         $jsonldinfo['author_description'] = trim($content);
1111                 }
1112
1113                 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1114                 if (!empty($content) && is_string($content)) {
1115                         $jsonldinfo['author_url'] = trim($content);
1116                 }
1117
1118                 $content = JsonLD::fetchElement($jsonld, 'url');
1119                 if (!empty($content)) {
1120                         $jsonldinfo['author_url'] = trim($content);
1121                 }
1122
1123                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1124                 if (!empty($content)) {
1125                         $jsonldinfo['author_img'] = trim($content);
1126                 }
1127
1128                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1129                 return array_merge($siteinfo, $jsonldinfo);
1130         }
1131
1132         /**
1133          * Fetch data from the provided JSON-LD MediaObject type
1134          * @see https://schema.org/MediaObject
1135          *
1136          * @param array $siteinfo
1137          * @param array $jsonld
1138          * @return array siteinfo
1139          */
1140         private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1141         {
1142                 $media = [];
1143
1144                 $content = JsonLD::fetchElement($jsonld, 'caption');
1145                 if (!empty($content)) {
1146                         $media['caption'] = trim($content);
1147                 }
1148
1149                 $content = JsonLD::fetchElement($jsonld, 'url');
1150                 if (!empty($content)) {
1151                         $media['url'] = trim($content);
1152                 }
1153
1154                 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1155                 if (!empty($content)) {
1156                         $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1157                 }
1158
1159                 $content = JsonLD::fetchElement($jsonld, 'description');
1160                 if (!empty($content)) {
1161                         $media['description'] = trim($content);
1162                 }
1163
1164                 $content = JsonLD::fetchElement($jsonld, 'name');
1165                 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1166                         $media['name'] = trim($content);
1167                 }
1168
1169                 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1170                 if (!empty($content)) {
1171                         $media['content'] = trim($content);
1172                 }
1173
1174                 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1175                 if (!empty($content)) {
1176                         $media['embed'] = trim($content);
1177                 }
1178
1179                 $content = JsonLD::fetchElement($jsonld, 'height');
1180                 if (!empty($content)) {
1181                         $media['height'] = trim($content);
1182                 }
1183
1184                 $content = JsonLD::fetchElement($jsonld, 'width');
1185                 if (!empty($content)) {
1186                         $media['width'] = trim($content);
1187                 }
1188
1189                 $content = JsonLD::fetchElement($jsonld, 'image');
1190                 if (!empty($content)) {
1191                         $media['image'] = trim($content);
1192                 }
1193
1194                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1195                 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1196                         if (!empty($media['image'])) {
1197                                 $media['preview'] = trim($content);
1198                         } else {
1199                                 $media['image'] = trim($content);
1200                         }
1201                 }
1202
1203                 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1204                 $siteinfo[$name][] = $media;
1205                 return $siteinfo;
1206         }
1207 }