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\HTTPClient\Client\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 $list = $xpath->query('//meta[@name]');
348 foreach ($list as $node) {
350 if ($node->attributes->length) {
351 foreach ($node->attributes as $attribute) {
352 $meta_tag[$attribute->name] = $attribute->value;
356 if (empty($meta_tag['content'])) {
360 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
362 switch (strtolower($meta_tag['name'])) {
364 $siteinfo['title'] = trim($meta_tag['content']);
367 $siteinfo['text'] = trim($meta_tag['content']);
370 $siteinfo['image'] = $meta_tag['content'];
372 case 'twitter:image':
373 $siteinfo['image'] = $meta_tag['content'];
375 case 'twitter:image:src':
376 $siteinfo['image'] = $meta_tag['content'];
378 case 'twitter:description':
379 $siteinfo['text'] = trim($meta_tag['content']);
381 case 'twitter:title':
382 $siteinfo['title'] = trim($meta_tag['content']);
384 case 'twitter:player':
385 $siteinfo['player']['embed'] = trim($meta_tag['content']);
387 case 'twitter:player:stream':
388 $siteinfo['player']['stream'] = trim($meta_tag['content']);
390 case 'twitter:player:width':
391 $siteinfo['player']['width'] = intval($meta_tag['content']);
393 case 'twitter:player:height':
394 $siteinfo['player']['height'] = intval($meta_tag['content']);
397 $siteinfo['title'] = trim($meta_tag['content']);
399 case 'dc.description':
400 $siteinfo['text'] = trim($meta_tag['content']);
403 $siteinfo['publisher_name'] = trim($meta_tag['content']);
406 $keywords = explode(',', $meta_tag['content']);
408 case 'news_keywords':
409 $keywords = explode(',', $meta_tag['content']);
414 if (isset($keywords)) {
415 $siteinfo['keywords'] = [];
416 foreach ($keywords as $keyword) {
417 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
418 $siteinfo['keywords'][] = trim($keyword);
423 $list = $xpath->query('//meta[@property]');
424 foreach ($list as $node) {
426 if ($node->attributes->length) {
427 foreach ($node->attributes as $attribute) {
428 $meta_tag[$attribute->name] = $attribute->value;
432 if (!empty($meta_tag['content'])) {
433 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
435 switch (strtolower($meta_tag['property'])) {
437 $siteinfo['image'] = $meta_tag['content'];
440 $siteinfo['image'] = $meta_tag['content'];
442 case 'og:image:secure_url':
443 $siteinfo['image'] = $meta_tag['content'];
446 $siteinfo['title'] = trim($meta_tag['content']);
448 case 'og:description':
449 $siteinfo['text'] = trim($meta_tag['content']);
452 $siteinfo['publisher_name'] = trim($meta_tag['content']);
455 $siteinfo['language'] = trim($meta_tag['content']);
458 $siteinfo['pagetype'] = trim($meta_tag['content']);
460 case 'twitter:description':
461 $siteinfo['text'] = trim($meta_tag['content']);
463 case 'twitter:title':
464 $siteinfo['title'] = trim($meta_tag['content']);
466 case 'twitter:image':
467 $siteinfo['image'] = $meta_tag['content'];
473 $list = $xpath->query("//script[@type='application/ld+json']");
474 foreach ($list as $node) {
475 if (!empty($node->nodeValue)) {
476 if ($jsonld = json_decode($node->nodeValue, true)) {
477 $siteinfo = self::parseParts($siteinfo, $jsonld);
482 if (!empty($siteinfo['player']['stream'])) {
483 // Only add player data to media arrays if there is no duplicate
484 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
485 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
486 $contenttype = self::getContentType($siteinfo['player']['stream']);
487 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
488 $media = ['content' => $siteinfo['player']['stream']];
490 if (!empty($siteinfo['player']['embed'])) {
491 $media['embed'] = $siteinfo['player']['embed'];
494 $siteinfo[$contenttype[0]][] = $media;
499 if (!empty($siteinfo['image'])) {
500 $siteinfo['images'] = $siteinfo['images'] ?? [];
501 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
502 unset($siteinfo['image']);
505 $siteinfo = self::checkMedia($url, $siteinfo);
507 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
508 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
509 $pos = mb_strrpos($siteinfo['text'], '.');
510 if ($pos > self::MIN_DESC_COUNT) {
511 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
515 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
517 Hook::callAll('getsiteinfo', $siteinfo);
525 * Check the attached media elements.
526 * Fix existing data and add missing data.
528 * @param string $page_url
529 * @param array $siteinfo
532 private static function checkMedia(string $page_url, array $siteinfo) : array
534 if (!empty($siteinfo['images'])) {
535 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
536 // According to the specifications someone could place a picture url into the content field as well.
537 // But this doesn't seem to happen in the wild, so we don't cover it here.
538 if (!empty($image['url'])) {
539 $image['url'] = self::completeUrl($image['url'], $page_url);
540 $photodata = Images::getInfoFromURLCached($image['url']);
541 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
542 $image['src'] = $image['url'];
543 $image['width'] = $photodata[0];
544 $image['height'] = $photodata[1];
545 $image['contenttype'] = $photodata['mime'];
546 unset($image['url']);
556 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
559 foreach (['audio', 'video'] as $element) {
560 if (!empty($siteinfo[$element])) {
561 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
566 foreach (['embed', 'content', 'url'] as $field) {
567 if (!empty($media[$field])) {
568 $media[$field] = self::completeUrl($media[$field], $page_url);
569 $type = self::getContentType($media[$field]);
570 if (($type[0] ?? '') == 'text') {
571 if ($field == 'embed') {
572 $embed = $media[$field];
574 $url = $media[$field];
576 } elseif (!empty($type[0])) {
577 $content = $media[$field];
578 $contenttype = implode('/', $type);
581 unset($media[$field]);
584 foreach (['image', 'preview'] as $field) {
585 if (!empty($media[$field])) {
586 $media[$field] = self::completeUrl($media[$field], $page_url);
591 $media['url'] = $url;
593 if (!empty($embed)) {
594 $media['embed'] = $embed;
595 if (empty($siteinfo['player']['embed'])) {
596 $siteinfo['player']['embed'] = $embed;
599 if (!empty($content)) {
600 $media['src'] = $content;
602 if (!empty($contenttype)) {
603 $media['contenttype'] = $contenttype;
605 if (empty($url) && empty($content) && empty($embed)) {
611 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
613 if (empty($siteinfo[$element])) {
614 unset($siteinfo[$element]);
621 * Convert tags from CSV to an array
623 * @param string $string Tags
624 * @return array with formatted Hashtags
626 public static function convertTagsToArray($string)
628 $arr_tags = str_getcsv($string);
629 if (count($arr_tags)) {
630 // add the # sign to every tag
631 array_walk($arr_tags, ["self", "arrAddHashes"]);
638 * Add a hasht sign to a string
640 * This method is used as callback function
642 * @param string $tag The pure tag name
643 * @param int $k Counter for internal use
646 private static function arrAddHashes(&$tag, $k)
652 * Add a scheme to an url
654 * The src attribute of some html elements (e.g. images)
655 * can miss the scheme so we need to add the correct
658 * @param string $url The url which possibly does have
659 * a missing scheme (a link to an image)
660 * @param string $scheme The url with a correct scheme
661 * (e.g. the url from the webpage which does contain the image)
663 * @return string The url with a scheme
665 private static function completeUrl($url, $scheme)
667 $urlarr = parse_url($url);
669 // If the url does allready have an scheme
670 // we can stop the process here
671 if (isset($urlarr["scheme"])) {
675 $schemearr = parse_url($scheme);
677 $complete = $schemearr["scheme"]."://".$schemearr["host"];
679 if (!empty($schemearr["port"])) {
680 $complete .= ":".$schemearr["port"];
683 if (!empty($urlarr["path"])) {
684 if (strpos($urlarr["path"], "/") !== 0) {
688 $complete .= $urlarr["path"];
691 if (!empty($urlarr["query"])) {
692 $complete .= "?".$urlarr["query"];
695 if (!empty($urlarr["fragment"])) {
696 $complete .= "#".$urlarr["fragment"];
703 * Parse the Json-Ld parts of a web page
705 * @param array $siteinfo
706 * @param array $jsonld
707 * @return array siteinfo
709 private static function parseParts(array $siteinfo, array $jsonld)
711 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
712 foreach ($jsonld['@graph'] as $part) {
713 if (!empty($part) && is_array($part)) {
714 $siteinfo = self::parseParts($siteinfo, $part);
717 } elseif (!empty($jsonld['@type'])) {
718 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
719 } elseif (!empty($jsonld)) {
720 $keys = array_keys($jsonld);
721 $numeric_keys = true;
722 foreach ($keys as $key) {
724 $numeric_keys = false;
728 foreach ($jsonld as $part) {
729 if (!empty($part) && is_array($part)) {
730 $siteinfo = self::parseParts($siteinfo, $part);
736 array_walk_recursive($siteinfo, function (&$element) {
737 if (is_string($element)) {
738 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
746 * Improve the siteinfo with information from the provided JSON-LD information
747 * @see https://jsonld.com/
748 * @see https://schema.org/
750 * @param array $siteinfo
751 * @param array $jsonld
752 * @return array siteinfo
754 private static function parseJsonLd(array $siteinfo, array $jsonld)
756 $type = JsonLD::fetchElement($jsonld, '@type');
758 Logger::info('Empty type', ['url' => $siteinfo['url']]);
762 // Silently ignore some types that aren't processed
763 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
764 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
765 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
771 case 'AdvertiserContentArticle':
774 case 'SatiricalArticle':
775 case 'ScholarlyArticle':
776 case 'SocialMediaPosting':
778 case 'ReportageNewsArticle':
779 case 'SocialMediaPosting':
781 case 'LiveBlogPosting':
782 case 'DiscussionForumPosting':
783 return self::parseJsonLdArticle($siteinfo, $jsonld);
787 case 'CollectionPage':
791 case 'MedicalWebPage':
794 case 'RealEstateListing':
795 case 'SearchResultsPage':
801 return self::parseJsonLdWebPage($siteinfo, $jsonld);
803 return self::parseJsonLdWebSite($siteinfo, $jsonld);
808 case 'EducationalOrganization':
809 case 'FundingScheme':
810 case 'GovernmentOrganization':
811 case 'LibrarySystem':
812 case 'LocalBusiness':
813 case 'MedicalOrganization':
815 case 'NewsMediaOrganization':
817 case 'SportsOrganization':
819 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
822 case 'PerformingGroup':
826 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
829 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
831 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
833 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
835 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
841 * Fetch author and publisher data
843 * @param array $siteinfo
844 * @param array $jsonld
845 * @return array siteinfo
847 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
851 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
852 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
853 if (!empty($content) && is_string($content)) {
854 $jsonldinfo['publisher_name'] = trim($content);
857 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
858 if (!empty($content) && is_string($content)) {
859 $jsonldinfo['publisher_url'] = trim($content);
862 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
863 if (!empty($brand) && is_array($brand)) {
864 $content = JsonLD::fetchElement($brand, 'name');
865 if (!empty($content) && is_string($content)) {
866 $jsonldinfo['publisher_name'] = trim($content);
869 $content = JsonLD::fetchElement($brand, 'url');
870 if (!empty($content) && is_string($content)) {
871 $jsonldinfo['publisher_url'] = trim($content);
874 $content = JsonLD::fetchElement($brand, 'logo', 'url');
875 if (!empty($content) && is_string($content)) {
876 $jsonldinfo['publisher_img'] = trim($content);
880 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
881 if (!empty($logo) && is_array($logo)) {
882 $content = JsonLD::fetchElement($logo, 'url');
883 if (!empty($content) && is_string($content)) {
884 $jsonldinfo['publisher_img'] = trim($content);
887 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
888 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
891 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
892 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
893 if (!empty($content) && is_string($content)) {
894 $jsonldinfo['author_name'] = trim($content);
897 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
898 if (!empty($content) && is_string($content)) {
899 $jsonldinfo['author_url'] = trim($content);
902 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
903 if (!empty($content) && is_string($content)) {
904 $jsonldinfo['author_url'] = trim($content);
907 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
908 if (!empty($logo) && is_array($logo)) {
909 $content = JsonLD::fetchElement($logo, 'url');
910 if (!empty($content) && is_string($content)) {
911 $jsonldinfo['author_img'] = trim($content);
914 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
915 $jsonldinfo['author_name'] = trim($jsonld['author']);
918 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
920 return array_merge($siteinfo, $jsonldinfo);
924 * Fetch data from the provided JSON-LD Article type
925 * @see https://schema.org/Article
927 * @param array $siteinfo
928 * @param array $jsonld
929 * @return array siteinfo
931 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
935 $content = JsonLD::fetchElement($jsonld, 'headline');
936 if (!empty($content) && is_string($content)) {
937 $jsonldinfo['title'] = trim($content);
940 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
941 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
942 $jsonldinfo['alternative_title'] = trim($content);
945 $content = JsonLD::fetchElement($jsonld, 'description');
946 if (!empty($content) && is_string($content)) {
947 $jsonldinfo['text'] = trim($content);
950 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
951 if (!empty($content)) {
952 $jsonldinfo['image'] = trim($content);
955 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
956 if (!empty($content) && is_string($content)) {
957 $jsonldinfo['image'] = trim($content);
960 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
961 $content = JsonLD::fetchElement($jsonld, 'keywords');
962 if (!empty($content)) {
963 $siteinfo['keywords'] = [];
964 $keywords = explode(',', $content);
965 foreach ($keywords as $keyword) {
966 $siteinfo['keywords'][] = trim($keyword);
969 } elseif (!empty($jsonld['keywords'])) {
970 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
971 if (!empty($content) && is_array($content)) {
972 $jsonldinfo['keywords'] = $content;
976 $content = JsonLD::fetchElement($jsonld, 'datePublished');
977 if (!empty($content) && is_string($content)) {
978 $jsonldinfo['published'] = DateTimeFormat::utc($content);
981 $content = JsonLD::fetchElement($jsonld, 'dateModified');
982 if (!empty($content) && is_string($content)) {
983 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
986 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
988 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
990 return array_merge($siteinfo, $jsonldinfo);
994 * Fetch data from the provided JSON-LD WebPage type
995 * @see https://schema.org/WebPage
997 * @param array $siteinfo
998 * @param array $jsonld
999 * @return array siteinfo
1001 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
1005 $content = JsonLD::fetchElement($jsonld, 'name');
1006 if (!empty($content)) {
1007 $jsonldinfo['title'] = trim($content);
1010 $content = JsonLD::fetchElement($jsonld, 'description');
1011 if (!empty($content)) {
1012 $jsonldinfo['text'] = trim($content);
1015 $content = JsonLD::fetchElement($jsonld, 'image');
1016 if (!empty($content)) {
1017 $jsonldinfo['image'] = trim($content);
1020 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1021 if (!empty($content)) {
1022 $jsonldinfo['image'] = trim($content);
1025 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1027 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1029 return array_merge($siteinfo, $jsonldinfo);
1033 * Fetch data from the provided JSON-LD WebSite type
1034 * @see https://schema.org/WebSite
1036 * @param array $siteinfo
1037 * @param array $jsonld
1038 * @return array siteinfo
1040 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1044 $content = JsonLD::fetchElement($jsonld, 'name');
1045 if (!empty($content)) {
1046 $jsonldinfo['publisher_name'] = trim($content);
1049 $content = JsonLD::fetchElement($jsonld, 'description');
1050 if (!empty($content)) {
1051 $jsonldinfo['publisher_description'] = trim($content);
1054 $content = JsonLD::fetchElement($jsonld, 'url');
1055 if (!empty($content)) {
1056 $jsonldinfo['publisher_url'] = trim($content);
1059 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1060 if (!empty($content)) {
1061 $jsonldinfo['image'] = trim($content);
1064 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1066 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1067 return array_merge($siteinfo, $jsonldinfo);
1071 * Fetch data from the provided JSON-LD Organization type
1072 * @see https://schema.org/Organization
1074 * @param array $siteinfo
1075 * @param array $jsonld
1076 * @return array siteinfo
1078 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1082 $content = JsonLD::fetchElement($jsonld, 'name');
1083 if (!empty($content)) {
1084 $jsonldinfo['publisher_name'] = trim($content);
1087 $content = JsonLD::fetchElement($jsonld, 'description');
1088 if (!empty($content)) {
1089 $jsonldinfo['publisher_description'] = trim($content);
1092 $content = JsonLD::fetchElement($jsonld, 'url');
1093 if (!empty($content)) {
1094 $jsonldinfo['publisher_url'] = trim($content);
1097 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1098 if (!empty($content)) {
1099 $jsonldinfo['publisher_img'] = trim($content);
1102 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1103 if (!empty($content)) {
1104 $jsonldinfo['publisher_name'] = trim($content);
1107 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1108 if (!empty($content)) {
1109 $jsonldinfo['publisher_url'] = trim($content);
1112 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1113 return array_merge($siteinfo, $jsonldinfo);
1117 * Fetch data from the provided JSON-LD Person type
1118 * @see https://schema.org/Person
1120 * @param array $siteinfo
1121 * @param array $jsonld
1122 * @return array siteinfo
1124 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1128 $content = JsonLD::fetchElement($jsonld, 'name');
1129 if (!empty($content)) {
1130 $jsonldinfo['author_name'] = trim($content);
1133 $content = JsonLD::fetchElement($jsonld, 'description');
1134 if (!empty($content)) {
1135 $jsonldinfo['author_description'] = trim($content);
1138 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1139 if (!empty($content) && is_string($content)) {
1140 $jsonldinfo['author_url'] = trim($content);
1143 $content = JsonLD::fetchElement($jsonld, 'url');
1144 if (!empty($content)) {
1145 $jsonldinfo['author_url'] = trim($content);
1148 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1149 if (!empty($content) && !is_string($content)) {
1150 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1153 if (!empty($content) && is_string($content)) {
1154 $jsonldinfo['author_img'] = trim($content);
1157 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1158 return array_merge($siteinfo, $jsonldinfo);
1162 * Fetch data from the provided JSON-LD MediaObject type
1163 * @see https://schema.org/MediaObject
1165 * @param array $siteinfo
1166 * @param array $jsonld
1167 * @return array siteinfo
1169 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1173 $content = JsonLD::fetchElement($jsonld, 'caption');
1174 if (!empty($content)) {
1175 $media['caption'] = trim($content);
1178 $content = JsonLD::fetchElement($jsonld, 'url');
1179 if (!empty($content)) {
1180 $media['url'] = trim($content);
1183 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1184 if (!empty($content)) {
1185 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1188 $content = JsonLD::fetchElement($jsonld, 'description');
1189 if (!empty($content)) {
1190 $media['description'] = trim($content);
1193 $content = JsonLD::fetchElement($jsonld, 'name');
1194 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1195 $media['name'] = trim($content);
1198 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1199 if (!empty($content)) {
1200 $media['content'] = trim($content);
1203 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1204 if (!empty($content)) {
1205 $media['embed'] = trim($content);
1208 $content = JsonLD::fetchElement($jsonld, 'height');
1209 if (!empty($content)) {
1210 $media['height'] = trim($content);
1213 $content = JsonLD::fetchElement($jsonld, 'width');
1214 if (!empty($content)) {
1215 $media['width'] = trim($content);
1218 $content = JsonLD::fetchElement($jsonld, 'image');
1219 if (!empty($content)) {
1220 $media['image'] = trim($content);
1223 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1224 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1225 if (!empty($media['image'])) {
1226 $media['preview'] = trim($content);
1228 $media['image'] = trim($content);
1232 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1233 $siteinfo[$name][] = $media;