]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
683544f44860d42b7cf2c008b199835ada1a762a
[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                 // Prevent to have a photo type without an image
481                 if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
482                         $siteinfo['type'] = 'photo';
483                 }
484
485                 if (!empty($siteinfo['image'])) {
486                         $siteinfo['images'] = $siteinfo['images'] ?? [];
487                         array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
488                         unset($siteinfo['image']);
489                 }
490
491                 $siteinfo = self::checkMedia($url, $siteinfo);
492
493                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
494                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
495                         $pos = mb_strrpos($siteinfo['text'], '.');
496                         if ($pos > self::MIN_DESC_COUNT) {
497                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
498                         }
499                 }
500
501                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
502
503                 Hook::callAll('getsiteinfo', $siteinfo);
504
505                 return $siteinfo;
506         }
507
508         /**
509          * Check the attached media elements.
510          * Fix existing data and add missing data.
511          *
512          * @param string $page_url
513          * @param array $siteinfo
514          * @return void
515          */
516         private static function checkMedia(string $page_url, array $siteinfo)
517         {
518                 if (!empty($siteinfo['images'])) {
519                         array_walk($siteinfo['images'], function (&$image) use ($page_url) {
520                                 // According to the specifications someone could place a picture url into the content field as well.
521                                 // But this doesn't seem to happen in the wild, so we don't cover it here.
522                                 if (!empty($image['url'])) {
523                                         $image['url'] = self::completeUrl($image['url'], $page_url);
524                                         $photodata = Images::getInfoFromURLCached($image['url']);
525                                         if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
526                                                 $image['src'] = $image['url'];
527                                                 $image['width'] = $photodata[0];
528                                                 $image['height'] = $photodata[1];
529                                                 $image['contenttype'] = $photodata['mime'];
530                                                 unset($image['url']);
531                                                 ksort($image);
532                                         } else {
533                                                 $image = [];
534                                         }
535                                 } else {
536                                         $image = [];
537                                 }
538                         });
539
540                         $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
541                 }
542
543                 foreach (['audio', 'video'] as $element) {
544                         if (!empty($siteinfo[$element])) {
545                                 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
546                                         $url = '';
547                                         $embed = '';
548                                         $content = '';
549                                         $contenttype = '';
550                                         foreach (['embed', 'content', 'url'] as $field) {
551                                                 if (!empty($media[$field])) {
552                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
553                                                         $type = self::getContentType($media[$field]);
554                                                         if (($type[0] ?? '') == 'text') {
555                                                                 if ($field == 'embed') {
556                                                                         $embed = $media[$field];
557                                                                 } else {
558                                                                         $url = $media[$field];
559                                                                 }
560                                                         } elseif (!empty($type[0])) {
561                                                                 $content = $media[$field];
562                                                                 $contenttype = implode('/', $type);
563                                                         }
564                                                 }
565                                                 unset($media[$field]);
566                                         }
567
568                                         foreach (['image', 'preview'] as $field) {
569                                                 if (!empty($media[$field])) {
570                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
571                                                 }
572                                         }
573
574                                         if (!empty($url)) {
575                                                 $media['url'] = $url;
576                                         }
577                                         if (!empty($embed)) {
578                                                 $media['embed'] = $embed;
579                                                 if (!empty($media['main'])) {
580                                                         $siteinfo['embed'] = $embed;
581                                                 }
582                                         }
583                                         if (!empty($content)) {
584                                                 $media['src'] = $content;
585                                         }
586                                         if (!empty($contenttype)) {
587                                                 $media['contenttype'] = $contenttype;
588                                         }
589                                         if (empty($url) && empty($content) && empty($embed)) {
590                                                 $media = [];
591                                         }
592                                         ksort($media);
593                                 });
594
595                                 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
596                         }
597                         if (empty($siteinfo[$element])) {
598                                 unset($siteinfo[$element]);
599                         }
600                 }
601                 return $siteinfo;
602         }
603
604         /**
605          * Convert tags from CSV to an array
606          *
607          * @param string $string Tags
608          * @return array with formatted Hashtags
609          */
610         public static function convertTagsToArray($string)
611         {
612                 $arr_tags = str_getcsv($string);
613                 if (count($arr_tags)) {
614                         // add the # sign to every tag
615                         array_walk($arr_tags, ["self", "arrAddHashes"]);
616
617                         return $arr_tags;
618                 }
619         }
620
621         /**
622          * Add a hasht sign to a string
623          *
624          * This method is used as callback function
625          *
626          * @param string $tag The pure tag name
627          * @param int    $k   Counter for internal use
628          * @return void
629          */
630         private static function arrAddHashes(&$tag, $k)
631         {
632                 $tag = "#" . $tag;
633         }
634
635         /**
636          * Add a scheme to an url
637          *
638          * The src attribute of some html elements (e.g. images)
639          * can miss the scheme so we need to add the correct
640          * scheme
641          *
642          * @param string $url    The url which possibly does have
643          *                       a missing scheme (a link to an image)
644          * @param string $scheme The url with a correct scheme
645          *                       (e.g. the url from the webpage which does contain the image)
646          *
647          * @return string The url with a scheme
648          */
649         private static function completeUrl($url, $scheme)
650         {
651                 $urlarr = parse_url($url);
652
653                 // If the url does allready have an scheme
654                 // we can stop the process here
655                 if (isset($urlarr["scheme"])) {
656                         return($url);
657                 }
658
659                 $schemearr = parse_url($scheme);
660
661                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
662
663                 if (!empty($schemearr["port"])) {
664                         $complete .= ":".$schemearr["port"];
665                 }
666
667                 if (!empty($urlarr["path"])) {
668                         if (strpos($urlarr["path"], "/") !== 0) {
669                                 $complete .= "/";
670                         }
671
672                         $complete .= $urlarr["path"];
673                 }
674
675                 if (!empty($urlarr["query"])) {
676                         $complete .= "?".$urlarr["query"];
677                 }
678
679                 if (!empty($urlarr["fragment"])) {
680                         $complete .= "#".$urlarr["fragment"];
681                 }
682
683                 return($complete);
684         }
685
686         /**
687          * Parse the Json-Ld parts of a web page
688          *
689          * @param array $siteinfo
690          * @param array $jsonld
691          * @return array siteinfo
692          */
693         private static function parseParts(array $siteinfo, array $jsonld)
694         {
695                 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
696                         foreach ($jsonld['@graph'] as $part) {
697                                 if (!empty($part)) {
698                                         $siteinfo = self::parseParts($siteinfo, $part);
699                                 }
700                         }
701                 } elseif (!empty($jsonld['@type'])) {
702                         $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
703                 } elseif (!empty($jsonld)) {
704                         $keys = array_keys($jsonld);
705                         $numeric_keys = true;
706                         foreach ($keys as $key) {
707                                 if (!is_int($key)) {
708                                         $numeric_keys = false;
709                                 }
710                         }
711                         if ($numeric_keys) {
712                                 foreach ($jsonld as $part) {
713                                         if (!empty($part)) {
714                                                 $siteinfo = self::parseParts($siteinfo, $part);
715                                         }
716                                 }
717                         }
718                 }
719
720                 array_walk_recursive($siteinfo, function (&$element) {
721                         if (is_string($element)) {
722                                 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
723                         }
724                 });
725
726                 return $siteinfo;
727         }
728
729         /**
730          * Improve the siteinfo with information from the provided JSON-LD information
731          * @see https://jsonld.com/
732          * @see https://schema.org/
733          *
734          * @param array $siteinfo
735          * @param array $jsonld
736          * @return array siteinfo
737          */
738         private static function parseJsonLd(array $siteinfo, array $jsonld)
739         {
740                 $type = JsonLD::fetchElement($jsonld, '@type');
741                 if (empty($type)) {
742                         Logger::info('Empty type', ['url' => $siteinfo['url']]);
743                         return $siteinfo;
744                 }
745
746                 // Silently ignore some types that aren't processed
747                 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
748                         'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
749                         'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
750                         return $siteinfo;
751                 }
752
753                 switch ($type) {
754                         case 'Article':
755                         case 'AdvertiserContentArticle':
756                         case 'NewsArticle':
757                         case 'Report':
758                         case 'SatiricalArticle':
759                         case 'ScholarlyArticle':
760                         case 'SocialMediaPosting':
761                         case 'TechArticle':
762                         case 'ReportageNewsArticle':
763                         case 'SocialMediaPosting':
764                         case 'BlogPosting':
765                         case 'LiveBlogPosting':
766                         case 'DiscussionForumPosting':
767                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
768                         case 'WebPage':
769                         case 'AboutPage':
770                         case 'CheckoutPage':
771                         case 'CollectionPage':
772                         case 'ContactPage':
773                         case 'FAQPage':
774                         case 'ItemPage':
775                         case 'MedicalWebPage':
776                         case 'ProfilePage':
777                         case 'QAPage':
778                         case 'RealEstateListing':
779                         case 'SearchResultsPage':
780                         case 'MediaGallery':                    
781                         case 'ImageGallery':
782                         case 'VideoGallery':
783                         case 'RadioEpisode':
784                         case 'Event':
785                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
786                         case 'WebSite':
787                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
788                         case 'Organization':
789                         case 'Airline':
790                         case 'Consortium':
791                         case 'Corporation':
792                         case 'EducationalOrganization':
793                         case 'FundingScheme':
794                         case 'GovernmentOrganization':
795                         case 'LibrarySystem':
796                         case 'LocalBusiness':
797                         case 'MedicalOrganization':
798                         case 'NGO':
799                         case 'NewsMediaOrganization':
800                         case 'Project':
801                         case 'SportsOrganization':
802                         case 'WorkersUnion':
803                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
804                         case 'Person':
805                         case 'Patient':
806                         case 'PerformingGroup':
807                         case 'DanceGroup';
808                         case 'MusicGroup':
809                         case 'TheaterGroup':                    
810                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
811                         case 'AudioObject':
812                         case 'Audio':
813                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
814                         case 'VideoObject':
815                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
816                         case 'ImageObject':
817                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
818                         default:
819                                 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
820                                 return $siteinfo;
821                 }
822         }
823
824         /**
825          * Fetch author and publisher data
826          *
827          * @param array $siteinfo
828          * @param array $jsonld
829          * @return array siteinfo
830          */
831         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
832         {
833                 $jsonldinfo = [];
834
835                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
836                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
837                         if (!empty($content) && is_string($content)) {
838                                 $jsonldinfo['publisher_name'] = trim($content);
839                         }
840
841                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
842                         if (!empty($content) && is_string($content)) {
843                                 $jsonldinfo['publisher_url'] = trim($content);
844                         }
845
846                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
847                         if (!empty($brand) && is_array($brand)) {
848                                 $content = JsonLD::fetchElement($brand, 'name');
849                                 if (!empty($content) && is_string($content)) {
850                                         $jsonldinfo['publisher_name'] = trim($content);
851                                 }
852
853                                 $content = JsonLD::fetchElement($brand, 'url');
854                                 if (!empty($content) && is_string($content)) {
855                                         $jsonldinfo['publisher_url'] = trim($content);
856                                 }
857
858                                 $content = JsonLD::fetchElement($brand, 'logo', 'url');
859                                 if (!empty($content) && is_string($content)) {
860                                         $jsonldinfo['publisher_img'] = trim($content);
861                                 }
862                         }
863
864                         $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
865                         if (!empty($logo) && is_array($logo)) {
866                                 $content = JsonLD::fetchElement($logo, 'url');
867                                 if (!empty($content) && is_string($content)) {
868                                         $jsonldinfo['publisher_img'] = trim($content);
869                                 }
870                         }
871                 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
872                         $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
873                 }
874
875                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
876                         $content = JsonLD::fetchElement($jsonld, 'author', 'name');
877                         if (!empty($content) && is_string($content)) {
878                                 $jsonldinfo['author_name'] = trim($content);
879                         }
880
881                         $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
882                         if (!empty($content) && is_string($content)) {
883                                 $jsonldinfo['author_url'] = trim($content);
884                         }
885
886                         $content = JsonLD::fetchElement($jsonld, 'author', 'url');
887                         if (!empty($content) && is_string($content)) {
888                                 $jsonldinfo['author_url'] = trim($content);
889                         }
890
891                         $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
892                         if (!empty($logo) && is_array($logo)) {
893                                 $content = JsonLD::fetchElement($logo, 'url');
894                                 if (!empty($content) && is_string($content)) {
895                                         $jsonldinfo['author_img'] = trim($content);
896                                 }
897                         }
898                 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
899                         $jsonldinfo['author_name'] = trim($jsonld['author']);
900                 }
901
902                 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
903
904                 return array_merge($siteinfo, $jsonldinfo);
905         }
906
907         /**
908          * Fetch data from the provided JSON-LD Article type
909          * @see https://schema.org/Article
910          *
911          * @param array $siteinfo
912          * @param array $jsonld
913          * @return array siteinfo
914          */
915         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
916         {
917                 $jsonldinfo = [];
918
919                 $content = JsonLD::fetchElement($jsonld, 'headline');
920                 if (!empty($content) && is_string($content)) {
921                         $jsonldinfo['title'] = trim($content);
922                 }
923
924                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
925                 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
926                         $jsonldinfo['alternative_title'] = trim($content);
927                 }
928
929                 $content = JsonLD::fetchElement($jsonld, 'description');
930                 if (!empty($content) && is_string($content)) {
931                         $jsonldinfo['text'] = trim($content);
932                 }
933
934                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
935                 if (!empty($content)) {
936                         $jsonldinfo['image'] = trim($content);
937                 }
938
939                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
940                 if (!empty($content) && is_string($content)) {
941                         $jsonldinfo['image'] = trim($content);
942                 }
943
944                 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
945                         $content = JsonLD::fetchElement($jsonld, 'keywords');
946                         if (!empty($content)) {
947                                 $siteinfo['keywords'] = [];
948                                 $keywords = explode(',', $content);
949                                 foreach ($keywords as $keyword) {
950                                         $siteinfo['keywords'][] = trim($keyword);
951                                 }
952                         }
953                 } elseif (!empty($jsonld['keywords'])) {
954                         $content = JsonLD::fetchElementArray($jsonld, 'keywords');
955                         if (!empty($content) && is_array($content)) {
956                                 $jsonldinfo['keywords'] = $content;
957                         }
958                 }
959
960                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
961
962                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
963
964                 return array_merge($siteinfo, $jsonldinfo);
965         }
966
967         /**
968          * Fetch data from the provided JSON-LD WebPage type
969          * @see https://schema.org/WebPage
970          *
971          * @param array $siteinfo
972          * @param array $jsonld
973          * @return array siteinfo
974          */
975         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
976         {
977                 $jsonldinfo = [];
978
979                 $content = JsonLD::fetchElement($jsonld, 'name');
980                 if (!empty($content)) {
981                         $jsonldinfo['title'] = trim($content);
982                 }
983
984                 $content = JsonLD::fetchElement($jsonld, 'description');
985                 if (!empty($content)) {
986                         $jsonldinfo['text'] = trim($content);
987                 }
988
989                 $content = JsonLD::fetchElement($jsonld, 'image');
990                 if (!empty($content)) {
991                         $jsonldinfo['image'] = trim($content);
992                 }
993
994                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
995                 if (!empty($content)) {
996                         $jsonldinfo['image'] = trim($content);
997                 }
998
999                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1000
1001                 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1002
1003                 return array_merge($siteinfo, $jsonldinfo);
1004         }
1005
1006         /**
1007          * Fetch data from the provided JSON-LD WebSite type
1008          * @see https://schema.org/WebSite
1009          *
1010          * @param array $siteinfo
1011          * @param array $jsonld
1012          * @return array siteinfo
1013          */
1014         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1015         {
1016                 $jsonldinfo = [];
1017
1018                 $content = JsonLD::fetchElement($jsonld, 'name');
1019                 if (!empty($content)) {
1020                         $jsonldinfo['publisher_name'] = trim($content);
1021                 }
1022
1023                 $content = JsonLD::fetchElement($jsonld, 'description');
1024                 if (!empty($content)) {
1025                         $jsonldinfo['publisher_description'] = trim($content);
1026                 }
1027
1028                 $content = JsonLD::fetchElement($jsonld, 'url');
1029                 if (!empty($content)) {
1030                         $jsonldinfo['publisher_url'] = trim($content);
1031                 }
1032
1033                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1034                 if (!empty($content)) {
1035                         $jsonldinfo['image'] = trim($content);
1036                 }
1037
1038                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1039
1040                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1041                 return array_merge($siteinfo, $jsonldinfo);
1042         }
1043
1044         /**
1045          * Fetch data from the provided JSON-LD Organization type
1046          * @see https://schema.org/Organization
1047          *
1048          * @param array $siteinfo
1049          * @param array $jsonld
1050          * @return array siteinfo
1051          */
1052         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1053         {
1054                 $jsonldinfo = [];
1055
1056                 $content = JsonLD::fetchElement($jsonld, 'name');
1057                 if (!empty($content)) {
1058                         $jsonldinfo['publisher_name'] = trim($content);
1059                 }
1060
1061                 $content = JsonLD::fetchElement($jsonld, 'description');
1062                 if (!empty($content)) {
1063                         $jsonldinfo['publisher_description'] = trim($content);
1064                 }
1065
1066                 $content = JsonLD::fetchElement($jsonld, 'url');
1067                 if (!empty($content)) {
1068                         $jsonldinfo['publisher_url'] = trim($content);
1069                 }
1070
1071                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1072                 if (!empty($content)) {
1073                         $jsonldinfo['publisher_img'] = trim($content);
1074                 }
1075
1076                 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1077                 if (!empty($content)) {
1078                         $jsonldinfo['publisher_name'] = trim($content);
1079                 }
1080
1081                 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1082                 if (!empty($content)) {
1083                         $jsonldinfo['publisher_url'] = trim($content);
1084                 }
1085
1086                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1087                 return array_merge($siteinfo, $jsonldinfo);
1088         }
1089
1090         /**
1091          * Fetch data from the provided JSON-LD Person type
1092          * @see https://schema.org/Person
1093          *
1094          * @param array $siteinfo
1095          * @param array $jsonld
1096          * @return array siteinfo
1097          */
1098         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1099         {
1100                 $jsonldinfo = [];
1101
1102                 $content = JsonLD::fetchElement($jsonld, 'name');
1103                 if (!empty($content)) {
1104                         $jsonldinfo['author_name'] = trim($content);
1105                 }
1106
1107                 $content = JsonLD::fetchElement($jsonld, 'description');
1108                 if (!empty($content)) {
1109                         $jsonldinfo['author_description'] = trim($content);
1110                 }
1111
1112                 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1113                 if (!empty($content) && is_string($content)) {
1114                         $jsonldinfo['author_url'] = trim($content);
1115                 }
1116
1117                 $content = JsonLD::fetchElement($jsonld, 'url');
1118                 if (!empty($content)) {
1119                         $jsonldinfo['author_url'] = trim($content);
1120                 }
1121
1122                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1123                 if (!empty($content)) {
1124                         $jsonldinfo['author_img'] = trim($content);
1125                 }
1126
1127                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1128                 return array_merge($siteinfo, $jsonldinfo);
1129         }
1130
1131         /**
1132          * Fetch data from the provided JSON-LD MediaObject type
1133          * @see https://schema.org/MediaObject
1134          *
1135          * @param array $siteinfo
1136          * @param array $jsonld
1137          * @return array siteinfo
1138          */
1139         private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1140         {
1141                 $media = [];
1142
1143                 $content = JsonLD::fetchElement($jsonld, 'caption');
1144                 if (!empty($content)) {
1145                         $media['caption'] = trim($content);
1146                 }
1147
1148                 $content = JsonLD::fetchElement($jsonld, 'url');
1149                 if (!empty($content)) {
1150                         $media['url'] = trim($content);
1151                 }
1152
1153                 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1154                 if (!empty($content)) {
1155                         $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1156                 }
1157
1158                 $content = JsonLD::fetchElement($jsonld, 'description');
1159                 if (!empty($content)) {
1160                         $media['description'] = trim($content);
1161                 }
1162
1163                 $content = JsonLD::fetchElement($jsonld, 'name');
1164                 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1165                         $media['name'] = trim($content);
1166                 }
1167
1168                 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1169                 if (!empty($content)) {
1170                         $media['content'] = trim($content);
1171                 }
1172
1173                 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1174                 if (!empty($content)) {
1175                         $media['embed'] = trim($content);
1176                 }
1177
1178                 $content = JsonLD::fetchElement($jsonld, 'height');
1179                 if (!empty($content)) {
1180                         $media['height'] = trim($content);
1181                 }
1182
1183                 $content = JsonLD::fetchElement($jsonld, 'width');
1184                 if (!empty($content)) {
1185                         $media['width'] = trim($content);
1186                 }
1187
1188                 $content = JsonLD::fetchElement($jsonld, 'image');
1189                 if (!empty($content)) {
1190                         $media['image'] = trim($content);
1191                 }
1192
1193                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1194                 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1195                         if (!empty($media['image'])) {
1196                                 $media['preview'] = trim($content);
1197                         } else {
1198                                 $media['image'] = trim($content);
1199                         }
1200                 }
1201
1202                 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1203                 $siteinfo[$name][] = $media;
1204                 return $siteinfo;
1205         }
1206 }