3 * @copyright Copyright (C) 2010-2022, 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\HTTPClient\Client\HttpClientAccept;
33 use Friendica\Network\HTTPException;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
37 * Get information about a given URL
39 * Class with methods for extracting certain content from an url
43 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
44 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
47 * Maximum number of characters for the description
49 const MAX_DESC_COUNT = 250;
52 * Minimum number of characters for the description
54 const MIN_DESC_COUNT = 100;
57 * Fetch the content type of the given url
58 * @param string $url URL of the page
59 * @param string $accept content-type to accept
61 * @return array content type
63 public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT, int $timeout = 0): array
65 if (!empty($timeout)) {
66 $options = [HttpClientOptions::TIMEOUT => $timeout];
71 $curlResult = DI::httpClient()->head($url, array_merge([HttpClientOptions::ACCEPT_CONTENT => $accept], $options));
73 // Workaround for systems that can't handle a HEAD request. Don't retry on timeouts.
74 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() >= 400) && !in_array($curlResult->getReturnCode(), [408, 504])) {
75 $curlResult = DI::httpClient()->get($url, $accept, array_merge([HttpClientOptions::CONTENT_LENGTH => 1000000], $options));
78 if (!$curlResult->isSuccess()) {
79 Logger::debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]);
83 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
84 if (empty($contenttype)) {
85 return ['application', 'octet-stream'];
88 return explode('/', current(explode(';', $contenttype)));
92 * Search for chached embeddable data of an url otherwise fetch it
94 * @param string $url The url of the page which should be scraped
95 * @param bool $do_oembed The false option is used by the function fetch_oembed()
96 * to avoid endless loops
98 * @return array which contains needed data for embedding
99 * string 'url' => The url of the parsed page
100 * string 'type' => Content type
101 * string 'title' => (optional) The title of the content
102 * string 'text' => (optional) The description for the content
103 * string 'image' => (optional) A preview image of the content
104 * array 'images' => (optional) Array of preview pictures
105 * string 'keywords' => (optional) The tags which belong to the content
107 * @throws HTTPException\InternalServerErrorException
108 * @see ParseUrl::getSiteinfo() for more information about scraping
111 public static function getSiteinfoCached(string $url, bool $do_oembed = true): array
120 $urlHash = hash('sha256', $url);
122 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
123 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
125 if (!empty($parsed_url['content'])) {
126 $data = unserialize($parsed_url['content']);
130 $data = self::getSiteinfo($url, $do_oembed);
132 $expires = $data['expires'];
134 unset($data['expires']);
139 'url_hash' => $urlHash,
140 'oembed' => $do_oembed,
142 'content' => serialize($data),
143 'created' => DateTimeFormat::utcNow(),
144 'expires' => $expires,
146 Database::INSERT_UPDATE
153 * Parse a page for embeddable content information
155 * This method parses to url for meta data which can be used to embed
156 * the content. If available it prioritizes Open Graph meta tags.
157 * If this is not available it uses the twitter cards meta tags.
158 * As fallback it uses standard html elements with meta informations
159 * like \<title\>Awesome Title\</title\> or
160 * \<meta name="description" content="An awesome description"\>
162 * @param string $url The url of the page which should be scraped
163 * @param bool $do_oembed The false option is used by the function fetch_oembed()
164 * to avoid endless loops
165 * @param int $count Internal counter to avoid endless loops
167 * @return array which contains needed data for embedding
168 * string 'url' => The url of the parsed page
169 * string 'type' => Content type (error, link, photo, image, audio, video)
170 * string 'title' => (optional) The title of the content
171 * string 'text' => (optional) The description for the content
172 * string 'image' => (optional) A preview image of the content
173 * array 'images' => (optional) Array of preview pictures
174 * string 'keywords' => (optional) The tags which belong to the content
176 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
177 * @todo https://developers.google.com/+/plugins/snippet/
179 * <meta itemprop="name" content="Awesome title">
180 * <meta itemprop="description" content="An awesome description">
181 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
183 * <body itemscope itemtype="http://schema.org/Product">
184 * <h1 itemprop="name">Shiny Trinket</h1>
185 * <img itemprop="image" src="{image-url}" />
186 * <p itemprop="description">Shiny trinkets are shiny.</p>
190 public static function getSiteinfo(string $url, bool $do_oembed = true, int $count = 1)
199 // Check if the URL does contain a scheme
200 $scheme = parse_url($url, PHP_URL_SCHEME);
203 $url = 'http://' . ltrim($url, '/');
206 $url = trim($url, "'\"");
208 $url = Network::stripTrackingQueryParams($url);
213 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
217 Logger::notice('Endless loop detected', ['url' => $url]);
221 $type = self::getContentType($url);
222 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
223 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
224 $siteinfo['type'] = $type[0];
228 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
229 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
233 $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000]);
234 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
235 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
239 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
241 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
242 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
243 $maxAge = max(86400, (int)array_pop($matches));
244 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
248 $body = $curlResult->getBody();
251 $oembed_data = OEmbed::fetchURL($url, false, false);
253 if (!empty($oembed_data->type)) {
254 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
255 $siteinfo['type'] = $oembed_data->type;
258 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
259 if ($siteinfo['type'] != 'photo') {
260 if (!empty($oembed_data->title)) {
261 $siteinfo['title'] = trim($oembed_data->title);
263 if (!empty($oembed_data->description)) {
264 $siteinfo['text'] = trim($oembed_data->description);
266 if (!empty($oembed_data->author_name)) {
267 $siteinfo['author_name'] = trim($oembed_data->author_name);
269 if (!empty($oembed_data->author_url)) {
270 $siteinfo['author_url'] = trim($oembed_data->author_url);
272 if (!empty($oembed_data->provider_name)) {
273 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
275 if (!empty($oembed_data->provider_url)) {
276 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
278 if (!empty($oembed_data->thumbnail_url)) {
279 $siteinfo['image'] = $oembed_data->thumbnail_url;
286 // Look for a charset, first in headers
287 // Expected form: Content-Type: text/html; charset=ISO-8859-4
288 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
289 $charset = trim(trim(trim(array_pop($matches)), ';,'));
292 // Then in body that gets precedence
294 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
295 // - <meta charset="utf-8">
296 // - <meta charset=utf-8>
297 // - <meta charSet="utf-8">
298 // We escape <style> and <script> tags since they can contain irrelevant charset information
299 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
300 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
301 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
302 $charset = trim(trim(trim(array_pop($matches)), ';,'));
306 $siteinfo['charset'] = $charset;
308 if ($charset && strtoupper($charset) != 'UTF-8') {
309 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
310 $charset = str_ireplace('latin-1', 'latin1', $charset);
312 Logger::info('detected charset', ['charset' => $charset]);
313 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
316 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
318 $doc = new DOMDocument();
319 @$doc->loadHTML($body);
321 XML::deleteNode($doc, 'style');
322 XML::deleteNode($doc, 'option');
323 XML::deleteNode($doc, 'h1');
324 XML::deleteNode($doc, 'h2');
325 XML::deleteNode($doc, 'h3');
326 XML::deleteNode($doc, 'h4');
327 XML::deleteNode($doc, 'h5');
328 XML::deleteNode($doc, 'h6');
329 XML::deleteNode($doc, 'ol');
330 XML::deleteNode($doc, 'ul');
332 $xpath = new DOMXPath($doc);
334 $list = $xpath->query('//meta[@content]');
335 foreach ($list as $node) {
337 if ($node->attributes->length) {
338 foreach ($node->attributes as $attribute) {
339 $meta_tag[$attribute->name] = $attribute->value;
343 if (@$meta_tag['http-equiv'] == 'refresh') {
344 $path = $meta_tag['content'];
345 $pathinfo = explode(';', $path);
347 foreach ($pathinfo as $value) {
348 if (substr(strtolower($value), 0, 4) == 'url=') {
349 $content = substr($value, 4);
352 if ($content != '') {
353 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
359 $list = $xpath->query('//title');
360 if ($list->length > 0) {
361 $siteinfo['title'] = trim($list->item(0)->nodeValue);
364 $list = $xpath->query('//meta[@name]');
365 foreach ($list as $node) {
367 if ($node->attributes->length) {
368 foreach ($node->attributes as $attribute) {
369 $meta_tag[$attribute->name] = $attribute->value;
373 if (empty($meta_tag['content'])) {
377 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
379 switch (strtolower($meta_tag['name'])) {
381 $siteinfo['title'] = trim($meta_tag['content']);
384 $siteinfo['text'] = trim($meta_tag['content']);
387 $siteinfo['image'] = $meta_tag['content'];
389 case 'twitter:image':
390 $siteinfo['image'] = $meta_tag['content'];
392 case 'twitter:image:src':
393 $siteinfo['image'] = $meta_tag['content'];
395 case 'twitter:description':
396 $siteinfo['text'] = trim($meta_tag['content']);
398 case 'twitter:title':
399 $siteinfo['title'] = trim($meta_tag['content']);
401 case 'twitter:player':
402 $siteinfo['player']['embed'] = trim($meta_tag['content']);
404 case 'twitter:player:stream':
405 $siteinfo['player']['stream'] = trim($meta_tag['content']);
407 case 'twitter:player:width':
408 $siteinfo['player']['width'] = intval($meta_tag['content']);
410 case 'twitter:player:height':
411 $siteinfo['player']['height'] = intval($meta_tag['content']);
414 $siteinfo['title'] = trim($meta_tag['content']);
416 case 'dc.description':
417 $siteinfo['text'] = trim($meta_tag['content']);
420 $siteinfo['publisher_name'] = trim($meta_tag['content']);
423 $keywords = explode(',', $meta_tag['content']);
425 case 'news_keywords':
426 $keywords = explode(',', $meta_tag['content']);
431 if (isset($keywords)) {
432 $siteinfo['keywords'] = [];
433 foreach ($keywords as $keyword) {
434 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
435 $siteinfo['keywords'][] = trim($keyword);
440 $list = $xpath->query('//meta[@property]');
441 foreach ($list as $node) {
443 if ($node->attributes->length) {
444 foreach ($node->attributes as $attribute) {
445 $meta_tag[$attribute->name] = $attribute->value;
449 if (!empty($meta_tag['content'])) {
450 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
452 switch (strtolower($meta_tag['property'])) {
454 $siteinfo['image'] = $meta_tag['content'];
457 $siteinfo['image'] = $meta_tag['content'];
459 case 'og:image:secure_url':
460 $siteinfo['image'] = $meta_tag['content'];
463 $siteinfo['title'] = trim($meta_tag['content']);
465 case 'og:description':
466 $siteinfo['text'] = trim($meta_tag['content']);
469 $siteinfo['publisher_name'] = trim($meta_tag['content']);
472 $siteinfo['language'] = trim($meta_tag['content']);
475 $siteinfo['pagetype'] = trim($meta_tag['content']);
477 case 'twitter:description':
478 $siteinfo['text'] = trim($meta_tag['content']);
480 case 'twitter:title':
481 $siteinfo['title'] = trim($meta_tag['content']);
483 case 'twitter:image':
484 $siteinfo['image'] = $meta_tag['content'];
490 $list = $xpath->query("//script[@type='application/ld+json']");
491 foreach ($list as $node) {
492 if (!empty($node->nodeValue)) {
493 if ($jsonld = json_decode($node->nodeValue, true)) {
494 $siteinfo = self::parseParts($siteinfo, $jsonld);
499 if (!empty($siteinfo['player']['stream'])) {
500 // Only add player data to media arrays if there is no duplicate
501 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
502 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
503 $contenttype = self::getContentType($siteinfo['player']['stream']);
504 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
505 $media = ['content' => $siteinfo['player']['stream']];
507 if (!empty($siteinfo['player']['embed'])) {
508 $media['embed'] = $siteinfo['player']['embed'];
511 $siteinfo[$contenttype[0]][] = $media;
516 if (!empty($siteinfo['image'])) {
517 $siteinfo['images'] = $siteinfo['images'] ?? [];
518 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
519 unset($siteinfo['image']);
522 $siteinfo = self::checkMedia($url, $siteinfo);
524 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
525 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
526 $pos = mb_strrpos($siteinfo['text'], '.');
527 if ($pos > self::MIN_DESC_COUNT) {
528 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
532 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
534 Hook::callAll('getsiteinfo', $siteinfo);
542 * Check the attached media elements.
543 * Fix existing data and add missing data.
545 * @param string $page_url
546 * @param array $siteinfo
549 private static function checkMedia(string $page_url, array $siteinfo) : array
551 if (!empty($siteinfo['images'])) {
552 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
554 * According to the specifications someone could place a picture
555 * URL into the content field as well. But this doesn't seem to
556 * happen in the wild, so we don't cover it here.
558 if (!empty($image['url'])) {
559 $image['url'] = self::completeUrl($image['url'], $page_url);
560 $photodata = Images::getInfoFromURLCached($image['url']);
561 if (($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
562 $image['src'] = $image['url'];
563 $image['width'] = $photodata[0];
564 $image['height'] = $photodata[1];
565 $image['contenttype'] = $photodata['mime'];
566 unset($image['url']);
576 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
579 foreach (['audio', 'video'] as $element) {
580 if (!empty($siteinfo[$element])) {
581 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
586 foreach (['embed', 'content', 'url'] as $field) {
587 if (!empty($media[$field])) {
588 $media[$field] = self::completeUrl($media[$field], $page_url);
589 $type = self::getContentType($media[$field]);
590 if (($type[0] ?? '') == 'text') {
591 if ($field == 'embed') {
592 $embed = $media[$field];
594 $url = $media[$field];
596 } elseif (!empty($type[0])) {
597 $content = $media[$field];
598 $contenttype = implode('/', $type);
601 unset($media[$field]);
604 foreach (['image', 'preview'] as $field) {
605 if (!empty($media[$field])) {
606 $media[$field] = self::completeUrl($media[$field], $page_url);
611 $media['url'] = $url;
613 if (!empty($embed)) {
614 $media['embed'] = $embed;
615 if (empty($siteinfo['player']['embed'])) {
616 $siteinfo['player']['embed'] = $embed;
619 if (!empty($content)) {
620 $media['src'] = $content;
622 if (!empty($contenttype)) {
623 $media['contenttype'] = $contenttype;
625 if (empty($url) && empty($content) && empty($embed)) {
631 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
633 if (empty($siteinfo[$element])) {
634 unset($siteinfo[$element]);
641 * Convert tags from CSV to an array
643 * @param string $string Tags
644 * @return array with formatted Hashtags
646 public static function convertTagsToArray(string $string): array
648 $arr_tags = str_getcsv($string);
649 if (count($arr_tags)) {
650 // add the # sign to every tag
651 array_walk($arr_tags, ['self', 'arrAddHashes']);
659 * Add a hasht sign to a string
661 * This method is used as callback function
663 * @param string $tag The pure tag name
664 * @param int $k Counter for internal use
667 private static function arrAddHashes(string &$tag, int $k)
673 * Add a scheme to an url
675 * The src attribute of some html elements (e.g. images)
676 * can miss the scheme so we need to add the correct
679 * @param string $url The url which possibly does have
680 * a missing scheme (a link to an image)
681 * @param string $scheme The url with a correct scheme
682 * (e.g. the url from the webpage which does contain the image)
684 * @return string The url with a scheme
686 private static function completeUrl(string $url, string $scheme): string
688 $urlarr = parse_url($url);
690 // If the url does allready have an scheme
691 // we can stop the process here
692 if (isset($urlarr['scheme'])) {
696 $schemearr = parse_url($scheme);
698 $complete = $schemearr['scheme'] . '://' . $schemearr['host'];
700 if (!empty($schemearr['port'])) {
701 $complete .= ':' . $schemearr['port'];
704 if (!empty($urlarr['path'])) {
705 if (strpos($urlarr['path'], '/') !== 0) {
709 $complete .= $urlarr['path'];
712 if (!empty($urlarr['query'])) {
713 $complete .= '?' . $urlarr['query'];
716 if (!empty($urlarr['fragment'])) {
717 $complete .= '#' . $urlarr['fragment'];
724 * Parse the Json-Ld parts of a web page
726 * @param array $siteinfo
727 * @param array $jsonld
728 * @return array siteinfo
730 private static function parseParts(array $siteinfo, array $jsonld): array
732 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
733 foreach ($jsonld['@graph'] as $part) {
734 if (!empty($part) && is_array($part)) {
735 $siteinfo = self::parseParts($siteinfo, $part);
738 } elseif (!empty($jsonld['@type'])) {
739 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
740 } elseif (!empty($jsonld)) {
741 $keys = array_keys($jsonld);
742 $numeric_keys = true;
743 foreach ($keys as $key) {
745 $numeric_keys = false;
749 foreach ($jsonld as $part) {
750 if (!empty($part) && is_array($part)) {
751 $siteinfo = self::parseParts($siteinfo, $part);
757 array_walk_recursive($siteinfo, function (&$element) {
758 if (is_string($element)) {
759 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
767 * Improve the siteinfo with information from the provided JSON-LD information
768 * @see https://jsonld.com/
769 * @see https://schema.org/
771 * @param array $siteinfo
772 * @param array $jsonld
773 * @return array siteinfo
775 private static function parseJsonLd(array $siteinfo, array $jsonld): array
777 $type = JsonLD::fetchElement($jsonld, '@type');
779 Logger::info('Empty type', ['url' => $siteinfo['url']]);
783 // Silently ignore some types that aren't processed
784 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
785 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
786 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
792 case 'AdvertiserContentArticle':
795 case 'SatiricalArticle':
796 case 'ScholarlyArticle':
797 case 'SocialMediaPosting':
799 case 'ReportageNewsArticle':
800 case 'SocialMediaPosting':
802 case 'LiveBlogPosting':
803 case 'DiscussionForumPosting':
804 return self::parseJsonLdArticle($siteinfo, $jsonld);
808 case 'CollectionPage':
812 case 'MedicalWebPage':
815 case 'RealEstateListing':
816 case 'SearchResultsPage':
822 return self::parseJsonLdWebPage($siteinfo, $jsonld);
824 return self::parseJsonLdWebSite($siteinfo, $jsonld);
829 case 'EducationalOrganization':
830 case 'FundingScheme':
831 case 'GovernmentOrganization':
832 case 'LibrarySystem':
833 case 'LocalBusiness':
834 case 'MedicalOrganization':
836 case 'NewsMediaOrganization':
838 case 'SportsOrganization':
840 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
843 case 'PerformingGroup':
847 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
850 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
852 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
854 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
856 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
862 * Fetch author and publisher data
864 * @param array $siteinfo
865 * @param array $jsonld
866 * @return array siteinfo
868 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld): array
872 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
873 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
874 if (!empty($content) && is_string($content)) {
875 $jsonldinfo['publisher_name'] = trim($content);
878 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
879 if (!empty($content) && is_string($content)) {
880 $jsonldinfo['publisher_url'] = trim($content);
883 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
884 if (!empty($brand) && is_array($brand)) {
885 $content = JsonLD::fetchElement($brand, 'name');
886 if (!empty($content) && is_string($content)) {
887 $jsonldinfo['publisher_name'] = trim($content);
890 $content = JsonLD::fetchElement($brand, 'url');
891 if (!empty($content) && is_string($content)) {
892 $jsonldinfo['publisher_url'] = trim($content);
895 $content = JsonLD::fetchElement($brand, 'logo', 'url');
896 if (!empty($content) && is_string($content)) {
897 $jsonldinfo['publisher_img'] = trim($content);
901 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
902 if (!empty($logo) && is_array($logo)) {
903 $content = JsonLD::fetchElement($logo, 'url');
904 if (!empty($content) && is_string($content)) {
905 $jsonldinfo['publisher_img'] = trim($content);
908 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
909 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
912 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
913 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
914 if (!empty($content) && is_string($content)) {
915 $jsonldinfo['author_name'] = trim($content);
918 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
919 if (!empty($content) && is_string($content)) {
920 $jsonldinfo['author_url'] = trim($content);
923 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
924 if (!empty($content) && is_string($content)) {
925 $jsonldinfo['author_url'] = trim($content);
928 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
929 if (!empty($logo) && is_array($logo)) {
930 $content = JsonLD::fetchElement($logo, 'url');
931 if (!empty($content) && is_string($content)) {
932 $jsonldinfo['author_img'] = trim($content);
935 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
936 $jsonldinfo['author_name'] = trim($jsonld['author']);
939 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
941 return array_merge($siteinfo, $jsonldinfo);
945 * Fetch data from the provided JSON-LD Article type
946 * @see https://schema.org/Article
948 * @param array $siteinfo
949 * @param array $jsonld
950 * @return array siteinfo
952 private static function parseJsonLdArticle(array $siteinfo, array $jsonld): array
956 $content = JsonLD::fetchElement($jsonld, 'headline');
957 if (!empty($content) && is_string($content)) {
958 $jsonldinfo['title'] = trim($content);
961 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
962 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
963 $jsonldinfo['alternative_title'] = trim($content);
966 $content = JsonLD::fetchElement($jsonld, 'description');
967 if (!empty($content) && is_string($content)) {
968 $jsonldinfo['text'] = trim($content);
971 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
972 if (!empty($content)) {
973 $jsonldinfo['image'] = trim($content);
976 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
977 if (!empty($content) && is_string($content)) {
978 $jsonldinfo['image'] = trim($content);
981 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
982 $content = JsonLD::fetchElement($jsonld, 'keywords');
983 if (!empty($content)) {
984 $siteinfo['keywords'] = [];
985 $keywords = explode(',', $content);
986 foreach ($keywords as $keyword) {
987 $siteinfo['keywords'][] = trim($keyword);
990 } elseif (!empty($jsonld['keywords'])) {
991 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
992 if (!empty($content) && is_array($content)) {
993 $jsonldinfo['keywords'] = $content;
997 $content = JsonLD::fetchElement($jsonld, 'datePublished');
998 if (!empty($content) && is_string($content)) {
999 $jsonldinfo['published'] = DateTimeFormat::utc($content);
1002 $content = JsonLD::fetchElement($jsonld, 'dateModified');
1003 if (!empty($content) && is_string($content)) {
1004 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
1007 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1009 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1011 return array_merge($siteinfo, $jsonldinfo);
1015 * Fetch data from the provided JSON-LD WebPage type
1016 * @see https://schema.org/WebPage
1018 * @param array $siteinfo
1019 * @param array $jsonld
1020 * @return array siteinfo
1022 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld): array
1026 $content = JsonLD::fetchElement($jsonld, 'name');
1027 if (!empty($content)) {
1028 $jsonldinfo['title'] = trim($content);
1031 $content = JsonLD::fetchElement($jsonld, 'description');
1032 if (!empty($content)) {
1033 $jsonldinfo['text'] = trim($content);
1036 $content = JsonLD::fetchElement($jsonld, 'image');
1037 if (!empty($content)) {
1038 $jsonldinfo['image'] = trim($content);
1041 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1042 if (!empty($content)) {
1043 $jsonldinfo['image'] = trim($content);
1046 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1048 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1050 return array_merge($siteinfo, $jsonldinfo);
1054 * Fetch data from the provided JSON-LD WebSite type
1055 * @see https://schema.org/WebSite
1057 * @param array $siteinfo
1058 * @param array $jsonld
1059 * @return array siteinfo
1061 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld): array
1065 $content = JsonLD::fetchElement($jsonld, 'name');
1066 if (!empty($content)) {
1067 $jsonldinfo['publisher_name'] = trim($content);
1070 $content = JsonLD::fetchElement($jsonld, 'description');
1071 if (!empty($content)) {
1072 $jsonldinfo['publisher_description'] = trim($content);
1075 $content = JsonLD::fetchElement($jsonld, 'url');
1076 if (!empty($content)) {
1077 $jsonldinfo['publisher_url'] = trim($content);
1080 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1081 if (!empty($content)) {
1082 $jsonldinfo['image'] = trim($content);
1085 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1087 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1088 return array_merge($siteinfo, $jsonldinfo);
1092 * Fetch data from the provided JSON-LD Organization type
1093 * @see https://schema.org/Organization
1095 * @param array $siteinfo
1096 * @param array $jsonld
1097 * @return array siteinfo
1099 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld): array
1103 $content = JsonLD::fetchElement($jsonld, 'name');
1104 if (!empty($content)) {
1105 $jsonldinfo['publisher_name'] = trim($content);
1108 $content = JsonLD::fetchElement($jsonld, 'description');
1109 if (!empty($content)) {
1110 $jsonldinfo['publisher_description'] = trim($content);
1113 $content = JsonLD::fetchElement($jsonld, 'url');
1114 if (!empty($content)) {
1115 $jsonldinfo['publisher_url'] = trim($content);
1118 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1119 if (!empty($content)) {
1120 $jsonldinfo['publisher_img'] = trim($content);
1123 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1124 if (!empty($content)) {
1125 $jsonldinfo['publisher_name'] = trim($content);
1128 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1129 if (!empty($content)) {
1130 $jsonldinfo['publisher_url'] = trim($content);
1133 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1134 return array_merge($siteinfo, $jsonldinfo);
1138 * Fetch data from the provided JSON-LD Person type
1139 * @see https://schema.org/Person
1141 * @param array $siteinfo
1142 * @param array $jsonld
1143 * @return array siteinfo
1145 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld): array
1149 $content = JsonLD::fetchElement($jsonld, 'name');
1150 if (!empty($content)) {
1151 $jsonldinfo['author_name'] = trim($content);
1154 $content = JsonLD::fetchElement($jsonld, 'description');
1155 if (!empty($content)) {
1156 $jsonldinfo['author_description'] = trim($content);
1159 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1160 if (!empty($content) && is_string($content)) {
1161 $jsonldinfo['author_url'] = trim($content);
1164 $content = JsonLD::fetchElement($jsonld, 'url');
1165 if (!empty($content)) {
1166 $jsonldinfo['author_url'] = trim($content);
1169 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1170 if (!empty($content) && !is_string($content)) {
1171 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1174 if (!empty($content) && is_string($content)) {
1175 $jsonldinfo['author_img'] = trim($content);
1178 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1179 return array_merge($siteinfo, $jsonldinfo);
1183 * Fetch data from the provided JSON-LD MediaObject type
1184 * @see https://schema.org/MediaObject
1186 * @param array $siteinfo
1187 * @param array $jsonld
1188 * @return array siteinfo
1190 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name): array
1194 $content = JsonLD::fetchElement($jsonld, 'caption');
1195 if (!empty($content)) {
1196 $media['caption'] = trim($content);
1199 $content = JsonLD::fetchElement($jsonld, 'url');
1200 if (!empty($content)) {
1201 $media['url'] = trim($content);
1204 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1205 if (!empty($content)) {
1206 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1209 $content = JsonLD::fetchElement($jsonld, 'description');
1210 if (!empty($content)) {
1211 $media['description'] = trim($content);
1214 $content = JsonLD::fetchElement($jsonld, 'name');
1215 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1216 $media['name'] = trim($content);
1219 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1220 if (!empty($content)) {
1221 $media['content'] = trim($content);
1224 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1225 if (!empty($content)) {
1226 $media['embed'] = trim($content);
1229 $content = JsonLD::fetchElement($jsonld, 'height');
1230 if (!empty($content)) {
1231 $media['height'] = trim($content);
1234 $content = JsonLD::fetchElement($jsonld, 'width');
1235 if (!empty($content)) {
1236 $media['width'] = trim($content);
1239 $content = JsonLD::fetchElement($jsonld, 'image');
1240 if (!empty($content)) {
1241 $media['image'] = trim($content);
1244 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1245 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1246 if (!empty($media['image'])) {
1247 $media['preview'] = trim($content);
1249 $media['image'] = trim($content);
1253 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1254 $siteinfo[$name][] = $media;