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