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);
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 $header = $curlResult->getHeader();
236 $body = $curlResult->getBody();
239 $oembed_data = OEmbed::fetchURL($url, false, false);
241 if (!empty($oembed_data->type)) {
242 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
243 $siteinfo['type'] = $oembed_data->type;
246 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
247 if ($siteinfo['type'] != 'photo') {
248 if (!empty($oembed_data->title)) {
249 $siteinfo['title'] = trim($oembed_data->title);
251 if (!empty($oembed_data->description)) {
252 $siteinfo['text'] = trim($oembed_data->description);
254 if (!empty($oembed_data->author_name)) {
255 $siteinfo['author_name'] = trim($oembed_data->author_name);
257 if (!empty($oembed_data->author_url)) {
258 $siteinfo['author_url'] = trim($oembed_data->author_url);
260 if (!empty($oembed_data->provider_name)) {
261 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
263 if (!empty($oembed_data->provider_url)) {
264 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
266 if (!empty($oembed_data->thumbnail_url)) {
267 $siteinfo['image'] = $oembed_data->thumbnail_url;
274 // Look for a charset, first in headers
275 // Expected form: Content-Type: text/html; charset=ISO-8859-4
276 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
277 $charset = trim(trim(trim(array_pop($matches)), ';,'));
280 // Then in body that gets precedence
282 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
283 // - <meta charset="utf-8">
284 // - <meta charset=utf-8>
285 // - <meta charSet="utf-8">
286 // We escape <style> and <script> tags since they can contain irrelevant charset information
287 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
288 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
289 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
290 $charset = trim(trim(trim(array_pop($matches)), ';,'));
294 $siteinfo['charset'] = $charset;
296 if ($charset && strtoupper($charset) != 'UTF-8') {
297 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
298 $charset = str_ireplace('latin-1', 'latin1', $charset);
300 Logger::info('detected charset', ['charset' => $charset]);
301 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
304 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
306 $doc = new DOMDocument();
307 @$doc->loadHTML($body);
309 XML::deleteNode($doc, 'style');
310 XML::deleteNode($doc, 'option');
311 XML::deleteNode($doc, 'h1');
312 XML::deleteNode($doc, 'h2');
313 XML::deleteNode($doc, 'h3');
314 XML::deleteNode($doc, 'h4');
315 XML::deleteNode($doc, 'h5');
316 XML::deleteNode($doc, 'h6');
317 XML::deleteNode($doc, 'ol');
318 XML::deleteNode($doc, 'ul');
320 $xpath = new DOMXPath($doc);
322 $list = $xpath->query('//meta[@content]');
323 foreach ($list as $node) {
325 if ($node->attributes->length) {
326 foreach ($node->attributes as $attribute) {
327 $meta_tag[$attribute->name] = $attribute->value;
331 if (@$meta_tag['http-equiv'] == 'refresh') {
332 $path = $meta_tag['content'];
333 $pathinfo = explode(';', $path);
335 foreach ($pathinfo as $value) {
336 if (substr(strtolower($value), 0, 4) == 'url=') {
337 $content = substr($value, 4);
340 if ($content != '') {
341 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
347 $list = $xpath->query('//title');
348 if ($list->length > 0) {
349 $siteinfo['title'] = trim($list->item(0)->nodeValue);
352 $twitter_card = false;
353 $twitter_image = false;
355 $list = $xpath->query('//meta[@name]');
356 foreach ($list as $node) {
358 if ($node->attributes->length) {
359 foreach ($node->attributes as $attribute) {
360 $meta_tag[$attribute->name] = $attribute->value;
364 if (empty($meta_tag['content'])) {
368 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
370 switch (strtolower($meta_tag['name'])) {
372 $siteinfo['title'] = trim($meta_tag['content']);
375 $siteinfo['text'] = trim($meta_tag['content']);
378 $siteinfo['image'] = $meta_tag['content'];
380 case 'twitter:image':
381 $siteinfo['image'] = $meta_tag['content'];
382 $twitter_image = true;
384 case 'twitter:image:src':
385 $siteinfo['image'] = $meta_tag['content'];
388 // Detect photo pages
389 if ($meta_tag['content'] == 'summary_large_image') {
390 $twitter_card = true;
393 case 'twitter:description':
394 $siteinfo['text'] = trim($meta_tag['content']);
396 case 'twitter:title':
397 $siteinfo['title'] = trim($meta_tag['content']);
400 $siteinfo['title'] = trim($meta_tag['content']);
402 case 'dc.description':
403 $siteinfo['text'] = trim($meta_tag['content']);
406 $siteinfo['publisher_name'] = trim($meta_tag['content']);
409 $keywords = explode(',', $meta_tag['content']);
411 case 'news_keywords':
412 $keywords = explode(',', $meta_tag['content']);
417 if (isset($keywords)) {
418 $siteinfo['keywords'] = [];
419 foreach ($keywords as $keyword) {
420 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
421 $siteinfo['keywords'][] = trim($keyword);
426 $list = $xpath->query('//meta[@property]');
427 foreach ($list as $node) {
429 if ($node->attributes->length) {
430 foreach ($node->attributes as $attribute) {
431 $meta_tag[$attribute->name] = $attribute->value;
435 if (!empty($meta_tag['content'])) {
436 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
438 switch (strtolower($meta_tag['property'])) {
440 $siteinfo['image'] = $meta_tag['content'];
443 $siteinfo['image'] = $meta_tag['content'];
445 case 'og:image:secure_url':
446 $siteinfo['image'] = $meta_tag['content'];
449 $siteinfo['title'] = trim($meta_tag['content']);
451 case 'og:description':
452 $siteinfo['text'] = trim($meta_tag['content']);
455 $siteinfo['publisher_name'] = trim($meta_tag['content']);
457 case 'twitter:description':
458 $siteinfo['text'] = trim($meta_tag['content']);
460 case 'twitter:title':
461 $siteinfo['title'] = trim($meta_tag['content']);
463 case 'twitter:image':
464 $siteinfo['image'] = $meta_tag['content'];
465 $twitter_image = true;
471 $list = $xpath->query("//script[@type='application/ld+json']");
472 foreach ($list as $node) {
473 if (!empty($node->nodeValue)) {
474 if ($jsonld = json_decode($node->nodeValue, true)) {
475 $siteinfo = self::parseParts($siteinfo, $jsonld);
480 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
481 // Prevent to have a photo type without an image
482 // if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
483 // $siteinfo['type'] = 'photo';
486 if (!empty($siteinfo['image'])) {
487 $siteinfo['images'] = $siteinfo['images'] ?? [];
488 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
489 unset($siteinfo['image']);
492 $siteinfo = self::checkMedia($url, $siteinfo);
494 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
495 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
496 $pos = mb_strrpos($siteinfo['text'], '.');
497 if ($pos > self::MIN_DESC_COUNT) {
498 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
502 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
504 Hook::callAll('getsiteinfo', $siteinfo);
510 * Check the attached media elements.
511 * Fix existing data and add missing data.
513 * @param string $page_url
514 * @param array $siteinfo
517 private static function checkMedia(string $page_url, array $siteinfo)
519 if (!empty($siteinfo['images'])) {
520 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
521 // According to the specifications someone could place a picture url into the content field as well.
522 // But this doesn't seem to happen in the wild, so we don't cover it here.
523 if (!empty($image['url'])) {
524 $image['url'] = self::completeUrl($image['url'], $page_url);
525 $photodata = Images::getInfoFromURLCached($image['url']);
526 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
527 $image['src'] = $image['url'];
528 $image['width'] = $photodata[0];
529 $image['height'] = $photodata[1];
530 $image['contenttype'] = $photodata['mime'];
531 unset($image['url']);
541 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
544 foreach (['audio', 'video'] as $element) {
545 if (!empty($siteinfo[$element])) {
546 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
551 foreach (['embed', 'content', 'url'] as $field) {
552 if (!empty($media[$field])) {
553 $media[$field] = self::completeUrl($media[$field], $page_url);
554 $type = self::getContentType($media[$field]);
555 if (($type[0] ?? '') == 'text') {
556 if ($field == 'embed') {
557 $embed = $media[$field];
559 $url = $media[$field];
561 } elseif (!empty($type[0])) {
562 $content = $media[$field];
563 $contenttype = implode('/', $type);
566 unset($media[$field]);
569 foreach (['image', 'preview'] as $field) {
570 if (!empty($media[$field])) {
571 $media[$field] = self::completeUrl($media[$field], $page_url);
576 $media['url'] = $url;
578 if (!empty($embed)) {
579 $media['embed'] = $embed;
580 if (!empty($media['main'])) {
581 $siteinfo['embed'] = $embed;
584 if (!empty($content)) {
585 $media['src'] = $content;
587 if (!empty($contenttype)) {
588 $media['contenttype'] = $contenttype;
590 if (empty($url) && empty($content) && empty($embed)) {
596 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
598 if (empty($siteinfo[$element])) {
599 unset($siteinfo[$element]);
606 * Convert tags from CSV to an array
608 * @param string $string Tags
609 * @return array with formatted Hashtags
611 public static function convertTagsToArray($string)
613 $arr_tags = str_getcsv($string);
614 if (count($arr_tags)) {
615 // add the # sign to every tag
616 array_walk($arr_tags, ["self", "arrAddHashes"]);
623 * Add a hasht sign to a string
625 * This method is used as callback function
627 * @param string $tag The pure tag name
628 * @param int $k Counter for internal use
631 private static function arrAddHashes(&$tag, $k)
637 * Add a scheme to an url
639 * The src attribute of some html elements (e.g. images)
640 * can miss the scheme so we need to add the correct
643 * @param string $url The url which possibly does have
644 * a missing scheme (a link to an image)
645 * @param string $scheme The url with a correct scheme
646 * (e.g. the url from the webpage which does contain the image)
648 * @return string The url with a scheme
650 private static function completeUrl($url, $scheme)
652 $urlarr = parse_url($url);
654 // If the url does allready have an scheme
655 // we can stop the process here
656 if (isset($urlarr["scheme"])) {
660 $schemearr = parse_url($scheme);
662 $complete = $schemearr["scheme"]."://".$schemearr["host"];
664 if (!empty($schemearr["port"])) {
665 $complete .= ":".$schemearr["port"];
668 if (!empty($urlarr["path"])) {
669 if (strpos($urlarr["path"], "/") !== 0) {
673 $complete .= $urlarr["path"];
676 if (!empty($urlarr["query"])) {
677 $complete .= "?".$urlarr["query"];
680 if (!empty($urlarr["fragment"])) {
681 $complete .= "#".$urlarr["fragment"];
688 * Parse the Json-Ld parts of a web page
690 * @param array $siteinfo
691 * @param array $jsonld
692 * @return array siteinfo
694 private static function parseParts(array $siteinfo, array $jsonld)
696 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
697 foreach ($jsonld['@graph'] as $part) {
698 if (!empty($part) && is_array($part)) {
699 $siteinfo = self::parseParts($siteinfo, $part);
702 } elseif (!empty($jsonld['@type'])) {
703 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
704 } elseif (!empty($jsonld)) {
705 $keys = array_keys($jsonld);
706 $numeric_keys = true;
707 foreach ($keys as $key) {
709 $numeric_keys = false;
713 foreach ($jsonld as $part) {
714 if (!empty($part) && is_array($part)) {
715 $siteinfo = self::parseParts($siteinfo, $part);
721 array_walk_recursive($siteinfo, function (&$element) {
722 if (is_string($element)) {
723 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
731 * Improve the siteinfo with information from the provided JSON-LD information
732 * @see https://jsonld.com/
733 * @see https://schema.org/
735 * @param array $siteinfo
736 * @param array $jsonld
737 * @return array siteinfo
739 private static function parseJsonLd(array $siteinfo, array $jsonld)
741 $type = JsonLD::fetchElement($jsonld, '@type');
743 Logger::info('Empty type', ['url' => $siteinfo['url']]);
747 // Silently ignore some types that aren't processed
748 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
749 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
750 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
756 case 'AdvertiserContentArticle':
759 case 'SatiricalArticle':
760 case 'ScholarlyArticle':
761 case 'SocialMediaPosting':
763 case 'ReportageNewsArticle':
764 case 'SocialMediaPosting':
766 case 'LiveBlogPosting':
767 case 'DiscussionForumPosting':
768 return self::parseJsonLdArticle($siteinfo, $jsonld);
772 case 'CollectionPage':
776 case 'MedicalWebPage':
779 case 'RealEstateListing':
780 case 'SearchResultsPage':
786 return self::parseJsonLdWebPage($siteinfo, $jsonld);
788 return self::parseJsonLdWebSite($siteinfo, $jsonld);
793 case 'EducationalOrganization':
794 case 'FundingScheme':
795 case 'GovernmentOrganization':
796 case 'LibrarySystem':
797 case 'LocalBusiness':
798 case 'MedicalOrganization':
800 case 'NewsMediaOrganization':
802 case 'SportsOrganization':
804 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
807 case 'PerformingGroup':
811 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
814 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
816 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
818 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
820 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
826 * Fetch author and publisher data
828 * @param array $siteinfo
829 * @param array $jsonld
830 * @return array siteinfo
832 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
836 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
837 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
838 if (!empty($content) && is_string($content)) {
839 $jsonldinfo['publisher_name'] = trim($content);
842 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
843 if (!empty($content) && is_string($content)) {
844 $jsonldinfo['publisher_url'] = trim($content);
847 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
848 if (!empty($brand) && is_array($brand)) {
849 $content = JsonLD::fetchElement($brand, 'name');
850 if (!empty($content) && is_string($content)) {
851 $jsonldinfo['publisher_name'] = trim($content);
854 $content = JsonLD::fetchElement($brand, 'url');
855 if (!empty($content) && is_string($content)) {
856 $jsonldinfo['publisher_url'] = trim($content);
859 $content = JsonLD::fetchElement($brand, 'logo', 'url');
860 if (!empty($content) && is_string($content)) {
861 $jsonldinfo['publisher_img'] = trim($content);
865 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
866 if (!empty($logo) && is_array($logo)) {
867 $content = JsonLD::fetchElement($logo, 'url');
868 if (!empty($content) && is_string($content)) {
869 $jsonldinfo['publisher_img'] = trim($content);
872 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
873 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
876 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
877 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
878 if (!empty($content) && is_string($content)) {
879 $jsonldinfo['author_name'] = trim($content);
882 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
883 if (!empty($content) && is_string($content)) {
884 $jsonldinfo['author_url'] = trim($content);
887 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
888 if (!empty($content) && is_string($content)) {
889 $jsonldinfo['author_url'] = trim($content);
892 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
893 if (!empty($logo) && is_array($logo)) {
894 $content = JsonLD::fetchElement($logo, 'url');
895 if (!empty($content) && is_string($content)) {
896 $jsonldinfo['author_img'] = trim($content);
899 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
900 $jsonldinfo['author_name'] = trim($jsonld['author']);
903 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
905 return array_merge($siteinfo, $jsonldinfo);
909 * Fetch data from the provided JSON-LD Article type
910 * @see https://schema.org/Article
912 * @param array $siteinfo
913 * @param array $jsonld
914 * @return array siteinfo
916 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
920 $content = JsonLD::fetchElement($jsonld, 'headline');
921 if (!empty($content) && is_string($content)) {
922 $jsonldinfo['title'] = trim($content);
925 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
926 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
927 $jsonldinfo['alternative_title'] = trim($content);
930 $content = JsonLD::fetchElement($jsonld, 'description');
931 if (!empty($content) && is_string($content)) {
932 $jsonldinfo['text'] = trim($content);
935 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
936 if (!empty($content)) {
937 $jsonldinfo['image'] = trim($content);
940 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
941 if (!empty($content) && is_string($content)) {
942 $jsonldinfo['image'] = trim($content);
945 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
946 $content = JsonLD::fetchElement($jsonld, 'keywords');
947 if (!empty($content)) {
948 $siteinfo['keywords'] = [];
949 $keywords = explode(',', $content);
950 foreach ($keywords as $keyword) {
951 $siteinfo['keywords'][] = trim($keyword);
954 } elseif (!empty($jsonld['keywords'])) {
955 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
956 if (!empty($content) && is_array($content)) {
957 $jsonldinfo['keywords'] = $content;
961 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
963 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
965 return array_merge($siteinfo, $jsonldinfo);
969 * Fetch data from the provided JSON-LD WebPage type
970 * @see https://schema.org/WebPage
972 * @param array $siteinfo
973 * @param array $jsonld
974 * @return array siteinfo
976 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
980 $content = JsonLD::fetchElement($jsonld, 'name');
981 if (!empty($content)) {
982 $jsonldinfo['title'] = trim($content);
985 $content = JsonLD::fetchElement($jsonld, 'description');
986 if (!empty($content)) {
987 $jsonldinfo['text'] = trim($content);
990 $content = JsonLD::fetchElement($jsonld, 'image');
991 if (!empty($content)) {
992 $jsonldinfo['image'] = trim($content);
995 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
996 if (!empty($content)) {
997 $jsonldinfo['image'] = trim($content);
1000 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1002 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1004 return array_merge($siteinfo, $jsonldinfo);
1008 * Fetch data from the provided JSON-LD WebSite type
1009 * @see https://schema.org/WebSite
1011 * @param array $siteinfo
1012 * @param array $jsonld
1013 * @return array siteinfo
1015 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1019 $content = JsonLD::fetchElement($jsonld, 'name');
1020 if (!empty($content)) {
1021 $jsonldinfo['publisher_name'] = trim($content);
1024 $content = JsonLD::fetchElement($jsonld, 'description');
1025 if (!empty($content)) {
1026 $jsonldinfo['publisher_description'] = trim($content);
1029 $content = JsonLD::fetchElement($jsonld, 'url');
1030 if (!empty($content)) {
1031 $jsonldinfo['publisher_url'] = trim($content);
1034 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1035 if (!empty($content)) {
1036 $jsonldinfo['image'] = trim($content);
1039 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1041 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1042 return array_merge($siteinfo, $jsonldinfo);
1046 * Fetch data from the provided JSON-LD Organization type
1047 * @see https://schema.org/Organization
1049 * @param array $siteinfo
1050 * @param array $jsonld
1051 * @return array siteinfo
1053 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1057 $content = JsonLD::fetchElement($jsonld, 'name');
1058 if (!empty($content)) {
1059 $jsonldinfo['publisher_name'] = trim($content);
1062 $content = JsonLD::fetchElement($jsonld, 'description');
1063 if (!empty($content)) {
1064 $jsonldinfo['publisher_description'] = trim($content);
1067 $content = JsonLD::fetchElement($jsonld, 'url');
1068 if (!empty($content)) {
1069 $jsonldinfo['publisher_url'] = trim($content);
1072 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1073 if (!empty($content)) {
1074 $jsonldinfo['publisher_img'] = trim($content);
1077 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1078 if (!empty($content)) {
1079 $jsonldinfo['publisher_name'] = trim($content);
1082 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1083 if (!empty($content)) {
1084 $jsonldinfo['publisher_url'] = trim($content);
1087 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1088 return array_merge($siteinfo, $jsonldinfo);
1092 * Fetch data from the provided JSON-LD Person type
1093 * @see https://schema.org/Person
1095 * @param array $siteinfo
1096 * @param array $jsonld
1097 * @return array siteinfo
1099 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1103 $content = JsonLD::fetchElement($jsonld, 'name');
1104 if (!empty($content)) {
1105 $jsonldinfo['author_name'] = trim($content);
1108 $content = JsonLD::fetchElement($jsonld, 'description');
1109 if (!empty($content)) {
1110 $jsonldinfo['author_description'] = trim($content);
1113 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1114 if (!empty($content) && is_string($content)) {
1115 $jsonldinfo['author_url'] = trim($content);
1118 $content = JsonLD::fetchElement($jsonld, 'url');
1119 if (!empty($content)) {
1120 $jsonldinfo['author_url'] = trim($content);
1123 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1124 if (!empty($content)) {
1125 $jsonldinfo['author_img'] = trim($content);
1128 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1129 return array_merge($siteinfo, $jsonldinfo);
1133 * Fetch data from the provided JSON-LD MediaObject type
1134 * @see https://schema.org/MediaObject
1136 * @param array $siteinfo
1137 * @param array $jsonld
1138 * @return array siteinfo
1140 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1144 $content = JsonLD::fetchElement($jsonld, 'caption');
1145 if (!empty($content)) {
1146 $media['caption'] = trim($content);
1149 $content = JsonLD::fetchElement($jsonld, 'url');
1150 if (!empty($content)) {
1151 $media['url'] = trim($content);
1154 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1155 if (!empty($content)) {
1156 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1159 $content = JsonLD::fetchElement($jsonld, 'description');
1160 if (!empty($content)) {
1161 $media['description'] = trim($content);
1164 $content = JsonLD::fetchElement($jsonld, 'name');
1165 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1166 $media['name'] = trim($content);
1169 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1170 if (!empty($content)) {
1171 $media['content'] = trim($content);
1174 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1175 if (!empty($content)) {
1176 $media['embed'] = trim($content);
1179 $content = JsonLD::fetchElement($jsonld, 'height');
1180 if (!empty($content)) {
1181 $media['height'] = trim($content);
1184 $content = JsonLD::fetchElement($jsonld, 'width');
1185 if (!empty($content)) {
1186 $media['width'] = trim($content);
1189 $content = JsonLD::fetchElement($jsonld, 'image');
1190 if (!empty($content)) {
1191 $media['image'] = trim($content);
1194 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1195 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1196 if (!empty($media['image'])) {
1197 $media['preview'] = trim($content);
1199 $media['image'] = trim($content);
1203 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1204 $siteinfo[$name][] = $media;