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;
33 use Friendica\Network\HTTPClientOptions;
36 * Get information about a given URL
38 * Class with methods for extracting certain content from an url
42 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
43 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
46 * Maximum number of characters for the description
48 const MAX_DESC_COUNT = 250;
51 * Minimum number of characters for the description
53 const MIN_DESC_COUNT = 100;
56 * Fetch the content type of the given url
57 * @param string $url URL of the page
58 * @return array content type
60 public static function getContentType(string $url)
62 $curlResult = DI::httpClient()->head($url);
63 if (!$curlResult->isSuccess()) {
67 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
68 if (empty($contenttype)) {
72 return explode('/', current(explode(';', $contenttype)));
76 * Search for chached embeddable data of an url otherwise fetch it
78 * @param string $url The url of the page which should be scraped
79 * @param bool $do_oembed The false option is used by the function fetch_oembed()
80 * to avoid endless loops
82 * @return array which contains needed data for embedding
83 * string 'url' => The url of the parsed page
84 * string 'type' => Content type
85 * string 'title' => (optional) The title of the content
86 * string 'text' => (optional) The description for the content
87 * string 'image' => (optional) A preview image of the content
88 * array 'images' => (optional) Array of preview pictures
89 * string 'keywords' => (optional) The tags which belong to the content
91 * @throws HTTPException\InternalServerErrorException
92 * @see ParseUrl::getSiteinfo() for more information about scraping
95 public static function getSiteinfoCached($url, $do_oembed = true): array
104 $urlHash = hash('sha256', $url);
106 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
107 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
109 if (!empty($parsed_url['content'])) {
110 $data = unserialize($parsed_url['content']);
114 $data = self::getSiteinfo($url, $do_oembed);
116 $expires = $data['expires'];
118 unset($data['expires']);
123 'url_hash' => $urlHash,
124 'oembed' => $do_oembed,
126 'content' => serialize($data),
127 'created' => DateTimeFormat::utcNow(),
128 'expires' => $expires,
130 Database::INSERT_UPDATE
137 * Parse a page for embeddable content information
139 * This method parses to url for meta data which can be used to embed
140 * the content. If available it prioritizes Open Graph meta tags.
141 * If this is not available it uses the twitter cards meta tags.
142 * As fallback it uses standard html elements with meta informations
143 * like \<title\>Awesome Title\</title\> or
144 * \<meta name="description" content="An awesome description"\>
146 * @param string $url The url of the page which should be scraped
147 * @param bool $do_oembed The false option is used by the function fetch_oembed()
148 * to avoid endless loops
149 * @param int $count Internal counter to avoid endless loops
151 * @return array which contains needed data for embedding
152 * string 'url' => The url of the parsed page
153 * string 'type' => Content type (error, link, photo, image, audio, video)
154 * string 'title' => (optional) The title of the content
155 * string 'text' => (optional) The description for the content
156 * string 'image' => (optional) A preview image of the content
157 * array 'images' => (optional) Array of preview pictures
158 * string 'keywords' => (optional) The tags which belong to the content
160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
161 * @todo https://developers.google.com/+/plugins/snippet/
163 * <meta itemprop="name" content="Awesome title">
164 * <meta itemprop="description" content="An awesome description">
165 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
167 * <body itemscope itemtype="http://schema.org/Product">
168 * <h1 itemprop="name">Shiny Trinket</h1>
169 * <img itemprop="image" src="{image-url}" />
170 * <p itemprop="description">Shiny trinkets are shiny.</p>
174 public static function getSiteinfo($url, $do_oembed = true, $count = 1)
183 // Check if the URL does contain a scheme
184 $scheme = parse_url($url, PHP_URL_SCHEME);
187 $url = 'http://' . ltrim($url, '/');
190 $url = trim($url, "'\"");
192 $url = Network::stripTrackingQueryParams($url);
197 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
201 Logger::notice('Endless loop detected', ['url' => $url]);
205 $type = self::getContentType($url);
206 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
207 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
208 $siteinfo['type'] = $type[0];
212 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
213 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
217 $curlResult = DI::httpClient()->get($url, [HTTPClientOptions::CONTENT_LENGTH => 1000000]);
218 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
222 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
224 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
225 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
226 $maxAge = max(86400, (int)array_pop($matches));
227 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
231 $body = $curlResult->getBody();
234 $oembed_data = OEmbed::fetchURL($url, false, false);
236 if (!empty($oembed_data->type)) {
237 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
238 $siteinfo['type'] = $oembed_data->type;
241 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
242 if ($siteinfo['type'] != 'photo') {
243 if (!empty($oembed_data->title)) {
244 $siteinfo['title'] = trim($oembed_data->title);
246 if (!empty($oembed_data->description)) {
247 $siteinfo['text'] = trim($oembed_data->description);
249 if (!empty($oembed_data->author_name)) {
250 $siteinfo['author_name'] = trim($oembed_data->author_name);
252 if (!empty($oembed_data->author_url)) {
253 $siteinfo['author_url'] = trim($oembed_data->author_url);
255 if (!empty($oembed_data->provider_name)) {
256 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
258 if (!empty($oembed_data->provider_url)) {
259 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
261 if (!empty($oembed_data->thumbnail_url)) {
262 $siteinfo['image'] = $oembed_data->thumbnail_url;
269 // Look for a charset, first in headers
270 // Expected form: Content-Type: text/html; charset=ISO-8859-4
271 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
272 $charset = trim(trim(trim(array_pop($matches)), ';,'));
275 // Then in body that gets precedence
277 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
278 // - <meta charset="utf-8">
279 // - <meta charset=utf-8>
280 // - <meta charSet="utf-8">
281 // We escape <style> and <script> tags since they can contain irrelevant charset information
282 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
283 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
284 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
285 $charset = trim(trim(trim(array_pop($matches)), ';,'));
289 $siteinfo['charset'] = $charset;
291 if ($charset && strtoupper($charset) != 'UTF-8') {
292 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
293 $charset = str_ireplace('latin-1', 'latin1', $charset);
295 Logger::info('detected charset', ['charset' => $charset]);
296 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
299 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
301 $doc = new DOMDocument();
302 @$doc->loadHTML($body);
304 XML::deleteNode($doc, 'style');
305 XML::deleteNode($doc, 'option');
306 XML::deleteNode($doc, 'h1');
307 XML::deleteNode($doc, 'h2');
308 XML::deleteNode($doc, 'h3');
309 XML::deleteNode($doc, 'h4');
310 XML::deleteNode($doc, 'h5');
311 XML::deleteNode($doc, 'h6');
312 XML::deleteNode($doc, 'ol');
313 XML::deleteNode($doc, 'ul');
315 $xpath = new DOMXPath($doc);
317 $list = $xpath->query('//meta[@content]');
318 foreach ($list as $node) {
320 if ($node->attributes->length) {
321 foreach ($node->attributes as $attribute) {
322 $meta_tag[$attribute->name] = $attribute->value;
326 if (@$meta_tag['http-equiv'] == 'refresh') {
327 $path = $meta_tag['content'];
328 $pathinfo = explode(';', $path);
330 foreach ($pathinfo as $value) {
331 if (substr(strtolower($value), 0, 4) == 'url=') {
332 $content = substr($value, 4);
335 if ($content != '') {
336 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
342 $list = $xpath->query('//title');
343 if ($list->length > 0) {
344 $siteinfo['title'] = trim($list->item(0)->nodeValue);
347 $twitter_card = false;
348 $twitter_image = false;
350 $list = $xpath->query('//meta[@name]');
351 foreach ($list as $node) {
353 if ($node->attributes->length) {
354 foreach ($node->attributes as $attribute) {
355 $meta_tag[$attribute->name] = $attribute->value;
359 if (empty($meta_tag['content'])) {
363 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
365 switch (strtolower($meta_tag['name'])) {
367 $siteinfo['title'] = trim($meta_tag['content']);
370 $siteinfo['text'] = trim($meta_tag['content']);
373 $siteinfo['image'] = $meta_tag['content'];
375 case 'twitter:image':
376 $siteinfo['image'] = $meta_tag['content'];
377 $twitter_image = true;
379 case 'twitter:image:src':
380 $siteinfo['image'] = $meta_tag['content'];
383 // Detect photo pages
384 if ($meta_tag['content'] == 'summary_large_image') {
385 $twitter_card = true;
388 case 'twitter:description':
389 $siteinfo['text'] = trim($meta_tag['content']);
391 case 'twitter:title':
392 $siteinfo['title'] = trim($meta_tag['content']);
395 $siteinfo['title'] = trim($meta_tag['content']);
397 case 'dc.description':
398 $siteinfo['text'] = trim($meta_tag['content']);
401 $siteinfo['publisher_name'] = trim($meta_tag['content']);
404 $keywords = explode(',', $meta_tag['content']);
406 case 'news_keywords':
407 $keywords = explode(',', $meta_tag['content']);
412 if (isset($keywords)) {
413 $siteinfo['keywords'] = [];
414 foreach ($keywords as $keyword) {
415 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
416 $siteinfo['keywords'][] = trim($keyword);
421 $list = $xpath->query('//meta[@property]');
422 foreach ($list as $node) {
424 if ($node->attributes->length) {
425 foreach ($node->attributes as $attribute) {
426 $meta_tag[$attribute->name] = $attribute->value;
430 if (!empty($meta_tag['content'])) {
431 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
433 switch (strtolower($meta_tag['property'])) {
435 $siteinfo['image'] = $meta_tag['content'];
438 $siteinfo['image'] = $meta_tag['content'];
440 case 'og:image:secure_url':
441 $siteinfo['image'] = $meta_tag['content'];
444 $siteinfo['title'] = trim($meta_tag['content']);
446 case 'og:description':
447 $siteinfo['text'] = trim($meta_tag['content']);
450 $siteinfo['publisher_name'] = trim($meta_tag['content']);
452 case 'twitter:description':
453 $siteinfo['text'] = trim($meta_tag['content']);
455 case 'twitter:title':
456 $siteinfo['title'] = trim($meta_tag['content']);
458 case 'twitter:image':
459 $siteinfo['image'] = $meta_tag['content'];
460 $twitter_image = true;
466 $list = $xpath->query("//script[@type='application/ld+json']");
467 foreach ($list as $node) {
468 if (!empty($node->nodeValue)) {
469 if ($jsonld = json_decode($node->nodeValue, true)) {
470 $siteinfo = self::parseParts($siteinfo, $jsonld);
475 // Currently deactivated, see https://github.com/friendica/friendica/pull/10148#issuecomment-821512658
476 // Prevent to have a photo type without an image
477 // if ($twitter_card && $twitter_image && !empty($siteinfo['image'])) {
478 // $siteinfo['type'] = 'photo';
481 if (!empty($siteinfo['image'])) {
482 $siteinfo['images'] = $siteinfo['images'] ?? [];
483 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
484 unset($siteinfo['image']);
487 $siteinfo = self::checkMedia($url, $siteinfo);
489 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
490 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
491 $pos = mb_strrpos($siteinfo['text'], '.');
492 if ($pos > self::MIN_DESC_COUNT) {
493 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
497 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
499 Hook::callAll('getsiteinfo', $siteinfo);
505 * Check the attached media elements.
506 * Fix existing data and add missing data.
508 * @param string $page_url
509 * @param array $siteinfo
512 private static function checkMedia(string $page_url, array $siteinfo)
514 if (!empty($siteinfo['images'])) {
515 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
516 // According to the specifications someone could place a picture url into the content field as well.
517 // But this doesn't seem to happen in the wild, so we don't cover it here.
518 if (!empty($image['url'])) {
519 $image['url'] = self::completeUrl($image['url'], $page_url);
520 $photodata = Images::getInfoFromURLCached($image['url']);
521 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
522 $image['src'] = $image['url'];
523 $image['width'] = $photodata[0];
524 $image['height'] = $photodata[1];
525 $image['contenttype'] = $photodata['mime'];
526 unset($image['url']);
536 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
539 foreach (['audio', 'video'] as $element) {
540 if (!empty($siteinfo[$element])) {
541 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
546 foreach (['embed', 'content', 'url'] as $field) {
547 if (!empty($media[$field])) {
548 $media[$field] = self::completeUrl($media[$field], $page_url);
549 $type = self::getContentType($media[$field]);
550 if (($type[0] ?? '') == 'text') {
551 if ($field == 'embed') {
552 $embed = $media[$field];
554 $url = $media[$field];
556 } elseif (!empty($type[0])) {
557 $content = $media[$field];
558 $contenttype = implode('/', $type);
561 unset($media[$field]);
564 foreach (['image', 'preview'] as $field) {
565 if (!empty($media[$field])) {
566 $media[$field] = self::completeUrl($media[$field], $page_url);
571 $media['url'] = $url;
573 if (!empty($embed)) {
574 $media['embed'] = $embed;
575 if (!empty($media['main'])) {
576 $siteinfo['embed'] = $embed;
579 if (!empty($content)) {
580 $media['src'] = $content;
582 if (!empty($contenttype)) {
583 $media['contenttype'] = $contenttype;
585 if (empty($url) && empty($content) && empty($embed)) {
591 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
593 if (empty($siteinfo[$element])) {
594 unset($siteinfo[$element]);
601 * Convert tags from CSV to an array
603 * @param string $string Tags
604 * @return array with formatted Hashtags
606 public static function convertTagsToArray($string)
608 $arr_tags = str_getcsv($string);
609 if (count($arr_tags)) {
610 // add the # sign to every tag
611 array_walk($arr_tags, ["self", "arrAddHashes"]);
618 * Add a hasht sign to a string
620 * This method is used as callback function
622 * @param string $tag The pure tag name
623 * @param int $k Counter for internal use
626 private static function arrAddHashes(&$tag, $k)
632 * Add a scheme to an url
634 * The src attribute of some html elements (e.g. images)
635 * can miss the scheme so we need to add the correct
638 * @param string $url The url which possibly does have
639 * a missing scheme (a link to an image)
640 * @param string $scheme The url with a correct scheme
641 * (e.g. the url from the webpage which does contain the image)
643 * @return string The url with a scheme
645 private static function completeUrl($url, $scheme)
647 $urlarr = parse_url($url);
649 // If the url does allready have an scheme
650 // we can stop the process here
651 if (isset($urlarr["scheme"])) {
655 $schemearr = parse_url($scheme);
657 $complete = $schemearr["scheme"]."://".$schemearr["host"];
659 if (!empty($schemearr["port"])) {
660 $complete .= ":".$schemearr["port"];
663 if (!empty($urlarr["path"])) {
664 if (strpos($urlarr["path"], "/") !== 0) {
668 $complete .= $urlarr["path"];
671 if (!empty($urlarr["query"])) {
672 $complete .= "?".$urlarr["query"];
675 if (!empty($urlarr["fragment"])) {
676 $complete .= "#".$urlarr["fragment"];
683 * Parse the Json-Ld parts of a web page
685 * @param array $siteinfo
686 * @param array $jsonld
687 * @return array siteinfo
689 private static function parseParts(array $siteinfo, array $jsonld)
691 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
692 foreach ($jsonld['@graph'] as $part) {
693 if (!empty($part) && is_array($part)) {
694 $siteinfo = self::parseParts($siteinfo, $part);
697 } elseif (!empty($jsonld['@type'])) {
698 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
699 } elseif (!empty($jsonld)) {
700 $keys = array_keys($jsonld);
701 $numeric_keys = true;
702 foreach ($keys as $key) {
704 $numeric_keys = false;
708 foreach ($jsonld as $part) {
709 if (!empty($part) && is_array($part)) {
710 $siteinfo = self::parseParts($siteinfo, $part);
716 array_walk_recursive($siteinfo, function (&$element) {
717 if (is_string($element)) {
718 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
726 * Improve the siteinfo with information from the provided JSON-LD information
727 * @see https://jsonld.com/
728 * @see https://schema.org/
730 * @param array $siteinfo
731 * @param array $jsonld
732 * @return array siteinfo
734 private static function parseJsonLd(array $siteinfo, array $jsonld)
736 $type = JsonLD::fetchElement($jsonld, '@type');
738 Logger::info('Empty type', ['url' => $siteinfo['url']]);
742 // Silently ignore some types that aren't processed
743 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
744 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
745 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
751 case 'AdvertiserContentArticle':
754 case 'SatiricalArticle':
755 case 'ScholarlyArticle':
756 case 'SocialMediaPosting':
758 case 'ReportageNewsArticle':
759 case 'SocialMediaPosting':
761 case 'LiveBlogPosting':
762 case 'DiscussionForumPosting':
763 return self::parseJsonLdArticle($siteinfo, $jsonld);
767 case 'CollectionPage':
771 case 'MedicalWebPage':
774 case 'RealEstateListing':
775 case 'SearchResultsPage':
781 return self::parseJsonLdWebPage($siteinfo, $jsonld);
783 return self::parseJsonLdWebSite($siteinfo, $jsonld);
788 case 'EducationalOrganization':
789 case 'FundingScheme':
790 case 'GovernmentOrganization':
791 case 'LibrarySystem':
792 case 'LocalBusiness':
793 case 'MedicalOrganization':
795 case 'NewsMediaOrganization':
797 case 'SportsOrganization':
799 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
802 case 'PerformingGroup':
806 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
809 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
811 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
813 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
815 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
821 * Fetch author and publisher data
823 * @param array $siteinfo
824 * @param array $jsonld
825 * @return array siteinfo
827 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
831 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
832 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
833 if (!empty($content) && is_string($content)) {
834 $jsonldinfo['publisher_name'] = trim($content);
837 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
838 if (!empty($content) && is_string($content)) {
839 $jsonldinfo['publisher_url'] = trim($content);
842 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
843 if (!empty($brand) && is_array($brand)) {
844 $content = JsonLD::fetchElement($brand, 'name');
845 if (!empty($content) && is_string($content)) {
846 $jsonldinfo['publisher_name'] = trim($content);
849 $content = JsonLD::fetchElement($brand, 'url');
850 if (!empty($content) && is_string($content)) {
851 $jsonldinfo['publisher_url'] = trim($content);
854 $content = JsonLD::fetchElement($brand, 'logo', 'url');
855 if (!empty($content) && is_string($content)) {
856 $jsonldinfo['publisher_img'] = trim($content);
860 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
861 if (!empty($logo) && is_array($logo)) {
862 $content = JsonLD::fetchElement($logo, 'url');
863 if (!empty($content) && is_string($content)) {
864 $jsonldinfo['publisher_img'] = trim($content);
867 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
868 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
871 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
872 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
873 if (!empty($content) && is_string($content)) {
874 $jsonldinfo['author_name'] = trim($content);
877 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
878 if (!empty($content) && is_string($content)) {
879 $jsonldinfo['author_url'] = trim($content);
882 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
883 if (!empty($content) && is_string($content)) {
884 $jsonldinfo['author_url'] = trim($content);
887 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
888 if (!empty($logo) && is_array($logo)) {
889 $content = JsonLD::fetchElement($logo, 'url');
890 if (!empty($content) && is_string($content)) {
891 $jsonldinfo['author_img'] = trim($content);
894 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
895 $jsonldinfo['author_name'] = trim($jsonld['author']);
898 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
900 return array_merge($siteinfo, $jsonldinfo);
904 * Fetch data from the provided JSON-LD Article type
905 * @see https://schema.org/Article
907 * @param array $siteinfo
908 * @param array $jsonld
909 * @return array siteinfo
911 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
915 $content = JsonLD::fetchElement($jsonld, 'headline');
916 if (!empty($content) && is_string($content)) {
917 $jsonldinfo['title'] = trim($content);
920 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
921 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
922 $jsonldinfo['alternative_title'] = trim($content);
925 $content = JsonLD::fetchElement($jsonld, 'description');
926 if (!empty($content) && is_string($content)) {
927 $jsonldinfo['text'] = trim($content);
930 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
931 if (!empty($content)) {
932 $jsonldinfo['image'] = trim($content);
935 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
936 if (!empty($content) && is_string($content)) {
937 $jsonldinfo['image'] = trim($content);
940 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
941 $content = JsonLD::fetchElement($jsonld, 'keywords');
942 if (!empty($content)) {
943 $siteinfo['keywords'] = [];
944 $keywords = explode(',', $content);
945 foreach ($keywords as $keyword) {
946 $siteinfo['keywords'][] = trim($keyword);
949 } elseif (!empty($jsonld['keywords'])) {
950 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
951 if (!empty($content) && is_array($content)) {
952 $jsonldinfo['keywords'] = $content;
956 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
958 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
960 return array_merge($siteinfo, $jsonldinfo);
964 * Fetch data from the provided JSON-LD WebPage type
965 * @see https://schema.org/WebPage
967 * @param array $siteinfo
968 * @param array $jsonld
969 * @return array siteinfo
971 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
975 $content = JsonLD::fetchElement($jsonld, 'name');
976 if (!empty($content)) {
977 $jsonldinfo['title'] = trim($content);
980 $content = JsonLD::fetchElement($jsonld, 'description');
981 if (!empty($content)) {
982 $jsonldinfo['text'] = trim($content);
985 $content = JsonLD::fetchElement($jsonld, 'image');
986 if (!empty($content)) {
987 $jsonldinfo['image'] = trim($content);
990 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
991 if (!empty($content)) {
992 $jsonldinfo['image'] = trim($content);
995 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
997 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
999 return array_merge($siteinfo, $jsonldinfo);
1003 * Fetch data from the provided JSON-LD WebSite type
1004 * @see https://schema.org/WebSite
1006 * @param array $siteinfo
1007 * @param array $jsonld
1008 * @return array siteinfo
1010 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1014 $content = JsonLD::fetchElement($jsonld, 'name');
1015 if (!empty($content)) {
1016 $jsonldinfo['publisher_name'] = trim($content);
1019 $content = JsonLD::fetchElement($jsonld, 'description');
1020 if (!empty($content)) {
1021 $jsonldinfo['publisher_description'] = trim($content);
1024 $content = JsonLD::fetchElement($jsonld, 'url');
1025 if (!empty($content)) {
1026 $jsonldinfo['publisher_url'] = trim($content);
1029 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1030 if (!empty($content)) {
1031 $jsonldinfo['image'] = trim($content);
1034 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1036 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1037 return array_merge($siteinfo, $jsonldinfo);
1041 * Fetch data from the provided JSON-LD Organization type
1042 * @see https://schema.org/Organization
1044 * @param array $siteinfo
1045 * @param array $jsonld
1046 * @return array siteinfo
1048 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1052 $content = JsonLD::fetchElement($jsonld, 'name');
1053 if (!empty($content)) {
1054 $jsonldinfo['publisher_name'] = trim($content);
1057 $content = JsonLD::fetchElement($jsonld, 'description');
1058 if (!empty($content)) {
1059 $jsonldinfo['publisher_description'] = trim($content);
1062 $content = JsonLD::fetchElement($jsonld, 'url');
1063 if (!empty($content)) {
1064 $jsonldinfo['publisher_url'] = trim($content);
1067 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1068 if (!empty($content)) {
1069 $jsonldinfo['publisher_img'] = trim($content);
1072 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1073 if (!empty($content)) {
1074 $jsonldinfo['publisher_name'] = trim($content);
1077 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1078 if (!empty($content)) {
1079 $jsonldinfo['publisher_url'] = trim($content);
1082 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1083 return array_merge($siteinfo, $jsonldinfo);
1087 * Fetch data from the provided JSON-LD Person type
1088 * @see https://schema.org/Person
1090 * @param array $siteinfo
1091 * @param array $jsonld
1092 * @return array siteinfo
1094 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1098 $content = JsonLD::fetchElement($jsonld, 'name');
1099 if (!empty($content)) {
1100 $jsonldinfo['author_name'] = trim($content);
1103 $content = JsonLD::fetchElement($jsonld, 'description');
1104 if (!empty($content)) {
1105 $jsonldinfo['author_description'] = trim($content);
1108 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1109 if (!empty($content) && is_string($content)) {
1110 $jsonldinfo['author_url'] = trim($content);
1113 $content = JsonLD::fetchElement($jsonld, 'url');
1114 if (!empty($content)) {
1115 $jsonldinfo['author_url'] = trim($content);
1118 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1119 if (!empty($content)) {
1120 $jsonldinfo['author_img'] = trim($content);
1123 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1124 return array_merge($siteinfo, $jsonldinfo);
1128 * Fetch data from the provided JSON-LD MediaObject type
1129 * @see https://schema.org/MediaObject
1131 * @param array $siteinfo
1132 * @param array $jsonld
1133 * @return array siteinfo
1135 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1139 $content = JsonLD::fetchElement($jsonld, 'caption');
1140 if (!empty($content)) {
1141 $media['caption'] = trim($content);
1144 $content = JsonLD::fetchElement($jsonld, 'url');
1145 if (!empty($content)) {
1146 $media['url'] = trim($content);
1149 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1150 if (!empty($content)) {
1151 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1154 $content = JsonLD::fetchElement($jsonld, 'description');
1155 if (!empty($content)) {
1156 $media['description'] = trim($content);
1159 $content = JsonLD::fetchElement($jsonld, 'name');
1160 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1161 $media['name'] = trim($content);
1164 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1165 if (!empty($content)) {
1166 $media['content'] = trim($content);
1169 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1170 if (!empty($content)) {
1171 $media['embed'] = trim($content);
1174 $content = JsonLD::fetchElement($jsonld, 'height');
1175 if (!empty($content)) {
1176 $media['height'] = trim($content);
1179 $content = JsonLD::fetchElement($jsonld, 'width');
1180 if (!empty($content)) {
1181 $media['width'] = trim($content);
1184 $content = JsonLD::fetchElement($jsonld, 'image');
1185 if (!empty($content)) {
1186 $media['image'] = trim($content);
1189 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1190 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1191 if (!empty($media['image'])) {
1192 $media['preview'] = trim($content);
1194 $media['image'] = trim($content);
1198 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1199 $siteinfo[$name][] = $media;