]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Display rhe provider and author of a shared post
[friendica.git] / src / Util / ParseUrl.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\OEmbed;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Network\HTTPException;
33
34 /**
35  * Get information about a given URL
36  *
37  * Class with methods for extracting certain content from an url
38  */
39 class ParseUrl
40 {
41         const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42         const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
43
44         /**
45          * Maximum number of characters for the description
46          */
47         const MAX_DESC_COUNT = 250;
48
49         /**
50          * Minimum number of characters for the description
51          */
52         const MIN_DESC_COUNT = 100;
53
54         /**
55          * Fetch the content type of the given url
56          * @param string $url URL of the page
57          * @return 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()) {
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                 $list = $xpath->query('//meta[@name]');
353                 foreach ($list as $node) {
354                         $meta_tag = [];
355                         if ($node->attributes->length) {
356                                 foreach ($node->attributes as $attribute) {
357                                         $meta_tag[$attribute->name] = $attribute->value;
358                                 }
359                         }
360
361                         if (empty($meta_tag['content'])) {
362                                 continue;
363                         }
364
365                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
366
367                         switch (strtolower($meta_tag['name'])) {
368                                 case 'fulltitle':
369                                         $siteinfo['title'] = trim($meta_tag['content']);
370                                         break;
371                                 case 'description':
372                                         $siteinfo['text'] = trim($meta_tag['content']);
373                                         break;
374                                 case 'thumbnail':
375                                         $siteinfo['image'] = $meta_tag['content'];
376                                         break;
377                                 case 'twitter:image':
378                                         $siteinfo['image'] = $meta_tag['content'];
379                                         break;
380                                 case 'twitter:image:src':
381                                         $siteinfo['image'] = $meta_tag['content'];
382                                         break;
383                                 case 'twitter:card':
384                                         // Detect photo pages
385                                         if ($meta_tag['content'] == 'summary_large_image') {
386                                                 $siteinfo['type'] = 'photo';
387                                         }
388                                         break;
389                                 case 'twitter:description':
390                                         $siteinfo['text'] = trim($meta_tag['content']);
391                                         break;
392                                 case 'twitter:title':
393                                         $siteinfo['title'] = trim($meta_tag['content']);
394                                         break;
395                                 case 'dc.title':
396                                         $siteinfo['title'] = trim($meta_tag['content']);
397                                         break;
398                                 case 'dc.description':
399                                         $siteinfo['text'] = trim($meta_tag['content']);
400                                         break;
401                                 case 'dc.creator':
402                                         $siteinfo['publisher_name'] = trim($meta_tag['content']);
403                                         break;
404                                 case 'keywords':
405                                         $keywords = explode(',', $meta_tag['content']);
406                                         break;
407                                 case 'news_keywords':
408                                         $keywords = explode(',', $meta_tag['content']);
409                                         break;
410                         }
411                 }
412
413                 if (isset($keywords)) {
414                         $siteinfo['keywords'] = [];
415                         foreach ($keywords as $keyword) {
416                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
417                                         $siteinfo['keywords'][] = trim($keyword);
418                                 }
419                         }
420                 }
421
422                 $list = $xpath->query('//meta[@property]');
423                 foreach ($list as $node) {
424                         $meta_tag = [];
425                         if ($node->attributes->length) {
426                                 foreach ($node->attributes as $attribute) {
427                                         $meta_tag[$attribute->name] = $attribute->value;
428                                 }
429                         }
430
431                         if (!empty($meta_tag['content'])) {
432                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
433
434                                 switch (strtolower($meta_tag['property'])) {
435                                         case 'og:image':
436                                                 $siteinfo['image'] = $meta_tag['content'];
437                                                 break;
438                                         case 'og:image:url':
439                                                 $siteinfo['image'] = $meta_tag['content'];
440                                                 break;
441                                         case 'og:image:secure_url':
442                                                 $siteinfo['image'] = $meta_tag['content'];
443                                                 break;
444                                         case 'og:title':
445                                                 $siteinfo['title'] = trim($meta_tag['content']);
446                                                 break;
447                                         case 'og:description':
448                                                 $siteinfo['text'] = trim($meta_tag['content']);
449                                                 break;
450                                         case 'og:site_name':
451                                                 $siteinfo['publisher_name'] = trim($meta_tag['content']);
452                                                 break;
453                                         case 'twitter:description':
454                                                 $siteinfo['text'] = trim($meta_tag['content']);
455                                                 break;
456                                         case 'twitter:title':
457                                                 $siteinfo['title'] = trim($meta_tag['content']);
458                                                 break;
459                                         case 'twitter:image':
460                                                 $siteinfo['image'] = $meta_tag['content'];
461                                                 break;
462                                 }
463                         }
464                 }
465
466                 $list = $xpath->query("//script[@type='application/ld+json']");
467                 foreach ($list as $node) {
468                         if (!empty($node->nodeValue)) {
469                                 $nodevalue = html_entity_decode($node->nodeValue, ENT_COMPAT, 'UTF-8');
470                                 if ($jsonld = json_decode($nodevalue, true)) {
471                                         $siteinfo = self::parseParts($siteinfo, $jsonld);
472                                 }
473                         }
474                 }
475
476                 // Prevent to have a photo type without an image
477                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
478                         $siteinfo['type'] = 'link';
479                 }
480
481                 if (!empty($siteinfo['image'])) {
482                         $siteinfo['images'] = $siteinfo['images'] ?? [];
483                         array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
484                         unset($siteinfo['image']);
485                 }
486
487                 $siteinfo = self::checkMedia($url, $siteinfo);
488
489                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
490                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
491                         $pos = mb_strrpos($siteinfo['text'], '.');
492                         if ($pos > self::MIN_DESC_COUNT) {
493                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
494                         }
495                 }
496
497                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
498
499                 Hook::callAll('getsiteinfo', $siteinfo);
500
501                 return $siteinfo;
502         }
503
504         /**
505          * Check the attached media elements.
506          * Fix existing data and add missing data.
507          *
508          * @param string $page_url
509          * @param array $siteinfo
510          * @return void
511          */
512         private static function checkMedia(string $page_url, array $siteinfo)
513         {
514                 if (!empty($siteinfo['images'])) {
515                         array_walk($siteinfo['images'], function (&$image) use ($page_url) {
516                                 // According to the specifications someone could place a picture url into the content field as well.
517                                 // But this doesn't seem to happen in the wild, so we don't cover it here.
518                                 $image['url'] = self::completeUrl($image['url'], $page_url);
519                                 $photodata = Images::getInfoFromURLCached($image['url']);
520                                 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
521                                         $image['src'] = $image['url'];
522                                         $image['width'] = $photodata[0];
523                                         $image['height'] = $photodata[1];
524                                         $image['contenttype'] = $photodata['mime'];
525                                         unset($image['url']);
526                                         ksort($image);
527                                 } else {
528                                         $image = [];
529                                 }
530                         });
531
532                         $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
533                 }
534
535                 foreach (['audio', 'video'] as $element) {
536                         if (!empty($siteinfo[$element])) {
537                                 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
538                                         $url = '';
539                                         $embed = '';
540                                         $content = '';
541                                         $contenttype = '';
542                                         foreach (['embed', 'content', 'url'] as $field) {
543                                                 if (!empty($media[$field])) {
544                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
545                                                         $type = self::getContentType($media[$field]);
546                                                         if ($type[0] == 'text') {
547                                                                 if ($field == 'embed') {
548                                                                         $embed = $media[$field];
549                                                                 } else {
550                                                                         $url = $media[$field];
551                                                                 }
552                                                         } elseif (!empty($type[0])) {
553                                                                 $content = $media[$field];
554                                                                 $contenttype = implode('/', $type);
555                                                         }
556                                                 }
557                                                 unset($media[$field]);
558                                         }
559
560                                         foreach (['image', 'preview'] as $field) {
561                                                 if (!empty($media[$field])) {
562                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
563                                                 }
564                                         }
565
566                                         if (!empty($url)) {
567                                                 $media['url'] = $url;
568                                         }
569                                         if (!empty($embed)) {
570                                                 $media['embed'] = $embed;
571                                                 if (!empty($media['main'])) {
572                                                         $siteinfo['embed'] = $embed;
573                                                 }
574                                         }
575                                         if (!empty($content)) {
576                                                 $media['src'] = $content;
577                                         }
578                                         if (!empty($contenttype)) {
579                                                 $media['contenttype'] = $contenttype;
580                                         }
581                                         if (empty($url) && empty($content) && empty($embed)) {
582                                                 $media = [];
583                                         }
584                                         ksort($media);
585                                 });
586
587                                 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
588                         }
589                         if (empty($siteinfo[$element])) {
590                                 unset($siteinfo[$element]);
591                         }
592                 }
593                 return $siteinfo;
594         }
595
596         /**
597          * Convert tags from CSV to an array
598          *
599          * @param string $string Tags
600          * @return array with formatted Hashtags
601          */
602         public static function convertTagsToArray($string)
603         {
604                 $arr_tags = str_getcsv($string);
605                 if (count($arr_tags)) {
606                         // add the # sign to every tag
607                         array_walk($arr_tags, ["self", "arrAddHashes"]);
608
609                         return $arr_tags;
610                 }
611         }
612
613         /**
614          * Add a hasht sign to a string
615          *
616          * This method is used as callback function
617          *
618          * @param string $tag The pure tag name
619          * @param int    $k   Counter for internal use
620          * @return void
621          */
622         private static function arrAddHashes(&$tag, $k)
623         {
624                 $tag = "#" . $tag;
625         }
626
627         /**
628          * Add a scheme to an url
629          *
630          * The src attribute of some html elements (e.g. images)
631          * can miss the scheme so we need to add the correct
632          * scheme
633          *
634          * @param string $url    The url which possibly does have
635          *                       a missing scheme (a link to an image)
636          * @param string $scheme The url with a correct scheme
637          *                       (e.g. the url from the webpage which does contain the image)
638          *
639          * @return string The url with a scheme
640          */
641         private static function completeUrl($url, $scheme)
642         {
643                 $urlarr = parse_url($url);
644
645                 // If the url does allready have an scheme
646                 // we can stop the process here
647                 if (isset($urlarr["scheme"])) {
648                         return($url);
649                 }
650
651                 $schemearr = parse_url($scheme);
652
653                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
654
655                 if (!empty($schemearr["port"])) {
656                         $complete .= ":".$schemearr["port"];
657                 }
658
659                 if (!empty($urlarr["path"])) {
660                         if (strpos($urlarr["path"], "/") !== 0) {
661                                 $complete .= "/";
662                         }
663
664                         $complete .= $urlarr["path"];
665                 }
666
667                 if (!empty($urlarr["query"])) {
668                         $complete .= "?".$urlarr["query"];
669                 }
670
671                 if (!empty($urlarr["fragment"])) {
672                         $complete .= "#".$urlarr["fragment"];
673                 }
674
675                 return($complete);
676         }
677
678         /**
679          * Parse the Json-Ld parts of a web page
680          *
681          * @param array $siteinfo
682          * @param array $jsonld
683          * @return array siteinfo
684          */
685         private static function parseParts(array $siteinfo, array $jsonld)
686         {
687                 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
688                         foreach ($jsonld['@graph'] as $part) {
689                                 $siteinfo = self::parseParts($siteinfo, $part);
690                         }
691                 } elseif (!empty($jsonld['@type'])) {
692                         $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
693                 } elseif (!empty($jsonld)) {
694                         $keys = array_keys($jsonld);
695                         $numeric_keys = true;
696                         foreach ($keys as $key) {
697                                 if (!is_int($key)) {
698                                         $numeric_keys = false;
699                                 }
700                         }
701                         if ($numeric_keys) {
702                                 foreach ($jsonld as $part) {
703                                         $siteinfo = self::parseParts($siteinfo, $part);
704                                 }       
705                         }
706                 }
707
708                 return $siteinfo;
709         }
710
711         /**
712          * Improve the siteinfo with information from the provided JSON-LD information
713          * @see https://jsonld.com/
714          * @see https://schema.org/
715          *
716          * @param array $siteinfo
717          * @param array $jsonld
718          * @return array siteinfo
719          */
720         private static function parseJsonLd(array $siteinfo, array $jsonld)
721         {
722                 $type = JsonLD::fetchElement($jsonld, '@type');
723                 if (empty($type)) {
724                         Logger::info('Empty type', ['url' => $siteinfo['url']]);
725                         return $siteinfo;
726                 }
727
728                 // Silently ignore some types that aren't processed
729                 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
730                         'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
731                         'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
732                         return $siteinfo;
733                 }
734
735                 switch ($type) {
736                         case 'Article':
737                         case 'AdvertiserContentArticle':
738                         case 'NewsArticle':
739                         case 'Report':
740                         case 'SatiricalArticle':
741                         case 'ScholarlyArticle':
742                         case 'SocialMediaPosting':
743                         case 'TechArticle':
744                         case 'ReportageNewsArticle':
745                         case 'SocialMediaPosting':
746                         case 'BlogPosting':
747                         case 'LiveBlogPosting':
748                         case 'DiscussionForumPosting':
749                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
750                         case 'WebPage':
751                         case 'AboutPage':
752                         case 'CheckoutPage':
753                         case 'CollectionPage':
754                         case 'ContactPage':
755                         case 'FAQPage':
756                         case 'ItemPage':
757                         case 'MedicalWebPage':
758                         case 'ProfilePage':
759                         case 'QAPage':
760                         case 'RealEstateListing':
761                         case 'SearchResultsPage':
762                         case 'MediaGallery':                    
763                         case 'ImageGallery':
764                         case 'VideoGallery':
765                         case 'RadioEpisode':
766                         case 'Event':
767                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
768                         case 'WebSite':
769                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
770                         case 'Organization':
771                         case 'Airline':
772                         case 'Consortium':
773                         case 'Corporation':
774                         case 'EducationalOrganization':
775                         case 'FundingScheme':
776                         case 'GovernmentOrganization':
777                         case 'LibrarySystem':
778                         case 'LocalBusiness':
779                         case 'MedicalOrganization':
780                         case 'NGO':
781                         case 'NewsMediaOrganization':
782                         case 'Project':
783                         case 'SportsOrganization':
784                         case 'WorkersUnion':
785                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
786                         case 'Person':
787                         case 'Patient':
788                         case 'PerformingGroup':
789                         case 'DanceGroup';
790                         case 'MusicGroup':
791                         case 'TheaterGroup':                    
792                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
793                         case 'AudioObject':
794                         case 'Audio':
795                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
796                         case 'VideoObject':
797                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
798                         case 'ImageObject':
799                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
800                         default:
801                                 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
802                                 return $siteinfo;
803                 }
804         }
805
806         /**
807          * Fetch author and publisher data
808          *
809          * @param array $siteinfo
810          * @param array $jsonld
811          * @return array siteinfo
812          */
813         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
814         {
815                 $jsonldinfo = [];
816
817                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
818                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
819                         if (!empty($content) && is_string($content)) {
820                                 $jsonldinfo['publisher_name'] = trim($content);
821                         }
822
823                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
824                         if (!empty($content) && is_string($content)) {
825                                 $jsonldinfo['publisher_url'] = trim($content);
826                         }
827
828                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
829                         if (!empty($brand) && is_array($brand)) {
830                                 $content = JsonLD::fetchElement($brand, 'name');
831                                 if (!empty($content) && is_string($content)) {
832                                         $jsonldinfo['publisher_name'] = trim($content);
833                                 }
834
835                                 $content = JsonLD::fetchElement($brand, 'url');
836                                 if (!empty($content) && is_string($content)) {
837                                         $jsonldinfo['publisher_url'] = trim($content);
838                                 }
839
840                                 $content = JsonLD::fetchElement($brand, 'logo', 'url');
841                                 if (!empty($content) && is_string($content)) {
842                                         $jsonldinfo['publisher_img'] = trim($content);
843                                 }
844                         }
845
846                         $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
847                         if (!empty($logo) && is_array($logo)) {
848                                 $content = JsonLD::fetchElement($logo, 'url');
849                                 if (!empty($content) && is_string($content)) {
850                                         $jsonldinfo['publisher_img'] = trim($content);
851                                 }
852                         }
853                 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
854                         $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
855                 }
856
857                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
858                         $content = JsonLD::fetchElement($jsonld, 'author', 'name');
859                         if (!empty($content) && is_string($content)) {
860                                 $jsonldinfo['author_name'] = trim($content);
861                         }
862
863                         $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
864                         if (!empty($content) && is_string($content)) {
865                                 $jsonldinfo['author_url'] = trim($content);
866                         }
867
868                         $content = JsonLD::fetchElement($jsonld, 'author', 'url');
869                         if (!empty($content) && is_string($content)) {
870                                 $jsonldinfo['author_url'] = trim($content);
871                         }
872
873                         $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
874                         if (!empty($logo) && is_array($logo)) {
875                                 $content = JsonLD::fetchElement($logo, 'url');
876                                 if (!empty($content) && is_string($content)) {
877                                         $jsonldinfo['author_img'] = trim($content);
878                                 }
879                         }
880                 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
881                         $jsonldinfo['author_name'] = trim($jsonld['author']);
882                 }
883
884                 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
885
886                 return array_merge($siteinfo, $jsonldinfo);
887         }
888
889         /**
890          * Fetch data from the provided JSON-LD Article type
891          * @see https://schema.org/Article
892          *
893          * @param array $siteinfo
894          * @param array $jsonld
895          * @return array siteinfo
896          */
897         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
898         {
899                 $jsonldinfo = [];
900
901                 $content = JsonLD::fetchElement($jsonld, 'headline');
902                 if (!empty($content) && is_string($content)) {
903                         $jsonldinfo['title'] = trim($content);
904                 }
905
906                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
907                 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
908                         $jsonldinfo['alternative_title'] = trim($content);
909                 }
910
911                 $content = JsonLD::fetchElement($jsonld, 'description');
912                 if (!empty($content) && is_string($content)) {
913                         $jsonldinfo['text'] = trim($content);
914                 }
915
916                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
917                 if (!empty($content)) {
918                         $jsonldinfo['image'] = trim($content);
919                 }
920
921                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
922                 if (!empty($content) && is_string($content)) {
923                         $jsonldinfo['image'] = trim($content);
924                 }
925
926                 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
927                         $content = JsonLD::fetchElement($jsonld, 'keywords');
928                         if (!empty($content)) {
929                                 $siteinfo['keywords'] = [];
930                                 $keywords = explode(',', $content);
931                                 foreach ($keywords as $keyword) {
932                                         $siteinfo['keywords'][] = trim($keyword);
933                                 }
934                         }
935                 } else {
936                         $content = JsonLD::fetchElementArray($jsonld, 'keywords');
937                         if (!empty($content) && is_array($content)) {
938                                 $jsonldinfo['keywords'] = $content;
939                         }
940                 }
941
942                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
943
944                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
945
946                 return array_merge($siteinfo, $jsonldinfo);
947         }
948
949         /**
950          * Fetch data from the provided JSON-LD WebPage type
951          * @see https://schema.org/WebPage
952          *
953          * @param array $siteinfo
954          * @param array $jsonld
955          * @return array siteinfo
956          */
957         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
958         {
959                 $jsonldinfo = [];
960
961                 $content = JsonLD::fetchElement($jsonld, 'name');
962                 if (!empty($content)) {
963                         $jsonldinfo['title'] = trim($content);
964                 }
965
966                 $content = JsonLD::fetchElement($jsonld, 'description');
967                 if (!empty($content)) {
968                         $jsonldinfo['text'] = trim($content);
969                 }
970
971                 $content = JsonLD::fetchElement($jsonld, 'image');
972                 if (!empty($content)) {
973                         $jsonldinfo['image'] = trim($content);
974                 }
975
976                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
977                 if (!empty($content)) {
978                         $jsonldinfo['image'] = trim($content);
979                 }
980
981                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
982
983                 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
984
985                 return array_merge($siteinfo, $jsonldinfo);
986         }
987
988         /**
989          * Fetch data from the provided JSON-LD WebSite type
990          * @see https://schema.org/WebSite
991          *
992          * @param array $siteinfo
993          * @param array $jsonld
994          * @return array siteinfo
995          */
996         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
997         {
998                 $jsonldinfo = [];
999
1000                 $content = JsonLD::fetchElement($jsonld, 'name');
1001                 if (!empty($content)) {
1002                         $jsonldinfo['publisher_name'] = trim($content);
1003                 }
1004
1005                 $content = JsonLD::fetchElement($jsonld, 'description');
1006                 if (!empty($content)) {
1007                         $jsonldinfo['publisher_description'] = trim($content);
1008                 }
1009
1010                 $content = JsonLD::fetchElement($jsonld, 'url');
1011                 if (!empty($content)) {
1012                         $jsonldinfo['publisher_url'] = trim($content);
1013                 }
1014
1015                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1016                 if (!empty($content)) {
1017                         $jsonldinfo['image'] = trim($content);
1018                 }
1019
1020                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1021
1022                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1023                 return array_merge($siteinfo, $jsonldinfo);
1024         }
1025
1026         /**
1027          * Fetch data from the provided JSON-LD Organization type
1028          * @see https://schema.org/Organization
1029          *
1030          * @param array $siteinfo
1031          * @param array $jsonld
1032          * @return array siteinfo
1033          */
1034         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1035         {
1036                 $jsonldinfo = [];
1037
1038                 $content = JsonLD::fetchElement($jsonld, 'name');
1039                 if (!empty($content)) {
1040                         $jsonldinfo['publisher_name'] = trim($content);
1041                 }
1042
1043                 $content = JsonLD::fetchElement($jsonld, 'description');
1044                 if (!empty($content)) {
1045                         $jsonldinfo['publisher_description'] = trim($content);
1046                 }
1047
1048                 $content = JsonLD::fetchElement($jsonld, 'url');
1049                 if (!empty($content)) {
1050                         $jsonldinfo['publisher_url'] = trim($content);
1051                 }
1052
1053                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1054                 if (!empty($content)) {
1055                         $jsonldinfo['publisher_img'] = trim($content);
1056                 }
1057
1058                 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1059                 if (!empty($content)) {
1060                         $jsonldinfo['publisher_name'] = trim($content);
1061                 }
1062
1063                 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1064                 if (!empty($content)) {
1065                         $jsonldinfo['publisher_url'] = trim($content);
1066                 }
1067
1068                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1069                 return array_merge($siteinfo, $jsonldinfo);
1070         }
1071
1072         /**
1073          * Fetch data from the provided JSON-LD Person type
1074          * @see https://schema.org/Person
1075          *
1076          * @param array $siteinfo
1077          * @param array $jsonld
1078          * @return array siteinfo
1079          */
1080         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1081         {
1082                 $jsonldinfo = [];
1083
1084                 $content = JsonLD::fetchElement($jsonld, 'name');
1085                 if (!empty($content)) {
1086                         $jsonldinfo['author_name'] = trim($content);
1087                 }
1088
1089                 $content = JsonLD::fetchElement($jsonld, 'description');
1090                 if (!empty($content)) {
1091                         $jsonldinfo['author_description'] = trim($content);
1092                 }
1093
1094                 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1095                 if (!empty($content) && is_string($content)) {
1096                         $jsonldinfo['author_url'] = trim($content);
1097                 }
1098
1099                 $content = JsonLD::fetchElement($jsonld, 'url');
1100                 if (!empty($content)) {
1101                         $jsonldinfo['author_url'] = trim($content);
1102                 }
1103
1104                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1105                 if (!empty($content)) {
1106                         $jsonldinfo['author_img'] = trim($content);
1107                 }
1108
1109                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1110                 return array_merge($siteinfo, $jsonldinfo);
1111         }
1112
1113         /**
1114          * Fetch data from the provided JSON-LD MediaObject type
1115          * @see https://schema.org/MediaObject
1116          *
1117          * @param array $siteinfo
1118          * @param array $jsonld
1119          * @return array siteinfo
1120          */
1121         private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1122         {
1123                 $media = [];
1124
1125                 $content = JsonLD::fetchElement($jsonld, 'caption');
1126                 if (!empty($content)) {
1127                         $media['caption'] = trim($content);
1128                 }
1129
1130                 $content = JsonLD::fetchElement($jsonld, 'url');
1131                 if (!empty($content)) {
1132                         $media['url'] = trim($content);
1133                 }
1134
1135                 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1136                 if (!empty($content)) {
1137                         $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1138                 }
1139
1140                 $content = JsonLD::fetchElement($jsonld, 'description');
1141                 if (!empty($content)) {
1142                         $media['description'] = trim($content);
1143                 }
1144
1145                 $content = JsonLD::fetchElement($jsonld, 'name');
1146                 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1147                         $media['name'] = trim($content);
1148                 }
1149
1150                 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1151                 if (!empty($content)) {
1152                         $media['content'] = trim($content);
1153                 }
1154
1155                 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1156                 if (!empty($content)) {
1157                         $media['embed'] = trim($content);
1158                 }
1159
1160                 $content = JsonLD::fetchElement($jsonld, 'height');
1161                 if (!empty($content)) {
1162                         $media['height'] = trim($content);
1163                 }
1164
1165                 $content = JsonLD::fetchElement($jsonld, 'width');
1166                 if (!empty($content)) {
1167                         $media['width'] = trim($content);
1168                 }
1169
1170                 $content = JsonLD::fetchElement($jsonld, 'image');
1171                 if (!empty($content)) {
1172                         $media['image'] = trim($content);
1173                 }
1174
1175                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1176                 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1177                         if (!empty($media['image'])) {
1178                                 $media['preview'] = trim($content);
1179                         } else {
1180                                 $media['image'] = trim($content);
1181                         }
1182                 }
1183
1184                 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1185                 $siteinfo[$name][] = $media;
1186                 return $siteinfo;
1187         }
1188 }