]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
79c3928d7de5703e749f7691912b2f8b1dcda5fa
[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::notice('Endless loop detected', ['url' => $url]);
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, false, ['content_length' => 1000000]);
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                 $body = $curlResult->getBody();
236
237                 if ($do_oembed) {
238                         $oembed_data = OEmbed::fetchURL($url, false, false);
239
240                         if (!empty($oembed_data->type)) {
241                                 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
242                                         $siteinfo['type'] = $oembed_data->type;
243                                 }
244
245                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
246                                 if ($siteinfo['type'] != 'photo') {
247                                         if (!empty($oembed_data->title)) {
248                                                 $siteinfo['title'] = trim($oembed_data->title);
249                                         }
250                                         if (!empty($oembed_data->description)) {
251                                                 $siteinfo['text'] = trim($oembed_data->description);
252                                         }
253                                         if (!empty($oembed_data->author_name)) {
254                                                 $siteinfo['author_name'] = trim($oembed_data->author_name);
255                                         }
256                                         if (!empty($oembed_data->author_url)) {
257                                                 $siteinfo['author_url'] = trim($oembed_data->author_url);
258                                         }
259                                         if (!empty($oembed_data->provider_name)) {
260                                                 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
261                                         }
262                                         if (!empty($oembed_data->provider_url)) {
263                                                 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
264                                         }
265                                         if (!empty($oembed_data->thumbnail_url)) {
266                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
267                                         }
268                                 }
269                         }
270                 }
271
272                 $charset = '';
273                 // Look for a charset, first in headers
274                 // Expected form: Content-Type: text/html; charset=ISO-8859-4
275                 foreach ($curlResult->getContentType() as $type) {
276                         if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $type, $matches)) {
277                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
278                         }
279                 }
280
281                 // Then in body that gets precedence
282                 // Expected forms:
283                 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
284                 // - <meta charset="utf-8">
285                 // - <meta charset=utf-8>
286                 // - <meta charSet="utf-8">
287                 // We escape <style> and <script> tags since they can contain irrelevant charset information
288                 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
289                 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
290                         if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
291                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
292                         }
293                 });
294
295                 $siteinfo['charset'] = $charset;
296
297                 if ($charset && strtoupper($charset) != 'UTF-8') {
298                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
299                         $charset = str_ireplace('latin-1', 'latin1', $charset);
300
301                         Logger::info('detected charset', ['charset' => $charset]);
302                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
303                 }
304
305                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
306
307                 $doc = new DOMDocument();
308                 @$doc->loadHTML($body);
309
310                 XML::deleteNode($doc, 'style');
311                 XML::deleteNode($doc, 'option');
312                 XML::deleteNode($doc, 'h1');
313                 XML::deleteNode($doc, 'h2');
314                 XML::deleteNode($doc, 'h3');
315                 XML::deleteNode($doc, 'h4');
316                 XML::deleteNode($doc, 'h5');
317                 XML::deleteNode($doc, 'h6');
318                 XML::deleteNode($doc, 'ol');
319                 XML::deleteNode($doc, 'ul');
320
321                 $xpath = new DOMXPath($doc);
322
323                 $list = $xpath->query('//meta[@content]');
324                 foreach ($list as $node) {
325                         $meta_tag = [];
326                         if ($node->attributes->length) {
327                                 foreach ($node->attributes as $attribute) {
328                                         $meta_tag[$attribute->name] = $attribute->value;
329                                 }
330                         }
331
332                         if (@$meta_tag['http-equiv'] == 'refresh') {
333                                 $path = $meta_tag['content'];
334                                 $pathinfo = explode(';', $path);
335                                 $content = '';
336                                 foreach ($pathinfo as $value) {
337                                         if (substr(strtolower($value), 0, 4) == 'url=') {
338                                                 $content = substr($value, 4);
339                                         }
340                                 }
341                                 if ($content != '') {
342                                         $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
343                                         return $siteinfo;
344                                 }
345                         }
346                 }
347
348                 $list = $xpath->query('//title');
349                 if ($list->length > 0) {
350                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
351                 }
352
353                 $twitter_card = false;
354                 $twitter_image = false;
355
356                 $list = $xpath->query('//meta[@name]');
357                 foreach ($list as $node) {
358                         $meta_tag = [];
359                         if ($node->attributes->length) {
360                                 foreach ($node->attributes as $attribute) {
361                                         $meta_tag[$attribute->name] = $attribute->value;
362                                 }
363                         }
364
365                         if (empty($meta_tag['content'])) {
366                                 continue;
367                         }
368
369                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
370
371                         switch (strtolower($meta_tag['name'])) {
372                                 case 'fulltitle':
373                                         $siteinfo['title'] = trim($meta_tag['content']);
374                                         break;
375                                 case 'description':
376                                         $siteinfo['text'] = trim($meta_tag['content']);
377                                         break;
378                                 case 'thumbnail':
379                                         $siteinfo['image'] = $meta_tag['content'];
380                                         break;
381                                 case 'twitter:image':
382                                         $siteinfo['image'] = $meta_tag['content'];
383                                         $twitter_image = true;
384                                         break;
385                                 case 'twitter:image:src':
386                                         $siteinfo['image'] = $meta_tag['content'];
387                                         break;
388                                 case 'twitter:card':
389                                         // Detect photo pages
390                                         if ($meta_tag['content'] == 'summary_large_image') {
391                                                 $twitter_card = true;
392                                         }
393                                         break;
394                                 case 'twitter:description':
395                                         $siteinfo['text'] = trim($meta_tag['content']);
396                                         break;
397                                 case 'twitter:title':
398                                         $siteinfo['title'] = trim($meta_tag['content']);
399                                         break;
400                                 case 'dc.title':
401                                         $siteinfo['title'] = trim($meta_tag['content']);
402                                         break;
403                                 case 'dc.description':
404                                         $siteinfo['text'] = trim($meta_tag['content']);
405                                         break;
406                                 case 'dc.creator':
407                                         $siteinfo['publisher_name'] = trim($meta_tag['content']);
408                                         break;
409                                 case 'keywords':
410                                         $keywords = explode(',', $meta_tag['content']);
411                                         break;
412                                 case 'news_keywords':
413                                         $keywords = explode(',', $meta_tag['content']);
414                                         break;
415                         }
416                 }
417
418                 if (isset($keywords)) {
419                         $siteinfo['keywords'] = [];
420                         foreach ($keywords as $keyword) {
421                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
422                                         $siteinfo['keywords'][] = trim($keyword);
423                                 }
424                         }
425                 }
426
427                 $list = $xpath->query('//meta[@property]');
428                 foreach ($list as $node) {
429                         $meta_tag = [];
430                         if ($node->attributes->length) {
431                                 foreach ($node->attributes as $attribute) {
432                                         $meta_tag[$attribute->name] = $attribute->value;
433                                 }
434                         }
435
436                         if (!empty($meta_tag['content'])) {
437                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
438
439                                 switch (strtolower($meta_tag['property'])) {
440                                         case 'og:image':
441                                                 $siteinfo['image'] = $meta_tag['content'];
442                                                 break;
443                                         case 'og:image:url':
444                                                 $siteinfo['image'] = $meta_tag['content'];
445                                                 break;
446                                         case 'og:image:secure_url':
447                                                 $siteinfo['image'] = $meta_tag['content'];
448                                                 break;
449                                         case 'og:title':
450                                                 $siteinfo['title'] = trim($meta_tag['content']);
451                                                 break;
452                                         case 'og:description':
453                                                 $siteinfo['text'] = trim($meta_tag['content']);
454                                                 break;
455                                         case 'og:site_name':
456                                                 $siteinfo['publisher_name'] = trim($meta_tag['content']);
457                                                 break;
458                                         case 'twitter:description':
459                                                 $siteinfo['text'] = trim($meta_tag['content']);
460                                                 break;
461                                         case 'twitter:title':
462                                                 $siteinfo['title'] = trim($meta_tag['content']);
463                                                 break;
464                                         case 'twitter:image':
465                                                 $siteinfo['image'] = $meta_tag['content'];
466                                                 $twitter_image = true;
467                                                 break;
468                                 }
469                         }
470                 }
471
472                 $list = $xpath->query("//script[@type='application/ld+json']");
473                 foreach ($list as $node) {
474                         if (!empty($node->nodeValue)) {
475                                 if ($jsonld = json_decode($node->nodeValue, true)) {
476                                         $siteinfo = self::parseParts($siteinfo, $jsonld);
477                                 }
478                         }
479                 }
480
481 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
482                 // Prevent to have a photo type without an image
483 //              if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
484 //                      $siteinfo['type'] = 'photo';
485 //              }
486
487                 if (!empty($siteinfo['image'])) {
488                         $siteinfo['images'] = $siteinfo['images'] ?? [];
489                         array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
490                         unset($siteinfo['image']);
491                 }
492
493                 $siteinfo = self::checkMedia($url, $siteinfo);
494
495                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
496                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
497                         $pos = mb_strrpos($siteinfo['text'], '.');
498                         if ($pos > self::MIN_DESC_COUNT) {
499                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
500                         }
501                 }
502
503                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
504
505                 Hook::callAll('getsiteinfo', $siteinfo);
506
507                 return $siteinfo;
508         }
509
510         /**
511          * Check the attached media elements.
512          * Fix existing data and add missing data.
513          *
514          * @param string $page_url
515          * @param array $siteinfo
516          * @return void
517          */
518         private static function checkMedia(string $page_url, array $siteinfo)
519         {
520                 if (!empty($siteinfo['images'])) {
521                         array_walk($siteinfo['images'], function (&$image) use ($page_url) {
522                                 // According to the specifications someone could place a picture url into the content field as well.
523                                 // But this doesn't seem to happen in the wild, so we don't cover it here.
524                                 if (!empty($image['url'])) {
525                                         $image['url'] = self::completeUrl($image['url'], $page_url);
526                                         $photodata = Images::getInfoFromURLCached($image['url']);
527                                         if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
528                                                 $image['src'] = $image['url'];
529                                                 $image['width'] = $photodata[0];
530                                                 $image['height'] = $photodata[1];
531                                                 $image['contenttype'] = $photodata['mime'];
532                                                 unset($image['url']);
533                                                 ksort($image);
534                                         } else {
535                                                 $image = [];
536                                         }
537                                 } else {
538                                         $image = [];
539                                 }
540                         });
541
542                         $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
543                 }
544
545                 foreach (['audio', 'video'] as $element) {
546                         if (!empty($siteinfo[$element])) {
547                                 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
548                                         $url = '';
549                                         $embed = '';
550                                         $content = '';
551                                         $contenttype = '';
552                                         foreach (['embed', 'content', 'url'] as $field) {
553                                                 if (!empty($media[$field])) {
554                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
555                                                         $type = self::getContentType($media[$field]);
556                                                         if (($type[0] ?? '') == 'text') {
557                                                                 if ($field == 'embed') {
558                                                                         $embed = $media[$field];
559                                                                 } else {
560                                                                         $url = $media[$field];
561                                                                 }
562                                                         } elseif (!empty($type[0])) {
563                                                                 $content = $media[$field];
564                                                                 $contenttype = implode('/', $type);
565                                                         }
566                                                 }
567                                                 unset($media[$field]);
568                                         }
569
570                                         foreach (['image', 'preview'] as $field) {
571                                                 if (!empty($media[$field])) {
572                                                         $media[$field] = self::completeUrl($media[$field], $page_url);
573                                                 }
574                                         }
575
576                                         if (!empty($url)) {
577                                                 $media['url'] = $url;
578                                         }
579                                         if (!empty($embed)) {
580                                                 $media['embed'] = $embed;
581                                                 if (!empty($media['main'])) {
582                                                         $siteinfo['embed'] = $embed;
583                                                 }
584                                         }
585                                         if (!empty($content)) {
586                                                 $media['src'] = $content;
587                                         }
588                                         if (!empty($contenttype)) {
589                                                 $media['contenttype'] = $contenttype;
590                                         }
591                                         if (empty($url) && empty($content) && empty($embed)) {
592                                                 $media = [];
593                                         }
594                                         ksort($media);
595                                 });
596
597                                 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
598                         }
599                         if (empty($siteinfo[$element])) {
600                                 unset($siteinfo[$element]);
601                         }
602                 }
603                 return $siteinfo;
604         }
605
606         /**
607          * Convert tags from CSV to an array
608          *
609          * @param string $string Tags
610          * @return array with formatted Hashtags
611          */
612         public static function convertTagsToArray($string)
613         {
614                 $arr_tags = str_getcsv($string);
615                 if (count($arr_tags)) {
616                         // add the # sign to every tag
617                         array_walk($arr_tags, ["self", "arrAddHashes"]);
618
619                         return $arr_tags;
620                 }
621         }
622
623         /**
624          * Add a hasht sign to a string
625          *
626          * This method is used as callback function
627          *
628          * @param string $tag The pure tag name
629          * @param int    $k   Counter for internal use
630          * @return void
631          */
632         private static function arrAddHashes(&$tag, $k)
633         {
634                 $tag = "#" . $tag;
635         }
636
637         /**
638          * Add a scheme to an url
639          *
640          * The src attribute of some html elements (e.g. images)
641          * can miss the scheme so we need to add the correct
642          * scheme
643          *
644          * @param string $url    The url which possibly does have
645          *                       a missing scheme (a link to an image)
646          * @param string $scheme The url with a correct scheme
647          *                       (e.g. the url from the webpage which does contain the image)
648          *
649          * @return string The url with a scheme
650          */
651         private static function completeUrl($url, $scheme)
652         {
653                 $urlarr = parse_url($url);
654
655                 // If the url does allready have an scheme
656                 // we can stop the process here
657                 if (isset($urlarr["scheme"])) {
658                         return($url);
659                 }
660
661                 $schemearr = parse_url($scheme);
662
663                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
664
665                 if (!empty($schemearr["port"])) {
666                         $complete .= ":".$schemearr["port"];
667                 }
668
669                 if (!empty($urlarr["path"])) {
670                         if (strpos($urlarr["path"], "/") !== 0) {
671                                 $complete .= "/";
672                         }
673
674                         $complete .= $urlarr["path"];
675                 }
676
677                 if (!empty($urlarr["query"])) {
678                         $complete .= "?".$urlarr["query"];
679                 }
680
681                 if (!empty($urlarr["fragment"])) {
682                         $complete .= "#".$urlarr["fragment"];
683                 }
684
685                 return($complete);
686         }
687
688         /**
689          * Parse the Json-Ld parts of a web page
690          *
691          * @param array $siteinfo
692          * @param array $jsonld
693          * @return array siteinfo
694          */
695         private static function parseParts(array $siteinfo, array $jsonld)
696         {
697                 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
698                         foreach ($jsonld['@graph'] as $part) {
699                                 if (!empty($part) && is_array($part)) {
700                                         $siteinfo = self::parseParts($siteinfo, $part);
701                                 }
702                         }
703                 } elseif (!empty($jsonld['@type'])) {
704                         $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
705                 } elseif (!empty($jsonld)) {
706                         $keys = array_keys($jsonld);
707                         $numeric_keys = true;
708                         foreach ($keys as $key) {
709                                 if (!is_int($key)) {
710                                         $numeric_keys = false;
711                                 }
712                         }
713                         if ($numeric_keys) {
714                                 foreach ($jsonld as $part) {
715                                         if (!empty($part) && is_array($part)) {
716                                                 $siteinfo = self::parseParts($siteinfo, $part);
717                                         }
718                                 }
719                         }
720                 }
721
722                 array_walk_recursive($siteinfo, function (&$element) {
723                         if (is_string($element)) {
724                                 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
725                         }
726                 });
727
728                 return $siteinfo;
729         }
730
731         /**
732          * Improve the siteinfo with information from the provided JSON-LD information
733          * @see https://jsonld.com/
734          * @see https://schema.org/
735          *
736          * @param array $siteinfo
737          * @param array $jsonld
738          * @return array siteinfo
739          */
740         private static function parseJsonLd(array $siteinfo, array $jsonld)
741         {
742                 $type = JsonLD::fetchElement($jsonld, '@type');
743                 if (empty($type)) {
744                         Logger::info('Empty type', ['url' => $siteinfo['url']]);
745                         return $siteinfo;
746                 }
747
748                 // Silently ignore some types that aren't processed
749                 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
750                         'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
751                         'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
752                         return $siteinfo;
753                 }
754
755                 switch ($type) {
756                         case 'Article':
757                         case 'AdvertiserContentArticle':
758                         case 'NewsArticle':
759                         case 'Report':
760                         case 'SatiricalArticle':
761                         case 'ScholarlyArticle':
762                         case 'SocialMediaPosting':
763                         case 'TechArticle':
764                         case 'ReportageNewsArticle':
765                         case 'SocialMediaPosting':
766                         case 'BlogPosting':
767                         case 'LiveBlogPosting':
768                         case 'DiscussionForumPosting':
769                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
770                         case 'WebPage':
771                         case 'AboutPage':
772                         case 'CheckoutPage':
773                         case 'CollectionPage':
774                         case 'ContactPage':
775                         case 'FAQPage':
776                         case 'ItemPage':
777                         case 'MedicalWebPage':
778                         case 'ProfilePage':
779                         case 'QAPage':
780                         case 'RealEstateListing':
781                         case 'SearchResultsPage':
782                         case 'MediaGallery':
783                         case 'ImageGallery':
784                         case 'VideoGallery':
785                         case 'RadioEpisode':
786                         case 'Event':
787                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
788                         case 'WebSite':
789                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
790                         case 'Organization':
791                         case 'Airline':
792                         case 'Consortium':
793                         case 'Corporation':
794                         case 'EducationalOrganization':
795                         case 'FundingScheme':
796                         case 'GovernmentOrganization':
797                         case 'LibrarySystem':
798                         case 'LocalBusiness':
799                         case 'MedicalOrganization':
800                         case 'NGO':
801                         case 'NewsMediaOrganization':
802                         case 'Project':
803                         case 'SportsOrganization':
804                         case 'WorkersUnion':
805                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
806                         case 'Person':
807                         case 'Patient':
808                         case 'PerformingGroup':
809                         case 'DanceGroup';
810                         case 'MusicGroup':
811                         case 'TheaterGroup':
812                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
813                         case 'AudioObject':
814                         case 'Audio':
815                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
816                         case 'VideoObject':
817                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
818                         case 'ImageObject':
819                                 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
820                         default:
821                                 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
822                                 return $siteinfo;
823                 }
824         }
825
826         /**
827          * Fetch author and publisher data
828          *
829          * @param array $siteinfo
830          * @param array $jsonld
831          * @return array siteinfo
832          */
833         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
834         {
835                 $jsonldinfo = [];
836
837                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
838                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
839                         if (!empty($content) && is_string($content)) {
840                                 $jsonldinfo['publisher_name'] = trim($content);
841                         }
842
843                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
844                         if (!empty($content) && is_string($content)) {
845                                 $jsonldinfo['publisher_url'] = trim($content);
846                         }
847
848                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
849                         if (!empty($brand) && is_array($brand)) {
850                                 $content = JsonLD::fetchElement($brand, 'name');
851                                 if (!empty($content) && is_string($content)) {
852                                         $jsonldinfo['publisher_name'] = trim($content);
853                                 }
854
855                                 $content = JsonLD::fetchElement($brand, 'url');
856                                 if (!empty($content) && is_string($content)) {
857                                         $jsonldinfo['publisher_url'] = trim($content);
858                                 }
859
860                                 $content = JsonLD::fetchElement($brand, 'logo', 'url');
861                                 if (!empty($content) && is_string($content)) {
862                                         $jsonldinfo['publisher_img'] = trim($content);
863                                 }
864                         }
865
866                         $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
867                         if (!empty($logo) && is_array($logo)) {
868                                 $content = JsonLD::fetchElement($logo, 'url');
869                                 if (!empty($content) && is_string($content)) {
870                                         $jsonldinfo['publisher_img'] = trim($content);
871                                 }
872                         }
873                 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
874                         $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
875                 }
876
877                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
878                         $content = JsonLD::fetchElement($jsonld, 'author', 'name');
879                         if (!empty($content) && is_string($content)) {
880                                 $jsonldinfo['author_name'] = trim($content);
881                         }
882
883                         $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
884                         if (!empty($content) && is_string($content)) {
885                                 $jsonldinfo['author_url'] = trim($content);
886                         }
887
888                         $content = JsonLD::fetchElement($jsonld, 'author', 'url');
889                         if (!empty($content) && is_string($content)) {
890                                 $jsonldinfo['author_url'] = trim($content);
891                         }
892
893                         $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
894                         if (!empty($logo) && is_array($logo)) {
895                                 $content = JsonLD::fetchElement($logo, 'url');
896                                 if (!empty($content) && is_string($content)) {
897                                         $jsonldinfo['author_img'] = trim($content);
898                                 }
899                         }
900                 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
901                         $jsonldinfo['author_name'] = trim($jsonld['author']);
902                 }
903
904                 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
905
906                 return array_merge($siteinfo, $jsonldinfo);
907         }
908
909         /**
910          * Fetch data from the provided JSON-LD Article type
911          * @see https://schema.org/Article
912          *
913          * @param array $siteinfo
914          * @param array $jsonld
915          * @return array siteinfo
916          */
917         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
918         {
919                 $jsonldinfo = [];
920
921                 $content = JsonLD::fetchElement($jsonld, 'headline');
922                 if (!empty($content) && is_string($content)) {
923                         $jsonldinfo['title'] = trim($content);
924                 }
925
926                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
927                 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
928                         $jsonldinfo['alternative_title'] = trim($content);
929                 }
930
931                 $content = JsonLD::fetchElement($jsonld, 'description');
932                 if (!empty($content) && is_string($content)) {
933                         $jsonldinfo['text'] = trim($content);
934                 }
935
936                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
937                 if (!empty($content)) {
938                         $jsonldinfo['image'] = trim($content);
939                 }
940
941                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
942                 if (!empty($content) && is_string($content)) {
943                         $jsonldinfo['image'] = trim($content);
944                 }
945
946                 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
947                         $content = JsonLD::fetchElement($jsonld, 'keywords');
948                         if (!empty($content)) {
949                                 $siteinfo['keywords'] = [];
950                                 $keywords = explode(',', $content);
951                                 foreach ($keywords as $keyword) {
952                                         $siteinfo['keywords'][] = trim($keyword);
953                                 }
954                         }
955                 } elseif (!empty($jsonld['keywords'])) {
956                         $content = JsonLD::fetchElementArray($jsonld, 'keywords');
957                         if (!empty($content) && is_array($content)) {
958                                 $jsonldinfo['keywords'] = $content;
959                         }
960                 }
961
962                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
963
964                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
965
966                 return array_merge($siteinfo, $jsonldinfo);
967         }
968
969         /**
970          * Fetch data from the provided JSON-LD WebPage type
971          * @see https://schema.org/WebPage
972          *
973          * @param array $siteinfo
974          * @param array $jsonld
975          * @return array siteinfo
976          */
977         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
978         {
979                 $jsonldinfo = [];
980
981                 $content = JsonLD::fetchElement($jsonld, 'name');
982                 if (!empty($content)) {
983                         $jsonldinfo['title'] = trim($content);
984                 }
985
986                 $content = JsonLD::fetchElement($jsonld, 'description');
987                 if (!empty($content)) {
988                         $jsonldinfo['text'] = trim($content);
989                 }
990
991                 $content = JsonLD::fetchElement($jsonld, 'image');
992                 if (!empty($content)) {
993                         $jsonldinfo['image'] = trim($content);
994                 }
995
996                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
997                 if (!empty($content)) {
998                         $jsonldinfo['image'] = trim($content);
999                 }
1000
1001                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1002
1003                 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1004
1005                 return array_merge($siteinfo, $jsonldinfo);
1006         }
1007
1008         /**
1009          * Fetch data from the provided JSON-LD WebSite type
1010          * @see https://schema.org/WebSite
1011          *
1012          * @param array $siteinfo
1013          * @param array $jsonld
1014          * @return array siteinfo
1015          */
1016         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1017         {
1018                 $jsonldinfo = [];
1019
1020                 $content = JsonLD::fetchElement($jsonld, 'name');
1021                 if (!empty($content)) {
1022                         $jsonldinfo['publisher_name'] = trim($content);
1023                 }
1024
1025                 $content = JsonLD::fetchElement($jsonld, 'description');
1026                 if (!empty($content)) {
1027                         $jsonldinfo['publisher_description'] = trim($content);
1028                 }
1029
1030                 $content = JsonLD::fetchElement($jsonld, 'url');
1031                 if (!empty($content)) {
1032                         $jsonldinfo['publisher_url'] = trim($content);
1033                 }
1034
1035                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1036                 if (!empty($content)) {
1037                         $jsonldinfo['image'] = trim($content);
1038                 }
1039
1040                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1041
1042                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1043                 return array_merge($siteinfo, $jsonldinfo);
1044         }
1045
1046         /**
1047          * Fetch data from the provided JSON-LD Organization type
1048          * @see https://schema.org/Organization
1049          *
1050          * @param array $siteinfo
1051          * @param array $jsonld
1052          * @return array siteinfo
1053          */
1054         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1055         {
1056                 $jsonldinfo = [];
1057
1058                 $content = JsonLD::fetchElement($jsonld, 'name');
1059                 if (!empty($content)) {
1060                         $jsonldinfo['publisher_name'] = trim($content);
1061                 }
1062
1063                 $content = JsonLD::fetchElement($jsonld, 'description');
1064                 if (!empty($content)) {
1065                         $jsonldinfo['publisher_description'] = trim($content);
1066                 }
1067
1068                 $content = JsonLD::fetchElement($jsonld, 'url');
1069                 if (!empty($content)) {
1070                         $jsonldinfo['publisher_url'] = trim($content);
1071                 }
1072
1073                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1074                 if (!empty($content)) {
1075                         $jsonldinfo['publisher_img'] = trim($content);
1076                 }
1077
1078                 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1079                 if (!empty($content)) {
1080                         $jsonldinfo['publisher_name'] = trim($content);
1081                 }
1082
1083                 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1084                 if (!empty($content)) {
1085                         $jsonldinfo['publisher_url'] = trim($content);
1086                 }
1087
1088                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1089                 return array_merge($siteinfo, $jsonldinfo);
1090         }
1091
1092         /**
1093          * Fetch data from the provided JSON-LD Person type
1094          * @see https://schema.org/Person
1095          *
1096          * @param array $siteinfo
1097          * @param array $jsonld
1098          * @return array siteinfo
1099          */
1100         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1101         {
1102                 $jsonldinfo = [];
1103
1104                 $content = JsonLD::fetchElement($jsonld, 'name');
1105                 if (!empty($content)) {
1106                         $jsonldinfo['author_name'] = trim($content);
1107                 }
1108
1109                 $content = JsonLD::fetchElement($jsonld, 'description');
1110                 if (!empty($content)) {
1111                         $jsonldinfo['author_description'] = trim($content);
1112                 }
1113
1114                 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1115                 if (!empty($content) && is_string($content)) {
1116                         $jsonldinfo['author_url'] = trim($content);
1117                 }
1118
1119                 $content = JsonLD::fetchElement($jsonld, 'url');
1120                 if (!empty($content)) {
1121                         $jsonldinfo['author_url'] = trim($content);
1122                 }
1123
1124                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1125                 if (!empty($content)) {
1126                         $jsonldinfo['author_img'] = trim($content);
1127                 }
1128
1129                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1130                 return array_merge($siteinfo, $jsonldinfo);
1131         }
1132
1133         /**
1134          * Fetch data from the provided JSON-LD MediaObject type
1135          * @see https://schema.org/MediaObject
1136          *
1137          * @param array $siteinfo
1138          * @param array $jsonld
1139          * @return array siteinfo
1140          */
1141         private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1142         {
1143                 $media = [];
1144
1145                 $content = JsonLD::fetchElement($jsonld, 'caption');
1146                 if (!empty($content)) {
1147                         $media['caption'] = trim($content);
1148                 }
1149
1150                 $content = JsonLD::fetchElement($jsonld, 'url');
1151                 if (!empty($content)) {
1152                         $media['url'] = trim($content);
1153                 }
1154
1155                 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1156                 if (!empty($content)) {
1157                         $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1158                 }
1159
1160                 $content = JsonLD::fetchElement($jsonld, 'description');
1161                 if (!empty($content)) {
1162                         $media['description'] = trim($content);
1163                 }
1164
1165                 $content = JsonLD::fetchElement($jsonld, 'name');
1166                 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1167                         $media['name'] = trim($content);
1168                 }
1169
1170                 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1171                 if (!empty($content)) {
1172                         $media['content'] = trim($content);
1173                 }
1174
1175                 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1176                 if (!empty($content)) {
1177                         $media['embed'] = trim($content);
1178                 }
1179
1180                 $content = JsonLD::fetchElement($jsonld, 'height');
1181                 if (!empty($content)) {
1182                         $media['height'] = trim($content);
1183                 }
1184
1185                 $content = JsonLD::fetchElement($jsonld, 'width');
1186                 if (!empty($content)) {
1187                         $media['width'] = trim($content);
1188                 }
1189
1190                 $content = JsonLD::fetchElement($jsonld, 'image');
1191                 if (!empty($content)) {
1192                         $media['image'] = trim($content);
1193                 }
1194
1195                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1196                 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1197                         if (!empty($media['image'])) {
1198                                 $media['preview'] = trim($content);
1199                         } else {
1200                                 $media['image'] = trim($content);
1201                         }
1202                 }
1203
1204                 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1205                 $siteinfo[$name][] = $media;
1206                 return $siteinfo;
1207         }
1208 }