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