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 foreach ($curlResult->getContentType() as $type) {
276 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $type, $matches)) {
277 $charset = trim(trim(trim(array_pop($matches)), ';,'));
281 // Then in body that gets precedence
283 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
284 // - <meta charset="utf-8">
285 // - <meta charset=utf-8>
286 // - <meta charSet="utf-8">
287 // We escape <style> and <script> tags since they can contain irrelevant charset information
288 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
289 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
290 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
291 $charset = trim(trim(trim(array_pop($matches)), ';,'));
295 $siteinfo['charset'] = $charset;
297 if ($charset && strtoupper($charset) != 'UTF-8') {
298 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
299 $charset = str_ireplace('latin-1', 'latin1', $charset);
301 Logger::info('detected charset', ['charset' => $charset]);
302 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
305 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
307 $doc = new DOMDocument();
308 @$doc->loadHTML($body);
310 XML::deleteNode($doc, 'style');
311 XML::deleteNode($doc, 'option');
312 XML::deleteNode($doc, 'h1');
313 XML::deleteNode($doc, 'h2');
314 XML::deleteNode($doc, 'h3');
315 XML::deleteNode($doc, 'h4');
316 XML::deleteNode($doc, 'h5');
317 XML::deleteNode($doc, 'h6');
318 XML::deleteNode($doc, 'ol');
319 XML::deleteNode($doc, 'ul');
321 $xpath = new DOMXPath($doc);
323 $list = $xpath->query('//meta[@content]');
324 foreach ($list as $node) {
326 if ($node->attributes->length) {
327 foreach ($node->attributes as $attribute) {
328 $meta_tag[$attribute->name] = $attribute->value;
332 if (@$meta_tag['http-equiv'] == 'refresh') {
333 $path = $meta_tag['content'];
334 $pathinfo = explode(';', $path);
336 foreach ($pathinfo as $value) {
337 if (substr(strtolower($value), 0, 4) == 'url=') {
338 $content = substr($value, 4);
341 if ($content != '') {
342 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
348 $list = $xpath->query('//title');
349 if ($list->length > 0) {
350 $siteinfo['title'] = trim($list->item(0)->nodeValue);
353 $twitter_card = false;
354 $twitter_image = false;
356 $list = $xpath->query('//meta[@name]');
357 foreach ($list as $node) {
359 if ($node->attributes->length) {
360 foreach ($node->attributes as $attribute) {
361 $meta_tag[$attribute->name] = $attribute->value;
365 if (empty($meta_tag['content'])) {
369 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
371 switch (strtolower($meta_tag['name'])) {
373 $siteinfo['title'] = trim($meta_tag['content']);
376 $siteinfo['text'] = trim($meta_tag['content']);
379 $siteinfo['image'] = $meta_tag['content'];
381 case 'twitter:image':
382 $siteinfo['image'] = $meta_tag['content'];
383 $twitter_image = true;
385 case 'twitter:image:src':
386 $siteinfo['image'] = $meta_tag['content'];
389 // Detect photo pages
390 if ($meta_tag['content'] == 'summary_large_image') {
391 $twitter_card = true;
394 case 'twitter:description':
395 $siteinfo['text'] = trim($meta_tag['content']);
397 case 'twitter:title':
398 $siteinfo['title'] = trim($meta_tag['content']);
401 $siteinfo['title'] = trim($meta_tag['content']);
403 case 'dc.description':
404 $siteinfo['text'] = trim($meta_tag['content']);
407 $siteinfo['publisher_name'] = trim($meta_tag['content']);
410 $keywords = explode(',', $meta_tag['content']);
412 case 'news_keywords':
413 $keywords = explode(',', $meta_tag['content']);
418 if (isset($keywords)) {
419 $siteinfo['keywords'] = [];
420 foreach ($keywords as $keyword) {
421 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
422 $siteinfo['keywords'][] = trim($keyword);
427 $list = $xpath->query('//meta[@property]');
428 foreach ($list as $node) {
430 if ($node->attributes->length) {
431 foreach ($node->attributes as $attribute) {
432 $meta_tag[$attribute->name] = $attribute->value;
436 if (!empty($meta_tag['content'])) {
437 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
439 switch (strtolower($meta_tag['property'])) {
441 $siteinfo['image'] = $meta_tag['content'];
444 $siteinfo['image'] = $meta_tag['content'];
446 case 'og:image:secure_url':
447 $siteinfo['image'] = $meta_tag['content'];
450 $siteinfo['title'] = trim($meta_tag['content']);
452 case 'og:description':
453 $siteinfo['text'] = trim($meta_tag['content']);
456 $siteinfo['publisher_name'] = trim($meta_tag['content']);
458 case 'twitter:description':
459 $siteinfo['text'] = trim($meta_tag['content']);
461 case 'twitter:title':
462 $siteinfo['title'] = trim($meta_tag['content']);
464 case 'twitter:image':
465 $siteinfo['image'] = $meta_tag['content'];
466 $twitter_image = true;
472 $list = $xpath->query("//script[@type='application/ld+json']");
473 foreach ($list as $node) {
474 if (!empty($node->nodeValue)) {
475 if ($jsonld = json_decode($node->nodeValue, true)) {
476 $siteinfo = self::parseParts($siteinfo, $jsonld);
481 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
482 // Prevent to have a photo type without an image
483 // if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
484 // $siteinfo['type'] = 'photo';
487 if (!empty($siteinfo['image'])) {
488 $siteinfo['images'] = $siteinfo['images'] ?? [];
489 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
490 unset($siteinfo['image']);
493 $siteinfo = self::checkMedia($url, $siteinfo);
495 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
496 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
497 $pos = mb_strrpos($siteinfo['text'], '.');
498 if ($pos > self::MIN_DESC_COUNT) {
499 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
503 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
505 Hook::callAll('getsiteinfo', $siteinfo);
511 * Check the attached media elements.
512 * Fix existing data and add missing data.
514 * @param string $page_url
515 * @param array $siteinfo
518 private static function checkMedia(string $page_url, array $siteinfo)
520 if (!empty($siteinfo['images'])) {
521 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
522 // According to the specifications someone could place a picture url into the content field as well.
523 // But this doesn't seem to happen in the wild, so we don't cover it here.
524 if (!empty($image['url'])) {
525 $image['url'] = self::completeUrl($image['url'], $page_url);
526 $photodata = Images::getInfoFromURLCached($image['url']);
527 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
528 $image['src'] = $image['url'];
529 $image['width'] = $photodata[0];
530 $image['height'] = $photodata[1];
531 $image['contenttype'] = $photodata['mime'];
532 unset($image['url']);
542 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
545 foreach (['audio', 'video'] as $element) {
546 if (!empty($siteinfo[$element])) {
547 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
552 foreach (['embed', 'content', 'url'] as $field) {
553 if (!empty($media[$field])) {
554 $media[$field] = self::completeUrl($media[$field], $page_url);
555 $type = self::getContentType($media[$field]);
556 if (($type[0] ?? '') == 'text') {
557 if ($field == 'embed') {
558 $embed = $media[$field];
560 $url = $media[$field];
562 } elseif (!empty($type[0])) {
563 $content = $media[$field];
564 $contenttype = implode('/', $type);
567 unset($media[$field]);
570 foreach (['image', 'preview'] as $field) {
571 if (!empty($media[$field])) {
572 $media[$field] = self::completeUrl($media[$field], $page_url);
577 $media['url'] = $url;
579 if (!empty($embed)) {
580 $media['embed'] = $embed;
581 if (!empty($media['main'])) {
582 $siteinfo['embed'] = $embed;
585 if (!empty($content)) {
586 $media['src'] = $content;
588 if (!empty($contenttype)) {
589 $media['contenttype'] = $contenttype;
591 if (empty($url) && empty($content) && empty($embed)) {
597 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
599 if (empty($siteinfo[$element])) {
600 unset($siteinfo[$element]);
607 * Convert tags from CSV to an array
609 * @param string $string Tags
610 * @return array with formatted Hashtags
612 public static function convertTagsToArray($string)
614 $arr_tags = str_getcsv($string);
615 if (count($arr_tags)) {
616 // add the # sign to every tag
617 array_walk($arr_tags, ["self", "arrAddHashes"]);
624 * Add a hasht sign to a string
626 * This method is used as callback function
628 * @param string $tag The pure tag name
629 * @param int $k Counter for internal use
632 private static function arrAddHashes(&$tag, $k)
638 * Add a scheme to an url
640 * The src attribute of some html elements (e.g. images)
641 * can miss the scheme so we need to add the correct
644 * @param string $url The url which possibly does have
645 * a missing scheme (a link to an image)
646 * @param string $scheme The url with a correct scheme
647 * (e.g. the url from the webpage which does contain the image)
649 * @return string The url with a scheme
651 private static function completeUrl($url, $scheme)
653 $urlarr = parse_url($url);
655 // If the url does allready have an scheme
656 // we can stop the process here
657 if (isset($urlarr["scheme"])) {
661 $schemearr = parse_url($scheme);
663 $complete = $schemearr["scheme"]."://".$schemearr["host"];
665 if (!empty($schemearr["port"])) {
666 $complete .= ":".$schemearr["port"];
669 if (!empty($urlarr["path"])) {
670 if (strpos($urlarr["path"], "/") !== 0) {
674 $complete .= $urlarr["path"];
677 if (!empty($urlarr["query"])) {
678 $complete .= "?".$urlarr["query"];
681 if (!empty($urlarr["fragment"])) {
682 $complete .= "#".$urlarr["fragment"];
689 * Parse the Json-Ld parts of a web page
691 * @param array $siteinfo
692 * @param array $jsonld
693 * @return array siteinfo
695 private static function parseParts(array $siteinfo, array $jsonld)
697 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
698 foreach ($jsonld['@graph'] as $part) {
699 if (!empty($part) && is_array($part)) {
700 $siteinfo = self::parseParts($siteinfo, $part);
703 } elseif (!empty($jsonld['@type'])) {
704 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
705 } elseif (!empty($jsonld)) {
706 $keys = array_keys($jsonld);
707 $numeric_keys = true;
708 foreach ($keys as $key) {
710 $numeric_keys = false;
714 foreach ($jsonld as $part) {
715 if (!empty($part) && is_array($part)) {
716 $siteinfo = self::parseParts($siteinfo, $part);
722 array_walk_recursive($siteinfo, function (&$element) {
723 if (is_string($element)) {
724 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
732 * Improve the siteinfo with information from the provided JSON-LD information
733 * @see https://jsonld.com/
734 * @see https://schema.org/
736 * @param array $siteinfo
737 * @param array $jsonld
738 * @return array siteinfo
740 private static function parseJsonLd(array $siteinfo, array $jsonld)
742 $type = JsonLD::fetchElement($jsonld, '@type');
744 Logger::info('Empty type', ['url' => $siteinfo['url']]);
748 // Silently ignore some types that aren't processed
749 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
750 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
751 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
757 case 'AdvertiserContentArticle':
760 case 'SatiricalArticle':
761 case 'ScholarlyArticle':
762 case 'SocialMediaPosting':
764 case 'ReportageNewsArticle':
765 case 'SocialMediaPosting':
767 case 'LiveBlogPosting':
768 case 'DiscussionForumPosting':
769 return self::parseJsonLdArticle($siteinfo, $jsonld);
773 case 'CollectionPage':
777 case 'MedicalWebPage':
780 case 'RealEstateListing':
781 case 'SearchResultsPage':
787 return self::parseJsonLdWebPage($siteinfo, $jsonld);
789 return self::parseJsonLdWebSite($siteinfo, $jsonld);
794 case 'EducationalOrganization':
795 case 'FundingScheme':
796 case 'GovernmentOrganization':
797 case 'LibrarySystem':
798 case 'LocalBusiness':
799 case 'MedicalOrganization':
801 case 'NewsMediaOrganization':
803 case 'SportsOrganization':
805 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
808 case 'PerformingGroup':
812 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
815 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
817 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
819 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
821 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
827 * Fetch author and publisher data
829 * @param array $siteinfo
830 * @param array $jsonld
831 * @return array siteinfo
833 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
837 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
838 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
839 if (!empty($content) && is_string($content)) {
840 $jsonldinfo['publisher_name'] = trim($content);
843 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
844 if (!empty($content) && is_string($content)) {
845 $jsonldinfo['publisher_url'] = trim($content);
848 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
849 if (!empty($brand) && is_array($brand)) {
850 $content = JsonLD::fetchElement($brand, 'name');
851 if (!empty($content) && is_string($content)) {
852 $jsonldinfo['publisher_name'] = trim($content);
855 $content = JsonLD::fetchElement($brand, 'url');
856 if (!empty($content) && is_string($content)) {
857 $jsonldinfo['publisher_url'] = trim($content);
860 $content = JsonLD::fetchElement($brand, 'logo', 'url');
861 if (!empty($content) && is_string($content)) {
862 $jsonldinfo['publisher_img'] = trim($content);
866 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
867 if (!empty($logo) && is_array($logo)) {
868 $content = JsonLD::fetchElement($logo, 'url');
869 if (!empty($content) && is_string($content)) {
870 $jsonldinfo['publisher_img'] = trim($content);
873 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
874 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
877 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
878 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
879 if (!empty($content) && is_string($content)) {
880 $jsonldinfo['author_name'] = trim($content);
883 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
884 if (!empty($content) && is_string($content)) {
885 $jsonldinfo['author_url'] = trim($content);
888 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
889 if (!empty($content) && is_string($content)) {
890 $jsonldinfo['author_url'] = trim($content);
893 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
894 if (!empty($logo) && is_array($logo)) {
895 $content = JsonLD::fetchElement($logo, 'url');
896 if (!empty($content) && is_string($content)) {
897 $jsonldinfo['author_img'] = trim($content);
900 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
901 $jsonldinfo['author_name'] = trim($jsonld['author']);
904 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
906 return array_merge($siteinfo, $jsonldinfo);
910 * Fetch data from the provided JSON-LD Article type
911 * @see https://schema.org/Article
913 * @param array $siteinfo
914 * @param array $jsonld
915 * @return array siteinfo
917 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
921 $content = JsonLD::fetchElement($jsonld, 'headline');
922 if (!empty($content) && is_string($content)) {
923 $jsonldinfo['title'] = trim($content);
926 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
927 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
928 $jsonldinfo['alternative_title'] = trim($content);
931 $content = JsonLD::fetchElement($jsonld, 'description');
932 if (!empty($content) && is_string($content)) {
933 $jsonldinfo['text'] = trim($content);
936 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
937 if (!empty($content)) {
938 $jsonldinfo['image'] = trim($content);
941 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
942 if (!empty($content) && is_string($content)) {
943 $jsonldinfo['image'] = trim($content);
946 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
947 $content = JsonLD::fetchElement($jsonld, 'keywords');
948 if (!empty($content)) {
949 $siteinfo['keywords'] = [];
950 $keywords = explode(',', $content);
951 foreach ($keywords as $keyword) {
952 $siteinfo['keywords'][] = trim($keyword);
955 } elseif (!empty($jsonld['keywords'])) {
956 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
957 if (!empty($content) && is_array($content)) {
958 $jsonldinfo['keywords'] = $content;
962 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
964 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
966 return array_merge($siteinfo, $jsonldinfo);
970 * Fetch data from the provided JSON-LD WebPage type
971 * @see https://schema.org/WebPage
973 * @param array $siteinfo
974 * @param array $jsonld
975 * @return array siteinfo
977 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
981 $content = JsonLD::fetchElement($jsonld, 'name');
982 if (!empty($content)) {
983 $jsonldinfo['title'] = trim($content);
986 $content = JsonLD::fetchElement($jsonld, 'description');
987 if (!empty($content)) {
988 $jsonldinfo['text'] = trim($content);
991 $content = JsonLD::fetchElement($jsonld, 'image');
992 if (!empty($content)) {
993 $jsonldinfo['image'] = trim($content);
996 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
997 if (!empty($content)) {
998 $jsonldinfo['image'] = trim($content);
1001 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1003 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1005 return array_merge($siteinfo, $jsonldinfo);
1009 * Fetch data from the provided JSON-LD WebSite type
1010 * @see https://schema.org/WebSite
1012 * @param array $siteinfo
1013 * @param array $jsonld
1014 * @return array siteinfo
1016 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1020 $content = JsonLD::fetchElement($jsonld, 'name');
1021 if (!empty($content)) {
1022 $jsonldinfo['publisher_name'] = trim($content);
1025 $content = JsonLD::fetchElement($jsonld, 'description');
1026 if (!empty($content)) {
1027 $jsonldinfo['publisher_description'] = trim($content);
1030 $content = JsonLD::fetchElement($jsonld, 'url');
1031 if (!empty($content)) {
1032 $jsonldinfo['publisher_url'] = trim($content);
1035 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1036 if (!empty($content)) {
1037 $jsonldinfo['image'] = trim($content);
1040 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1042 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1043 return array_merge($siteinfo, $jsonldinfo);
1047 * Fetch data from the provided JSON-LD Organization type
1048 * @see https://schema.org/Organization
1050 * @param array $siteinfo
1051 * @param array $jsonld
1052 * @return array siteinfo
1054 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1058 $content = JsonLD::fetchElement($jsonld, 'name');
1059 if (!empty($content)) {
1060 $jsonldinfo['publisher_name'] = trim($content);
1063 $content = JsonLD::fetchElement($jsonld, 'description');
1064 if (!empty($content)) {
1065 $jsonldinfo['publisher_description'] = trim($content);
1068 $content = JsonLD::fetchElement($jsonld, 'url');
1069 if (!empty($content)) {
1070 $jsonldinfo['publisher_url'] = trim($content);
1073 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1074 if (!empty($content)) {
1075 $jsonldinfo['publisher_img'] = trim($content);
1078 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1079 if (!empty($content)) {
1080 $jsonldinfo['publisher_name'] = trim($content);
1083 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1084 if (!empty($content)) {
1085 $jsonldinfo['publisher_url'] = trim($content);
1088 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1089 return array_merge($siteinfo, $jsonldinfo);
1093 * Fetch data from the provided JSON-LD Person type
1094 * @see https://schema.org/Person
1096 * @param array $siteinfo
1097 * @param array $jsonld
1098 * @return array siteinfo
1100 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1104 $content = JsonLD::fetchElement($jsonld, 'name');
1105 if (!empty($content)) {
1106 $jsonldinfo['author_name'] = trim($content);
1109 $content = JsonLD::fetchElement($jsonld, 'description');
1110 if (!empty($content)) {
1111 $jsonldinfo['author_description'] = trim($content);
1114 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1115 if (!empty($content) && is_string($content)) {
1116 $jsonldinfo['author_url'] = trim($content);
1119 $content = JsonLD::fetchElement($jsonld, 'url');
1120 if (!empty($content)) {
1121 $jsonldinfo['author_url'] = trim($content);
1124 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1125 if (!empty($content)) {
1126 $jsonldinfo['author_img'] = trim($content);
1129 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1130 return array_merge($siteinfo, $jsonldinfo);
1134 * Fetch data from the provided JSON-LD MediaObject type
1135 * @see https://schema.org/MediaObject
1137 * @param array $siteinfo
1138 * @param array $jsonld
1139 * @return array siteinfo
1141 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1145 $content = JsonLD::fetchElement($jsonld, 'caption');
1146 if (!empty($content)) {
1147 $media['caption'] = trim($content);
1150 $content = JsonLD::fetchElement($jsonld, 'url');
1151 if (!empty($content)) {
1152 $media['url'] = trim($content);
1155 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1156 if (!empty($content)) {
1157 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1160 $content = JsonLD::fetchElement($jsonld, 'description');
1161 if (!empty($content)) {
1162 $media['description'] = trim($content);
1165 $content = JsonLD::fetchElement($jsonld, 'name');
1166 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1167 $media['name'] = trim($content);
1170 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1171 if (!empty($content)) {
1172 $media['content'] = trim($content);
1175 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1176 if (!empty($content)) {
1177 $media['embed'] = trim($content);
1180 $content = JsonLD::fetchElement($jsonld, 'height');
1181 if (!empty($content)) {
1182 $media['height'] = trim($content);
1185 $content = JsonLD::fetchElement($jsonld, 'width');
1186 if (!empty($content)) {
1187 $media['width'] = trim($content);
1190 $content = JsonLD::fetchElement($jsonld, 'image');
1191 if (!empty($content)) {
1192 $media['image'] = trim($content);
1195 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1196 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1197 if (!empty($media['image'])) {
1198 $media['preview'] = trim($content);
1200 $media['image'] = trim($content);
1204 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1205 $siteinfo[$name][] = $media;