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;
14 use Friendica\Object\Image;
17 * @brief Class with methods for extracting certain content from an url
22 * @brief Search for chached embeddable data of an url otherwise fetch it
24 * @param string $url The url of the page which should be scraped
25 * @param bool $no_guessing If true the parse doens't search for
27 * @param bool $do_oembed The false option is used by the function fetch_oembed()
28 * to avoid endless loops
30 * @return array which contains needed data for embedding
31 * string 'url' => The url of the parsed page
32 * string 'type' => Content type
33 * string 'title' => The title of the content
34 * string 'text' => The description for the content
35 * string 'image' => A preview image of the content (only available
36 * if $no_geuessing = false
37 * array'images' = Array of preview pictures
38 * string 'keywords' => The tags which belong to the content
40 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
41 * @see ParseUrl::getSiteinfo() for more information about scraping
44 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
50 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
51 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
53 if (!empty($parsed_url['content'])) {
54 $data = unserialize($parsed_url['content']);
58 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
63 'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
64 'oembed' => $do_oembed, 'content' => serialize($data),
65 'created' => DateTimeFormat::utcNow()
74 * @brief Parse a page for embeddable content information
76 * This method parses to url for meta data which can be used to embed
77 * the content. If available it prioritizes Open Graph meta tags.
78 * If this is not available it uses the twitter cards meta tags.
79 * As fallback it uses standard html elements with meta informations
80 * like \<title\>Awesome Title\</title\> or
81 * \<meta name="description" content="An awesome description"\>
83 * @param string $url The url of the page which should be scraped
84 * @param bool $no_guessing If true the parse doens't search for
86 * @param bool $do_oembed The false option is used by the function fetch_oembed()
87 * to avoid endless loops
88 * @param int $count Internal counter 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' => The title of the content
94 * string 'text' => The description for the content
95 * string 'image' => A preview image of the content (only available
96 * if $no_geuessing = false
97 * array'images' = Array of preview pictures
98 * string 'keywords' => The tags which belong to the content
100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 * @todo https://developers.google.com/+/plugins/snippet/
103 * <meta itemprop="name" content="Awesome title">
104 * <meta itemprop="description" content="An awesome description">
105 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
107 * <body itemscope itemtype="http://schema.org/Product">
108 * <h1 itemprop="name">Shiny Trinket</h1>
109 * <img itemprop="image" src="{image-url}" />
110 * <p itemprop="description">Shiny trinkets are shiny.</p>
114 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
118 // Check if the URL does contain a scheme
119 $scheme = parse_url($url, PHP_URL_SCHEME);
122 $url = 'http://' . trim($url, '/');
126 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
130 $url = trim($url, "'");
131 $url = trim($url, '"');
133 $url = Network::stripTrackingQueryParams($url);
135 $siteinfo['url'] = $url;
136 $siteinfo['type'] = 'link';
138 $curlResult = Network::curl($url);
139 if (!$curlResult->isSuccess()) {
143 // If the file is too large then exit
144 if (defaults($curlResult->getInfo(), 'download_content_length', 0) > 1000000) {
148 // If it isn't a HTML file then exit
149 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
153 $header = $curlResult->getHeader();
154 $body = $curlResult->getBody();
157 $oembed_data = OEmbed::fetchURL($url);
159 if (!empty($oembed_data->type)) {
160 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
161 $siteinfo['type'] = $oembed_data->type;
164 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
165 if ($siteinfo['type'] != 'photo') {
166 if (isset($oembed_data->title)) {
167 $siteinfo['title'] = trim($oembed_data->title);
169 if (isset($oembed_data->description)) {
170 $siteinfo['text'] = trim($oembed_data->description);
172 if (isset($oembed_data->thumbnail_url)) {
173 $siteinfo['image'] = $oembed_data->thumbnail_url;
179 // Fetch the first mentioned charset. Can be in body or header
181 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
182 $charset = trim(trim(trim(array_pop($matches)), ';,'));
185 if ($charset && strtoupper($charset) != 'UTF-8') {
186 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
187 $charset = str_ireplace('latin-1', 'latin1', $charset);
189 Logger::log('detected charset ' . $charset, Logger::DEBUG);
190 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
193 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
195 $doc = new DOMDocument();
196 @$doc->loadHTML($body);
198 XML::deleteNode($doc, 'style');
199 XML::deleteNode($doc, 'script');
200 XML::deleteNode($doc, 'option');
201 XML::deleteNode($doc, 'h1');
202 XML::deleteNode($doc, 'h2');
203 XML::deleteNode($doc, 'h3');
204 XML::deleteNode($doc, 'h4');
205 XML::deleteNode($doc, 'h5');
206 XML::deleteNode($doc, 'h6');
207 XML::deleteNode($doc, 'ol');
208 XML::deleteNode($doc, 'ul');
210 $xpath = new DOMXPath($doc);
212 $list = $xpath->query('//meta[@content]');
213 foreach ($list as $node) {
215 if ($node->attributes->length) {
216 foreach ($node->attributes as $attribute) {
217 $meta_tag[$attribute->name] = $attribute->value;
221 if (@$meta_tag['http-equiv'] == 'refresh') {
222 $path = $meta_tag['content'];
223 $pathinfo = explode(';', $path);
225 foreach ($pathinfo as $value) {
226 if (substr(strtolower($value), 0, 4) == 'url=') {
227 $content = substr($value, 4);
230 if ($content != '') {
231 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
237 $list = $xpath->query('//title');
238 if ($list->length > 0) {
239 $siteinfo['title'] = trim($list->item(0)->nodeValue);
242 $list = $xpath->query('//meta[@name]');
243 foreach ($list as $node) {
245 if ($node->attributes->length) {
246 foreach ($node->attributes as $attribute) {
247 $meta_tag[$attribute->name] = $attribute->value;
251 if (empty($meta_tag['content'])) {
255 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
257 switch (strtolower($meta_tag['name'])) {
259 $siteinfo['title'] = trim($meta_tag['content']);
262 $siteinfo['text'] = trim($meta_tag['content']);
265 $siteinfo['image'] = $meta_tag['content'];
267 case 'twitter:image':
268 $siteinfo['image'] = $meta_tag['content'];
270 case 'twitter:image:src':
271 $siteinfo['image'] = $meta_tag['content'];
274 // Detect photo pages
275 if ($meta_tag['content'] == 'summary_large_image') {
276 $siteinfo['type'] = 'photo';
279 case 'twitter:description':
280 $siteinfo['text'] = trim($meta_tag['content']);
282 case 'twitter:title':
283 $siteinfo['title'] = trim($meta_tag['content']);
286 $siteinfo['title'] = trim($meta_tag['content']);
288 case 'dc.description':
289 $siteinfo['text'] = trim($meta_tag['content']);
292 $keywords = explode(',', $meta_tag['content']);
294 case 'news_keywords':
295 $keywords = explode(',', $meta_tag['content']);
300 if (isset($keywords)) {
301 $siteinfo['keywords'] = [];
302 foreach ($keywords as $keyword) {
303 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
304 $siteinfo['keywords'][] = trim($keyword);
309 $list = $xpath->query('//meta[@property]');
310 foreach ($list as $node) {
312 if ($node->attributes->length) {
313 foreach ($node->attributes as $attribute) {
314 $meta_tag[$attribute->name] = $attribute->value;
318 if (!empty($meta_tag['content'])) {
319 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
321 switch (strtolower($meta_tag['property'])) {
323 $siteinfo['image'] = $meta_tag['content'];
326 $siteinfo['title'] = trim($meta_tag['content']);
328 case 'og:description':
329 $siteinfo['text'] = trim($meta_tag['content']);
335 // Prevent to have a photo type without an image
336 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
337 $siteinfo['type'] = 'link';
340 if (empty($siteinfo['image']) && !$no_guessing) {
341 $list = $xpath->query('//img[@src]');
342 foreach ($list as $node) {
344 if ($node->attributes->length) {
345 foreach ($node->attributes as $attribute) {
346 $img_tag[$attribute->name] = $attribute->value;
350 $src = self::completeUrl($img_tag['src'], $url);
351 $photodata = Image::getInfoFromURL($src);
353 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
354 if ($photodata[0] > 300) {
355 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
358 if ($photodata[1] > 300) {
359 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
362 $siteinfo['images'][] = [
364 'width' => $photodata[0],
365 'height' => $photodata[1]
369 } elseif (!empty($siteinfo['image'])) {
370 $src = self::completeUrl($siteinfo['image'], $url);
372 unset($siteinfo['image']);
374 $photodata = Image::getInfoFromURL($src);
376 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
377 $siteinfo['images'][] = ['src' => $src,
378 'width' => $photodata[0],
379 'height' => $photodata[1]];
383 if ((@$siteinfo['text'] == '') && (@$siteinfo['title'] != '') && !$no_guessing) {
386 $list = $xpath->query('//div[@class="article"]');
387 foreach ($list as $node) {
388 if (strlen($node->nodeValue) > 40) {
389 $text .= ' ' . trim($node->nodeValue);
394 $list = $xpath->query('//div[@class="content"]');
395 foreach ($list as $node) {
396 if (strlen($node->nodeValue) > 40) {
397 $text .= ' ' . trim($node->nodeValue);
402 // If none text was found then take the paragraph content
404 $list = $xpath->query('//p');
405 foreach ($list as $node) {
406 if (strlen($node->nodeValue) > 40) {
407 $text .= ' ' . trim($node->nodeValue);
413 $text = trim(str_replace(["\n", "\r"], [' ', ' '], $text));
415 while (strpos($text, ' ')) {
416 $text = trim(str_replace(' ', ' ', $text));
419 $siteinfo['text'] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, 'UTF-8') . '...');
423 Logger::log('Siteinfo for ' . $url . ' ' . print_r($siteinfo, true), Logger::DEBUG);
425 Hook::callAll('getsiteinfo', $siteinfo);
431 * @brief Convert tags from CSV to an array
433 * @param string $string Tags
434 * @return array with formatted Hashtags
436 public static function convertTagsToArray($string)
438 $arr_tags = str_getcsv($string);
439 if (count($arr_tags)) {
440 // add the # sign to every tag
441 array_walk($arr_tags, ["self", "arrAddHashes"]);
448 * @brief Add a hasht sign to a string
450 * This method is used as callback function
452 * @param string $tag The pure tag name
453 * @param int $k Counter for internal use
456 private static function arrAddHashes(&$tag, $k)
462 * @brief Add a scheme to an url
464 * The src attribute of some html elements (e.g. images)
465 * can miss the scheme so we need to add the correct
468 * @param string $url The url which possibly does have
469 * a missing scheme (a link to an image)
470 * @param string $scheme The url with a correct scheme
471 * (e.g. the url from the webpage which does contain the image)
473 * @return string The url with a scheme
475 private static function completeUrl($url, $scheme)
477 $urlarr = parse_url($url);
479 // If the url does allready have an scheme
480 // we can stop the process here
481 if (isset($urlarr["scheme"])) {
485 $schemearr = parse_url($scheme);
487 $complete = $schemearr["scheme"]."://".$schemearr["host"];
489 if (!empty($schemearr["port"])) {
490 $complete .= ":".$schemearr["port"];
493 if (!empty($urlarr["path"])) {
494 if (strpos($urlarr["path"], "/") !== 0) {
498 $complete .= $urlarr["path"];
501 if (!empty($urlarr["query"])) {
502 $complete .= "?".$urlarr["query"];
505 if (!empty($urlarr["fragment"])) {
506 $complete .= "#".$urlarr["fragment"];