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