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\Addon;
12 use Friendica\Database\DBA;
13 use Friendica\Object\Image;
15 require_once 'include/dba.php';
18 * @brief Class with methods for extracting certain content from an url
23 * @brief Search for chached embeddable data of an url otherwise fetch it
25 * @param string $url The url of the page which should be scraped
26 * @param bool $no_guessing If true the parse doens't search for
28 * @param bool $do_oembed The false option is used by the function fetch_oembed()
29 * to avoid endless loops
31 * @return array which contains needed data for embedding
32 * string 'url' => The url of the parsed page
33 * string 'type' => Content type
34 * string 'title' => The title of the content
35 * string 'text' => The description for the content
36 * string 'image' => A preview image of the content (only available
37 * if $no_geuessing = false
38 * array'images' = Array of preview pictures
39 * string 'keywords' => The tags which belong to the content
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' => normalise_link($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' => normalise_link($url), 'guessing' => !$no_guessing,
64 'oembed' => $do_oembed, 'content' => serialize($data),
65 'created' => DateTimeFormat::utcNow()
73 * @brief Parse a page for embeddable content information
75 * This method parses to url for meta data which can be used to embed
76 * the content. If available it prioritizes Open Graph meta tags.
77 * If this is not available it uses the twitter cards meta tags.
78 * As fallback it uses standard html elements with meta informations
79 * like \<title\>Awesome Title\</title\> or
80 * \<meta name="description" content="An awesome description"\>
82 * @param string $url The url of the page which should be scraped
83 * @param bool $no_guessing If true the parse doens't search for
85 * @param bool $do_oembed The false option is used by the function fetch_oembed()
86 * to avoid endless loops
87 * @param int $count Internal counter to avoid endless loops
89 * @return array which contains needed data for embedding
90 * string 'url' => The url of the parsed page
91 * string 'type' => Content type
92 * string 'title' => The title of the content
93 * string 'text' => The description for the content
94 * string 'image' => A preview image of the content (only available
95 * if $no_geuessing = false
96 * array'images' = Array of preview pictures
97 * string 'keywords' => The tags which belong to the content
99 * @todo https://developers.google.com/+/plugins/snippet/
101 * <meta itemprop="name" content="Awesome title">
102 * <meta itemprop="description" content="An awesome description">
103 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
105 * <body itemscope itemtype="http://schema.org/Product">
106 * <h1 itemprop="name">Shiny Trinket</h1>
107 * <img itemprop="image" src="{image-url}" />
108 * <p itemprop="description">Shiny trinkets are shiny.</p>
112 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('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 $data = Network::curl($url);
139 if (!$data['success']) {
143 // If the file is too large then exit
144 if ($data['info']['download_content_length'] > 1000000) {
148 // If it isn't a HTML file then exit
149 if (($data['info']['content_type'] != '') && !strstr(strtolower($data['info']['content_type']), 'html')) {
153 $header = $data['header'];
154 $body = $data['body'];
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 if (isset($oembed_data->title)) {
165 $siteinfo['title'] = trim($oembed_data->title);
167 if (isset($oembed_data->description)) {
168 $siteinfo['text'] = trim($oembed_data->description);
170 if (isset($oembed_data->thumbnail_url)) {
171 $siteinfo['image'] = $oembed_data->thumbnail_url;
176 // Fetch the first mentioned charset. Can be in body or header
178 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
179 $charset = trim(trim(trim(array_pop($matches)), ';,'));
182 if ($charset == '') {
186 if (($charset != '') && (strtoupper($charset) != 'UTF-8')) {
187 logger('detected charset ' . $charset, LOGGER_DEBUG);
188 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
191 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
193 $doc = new DOMDocument();
194 @$doc->loadHTML($body);
196 XML::deleteNode($doc, 'style');
197 XML::deleteNode($doc, 'script');
198 XML::deleteNode($doc, 'option');
199 XML::deleteNode($doc, 'h1');
200 XML::deleteNode($doc, 'h2');
201 XML::deleteNode($doc, 'h3');
202 XML::deleteNode($doc, 'h4');
203 XML::deleteNode($doc, 'h5');
204 XML::deleteNode($doc, 'h6');
205 XML::deleteNode($doc, 'ol');
206 XML::deleteNode($doc, 'ul');
208 $xpath = new DOMXPath($doc);
210 $list = $xpath->query('//meta[@content]');
211 foreach ($list as $node) {
213 if ($node->attributes->length) {
214 foreach ($node->attributes as $attribute) {
215 $meta_tag[$attribute->name] = $attribute->value;
219 if (@$meta_tag['http-equiv'] == 'refresh') {
220 $path = $meta_tag['content'];
221 $pathinfo = explode(';', $path);
223 foreach ($pathinfo as $value) {
224 if (substr(strtolower($value), 0, 4) == 'url=') {
225 $content = substr($value, 4);
228 if ($content != '') {
229 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
235 $list = $xpath->query('//title');
236 if ($list->length > 0) {
237 $siteinfo['title'] = trim($list->item(0)->nodeValue);
240 $list = $xpath->query('//meta[@name]');
241 foreach ($list as $node) {
243 if ($node->attributes->length) {
244 foreach ($node->attributes as $attribute) {
245 $meta_tag[$attribute->name] = $attribute->value;
249 if (empty($meta_tag['content'])) {
253 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
255 switch (strtolower($meta_tag['name'])) {
257 $siteinfo['title'] = trim($meta_tag['content']);
260 $siteinfo['text'] = trim($meta_tag['content']);
263 $siteinfo['image'] = $meta_tag['content'];
265 case 'twitter:image':
266 $siteinfo['image'] = $meta_tag['content'];
268 case 'twitter:image:src':
269 $siteinfo['image'] = $meta_tag['content'];
272 // Detect photo pages
273 if ($meta_tag['content'] == 'summary_large_image') {
274 $siteinfo['type'] = 'photo';
277 case 'twitter:description':
278 $siteinfo['text'] = trim($meta_tag['content']);
280 case 'twitter:title':
281 $siteinfo['title'] = trim($meta_tag['content']);
284 $siteinfo['title'] = trim($meta_tag['content']);
286 case 'dc.description':
287 $siteinfo['text'] = trim($meta_tag['content']);
290 $keywords = explode(',', $meta_tag['content']);
292 case 'news_keywords':
293 $keywords = explode(',', $meta_tag['content']);
298 if (isset($keywords)) {
299 $siteinfo['keywords'] = [];
300 foreach ($keywords as $keyword) {
301 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
302 $siteinfo['keywords'][] = trim($keyword);
307 $list = $xpath->query('//meta[@property]');
308 foreach ($list as $node) {
310 if ($node->attributes->length) {
311 foreach ($node->attributes as $attribute) {
312 $meta_tag[$attribute->name] = $attribute->value;
316 if (!empty($meta_tag['content'])) {
317 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
319 switch (strtolower($meta_tag['property'])) {
321 $siteinfo['image'] = $meta_tag['content'];
324 $siteinfo['title'] = trim($meta_tag['content']);
326 case 'og:description':
327 $siteinfo['text'] = trim($meta_tag['content']);
333 // Prevent to have a photo type without an image
334 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
335 $siteinfo['type'] = 'link';
338 if (empty($siteinfo['image']) && !$no_guessing) {
339 $list = $xpath->query('//img[@src]');
340 foreach ($list as $node) {
342 if ($node->attributes->length) {
343 foreach ($node->attributes as $attribute) {
344 $img_tag[$attribute->name] = $attribute->value;
348 $src = self::completeUrl($img_tag['src'], $url);
349 $photodata = Image::getInfoFromURL($src);
351 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
352 if ($photodata[0] > 300) {
353 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
356 if ($photodata[1] > 300) {
357 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
360 $siteinfo['images'][] = [
362 'width' => $photodata[0],
363 'height' => $photodata[1]
367 } elseif (!empty($siteinfo['image'])) {
368 $src = self::completeUrl($siteinfo['image'], $url);
370 unset($siteinfo['image']);
372 $photodata = Image::getInfoFromURL($src);
374 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
375 $siteinfo['images'][] = ['src' => $src,
376 'width' => $photodata[0],
377 'height' => $photodata[1]];
381 if ((@$siteinfo['text'] == '') && (@$siteinfo['title'] != '') && !$no_guessing) {
384 $list = $xpath->query('//div[@class="article"]');
385 foreach ($list as $node) {
386 if (strlen($node->nodeValue) > 40) {
387 $text .= ' ' . trim($node->nodeValue);
392 $list = $xpath->query('//div[@class="content"]');
393 foreach ($list as $node) {
394 if (strlen($node->nodeValue) > 40) {
395 $text .= ' ' . trim($node->nodeValue);
400 // If none text was found then take the paragraph content
402 $list = $xpath->query('//p');
403 foreach ($list as $node) {
404 if (strlen($node->nodeValue) > 40) {
405 $text .= ' ' . trim($node->nodeValue);
411 $text = trim(str_replace(["\n", "\r"], [' ', ' '], $text));
413 while (strpos($text, ' ')) {
414 $text = trim(str_replace(' ', ' ', $text));
417 $siteinfo['text'] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, 'UTF-8') . '...');
421 logger('Siteinfo for ' . $url . ' ' . print_r($siteinfo, true), LOGGER_DEBUG);
423 Addon::callHooks('getsiteinfo', $siteinfo);
429 * @brief Convert tags from CSV to an array
431 * @param string $string Tags
432 * @return array with formatted Hashtags
434 public static function convertTagsToArray($string)
436 $arr_tags = str_getcsv($string);
437 if (count($arr_tags)) {
438 // add the # sign to every tag
439 array_walk($arr_tags, ["self", "arrAddHashes"]);
446 * @brief Add a hasht sign to a string
448 * This method is used as callback function
450 * @param string $tag The pure tag name
451 * @param int $k Counter for internal use
454 private static function arrAddHashes(&$tag, $k)
460 * @brief Add a scheme to an url
462 * The src attribute of some html elements (e.g. images)
463 * can miss the scheme so we need to add the correct
466 * @param string $url The url which possibly does have
467 * a missing scheme (a link to an image)
468 * @param string $scheme The url with a correct scheme
469 * (e.g. the url from the webpage which does contain the image)
471 * @return string The url with a scheme
473 private static function completeUrl($url, $scheme)
475 $urlarr = parse_url($url);
477 // If the url does allready have an scheme
478 // we can stop the process here
479 if (isset($urlarr["scheme"])) {
483 $schemearr = parse_url($scheme);
485 $complete = $schemearr["scheme"]."://".$schemearr["host"];
487 if (@$schemearr["port"] != "") {
488 $complete .= ":".$schemearr["port"];
491 if (strpos($urlarr["path"], "/") !== 0) {
495 $complete .= $urlarr["path"];
497 if (@$urlarr["query"] != "") {
498 $complete .= "?".$urlarr["query"];
501 if (@$urlarr["fragment"] != "") {
502 $complete .= "#".$urlarr["fragment"];