3 * @copyright Copyright (C) 2010-2022, 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\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
32 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 * Get information about a given URL
39 * Class with methods for extracting certain content from an url
43 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
44 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
47 * Maximum number of characters for the description
49 const MAX_DESC_COUNT = 250;
52 * Minimum number of characters for the description
54 const MIN_DESC_COUNT = 100;
57 * Fetch the content type of the given url
58 * @param string $url URL of the page
59 * @param string $accept content-type to accept
60 * @return array content type
62 public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT): array
64 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => $accept]);
66 // Workaround for systems that can't handle a HEAD request
67 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
68 $curlResult = DI::httpClient()->get($url, $accept, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
71 if (!$curlResult->isSuccess()) {
72 Logger::debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]);
76 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
77 if (empty($contenttype)) {
78 return ['application', 'octet-stream'];
81 return explode('/', current(explode(';', $contenttype)));
85 * Search for chached embeddable data of an url otherwise fetch it
87 * @param string $url The url of the page which should be scraped
88 * @param bool $do_oembed The false option is used by the function fetch_oembed()
89 * to avoid endless loops
91 * @return array which contains needed data for embedding
92 * string 'url' => The url of the parsed page
93 * string 'type' => Content type
94 * string 'title' => (optional) The title of the content
95 * string 'text' => (optional) The description for the content
96 * string 'image' => (optional) A preview image of the content
97 * array 'images' => (optional) Array of preview pictures
98 * string 'keywords' => (optional) The tags which belong to the content
100 * @throws HTTPException\InternalServerErrorException
101 * @see ParseUrl::getSiteinfo() for more information about scraping
104 public static function getSiteinfoCached(string $url, bool $do_oembed = true): array
113 $urlHash = hash('sha256', $url);
115 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
116 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
118 if (!empty($parsed_url['content'])) {
119 $data = unserialize($parsed_url['content']);
123 $data = self::getSiteinfo($url, $do_oembed);
125 $expires = $data['expires'];
127 unset($data['expires']);
132 'url_hash' => $urlHash,
133 'oembed' => $do_oembed,
135 'content' => serialize($data),
136 'created' => DateTimeFormat::utcNow(),
137 'expires' => $expires,
139 Database::INSERT_UPDATE
146 * Parse a page for embeddable content information
148 * This method parses to url for meta data which can be used to embed
149 * the content. If available it prioritizes Open Graph meta tags.
150 * If this is not available it uses the twitter cards meta tags.
151 * As fallback it uses standard html elements with meta informations
152 * like \<title\>Awesome Title\</title\> or
153 * \<meta name="description" content="An awesome description"\>
155 * @param string $url The url of the page which should be scraped
156 * @param bool $do_oembed The false option is used by the function fetch_oembed()
157 * to avoid endless loops
158 * @param int $count Internal counter to avoid endless loops
160 * @return array which contains needed data for embedding
161 * string 'url' => The url of the parsed page
162 * string 'type' => Content type (error, link, photo, image, audio, video)
163 * string 'title' => (optional) The title of the content
164 * string 'text' => (optional) The description for the content
165 * string 'image' => (optional) A preview image of the content
166 * array 'images' => (optional) Array of preview pictures
167 * string 'keywords' => (optional) The tags which belong to the content
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 * @todo https://developers.google.com/+/plugins/snippet/
172 * <meta itemprop="name" content="Awesome title">
173 * <meta itemprop="description" content="An awesome description">
174 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
176 * <body itemscope itemtype="http://schema.org/Product">
177 * <h1 itemprop="name">Shiny Trinket</h1>
178 * <img itemprop="image" src="{image-url}" />
179 * <p itemprop="description">Shiny trinkets are shiny.</p>
183 public static function getSiteinfo(string $url, bool $do_oembed = true, int $count = 1)
192 // Check if the URL does contain a scheme
193 $scheme = parse_url($url, PHP_URL_SCHEME);
196 $url = 'http://' . ltrim($url, '/');
199 $url = trim($url, "'\"");
201 $url = Network::stripTrackingQueryParams($url);
206 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
210 Logger::notice('Endless loop detected', ['url' => $url]);
214 $type = self::getContentType($url);
215 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
216 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
217 $siteinfo['type'] = $type[0];
221 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
222 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
226 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
227 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
228 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
232 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
234 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
235 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
236 $maxAge = max(86400, (int)array_pop($matches));
237 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
241 $body = $curlResult->getBody();
244 $oembed_data = OEmbed::fetchURL($url, false, false);
246 if (!empty($oembed_data->type)) {
247 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
248 $siteinfo['type'] = $oembed_data->type;
251 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
252 if ($siteinfo['type'] != 'photo') {
253 if (!empty($oembed_data->title)) {
254 $siteinfo['title'] = trim($oembed_data->title);
256 if (!empty($oembed_data->description)) {
257 $siteinfo['text'] = trim($oembed_data->description);
259 if (!empty($oembed_data->author_name)) {
260 $siteinfo['author_name'] = trim($oembed_data->author_name);
262 if (!empty($oembed_data->author_url)) {
263 $siteinfo['author_url'] = trim($oembed_data->author_url);
265 if (!empty($oembed_data->provider_name)) {
266 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
268 if (!empty($oembed_data->provider_url)) {
269 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
271 if (!empty($oembed_data->thumbnail_url)) {
272 $siteinfo['image'] = $oembed_data->thumbnail_url;
279 // Look for a charset, first in headers
280 // Expected form: Content-Type: text/html; charset=ISO-8859-4
281 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
282 $charset = trim(trim(trim(array_pop($matches)), ';,'));
285 // Then in body that gets precedence
287 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
288 // - <meta charset="utf-8">
289 // - <meta charset=utf-8>
290 // - <meta charSet="utf-8">
291 // We escape <style> and <script> tags since they can contain irrelevant charset information
292 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
293 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
294 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
295 $charset = trim(trim(trim(array_pop($matches)), ';,'));
299 $siteinfo['charset'] = $charset;
301 if ($charset && strtoupper($charset) != 'UTF-8') {
302 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
303 $charset = str_ireplace('latin-1', 'latin1', $charset);
305 Logger::info('detected charset', ['charset' => $charset]);
306 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
309 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
311 $doc = new DOMDocument();
312 @$doc->loadHTML($body);
314 XML::deleteNode($doc, 'style');
315 XML::deleteNode($doc, 'option');
316 XML::deleteNode($doc, 'h1');
317 XML::deleteNode($doc, 'h2');
318 XML::deleteNode($doc, 'h3');
319 XML::deleteNode($doc, 'h4');
320 XML::deleteNode($doc, 'h5');
321 XML::deleteNode($doc, 'h6');
322 XML::deleteNode($doc, 'ol');
323 XML::deleteNode($doc, 'ul');
325 $xpath = new DOMXPath($doc);
327 $list = $xpath->query('//meta[@content]');
328 foreach ($list as $node) {
330 if ($node->attributes->length) {
331 foreach ($node->attributes as $attribute) {
332 $meta_tag[$attribute->name] = $attribute->value;
336 if (@$meta_tag['http-equiv'] == 'refresh') {
337 $path = $meta_tag['content'];
338 $pathinfo = explode(';', $path);
340 foreach ($pathinfo as $value) {
341 if (substr(strtolower($value), 0, 4) == 'url=') {
342 $content = substr($value, 4);
345 if ($content != '') {
346 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
352 $list = $xpath->query('//title');
353 if ($list->length > 0) {
354 $siteinfo['title'] = trim($list->item(0)->nodeValue);
357 $list = $xpath->query('//meta[@name]');
358 foreach ($list as $node) {
360 if ($node->attributes->length) {
361 foreach ($node->attributes as $attribute) {
362 $meta_tag[$attribute->name] = $attribute->value;
366 if (empty($meta_tag['content'])) {
370 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
372 switch (strtolower($meta_tag['name'])) {
374 $siteinfo['title'] = trim($meta_tag['content']);
377 $siteinfo['text'] = trim($meta_tag['content']);
380 $siteinfo['image'] = $meta_tag['content'];
382 case 'twitter:image':
383 $siteinfo['image'] = $meta_tag['content'];
385 case 'twitter:image:src':
386 $siteinfo['image'] = $meta_tag['content'];
388 case 'twitter:description':
389 $siteinfo['text'] = trim($meta_tag['content']);
391 case 'twitter:title':
392 $siteinfo['title'] = trim($meta_tag['content']);
394 case 'twitter:player':
395 $siteinfo['player']['embed'] = trim($meta_tag['content']);
397 case 'twitter:player:stream':
398 $siteinfo['player']['stream'] = trim($meta_tag['content']);
400 case 'twitter:player:width':
401 $siteinfo['player']['width'] = intval($meta_tag['content']);
403 case 'twitter:player:height':
404 $siteinfo['player']['height'] = intval($meta_tag['content']);
407 $siteinfo['title'] = trim($meta_tag['content']);
409 case 'dc.description':
410 $siteinfo['text'] = trim($meta_tag['content']);
413 $siteinfo['publisher_name'] = trim($meta_tag['content']);
416 $keywords = explode(',', $meta_tag['content']);
418 case 'news_keywords':
419 $keywords = explode(',', $meta_tag['content']);
424 if (isset($keywords)) {
425 $siteinfo['keywords'] = [];
426 foreach ($keywords as $keyword) {
427 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
428 $siteinfo['keywords'][] = trim($keyword);
433 $list = $xpath->query('//meta[@property]');
434 foreach ($list as $node) {
436 if ($node->attributes->length) {
437 foreach ($node->attributes as $attribute) {
438 $meta_tag[$attribute->name] = $attribute->value;
442 if (!empty($meta_tag['content'])) {
443 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
445 switch (strtolower($meta_tag['property'])) {
447 $siteinfo['image'] = $meta_tag['content'];
450 $siteinfo['image'] = $meta_tag['content'];
452 case 'og:image:secure_url':
453 $siteinfo['image'] = $meta_tag['content'];
456 $siteinfo['title'] = trim($meta_tag['content']);
458 case 'og:description':
459 $siteinfo['text'] = trim($meta_tag['content']);
462 $siteinfo['publisher_name'] = trim($meta_tag['content']);
465 $siteinfo['language'] = trim($meta_tag['content']);
468 $siteinfo['pagetype'] = trim($meta_tag['content']);
470 case 'twitter:description':
471 $siteinfo['text'] = trim($meta_tag['content']);
473 case 'twitter:title':
474 $siteinfo['title'] = trim($meta_tag['content']);
476 case 'twitter:image':
477 $siteinfo['image'] = $meta_tag['content'];
483 $list = $xpath->query("//script[@type='application/ld+json']");
484 foreach ($list as $node) {
485 if (!empty($node->nodeValue)) {
486 if ($jsonld = json_decode($node->nodeValue, true)) {
487 $siteinfo = self::parseParts($siteinfo, $jsonld);
492 if (!empty($siteinfo['player']['stream'])) {
493 // Only add player data to media arrays if there is no duplicate
494 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
495 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
496 $contenttype = self::getContentType($siteinfo['player']['stream']);
497 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
498 $media = ['content' => $siteinfo['player']['stream']];
500 if (!empty($siteinfo['player']['embed'])) {
501 $media['embed'] = $siteinfo['player']['embed'];
504 $siteinfo[$contenttype[0]][] = $media;
509 if (!empty($siteinfo['image'])) {
510 $siteinfo['images'] = $siteinfo['images'] ?? [];
511 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
512 unset($siteinfo['image']);
515 $siteinfo = self::checkMedia($url, $siteinfo);
517 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
518 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
519 $pos = mb_strrpos($siteinfo['text'], '.');
520 if ($pos > self::MIN_DESC_COUNT) {
521 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
525 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
527 Hook::callAll('getsiteinfo', $siteinfo);
535 * Check the attached media elements.
536 * Fix existing data and add missing data.
538 * @param string $page_url
539 * @param array $siteinfo
542 private static function checkMedia(string $page_url, array $siteinfo) : array
544 if (!empty($siteinfo['images'])) {
545 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
546 // According to the specifications someone could place a picture url into the content field as well.
547 // But this doesn't seem to happen in the wild, so we don't cover it here.
548 if (!empty($image['url'])) {
549 $image['url'] = self::completeUrl($image['url'], $page_url);
550 $photodata = Images::getInfoFromURLCached($image['url']);
551 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
552 $image['src'] = $image['url'];
553 $image['width'] = $photodata[0];
554 $image['height'] = $photodata[1];
555 $image['contenttype'] = $photodata['mime'];
556 unset($image['url']);
566 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
569 foreach (['audio', 'video'] as $element) {
570 if (!empty($siteinfo[$element])) {
571 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
576 foreach (['embed', 'content', 'url'] as $field) {
577 if (!empty($media[$field])) {
578 $media[$field] = self::completeUrl($media[$field], $page_url);
579 $type = self::getContentType($media[$field]);
580 if (($type[0] ?? '') == 'text') {
581 if ($field == 'embed') {
582 $embed = $media[$field];
584 $url = $media[$field];
586 } elseif (!empty($type[0])) {
587 $content = $media[$field];
588 $contenttype = implode('/', $type);
591 unset($media[$field]);
594 foreach (['image', 'preview'] as $field) {
595 if (!empty($media[$field])) {
596 $media[$field] = self::completeUrl($media[$field], $page_url);
601 $media['url'] = $url;
603 if (!empty($embed)) {
604 $media['embed'] = $embed;
605 if (empty($siteinfo['player']['embed'])) {
606 $siteinfo['player']['embed'] = $embed;
609 if (!empty($content)) {
610 $media['src'] = $content;
612 if (!empty($contenttype)) {
613 $media['contenttype'] = $contenttype;
615 if (empty($url) && empty($content) && empty($embed)) {
621 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
623 if (empty($siteinfo[$element])) {
624 unset($siteinfo[$element]);
631 * Convert tags from CSV to an array
633 * @param string $string Tags
634 * @return array with formatted Hashtags
636 public static function convertTagsToArray(string $string): array
638 $arr_tags = str_getcsv($string);
639 if (count($arr_tags)) {
640 // add the # sign to every tag
641 array_walk($arr_tags, ['self', 'arrAddHashes']);
649 * Add a hasht sign to a string
651 * This method is used as callback function
653 * @param string $tag The pure tag name
654 * @param int $k Counter for internal use
657 private static function arrAddHashes(string &$tag, int $k)
663 * Add a scheme to an url
665 * The src attribute of some html elements (e.g. images)
666 * can miss the scheme so we need to add the correct
669 * @param string $url The url which possibly does have
670 * a missing scheme (a link to an image)
671 * @param string $scheme The url with a correct scheme
672 * (e.g. the url from the webpage which does contain the image)
674 * @return string The url with a scheme
676 private static function completeUrl(string $url, string $scheme): string
678 $urlarr = parse_url($url);
680 // If the url does allready have an scheme
681 // we can stop the process here
682 if (isset($urlarr['scheme'])) {
686 $schemearr = parse_url($scheme);
688 $complete = $schemearr['scheme'] . '://' . $schemearr['host'];
690 if (!empty($schemearr['port'])) {
691 $complete .= ':' . $schemearr['port'];
694 if (!empty($urlarr['path'])) {
695 if (strpos($urlarr['path'], '/') !== 0) {
699 $complete .= $urlarr['path'];
702 if (!empty($urlarr['query'])) {
703 $complete .= '?' . $urlarr['query'];
706 if (!empty($urlarr['fragment'])) {
707 $complete .= '#' . $urlarr['fragment'];
714 * Parse the Json-Ld parts of a web page
716 * @param array $siteinfo
717 * @param array $jsonld
718 * @return array siteinfo
720 private static function parseParts(array $siteinfo, array $jsonld): array
722 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
723 foreach ($jsonld['@graph'] as $part) {
724 if (!empty($part) && is_array($part)) {
725 $siteinfo = self::parseParts($siteinfo, $part);
728 } elseif (!empty($jsonld['@type'])) {
729 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
730 } elseif (!empty($jsonld)) {
731 $keys = array_keys($jsonld);
732 $numeric_keys = true;
733 foreach ($keys as $key) {
735 $numeric_keys = false;
739 foreach ($jsonld as $part) {
740 if (!empty($part) && is_array($part)) {
741 $siteinfo = self::parseParts($siteinfo, $part);
747 array_walk_recursive($siteinfo, function (&$element) {
748 if (is_string($element)) {
749 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
757 * Improve the siteinfo with information from the provided JSON-LD information
758 * @see https://jsonld.com/
759 * @see https://schema.org/
761 * @param array $siteinfo
762 * @param array $jsonld
763 * @return array siteinfo
765 private static function parseJsonLd(array $siteinfo, array $jsonld): array
767 $type = JsonLD::fetchElement($jsonld, '@type');
769 Logger::info('Empty type', ['url' => $siteinfo['url']]);
773 // Silently ignore some types that aren't processed
774 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
775 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
776 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
782 case 'AdvertiserContentArticle':
785 case 'SatiricalArticle':
786 case 'ScholarlyArticle':
787 case 'SocialMediaPosting':
789 case 'ReportageNewsArticle':
790 case 'SocialMediaPosting':
792 case 'LiveBlogPosting':
793 case 'DiscussionForumPosting':
794 return self::parseJsonLdArticle($siteinfo, $jsonld);
798 case 'CollectionPage':
802 case 'MedicalWebPage':
805 case 'RealEstateListing':
806 case 'SearchResultsPage':
812 return self::parseJsonLdWebPage($siteinfo, $jsonld);
814 return self::parseJsonLdWebSite($siteinfo, $jsonld);
819 case 'EducationalOrganization':
820 case 'FundingScheme':
821 case 'GovernmentOrganization':
822 case 'LibrarySystem':
823 case 'LocalBusiness':
824 case 'MedicalOrganization':
826 case 'NewsMediaOrganization':
828 case 'SportsOrganization':
830 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
833 case 'PerformingGroup':
837 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
840 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
842 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
844 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
846 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
852 * Fetch author and publisher data
854 * @param array $siteinfo
855 * @param array $jsonld
856 * @return array siteinfo
858 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld): array
862 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
863 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
864 if (!empty($content) && is_string($content)) {
865 $jsonldinfo['publisher_name'] = trim($content);
868 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
869 if (!empty($content) && is_string($content)) {
870 $jsonldinfo['publisher_url'] = trim($content);
873 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
874 if (!empty($brand) && is_array($brand)) {
875 $content = JsonLD::fetchElement($brand, 'name');
876 if (!empty($content) && is_string($content)) {
877 $jsonldinfo['publisher_name'] = trim($content);
880 $content = JsonLD::fetchElement($brand, 'url');
881 if (!empty($content) && is_string($content)) {
882 $jsonldinfo['publisher_url'] = trim($content);
885 $content = JsonLD::fetchElement($brand, 'logo', 'url');
886 if (!empty($content) && is_string($content)) {
887 $jsonldinfo['publisher_img'] = trim($content);
891 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
892 if (!empty($logo) && is_array($logo)) {
893 $content = JsonLD::fetchElement($logo, 'url');
894 if (!empty($content) && is_string($content)) {
895 $jsonldinfo['publisher_img'] = trim($content);
898 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
899 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
902 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
903 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
904 if (!empty($content) && is_string($content)) {
905 $jsonldinfo['author_name'] = trim($content);
908 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
909 if (!empty($content) && is_string($content)) {
910 $jsonldinfo['author_url'] = trim($content);
913 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
914 if (!empty($content) && is_string($content)) {
915 $jsonldinfo['author_url'] = trim($content);
918 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
919 if (!empty($logo) && is_array($logo)) {
920 $content = JsonLD::fetchElement($logo, 'url');
921 if (!empty($content) && is_string($content)) {
922 $jsonldinfo['author_img'] = trim($content);
925 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
926 $jsonldinfo['author_name'] = trim($jsonld['author']);
929 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
931 return array_merge($siteinfo, $jsonldinfo);
935 * Fetch data from the provided JSON-LD Article type
936 * @see https://schema.org/Article
938 * @param array $siteinfo
939 * @param array $jsonld
940 * @return array siteinfo
942 private static function parseJsonLdArticle(array $siteinfo, array $jsonld): array
946 $content = JsonLD::fetchElement($jsonld, 'headline');
947 if (!empty($content) && is_string($content)) {
948 $jsonldinfo['title'] = trim($content);
951 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
952 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
953 $jsonldinfo['alternative_title'] = trim($content);
956 $content = JsonLD::fetchElement($jsonld, 'description');
957 if (!empty($content) && is_string($content)) {
958 $jsonldinfo['text'] = trim($content);
961 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
962 if (!empty($content)) {
963 $jsonldinfo['image'] = trim($content);
966 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
967 if (!empty($content) && is_string($content)) {
968 $jsonldinfo['image'] = trim($content);
971 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
972 $content = JsonLD::fetchElement($jsonld, 'keywords');
973 if (!empty($content)) {
974 $siteinfo['keywords'] = [];
975 $keywords = explode(',', $content);
976 foreach ($keywords as $keyword) {
977 $siteinfo['keywords'][] = trim($keyword);
980 } elseif (!empty($jsonld['keywords'])) {
981 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
982 if (!empty($content) && is_array($content)) {
983 $jsonldinfo['keywords'] = $content;
987 $content = JsonLD::fetchElement($jsonld, 'datePublished');
988 if (!empty($content) && is_string($content)) {
989 $jsonldinfo['published'] = DateTimeFormat::utc($content);
992 $content = JsonLD::fetchElement($jsonld, 'dateModified');
993 if (!empty($content) && is_string($content)) {
994 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
997 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
999 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1001 return array_merge($siteinfo, $jsonldinfo);
1005 * Fetch data from the provided JSON-LD WebPage type
1006 * @see https://schema.org/WebPage
1008 * @param array $siteinfo
1009 * @param array $jsonld
1010 * @return array siteinfo
1012 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld): array
1016 $content = JsonLD::fetchElement($jsonld, 'name');
1017 if (!empty($content)) {
1018 $jsonldinfo['title'] = trim($content);
1021 $content = JsonLD::fetchElement($jsonld, 'description');
1022 if (!empty($content)) {
1023 $jsonldinfo['text'] = trim($content);
1026 $content = JsonLD::fetchElement($jsonld, 'image');
1027 if (!empty($content)) {
1028 $jsonldinfo['image'] = trim($content);
1031 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1032 if (!empty($content)) {
1033 $jsonldinfo['image'] = trim($content);
1036 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1038 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1040 return array_merge($siteinfo, $jsonldinfo);
1044 * Fetch data from the provided JSON-LD WebSite type
1045 * @see https://schema.org/WebSite
1047 * @param array $siteinfo
1048 * @param array $jsonld
1049 * @return array siteinfo
1051 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld): array
1055 $content = JsonLD::fetchElement($jsonld, 'name');
1056 if (!empty($content)) {
1057 $jsonldinfo['publisher_name'] = trim($content);
1060 $content = JsonLD::fetchElement($jsonld, 'description');
1061 if (!empty($content)) {
1062 $jsonldinfo['publisher_description'] = trim($content);
1065 $content = JsonLD::fetchElement($jsonld, 'url');
1066 if (!empty($content)) {
1067 $jsonldinfo['publisher_url'] = trim($content);
1070 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1071 if (!empty($content)) {
1072 $jsonldinfo['image'] = trim($content);
1075 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1077 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1078 return array_merge($siteinfo, $jsonldinfo);
1082 * Fetch data from the provided JSON-LD Organization type
1083 * @see https://schema.org/Organization
1085 * @param array $siteinfo
1086 * @param array $jsonld
1087 * @return array siteinfo
1089 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld): array
1093 $content = JsonLD::fetchElement($jsonld, 'name');
1094 if (!empty($content)) {
1095 $jsonldinfo['publisher_name'] = trim($content);
1098 $content = JsonLD::fetchElement($jsonld, 'description');
1099 if (!empty($content)) {
1100 $jsonldinfo['publisher_description'] = trim($content);
1103 $content = JsonLD::fetchElement($jsonld, 'url');
1104 if (!empty($content)) {
1105 $jsonldinfo['publisher_url'] = trim($content);
1108 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1109 if (!empty($content)) {
1110 $jsonldinfo['publisher_img'] = trim($content);
1113 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1114 if (!empty($content)) {
1115 $jsonldinfo['publisher_name'] = trim($content);
1118 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1119 if (!empty($content)) {
1120 $jsonldinfo['publisher_url'] = trim($content);
1123 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1124 return array_merge($siteinfo, $jsonldinfo);
1128 * Fetch data from the provided JSON-LD Person type
1129 * @see https://schema.org/Person
1131 * @param array $siteinfo
1132 * @param array $jsonld
1133 * @return array siteinfo
1135 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld): array
1139 $content = JsonLD::fetchElement($jsonld, 'name');
1140 if (!empty($content)) {
1141 $jsonldinfo['author_name'] = trim($content);
1144 $content = JsonLD::fetchElement($jsonld, 'description');
1145 if (!empty($content)) {
1146 $jsonldinfo['author_description'] = trim($content);
1149 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1150 if (!empty($content) && is_string($content)) {
1151 $jsonldinfo['author_url'] = trim($content);
1154 $content = JsonLD::fetchElement($jsonld, 'url');
1155 if (!empty($content)) {
1156 $jsonldinfo['author_url'] = trim($content);
1159 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1160 if (!empty($content) && !is_string($content)) {
1161 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1164 if (!empty($content) && is_string($content)) {
1165 $jsonldinfo['author_img'] = trim($content);
1168 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1169 return array_merge($siteinfo, $jsonldinfo);
1173 * Fetch data from the provided JSON-LD MediaObject type
1174 * @see https://schema.org/MediaObject
1176 * @param array $siteinfo
1177 * @param array $jsonld
1178 * @return array siteinfo
1180 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name): array
1184 $content = JsonLD::fetchElement($jsonld, 'caption');
1185 if (!empty($content)) {
1186 $media['caption'] = trim($content);
1189 $content = JsonLD::fetchElement($jsonld, 'url');
1190 if (!empty($content)) {
1191 $media['url'] = trim($content);
1194 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1195 if (!empty($content)) {
1196 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1199 $content = JsonLD::fetchElement($jsonld, 'description');
1200 if (!empty($content)) {
1201 $media['description'] = trim($content);
1204 $content = JsonLD::fetchElement($jsonld, 'name');
1205 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1206 $media['name'] = trim($content);
1209 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1210 if (!empty($content)) {
1211 $media['content'] = trim($content);
1214 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1215 if (!empty($content)) {
1216 $media['embed'] = trim($content);
1219 $content = JsonLD::fetchElement($jsonld, 'height');
1220 if (!empty($content)) {
1221 $media['height'] = trim($content);
1224 $content = JsonLD::fetchElement($jsonld, 'width');
1225 if (!empty($content)) {
1226 $media['width'] = trim($content);
1229 $content = JsonLD::fetchElement($jsonld, 'image');
1230 if (!empty($content)) {
1231 $media['image'] = trim($content);
1234 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1235 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1236 if (!empty($media['image'])) {
1237 $media['preview'] = trim($content);
1239 $media['image'] = trim($content);
1243 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1244 $siteinfo[$name][] = $media;