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\HTTPException;
33 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 * Get information about a given URL
38 * Class with methods for extracting certain content from an url
42 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
43 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
46 * Maximum number of characters for the description
48 const MAX_DESC_COUNT = 250;
51 * Minimum number of characters for the description
53 const MIN_DESC_COUNT = 100;
56 * Fetch the content type of the given url
57 * @param string $url URL of the page
58 * @return array content type
60 public static function getContentType(string $url)
62 $curlResult = DI::httpClient()->head($url);
64 // Workaround for systems that can't handle a HEAD request
65 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
66 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
69 if (!$curlResult->isSuccess()) {
73 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
74 if (empty($contenttype)) {
75 return ['application', 'octet-stream'];
78 return explode('/', current(explode(';', $contenttype)));
82 * Search for chached embeddable data of an url otherwise fetch it
84 * @param string $url The url of the page which should be scraped
85 * @param bool $do_oembed The false option is used by the function fetch_oembed()
86 * to avoid endless loops
88 * @return array which contains needed data for embedding
89 * string 'url' => The url of the parsed page
90 * string 'type' => Content type
91 * string 'title' => (optional) The title of the content
92 * string 'text' => (optional) The description for the content
93 * string 'image' => (optional) A preview image of the content
94 * array 'images' => (optional) Array of preview pictures
95 * string 'keywords' => (optional) The tags which belong to the content
97 * @throws HTTPException\InternalServerErrorException
98 * @see ParseUrl::getSiteinfo() for more information about scraping
101 public static function getSiteinfoCached($url, $do_oembed = true): array
110 $urlHash = hash('sha256', $url);
112 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
113 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
115 if (!empty($parsed_url['content'])) {
116 $data = unserialize($parsed_url['content']);
120 $data = self::getSiteinfo($url, $do_oembed);
122 $expires = $data['expires'];
124 unset($data['expires']);
129 'url_hash' => $urlHash,
130 'oembed' => $do_oembed,
132 'content' => serialize($data),
133 'created' => DateTimeFormat::utcNow(),
134 'expires' => $expires,
136 Database::INSERT_UPDATE
143 * Parse a page for embeddable content information
145 * This method parses to url for meta data which can be used to embed
146 * the content. If available it prioritizes Open Graph meta tags.
147 * If this is not available it uses the twitter cards meta tags.
148 * As fallback it uses standard html elements with meta informations
149 * like \<title\>Awesome Title\</title\> or
150 * \<meta name="description" content="An awesome description"\>
152 * @param string $url The url of the page which should be scraped
153 * @param bool $do_oembed The false option is used by the function fetch_oembed()
154 * to avoid endless loops
155 * @param int $count Internal counter to avoid endless loops
157 * @return array which contains needed data for embedding
158 * string 'url' => The url of the parsed page
159 * string 'type' => Content type (error, link, photo, image, audio, video)
160 * string 'title' => (optional) The title of the content
161 * string 'text' => (optional) The description for the content
162 * string 'image' => (optional) A preview image of the content
163 * array 'images' => (optional) Array of preview pictures
164 * string 'keywords' => (optional) The tags which belong to the content
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167 * @todo https://developers.google.com/+/plugins/snippet/
169 * <meta itemprop="name" content="Awesome title">
170 * <meta itemprop="description" content="An awesome description">
171 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
173 * <body itemscope itemtype="http://schema.org/Product">
174 * <h1 itemprop="name">Shiny Trinket</h1>
175 * <img itemprop="image" src="{image-url}" />
176 * <p itemprop="description">Shiny trinkets are shiny.</p>
180 public static function getSiteinfo($url, $do_oembed = true, $count = 1)
189 // Check if the URL does contain a scheme
190 $scheme = parse_url($url, PHP_URL_SCHEME);
193 $url = 'http://' . ltrim($url, '/');
196 $url = trim($url, "'\"");
198 $url = Network::stripTrackingQueryParams($url);
203 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
207 Logger::notice('Endless loop detected', ['url' => $url]);
211 $type = self::getContentType($url);
212 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
213 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
214 $siteinfo['type'] = $type[0];
218 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
219 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
223 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
224 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
225 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
229 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
231 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
232 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
233 $maxAge = max(86400, (int)array_pop($matches));
234 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
238 $body = $curlResult->getBody();
241 $oembed_data = OEmbed::fetchURL($url, false, false);
243 if (!empty($oembed_data->type)) {
244 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
245 $siteinfo['type'] = $oembed_data->type;
248 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
249 if ($siteinfo['type'] != 'photo') {
250 if (!empty($oembed_data->title)) {
251 $siteinfo['title'] = trim($oembed_data->title);
253 if (!empty($oembed_data->description)) {
254 $siteinfo['text'] = trim($oembed_data->description);
256 if (!empty($oembed_data->author_name)) {
257 $siteinfo['author_name'] = trim($oembed_data->author_name);
259 if (!empty($oembed_data->author_url)) {
260 $siteinfo['author_url'] = trim($oembed_data->author_url);
262 if (!empty($oembed_data->provider_name)) {
263 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
265 if (!empty($oembed_data->provider_url)) {
266 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
268 if (!empty($oembed_data->thumbnail_url)) {
269 $siteinfo['image'] = $oembed_data->thumbnail_url;
276 // Look for a charset, first in headers
277 // Expected form: Content-Type: text/html; charset=ISO-8859-4
278 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
279 $charset = trim(trim(trim(array_pop($matches)), ';,'));
282 // Then in body that gets precedence
284 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
285 // - <meta charset="utf-8">
286 // - <meta charset=utf-8>
287 // - <meta charSet="utf-8">
288 // We escape <style> and <script> tags since they can contain irrelevant charset information
289 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
290 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
291 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
292 $charset = trim(trim(trim(array_pop($matches)), ';,'));
296 $siteinfo['charset'] = $charset;
298 if ($charset && strtoupper($charset) != 'UTF-8') {
299 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
300 $charset = str_ireplace('latin-1', 'latin1', $charset);
302 Logger::info('detected charset', ['charset' => $charset]);
303 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
306 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
308 $doc = new DOMDocument();
309 @$doc->loadHTML($body);
311 XML::deleteNode($doc, 'style');
312 XML::deleteNode($doc, 'option');
313 XML::deleteNode($doc, 'h1');
314 XML::deleteNode($doc, 'h2');
315 XML::deleteNode($doc, 'h3');
316 XML::deleteNode($doc, 'h4');
317 XML::deleteNode($doc, 'h5');
318 XML::deleteNode($doc, 'h6');
319 XML::deleteNode($doc, 'ol');
320 XML::deleteNode($doc, 'ul');
322 $xpath = new DOMXPath($doc);
324 $list = $xpath->query('//meta[@content]');
325 foreach ($list as $node) {
327 if ($node->attributes->length) {
328 foreach ($node->attributes as $attribute) {
329 $meta_tag[$attribute->name] = $attribute->value;
333 if (@$meta_tag['http-equiv'] == 'refresh') {
334 $path = $meta_tag['content'];
335 $pathinfo = explode(';', $path);
337 foreach ($pathinfo as $value) {
338 if (substr(strtolower($value), 0, 4) == 'url=') {
339 $content = substr($value, 4);
342 if ($content != '') {
343 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
349 $list = $xpath->query('//title');
350 if ($list->length > 0) {
351 $siteinfo['title'] = trim($list->item(0)->nodeValue);
354 $list = $xpath->query('//meta[@name]');
355 foreach ($list as $node) {
357 if ($node->attributes->length) {
358 foreach ($node->attributes as $attribute) {
359 $meta_tag[$attribute->name] = $attribute->value;
363 if (empty($meta_tag['content'])) {
367 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
369 switch (strtolower($meta_tag['name'])) {
371 $siteinfo['title'] = trim($meta_tag['content']);
374 $siteinfo['text'] = trim($meta_tag['content']);
377 $siteinfo['image'] = $meta_tag['content'];
379 case 'twitter:image':
380 $siteinfo['image'] = $meta_tag['content'];
382 case 'twitter:image:src':
383 $siteinfo['image'] = $meta_tag['content'];
385 case 'twitter:description':
386 $siteinfo['text'] = trim($meta_tag['content']);
388 case 'twitter:title':
389 $siteinfo['title'] = trim($meta_tag['content']);
391 case 'twitter:player':
392 $siteinfo['player']['embed'] = trim($meta_tag['content']);
394 case 'twitter:player:stream':
395 $siteinfo['player']['stream'] = trim($meta_tag['content']);
397 case 'twitter:player:width':
398 $siteinfo['player']['width'] = intval($meta_tag['content']);
400 case 'twitter:player:height':
401 $siteinfo['player']['height'] = intval($meta_tag['content']);
404 $siteinfo['title'] = trim($meta_tag['content']);
406 case 'dc.description':
407 $siteinfo['text'] = trim($meta_tag['content']);
410 $siteinfo['publisher_name'] = trim($meta_tag['content']);
413 $keywords = explode(',', $meta_tag['content']);
415 case 'news_keywords':
416 $keywords = explode(',', $meta_tag['content']);
421 if (isset($keywords)) {
422 $siteinfo['keywords'] = [];
423 foreach ($keywords as $keyword) {
424 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
425 $siteinfo['keywords'][] = trim($keyword);
430 $list = $xpath->query('//meta[@property]');
431 foreach ($list as $node) {
433 if ($node->attributes->length) {
434 foreach ($node->attributes as $attribute) {
435 $meta_tag[$attribute->name] = $attribute->value;
439 if (!empty($meta_tag['content'])) {
440 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
442 switch (strtolower($meta_tag['property'])) {
444 $siteinfo['image'] = $meta_tag['content'];
447 $siteinfo['image'] = $meta_tag['content'];
449 case 'og:image:secure_url':
450 $siteinfo['image'] = $meta_tag['content'];
453 $siteinfo['title'] = trim($meta_tag['content']);
455 case 'og:description':
456 $siteinfo['text'] = trim($meta_tag['content']);
459 $siteinfo['publisher_name'] = trim($meta_tag['content']);
462 $siteinfo['language'] = trim($meta_tag['content']);
465 $siteinfo['pagetype'] = trim($meta_tag['content']);
467 case 'twitter:description':
468 $siteinfo['text'] = trim($meta_tag['content']);
470 case 'twitter:title':
471 $siteinfo['title'] = trim($meta_tag['content']);
473 case 'twitter:image':
474 $siteinfo['image'] = $meta_tag['content'];
480 $list = $xpath->query("//script[@type='application/ld+json']");
481 foreach ($list as $node) {
482 if (!empty($node->nodeValue)) {
483 if ($jsonld = json_decode($node->nodeValue, true)) {
484 $siteinfo = self::parseParts($siteinfo, $jsonld);
489 if (!empty($siteinfo['player']['stream'])) {
490 // Only add player data to media arrays if there is no duplicate
491 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
492 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
493 $contenttype = self::getContentType($siteinfo['player']['stream']);
494 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
495 $media = ['content' => $siteinfo['player']['stream']];
497 if (!empty($siteinfo['player']['embed'])) {
498 $media['embed'] = $siteinfo['player']['embed'];
501 $siteinfo[$contenttype[0]][] = $media;
506 if (!empty($siteinfo['image'])) {
507 $siteinfo['images'] = $siteinfo['images'] ?? [];
508 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
509 unset($siteinfo['image']);
512 $siteinfo = self::checkMedia($url, $siteinfo);
514 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
515 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
516 $pos = mb_strrpos($siteinfo['text'], '.');
517 if ($pos > self::MIN_DESC_COUNT) {
518 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
522 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
524 Hook::callAll('getsiteinfo', $siteinfo);
532 * Check the attached media elements.
533 * Fix existing data and add missing data.
535 * @param string $page_url
536 * @param array $siteinfo
539 private static function checkMedia(string $page_url, array $siteinfo) : array
541 if (!empty($siteinfo['images'])) {
542 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
543 // According to the specifications someone could place a picture url into the content field as well.
544 // But this doesn't seem to happen in the wild, so we don't cover it here.
545 if (!empty($image['url'])) {
546 $image['url'] = self::completeUrl($image['url'], $page_url);
547 $photodata = Images::getInfoFromURLCached($image['url']);
548 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
549 $image['src'] = $image['url'];
550 $image['width'] = $photodata[0];
551 $image['height'] = $photodata[1];
552 $image['contenttype'] = $photodata['mime'];
553 unset($image['url']);
563 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
566 foreach (['audio', 'video'] as $element) {
567 if (!empty($siteinfo[$element])) {
568 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
573 foreach (['embed', 'content', 'url'] as $field) {
574 if (!empty($media[$field])) {
575 $media[$field] = self::completeUrl($media[$field], $page_url);
576 $type = self::getContentType($media[$field]);
577 if (($type[0] ?? '') == 'text') {
578 if ($field == 'embed') {
579 $embed = $media[$field];
581 $url = $media[$field];
583 } elseif (!empty($type[0])) {
584 $content = $media[$field];
585 $contenttype = implode('/', $type);
588 unset($media[$field]);
591 foreach (['image', 'preview'] as $field) {
592 if (!empty($media[$field])) {
593 $media[$field] = self::completeUrl($media[$field], $page_url);
598 $media['url'] = $url;
600 if (!empty($embed)) {
601 $media['embed'] = $embed;
602 if (empty($siteinfo['player']['embed'])) {
603 $siteinfo['player']['embed'] = $embed;
606 if (!empty($content)) {
607 $media['src'] = $content;
609 if (!empty($contenttype)) {
610 $media['contenttype'] = $contenttype;
612 if (empty($url) && empty($content) && empty($embed)) {
618 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
620 if (empty($siteinfo[$element])) {
621 unset($siteinfo[$element]);
628 * Convert tags from CSV to an array
630 * @param string $string Tags
631 * @return array with formatted Hashtags
633 public static function convertTagsToArray($string)
635 $arr_tags = str_getcsv($string);
636 if (count($arr_tags)) {
637 // add the # sign to every tag
638 array_walk($arr_tags, ["self", "arrAddHashes"]);
645 * Add a hasht sign to a string
647 * This method is used as callback function
649 * @param string $tag The pure tag name
650 * @param int $k Counter for internal use
653 private static function arrAddHashes(&$tag, $k)
659 * Add a scheme to an url
661 * The src attribute of some html elements (e.g. images)
662 * can miss the scheme so we need to add the correct
665 * @param string $url The url which possibly does have
666 * a missing scheme (a link to an image)
667 * @param string $scheme The url with a correct scheme
668 * (e.g. the url from the webpage which does contain the image)
670 * @return string The url with a scheme
672 private static function completeUrl($url, $scheme)
674 $urlarr = parse_url($url);
676 // If the url does allready have an scheme
677 // we can stop the process here
678 if (isset($urlarr["scheme"])) {
682 $schemearr = parse_url($scheme);
684 $complete = $schemearr["scheme"]."://".$schemearr["host"];
686 if (!empty($schemearr["port"])) {
687 $complete .= ":".$schemearr["port"];
690 if (!empty($urlarr["path"])) {
691 if (strpos($urlarr["path"], "/") !== 0) {
695 $complete .= $urlarr["path"];
698 if (!empty($urlarr["query"])) {
699 $complete .= "?".$urlarr["query"];
702 if (!empty($urlarr["fragment"])) {
703 $complete .= "#".$urlarr["fragment"];
710 * Parse the Json-Ld parts of a web page
712 * @param array $siteinfo
713 * @param array $jsonld
714 * @return array siteinfo
716 private static function parseParts(array $siteinfo, array $jsonld)
718 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
719 foreach ($jsonld['@graph'] as $part) {
720 if (!empty($part) && is_array($part)) {
721 $siteinfo = self::parseParts($siteinfo, $part);
724 } elseif (!empty($jsonld['@type'])) {
725 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
726 } elseif (!empty($jsonld)) {
727 $keys = array_keys($jsonld);
728 $numeric_keys = true;
729 foreach ($keys as $key) {
731 $numeric_keys = false;
735 foreach ($jsonld as $part) {
736 if (!empty($part) && is_array($part)) {
737 $siteinfo = self::parseParts($siteinfo, $part);
743 array_walk_recursive($siteinfo, function (&$element) {
744 if (is_string($element)) {
745 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
753 * Improve the siteinfo with information from the provided JSON-LD information
754 * @see https://jsonld.com/
755 * @see https://schema.org/
757 * @param array $siteinfo
758 * @param array $jsonld
759 * @return array siteinfo
761 private static function parseJsonLd(array $siteinfo, array $jsonld)
763 $type = JsonLD::fetchElement($jsonld, '@type');
765 Logger::info('Empty type', ['url' => $siteinfo['url']]);
769 // Silently ignore some types that aren't processed
770 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
771 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
772 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
778 case 'AdvertiserContentArticle':
781 case 'SatiricalArticle':
782 case 'ScholarlyArticle':
783 case 'SocialMediaPosting':
785 case 'ReportageNewsArticle':
786 case 'SocialMediaPosting':
788 case 'LiveBlogPosting':
789 case 'DiscussionForumPosting':
790 return self::parseJsonLdArticle($siteinfo, $jsonld);
794 case 'CollectionPage':
798 case 'MedicalWebPage':
801 case 'RealEstateListing':
802 case 'SearchResultsPage':
808 return self::parseJsonLdWebPage($siteinfo, $jsonld);
810 return self::parseJsonLdWebSite($siteinfo, $jsonld);
815 case 'EducationalOrganization':
816 case 'FundingScheme':
817 case 'GovernmentOrganization':
818 case 'LibrarySystem':
819 case 'LocalBusiness':
820 case 'MedicalOrganization':
822 case 'NewsMediaOrganization':
824 case 'SportsOrganization':
826 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
829 case 'PerformingGroup':
833 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
836 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
838 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
840 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
842 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
848 * Fetch author and publisher data
850 * @param array $siteinfo
851 * @param array $jsonld
852 * @return array siteinfo
854 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
858 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
859 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
860 if (!empty($content) && is_string($content)) {
861 $jsonldinfo['publisher_name'] = trim($content);
864 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
865 if (!empty($content) && is_string($content)) {
866 $jsonldinfo['publisher_url'] = trim($content);
869 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
870 if (!empty($brand) && is_array($brand)) {
871 $content = JsonLD::fetchElement($brand, 'name');
872 if (!empty($content) && is_string($content)) {
873 $jsonldinfo['publisher_name'] = trim($content);
876 $content = JsonLD::fetchElement($brand, 'url');
877 if (!empty($content) && is_string($content)) {
878 $jsonldinfo['publisher_url'] = trim($content);
881 $content = JsonLD::fetchElement($brand, 'logo', 'url');
882 if (!empty($content) && is_string($content)) {
883 $jsonldinfo['publisher_img'] = trim($content);
887 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
888 if (!empty($logo) && is_array($logo)) {
889 $content = JsonLD::fetchElement($logo, 'url');
890 if (!empty($content) && is_string($content)) {
891 $jsonldinfo['publisher_img'] = trim($content);
894 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
895 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
898 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
899 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
900 if (!empty($content) && is_string($content)) {
901 $jsonldinfo['author_name'] = trim($content);
904 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
905 if (!empty($content) && is_string($content)) {
906 $jsonldinfo['author_url'] = trim($content);
909 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
910 if (!empty($content) && is_string($content)) {
911 $jsonldinfo['author_url'] = trim($content);
914 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
915 if (!empty($logo) && is_array($logo)) {
916 $content = JsonLD::fetchElement($logo, 'url');
917 if (!empty($content) && is_string($content)) {
918 $jsonldinfo['author_img'] = trim($content);
921 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
922 $jsonldinfo['author_name'] = trim($jsonld['author']);
925 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
927 return array_merge($siteinfo, $jsonldinfo);
931 * Fetch data from the provided JSON-LD Article type
932 * @see https://schema.org/Article
934 * @param array $siteinfo
935 * @param array $jsonld
936 * @return array siteinfo
938 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
942 $content = JsonLD::fetchElement($jsonld, 'headline');
943 if (!empty($content) && is_string($content)) {
944 $jsonldinfo['title'] = trim($content);
947 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
948 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
949 $jsonldinfo['alternative_title'] = trim($content);
952 $content = JsonLD::fetchElement($jsonld, 'description');
953 if (!empty($content) && is_string($content)) {
954 $jsonldinfo['text'] = trim($content);
957 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
958 if (!empty($content)) {
959 $jsonldinfo['image'] = trim($content);
962 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
963 if (!empty($content) && is_string($content)) {
964 $jsonldinfo['image'] = trim($content);
967 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
968 $content = JsonLD::fetchElement($jsonld, 'keywords');
969 if (!empty($content)) {
970 $siteinfo['keywords'] = [];
971 $keywords = explode(',', $content);
972 foreach ($keywords as $keyword) {
973 $siteinfo['keywords'][] = trim($keyword);
976 } elseif (!empty($jsonld['keywords'])) {
977 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
978 if (!empty($content) && is_array($content)) {
979 $jsonldinfo['keywords'] = $content;
983 $content = JsonLD::fetchElement($jsonld, 'datePublished');
984 if (!empty($content) && is_string($content)) {
985 $jsonldinfo['published'] = DateTimeFormat::utc($content);
988 $content = JsonLD::fetchElement($jsonld, 'dateModified');
989 if (!empty($content) && is_string($content)) {
990 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
993 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
995 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
997 return array_merge($siteinfo, $jsonldinfo);
1001 * Fetch data from the provided JSON-LD WebPage type
1002 * @see https://schema.org/WebPage
1004 * @param array $siteinfo
1005 * @param array $jsonld
1006 * @return array siteinfo
1008 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
1012 $content = JsonLD::fetchElement($jsonld, 'name');
1013 if (!empty($content)) {
1014 $jsonldinfo['title'] = trim($content);
1017 $content = JsonLD::fetchElement($jsonld, 'description');
1018 if (!empty($content)) {
1019 $jsonldinfo['text'] = trim($content);
1022 $content = JsonLD::fetchElement($jsonld, 'image');
1023 if (!empty($content)) {
1024 $jsonldinfo['image'] = trim($content);
1027 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1028 if (!empty($content)) {
1029 $jsonldinfo['image'] = trim($content);
1032 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1034 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1036 return array_merge($siteinfo, $jsonldinfo);
1040 * Fetch data from the provided JSON-LD WebSite type
1041 * @see https://schema.org/WebSite
1043 * @param array $siteinfo
1044 * @param array $jsonld
1045 * @return array siteinfo
1047 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1051 $content = JsonLD::fetchElement($jsonld, 'name');
1052 if (!empty($content)) {
1053 $jsonldinfo['publisher_name'] = trim($content);
1056 $content = JsonLD::fetchElement($jsonld, 'description');
1057 if (!empty($content)) {
1058 $jsonldinfo['publisher_description'] = trim($content);
1061 $content = JsonLD::fetchElement($jsonld, 'url');
1062 if (!empty($content)) {
1063 $jsonldinfo['publisher_url'] = trim($content);
1066 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1067 if (!empty($content)) {
1068 $jsonldinfo['image'] = trim($content);
1071 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1073 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1074 return array_merge($siteinfo, $jsonldinfo);
1078 * Fetch data from the provided JSON-LD Organization type
1079 * @see https://schema.org/Organization
1081 * @param array $siteinfo
1082 * @param array $jsonld
1083 * @return array siteinfo
1085 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1089 $content = JsonLD::fetchElement($jsonld, 'name');
1090 if (!empty($content)) {
1091 $jsonldinfo['publisher_name'] = trim($content);
1094 $content = JsonLD::fetchElement($jsonld, 'description');
1095 if (!empty($content)) {
1096 $jsonldinfo['publisher_description'] = trim($content);
1099 $content = JsonLD::fetchElement($jsonld, 'url');
1100 if (!empty($content)) {
1101 $jsonldinfo['publisher_url'] = trim($content);
1104 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1105 if (!empty($content)) {
1106 $jsonldinfo['publisher_img'] = trim($content);
1109 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1110 if (!empty($content)) {
1111 $jsonldinfo['publisher_name'] = trim($content);
1114 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1115 if (!empty($content)) {
1116 $jsonldinfo['publisher_url'] = trim($content);
1119 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1120 return array_merge($siteinfo, $jsonldinfo);
1124 * Fetch data from the provided JSON-LD Person type
1125 * @see https://schema.org/Person
1127 * @param array $siteinfo
1128 * @param array $jsonld
1129 * @return array siteinfo
1131 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1135 $content = JsonLD::fetchElement($jsonld, 'name');
1136 if (!empty($content)) {
1137 $jsonldinfo['author_name'] = trim($content);
1140 $content = JsonLD::fetchElement($jsonld, 'description');
1141 if (!empty($content)) {
1142 $jsonldinfo['author_description'] = trim($content);
1145 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1146 if (!empty($content) && is_string($content)) {
1147 $jsonldinfo['author_url'] = trim($content);
1150 $content = JsonLD::fetchElement($jsonld, 'url');
1151 if (!empty($content)) {
1152 $jsonldinfo['author_url'] = trim($content);
1155 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1156 if (!empty($content) && !is_string($content)) {
1157 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1160 if (!empty($content) && is_string($content)) {
1161 $jsonldinfo['author_img'] = trim($content);
1164 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1165 return array_merge($siteinfo, $jsonldinfo);
1169 * Fetch data from the provided JSON-LD MediaObject type
1170 * @see https://schema.org/MediaObject
1172 * @param array $siteinfo
1173 * @param array $jsonld
1174 * @return array siteinfo
1176 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1180 $content = JsonLD::fetchElement($jsonld, 'caption');
1181 if (!empty($content)) {
1182 $media['caption'] = trim($content);
1185 $content = JsonLD::fetchElement($jsonld, 'url');
1186 if (!empty($content)) {
1187 $media['url'] = trim($content);
1190 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1191 if (!empty($content)) {
1192 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1195 $content = JsonLD::fetchElement($jsonld, 'description');
1196 if (!empty($content)) {
1197 $media['description'] = trim($content);
1200 $content = JsonLD::fetchElement($jsonld, 'name');
1201 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1202 $media['name'] = trim($content);
1205 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1206 if (!empty($content)) {
1207 $media['content'] = trim($content);
1210 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1211 if (!empty($content)) {
1212 $media['embed'] = trim($content);
1215 $content = JsonLD::fetchElement($jsonld, 'height');
1216 if (!empty($content)) {
1217 $media['height'] = trim($content);
1220 $content = JsonLD::fetchElement($jsonld, 'width');
1221 if (!empty($content)) {
1222 $media['width'] = trim($content);
1225 $content = JsonLD::fetchElement($jsonld, 'image');
1226 if (!empty($content)) {
1227 $media['image'] = trim($content);
1230 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1231 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1232 if (!empty($media['image'])) {
1233 $media['preview'] = trim($content);
1235 $media['image'] = trim($content);
1239 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1240 $siteinfo[$name][] = $media;