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\Core\Logger;
13 use Friendica\Database\DBA;
14 use Friendica\Object\Image;
15 use Friendica\Util\Strings;
17 require_once 'include/dba.php';
20 * @brief Class with methods for extracting certain content from an url
25 * @brief Search for chached embeddable data of an url otherwise fetch it
27 * @param string $url The url of the page which should be scraped
28 * @param bool $no_guessing If true the parse doens't search for
30 * @param bool $do_oembed The false option is used by the function fetch_oembed()
31 * to avoid endless loops
33 * @return array which contains needed data for embedding
34 * string 'url' => The url of the parsed page
35 * string 'type' => Content type
36 * string 'title' => The title of the content
37 * string 'text' => The description for the content
38 * string 'image' => A preview image of the content (only available
39 * if $no_geuessing = false
40 * array'images' = Array of preview pictures
41 * string 'keywords' => The tags which belong to the content
43 * @see ParseUrl::getSiteinfo() for more information about scraping
46 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
52 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
53 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
55 if (!empty($parsed_url['content'])) {
56 $data = unserialize($parsed_url['content']);
60 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
65 'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
66 'oembed' => $do_oembed, 'content' => serialize($data),
67 'created' => DateTimeFormat::utcNow()
75 * @brief Parse a page for embeddable content information
77 * This method parses to url for meta data which can be used to embed
78 * the content. If available it prioritizes Open Graph meta tags.
79 * If this is not available it uses the twitter cards meta tags.
80 * As fallback it uses standard html elements with meta informations
81 * like \<title\>Awesome Title\</title\> or
82 * \<meta name="description" content="An awesome description"\>
84 * @param string $url The url of the page which should be scraped
85 * @param bool $no_guessing If true the parse doens't search for
87 * @param bool $do_oembed The false option is used by the function fetch_oembed()
88 * to avoid endless loops
89 * @param int $count Internal counter to avoid endless loops
91 * @return array which contains needed data for embedding
92 * string 'url' => The url of the parsed page
93 * string 'type' => Content type
94 * string 'title' => The title of the content
95 * string 'text' => The description for the content
96 * string 'image' => A preview image of the content (only available
97 * if $no_geuessing = false
98 * array'images' = Array of preview pictures
99 * string 'keywords' => The tags which belong to the content
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)
120 // Check if the URL does contain a scheme
121 $scheme = parse_url($url, PHP_URL_SCHEME);
124 $url = 'http://' . trim($url, '/');
128 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
132 $url = trim($url, "'");
133 $url = trim($url, '"');
135 $url = Network::stripTrackingQueryParams($url);
137 $siteinfo['url'] = $url;
138 $siteinfo['type'] = 'link';
140 $curlResult = Network::curl($url);
141 if (!$curlResult->isSuccess()) {
145 // If the file is too large then exit
146 if (defaults($curlResult->getInfo(), 'download_content_length', 0) > 1000000) {
150 // If it isn't a HTML file then exit
151 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
155 $header = $curlResult->getHeader();
156 $body = $curlResult->getBody();
159 $oembed_data = OEmbed::fetchURL($url);
161 if (!empty($oembed_data->type)) {
162 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
163 $siteinfo['type'] = $oembed_data->type;
166 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
167 if ($siteinfo['type'] != 'photo') {
168 if (isset($oembed_data->title)) {
169 $siteinfo['title'] = trim($oembed_data->title);
171 if (isset($oembed_data->description)) {
172 $siteinfo['text'] = trim($oembed_data->description);
174 if (isset($oembed_data->thumbnail_url)) {
175 $siteinfo['image'] = $oembed_data->thumbnail_url;
181 // Fetch the first mentioned charset. Can be in body or header
183 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
184 $charset = trim(trim(trim(array_pop($matches)), ';,'));
187 if ($charset == '') {
191 if (($charset != '') && (strtoupper($charset) != 'UTF-8')) {
192 Logger::log('detected charset ' . $charset, Logger::DEBUG);
193 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
196 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
198 $doc = new DOMDocument();
199 @$doc->loadHTML($body);
201 XML::deleteNode($doc, 'style');
202 XML::deleteNode($doc, 'script');
203 XML::deleteNode($doc, 'option');
204 XML::deleteNode($doc, 'h1');
205 XML::deleteNode($doc, 'h2');
206 XML::deleteNode($doc, 'h3');
207 XML::deleteNode($doc, 'h4');
208 XML::deleteNode($doc, 'h5');
209 XML::deleteNode($doc, 'h6');
210 XML::deleteNode($doc, 'ol');
211 XML::deleteNode($doc, 'ul');
213 $xpath = new DOMXPath($doc);
215 $list = $xpath->query('//meta[@content]');
216 foreach ($list as $node) {
218 if ($node->attributes->length) {
219 foreach ($node->attributes as $attribute) {
220 $meta_tag[$attribute->name] = $attribute->value;
224 if (@$meta_tag['http-equiv'] == 'refresh') {
225 $path = $meta_tag['content'];
226 $pathinfo = explode(';', $path);
228 foreach ($pathinfo as $value) {
229 if (substr(strtolower($value), 0, 4) == 'url=') {
230 $content = substr($value, 4);
233 if ($content != '') {
234 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
240 $list = $xpath->query('//title');
241 if ($list->length > 0) {
242 $siteinfo['title'] = trim($list->item(0)->nodeValue);
245 $list = $xpath->query('//meta[@name]');
246 foreach ($list as $node) {
248 if ($node->attributes->length) {
249 foreach ($node->attributes as $attribute) {
250 $meta_tag[$attribute->name] = $attribute->value;
254 if (empty($meta_tag['content'])) {
258 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
260 switch (strtolower($meta_tag['name'])) {
262 $siteinfo['title'] = trim($meta_tag['content']);
265 $siteinfo['text'] = trim($meta_tag['content']);
268 $siteinfo['image'] = $meta_tag['content'];
270 case 'twitter:image':
271 $siteinfo['image'] = $meta_tag['content'];
273 case 'twitter:image:src':
274 $siteinfo['image'] = $meta_tag['content'];
277 // Detect photo pages
278 if ($meta_tag['content'] == 'summary_large_image') {
279 $siteinfo['type'] = 'photo';
282 case 'twitter:description':
283 $siteinfo['text'] = trim($meta_tag['content']);
285 case 'twitter:title':
286 $siteinfo['title'] = trim($meta_tag['content']);
289 $siteinfo['title'] = trim($meta_tag['content']);
291 case 'dc.description':
292 $siteinfo['text'] = trim($meta_tag['content']);
295 $keywords = explode(',', $meta_tag['content']);
297 case 'news_keywords':
298 $keywords = explode(',', $meta_tag['content']);
303 if (isset($keywords)) {
304 $siteinfo['keywords'] = [];
305 foreach ($keywords as $keyword) {
306 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
307 $siteinfo['keywords'][] = trim($keyword);
312 $list = $xpath->query('//meta[@property]');
313 foreach ($list as $node) {
315 if ($node->attributes->length) {
316 foreach ($node->attributes as $attribute) {
317 $meta_tag[$attribute->name] = $attribute->value;
321 if (!empty($meta_tag['content'])) {
322 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
324 switch (strtolower($meta_tag['property'])) {
326 $siteinfo['image'] = $meta_tag['content'];
329 $siteinfo['title'] = trim($meta_tag['content']);
331 case 'og:description':
332 $siteinfo['text'] = trim($meta_tag['content']);
338 // Prevent to have a photo type without an image
339 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
340 $siteinfo['type'] = 'link';
343 if (empty($siteinfo['image']) && !$no_guessing) {
344 $list = $xpath->query('//img[@src]');
345 foreach ($list as $node) {
347 if ($node->attributes->length) {
348 foreach ($node->attributes as $attribute) {
349 $img_tag[$attribute->name] = $attribute->value;
353 $src = self::completeUrl($img_tag['src'], $url);
354 $photodata = Image::getInfoFromURL($src);
356 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
357 if ($photodata[0] > 300) {
358 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
361 if ($photodata[1] > 300) {
362 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
365 $siteinfo['images'][] = [
367 'width' => $photodata[0],
368 'height' => $photodata[1]
372 } elseif (!empty($siteinfo['image'])) {
373 $src = self::completeUrl($siteinfo['image'], $url);
375 unset($siteinfo['image']);
377 $photodata = Image::getInfoFromURL($src);
379 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
380 $siteinfo['images'][] = ['src' => $src,
381 'width' => $photodata[0],
382 'height' => $photodata[1]];
386 if ((@$siteinfo['text'] == '') && (@$siteinfo['title'] != '') && !$no_guessing) {
389 $list = $xpath->query('//div[@class="article"]');
390 foreach ($list as $node) {
391 if (strlen($node->nodeValue) > 40) {
392 $text .= ' ' . trim($node->nodeValue);
397 $list = $xpath->query('//div[@class="content"]');
398 foreach ($list as $node) {
399 if (strlen($node->nodeValue) > 40) {
400 $text .= ' ' . trim($node->nodeValue);
405 // If none text was found then take the paragraph content
407 $list = $xpath->query('//p');
408 foreach ($list as $node) {
409 if (strlen($node->nodeValue) > 40) {
410 $text .= ' ' . trim($node->nodeValue);
416 $text = trim(str_replace(["\n", "\r"], [' ', ' '], $text));
418 while (strpos($text, ' ')) {
419 $text = trim(str_replace(' ', ' ', $text));
422 $siteinfo['text'] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, 'UTF-8') . '...');
426 Logger::log('Siteinfo for ' . $url . ' ' . print_r($siteinfo, true), Logger::DEBUG);
428 Addon::callHooks('getsiteinfo', $siteinfo);
434 * @brief Convert tags from CSV to an array
436 * @param string $string Tags
437 * @return array with formatted Hashtags
439 public static function convertTagsToArray($string)
441 $arr_tags = str_getcsv($string);
442 if (count($arr_tags)) {
443 // add the # sign to every tag
444 array_walk($arr_tags, ["self", "arrAddHashes"]);
451 * @brief Add a hasht sign to a string
453 * This method is used as callback function
455 * @param string $tag The pure tag name
456 * @param int $k Counter for internal use
459 private static function arrAddHashes(&$tag, $k)
465 * @brief Add a scheme to an url
467 * The src attribute of some html elements (e.g. images)
468 * can miss the scheme so we need to add the correct
471 * @param string $url The url which possibly does have
472 * a missing scheme (a link to an image)
473 * @param string $scheme The url with a correct scheme
474 * (e.g. the url from the webpage which does contain the image)
476 * @return string The url with a scheme
478 private static function completeUrl($url, $scheme)
480 $urlarr = parse_url($url);
482 // If the url does allready have an scheme
483 // we can stop the process here
484 if (isset($urlarr["scheme"])) {
488 $schemearr = parse_url($scheme);
490 $complete = $schemearr["scheme"]."://".$schemearr["host"];
492 if (!empty($schemearr["port"])) {
493 $complete .= ":".$schemearr["port"];
496 if (!empty($urlarr["path"])) {
497 if (strpos($urlarr["path"], "/") !== 0) {
501 $complete .= $urlarr["path"];
504 if (!empty($urlarr["query"])) {
505 $complete .= "?".$urlarr["query"];
508 if (!empty($urlarr["fragment"])) {
509 $complete .= "#".$urlarr["fragment"];