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