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