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