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']);
454 case 'twitter:description':
455 $siteinfo['text'] = trim($meta_tag['content']);
457 case 'twitter:title':
458 $siteinfo['title'] = trim($meta_tag['content']);
460 case 'twitter:image':
461 $siteinfo['image'] = $meta_tag['content'];
467 $list = $xpath->query("//script[@type='application/ld+json']");
468 foreach ($list as $node) {
469 if (!empty($node->nodeValue)) {
470 if ($jsonld = json_decode($node->nodeValue, true)) {
471 $siteinfo = self::parseParts($siteinfo, $jsonld);
476 if (!empty($siteinfo['player']['stream'])) {
477 // Only add player data to media arrays if there is no duplicate
478 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
479 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
480 $contenttype = self::getContentType($siteinfo['player']['stream']);
481 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
482 $media = ['content' => $siteinfo['player']['stream']];
484 if (!empty($siteinfo['player']['embed'])) {
485 $media['embed'] = $siteinfo['player']['embed'];
488 $siteinfo[$contenttype[0]][] = $media;
493 if (!empty($siteinfo['image'])) {
494 $siteinfo['images'] = $siteinfo['images'] ?? [];
495 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
496 unset($siteinfo['image']);
499 $siteinfo = self::checkMedia($url, $siteinfo);
501 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
502 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
503 $pos = mb_strrpos($siteinfo['text'], '.');
504 if ($pos > self::MIN_DESC_COUNT) {
505 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
509 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
511 Hook::callAll('getsiteinfo', $siteinfo);
519 * Check the attached media elements.
520 * Fix existing data and add missing data.
522 * @param string $page_url
523 * @param array $siteinfo
526 private static function checkMedia(string $page_url, array $siteinfo) : array
528 if (!empty($siteinfo['images'])) {
529 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
530 // According to the specifications someone could place a picture url into the content field as well.
531 // But this doesn't seem to happen in the wild, so we don't cover it here.
532 if (!empty($image['url'])) {
533 $image['url'] = self::completeUrl($image['url'], $page_url);
534 $photodata = Images::getInfoFromURLCached($image['url']);
535 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
536 $image['src'] = $image['url'];
537 $image['width'] = $photodata[0];
538 $image['height'] = $photodata[1];
539 $image['contenttype'] = $photodata['mime'];
540 unset($image['url']);
550 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
553 foreach (['audio', 'video'] as $element) {
554 if (!empty($siteinfo[$element])) {
555 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
560 foreach (['embed', 'content', 'url'] as $field) {
561 if (!empty($media[$field])) {
562 $media[$field] = self::completeUrl($media[$field], $page_url);
563 $type = self::getContentType($media[$field]);
564 if (($type[0] ?? '') == 'text') {
565 if ($field == 'embed') {
566 $embed = $media[$field];
568 $url = $media[$field];
570 } elseif (!empty($type[0])) {
571 $content = $media[$field];
572 $contenttype = implode('/', $type);
575 unset($media[$field]);
578 foreach (['image', 'preview'] as $field) {
579 if (!empty($media[$field])) {
580 $media[$field] = self::completeUrl($media[$field], $page_url);
585 $media['url'] = $url;
587 if (!empty($embed)) {
588 $media['embed'] = $embed;
589 if (empty($siteinfo['player']['embed'])) {
590 $siteinfo['player']['embed'] = $embed;
593 if (!empty($content)) {
594 $media['src'] = $content;
596 if (!empty($contenttype)) {
597 $media['contenttype'] = $contenttype;
599 if (empty($url) && empty($content) && empty($embed)) {
605 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
607 if (empty($siteinfo[$element])) {
608 unset($siteinfo[$element]);
615 * Convert tags from CSV to an array
617 * @param string $string Tags
618 * @return array with formatted Hashtags
620 public static function convertTagsToArray($string)
622 $arr_tags = str_getcsv($string);
623 if (count($arr_tags)) {
624 // add the # sign to every tag
625 array_walk($arr_tags, ["self", "arrAddHashes"]);
632 * Add a hasht sign to a string
634 * This method is used as callback function
636 * @param string $tag The pure tag name
637 * @param int $k Counter for internal use
640 private static function arrAddHashes(&$tag, $k)
646 * Add a scheme to an url
648 * The src attribute of some html elements (e.g. images)
649 * can miss the scheme so we need to add the correct
652 * @param string $url The url which possibly does have
653 * a missing scheme (a link to an image)
654 * @param string $scheme The url with a correct scheme
655 * (e.g. the url from the webpage which does contain the image)
657 * @return string The url with a scheme
659 private static function completeUrl($url, $scheme)
661 $urlarr = parse_url($url);
663 // If the url does allready have an scheme
664 // we can stop the process here
665 if (isset($urlarr["scheme"])) {
669 $schemearr = parse_url($scheme);
671 $complete = $schemearr["scheme"]."://".$schemearr["host"];
673 if (!empty($schemearr["port"])) {
674 $complete .= ":".$schemearr["port"];
677 if (!empty($urlarr["path"])) {
678 if (strpos($urlarr["path"], "/") !== 0) {
682 $complete .= $urlarr["path"];
685 if (!empty($urlarr["query"])) {
686 $complete .= "?".$urlarr["query"];
689 if (!empty($urlarr["fragment"])) {
690 $complete .= "#".$urlarr["fragment"];
697 * Parse the Json-Ld parts of a web page
699 * @param array $siteinfo
700 * @param array $jsonld
701 * @return array siteinfo
703 private static function parseParts(array $siteinfo, array $jsonld)
705 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
706 foreach ($jsonld['@graph'] as $part) {
707 if (!empty($part) && is_array($part)) {
708 $siteinfo = self::parseParts($siteinfo, $part);
711 } elseif (!empty($jsonld['@type'])) {
712 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
713 } elseif (!empty($jsonld)) {
714 $keys = array_keys($jsonld);
715 $numeric_keys = true;
716 foreach ($keys as $key) {
718 $numeric_keys = false;
722 foreach ($jsonld as $part) {
723 if (!empty($part) && is_array($part)) {
724 $siteinfo = self::parseParts($siteinfo, $part);
730 array_walk_recursive($siteinfo, function (&$element) {
731 if (is_string($element)) {
732 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
740 * Improve the siteinfo with information from the provided JSON-LD information
741 * @see https://jsonld.com/
742 * @see https://schema.org/
744 * @param array $siteinfo
745 * @param array $jsonld
746 * @return array siteinfo
748 private static function parseJsonLd(array $siteinfo, array $jsonld)
750 $type = JsonLD::fetchElement($jsonld, '@type');
752 Logger::info('Empty type', ['url' => $siteinfo['url']]);
756 // Silently ignore some types that aren't processed
757 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
758 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
759 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
765 case 'AdvertiserContentArticle':
768 case 'SatiricalArticle':
769 case 'ScholarlyArticle':
770 case 'SocialMediaPosting':
772 case 'ReportageNewsArticle':
773 case 'SocialMediaPosting':
775 case 'LiveBlogPosting':
776 case 'DiscussionForumPosting':
777 return self::parseJsonLdArticle($siteinfo, $jsonld);
781 case 'CollectionPage':
785 case 'MedicalWebPage':
788 case 'RealEstateListing':
789 case 'SearchResultsPage':
795 return self::parseJsonLdWebPage($siteinfo, $jsonld);
797 return self::parseJsonLdWebSite($siteinfo, $jsonld);
802 case 'EducationalOrganization':
803 case 'FundingScheme':
804 case 'GovernmentOrganization':
805 case 'LibrarySystem':
806 case 'LocalBusiness':
807 case 'MedicalOrganization':
809 case 'NewsMediaOrganization':
811 case 'SportsOrganization':
813 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
816 case 'PerformingGroup':
820 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
823 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
825 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
827 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
829 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
835 * Fetch author and publisher data
837 * @param array $siteinfo
838 * @param array $jsonld
839 * @return array siteinfo
841 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
845 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
846 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
847 if (!empty($content) && is_string($content)) {
848 $jsonldinfo['publisher_name'] = trim($content);
851 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
852 if (!empty($content) && is_string($content)) {
853 $jsonldinfo['publisher_url'] = trim($content);
856 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
857 if (!empty($brand) && is_array($brand)) {
858 $content = JsonLD::fetchElement($brand, 'name');
859 if (!empty($content) && is_string($content)) {
860 $jsonldinfo['publisher_name'] = trim($content);
863 $content = JsonLD::fetchElement($brand, 'url');
864 if (!empty($content) && is_string($content)) {
865 $jsonldinfo['publisher_url'] = trim($content);
868 $content = JsonLD::fetchElement($brand, 'logo', 'url');
869 if (!empty($content) && is_string($content)) {
870 $jsonldinfo['publisher_img'] = trim($content);
874 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
875 if (!empty($logo) && is_array($logo)) {
876 $content = JsonLD::fetchElement($logo, 'url');
877 if (!empty($content) && is_string($content)) {
878 $jsonldinfo['publisher_img'] = trim($content);
881 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
882 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
885 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
886 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
887 if (!empty($content) && is_string($content)) {
888 $jsonldinfo['author_name'] = trim($content);
891 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
892 if (!empty($content) && is_string($content)) {
893 $jsonldinfo['author_url'] = trim($content);
896 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
897 if (!empty($content) && is_string($content)) {
898 $jsonldinfo['author_url'] = trim($content);
901 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
902 if (!empty($logo) && is_array($logo)) {
903 $content = JsonLD::fetchElement($logo, 'url');
904 if (!empty($content) && is_string($content)) {
905 $jsonldinfo['author_img'] = trim($content);
908 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
909 $jsonldinfo['author_name'] = trim($jsonld['author']);
912 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
914 return array_merge($siteinfo, $jsonldinfo);
918 * Fetch data from the provided JSON-LD Article type
919 * @see https://schema.org/Article
921 * @param array $siteinfo
922 * @param array $jsonld
923 * @return array siteinfo
925 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
929 $content = JsonLD::fetchElement($jsonld, 'headline');
930 if (!empty($content) && is_string($content)) {
931 $jsonldinfo['title'] = trim($content);
934 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
935 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
936 $jsonldinfo['alternative_title'] = trim($content);
939 $content = JsonLD::fetchElement($jsonld, 'description');
940 if (!empty($content) && is_string($content)) {
941 $jsonldinfo['text'] = trim($content);
944 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
945 if (!empty($content)) {
946 $jsonldinfo['image'] = trim($content);
949 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
950 if (!empty($content) && is_string($content)) {
951 $jsonldinfo['image'] = trim($content);
954 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
955 $content = JsonLD::fetchElement($jsonld, 'keywords');
956 if (!empty($content)) {
957 $siteinfo['keywords'] = [];
958 $keywords = explode(',', $content);
959 foreach ($keywords as $keyword) {
960 $siteinfo['keywords'][] = trim($keyword);
963 } elseif (!empty($jsonld['keywords'])) {
964 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
965 if (!empty($content) && is_array($content)) {
966 $jsonldinfo['keywords'] = $content;
970 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
972 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
974 return array_merge($siteinfo, $jsonldinfo);
978 * Fetch data from the provided JSON-LD WebPage type
979 * @see https://schema.org/WebPage
981 * @param array $siteinfo
982 * @param array $jsonld
983 * @return array siteinfo
985 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
989 $content = JsonLD::fetchElement($jsonld, 'name');
990 if (!empty($content)) {
991 $jsonldinfo['title'] = trim($content);
994 $content = JsonLD::fetchElement($jsonld, 'description');
995 if (!empty($content)) {
996 $jsonldinfo['text'] = trim($content);
999 $content = JsonLD::fetchElement($jsonld, 'image');
1000 if (!empty($content)) {
1001 $jsonldinfo['image'] = trim($content);
1004 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1005 if (!empty($content)) {
1006 $jsonldinfo['image'] = trim($content);
1009 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1011 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1013 return array_merge($siteinfo, $jsonldinfo);
1017 * Fetch data from the provided JSON-LD WebSite type
1018 * @see https://schema.org/WebSite
1020 * @param array $siteinfo
1021 * @param array $jsonld
1022 * @return array siteinfo
1024 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1028 $content = JsonLD::fetchElement($jsonld, 'name');
1029 if (!empty($content)) {
1030 $jsonldinfo['publisher_name'] = trim($content);
1033 $content = JsonLD::fetchElement($jsonld, 'description');
1034 if (!empty($content)) {
1035 $jsonldinfo['publisher_description'] = trim($content);
1038 $content = JsonLD::fetchElement($jsonld, 'url');
1039 if (!empty($content)) {
1040 $jsonldinfo['publisher_url'] = trim($content);
1043 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1044 if (!empty($content)) {
1045 $jsonldinfo['image'] = trim($content);
1048 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1050 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1051 return array_merge($siteinfo, $jsonldinfo);
1055 * Fetch data from the provided JSON-LD Organization type
1056 * @see https://schema.org/Organization
1058 * @param array $siteinfo
1059 * @param array $jsonld
1060 * @return array siteinfo
1062 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1066 $content = JsonLD::fetchElement($jsonld, 'name');
1067 if (!empty($content)) {
1068 $jsonldinfo['publisher_name'] = trim($content);
1071 $content = JsonLD::fetchElement($jsonld, 'description');
1072 if (!empty($content)) {
1073 $jsonldinfo['publisher_description'] = trim($content);
1076 $content = JsonLD::fetchElement($jsonld, 'url');
1077 if (!empty($content)) {
1078 $jsonldinfo['publisher_url'] = trim($content);
1081 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1082 if (!empty($content)) {
1083 $jsonldinfo['publisher_img'] = trim($content);
1086 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1087 if (!empty($content)) {
1088 $jsonldinfo['publisher_name'] = trim($content);
1091 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1092 if (!empty($content)) {
1093 $jsonldinfo['publisher_url'] = trim($content);
1096 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1097 return array_merge($siteinfo, $jsonldinfo);
1101 * Fetch data from the provided JSON-LD Person type
1102 * @see https://schema.org/Person
1104 * @param array $siteinfo
1105 * @param array $jsonld
1106 * @return array siteinfo
1108 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1112 $content = JsonLD::fetchElement($jsonld, 'name');
1113 if (!empty($content)) {
1114 $jsonldinfo['author_name'] = trim($content);
1117 $content = JsonLD::fetchElement($jsonld, 'description');
1118 if (!empty($content)) {
1119 $jsonldinfo['author_description'] = trim($content);
1122 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1123 if (!empty($content) && is_string($content)) {
1124 $jsonldinfo['author_url'] = trim($content);
1127 $content = JsonLD::fetchElement($jsonld, 'url');
1128 if (!empty($content)) {
1129 $jsonldinfo['author_url'] = trim($content);
1132 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1133 if (!empty($content) && !is_string($content)) {
1134 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1137 if (!empty($content) && is_string($content)) {
1138 $jsonldinfo['author_img'] = trim($content);
1141 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1142 return array_merge($siteinfo, $jsonldinfo);
1146 * Fetch data from the provided JSON-LD MediaObject type
1147 * @see https://schema.org/MediaObject
1149 * @param array $siteinfo
1150 * @param array $jsonld
1151 * @return array siteinfo
1153 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1157 $content = JsonLD::fetchElement($jsonld, 'caption');
1158 if (!empty($content)) {
1159 $media['caption'] = trim($content);
1162 $content = JsonLD::fetchElement($jsonld, 'url');
1163 if (!empty($content)) {
1164 $media['url'] = trim($content);
1167 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1168 if (!empty($content)) {
1169 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1172 $content = JsonLD::fetchElement($jsonld, 'description');
1173 if (!empty($content)) {
1174 $media['description'] = trim($content);
1177 $content = JsonLD::fetchElement($jsonld, 'name');
1178 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1179 $media['name'] = trim($content);
1182 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1183 if (!empty($content)) {
1184 $media['content'] = trim($content);
1187 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1188 if (!empty($content)) {
1189 $media['embed'] = trim($content);
1192 $content = JsonLD::fetchElement($jsonld, 'height');
1193 if (!empty($content)) {
1194 $media['height'] = trim($content);
1197 $content = JsonLD::fetchElement($jsonld, 'width');
1198 if (!empty($content)) {
1199 $media['width'] = trim($content);
1202 $content = JsonLD::fetchElement($jsonld, 'image');
1203 if (!empty($content)) {
1204 $media['image'] = trim($content);
1207 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1208 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1209 if (!empty($media['image'])) {
1210 $media['preview'] = trim($content);
1212 $media['image'] = trim($content);
1216 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1217 $siteinfo[$name][] = $media;