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