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')[0] ?? '';
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, ['content_length' => 1000000]);
217 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
221 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
223 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
224 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
225 $maxAge = max(86400, (int)array_pop($matches));
226 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
230 $body = $curlResult->getBody();
233 $oembed_data = OEmbed::fetchURL($url, false, false);
235 if (!empty($oembed_data->type)) {
236 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
237 $siteinfo['type'] = $oembed_data->type;
240 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
241 if ($siteinfo['type'] != 'photo') {
242 if (!empty($oembed_data->title)) {
243 $siteinfo['title'] = trim($oembed_data->title);
245 if (!empty($oembed_data->description)) {
246 $siteinfo['text'] = trim($oembed_data->description);
248 if (!empty($oembed_data->author_name)) {
249 $siteinfo['author_name'] = trim($oembed_data->author_name);
251 if (!empty($oembed_data->author_url)) {
252 $siteinfo['author_url'] = trim($oembed_data->author_url);
254 if (!empty($oembed_data->provider_name)) {
255 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
257 if (!empty($oembed_data->provider_url)) {
258 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
260 if (!empty($oembed_data->thumbnail_url)) {
261 $siteinfo['image'] = $oembed_data->thumbnail_url;
268 // Look for a charset, first in headers
269 // Expected form: Content-Type: text/html; charset=ISO-8859-4
270 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
271 $charset = trim(trim(trim(array_pop($matches)), ';,'));
274 // Then in body that gets precedence
276 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
277 // - <meta charset="utf-8">
278 // - <meta charset=utf-8>
279 // - <meta charSet="utf-8">
280 // We escape <style> and <script> tags since they can contain irrelevant charset information
281 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
282 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
283 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
284 $charset = trim(trim(trim(array_pop($matches)), ';,'));
288 $siteinfo['charset'] = $charset;
290 if ($charset && strtoupper($charset) != 'UTF-8') {
291 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
292 $charset = str_ireplace('latin-1', 'latin1', $charset);
294 Logger::info('detected charset', ['charset' => $charset]);
295 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
298 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
300 $doc = new DOMDocument();
301 @$doc->loadHTML($body);
303 XML::deleteNode($doc, 'style');
304 XML::deleteNode($doc, 'option');
305 XML::deleteNode($doc, 'h1');
306 XML::deleteNode($doc, 'h2');
307 XML::deleteNode($doc, 'h3');
308 XML::deleteNode($doc, 'h4');
309 XML::deleteNode($doc, 'h5');
310 XML::deleteNode($doc, 'h6');
311 XML::deleteNode($doc, 'ol');
312 XML::deleteNode($doc, 'ul');
314 $xpath = new DOMXPath($doc);
316 $list = $xpath->query('//meta[@content]');
317 foreach ($list as $node) {
319 if ($node->attributes->length) {
320 foreach ($node->attributes as $attribute) {
321 $meta_tag[$attribute->name] = $attribute->value;
325 if (@$meta_tag['http-equiv'] == 'refresh') {
326 $path = $meta_tag['content'];
327 $pathinfo = explode(';', $path);
329 foreach ($pathinfo as $value) {
330 if (substr(strtolower($value), 0, 4) == 'url=') {
331 $content = substr($value, 4);
334 if ($content != '') {
335 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
341 $list = $xpath->query('//title');
342 if ($list->length > 0) {
343 $siteinfo['title'] = trim($list->item(0)->nodeValue);
346 $twitter_card = false;
347 $twitter_image = false;
349 $list = $xpath->query('//meta[@name]');
350 foreach ($list as $node) {
352 if ($node->attributes->length) {
353 foreach ($node->attributes as $attribute) {
354 $meta_tag[$attribute->name] = $attribute->value;
358 if (empty($meta_tag['content'])) {
362 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
364 switch (strtolower($meta_tag['name'])) {
366 $siteinfo['title'] = trim($meta_tag['content']);
369 $siteinfo['text'] = trim($meta_tag['content']);
372 $siteinfo['image'] = $meta_tag['content'];
374 case 'twitter:image':
375 $siteinfo['image'] = $meta_tag['content'];
376 $twitter_image = true;
378 case 'twitter:image:src':
379 $siteinfo['image'] = $meta_tag['content'];
382 // Detect photo pages
383 if ($meta_tag['content'] == 'summary_large_image') {
384 $twitter_card = true;
387 case 'twitter:description':
388 $siteinfo['text'] = trim($meta_tag['content']);
390 case 'twitter:title':
391 $siteinfo['title'] = trim($meta_tag['content']);
394 $siteinfo['title'] = trim($meta_tag['content']);
396 case 'dc.description':
397 $siteinfo['text'] = trim($meta_tag['content']);
400 $siteinfo['publisher_name'] = trim($meta_tag['content']);
403 $keywords = explode(',', $meta_tag['content']);
405 case 'news_keywords':
406 $keywords = explode(',', $meta_tag['content']);
411 if (isset($keywords)) {
412 $siteinfo['keywords'] = [];
413 foreach ($keywords as $keyword) {
414 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
415 $siteinfo['keywords'][] = trim($keyword);
420 $list = $xpath->query('//meta[@property]');
421 foreach ($list as $node) {
423 if ($node->attributes->length) {
424 foreach ($node->attributes as $attribute) {
425 $meta_tag[$attribute->name] = $attribute->value;
429 if (!empty($meta_tag['content'])) {
430 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
432 switch (strtolower($meta_tag['property'])) {
434 $siteinfo['image'] = $meta_tag['content'];
437 $siteinfo['image'] = $meta_tag['content'];
439 case 'og:image:secure_url':
440 $siteinfo['image'] = $meta_tag['content'];
443 $siteinfo['title'] = trim($meta_tag['content']);
445 case 'og:description':
446 $siteinfo['text'] = trim($meta_tag['content']);
449 $siteinfo['publisher_name'] = trim($meta_tag['content']);
451 case 'twitter:description':
452 $siteinfo['text'] = trim($meta_tag['content']);
454 case 'twitter:title':
455 $siteinfo['title'] = trim($meta_tag['content']);
457 case 'twitter:image':
458 $siteinfo['image'] = $meta_tag['content'];
459 $twitter_image = true;
465 $list = $xpath->query("//script[@type='application/ld+json']");
466 foreach ($list as $node) {
467 if (!empty($node->nodeValue)) {
468 if ($jsonld = json_decode($node->nodeValue, true)) {
469 $siteinfo = self::parseParts($siteinfo, $jsonld);
474 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
475 // Prevent to have a photo type without an image
476 // if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
477 // $siteinfo['type'] = 'photo';
480 if (!empty($siteinfo['image'])) {
481 $siteinfo['images'] = $siteinfo['images'] ?? [];
482 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
483 unset($siteinfo['image']);
486 $siteinfo = self::checkMedia($url, $siteinfo);
488 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
489 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
490 $pos = mb_strrpos($siteinfo['text'], '.');
491 if ($pos > self::MIN_DESC_COUNT) {
492 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
496 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
498 Hook::callAll('getsiteinfo', $siteinfo);
504 * Check the attached media elements.
505 * Fix existing data and add missing data.
507 * @param string $page_url
508 * @param array $siteinfo
511 private static function checkMedia(string $page_url, array $siteinfo)
513 if (!empty($siteinfo['images'])) {
514 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
515 // According to the specifications someone could place a picture url into the content field as well.
516 // But this doesn't seem to happen in the wild, so we don't cover it here.
517 if (!empty($image['url'])) {
518 $image['url'] = self::completeUrl($image['url'], $page_url);
519 $photodata = Images::getInfoFromURLCached($image['url']);
520 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
521 $image['src'] = $image['url'];
522 $image['width'] = $photodata[0];
523 $image['height'] = $photodata[1];
524 $image['contenttype'] = $photodata['mime'];
525 unset($image['url']);
535 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
538 foreach (['audio', 'video'] as $element) {
539 if (!empty($siteinfo[$element])) {
540 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
545 foreach (['embed', 'content', 'url'] as $field) {
546 if (!empty($media[$field])) {
547 $media[$field] = self::completeUrl($media[$field], $page_url);
548 $type = self::getContentType($media[$field]);
549 if (($type[0] ?? '') == 'text') {
550 if ($field == 'embed') {
551 $embed = $media[$field];
553 $url = $media[$field];
555 } elseif (!empty($type[0])) {
556 $content = $media[$field];
557 $contenttype = implode('/', $type);
560 unset($media[$field]);
563 foreach (['image', 'preview'] as $field) {
564 if (!empty($media[$field])) {
565 $media[$field] = self::completeUrl($media[$field], $page_url);
570 $media['url'] = $url;
572 if (!empty($embed)) {
573 $media['embed'] = $embed;
574 if (!empty($media['main'])) {
575 $siteinfo['embed'] = $embed;
578 if (!empty($content)) {
579 $media['src'] = $content;
581 if (!empty($contenttype)) {
582 $media['contenttype'] = $contenttype;
584 if (empty($url) && empty($content) && empty($embed)) {
590 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
592 if (empty($siteinfo[$element])) {
593 unset($siteinfo[$element]);
600 * Convert tags from CSV to an array
602 * @param string $string Tags
603 * @return array with formatted Hashtags
605 public static function convertTagsToArray($string)
607 $arr_tags = str_getcsv($string);
608 if (count($arr_tags)) {
609 // add the # sign to every tag
610 array_walk($arr_tags, ["self", "arrAddHashes"]);
617 * Add a hasht sign to a string
619 * This method is used as callback function
621 * @param string $tag The pure tag name
622 * @param int $k Counter for internal use
625 private static function arrAddHashes(&$tag, $k)
631 * Add a scheme to an url
633 * The src attribute of some html elements (e.g. images)
634 * can miss the scheme so we need to add the correct
637 * @param string $url The url which possibly does have
638 * a missing scheme (a link to an image)
639 * @param string $scheme The url with a correct scheme
640 * (e.g. the url from the webpage which does contain the image)
642 * @return string The url with a scheme
644 private static function completeUrl($url, $scheme)
646 $urlarr = parse_url($url);
648 // If the url does allready have an scheme
649 // we can stop the process here
650 if (isset($urlarr["scheme"])) {
654 $schemearr = parse_url($scheme);
656 $complete = $schemearr["scheme"]."://".$schemearr["host"];
658 if (!empty($schemearr["port"])) {
659 $complete .= ":".$schemearr["port"];
662 if (!empty($urlarr["path"])) {
663 if (strpos($urlarr["path"], "/") !== 0) {
667 $complete .= $urlarr["path"];
670 if (!empty($urlarr["query"])) {
671 $complete .= "?".$urlarr["query"];
674 if (!empty($urlarr["fragment"])) {
675 $complete .= "#".$urlarr["fragment"];
682 * Parse the Json-Ld parts of a web page
684 * @param array $siteinfo
685 * @param array $jsonld
686 * @return array siteinfo
688 private static function parseParts(array $siteinfo, array $jsonld)
690 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
691 foreach ($jsonld['@graph'] as $part) {
692 if (!empty($part) && is_array($part)) {
693 $siteinfo = self::parseParts($siteinfo, $part);
696 } elseif (!empty($jsonld['@type'])) {
697 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
698 } elseif (!empty($jsonld)) {
699 $keys = array_keys($jsonld);
700 $numeric_keys = true;
701 foreach ($keys as $key) {
703 $numeric_keys = false;
707 foreach ($jsonld as $part) {
708 if (!empty($part) && is_array($part)) {
709 $siteinfo = self::parseParts($siteinfo, $part);
715 array_walk_recursive($siteinfo, function (&$element) {
716 if (is_string($element)) {
717 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
725 * Improve the siteinfo with information from the provided JSON-LD information
726 * @see https://jsonld.com/
727 * @see https://schema.org/
729 * @param array $siteinfo
730 * @param array $jsonld
731 * @return array siteinfo
733 private static function parseJsonLd(array $siteinfo, array $jsonld)
735 $type = JsonLD::fetchElement($jsonld, '@type');
737 Logger::info('Empty type', ['url' => $siteinfo['url']]);
741 // Silently ignore some types that aren't processed
742 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
743 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
744 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
750 case 'AdvertiserContentArticle':
753 case 'SatiricalArticle':
754 case 'ScholarlyArticle':
755 case 'SocialMediaPosting':
757 case 'ReportageNewsArticle':
758 case 'SocialMediaPosting':
760 case 'LiveBlogPosting':
761 case 'DiscussionForumPosting':
762 return self::parseJsonLdArticle($siteinfo, $jsonld);
766 case 'CollectionPage':
770 case 'MedicalWebPage':
773 case 'RealEstateListing':
774 case 'SearchResultsPage':
780 return self::parseJsonLdWebPage($siteinfo, $jsonld);
782 return self::parseJsonLdWebSite($siteinfo, $jsonld);
787 case 'EducationalOrganization':
788 case 'FundingScheme':
789 case 'GovernmentOrganization':
790 case 'LibrarySystem':
791 case 'LocalBusiness':
792 case 'MedicalOrganization':
794 case 'NewsMediaOrganization':
796 case 'SportsOrganization':
798 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
801 case 'PerformingGroup':
805 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
808 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
810 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
812 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
814 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
820 * Fetch author and publisher data
822 * @param array $siteinfo
823 * @param array $jsonld
824 * @return array siteinfo
826 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
830 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
831 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
832 if (!empty($content) && is_string($content)) {
833 $jsonldinfo['publisher_name'] = trim($content);
836 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
837 if (!empty($content) && is_string($content)) {
838 $jsonldinfo['publisher_url'] = trim($content);
841 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
842 if (!empty($brand) && is_array($brand)) {
843 $content = JsonLD::fetchElement($brand, 'name');
844 if (!empty($content) && is_string($content)) {
845 $jsonldinfo['publisher_name'] = trim($content);
848 $content = JsonLD::fetchElement($brand, 'url');
849 if (!empty($content) && is_string($content)) {
850 $jsonldinfo['publisher_url'] = trim($content);
853 $content = JsonLD::fetchElement($brand, 'logo', 'url');
854 if (!empty($content) && is_string($content)) {
855 $jsonldinfo['publisher_img'] = trim($content);
859 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
860 if (!empty($logo) && is_array($logo)) {
861 $content = JsonLD::fetchElement($logo, 'url');
862 if (!empty($content) && is_string($content)) {
863 $jsonldinfo['publisher_img'] = trim($content);
866 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
867 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
870 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
871 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
872 if (!empty($content) && is_string($content)) {
873 $jsonldinfo['author_name'] = trim($content);
876 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
877 if (!empty($content) && is_string($content)) {
878 $jsonldinfo['author_url'] = trim($content);
881 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
882 if (!empty($content) && is_string($content)) {
883 $jsonldinfo['author_url'] = trim($content);
886 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
887 if (!empty($logo) && is_array($logo)) {
888 $content = JsonLD::fetchElement($logo, 'url');
889 if (!empty($content) && is_string($content)) {
890 $jsonldinfo['author_img'] = trim($content);
893 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
894 $jsonldinfo['author_name'] = trim($jsonld['author']);
897 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
899 return array_merge($siteinfo, $jsonldinfo);
903 * Fetch data from the provided JSON-LD Article type
904 * @see https://schema.org/Article
906 * @param array $siteinfo
907 * @param array $jsonld
908 * @return array siteinfo
910 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
914 $content = JsonLD::fetchElement($jsonld, 'headline');
915 if (!empty($content) && is_string($content)) {
916 $jsonldinfo['title'] = trim($content);
919 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
920 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
921 $jsonldinfo['alternative_title'] = trim($content);
924 $content = JsonLD::fetchElement($jsonld, 'description');
925 if (!empty($content) && is_string($content)) {
926 $jsonldinfo['text'] = trim($content);
929 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
930 if (!empty($content)) {
931 $jsonldinfo['image'] = trim($content);
934 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
935 if (!empty($content) && is_string($content)) {
936 $jsonldinfo['image'] = trim($content);
939 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
940 $content = JsonLD::fetchElement($jsonld, 'keywords');
941 if (!empty($content)) {
942 $siteinfo['keywords'] = [];
943 $keywords = explode(',', $content);
944 foreach ($keywords as $keyword) {
945 $siteinfo['keywords'][] = trim($keyword);
948 } elseif (!empty($jsonld['keywords'])) {
949 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
950 if (!empty($content) && is_array($content)) {
951 $jsonldinfo['keywords'] = $content;
955 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
957 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
959 return array_merge($siteinfo, $jsonldinfo);
963 * Fetch data from the provided JSON-LD WebPage type
964 * @see https://schema.org/WebPage
966 * @param array $siteinfo
967 * @param array $jsonld
968 * @return array siteinfo
970 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
974 $content = JsonLD::fetchElement($jsonld, 'name');
975 if (!empty($content)) {
976 $jsonldinfo['title'] = trim($content);
979 $content = JsonLD::fetchElement($jsonld, 'description');
980 if (!empty($content)) {
981 $jsonldinfo['text'] = trim($content);
984 $content = JsonLD::fetchElement($jsonld, 'image');
985 if (!empty($content)) {
986 $jsonldinfo['image'] = trim($content);
989 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
990 if (!empty($content)) {
991 $jsonldinfo['image'] = trim($content);
994 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
996 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
998 return array_merge($siteinfo, $jsonldinfo);
1002 * Fetch data from the provided JSON-LD WebSite type
1003 * @see https://schema.org/WebSite
1005 * @param array $siteinfo
1006 * @param array $jsonld
1007 * @return array siteinfo
1009 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1013 $content = JsonLD::fetchElement($jsonld, 'name');
1014 if (!empty($content)) {
1015 $jsonldinfo['publisher_name'] = trim($content);
1018 $content = JsonLD::fetchElement($jsonld, 'description');
1019 if (!empty($content)) {
1020 $jsonldinfo['publisher_description'] = trim($content);
1023 $content = JsonLD::fetchElement($jsonld, 'url');
1024 if (!empty($content)) {
1025 $jsonldinfo['publisher_url'] = trim($content);
1028 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1029 if (!empty($content)) {
1030 $jsonldinfo['image'] = trim($content);
1033 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1035 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1036 return array_merge($siteinfo, $jsonldinfo);
1040 * Fetch data from the provided JSON-LD Organization type
1041 * @see https://schema.org/Organization
1043 * @param array $siteinfo
1044 * @param array $jsonld
1045 * @return array siteinfo
1047 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1051 $content = JsonLD::fetchElement($jsonld, 'name');
1052 if (!empty($content)) {
1053 $jsonldinfo['publisher_name'] = trim($content);
1056 $content = JsonLD::fetchElement($jsonld, 'description');
1057 if (!empty($content)) {
1058 $jsonldinfo['publisher_description'] = trim($content);
1061 $content = JsonLD::fetchElement($jsonld, 'url');
1062 if (!empty($content)) {
1063 $jsonldinfo['publisher_url'] = trim($content);
1066 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1067 if (!empty($content)) {
1068 $jsonldinfo['publisher_img'] = trim($content);
1071 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1072 if (!empty($content)) {
1073 $jsonldinfo['publisher_name'] = trim($content);
1076 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1077 if (!empty($content)) {
1078 $jsonldinfo['publisher_url'] = trim($content);
1081 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1082 return array_merge($siteinfo, $jsonldinfo);
1086 * Fetch data from the provided JSON-LD Person type
1087 * @see https://schema.org/Person
1089 * @param array $siteinfo
1090 * @param array $jsonld
1091 * @return array siteinfo
1093 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1097 $content = JsonLD::fetchElement($jsonld, 'name');
1098 if (!empty($content)) {
1099 $jsonldinfo['author_name'] = trim($content);
1102 $content = JsonLD::fetchElement($jsonld, 'description');
1103 if (!empty($content)) {
1104 $jsonldinfo['author_description'] = trim($content);
1107 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1108 if (!empty($content) && is_string($content)) {
1109 $jsonldinfo['author_url'] = trim($content);
1112 $content = JsonLD::fetchElement($jsonld, 'url');
1113 if (!empty($content)) {
1114 $jsonldinfo['author_url'] = trim($content);
1117 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1118 if (!empty($content)) {
1119 $jsonldinfo['author_img'] = trim($content);
1122 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1123 return array_merge($siteinfo, $jsonldinfo);
1127 * Fetch data from the provided JSON-LD MediaObject type
1128 * @see https://schema.org/MediaObject
1130 * @param array $siteinfo
1131 * @param array $jsonld
1132 * @return array siteinfo
1134 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1138 $content = JsonLD::fetchElement($jsonld, 'caption');
1139 if (!empty($content)) {
1140 $media['caption'] = trim($content);
1143 $content = JsonLD::fetchElement($jsonld, 'url');
1144 if (!empty($content)) {
1145 $media['url'] = trim($content);
1148 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1149 if (!empty($content)) {
1150 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1153 $content = JsonLD::fetchElement($jsonld, 'description');
1154 if (!empty($content)) {
1155 $media['description'] = trim($content);
1158 $content = JsonLD::fetchElement($jsonld, 'name');
1159 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1160 $media['name'] = trim($content);
1163 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1164 if (!empty($content)) {
1165 $media['content'] = trim($content);
1168 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1169 if (!empty($content)) {
1170 $media['embed'] = trim($content);
1173 $content = JsonLD::fetchElement($jsonld, 'height');
1174 if (!empty($content)) {
1175 $media['height'] = trim($content);
1178 $content = JsonLD::fetchElement($jsonld, 'width');
1179 if (!empty($content)) {
1180 $media['width'] = trim($content);
1183 $content = JsonLD::fetchElement($jsonld, 'image');
1184 if (!empty($content)) {
1185 $media['image'] = trim($content);
1188 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1189 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1190 if (!empty($media['image'])) {
1191 $media['preview'] = trim($content);
1193 $media['image'] = trim($content);
1197 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1198 $siteinfo[$name][] = $media;