3 * @copyright Copyright (C) 2010-2021, 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;
35 * Get information about a given URL
37 * Class with methods for extracting certain content from an url
41 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
45 * Maximum number of characters for the description
47 const MAX_DESC_COUNT = 250;
50 * Minimum number of characters for the description
52 const MIN_DESC_COUNT = 100;
55 * Fetch the content type of the given url
56 * @param string $url URL of the page
57 * @return array content type
59 public static function getContentType(string $url)
61 $curlResult = DI::httpRequest()->head($url);
62 if (!$curlResult->isSuccess()) {
66 $contenttype = $curlResult->getHeader('Content-Type');
67 if (empty($contenttype)) {
71 return explode('/', current(explode(';', $contenttype)));
75 * Search for chached embeddable data of an url otherwise fetch it
77 * @param string $url The url of the page which should be scraped
78 * @param bool $do_oembed The false option is used by the function fetch_oembed()
79 * to avoid endless loops
81 * @return array which contains needed data for embedding
82 * string 'url' => The url of the parsed page
83 * string 'type' => Content type
84 * string 'title' => (optional) The title of the content
85 * string 'text' => (optional) The description for the content
86 * string 'image' => (optional) A preview image of the content
87 * array 'images' => (optional) Array of preview pictures
88 * string 'keywords' => (optional) The tags which belong to the content
90 * @throws HTTPException\InternalServerErrorException
91 * @see ParseUrl::getSiteinfo() for more information about scraping
94 public static function getSiteinfoCached($url, $do_oembed = true): array
103 $urlHash = hash('sha256', $url);
105 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
106 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
108 if (!empty($parsed_url['content'])) {
109 $data = unserialize($parsed_url['content']);
113 $data = self::getSiteinfo($url, $do_oembed);
115 $expires = $data['expires'];
117 unset($data['expires']);
122 'url_hash' => $urlHash,
123 'oembed' => $do_oembed,
125 'content' => serialize($data),
126 'created' => DateTimeFormat::utcNow(),
127 'expires' => $expires,
129 Database::INSERT_UPDATE
136 * Parse a page for embeddable content information
138 * This method parses to url for meta data which can be used to embed
139 * the content. If available it prioritizes Open Graph meta tags.
140 * If this is not available it uses the twitter cards meta tags.
141 * As fallback it uses standard html elements with meta informations
142 * like \<title\>Awesome Title\</title\> or
143 * \<meta name="description" content="An awesome description"\>
145 * @param string $url The url of the page which should be scraped
146 * @param bool $do_oembed The false option is used by the function fetch_oembed()
147 * to avoid endless loops
148 * @param int $count Internal counter to avoid endless loops
150 * @return array which contains needed data for embedding
151 * string 'url' => The url of the parsed page
152 * string 'type' => Content type (error, link, photo, image, audio, video)
153 * string 'title' => (optional) The title of the content
154 * string 'text' => (optional) The description for the content
155 * string 'image' => (optional) A preview image of the content
156 * array 'images' => (optional) Array of preview pictures
157 * string 'keywords' => (optional) The tags which belong to the content
159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
160 * @todo https://developers.google.com/+/plugins/snippet/
162 * <meta itemprop="name" content="Awesome title">
163 * <meta itemprop="description" content="An awesome description">
164 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
166 * <body itemscope itemtype="http://schema.org/Product">
167 * <h1 itemprop="name">Shiny Trinket</h1>
168 * <img itemprop="image" src="{image-url}" />
169 * <p itemprop="description">Shiny trinkets are shiny.</p>
173 public static function getSiteinfo($url, $do_oembed = true, $count = 1)
182 // Check if the URL does contain a scheme
183 $scheme = parse_url($url, PHP_URL_SCHEME);
186 $url = 'http://' . ltrim($url, '/');
189 $url = trim($url, "'\"");
191 $url = Network::stripTrackingQueryParams($url);
196 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
200 Logger::notice('Endless loop detected', ['url' => $url]);
204 $type = self::getContentType($url);
205 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
206 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
207 $siteinfo['type'] = $type[0];
211 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
212 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
216 $curlResult = DI::httpRequest()->get($url, false, ['content_length' => 1000000]);
217 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
221 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
223 // If the file is too large then exit
224 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
228 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
229 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
230 $maxAge = max(86400, (int)array_pop($matches));
231 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
235 $body = $curlResult->getBody();
238 $oembed_data = OEmbed::fetchURL($url, false, false);
240 if (!empty($oembed_data->type)) {
241 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
242 $siteinfo['type'] = $oembed_data->type;
245 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
246 if ($siteinfo['type'] != 'photo') {
247 if (!empty($oembed_data->title)) {
248 $siteinfo['title'] = trim($oembed_data->title);
250 if (!empty($oembed_data->description)) {
251 $siteinfo['text'] = trim($oembed_data->description);
253 if (!empty($oembed_data->author_name)) {
254 $siteinfo['author_name'] = trim($oembed_data->author_name);
256 if (!empty($oembed_data->author_url)) {
257 $siteinfo['author_url'] = trim($oembed_data->author_url);
259 if (!empty($oembed_data->provider_name)) {
260 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
262 if (!empty($oembed_data->provider_url)) {
263 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
265 if (!empty($oembed_data->thumbnail_url)) {
266 $siteinfo['image'] = $oembed_data->thumbnail_url;
273 // Look for a charset, first in headers
274 // Expected form: Content-Type: text/html; charset=ISO-8859-4
275 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
276 $charset = trim(trim(trim(array_pop($matches)), ';,'));
279 // Then in body that gets precedence
281 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
282 // - <meta charset="utf-8">
283 // - <meta charset=utf-8>
284 // - <meta charSet="utf-8">
285 // We escape <style> and <script> tags since they can contain irrelevant charset information
286 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
287 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
288 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
289 $charset = trim(trim(trim(array_pop($matches)), ';,'));
293 $siteinfo['charset'] = $charset;
295 if ($charset && strtoupper($charset) != 'UTF-8') {
296 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
297 $charset = str_ireplace('latin-1', 'latin1', $charset);
299 Logger::info('detected charset', ['charset' => $charset]);
300 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
303 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
305 $doc = new DOMDocument();
306 @$doc->loadHTML($body);
308 XML::deleteNode($doc, 'style');
309 XML::deleteNode($doc, 'option');
310 XML::deleteNode($doc, 'h1');
311 XML::deleteNode($doc, 'h2');
312 XML::deleteNode($doc, 'h3');
313 XML::deleteNode($doc, 'h4');
314 XML::deleteNode($doc, 'h5');
315 XML::deleteNode($doc, 'h6');
316 XML::deleteNode($doc, 'ol');
317 XML::deleteNode($doc, 'ul');
319 $xpath = new DOMXPath($doc);
321 $list = $xpath->query('//meta[@content]');
322 foreach ($list as $node) {
324 if ($node->attributes->length) {
325 foreach ($node->attributes as $attribute) {
326 $meta_tag[$attribute->name] = $attribute->value;
330 if (@$meta_tag['http-equiv'] == 'refresh') {
331 $path = $meta_tag['content'];
332 $pathinfo = explode(';', $path);
334 foreach ($pathinfo as $value) {
335 if (substr(strtolower($value), 0, 4) == 'url=') {
336 $content = substr($value, 4);
339 if ($content != '') {
340 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
346 $list = $xpath->query('//title');
347 if ($list->length > 0) {
348 $siteinfo['title'] = trim($list->item(0)->nodeValue);
351 $twitter_card = false;
352 $twitter_image = false;
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'];
381 $twitter_image = true;
383 case 'twitter:image:src':
384 $siteinfo['image'] = $meta_tag['content'];
387 // Detect photo pages
388 if ($meta_tag['content'] == 'summary_large_image') {
389 $twitter_card = true;
392 case 'twitter:description':
393 $siteinfo['text'] = trim($meta_tag['content']);
395 case 'twitter:title':
396 $siteinfo['title'] = trim($meta_tag['content']);
399 $siteinfo['title'] = trim($meta_tag['content']);
401 case 'dc.description':
402 $siteinfo['text'] = trim($meta_tag['content']);
405 $siteinfo['publisher_name'] = trim($meta_tag['content']);
408 $keywords = explode(',', $meta_tag['content']);
410 case 'news_keywords':
411 $keywords = explode(',', $meta_tag['content']);
416 if (isset($keywords)) {
417 $siteinfo['keywords'] = [];
418 foreach ($keywords as $keyword) {
419 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
420 $siteinfo['keywords'][] = trim($keyword);
425 $list = $xpath->query('//meta[@property]');
426 foreach ($list as $node) {
428 if ($node->attributes->length) {
429 foreach ($node->attributes as $attribute) {
430 $meta_tag[$attribute->name] = $attribute->value;
434 if (!empty($meta_tag['content'])) {
435 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
437 switch (strtolower($meta_tag['property'])) {
439 $siteinfo['image'] = $meta_tag['content'];
442 $siteinfo['image'] = $meta_tag['content'];
444 case 'og:image:secure_url':
445 $siteinfo['image'] = $meta_tag['content'];
448 $siteinfo['title'] = trim($meta_tag['content']);
450 case 'og:description':
451 $siteinfo['text'] = trim($meta_tag['content']);
454 $siteinfo['publisher_name'] = trim($meta_tag['content']);
456 case 'twitter:description':
457 $siteinfo['text'] = trim($meta_tag['content']);
459 case 'twitter:title':
460 $siteinfo['title'] = trim($meta_tag['content']);
462 case 'twitter:image':
463 $siteinfo['image'] = $meta_tag['content'];
464 $twitter_image = true;
470 $list = $xpath->query("//script[@type='application/ld+json']");
471 foreach ($list as $node) {
472 if (!empty($node->nodeValue)) {
473 if ($jsonld = json_decode($node->nodeValue, true)) {
474 $siteinfo = self::parseParts($siteinfo, $jsonld);
479 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
480 // Prevent to have a photo type without an image
481 // if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
482 // $siteinfo['type'] = 'photo';
485 if (!empty($siteinfo['image'])) {
486 $siteinfo['images'] = $siteinfo['images'] ?? [];
487 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
488 unset($siteinfo['image']);
491 $siteinfo = self::checkMedia($url, $siteinfo);
493 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
494 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
495 $pos = mb_strrpos($siteinfo['text'], '.');
496 if ($pos > self::MIN_DESC_COUNT) {
497 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
501 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
503 Hook::callAll('getsiteinfo', $siteinfo);
509 * Check the attached media elements.
510 * Fix existing data and add missing data.
512 * @param string $page_url
513 * @param array $siteinfo
516 private static function checkMedia(string $page_url, array $siteinfo)
518 if (!empty($siteinfo['images'])) {
519 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
520 // According to the specifications someone could place a picture url into the content field as well.
521 // But this doesn't seem to happen in the wild, so we don't cover it here.
522 if (!empty($image['url'])) {
523 $image['url'] = self::completeUrl($image['url'], $page_url);
524 $photodata = Images::getInfoFromURLCached($image['url']);
525 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
526 $image['src'] = $image['url'];
527 $image['width'] = $photodata[0];
528 $image['height'] = $photodata[1];
529 $image['contenttype'] = $photodata['mime'];
530 unset($image['url']);
540 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
543 foreach (['audio', 'video'] as $element) {
544 if (!empty($siteinfo[$element])) {
545 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
550 foreach (['embed', 'content', 'url'] as $field) {
551 if (!empty($media[$field])) {
552 $media[$field] = self::completeUrl($media[$field], $page_url);
553 $type = self::getContentType($media[$field]);
554 if (($type[0] ?? '') == 'text') {
555 if ($field == 'embed') {
556 $embed = $media[$field];
558 $url = $media[$field];
560 } elseif (!empty($type[0])) {
561 $content = $media[$field];
562 $contenttype = implode('/', $type);
565 unset($media[$field]);
568 foreach (['image', 'preview'] as $field) {
569 if (!empty($media[$field])) {
570 $media[$field] = self::completeUrl($media[$field], $page_url);
575 $media['url'] = $url;
577 if (!empty($embed)) {
578 $media['embed'] = $embed;
579 if (!empty($media['main'])) {
580 $siteinfo['embed'] = $embed;
583 if (!empty($content)) {
584 $media['src'] = $content;
586 if (!empty($contenttype)) {
587 $media['contenttype'] = $contenttype;
589 if (empty($url) && empty($content) && empty($embed)) {
595 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
597 if (empty($siteinfo[$element])) {
598 unset($siteinfo[$element]);
605 * Convert tags from CSV to an array
607 * @param string $string Tags
608 * @return array with formatted Hashtags
610 public static function convertTagsToArray($string)
612 $arr_tags = str_getcsv($string);
613 if (count($arr_tags)) {
614 // add the # sign to every tag
615 array_walk($arr_tags, ["self", "arrAddHashes"]);
622 * Add a hasht sign to a string
624 * This method is used as callback function
626 * @param string $tag The pure tag name
627 * @param int $k Counter for internal use
630 private static function arrAddHashes(&$tag, $k)
636 * Add a scheme to an url
638 * The src attribute of some html elements (e.g. images)
639 * can miss the scheme so we need to add the correct
642 * @param string $url The url which possibly does have
643 * a missing scheme (a link to an image)
644 * @param string $scheme The url with a correct scheme
645 * (e.g. the url from the webpage which does contain the image)
647 * @return string The url with a scheme
649 private static function completeUrl($url, $scheme)
651 $urlarr = parse_url($url);
653 // If the url does allready have an scheme
654 // we can stop the process here
655 if (isset($urlarr["scheme"])) {
659 $schemearr = parse_url($scheme);
661 $complete = $schemearr["scheme"]."://".$schemearr["host"];
663 if (!empty($schemearr["port"])) {
664 $complete .= ":".$schemearr["port"];
667 if (!empty($urlarr["path"])) {
668 if (strpos($urlarr["path"], "/") !== 0) {
672 $complete .= $urlarr["path"];
675 if (!empty($urlarr["query"])) {
676 $complete .= "?".$urlarr["query"];
679 if (!empty($urlarr["fragment"])) {
680 $complete .= "#".$urlarr["fragment"];
687 * Parse the Json-Ld parts of a web page
689 * @param array $siteinfo
690 * @param array $jsonld
691 * @return array siteinfo
693 private static function parseParts(array $siteinfo, array $jsonld)
695 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
696 foreach ($jsonld['@graph'] as $part) {
697 if (!empty($part) && is_array($part)) {
698 $siteinfo = self::parseParts($siteinfo, $part);
701 } elseif (!empty($jsonld['@type'])) {
702 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
703 } elseif (!empty($jsonld)) {
704 $keys = array_keys($jsonld);
705 $numeric_keys = true;
706 foreach ($keys as $key) {
708 $numeric_keys = false;
712 foreach ($jsonld as $part) {
713 if (!empty($part) && is_array($part)) {
714 $siteinfo = self::parseParts($siteinfo, $part);
720 array_walk_recursive($siteinfo, function (&$element) {
721 if (is_string($element)) {
722 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
730 * Improve the siteinfo with information from the provided JSON-LD information
731 * @see https://jsonld.com/
732 * @see https://schema.org/
734 * @param array $siteinfo
735 * @param array $jsonld
736 * @return array siteinfo
738 private static function parseJsonLd(array $siteinfo, array $jsonld)
740 $type = JsonLD::fetchElement($jsonld, '@type');
742 Logger::info('Empty type', ['url' => $siteinfo['url']]);
746 // Silently ignore some types that aren't processed
747 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
748 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
749 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
755 case 'AdvertiserContentArticle':
758 case 'SatiricalArticle':
759 case 'ScholarlyArticle':
760 case 'SocialMediaPosting':
762 case 'ReportageNewsArticle':
763 case 'SocialMediaPosting':
765 case 'LiveBlogPosting':
766 case 'DiscussionForumPosting':
767 return self::parseJsonLdArticle($siteinfo, $jsonld);
771 case 'CollectionPage':
775 case 'MedicalWebPage':
778 case 'RealEstateListing':
779 case 'SearchResultsPage':
785 return self::parseJsonLdWebPage($siteinfo, $jsonld);
787 return self::parseJsonLdWebSite($siteinfo, $jsonld);
792 case 'EducationalOrganization':
793 case 'FundingScheme':
794 case 'GovernmentOrganization':
795 case 'LibrarySystem':
796 case 'LocalBusiness':
797 case 'MedicalOrganization':
799 case 'NewsMediaOrganization':
801 case 'SportsOrganization':
803 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
806 case 'PerformingGroup':
810 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
813 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
815 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
817 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
819 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
825 * Fetch author and publisher data
827 * @param array $siteinfo
828 * @param array $jsonld
829 * @return array siteinfo
831 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
835 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
836 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
837 if (!empty($content) && is_string($content)) {
838 $jsonldinfo['publisher_name'] = trim($content);
841 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
842 if (!empty($content) && is_string($content)) {
843 $jsonldinfo['publisher_url'] = trim($content);
846 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
847 if (!empty($brand) && is_array($brand)) {
848 $content = JsonLD::fetchElement($brand, 'name');
849 if (!empty($content) && is_string($content)) {
850 $jsonldinfo['publisher_name'] = trim($content);
853 $content = JsonLD::fetchElement($brand, 'url');
854 if (!empty($content) && is_string($content)) {
855 $jsonldinfo['publisher_url'] = trim($content);
858 $content = JsonLD::fetchElement($brand, 'logo', 'url');
859 if (!empty($content) && is_string($content)) {
860 $jsonldinfo['publisher_img'] = trim($content);
864 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
865 if (!empty($logo) && is_array($logo)) {
866 $content = JsonLD::fetchElement($logo, 'url');
867 if (!empty($content) && is_string($content)) {
868 $jsonldinfo['publisher_img'] = trim($content);
871 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
872 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
875 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
876 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
877 if (!empty($content) && is_string($content)) {
878 $jsonldinfo['author_name'] = trim($content);
881 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
882 if (!empty($content) && is_string($content)) {
883 $jsonldinfo['author_url'] = trim($content);
886 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
887 if (!empty($content) && is_string($content)) {
888 $jsonldinfo['author_url'] = trim($content);
891 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
892 if (!empty($logo) && is_array($logo)) {
893 $content = JsonLD::fetchElement($logo, 'url');
894 if (!empty($content) && is_string($content)) {
895 $jsonldinfo['author_img'] = trim($content);
898 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
899 $jsonldinfo['author_name'] = trim($jsonld['author']);
902 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
904 return array_merge($siteinfo, $jsonldinfo);
908 * Fetch data from the provided JSON-LD Article type
909 * @see https://schema.org/Article
911 * @param array $siteinfo
912 * @param array $jsonld
913 * @return array siteinfo
915 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
919 $content = JsonLD::fetchElement($jsonld, 'headline');
920 if (!empty($content) && is_string($content)) {
921 $jsonldinfo['title'] = trim($content);
924 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
925 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
926 $jsonldinfo['alternative_title'] = trim($content);
929 $content = JsonLD::fetchElement($jsonld, 'description');
930 if (!empty($content) && is_string($content)) {
931 $jsonldinfo['text'] = trim($content);
934 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
935 if (!empty($content)) {
936 $jsonldinfo['image'] = trim($content);
939 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
940 if (!empty($content) && is_string($content)) {
941 $jsonldinfo['image'] = trim($content);
944 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
945 $content = JsonLD::fetchElement($jsonld, 'keywords');
946 if (!empty($content)) {
947 $siteinfo['keywords'] = [];
948 $keywords = explode(',', $content);
949 foreach ($keywords as $keyword) {
950 $siteinfo['keywords'][] = trim($keyword);
953 } elseif (!empty($jsonld['keywords'])) {
954 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
955 if (!empty($content) && is_array($content)) {
956 $jsonldinfo['keywords'] = $content;
960 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
962 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
964 return array_merge($siteinfo, $jsonldinfo);
968 * Fetch data from the provided JSON-LD WebPage type
969 * @see https://schema.org/WebPage
971 * @param array $siteinfo
972 * @param array $jsonld
973 * @return array siteinfo
975 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
979 $content = JsonLD::fetchElement($jsonld, 'name');
980 if (!empty($content)) {
981 $jsonldinfo['title'] = trim($content);
984 $content = JsonLD::fetchElement($jsonld, 'description');
985 if (!empty($content)) {
986 $jsonldinfo['text'] = trim($content);
989 $content = JsonLD::fetchElement($jsonld, 'image');
990 if (!empty($content)) {
991 $jsonldinfo['image'] = trim($content);
994 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
995 if (!empty($content)) {
996 $jsonldinfo['image'] = trim($content);
999 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1001 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1003 return array_merge($siteinfo, $jsonldinfo);
1007 * Fetch data from the provided JSON-LD WebSite type
1008 * @see https://schema.org/WebSite
1010 * @param array $siteinfo
1011 * @param array $jsonld
1012 * @return array siteinfo
1014 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1018 $content = JsonLD::fetchElement($jsonld, 'name');
1019 if (!empty($content)) {
1020 $jsonldinfo['publisher_name'] = trim($content);
1023 $content = JsonLD::fetchElement($jsonld, 'description');
1024 if (!empty($content)) {
1025 $jsonldinfo['publisher_description'] = trim($content);
1028 $content = JsonLD::fetchElement($jsonld, 'url');
1029 if (!empty($content)) {
1030 $jsonldinfo['publisher_url'] = trim($content);
1033 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1034 if (!empty($content)) {
1035 $jsonldinfo['image'] = trim($content);
1038 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1040 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1041 return array_merge($siteinfo, $jsonldinfo);
1045 * Fetch data from the provided JSON-LD Organization type
1046 * @see https://schema.org/Organization
1048 * @param array $siteinfo
1049 * @param array $jsonld
1050 * @return array siteinfo
1052 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1056 $content = JsonLD::fetchElement($jsonld, 'name');
1057 if (!empty($content)) {
1058 $jsonldinfo['publisher_name'] = trim($content);
1061 $content = JsonLD::fetchElement($jsonld, 'description');
1062 if (!empty($content)) {
1063 $jsonldinfo['publisher_description'] = trim($content);
1066 $content = JsonLD::fetchElement($jsonld, 'url');
1067 if (!empty($content)) {
1068 $jsonldinfo['publisher_url'] = trim($content);
1071 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1072 if (!empty($content)) {
1073 $jsonldinfo['publisher_img'] = trim($content);
1076 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1077 if (!empty($content)) {
1078 $jsonldinfo['publisher_name'] = trim($content);
1081 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1082 if (!empty($content)) {
1083 $jsonldinfo['publisher_url'] = trim($content);
1086 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1087 return array_merge($siteinfo, $jsonldinfo);
1091 * Fetch data from the provided JSON-LD Person type
1092 * @see https://schema.org/Person
1094 * @param array $siteinfo
1095 * @param array $jsonld
1096 * @return array siteinfo
1098 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1102 $content = JsonLD::fetchElement($jsonld, 'name');
1103 if (!empty($content)) {
1104 $jsonldinfo['author_name'] = trim($content);
1107 $content = JsonLD::fetchElement($jsonld, 'description');
1108 if (!empty($content)) {
1109 $jsonldinfo['author_description'] = trim($content);
1112 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1113 if (!empty($content) && is_string($content)) {
1114 $jsonldinfo['author_url'] = trim($content);
1117 $content = JsonLD::fetchElement($jsonld, 'url');
1118 if (!empty($content)) {
1119 $jsonldinfo['author_url'] = trim($content);
1122 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1123 if (!empty($content)) {
1124 $jsonldinfo['author_img'] = trim($content);
1127 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1128 return array_merge($siteinfo, $jsonldinfo);
1132 * Fetch data from the provided JSON-LD MediaObject type
1133 * @see https://schema.org/MediaObject
1135 * @param array $siteinfo
1136 * @param array $jsonld
1137 * @return array siteinfo
1139 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1143 $content = JsonLD::fetchElement($jsonld, 'caption');
1144 if (!empty($content)) {
1145 $media['caption'] = trim($content);
1148 $content = JsonLD::fetchElement($jsonld, 'url');
1149 if (!empty($content)) {
1150 $media['url'] = trim($content);
1153 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1154 if (!empty($content)) {
1155 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1158 $content = JsonLD::fetchElement($jsonld, 'description');
1159 if (!empty($content)) {
1160 $media['description'] = trim($content);
1163 $content = JsonLD::fetchElement($jsonld, 'name');
1164 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1165 $media['name'] = trim($content);
1168 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1169 if (!empty($content)) {
1170 $media['content'] = trim($content);
1173 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1174 if (!empty($content)) {
1175 $media['embed'] = trim($content);
1178 $content = JsonLD::fetchElement($jsonld, 'height');
1179 if (!empty($content)) {
1180 $media['height'] = trim($content);
1183 $content = JsonLD::fetchElement($jsonld, 'width');
1184 if (!empty($content)) {
1185 $media['width'] = trim($content);
1188 $content = JsonLD::fetchElement($jsonld, 'image');
1189 if (!empty($content)) {
1190 $media['image'] = trim($content);
1193 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1194 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1195 if (!empty($media['image'])) {
1196 $media['preview'] = trim($content);
1198 $media['image'] = trim($content);
1202 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1203 $siteinfo[$name][] = $media;