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
60 * @return array content type
62 public static function getContentType(string $url, string $accept = HttpClientAccept::DEFAULT)
64 $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => $accept]);
66 // Workaround for systems that can't handle a HEAD request
67 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
68 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::ACCEPT_CONTENT => $accept]);
71 if (!$curlResult->isSuccess()) {
75 $contenttype = $curlResult->getHeader('Content-Type')[0] ?? '';
76 if (empty($contenttype)) {
77 return ['application', 'octet-stream'];
80 return explode('/', current(explode(';', $contenttype)));
84 * Search for chached embeddable data of an url otherwise fetch it
86 * @param string $url The url of the page which should be scraped
87 * @param bool $do_oembed The false option is used by the function fetch_oembed()
88 * to avoid endless loops
90 * @return array which contains needed data for embedding
91 * string 'url' => The url of the parsed page
92 * string 'type' => Content type
93 * string 'title' => (optional) The title of the content
94 * string 'text' => (optional) The description for the content
95 * string 'image' => (optional) A preview image of the content
96 * array 'images' => (optional) Array of preview pictures
97 * string 'keywords' => (optional) The tags which belong to the content
99 * @throws HTTPException\InternalServerErrorException
100 * @see ParseUrl::getSiteinfo() for more information about scraping
103 public static function getSiteinfoCached($url, $do_oembed = true): array
112 $urlHash = hash('sha256', $url);
114 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
115 ['url_hash' => $urlHash, 'oembed' => $do_oembed]
117 if (!empty($parsed_url['content'])) {
118 $data = unserialize($parsed_url['content']);
122 $data = self::getSiteinfo($url, $do_oembed);
124 $expires = $data['expires'];
126 unset($data['expires']);
131 'url_hash' => $urlHash,
132 'oembed' => $do_oembed,
134 'content' => serialize($data),
135 'created' => DateTimeFormat::utcNow(),
136 'expires' => $expires,
138 Database::INSERT_UPDATE
145 * Parse a page for embeddable content information
147 * This method parses to url for meta data which can be used to embed
148 * the content. If available it prioritizes Open Graph meta tags.
149 * If this is not available it uses the twitter cards meta tags.
150 * As fallback it uses standard html elements with meta informations
151 * like \<title\>Awesome Title\</title\> or
152 * \<meta name="description" content="An awesome description"\>
154 * @param string $url The url of the page which should be scraped
155 * @param bool $do_oembed The false option is used by the function fetch_oembed()
156 * to avoid endless loops
157 * @param int $count Internal counter to avoid endless loops
159 * @return array which contains needed data for embedding
160 * string 'url' => The url of the parsed page
161 * string 'type' => Content type (error, link, photo, image, audio, video)
162 * string 'title' => (optional) The title of the content
163 * string 'text' => (optional) The description for the content
164 * string 'image' => (optional) A preview image of the content
165 * array 'images' => (optional) Array of preview pictures
166 * string 'keywords' => (optional) The tags which belong to the content
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 * @todo https://developers.google.com/+/plugins/snippet/
171 * <meta itemprop="name" content="Awesome title">
172 * <meta itemprop="description" content="An awesome description">
173 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
175 * <body itemscope itemtype="http://schema.org/Product">
176 * <h1 itemprop="name">Shiny Trinket</h1>
177 * <img itemprop="image" src="{image-url}" />
178 * <p itemprop="description">Shiny trinkets are shiny.</p>
182 public static function getSiteinfo($url, $do_oembed = true, $count = 1)
191 // Check if the URL does contain a scheme
192 $scheme = parse_url($url, PHP_URL_SCHEME);
195 $url = 'http://' . ltrim($url, '/');
198 $url = trim($url, "'\"");
200 $url = Network::stripTrackingQueryParams($url);
205 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
209 Logger::notice('Endless loop detected', ['url' => $url]);
213 $type = self::getContentType($url);
214 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
215 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
216 $siteinfo['type'] = $type[0];
220 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
221 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
225 $curlResult = DI::httpClient()->get($url, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::HTML]);
226 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
227 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
231 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
233 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
234 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
235 $maxAge = max(86400, (int)array_pop($matches));
236 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
240 $body = $curlResult->getBody();
243 $oembed_data = OEmbed::fetchURL($url, false, false);
245 if (!empty($oembed_data->type)) {
246 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
247 $siteinfo['type'] = $oembed_data->type;
250 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
251 if ($siteinfo['type'] != 'photo') {
252 if (!empty($oembed_data->title)) {
253 $siteinfo['title'] = trim($oembed_data->title);
255 if (!empty($oembed_data->description)) {
256 $siteinfo['text'] = trim($oembed_data->description);
258 if (!empty($oembed_data->author_name)) {
259 $siteinfo['author_name'] = trim($oembed_data->author_name);
261 if (!empty($oembed_data->author_url)) {
262 $siteinfo['author_url'] = trim($oembed_data->author_url);
264 if (!empty($oembed_data->provider_name)) {
265 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
267 if (!empty($oembed_data->provider_url)) {
268 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
270 if (!empty($oembed_data->thumbnail_url)) {
271 $siteinfo['image'] = $oembed_data->thumbnail_url;
278 // Look for a charset, first in headers
279 // Expected form: Content-Type: text/html; charset=ISO-8859-4
280 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
281 $charset = trim(trim(trim(array_pop($matches)), ';,'));
284 // Then in body that gets precedence
286 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
287 // - <meta charset="utf-8">
288 // - <meta charset=utf-8>
289 // - <meta charSet="utf-8">
290 // We escape <style> and <script> tags since they can contain irrelevant charset information
291 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
292 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
293 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
294 $charset = trim(trim(trim(array_pop($matches)), ';,'));
298 $siteinfo['charset'] = $charset;
300 if ($charset && strtoupper($charset) != 'UTF-8') {
301 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
302 $charset = str_ireplace('latin-1', 'latin1', $charset);
304 Logger::info('detected charset', ['charset' => $charset]);
305 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
308 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
310 $doc = new DOMDocument();
311 @$doc->loadHTML($body);
313 XML::deleteNode($doc, 'style');
314 XML::deleteNode($doc, 'option');
315 XML::deleteNode($doc, 'h1');
316 XML::deleteNode($doc, 'h2');
317 XML::deleteNode($doc, 'h3');
318 XML::deleteNode($doc, 'h4');
319 XML::deleteNode($doc, 'h5');
320 XML::deleteNode($doc, 'h6');
321 XML::deleteNode($doc, 'ol');
322 XML::deleteNode($doc, 'ul');
324 $xpath = new DOMXPath($doc);
326 $list = $xpath->query('//meta[@content]');
327 foreach ($list as $node) {
329 if ($node->attributes->length) {
330 foreach ($node->attributes as $attribute) {
331 $meta_tag[$attribute->name] = $attribute->value;
335 if (@$meta_tag['http-equiv'] == 'refresh') {
336 $path = $meta_tag['content'];
337 $pathinfo = explode(';', $path);
339 foreach ($pathinfo as $value) {
340 if (substr(strtolower($value), 0, 4) == 'url=') {
341 $content = substr($value, 4);
344 if ($content != '') {
345 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
351 $list = $xpath->query('//title');
352 if ($list->length > 0) {
353 $siteinfo['title'] = trim($list->item(0)->nodeValue);
356 $list = $xpath->query('//meta[@name]');
357 foreach ($list as $node) {
359 if ($node->attributes->length) {
360 foreach ($node->attributes as $attribute) {
361 $meta_tag[$attribute->name] = $attribute->value;
365 if (empty($meta_tag['content'])) {
369 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
371 switch (strtolower($meta_tag['name'])) {
373 $siteinfo['title'] = trim($meta_tag['content']);
376 $siteinfo['text'] = trim($meta_tag['content']);
379 $siteinfo['image'] = $meta_tag['content'];
381 case 'twitter:image':
382 $siteinfo['image'] = $meta_tag['content'];
384 case 'twitter:image:src':
385 $siteinfo['image'] = $meta_tag['content'];
387 case 'twitter:description':
388 $siteinfo['text'] = trim($meta_tag['content']);
390 case 'twitter:title':
391 $siteinfo['title'] = trim($meta_tag['content']);
393 case 'twitter:player':
394 $siteinfo['player']['embed'] = trim($meta_tag['content']);
396 case 'twitter:player:stream':
397 $siteinfo['player']['stream'] = trim($meta_tag['content']);
399 case 'twitter:player:width':
400 $siteinfo['player']['width'] = intval($meta_tag['content']);
402 case 'twitter:player:height':
403 $siteinfo['player']['height'] = intval($meta_tag['content']);
406 $siteinfo['title'] = trim($meta_tag['content']);
408 case 'dc.description':
409 $siteinfo['text'] = trim($meta_tag['content']);
412 $siteinfo['publisher_name'] = trim($meta_tag['content']);
415 $keywords = explode(',', $meta_tag['content']);
417 case 'news_keywords':
418 $keywords = explode(',', $meta_tag['content']);
423 if (isset($keywords)) {
424 $siteinfo['keywords'] = [];
425 foreach ($keywords as $keyword) {
426 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
427 $siteinfo['keywords'][] = trim($keyword);
432 $list = $xpath->query('//meta[@property]');
433 foreach ($list as $node) {
435 if ($node->attributes->length) {
436 foreach ($node->attributes as $attribute) {
437 $meta_tag[$attribute->name] = $attribute->value;
441 if (!empty($meta_tag['content'])) {
442 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
444 switch (strtolower($meta_tag['property'])) {
446 $siteinfo['image'] = $meta_tag['content'];
449 $siteinfo['image'] = $meta_tag['content'];
451 case 'og:image:secure_url':
452 $siteinfo['image'] = $meta_tag['content'];
455 $siteinfo['title'] = trim($meta_tag['content']);
457 case 'og:description':
458 $siteinfo['text'] = trim($meta_tag['content']);
461 $siteinfo['publisher_name'] = trim($meta_tag['content']);
464 $siteinfo['language'] = trim($meta_tag['content']);
467 $siteinfo['pagetype'] = trim($meta_tag['content']);
469 case 'twitter:description':
470 $siteinfo['text'] = trim($meta_tag['content']);
472 case 'twitter:title':
473 $siteinfo['title'] = trim($meta_tag['content']);
475 case 'twitter:image':
476 $siteinfo['image'] = $meta_tag['content'];
482 $list = $xpath->query("//script[@type='application/ld+json']");
483 foreach ($list as $node) {
484 if (!empty($node->nodeValue)) {
485 if ($jsonld = json_decode($node->nodeValue, true)) {
486 $siteinfo = self::parseParts($siteinfo, $jsonld);
491 if (!empty($siteinfo['player']['stream'])) {
492 // Only add player data to media arrays if there is no duplicate
493 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
494 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
495 $contenttype = self::getContentType($siteinfo['player']['stream']);
496 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
497 $media = ['content' => $siteinfo['player']['stream']];
499 if (!empty($siteinfo['player']['embed'])) {
500 $media['embed'] = $siteinfo['player']['embed'];
503 $siteinfo[$contenttype[0]][] = $media;
508 if (!empty($siteinfo['image'])) {
509 $siteinfo['images'] = $siteinfo['images'] ?? [];
510 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
511 unset($siteinfo['image']);
514 $siteinfo = self::checkMedia($url, $siteinfo);
516 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
517 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
518 $pos = mb_strrpos($siteinfo['text'], '.');
519 if ($pos > self::MIN_DESC_COUNT) {
520 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
524 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
526 Hook::callAll('getsiteinfo', $siteinfo);
534 * Check the attached media elements.
535 * Fix existing data and add missing data.
537 * @param string $page_url
538 * @param array $siteinfo
541 private static function checkMedia(string $page_url, array $siteinfo) : array
543 if (!empty($siteinfo['images'])) {
544 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
545 // According to the specifications someone could place a picture url into the content field as well.
546 // But this doesn't seem to happen in the wild, so we don't cover it here.
547 if (!empty($image['url'])) {
548 $image['url'] = self::completeUrl($image['url'], $page_url);
549 $photodata = Images::getInfoFromURLCached($image['url']);
550 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
551 $image['src'] = $image['url'];
552 $image['width'] = $photodata[0];
553 $image['height'] = $photodata[1];
554 $image['contenttype'] = $photodata['mime'];
555 unset($image['url']);
565 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
568 foreach (['audio', 'video'] as $element) {
569 if (!empty($siteinfo[$element])) {
570 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
575 foreach (['embed', 'content', 'url'] as $field) {
576 if (!empty($media[$field])) {
577 $media[$field] = self::completeUrl($media[$field], $page_url);
578 $type = self::getContentType($media[$field]);
579 if (($type[0] ?? '') == 'text') {
580 if ($field == 'embed') {
581 $embed = $media[$field];
583 $url = $media[$field];
585 } elseif (!empty($type[0])) {
586 $content = $media[$field];
587 $contenttype = implode('/', $type);
590 unset($media[$field]);
593 foreach (['image', 'preview'] as $field) {
594 if (!empty($media[$field])) {
595 $media[$field] = self::completeUrl($media[$field], $page_url);
600 $media['url'] = $url;
602 if (!empty($embed)) {
603 $media['embed'] = $embed;
604 if (empty($siteinfo['player']['embed'])) {
605 $siteinfo['player']['embed'] = $embed;
608 if (!empty($content)) {
609 $media['src'] = $content;
611 if (!empty($contenttype)) {
612 $media['contenttype'] = $contenttype;
614 if (empty($url) && empty($content) && empty($embed)) {
620 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
622 if (empty($siteinfo[$element])) {
623 unset($siteinfo[$element]);
630 * Convert tags from CSV to an array
632 * @param string $string Tags
633 * @return array with formatted Hashtags
635 public static function convertTagsToArray($string)
637 $arr_tags = str_getcsv($string);
638 if (count($arr_tags)) {
639 // add the # sign to every tag
640 array_walk($arr_tags, ["self", "arrAddHashes"]);
647 * Add a hasht sign to a string
649 * This method is used as callback function
651 * @param string $tag The pure tag name
652 * @param int $k Counter for internal use
655 private static function arrAddHashes(&$tag, $k)
661 * Add a scheme to an url
663 * The src attribute of some html elements (e.g. images)
664 * can miss the scheme so we need to add the correct
667 * @param string $url The url which possibly does have
668 * a missing scheme (a link to an image)
669 * @param string $scheme The url with a correct scheme
670 * (e.g. the url from the webpage which does contain the image)
672 * @return string The url with a scheme
674 private static function completeUrl($url, $scheme)
676 $urlarr = parse_url($url);
678 // If the url does allready have an scheme
679 // we can stop the process here
680 if (isset($urlarr["scheme"])) {
684 $schemearr = parse_url($scheme);
686 $complete = $schemearr["scheme"]."://".$schemearr["host"];
688 if (!empty($schemearr["port"])) {
689 $complete .= ":".$schemearr["port"];
692 if (!empty($urlarr["path"])) {
693 if (strpos($urlarr["path"], "/") !== 0) {
697 $complete .= $urlarr["path"];
700 if (!empty($urlarr["query"])) {
701 $complete .= "?".$urlarr["query"];
704 if (!empty($urlarr["fragment"])) {
705 $complete .= "#".$urlarr["fragment"];
712 * Parse the Json-Ld parts of a web page
714 * @param array $siteinfo
715 * @param array $jsonld
716 * @return array siteinfo
718 private static function parseParts(array $siteinfo, array $jsonld)
720 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
721 foreach ($jsonld['@graph'] as $part) {
722 if (!empty($part) && is_array($part)) {
723 $siteinfo = self::parseParts($siteinfo, $part);
726 } elseif (!empty($jsonld['@type'])) {
727 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
728 } elseif (!empty($jsonld)) {
729 $keys = array_keys($jsonld);
730 $numeric_keys = true;
731 foreach ($keys as $key) {
733 $numeric_keys = false;
737 foreach ($jsonld as $part) {
738 if (!empty($part) && is_array($part)) {
739 $siteinfo = self::parseParts($siteinfo, $part);
745 array_walk_recursive($siteinfo, function (&$element) {
746 if (is_string($element)) {
747 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
755 * Improve the siteinfo with information from the provided JSON-LD information
756 * @see https://jsonld.com/
757 * @see https://schema.org/
759 * @param array $siteinfo
760 * @param array $jsonld
761 * @return array siteinfo
763 private static function parseJsonLd(array $siteinfo, array $jsonld)
765 $type = JsonLD::fetchElement($jsonld, '@type');
767 Logger::info('Empty type', ['url' => $siteinfo['url']]);
771 // Silently ignore some types that aren't processed
772 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
773 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
774 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
780 case 'AdvertiserContentArticle':
783 case 'SatiricalArticle':
784 case 'ScholarlyArticle':
785 case 'SocialMediaPosting':
787 case 'ReportageNewsArticle':
788 case 'SocialMediaPosting':
790 case 'LiveBlogPosting':
791 case 'DiscussionForumPosting':
792 return self::parseJsonLdArticle($siteinfo, $jsonld);
796 case 'CollectionPage':
800 case 'MedicalWebPage':
803 case 'RealEstateListing':
804 case 'SearchResultsPage':
810 return self::parseJsonLdWebPage($siteinfo, $jsonld);
812 return self::parseJsonLdWebSite($siteinfo, $jsonld);
817 case 'EducationalOrganization':
818 case 'FundingScheme':
819 case 'GovernmentOrganization':
820 case 'LibrarySystem':
821 case 'LocalBusiness':
822 case 'MedicalOrganization':
824 case 'NewsMediaOrganization':
826 case 'SportsOrganization':
828 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
831 case 'PerformingGroup':
835 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
838 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
840 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
842 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
844 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
850 * Fetch author and publisher data
852 * @param array $siteinfo
853 * @param array $jsonld
854 * @return array siteinfo
856 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
860 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
861 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
862 if (!empty($content) && is_string($content)) {
863 $jsonldinfo['publisher_name'] = trim($content);
866 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
867 if (!empty($content) && is_string($content)) {
868 $jsonldinfo['publisher_url'] = trim($content);
871 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
872 if (!empty($brand) && is_array($brand)) {
873 $content = JsonLD::fetchElement($brand, 'name');
874 if (!empty($content) && is_string($content)) {
875 $jsonldinfo['publisher_name'] = trim($content);
878 $content = JsonLD::fetchElement($brand, 'url');
879 if (!empty($content) && is_string($content)) {
880 $jsonldinfo['publisher_url'] = trim($content);
883 $content = JsonLD::fetchElement($brand, 'logo', 'url');
884 if (!empty($content) && is_string($content)) {
885 $jsonldinfo['publisher_img'] = trim($content);
889 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
890 if (!empty($logo) && is_array($logo)) {
891 $content = JsonLD::fetchElement($logo, 'url');
892 if (!empty($content) && is_string($content)) {
893 $jsonldinfo['publisher_img'] = trim($content);
896 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
897 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
900 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
901 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
902 if (!empty($content) && is_string($content)) {
903 $jsonldinfo['author_name'] = trim($content);
906 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
907 if (!empty($content) && is_string($content)) {
908 $jsonldinfo['author_url'] = trim($content);
911 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
912 if (!empty($content) && is_string($content)) {
913 $jsonldinfo['author_url'] = trim($content);
916 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
917 if (!empty($logo) && is_array($logo)) {
918 $content = JsonLD::fetchElement($logo, 'url');
919 if (!empty($content) && is_string($content)) {
920 $jsonldinfo['author_img'] = trim($content);
923 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
924 $jsonldinfo['author_name'] = trim($jsonld['author']);
927 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
929 return array_merge($siteinfo, $jsonldinfo);
933 * Fetch data from the provided JSON-LD Article type
934 * @see https://schema.org/Article
936 * @param array $siteinfo
937 * @param array $jsonld
938 * @return array siteinfo
940 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
944 $content = JsonLD::fetchElement($jsonld, 'headline');
945 if (!empty($content) && is_string($content)) {
946 $jsonldinfo['title'] = trim($content);
949 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
950 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
951 $jsonldinfo['alternative_title'] = trim($content);
954 $content = JsonLD::fetchElement($jsonld, 'description');
955 if (!empty($content) && is_string($content)) {
956 $jsonldinfo['text'] = trim($content);
959 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
960 if (!empty($content)) {
961 $jsonldinfo['image'] = trim($content);
964 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
965 if (!empty($content) && is_string($content)) {
966 $jsonldinfo['image'] = trim($content);
969 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
970 $content = JsonLD::fetchElement($jsonld, 'keywords');
971 if (!empty($content)) {
972 $siteinfo['keywords'] = [];
973 $keywords = explode(',', $content);
974 foreach ($keywords as $keyword) {
975 $siteinfo['keywords'][] = trim($keyword);
978 } elseif (!empty($jsonld['keywords'])) {
979 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
980 if (!empty($content) && is_array($content)) {
981 $jsonldinfo['keywords'] = $content;
985 $content = JsonLD::fetchElement($jsonld, 'datePublished');
986 if (!empty($content) && is_string($content)) {
987 $jsonldinfo['published'] = DateTimeFormat::utc($content);
990 $content = JsonLD::fetchElement($jsonld, 'dateModified');
991 if (!empty($content) && is_string($content)) {
992 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
995 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
997 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
999 return array_merge($siteinfo, $jsonldinfo);
1003 * Fetch data from the provided JSON-LD WebPage type
1004 * @see https://schema.org/WebPage
1006 * @param array $siteinfo
1007 * @param array $jsonld
1008 * @return array siteinfo
1010 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
1014 $content = JsonLD::fetchElement($jsonld, 'name');
1015 if (!empty($content)) {
1016 $jsonldinfo['title'] = trim($content);
1019 $content = JsonLD::fetchElement($jsonld, 'description');
1020 if (!empty($content)) {
1021 $jsonldinfo['text'] = trim($content);
1024 $content = JsonLD::fetchElement($jsonld, 'image');
1025 if (!empty($content)) {
1026 $jsonldinfo['image'] = trim($content);
1029 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1030 if (!empty($content)) {
1031 $jsonldinfo['image'] = trim($content);
1034 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1036 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1038 return array_merge($siteinfo, $jsonldinfo);
1042 * Fetch data from the provided JSON-LD WebSite type
1043 * @see https://schema.org/WebSite
1045 * @param array $siteinfo
1046 * @param array $jsonld
1047 * @return array siteinfo
1049 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1053 $content = JsonLD::fetchElement($jsonld, 'name');
1054 if (!empty($content)) {
1055 $jsonldinfo['publisher_name'] = trim($content);
1058 $content = JsonLD::fetchElement($jsonld, 'description');
1059 if (!empty($content)) {
1060 $jsonldinfo['publisher_description'] = trim($content);
1063 $content = JsonLD::fetchElement($jsonld, 'url');
1064 if (!empty($content)) {
1065 $jsonldinfo['publisher_url'] = trim($content);
1068 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1069 if (!empty($content)) {
1070 $jsonldinfo['image'] = trim($content);
1073 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1075 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1076 return array_merge($siteinfo, $jsonldinfo);
1080 * Fetch data from the provided JSON-LD Organization type
1081 * @see https://schema.org/Organization
1083 * @param array $siteinfo
1084 * @param array $jsonld
1085 * @return array siteinfo
1087 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1091 $content = JsonLD::fetchElement($jsonld, 'name');
1092 if (!empty($content)) {
1093 $jsonldinfo['publisher_name'] = trim($content);
1096 $content = JsonLD::fetchElement($jsonld, 'description');
1097 if (!empty($content)) {
1098 $jsonldinfo['publisher_description'] = trim($content);
1101 $content = JsonLD::fetchElement($jsonld, 'url');
1102 if (!empty($content)) {
1103 $jsonldinfo['publisher_url'] = trim($content);
1106 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1107 if (!empty($content)) {
1108 $jsonldinfo['publisher_img'] = trim($content);
1111 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1112 if (!empty($content)) {
1113 $jsonldinfo['publisher_name'] = trim($content);
1116 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1117 if (!empty($content)) {
1118 $jsonldinfo['publisher_url'] = trim($content);
1121 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1122 return array_merge($siteinfo, $jsonldinfo);
1126 * Fetch data from the provided JSON-LD Person type
1127 * @see https://schema.org/Person
1129 * @param array $siteinfo
1130 * @param array $jsonld
1131 * @return array siteinfo
1133 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1137 $content = JsonLD::fetchElement($jsonld, 'name');
1138 if (!empty($content)) {
1139 $jsonldinfo['author_name'] = trim($content);
1142 $content = JsonLD::fetchElement($jsonld, 'description');
1143 if (!empty($content)) {
1144 $jsonldinfo['author_description'] = trim($content);
1147 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1148 if (!empty($content) && is_string($content)) {
1149 $jsonldinfo['author_url'] = trim($content);
1152 $content = JsonLD::fetchElement($jsonld, 'url');
1153 if (!empty($content)) {
1154 $jsonldinfo['author_url'] = trim($content);
1157 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1158 if (!empty($content) && !is_string($content)) {
1159 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1162 if (!empty($content) && is_string($content)) {
1163 $jsonldinfo['author_img'] = trim($content);
1166 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1167 return array_merge($siteinfo, $jsonldinfo);
1171 * Fetch data from the provided JSON-LD MediaObject type
1172 * @see https://schema.org/MediaObject
1174 * @param array $siteinfo
1175 * @param array $jsonld
1176 * @return array siteinfo
1178 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1182 $content = JsonLD::fetchElement($jsonld, 'caption');
1183 if (!empty($content)) {
1184 $media['caption'] = trim($content);
1187 $content = JsonLD::fetchElement($jsonld, 'url');
1188 if (!empty($content)) {
1189 $media['url'] = trim($content);
1192 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1193 if (!empty($content)) {
1194 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1197 $content = JsonLD::fetchElement($jsonld, 'description');
1198 if (!empty($content)) {
1199 $media['description'] = trim($content);
1202 $content = JsonLD::fetchElement($jsonld, 'name');
1203 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1204 $media['name'] = trim($content);
1207 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1208 if (!empty($content)) {
1209 $media['content'] = trim($content);
1212 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1213 if (!empty($content)) {
1214 $media['embed'] = trim($content);
1217 $content = JsonLD::fetchElement($jsonld, 'height');
1218 if (!empty($content)) {
1219 $media['height'] = trim($content);
1222 $content = JsonLD::fetchElement($jsonld, 'width');
1223 if (!empty($content)) {
1224 $media['width'] = trim($content);
1227 $content = JsonLD::fetchElement($jsonld, 'image');
1228 if (!empty($content)) {
1229 $media['image'] = trim($content);
1232 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1233 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1234 if (!empty($media['image'])) {
1235 $media['preview'] = trim($content);
1237 $media['image'] = trim($content);
1241 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1242 $siteinfo[$name][] = $media;