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