3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
26 use Friendica\Content\OEmbed;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Protocol\HTTP\MediaType;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Database\Database;
32 use Friendica\Database\DBA;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
39 * Get information about a given URL
41 * Class with methods for extracting certain content from an url
45 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
46 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
49 * Maximum number of characters for the description
51 const MAX_DESC_COUNT = 250;
54 * Minimum number of characters for the description
56 const MIN_DESC_COUNT = 100;
59 * Fetch the content type of the given url
60 * @param string $url URL of the page
61 * @param string $accept content-type to accept
63 * @return array content type
65 public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT, int $timeout = 0): array
67 if (!empty($timeout)) {
68 $options = [HttpClientOptions::TIMEOUT => $timeout];
74 $curlResult = DI::httpClient()->head($url, array_merge([HttpClientOptions::ACCEPT_CONTENT => $accept], $options));
75 } catch (\Exception $e) {
76 DI::logger()->debug('Got exception', ['url' => $url, 'message' => $e->getMessage()]);
80 // Workaround for systems that can't handle a HEAD request. Don't retry on timeouts.
81 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() >= 400) && !in_array($curlResult->getReturnCode(), [408, 504])) {
82 $curlResult = DI::httpClient()->get($url, $accept, array_merge([HttpClientOptions::CONTENT_LENGTH => 1000000], $options));
85 if (!$curlResult->isSuccess()) {
86 Logger::debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]);
90 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
91 if (empty($contenttype)) {
92 return ['application', 'octet-stream'];
95 return explode('/', current(explode(';', $contenttype)));
99 * Search for cached embeddable data of an url otherwise fetch it
101 * @param string $url The url of the page which should be scraped
102 * @param bool $do_oembed The false option is used by the function fetch_oembed()
103 * to avoid endless loops
105 * @return array which contains needed data for embedding
106 * string 'url' => The url of the parsed page
107 * string 'type' => Content type
108 * string 'title' => (optional) The title of the content
109 * string 'text' => (optional) The description for the content
110 * string 'image' => (optional) A preview image of the content
111 * array 'images' => (optional) Array of preview pictures
112 * string 'keywords' => (optional) The tags which belong to the content
114 * @throws HTTPException\InternalServerErrorException
115 * @see ParseUrl::getSiteinfo() for more information about scraping
118 public static function getSiteinfoCached(string $url, bool $do_oembed = true): array
127 $urlHash = hash('sha256', $url);
129 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
130 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
132 if (!empty($parsed_url['content'])) {
133 $data = unserialize($parsed_url['content']);
137 $data = self::getSiteinfo($url, $do_oembed);
139 $expires = $data['expires'];
141 unset($data['expires']);
146 'url_hash' => $urlHash,
147 'oembed' => $do_oembed,
149 'content' => serialize($data),
150 'created' => DateTimeFormat::utcNow(),
151 'expires' => $expires,
153 Database::INSERT_UPDATE
160 * Parse a page for embeddable content information
162 * This method parses to url for meta data which can be used to embed
163 * the content. If available it prioritizes Open Graph meta tags.
164 * If this is not available it uses the twitter cards meta tags.
165 * As fallback it uses standard html elements with meta informations
166 * like \<title\>Awesome Title\</title\> or
167 * \<meta name="description" content="An awesome description"\>
169 * @param string $url The url of the page which should be scraped
170 * @param bool $do_oembed The false option is used by the function fetch_oembed()
171 * to avoid endless loops
172 * @param int $count Internal counter to avoid endless loops
174 * @return array which contains needed data for embedding
175 * string 'url' => The url of the parsed page
176 * string 'type' => Content type (error, link, photo, image, audio, video)
177 * string 'title' => (optional) The title of the content
178 * string 'text' => (optional) The description for the content
179 * string 'image' => (optional) A preview image of the content
180 * array 'images' => (optional) Array of preview pictures
181 * string 'keywords' => (optional) The tags which belong to the content
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @todo https://developers.google.com/+/plugins/snippet/
186 * <meta itemprop="name" content="Awesome title">
187 * <meta itemprop="description" content="An awesome description">
188 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
190 * <body itemscope itemtype="http://schema.org/Product">
191 * <h1 itemprop="name">Shiny Trinket</h1>
192 * <img itemprop="image" src="{image-url}" />
193 * <p itemprop="description">Shiny trinkets are shiny.</p>
197 public static function getSiteinfo(string $url, bool $do_oembed = true, int $count = 1): array
206 // Check if the URL does contain a scheme
207 $scheme = parse_url($url, PHP_URL_SCHEME);
210 $url = 'http://' . ltrim($url, '/');
213 $url = trim($url, "'\"");
215 $url = Network::stripTrackingQueryParams($url);
220 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
224 Logger::warning('Endless loop detected', ['url' => $url]);
228 $type = self::getContentType($url);
229 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
230 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
231 $siteinfo['type'] = $type[0];
235 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
236 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
240 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
241 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
242 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
246 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
248 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
249 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
250 $maxAge = max(86400, (int)array_pop($matches));
251 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
255 $body = $curlResult->getBody();
258 $oembed_data = OEmbed::fetchURL($url, false, false);
260 if (!empty($oembed_data->type)) {
261 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
262 $siteinfo['type'] = $oembed_data->type;
265 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
266 if ($siteinfo['type'] != 'photo') {
267 if (!empty($oembed_data->title)) {
268 $siteinfo['title'] = trim($oembed_data->title);
270 if (!empty($oembed_data->description)) {
271 $siteinfo['text'] = trim($oembed_data->description);
273 if (!empty($oembed_data->author_name)) {
274 $siteinfo['author_name'] = trim($oembed_data->author_name);
276 if (!empty($oembed_data->author_url)) {
277 $siteinfo['author_url'] = trim($oembed_data->author_url);
279 if (!empty($oembed_data->provider_name)) {
280 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
282 if (!empty($oembed_data->provider_url)) {
283 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
285 if (!empty($oembed_data->thumbnail_url)) {
286 $siteinfo['image'] = $oembed_data->thumbnail_url;
294 // Look for a charset, first in headers
295 $mediaType = MediaType::fromContentType($curlResult->getContentType());
296 if (isset($mediaType->parameters['charset'])) {
297 $charset = $mediaType->parameters['charset'];
299 } catch(\InvalidArgumentException $e) {}
301 $siteinfo['charset'] = $charset;
303 if ($charset && strtoupper($charset) != 'UTF-8') {
304 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
305 $charset = str_ireplace('latin-1', 'latin1', $charset);
307 Logger::info('detected charset', ['charset' => $charset]);
308 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
311 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
317 $doc = new DOMDocument();
318 @$doc->loadHTML($body);
320 $siteinfo['charset'] = HTML::extractCharset($doc) ?? $siteinfo['charset'];
322 XML::deleteNode($doc, 'style');
323 XML::deleteNode($doc, 'option');
324 XML::deleteNode($doc, 'h1');
325 XML::deleteNode($doc, 'h2');
326 XML::deleteNode($doc, 'h3');
327 XML::deleteNode($doc, 'h4');
328 XML::deleteNode($doc, 'h5');
329 XML::deleteNode($doc, 'h6');
330 XML::deleteNode($doc, 'ol');
331 XML::deleteNode($doc, 'ul');
333 $xpath = new DOMXPath($doc);
335 $list = $xpath->query('//meta[@content]');
336 foreach ($list as $node) {
338 if ($node->attributes->length) {
339 foreach ($node->attributes as $attribute) {
340 $meta_tag[$attribute->name] = $attribute->value;
344 if (@$meta_tag['http-equiv'] == 'refresh') {
345 $path = $meta_tag['content'];
346 $pathinfo = explode(';', $path);
348 foreach ($pathinfo as $value) {
349 if (substr(strtolower($value), 0, 4) == 'url=') {
350 $content = substr($value, 4);
353 if ($content != '') {
354 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
360 $list = $xpath->query('//title');
361 if ($list->length > 0) {
362 $siteinfo['title'] = trim($list->item(0)->nodeValue);
365 $list = $xpath->query('//meta[@name]');
366 foreach ($list as $node) {
368 if ($node->attributes->length) {
369 foreach ($node->attributes as $attribute) {
370 $meta_tag[$attribute->name] = $attribute->value;
374 if (empty($meta_tag['content'])) {
378 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
380 switch (strtolower($meta_tag['name'])) {
382 $siteinfo['title'] = trim($meta_tag['content']);
385 $siteinfo['text'] = trim($meta_tag['content']);
388 $siteinfo['image'] = $meta_tag['content'];
390 case 'twitter:image':
391 $siteinfo['image'] = $meta_tag['content'];
393 case 'twitter:image:src':
394 $siteinfo['image'] = $meta_tag['content'];
396 case 'twitter:description':
397 $siteinfo['text'] = trim($meta_tag['content']);
399 case 'twitter:title':
400 $siteinfo['title'] = trim($meta_tag['content']);
402 case 'twitter:player':
403 $siteinfo['player']['embed'] = trim($meta_tag['content']);
405 case 'twitter:player:stream':
406 $siteinfo['player']['stream'] = trim($meta_tag['content']);
408 case 'twitter:player:width':
409 $siteinfo['player']['width'] = intval($meta_tag['content']);
411 case 'twitter:player:height':
412 $siteinfo['player']['height'] = intval($meta_tag['content']);
415 $siteinfo['title'] = trim($meta_tag['content']);
417 case 'dc.description':
418 $siteinfo['text'] = trim($meta_tag['content']);
421 $siteinfo['publisher_name'] = trim($meta_tag['content']);
424 $keywords = explode(',', $meta_tag['content']);
426 case 'news_keywords':
427 $keywords = explode(',', $meta_tag['content']);
432 if (isset($keywords)) {
433 $siteinfo['keywords'] = [];
434 foreach ($keywords as $keyword) {
435 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
436 $siteinfo['keywords'][] = trim($keyword);
441 $list = $xpath->query('//meta[@property]');
442 foreach ($list as $node) {
444 if ($node->attributes->length) {
445 foreach ($node->attributes as $attribute) {
446 $meta_tag[$attribute->name] = $attribute->value;
450 if (!empty($meta_tag['content'])) {
451 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
453 switch (strtolower($meta_tag['property'])) {
455 $siteinfo['image'] = $meta_tag['content'];
458 $siteinfo['image'] = $meta_tag['content'];
460 case 'og:image:secure_url':
461 $siteinfo['image'] = $meta_tag['content'];
464 $siteinfo['title'] = trim($meta_tag['content']);
466 case 'og:description':
467 $siteinfo['text'] = trim($meta_tag['content']);
470 $siteinfo['publisher_name'] = trim($meta_tag['content']);
473 $siteinfo['language'] = trim($meta_tag['content']);
476 $siteinfo['pagetype'] = trim($meta_tag['content']);
478 case 'twitter:description':
479 $siteinfo['text'] = trim($meta_tag['content']);
481 case 'twitter:title':
482 $siteinfo['title'] = trim($meta_tag['content']);
484 case 'twitter:image':
485 $siteinfo['image'] = $meta_tag['content'];
491 $list = $xpath->query("//script[@type='application/ld+json']");
492 foreach ($list as $node) {
493 if (!empty($node->nodeValue)) {
494 if ($jsonld = json_decode($node->nodeValue, true)) {
495 $siteinfo = self::parseParts($siteinfo, $jsonld);
500 if (!empty($siteinfo['player']['stream'])) {
501 // Only add player data to media arrays if there is no duplicate
502 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
503 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
504 $contenttype = self::getContentType($siteinfo['player']['stream']);
505 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
506 $media = ['content' => $siteinfo['player']['stream']];
508 if (!empty($siteinfo['player']['embed'])) {
509 $media['embed'] = $siteinfo['player']['embed'];
512 $siteinfo[$contenttype[0]][] = $media;
517 if (!empty($siteinfo['image'])) {
518 $siteinfo['images'] = $siteinfo['images'] ?? [];
519 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
520 unset($siteinfo['image']);
523 $siteinfo = self::checkMedia($url, $siteinfo);
525 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
526 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
527 $pos = mb_strrpos($siteinfo['text'], '.');
528 if ($pos > self::MIN_DESC_COUNT) {
529 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
533 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
535 Hook::callAll('getsiteinfo', $siteinfo);
543 * Check the attached media elements.
544 * Fix existing data and add missing data.
546 * @param string $page_url
547 * @param array $siteinfo
550 private static function checkMedia(string $page_url, array $siteinfo) : array
552 if (!empty($siteinfo['images'])) {
553 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
555 * According to the specifications someone could place a picture
556 * URL into the content field as well. But this doesn't seem to
557 * happen in the wild, so we don't cover it here.
559 if (!empty($image['url'])) {
560 $image['url'] = self::completeUrl($image['url'], $page_url);
561 $photodata = Images::getInfoFromURLCached($image['url']);
562 if (($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
563 $image['src'] = $image['url'];
564 $image['width'] = $photodata[0];
565 $image['height'] = $photodata[1];
566 $image['contenttype'] = $photodata['mime'];
567 $image['blurhash'] = $photodata['blurhash'] ?? null;
568 unset($image['url']);
578 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
581 foreach (['audio', 'video'] as $element) {
582 if (!empty($siteinfo[$element])) {
583 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
588 foreach (['embed', 'content', 'url'] as $field) {
589 if (!empty($media[$field])) {
590 $media[$field] = self::completeUrl($media[$field], $page_url);
591 $type = self::getContentType($media[$field]);
592 if (($type[0] ?? '') == 'text') {
593 if ($field == 'embed') {
594 $embed = $media[$field];
596 $url = $media[$field];
598 } elseif (!empty($type[0])) {
599 $content = $media[$field];
600 $contenttype = implode('/', $type);
603 unset($media[$field]);
606 foreach (['image', 'preview'] as $field) {
607 if (!empty($media[$field])) {
608 $media[$field] = self::completeUrl($media[$field], $page_url);
613 $media['url'] = $url;
615 if (!empty($embed)) {
616 $media['embed'] = $embed;
617 if (empty($siteinfo['player']['embed'])) {
618 $siteinfo['player']['embed'] = $embed;
621 if (!empty($content)) {
622 $media['src'] = $content;
624 if (!empty($contenttype)) {
625 $media['contenttype'] = $contenttype;
627 if (empty($url) && empty($content) && empty($embed)) {
633 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
635 if (empty($siteinfo[$element])) {
636 unset($siteinfo[$element]);
643 * Convert tags from CSV to an array
645 * @param string $string Tags
647 * @return array with formatted Hashtags
649 public static function convertTagsToArray(string $string): array
651 $arr_tags = str_getcsv($string);
652 if (count($arr_tags)) {
653 // add the # sign to every tag
654 array_walk($arr_tags, [self::class, 'arrAddHashes']);
662 * Add a hasht sign to a string
664 * This method is used as callback function
666 * @param string $tag The pure tag name
667 * @param int $k Counter for internal use
671 private static function arrAddHashes(string &$tag, int $k)
677 * Add a scheme to an url
679 * The src attribute of some html elements (e.g. images)
680 * can miss the scheme so we need to add the correct
683 * @param string $url The url which possibly does have
684 * a missing scheme (a link to an image)
685 * @param string $scheme The url with a correct scheme
686 * (e.g. the url from the webpage which does contain the image)
688 * @return string The url with a scheme
690 private static function completeUrl(string $url, string $scheme): string
692 $urlarr = parse_url($url);
694 // If the url does already have an scheme
695 // we can stop the process here
696 if (isset($urlarr['scheme'])) {
700 $schemearr = parse_url($scheme);
702 $complete = $schemearr['scheme'] . '://' . $schemearr['host'];
704 if (!empty($schemearr['port'])) {
705 $complete .= ':' . $schemearr['port'];
708 if (!empty($urlarr['path'])) {
709 if (strpos($urlarr['path'], '/') !== 0) {
713 $complete .= $urlarr['path'];
716 if (!empty($urlarr['query'])) {
717 $complete .= '?' . $urlarr['query'];
720 if (!empty($urlarr['fragment'])) {
721 $complete .= '#' . $urlarr['fragment'];
728 * Parse the Json-Ld parts of a web page
730 * @param array $siteinfo
731 * @param array $jsonld
733 * @return array siteinfo
735 private static function parseParts(array $siteinfo, array $jsonld): array
737 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
738 foreach ($jsonld['@graph'] as $part) {
739 if (!empty($part) && is_array($part)) {
740 $siteinfo = self::parseParts($siteinfo, $part);
743 } elseif (!empty($jsonld['@type'])) {
744 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
745 } elseif (!empty($jsonld)) {
746 $keys = array_keys($jsonld);
747 $numeric_keys = true;
748 foreach ($keys as $key) {
750 $numeric_keys = false;
754 foreach ($jsonld as $part) {
755 if (!empty($part) && is_array($part)) {
756 $siteinfo = self::parseParts($siteinfo, $part);
762 array_walk_recursive($siteinfo, function (&$element) {
763 if (is_string($element)) {
764 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
772 * Improve the siteinfo with information from the provided JSON-LD information
773 * @see https://jsonld.com/
774 * @see https://schema.org/
776 * @param array $siteinfo
777 * @param array $jsonld
779 * @return array siteinfo
781 private static function parseJsonLd(array $siteinfo, array $jsonld): array
783 $type = JsonLD::fetchElement($jsonld, '@type');
785 Logger::info('Empty type', ['url' => $siteinfo['url']]);
789 // Silently ignore some types that aren't processed
790 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
791 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
792 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
798 case 'AdvertiserContentArticle':
801 case 'SatiricalArticle':
802 case 'ScholarlyArticle':
803 case 'SocialMediaPosting':
805 case 'ReportageNewsArticle':
806 case 'SocialMediaPosting':
808 case 'LiveBlogPosting':
809 case 'DiscussionForumPosting':
810 return self::parseJsonLdArticle($siteinfo, $jsonld);
814 case 'CollectionPage':
818 case 'MedicalWebPage':
821 case 'RealEstateListing':
822 case 'SearchResultsPage':
828 return self::parseJsonLdWebPage($siteinfo, $jsonld);
830 return self::parseJsonLdWebSite($siteinfo, $jsonld);
835 case 'EducationalOrganization':
836 case 'FundingScheme':
837 case 'GovernmentOrganization':
838 case 'LibrarySystem':
839 case 'LocalBusiness':
840 case 'MedicalOrganization':
842 case 'NewsMediaOrganization':
844 case 'SportsOrganization':
846 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
849 case 'PerformingGroup':
853 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
856 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
858 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
860 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
862 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
868 * Fetch author and publisher data
870 * @param array $siteinfo
871 * @param array $jsonld
873 * @return array siteinfo
875 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld): array
879 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
880 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
881 if (!empty($content) && is_string($content)) {
882 $jsonldinfo['publisher_name'] = trim($content);
885 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
886 if (!empty($content) && is_string($content)) {
887 $jsonldinfo['publisher_url'] = trim($content);
890 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
891 if (!empty($brand) && is_array($brand)) {
892 $content = JsonLD::fetchElement($brand, 'name');
893 if (!empty($content) && is_string($content)) {
894 $jsonldinfo['publisher_name'] = trim($content);
897 $content = JsonLD::fetchElement($brand, 'url');
898 if (!empty($content) && is_string($content)) {
899 $jsonldinfo['publisher_url'] = trim($content);
902 $content = JsonLD::fetchElement($brand, 'logo', 'url');
903 if (!empty($content) && is_string($content)) {
904 $jsonldinfo['publisher_img'] = trim($content);
908 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
909 if (!empty($logo) && is_array($logo)) {
910 $content = JsonLD::fetchElement($logo, 'url');
911 if (!empty($content) && is_string($content)) {
912 $jsonldinfo['publisher_img'] = trim($content);
915 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
916 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
919 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
920 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
921 if (!empty($content) && is_string($content)) {
922 $jsonldinfo['author_name'] = trim($content);
925 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
926 if (!empty($content) && is_string($content)) {
927 $jsonldinfo['author_url'] = trim($content);
930 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
931 if (!empty($content) && is_string($content)) {
932 $jsonldinfo['author_url'] = trim($content);
935 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
936 if (!empty($logo) && is_array($logo)) {
937 $content = JsonLD::fetchElement($logo, 'url');
938 if (!empty($content) && is_string($content)) {
939 $jsonldinfo['author_img'] = trim($content);
942 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
943 $jsonldinfo['author_name'] = trim($jsonld['author']);
946 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
948 return array_merge($siteinfo, $jsonldinfo);
952 * Fetch data from the provided JSON-LD Article type
953 * @see https://schema.org/Article
955 * @param array $siteinfo
956 * @param array $jsonld
958 * @return array siteinfo
960 private static function parseJsonLdArticle(array $siteinfo, array $jsonld): array
964 $content = JsonLD::fetchElement($jsonld, 'headline');
965 if (!empty($content) && is_string($content)) {
966 $jsonldinfo['title'] = trim($content);
969 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
970 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
971 $jsonldinfo['alternative_title'] = trim($content);
974 $content = JsonLD::fetchElement($jsonld, 'description');
975 if (!empty($content) && is_string($content)) {
976 $jsonldinfo['text'] = trim($content);
979 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
980 if (!empty($content)) {
981 $jsonldinfo['image'] = trim($content);
984 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
985 if (!empty($content) && is_string($content)) {
986 $jsonldinfo['image'] = trim($content);
989 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
990 $content = JsonLD::fetchElement($jsonld, 'keywords');
991 if (!empty($content)) {
992 $siteinfo['keywords'] = [];
993 $keywords = explode(',', $content);
994 foreach ($keywords as $keyword) {
995 $siteinfo['keywords'][] = trim($keyword);
998 } elseif (!empty($jsonld['keywords'])) {
999 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
1000 if (!empty($content) && is_array($content)) {
1001 $jsonldinfo['keywords'] = $content;
1005 $content = JsonLD::fetchElement($jsonld, 'datePublished');
1006 if (!empty($content) && is_string($content)) {
1007 $jsonldinfo['published'] = DateTimeFormat::utc($content);
1010 $content = JsonLD::fetchElement($jsonld, 'dateModified');
1011 if (!empty($content) && is_string($content)) {
1012 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
1015 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1017 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1019 return array_merge($siteinfo, $jsonldinfo);
1023 * Fetch data from the provided JSON-LD WebPage type
1024 * @see https://schema.org/WebPage
1026 * @param array $siteinfo
1027 * @param array $jsonld
1029 * @return array siteinfo
1031 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld): array
1035 $content = JsonLD::fetchElement($jsonld, 'name');
1036 if (!empty($content)) {
1037 $jsonldinfo['title'] = trim($content);
1040 $content = JsonLD::fetchElement($jsonld, 'description');
1041 if (!empty($content) && is_string($content)) {
1042 $jsonldinfo['text'] = trim($content);
1045 $content = JsonLD::fetchElement($jsonld, 'image');
1046 if (!empty($content) && is_string($content)) {
1047 $jsonldinfo['image'] = trim($content);
1050 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1051 if (!empty($content) && is_string($content)) {
1052 $jsonldinfo['image'] = trim($content);
1055 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1057 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1059 return array_merge($siteinfo, $jsonldinfo);
1063 * Fetch data from the provided JSON-LD WebSite type
1064 * @see https://schema.org/WebSite
1066 * @param array $siteinfo
1067 * @param array $jsonld
1069 * @return array siteinfo
1071 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld): array
1075 $content = JsonLD::fetchElement($jsonld, 'name');
1076 if (!empty($content) && is_string($content)) {
1077 $jsonldinfo['publisher_name'] = trim($content);
1080 $content = JsonLD::fetchElement($jsonld, 'description');
1081 if (!empty($content) && is_string($content)) {
1082 $jsonldinfo['publisher_description'] = trim($content);
1085 $content = JsonLD::fetchElement($jsonld, 'url');
1086 if (!empty($content) && is_string($content)) {
1087 $jsonldinfo['publisher_url'] = trim($content);
1090 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1091 if (!empty($content) && is_string($content)) {
1092 $jsonldinfo['image'] = trim($content);
1095 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1097 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1098 return array_merge($siteinfo, $jsonldinfo);
1102 * Fetch data from the provided JSON-LD Organization type
1103 * @see https://schema.org/Organization
1105 * @param array $siteinfo
1106 * @param array $jsonld
1108 * @return array siteinfo
1110 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld): array
1114 $content = JsonLD::fetchElement($jsonld, 'name');
1115 if (!empty($content) && is_string($content)) {
1116 $jsonldinfo['publisher_name'] = trim($content);
1119 $content = JsonLD::fetchElement($jsonld, 'description');
1120 if (!empty($content) && is_string($content)) {
1121 $jsonldinfo['publisher_description'] = trim($content);
1124 $content = JsonLD::fetchElement($jsonld, 'url');
1125 if (!empty($content) && is_string($content)) {
1126 $jsonldinfo['publisher_url'] = trim($content);
1129 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1130 if (!empty($content) && is_string($content)) {
1131 $jsonldinfo['publisher_img'] = trim($content);
1132 } elseif (!empty($content) && is_array($content)) {
1133 $jsonldinfo['publisher_img'] = trim($content[0]);
1136 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1137 if (!empty($content) && is_string($content)) {
1138 $jsonldinfo['publisher_name'] = trim($content);
1141 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1142 if (!empty($content) && is_string($content)) {
1143 $jsonldinfo['publisher_url'] = trim($content);
1146 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1147 return array_merge($siteinfo, $jsonldinfo);
1151 * Fetch data from the provided JSON-LD Person type
1152 * @see https://schema.org/Person
1154 * @param array $siteinfo
1155 * @param array $jsonld
1157 * @return array siteinfo
1159 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld): array
1163 $content = JsonLD::fetchElement($jsonld, 'name');
1164 if (!empty($content) && is_string($content)) {
1165 $jsonldinfo['author_name'] = trim($content);
1168 $content = JsonLD::fetchElement($jsonld, 'description');
1169 if (!empty($content) && is_string($content)) {
1170 $jsonldinfo['author_description'] = trim($content);
1173 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1174 if (!empty($content) && is_string($content)) {
1175 $jsonldinfo['author_url'] = trim($content);
1178 $content = JsonLD::fetchElement($jsonld, 'url');
1179 if (!empty($content) && is_string($content)) {
1180 $jsonldinfo['author_url'] = trim($content);
1183 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1184 if (!empty($content) && !is_string($content)) {
1185 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1188 if (!empty($content) && is_string($content)) {
1189 $jsonldinfo['author_img'] = trim($content);
1192 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1193 return array_merge($siteinfo, $jsonldinfo);
1197 * Fetch data from the provided JSON-LD MediaObject type
1198 * @see https://schema.org/MediaObject
1200 * @param array $siteinfo
1201 * @param array $jsonld
1203 * @return array siteinfo
1205 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name): array
1209 $content = JsonLD::fetchElement($jsonld, 'caption');
1210 if (!empty($content) && is_string($content)) {
1211 $media['caption'] = trim($content);
1214 $content = JsonLD::fetchElement($jsonld, 'url');
1215 if (!empty($content) && is_string($content)) {
1216 $media['url'] = trim($content);
1219 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1220 if (!empty($content) && is_string($content)) {
1221 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1224 $content = JsonLD::fetchElement($jsonld, 'description');
1225 if (!empty($content) && is_string($content)) {
1226 $media['description'] = trim($content);
1229 $content = JsonLD::fetchElement($jsonld, 'name');
1230 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1231 $media['name'] = trim($content);
1234 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1235 if (!empty($content) && is_string($content)) {
1236 $media['content'] = trim($content);
1239 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1240 if (!empty($content) && is_string($content)) {
1241 $media['embed'] = trim($content);
1244 $content = JsonLD::fetchElement($jsonld, 'height');
1245 if (!empty($content) && is_string($content)) {
1246 $media['height'] = trim($content);
1249 $content = JsonLD::fetchElement($jsonld, 'width');
1250 if (!empty($content) && is_string($content)) {
1251 $media['width'] = trim($content);
1254 $content = JsonLD::fetchElement($jsonld, 'image');
1255 if (!empty($content) && is_string($content)) {
1256 $media['image'] = trim($content);
1259 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1260 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1261 if (!empty($media['image'])) {
1262 $media['preview'] = trim($content);
1264 $media['image'] = trim($content);
1268 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1269 $siteinfo[$name][] = $media;