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\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())) {
219 Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
223 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
225 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') {
226 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
227 $maxAge = max(86400, (int)array_pop($matches));
228 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
232 $body = $curlResult->getBody();
235 $oembed_data = OEmbed::fetchURL($url, false, false);
237 if (!empty($oembed_data->type)) {
238 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
239 $siteinfo['type'] = $oembed_data->type;
242 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
243 if ($siteinfo['type'] != 'photo') {
244 if (!empty($oembed_data->title)) {
245 $siteinfo['title'] = trim($oembed_data->title);
247 if (!empty($oembed_data->description)) {
248 $siteinfo['text'] = trim($oembed_data->description);
250 if (!empty($oembed_data->author_name)) {
251 $siteinfo['author_name'] = trim($oembed_data->author_name);
253 if (!empty($oembed_data->author_url)) {
254 $siteinfo['author_url'] = trim($oembed_data->author_url);
256 if (!empty($oembed_data->provider_name)) {
257 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
259 if (!empty($oembed_data->provider_url)) {
260 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
262 if (!empty($oembed_data->thumbnail_url)) {
263 $siteinfo['image'] = $oembed_data->thumbnail_url;
270 // Look for a charset, first in headers
271 // Expected form: Content-Type: text/html; charset=ISO-8859-4
272 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $curlResult->getContentType(), $matches)) {
273 $charset = trim(trim(trim(array_pop($matches)), ';,'));
276 // Then in body that gets precedence
278 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
279 // - <meta charset="utf-8">
280 // - <meta charset=utf-8>
281 // - <meta charSet="utf-8">
282 // We escape <style> and <script> tags since they can contain irrelevant charset information
283 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
284 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
285 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
286 $charset = trim(trim(trim(array_pop($matches)), ';,'));
290 $siteinfo['charset'] = $charset;
292 if ($charset && strtoupper($charset) != 'UTF-8') {
293 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
294 $charset = str_ireplace('latin-1', 'latin1', $charset);
296 Logger::info('detected charset', ['charset' => $charset]);
297 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
300 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
302 $doc = new DOMDocument();
303 @$doc->loadHTML($body);
305 XML::deleteNode($doc, 'style');
306 XML::deleteNode($doc, 'option');
307 XML::deleteNode($doc, 'h1');
308 XML::deleteNode($doc, 'h2');
309 XML::deleteNode($doc, 'h3');
310 XML::deleteNode($doc, 'h4');
311 XML::deleteNode($doc, 'h5');
312 XML::deleteNode($doc, 'h6');
313 XML::deleteNode($doc, 'ol');
314 XML::deleteNode($doc, 'ul');
316 $xpath = new DOMXPath($doc);
318 $list = $xpath->query('//meta[@content]');
319 foreach ($list as $node) {
321 if ($node->attributes->length) {
322 foreach ($node->attributes as $attribute) {
323 $meta_tag[$attribute->name] = $attribute->value;
327 if (@$meta_tag['http-equiv'] == 'refresh') {
328 $path = $meta_tag['content'];
329 $pathinfo = explode(';', $path);
331 foreach ($pathinfo as $value) {
332 if (substr(strtolower($value), 0, 4) == 'url=') {
333 $content = substr($value, 4);
336 if ($content != '') {
337 $siteinfo = self::getSiteinfo($content, $do_oembed, ++$count);
343 $list = $xpath->query('//title');
344 if ($list->length > 0) {
345 $siteinfo['title'] = trim($list->item(0)->nodeValue);
348 $list = $xpath->query('//meta[@name]');
349 foreach ($list as $node) {
351 if ($node->attributes->length) {
352 foreach ($node->attributes as $attribute) {
353 $meta_tag[$attribute->name] = $attribute->value;
357 if (empty($meta_tag['content'])) {
361 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
363 switch (strtolower($meta_tag['name'])) {
365 $siteinfo['title'] = trim($meta_tag['content']);
368 $siteinfo['text'] = trim($meta_tag['content']);
371 $siteinfo['image'] = $meta_tag['content'];
373 case 'twitter:image':
374 $siteinfo['image'] = $meta_tag['content'];
376 case 'twitter:image:src':
377 $siteinfo['image'] = $meta_tag['content'];
379 case 'twitter:description':
380 $siteinfo['text'] = trim($meta_tag['content']);
382 case 'twitter:title':
383 $siteinfo['title'] = trim($meta_tag['content']);
385 case 'twitter:player':
386 $siteinfo['player']['embed'] = trim($meta_tag['content']);
388 case 'twitter:player:stream':
389 $siteinfo['player']['stream'] = trim($meta_tag['content']);
391 case 'twitter:player:width':
392 $siteinfo['player']['width'] = intval($meta_tag['content']);
394 case 'twitter:player:height':
395 $siteinfo['player']['height'] = intval($meta_tag['content']);
398 $siteinfo['title'] = trim($meta_tag['content']);
400 case 'dc.description':
401 $siteinfo['text'] = trim($meta_tag['content']);
404 $siteinfo['publisher_name'] = trim($meta_tag['content']);
407 $keywords = explode(',', $meta_tag['content']);
409 case 'news_keywords':
410 $keywords = explode(',', $meta_tag['content']);
415 if (isset($keywords)) {
416 $siteinfo['keywords'] = [];
417 foreach ($keywords as $keyword) {
418 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
419 $siteinfo['keywords'][] = trim($keyword);
424 $list = $xpath->query('//meta[@property]');
425 foreach ($list as $node) {
427 if ($node->attributes->length) {
428 foreach ($node->attributes as $attribute) {
429 $meta_tag[$attribute->name] = $attribute->value;
433 if (!empty($meta_tag['content'])) {
434 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
436 switch (strtolower($meta_tag['property'])) {
438 $siteinfo['image'] = $meta_tag['content'];
441 $siteinfo['image'] = $meta_tag['content'];
443 case 'og:image:secure_url':
444 $siteinfo['image'] = $meta_tag['content'];
447 $siteinfo['title'] = trim($meta_tag['content']);
449 case 'og:description':
450 $siteinfo['text'] = trim($meta_tag['content']);
453 $siteinfo['publisher_name'] = trim($meta_tag['content']);
456 $siteinfo['language'] = trim($meta_tag['content']);
459 $siteinfo['pagetype'] = trim($meta_tag['content']);
461 case 'twitter:description':
462 $siteinfo['text'] = trim($meta_tag['content']);
464 case 'twitter:title':
465 $siteinfo['title'] = trim($meta_tag['content']);
467 case 'twitter:image':
468 $siteinfo['image'] = $meta_tag['content'];
474 $list = $xpath->query("//script[@type='application/ld+json']");
475 foreach ($list as $node) {
476 if (!empty($node->nodeValue)) {
477 if ($jsonld = json_decode($node->nodeValue, true)) {
478 $siteinfo = self::parseParts($siteinfo, $jsonld);
483 if (!empty($siteinfo['player']['stream'])) {
484 // Only add player data to media arrays if there is no duplicate
485 $content_urls = array_merge(array_column($siteinfo['audio'] ?? [], 'content'), array_column($siteinfo['video'] ?? [], 'content'));
486 if (!in_array($siteinfo['player']['stream'], $content_urls)) {
487 $contenttype = self::getContentType($siteinfo['player']['stream']);
488 if (!empty($contenttype[0]) && in_array($contenttype[0], ['audio', 'video'])) {
489 $media = ['content' => $siteinfo['player']['stream']];
491 if (!empty($siteinfo['player']['embed'])) {
492 $media['embed'] = $siteinfo['player']['embed'];
495 $siteinfo[$contenttype[0]][] = $media;
500 if (!empty($siteinfo['image'])) {
501 $siteinfo['images'] = $siteinfo['images'] ?? [];
502 array_unshift($siteinfo['images'], ['url' => $siteinfo['image']]);
503 unset($siteinfo['image']);
506 $siteinfo = self::checkMedia($url, $siteinfo);
508 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
509 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
510 $pos = mb_strrpos($siteinfo['text'], '.');
511 if ($pos > self::MIN_DESC_COUNT) {
512 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
516 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
518 Hook::callAll('getsiteinfo', $siteinfo);
526 * Check the attached media elements.
527 * Fix existing data and add missing data.
529 * @param string $page_url
530 * @param array $siteinfo
533 private static function checkMedia(string $page_url, array $siteinfo) : array
535 if (!empty($siteinfo['images'])) {
536 array_walk($siteinfo['images'], function (&$image) use ($page_url) {
537 // According to the specifications someone could place a picture url into the content field as well.
538 // But this doesn't seem to happen in the wild, so we don't cover it here.
539 if (!empty($image['url'])) {
540 $image['url'] = self::completeUrl($image['url'], $page_url);
541 $photodata = Images::getInfoFromURLCached($image['url']);
542 if (!empty($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) {
543 $image['src'] = $image['url'];
544 $image['width'] = $photodata[0];
545 $image['height'] = $photodata[1];
546 $image['contenttype'] = $photodata['mime'];
547 unset($image['url']);
557 $siteinfo['images'] = array_values(array_filter($siteinfo['images']));
560 foreach (['audio', 'video'] as $element) {
561 if (!empty($siteinfo[$element])) {
562 array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) {
567 foreach (['embed', 'content', 'url'] as $field) {
568 if (!empty($media[$field])) {
569 $media[$field] = self::completeUrl($media[$field], $page_url);
570 $type = self::getContentType($media[$field]);
571 if (($type[0] ?? '') == 'text') {
572 if ($field == 'embed') {
573 $embed = $media[$field];
575 $url = $media[$field];
577 } elseif (!empty($type[0])) {
578 $content = $media[$field];
579 $contenttype = implode('/', $type);
582 unset($media[$field]);
585 foreach (['image', 'preview'] as $field) {
586 if (!empty($media[$field])) {
587 $media[$field] = self::completeUrl($media[$field], $page_url);
592 $media['url'] = $url;
594 if (!empty($embed)) {
595 $media['embed'] = $embed;
596 if (empty($siteinfo['player']['embed'])) {
597 $siteinfo['player']['embed'] = $embed;
600 if (!empty($content)) {
601 $media['src'] = $content;
603 if (!empty($contenttype)) {
604 $media['contenttype'] = $contenttype;
606 if (empty($url) && empty($content) && empty($embed)) {
612 $siteinfo[$element] = array_values(array_filter($siteinfo[$element]));
614 if (empty($siteinfo[$element])) {
615 unset($siteinfo[$element]);
622 * Convert tags from CSV to an array
624 * @param string $string Tags
625 * @return array with formatted Hashtags
627 public static function convertTagsToArray($string)
629 $arr_tags = str_getcsv($string);
630 if (count($arr_tags)) {
631 // add the # sign to every tag
632 array_walk($arr_tags, ["self", "arrAddHashes"]);
639 * Add a hasht sign to a string
641 * This method is used as callback function
643 * @param string $tag The pure tag name
644 * @param int $k Counter for internal use
647 private static function arrAddHashes(&$tag, $k)
653 * Add a scheme to an url
655 * The src attribute of some html elements (e.g. images)
656 * can miss the scheme so we need to add the correct
659 * @param string $url The url which possibly does have
660 * a missing scheme (a link to an image)
661 * @param string $scheme The url with a correct scheme
662 * (e.g. the url from the webpage which does contain the image)
664 * @return string The url with a scheme
666 private static function completeUrl($url, $scheme)
668 $urlarr = parse_url($url);
670 // If the url does allready have an scheme
671 // we can stop the process here
672 if (isset($urlarr["scheme"])) {
676 $schemearr = parse_url($scheme);
678 $complete = $schemearr["scheme"]."://".$schemearr["host"];
680 if (!empty($schemearr["port"])) {
681 $complete .= ":".$schemearr["port"];
684 if (!empty($urlarr["path"])) {
685 if (strpos($urlarr["path"], "/") !== 0) {
689 $complete .= $urlarr["path"];
692 if (!empty($urlarr["query"])) {
693 $complete .= "?".$urlarr["query"];
696 if (!empty($urlarr["fragment"])) {
697 $complete .= "#".$urlarr["fragment"];
704 * Parse the Json-Ld parts of a web page
706 * @param array $siteinfo
707 * @param array $jsonld
708 * @return array siteinfo
710 private static function parseParts(array $siteinfo, array $jsonld)
712 if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
713 foreach ($jsonld['@graph'] as $part) {
714 if (!empty($part) && is_array($part)) {
715 $siteinfo = self::parseParts($siteinfo, $part);
718 } elseif (!empty($jsonld['@type'])) {
719 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
720 } elseif (!empty($jsonld)) {
721 $keys = array_keys($jsonld);
722 $numeric_keys = true;
723 foreach ($keys as $key) {
725 $numeric_keys = false;
729 foreach ($jsonld as $part) {
730 if (!empty($part) && is_array($part)) {
731 $siteinfo = self::parseParts($siteinfo, $part);
737 array_walk_recursive($siteinfo, function (&$element) {
738 if (is_string($element)) {
739 $element = trim(strip_tags(html_entity_decode($element, ENT_COMPAT, 'UTF-8')));
747 * Improve the siteinfo with information from the provided JSON-LD information
748 * @see https://jsonld.com/
749 * @see https://schema.org/
751 * @param array $siteinfo
752 * @param array $jsonld
753 * @return array siteinfo
755 private static function parseJsonLd(array $siteinfo, array $jsonld)
757 $type = JsonLD::fetchElement($jsonld, '@type');
759 Logger::info('Empty type', ['url' => $siteinfo['url']]);
763 // Silently ignore some types that aren't processed
764 if (in_array($type, ['SiteNavigationElement', 'JobPosting', 'CreativeWork', 'MusicAlbum',
765 'WPHeader', 'WPSideBar', 'WPFooter', 'LegalService', 'MusicRecording',
766 'ItemList', 'BreadcrumbList', 'Blog', 'Dataset', 'Product'])) {
772 case 'AdvertiserContentArticle':
775 case 'SatiricalArticle':
776 case 'ScholarlyArticle':
777 case 'SocialMediaPosting':
779 case 'ReportageNewsArticle':
780 case 'SocialMediaPosting':
782 case 'LiveBlogPosting':
783 case 'DiscussionForumPosting':
784 return self::parseJsonLdArticle($siteinfo, $jsonld);
788 case 'CollectionPage':
792 case 'MedicalWebPage':
795 case 'RealEstateListing':
796 case 'SearchResultsPage':
802 return self::parseJsonLdWebPage($siteinfo, $jsonld);
804 return self::parseJsonLdWebSite($siteinfo, $jsonld);
809 case 'EducationalOrganization':
810 case 'FundingScheme':
811 case 'GovernmentOrganization':
812 case 'LibrarySystem':
813 case 'LocalBusiness':
814 case 'MedicalOrganization':
816 case 'NewsMediaOrganization':
818 case 'SportsOrganization':
820 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
823 case 'PerformingGroup':
827 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
830 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'audio');
832 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'video');
834 return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
836 Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
842 * Fetch author and publisher data
844 * @param array $siteinfo
845 * @param array $jsonld
846 * @return array siteinfo
848 private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
852 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
853 $content = JsonLD::fetchElement($jsonld, 'publisher', 'name');
854 if (!empty($content) && is_string($content)) {
855 $jsonldinfo['publisher_name'] = trim($content);
858 $content = JsonLD::fetchElement($jsonld, 'publisher', 'url');
859 if (!empty($content) && is_string($content)) {
860 $jsonldinfo['publisher_url'] = trim($content);
863 $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
864 if (!empty($brand) && is_array($brand)) {
865 $content = JsonLD::fetchElement($brand, 'name');
866 if (!empty($content) && is_string($content)) {
867 $jsonldinfo['publisher_name'] = trim($content);
870 $content = JsonLD::fetchElement($brand, 'url');
871 if (!empty($content) && is_string($content)) {
872 $jsonldinfo['publisher_url'] = trim($content);
875 $content = JsonLD::fetchElement($brand, 'logo', 'url');
876 if (!empty($content) && is_string($content)) {
877 $jsonldinfo['publisher_img'] = trim($content);
881 $logo = JsonLD::fetchElement($jsonld, 'publisher', 'logo');
882 if (!empty($logo) && is_array($logo)) {
883 $content = JsonLD::fetchElement($logo, 'url');
884 if (!empty($content) && is_string($content)) {
885 $jsonldinfo['publisher_img'] = trim($content);
888 } elseif (!empty($jsonld['publisher']) && is_string($jsonld['publisher'])) {
889 $jsonldinfo['publisher_name'] = trim($jsonld['publisher']);
892 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
893 $content = JsonLD::fetchElement($jsonld, 'author', 'name');
894 if (!empty($content) && is_string($content)) {
895 $jsonldinfo['author_name'] = trim($content);
898 $content = JsonLD::fetchElement($jsonld, 'author', 'sameAs');
899 if (!empty($content) && is_string($content)) {
900 $jsonldinfo['author_url'] = trim($content);
903 $content = JsonLD::fetchElement($jsonld, 'author', 'url');
904 if (!empty($content) && is_string($content)) {
905 $jsonldinfo['author_url'] = trim($content);
908 $logo = JsonLD::fetchElement($jsonld, 'author', 'logo');
909 if (!empty($logo) && is_array($logo)) {
910 $content = JsonLD::fetchElement($logo, 'url');
911 if (!empty($content) && is_string($content)) {
912 $jsonldinfo['author_img'] = trim($content);
915 } elseif (!empty($jsonld['author']) && is_string($jsonld['author'])) {
916 $jsonldinfo['author_name'] = trim($jsonld['author']);
919 Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]);
921 return array_merge($siteinfo, $jsonldinfo);
925 * Fetch data from the provided JSON-LD Article type
926 * @see https://schema.org/Article
928 * @param array $siteinfo
929 * @param array $jsonld
930 * @return array siteinfo
932 private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
936 $content = JsonLD::fetchElement($jsonld, 'headline');
937 if (!empty($content) && is_string($content)) {
938 $jsonldinfo['title'] = trim($content);
941 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
942 if (!empty($content) && is_string($content) && (($jsonldinfo['title'] ?? '') != trim($content))) {
943 $jsonldinfo['alternative_title'] = trim($content);
946 $content = JsonLD::fetchElement($jsonld, 'description');
947 if (!empty($content) && is_string($content)) {
948 $jsonldinfo['text'] = trim($content);
951 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
952 if (!empty($content)) {
953 $jsonldinfo['image'] = trim($content);
956 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
957 if (!empty($content) && is_string($content)) {
958 $jsonldinfo['image'] = trim($content);
961 if (!empty($jsonld['keywords']) && !is_array($jsonld['keywords'])) {
962 $content = JsonLD::fetchElement($jsonld, 'keywords');
963 if (!empty($content)) {
964 $siteinfo['keywords'] = [];
965 $keywords = explode(',', $content);
966 foreach ($keywords as $keyword) {
967 $siteinfo['keywords'][] = trim($keyword);
970 } elseif (!empty($jsonld['keywords'])) {
971 $content = JsonLD::fetchElementArray($jsonld, 'keywords');
972 if (!empty($content) && is_array($content)) {
973 $jsonldinfo['keywords'] = $content;
977 $content = JsonLD::fetchElement($jsonld, 'datePublished');
978 if (!empty($content) && is_string($content)) {
979 $jsonldinfo['published'] = DateTimeFormat::utc($content);
982 $content = JsonLD::fetchElement($jsonld, 'dateModified');
983 if (!empty($content) && is_string($content)) {
984 $jsonldinfo['modified'] = DateTimeFormat::utc($content);
987 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
989 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
991 return array_merge($siteinfo, $jsonldinfo);
995 * Fetch data from the provided JSON-LD WebPage type
996 * @see https://schema.org/WebPage
998 * @param array $siteinfo
999 * @param array $jsonld
1000 * @return array siteinfo
1002 private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
1006 $content = JsonLD::fetchElement($jsonld, 'name');
1007 if (!empty($content)) {
1008 $jsonldinfo['title'] = trim($content);
1011 $content = JsonLD::fetchElement($jsonld, 'description');
1012 if (!empty($content)) {
1013 $jsonldinfo['text'] = trim($content);
1016 $content = JsonLD::fetchElement($jsonld, 'image');
1017 if (!empty($content)) {
1018 $jsonldinfo['image'] = trim($content);
1021 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1022 if (!empty($content)) {
1023 $jsonldinfo['image'] = trim($content);
1026 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1028 Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1030 return array_merge($siteinfo, $jsonldinfo);
1034 * Fetch data from the provided JSON-LD WebSite type
1035 * @see https://schema.org/WebSite
1037 * @param array $siteinfo
1038 * @param array $jsonld
1039 * @return array siteinfo
1041 private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
1045 $content = JsonLD::fetchElement($jsonld, 'name');
1046 if (!empty($content)) {
1047 $jsonldinfo['publisher_name'] = trim($content);
1050 $content = JsonLD::fetchElement($jsonld, 'description');
1051 if (!empty($content)) {
1052 $jsonldinfo['publisher_description'] = trim($content);
1055 $content = JsonLD::fetchElement($jsonld, 'url');
1056 if (!empty($content)) {
1057 $jsonldinfo['publisher_url'] = trim($content);
1060 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1061 if (!empty($content)) {
1062 $jsonldinfo['image'] = trim($content);
1065 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
1067 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1068 return array_merge($siteinfo, $jsonldinfo);
1072 * Fetch data from the provided JSON-LD Organization type
1073 * @see https://schema.org/Organization
1075 * @param array $siteinfo
1076 * @param array $jsonld
1077 * @return array siteinfo
1079 private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
1083 $content = JsonLD::fetchElement($jsonld, 'name');
1084 if (!empty($content)) {
1085 $jsonldinfo['publisher_name'] = trim($content);
1088 $content = JsonLD::fetchElement($jsonld, 'description');
1089 if (!empty($content)) {
1090 $jsonldinfo['publisher_description'] = trim($content);
1093 $content = JsonLD::fetchElement($jsonld, 'url');
1094 if (!empty($content)) {
1095 $jsonldinfo['publisher_url'] = trim($content);
1098 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
1099 if (!empty($content)) {
1100 $jsonldinfo['publisher_img'] = trim($content);
1103 $content = JsonLD::fetchElement($jsonld, 'brand', 'name', '@type', 'Organization');
1104 if (!empty($content)) {
1105 $jsonldinfo['publisher_name'] = trim($content);
1108 $content = JsonLD::fetchElement($jsonld, 'brand', 'url', '@type', 'Organization');
1109 if (!empty($content)) {
1110 $jsonldinfo['publisher_url'] = trim($content);
1113 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1114 return array_merge($siteinfo, $jsonldinfo);
1118 * Fetch data from the provided JSON-LD Person type
1119 * @see https://schema.org/Person
1121 * @param array $siteinfo
1122 * @param array $jsonld
1123 * @return array siteinfo
1125 private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
1129 $content = JsonLD::fetchElement($jsonld, 'name');
1130 if (!empty($content)) {
1131 $jsonldinfo['author_name'] = trim($content);
1134 $content = JsonLD::fetchElement($jsonld, 'description');
1135 if (!empty($content)) {
1136 $jsonldinfo['author_description'] = trim($content);
1139 $content = JsonLD::fetchElement($jsonld, 'sameAs');
1140 if (!empty($content) && is_string($content)) {
1141 $jsonldinfo['author_url'] = trim($content);
1144 $content = JsonLD::fetchElement($jsonld, 'url');
1145 if (!empty($content)) {
1146 $jsonldinfo['author_url'] = trim($content);
1149 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
1150 if (!empty($content) && !is_string($content)) {
1151 Logger::notice('Unexpected return value for the author image', ['content' => $content]);
1154 if (!empty($content) && is_string($content)) {
1155 $jsonldinfo['author_img'] = trim($content);
1158 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
1159 return array_merge($siteinfo, $jsonldinfo);
1163 * Fetch data from the provided JSON-LD MediaObject type
1164 * @see https://schema.org/MediaObject
1166 * @param array $siteinfo
1167 * @param array $jsonld
1168 * @return array siteinfo
1170 private static function parseJsonLdMediaObject(array $siteinfo, array $jsonld, string $name)
1174 $content = JsonLD::fetchElement($jsonld, 'caption');
1175 if (!empty($content)) {
1176 $media['caption'] = trim($content);
1179 $content = JsonLD::fetchElement($jsonld, 'url');
1180 if (!empty($content)) {
1181 $media['url'] = trim($content);
1184 $content = JsonLD::fetchElement($jsonld, 'mainEntityOfPage');
1185 if (!empty($content)) {
1186 $media['main'] = Strings::compareLink($content, $siteinfo['url']);
1189 $content = JsonLD::fetchElement($jsonld, 'description');
1190 if (!empty($content)) {
1191 $media['description'] = trim($content);
1194 $content = JsonLD::fetchElement($jsonld, 'name');
1195 if (!empty($content) && (($media['description'] ?? '') != trim($content))) {
1196 $media['name'] = trim($content);
1199 $content = JsonLD::fetchElement($jsonld, 'contentUrl');
1200 if (!empty($content)) {
1201 $media['content'] = trim($content);
1204 $content = JsonLD::fetchElement($jsonld, 'embedUrl');
1205 if (!empty($content)) {
1206 $media['embed'] = trim($content);
1209 $content = JsonLD::fetchElement($jsonld, 'height');
1210 if (!empty($content)) {
1211 $media['height'] = trim($content);
1214 $content = JsonLD::fetchElement($jsonld, 'width');
1215 if (!empty($content)) {
1216 $media['width'] = trim($content);
1219 $content = JsonLD::fetchElement($jsonld, 'image');
1220 if (!empty($content)) {
1221 $media['image'] = trim($content);
1224 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
1225 if (!empty($content) && (($media['image'] ?? '') != trim($content))) {
1226 if (!empty($media['image'])) {
1227 $media['preview'] = trim($content);
1229 $media['image'] = trim($content);
1233 Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
1234 $siteinfo[$name][] = $media;