3 * @copyright Copyright (C) 2020, Friendica
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::log('Endless loop detected for ' . $url, Logger::DEBUG);
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()) {
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::log('detected charset ' . $charset, Logger::DEBUG);
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 $list = $xpath->query('//meta[@name]');
353 foreach ($list as $node) {
355 if ($node->attributes->length) {
356 foreach ($node->attributes as $attribute) {
357 $meta_tag[$attribute->name] = $attribute->value;
361 if (empty($meta_tag['content'])) {
365 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
367 switch (strtolower($meta_tag['name'])) {
369 $siteinfo['title'] = trim($meta_tag['content']);
372 $siteinfo['text'] = trim($meta_tag['content']);
375 $siteinfo['image'] = $meta_tag['content'];
377 case 'twitter:image':
378 $siteinfo['image'] = $meta_tag['content'];
380 case 'twitter:image:src':
381 $siteinfo['image'] = $meta_tag['content'];
384 // Detect photo pages
385 if ($meta_tag['content'] == 'summary_large_image') {
386 $siteinfo['type'] = 'photo';
389 case 'twitter:description':
390 $siteinfo['text'] = trim($meta_tag['content']);
392 case 'twitter:title':
393 $siteinfo['title'] = trim($meta_tag['content']);
396 $siteinfo['title'] = trim($meta_tag['content']);
398 case 'dc.description':
399 $siteinfo['text'] = trim($meta_tag['content']);
402 $siteinfo['publisher_name'] = trim($meta_tag['content']);
405 $keywords = explode(',', $meta_tag['content']);
407 case 'news_keywords':
408 $keywords = explode(',', $meta_tag['content']);
413 if (isset($keywords)) {
414 $siteinfo['keywords'] = [];
415 foreach ($keywords as $keyword) {
416 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
417 $siteinfo['keywords'][] = trim($keyword);
422 $list = $xpath->query('//meta[@property]');
423 foreach ($list as $node) {
425 if ($node->attributes->length) {
426 foreach ($node->attributes as $attribute) {
427 $meta_tag[$attribute->name] = $attribute->value;
431 if (!empty($meta_tag['content'])) {
432 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
434 switch (strtolower($meta_tag['property'])) {
436 $siteinfo['image'] = $meta_tag['content'];
439 $siteinfo['image'] = $meta_tag['content'];
441 case 'og:image:secure_url':
442 $siteinfo['image'] = $meta_tag['content'];
445 $siteinfo['title'] = trim($meta_tag['content']);
447 case 'og:description':
448 $siteinfo['text'] = trim($meta_tag['content']);
451 $siteinfo['publisher_name'] = trim($meta_tag['content']);
453 case 'twitter:description':
454 $siteinfo['text'] = trim($meta_tag['content']);
456 case 'twitter:title':
457 $siteinfo['title'] = trim($meta_tag['content']);
459 case 'twitter:image':
460 $siteinfo['image'] = $meta_tag['content'];
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 // Prevent to have a photo type without an image
476 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
477 $siteinfo['type'] = 'link';
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) {
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']);
532 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
535 foreach (['audio', 'video'] as $element) {
536 if (!empty($siteinfo[$element])) {
537 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
542 foreach (['embed', 'content', 'url'] as $field) {
543 if (!empty($media[$field])) {
544 $media[$field] = self::completeUrl($media[$field], $page_url);
545 $type = self::getContentType($media[$field]);
546 if (($type[0] ?? '') == 'text') {
547 if ($field == 'embed') {
548 $embed = $media[$field];
550 $url = $media[$field];
552 } elseif (!empty($type[0])) {
553 $content = $media[$field];
554 $contenttype = implode('/', $type);
557 unset($media[$field]);
560 foreach (['image', 'preview'] as $field) {
561 if (!empty($media[$field])) {
562 $media[$field] = self::completeUrl($media[$field], $page_url);
567 $media['url'] = $url;
569 if (!empty($embed)) {
570 $media['embed'] = $embed;
571 if (!empty($media['main'])) {
572 $siteinfo['embed'] = $embed;
575 if (!empty($content)) {
576 $media['src'] = $content;
578 if (!empty($contenttype)) {
579 $media['contenttype'] = $contenttype;
581 if (empty($url) && empty($content) && empty($embed)) {
587 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
589 if (empty($siteinfo[$element])) {
590 unset($siteinfo[$element]);
597 * Convert tags from CSV to an array
599 * @param string $string Tags
600 * @return array with formatted Hashtags
602 public static function convertTagsToArray($string)
604 $arr_tags = str_getcsv($string);
605 if (count($arr_tags)) {
606 // add the # sign to every tag
607 array_walk($arr_tags, ["self", "arrAddHashes"]);
614 * Add a hasht sign to a string
616 * This method is used as callback function
618 * @param string $tag The pure tag name
619 * @param int $k Counter for internal use
622 private static function arrAddHashes(&$tag, $k)
628 * Add a scheme to an url
630 * The src attribute of some html elements (e.g. images)
631 * can miss the scheme so we need to add the correct
634 * @param string $url The url which possibly does have
635 * a missing scheme (a link to an image)
636 * @param string $scheme The url with a correct scheme
637 * (e.g. the url from the webpage which does contain the image)
639 * @return string The url with a scheme
641 private static function completeUrl($url, $scheme)
643 $urlarr = parse_url($url);
645 // If the url does allready have an scheme
646 // we can stop the process here
647 if (isset($urlarr["scheme"])) {
651 $schemearr = parse_url($scheme);
653 $complete = $schemearr["scheme"]."://".$schemearr["host"];
655 if (!empty($schemearr["port"])) {
656 $complete .= ":".$schemearr["port"];
659 if (!empty($urlarr["path"])) {
660 if (strpos($urlarr["path"], "/") !== 0) {
664 $complete .= $urlarr["path"];
667 if (!empty($urlarr["query"])) {
668 $complete .= "?".$urlarr["query"];
671 if (!empty($urlarr["fragment"])) {
672 $complete .= "#".$urlarr["fragment"];
679 * Parse the Json-Ld parts of a web page
681 * @param array $siteinfo
682 * @param array $jsonld
683 * @return array siteinfo
685 private static function parseParts(array $siteinfo, array $jsonld)
687 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
688 foreach ($jsonld['@graph'] as $part) {
690 $siteinfo = self::parseParts($siteinfo, $part);
693 } elseif (!empty($jsonld['@type'])) {
694 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
695 } elseif (!empty($jsonld)) {
696 $keys = array_keys($jsonld);
697 $numeric_keys = true;
698 foreach ($keys as $key) {
700 $numeric_keys = false;
704 foreach ($jsonld as $part) {
706 $siteinfo = self::parseParts($siteinfo, $part);
712 array_walk_recursive($siteinfo, function (&$element) {
713 if (is_string($element)) {
714 $element = html_entity_decode($element, ENT_COMPAT, 'UTF-8');
722 * Improve the siteinfo with information from the provided JSON-LD information
723 * @see https://jsonld.com/
724 * @see https://schema.org/
726 * @param array $siteinfo
727 * @param array $jsonld
728 * @return array siteinfo
730 private static function parseJsonLd(array $siteinfo, array $jsonld)
732 $type = JsonLD::fetchElement($jsonld, '@type');
734 Logger::info('Empty type', ['url' => $siteinfo['url']]);
738 // Silently ignore some types that aren't processed
739 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
740 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
741 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
747 case 'AdvertiserContentArticle':
750 case 'SatiricalArticle':
751 case 'ScholarlyArticle':
752 case 'SocialMediaPosting':
754 case 'ReportageNewsArticle':
755 case 'SocialMediaPosting':
757 case 'LiveBlogPosting':
758 case 'DiscussionForumPosting':
759 return self::parseJsonLdArticle($siteinfo, $jsonld);
763 case 'CollectionPage':
767 case 'MedicalWebPage':
770 case 'RealEstateListing':
771 case 'SearchResultsPage':
777 return self::parseJsonLdWebPage($siteinfo, $jsonld);
779 return self::parseJsonLdWebSite($siteinfo, $jsonld);
784 case 'EducationalOrganization':
785 case 'FundingScheme':
786 case 'GovernmentOrganization':
787 case 'LibrarySystem':
788 case 'LocalBusiness':
789 case 'MedicalOrganization':
791 case 'NewsMediaOrganization':
793 case 'SportsOrganization':
795 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
798 case 'PerformingGroup':
802 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
805 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
807 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
809 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
811 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
817 * Fetch author and publisher data
819 * @param array $siteinfo
820 * @param array $jsonld
821 * @return array siteinfo
823 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
827 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
828 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
829 if (!empty($content) && is_string($content)) {
830 $jsonldinfo['publisher_name'] = trim($content);
833 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
834 if (!empty($content) && is_string($content)) {
835 $jsonldinfo['publisher_url'] = trim($content);
838 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
839 if (!empty($brand) && is_array($brand)) {
840 $content = JsonLD::fetchElement($brand, 'name');
841 if (!empty($content) && is_string($content)) {
842 $jsonldinfo['publisher_name'] = trim($content);
845 $content = JsonLD::fetchElement($brand, 'url');
846 if (!empty($content) && is_string($content)) {
847 $jsonldinfo['publisher_url'] = trim($content);
850 $content = JsonLD::fetchElement($brand, 'logo', 'url');
851 if (!empty($content) && is_string($content)) {
852 $jsonldinfo['publisher_img'] = trim($content);
856 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
857 if (!empty($logo) && is_array($logo)) {
858 $content = JsonLD::fetchElement($logo, 'url');
859 if (!empty($content) && is_string($content)) {
860 $jsonldinfo['publisher_img'] = trim($content);
863 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
864 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
867 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
868 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
869 if (!empty($content) && is_string($content)) {
870 $jsonldinfo['author_name'] = trim($content);
873 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
874 if (!empty($content) && is_string($content)) {
875 $jsonldinfo['author_url'] = trim($content);
878 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
879 if (!empty($content) && is_string($content)) {
880 $jsonldinfo['author_url'] = trim($content);
883 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
884 if (!empty($logo) && is_array($logo)) {
885 $content = JsonLD::fetchElement($logo, 'url');
886 if (!empty($content) && is_string($content)) {
887 $jsonldinfo['author_img'] = trim($content);
890 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
891 $jsonldinfo['author_name'] = trim($jsonld['author']);
894 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
896 return array_merge($siteinfo, $jsonldinfo);
900 * Fetch data from the provided JSON-LD Article type
901 * @see https://schema.org/Article
903 * @param array $siteinfo
904 * @param array $jsonld
905 * @return array siteinfo
907 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
911 $content = JsonLD::fetchElement($jsonld, 'headline');
912 if (!empty($content) && is_string($content)) {
913 $jsonldinfo['title'] = trim($content);
916 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
917 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
918 $jsonldinfo['alternative_title'] = trim($content);
921 $content = JsonLD::fetchElement($jsonld, 'description');
922 if (!empty($content) && is_string($content)) {
923 $jsonldinfo['text'] = trim($content);
926 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
927 if (!empty($content)) {
928 $jsonldinfo['image'] = trim($content);
931 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
932 if (!empty($content) && is_string($content)) {
933 $jsonldinfo['image'] = trim($content);
936 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
937 $content = JsonLD::fetchElement($jsonld, 'keywords');
938 if (!empty($content)) {
939 $siteinfo['keywords'] = [];
940 $keywords = explode(',', $content);
941 foreach ($keywords as $keyword) {
942 $siteinfo['keywords'][] = trim($keyword);
946 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
947 if (!empty($content) && is_array($content)) {
948 $jsonldinfo['keywords'] = $content;
952 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
954 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
956 return array_merge($siteinfo, $jsonldinfo);
960 * Fetch data from the provided JSON-LD WebPage type
961 * @see https://schema.org/WebPage
963 * @param array $siteinfo
964 * @param array $jsonld
965 * @return array siteinfo
967 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
971 $content = JsonLD::fetchElement($jsonld, 'name');
972 if (!empty($content)) {
973 $jsonldinfo['title'] = trim($content);
976 $content = JsonLD::fetchElement($jsonld, 'description');
977 if (!empty($content)) {
978 $jsonldinfo['text'] = trim($content);
981 $content = JsonLD::fetchElement($jsonld, 'image');
982 if (!empty($content)) {
983 $jsonldinfo['image'] = trim($content);
986 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
987 if (!empty($content)) {
988 $jsonldinfo['image'] = trim($content);
991 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
993 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
995 return array_merge($siteinfo, $jsonldinfo);
999 * Fetch data from the provided JSON-LD WebSite type
1000 * @see https://schema.org/WebSite
1002 * @param array $siteinfo
1003 * @param array $jsonld
1004 * @return array siteinfo
1006 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1010 $content = JsonLD::fetchElement($jsonld, 'name');
1011 if (!empty($content)) {
1012 $jsonldinfo['publisher_name'] = trim($content);
1015 $content = JsonLD::fetchElement($jsonld, 'description');
1016 if (!empty($content)) {
1017 $jsonldinfo['publisher_description'] = trim($content);
1020 $content = JsonLD::fetchElement($jsonld, 'url');
1021 if (!empty($content)) {
1022 $jsonldinfo['publisher_url'] = trim($content);
1025 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1026 if (!empty($content)) {
1027 $jsonldinfo['image'] = trim($content);
1030 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1032 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1033 return array_merge($siteinfo, $jsonldinfo);
1037 * Fetch data from the provided JSON-LD Organization type
1038 * @see https://schema.org/Organization
1040 * @param array $siteinfo
1041 * @param array $jsonld
1042 * @return array siteinfo
1044 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1048 $content = JsonLD::fetchElement($jsonld, 'name');
1049 if (!empty($content)) {
1050 $jsonldinfo['publisher_name'] = trim($content);
1053 $content = JsonLD::fetchElement($jsonld, 'description');
1054 if (!empty($content)) {
1055 $jsonldinfo['publisher_description'] = trim($content);
1058 $content = JsonLD::fetchElement($jsonld, 'url');
1059 if (!empty($content)) {
1060 $jsonldinfo['publisher_url'] = trim($content);
1063 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1064 if (!empty($content)) {
1065 $jsonldinfo['publisher_img'] = trim($content);
1068 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1069 if (!empty($content)) {
1070 $jsonldinfo['publisher_name'] = trim($content);
1073 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1074 if (!empty($content)) {
1075 $jsonldinfo['publisher_url'] = trim($content);
1078 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1079 return array_merge($siteinfo, $jsonldinfo);
1083 * Fetch data from the provided JSON-LD Person type
1084 * @see https://schema.org/Person
1086 * @param array $siteinfo
1087 * @param array $jsonld
1088 * @return array siteinfo
1090 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1094 $content = JsonLD::fetchElement($jsonld, 'name');
1095 if (!empty($content)) {
1096 $jsonldinfo['author_name'] = trim($content);
1099 $content = JsonLD::fetchElement($jsonld, 'description');
1100 if (!empty($content)) {
1101 $jsonldinfo['author_description'] = trim($content);
1104 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1105 if (!empty($content) && is_string($content)) {
1106 $jsonldinfo['author_url'] = trim($content);
1109 $content = JsonLD::fetchElement($jsonld, 'url');
1110 if (!empty($content)) {
1111 $jsonldinfo['author_url'] = trim($content);
1114 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1115 if (!empty($content)) {
1116 $jsonldinfo['author_img'] = trim($content);
1119 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1120 return array_merge($siteinfo, $jsonldinfo);
1124 * Fetch data from the provided JSON-LD MediaObject type
1125 * @see https://schema.org/MediaObject
1127 * @param array $siteinfo
1128 * @param array $jsonld
1129 * @return array siteinfo
1131 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1135 $content = JsonLD::fetchElement($jsonld, 'caption');
1136 if (!empty($content)) {
1137 $media['caption'] = trim($content);
1140 $content = JsonLD::fetchElement($jsonld, 'url');
1141 if (!empty($content)) {
1142 $media['url'] = trim($content);
1145 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1146 if (!empty($content)) {
1147 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1150 $content = JsonLD::fetchElement($jsonld, 'description');
1151 if (!empty($content)) {
1152 $media['description'] = trim($content);
1155 $content = JsonLD::fetchElement($jsonld, 'name');
1156 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1157 $media['name'] = trim($content);
1160 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1161 if (!empty($content)) {
1162 $media['content'] = trim($content);
1165 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1166 if (!empty($content)) {
1167 $media['embed'] = trim($content);
1170 $content = JsonLD::fetchElement($jsonld, 'height');
1171 if (!empty($content)) {
1172 $media['height'] = trim($content);
1175 $content = JsonLD::fetchElement($jsonld, 'width');
1176 if (!empty($content)) {
1177 $media['width'] = trim($content);
1180 $content = JsonLD::fetchElement($jsonld, 'image');
1181 if (!empty($content)) {
1182 $media['image'] = trim($content);
1185 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1186 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1187 if (!empty($media['image'])) {
1188 $media['preview'] = trim($content);
1190 $media['image'] = trim($content);
1194 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1195 $siteinfo[$name][] = $media;