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