3 * @file src/Util/ParseUrl.php
4 * @brief Get informations about a given URL
6 namespace Friendica\Util;
10 use Friendica\Content\OEmbed;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Database\DBA;
16 * @brief Class with methods for extracting certain content from an url
21 * Maximum number of characters for the description
23 const MAX_DESC_COUNT = 250;
26 * Minimum number of characters for the description
28 const MIN_DESC_COUNT = 100;
31 * @brief Search for chached embeddable data of an url otherwise fetch it
33 * @param string $url The url of the page which should be scraped
34 * @param bool $no_guessing If true the parse doens't search for
36 * @param bool $do_oembed The false option is used by the function fetch_oembed()
37 * to avoid endless loops
39 * @return array which contains needed data for embedding
40 * string 'url' => The url of the parsed page
41 * string 'type' => Content type
42 * string 'title' => The title of the content
43 * string 'text' => The description for the content
44 * string 'image' => A preview image of the content (only available
45 * if $no_geuessing = false
46 * array'images' = Array of preview pictures
47 * string 'keywords' => The tags which belong to the content
49 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50 * @see ParseUrl::getSiteinfo() for more information about scraping
53 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
59 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
60 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
62 if (!empty($parsed_url['content'])) {
63 $data = unserialize($parsed_url['content']);
67 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
72 'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
73 'oembed' => $do_oembed, 'content' => serialize($data),
74 'created' => DateTimeFormat::utcNow()
83 * @brief Parse a page for embeddable content information
85 * This method parses to url for meta data which can be used to embed
86 * the content. If available it prioritizes Open Graph meta tags.
87 * If this is not available it uses the twitter cards meta tags.
88 * As fallback it uses standard html elements with meta informations
89 * like \<title\>Awesome Title\</title\> or
90 * \<meta name="description" content="An awesome description"\>
92 * @param string $url The url of the page which should be scraped
93 * @param bool $no_guessing If true the parse doens't search for
95 * @param bool $do_oembed The false option is used by the function fetch_oembed()
96 * to avoid endless loops
97 * @param int $count Internal counter to avoid endless loops
99 * @return array which contains needed data for embedding
100 * string 'url' => The url of the parsed page
101 * string 'type' => Content type
102 * string 'title' => The title of the content
103 * string 'text' => The description for the content
104 * string 'image' => A preview image of the content (only available
105 * if $no_geuessing = false
106 * array'images' = Array of preview pictures
107 * string 'keywords' => The tags which belong to the content
109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110 * @todo https://developers.google.com/+/plugins/snippet/
112 * <meta itemprop="name" content="Awesome title">
113 * <meta itemprop="description" content="An awesome description">
114 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
116 * <body itemscope itemtype="http://schema.org/Product">
117 * <h1 itemprop="name">Shiny Trinket</h1>
118 * <img itemprop="image" src="{image-url}" />
119 * <p itemprop="description">Shiny trinkets are shiny.</p>
123 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
127 // Check if the URL does contain a scheme
128 $scheme = parse_url($url, PHP_URL_SCHEME);
131 $url = 'http://' . trim($url, '/');
135 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
139 $url = trim($url, "'");
140 $url = trim($url, '"');
142 $url = Network::stripTrackingQueryParams($url);
144 $siteinfo['url'] = $url;
145 $siteinfo['type'] = 'link';
147 $curlResult = Network::curl($url);
148 if (!$curlResult->isSuccess()) {
152 // If the file is too large then exit
153 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
157 // If it isn't a HTML file then exit
158 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
162 $header = $curlResult->getHeader();
163 $body = $curlResult->getBody();
166 $oembed_data = OEmbed::fetchURL($url);
168 if (!empty($oembed_data->type)) {
169 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
170 $siteinfo['type'] = $oembed_data->type;
173 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
174 if ($siteinfo['type'] != 'photo') {
175 if (isset($oembed_data->title)) {
176 $siteinfo['title'] = trim($oembed_data->title);
178 if (isset($oembed_data->description)) {
179 $siteinfo['text'] = trim($oembed_data->description);
181 if (isset($oembed_data->thumbnail_url)) {
182 $siteinfo['image'] = $oembed_data->thumbnail_url;
188 // Fetch the first mentioned charset. Can be in body or header
190 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
191 $charset = trim(trim(trim(array_pop($matches)), ';,'));
194 if ($charset && strtoupper($charset) != 'UTF-8') {
195 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
196 $charset = str_ireplace('latin-1', 'latin1', $charset);
198 Logger::log('detected charset ' . $charset, Logger::DEBUG);
199 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
202 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
204 $doc = new DOMDocument();
205 @$doc->loadHTML($body);
207 XML::deleteNode($doc, 'style');
208 XML::deleteNode($doc, 'script');
209 XML::deleteNode($doc, 'option');
210 XML::deleteNode($doc, 'h1');
211 XML::deleteNode($doc, 'h2');
212 XML::deleteNode($doc, 'h3');
213 XML::deleteNode($doc, 'h4');
214 XML::deleteNode($doc, 'h5');
215 XML::deleteNode($doc, 'h6');
216 XML::deleteNode($doc, 'ol');
217 XML::deleteNode($doc, 'ul');
219 $xpath = new DOMXPath($doc);
221 $list = $xpath->query('//meta[@content]');
222 foreach ($list as $node) {
224 if ($node->attributes->length) {
225 foreach ($node->attributes as $attribute) {
226 $meta_tag[$attribute->name] = $attribute->value;
230 if (@$meta_tag['http-equiv'] == 'refresh') {
231 $path = $meta_tag['content'];
232 $pathinfo = explode(';', $path);
234 foreach ($pathinfo as $value) {
235 if (substr(strtolower($value), 0, 4) == 'url=') {
236 $content = substr($value, 4);
239 if ($content != '') {
240 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
246 $list = $xpath->query('//title');
247 if ($list->length > 0) {
248 $siteinfo['title'] = trim($list->item(0)->nodeValue);
251 $list = $xpath->query('//meta[@name]');
252 foreach ($list as $node) {
254 if ($node->attributes->length) {
255 foreach ($node->attributes as $attribute) {
256 $meta_tag[$attribute->name] = $attribute->value;
260 if (empty($meta_tag['content'])) {
264 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
266 switch (strtolower($meta_tag['name'])) {
268 $siteinfo['title'] = trim($meta_tag['content']);
271 $siteinfo['text'] = trim($meta_tag['content']);
274 $siteinfo['image'] = $meta_tag['content'];
276 case 'twitter:image':
277 $siteinfo['image'] = $meta_tag['content'];
279 case 'twitter:image:src':
280 $siteinfo['image'] = $meta_tag['content'];
283 // Detect photo pages
284 if ($meta_tag['content'] == 'summary_large_image') {
285 $siteinfo['type'] = 'photo';
288 case 'twitter:description':
289 $siteinfo['text'] = trim($meta_tag['content']);
291 case 'twitter:title':
292 $siteinfo['title'] = trim($meta_tag['content']);
295 $siteinfo['title'] = trim($meta_tag['content']);
297 case 'dc.description':
298 $siteinfo['text'] = trim($meta_tag['content']);
301 $keywords = explode(',', $meta_tag['content']);
303 case 'news_keywords':
304 $keywords = explode(',', $meta_tag['content']);
309 if (isset($keywords)) {
310 $siteinfo['keywords'] = [];
311 foreach ($keywords as $keyword) {
312 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
313 $siteinfo['keywords'][] = trim($keyword);
318 $list = $xpath->query('//meta[@property]');
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 (!empty($meta_tag['content'])) {
328 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
330 switch (strtolower($meta_tag['property'])) {
332 $siteinfo['image'] = $meta_tag['content'];
335 $siteinfo['title'] = trim($meta_tag['content']);
337 case 'og:description':
338 $siteinfo['text'] = trim($meta_tag['content']);
344 // Prevent to have a photo type without an image
345 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
346 $siteinfo['type'] = 'link';
349 if (!empty($siteinfo['image'])) {
350 $src = self::completeUrl($siteinfo['image'], $url);
352 unset($siteinfo['image']);
354 $photodata = Images::getInfoFromURLCached($src);
356 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
357 $siteinfo['images'][] = ['src' => $src,
358 'width' => $photodata[0],
359 'height' => $photodata[1]];
363 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
364 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
365 $pos = mb_strrpos($siteinfo['text'], '.');
366 if ($pos > self::MIN_DESC_COUNT) {
367 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
371 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
373 Hook::callAll('getsiteinfo', $siteinfo);
379 * @brief Convert tags from CSV to an array
381 * @param string $string Tags
382 * @return array with formatted Hashtags
384 public static function convertTagsToArray($string)
386 $arr_tags = str_getcsv($string);
387 if (count($arr_tags)) {
388 // add the # sign to every tag
389 array_walk($arr_tags, ["self", "arrAddHashes"]);
396 * @brief Add a hasht sign to a string
398 * This method is used as callback function
400 * @param string $tag The pure tag name
401 * @param int $k Counter for internal use
404 private static function arrAddHashes(&$tag, $k)
410 * @brief Add a scheme to an url
412 * The src attribute of some html elements (e.g. images)
413 * can miss the scheme so we need to add the correct
416 * @param string $url The url which possibly does have
417 * a missing scheme (a link to an image)
418 * @param string $scheme The url with a correct scheme
419 * (e.g. the url from the webpage which does contain the image)
421 * @return string The url with a scheme
423 private static function completeUrl($url, $scheme)
425 $urlarr = parse_url($url);
427 // If the url does allready have an scheme
428 // we can stop the process here
429 if (isset($urlarr["scheme"])) {
433 $schemearr = parse_url($scheme);
435 $complete = $schemearr["scheme"]."://".$schemearr["host"];
437 if (!empty($schemearr["port"])) {
438 $complete .= ":".$schemearr["port"];
441 if (!empty($urlarr["path"])) {
442 if (strpos($urlarr["path"], "/") !== 0) {
446 $complete .= $urlarr["path"];
449 if (!empty($urlarr["query"])) {
450 $complete .= "?".$urlarr["query"];
453 if (!empty($urlarr["fragment"])) {
454 $complete .= "#".$urlarr["fragment"];