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