4 * @file include/ParseUrl.php
5 * @brief Get informations about a given URL
10 use Friendica\Core\Config;
17 require_once("include/network.php");
18 require_once("include/Photo.php");
19 require_once("include/oembed.php");
20 require_once("include/xml.php");
23 * @brief Class with methods for extracting certain content from an url
28 * @brief Search for chached embeddable data of an url otherwise fetch it
30 * @param type $url The url of the page which should be scraped
31 * @param type $no_guessing If true the parse doens't search for
33 * @param type $do_oembed The false option is used by the function fetch_oembed()
34 * to avoid endless loops
36 * @return array which contains needed data for embedding
37 * string 'url' => The url of the parsed page
38 * string 'type' => Content type
39 * string 'title' => The title of the content
40 * string 'text' => The description for the content
41 * string 'image' => A preview image of the content (only available
42 * if $no_geuessing = false
43 * array'images' = Array of preview pictures
44 * string 'keywords' => The tags which belong to the content
46 * @see ParseUrl::getSiteinfo() for more information about scraping
49 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
55 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
56 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
59 $data = $r[0]["content"];
62 if (!is_null($data)) {
63 $data = unserialize($data);
67 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
69 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
70 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
71 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
72 dbesc(serialize($data)), dbesc(datetime_convert()),
73 dbesc(serialize($data)), dbesc(datetime_convert()));
78 * @brief Parse a page for embeddable content information
80 * This method parses to url for meta data which can be used to embed
81 * the content. If available it prioritizes Open Graph meta tags.
82 * If this is not available it uses the twitter cards meta tags.
83 * As fallback it uses standard html elements with meta informations
84 * like \<title\>Awesome Title\</title\> or
85 * \<meta name="description" content="An awesome description"\>
87 * @param type $url The url of the page which should be scraped
88 * @param type $no_guessing If true the parse doens't search for
90 * @param type $do_oembed The false option is used by the function fetch_oembed()
91 * to avoid endless loops
92 * @param type $count Internal counter to avoid endless loops
94 * @return array which contains needed data for embedding
95 * string 'url' => The url of the parsed page
96 * string 'type' => Content type
97 * string 'title' => The title of the content
98 * string 'text' => The description for the content
99 * string 'image' => A preview image of the content (only available
100 * if $no_geuessing = false
101 * array'images' = Array of preview pictures
102 * string 'keywords' => The tags which belong to the content
104 * @todo https://developers.google.com/+/plugins/snippet/
106 * <meta itemprop="name" content="Awesome title">
107 * <meta itemprop="description" content="An awesome description">
108 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
110 * <body itemscope itemtype="http://schema.org/Product">
111 * <h1 itemprop="name">Shiny Trinket</h1>
112 * <img itemprop="image" src="{image-url}" />
113 * <p itemprop="description">Shiny trinkets are shiny.</p>
117 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
123 // Check if the URL does contain a scheme
124 $scheme = parse_url($url, PHP_URL_SCHEME);
127 $url = "http://".trim($url, "/");
131 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
135 $url = trim($url, "'");
136 $url = trim($url, '"');
138 $url = strip_tracking_query_params($url);
140 $siteinfo["url"] = $url;
141 $siteinfo["type"] = "link";
143 $check_cert = Config::get("system", "verifyssl");
145 $stamp1 = microtime(true);
148 curl_setopt($ch, CURLOPT_URL, $url);
149 curl_setopt($ch, CURLOPT_HEADER, 1);
150 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
151 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
152 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
153 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
155 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
158 $range = intval(Config::get('system', 'curl_range_bytes', 0));
161 curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
164 $header = curl_exec($ch);
165 $curl_info = @curl_getinfo($ch);
168 $a->save_timestamp($stamp1, "network");
170 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
171 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
172 if ($curl_info["redirect_url"] != "") {
173 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
175 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
180 // If the file is too large then exit
181 if ($curl_info["download_content_length"] > 1000000) {
185 // If it isn't a HTML file then exit
186 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
192 $oembed_data = oembed_fetch_url($url);
194 if (!in_array($oembed_data->type, array("error", "rich"))) {
195 $siteinfo["type"] = $oembed_data->type;
198 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
199 if (isset($oembed_data->title)) {
200 $siteinfo["title"] = $oembed_data->title;
202 if (isset($oembed_data->description)) {
203 $siteinfo["text"] = trim($oembed_data->description);
205 if (isset($oembed_data->thumbnail_url)) {
206 $siteinfo["image"] = $oembed_data->thumbnail_url;
211 // Fetch the first mentioned charset. Can be in body or header
213 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
214 $charset = trim(trim(trim(array_pop($matches)), ';,'));
217 if ($charset == "") {
221 $pos = strpos($header, "\r\n\r\n");
224 $body = trim(substr($header, $pos));
229 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
230 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
231 //$body = mb_convert_encoding($body, "UTF-8", $charset);
232 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
235 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
237 $doc = new DOMDocument();
238 @$doc->loadHTML($body);
240 xml::deleteNode($doc, "style");
241 xml::deleteNode($doc, "script");
242 xml::deleteNode($doc, "option");
243 xml::deleteNode($doc, "h1");
244 xml::deleteNode($doc, "h2");
245 xml::deleteNode($doc, "h3");
246 xml::deleteNode($doc, "h4");
247 xml::deleteNode($doc, "h5");
248 xml::deleteNode($doc, "h6");
249 xml::deleteNode($doc, "ol");
250 xml::deleteNode($doc, "ul");
252 $xpath = new DomXPath($doc);
254 $list = $xpath->query("//meta[@content]");
255 foreach ($list as $node) {
257 if ($node->attributes->length) {
258 foreach ($node->attributes as $attribute) {
259 $attr[$attribute->name] = $attribute->value;
263 if (@$attr["http-equiv"] == "refresh") {
264 $path = $attr["content"];
265 $pathinfo = explode(";", $path);
267 foreach ($pathinfo as $value) {
268 if (substr(strtolower($value), 0, 4) == "url=") {
269 $content = substr($value, 4);
272 if ($content != "") {
273 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
279 $list = $xpath->query("//title");
280 if ($list->length > 0) {
281 $siteinfo["title"] = $list->item(0)->nodeValue;
284 //$list = $xpath->query("head/meta[@name]");
285 $list = $xpath->query("//meta[@name]");
286 foreach ($list as $node) {
288 if ($node->attributes->length) {
289 foreach ($node->attributes as $attribute) {
290 $attr[$attribute->name] = $attribute->value;
294 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
296 if ($attr["content"] != "") {
297 switch (strtolower($attr["name"])) {
299 $siteinfo["title"] = $attr["content"];
302 $siteinfo["text"] = $attr["content"];
305 $siteinfo["image"] = $attr["content"];
307 case "twitter:image":
308 $siteinfo["image"] = $attr["content"];
310 case "twitter:image:src":
311 $siteinfo["image"] = $attr["content"];
314 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
315 $siteinfo["type"] = $attr["content"];
318 case "twitter:description":
319 $siteinfo["text"] = $attr["content"];
321 case "twitter:title":
322 $siteinfo["title"] = $attr["content"];
325 $siteinfo["title"] = $attr["content"];
327 case "dc.description":
328 $siteinfo["text"] = $attr["content"];
331 $keywords = explode(",", $attr["content"]);
333 case "news_keywords":
334 $keywords = explode(",", $attr["content"]);
338 if ($siteinfo["type"] == "summary") {
339 $siteinfo["type"] = "link";
343 if (isset($keywords)) {
344 $siteinfo["keywords"] = array();
345 foreach ($keywords as $keyword) {
346 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
347 $siteinfo["keywords"][] = trim($keyword);
352 //$list = $xpath->query("head/meta[@property]");
353 $list = $xpath->query("//meta[@property]");
354 foreach ($list as $node) {
356 if ($node->attributes->length) {
357 foreach ($node->attributes as $attribute) {
358 $attr[$attribute->name] = $attribute->value;
362 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
364 if ($attr["content"] != "") {
365 switch (strtolower($attr["property"])) {
367 $siteinfo["image"] = $attr["content"];
370 $siteinfo["title"] = $attr["content"];
372 case "og:description":
373 $siteinfo["text"] = $attr["content"];
379 if ((@$siteinfo["image"] == "") && !$no_guessing) {
380 $list = $xpath->query("//img[@src]");
381 foreach ($list as $node) {
383 if ($node->attributes->length) {
384 foreach ($node->attributes as $attribute) {
385 $attr[$attribute->name] = $attribute->value;
389 $src = self::completeUrl($attr["src"], $url);
390 $photodata = get_photo_info($src);
392 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
393 if ($photodata[0] > 300) {
394 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
397 if ($photodata[1] > 300) {
398 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
401 $siteinfo["images"][] = array("src" => $src,
402 "width" => $photodata[0],
403 "height" => $photodata[1]);
407 } elseif ($siteinfo["image"] != "") {
408 $src = self::completeUrl($siteinfo["image"], $url);
410 unset($siteinfo["image"]);
412 $photodata = get_photo_info($src);
414 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
415 $siteinfo["images"][] = array("src" => $src,
416 "width" => $photodata[0],
417 "height" => $photodata[1]);
421 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
424 $list = $xpath->query("//div[@class='article']");
425 foreach ($list as $node) {
426 if (strlen($node->nodeValue) > 40) {
427 $text .= " ".trim($node->nodeValue);
432 $list = $xpath->query("//div[@class='content']");
433 foreach ($list as $node) {
434 if (strlen($node->nodeValue) > 40) {
435 $text .= " ".trim($node->nodeValue);
440 // If none text was found then take the paragraph content
442 $list = $xpath->query("//p");
443 foreach ($list as $node) {
444 if (strlen($node->nodeValue) > 40) {
445 $text .= " ".trim($node->nodeValue);
451 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
453 while (strpos($text, " ")) {
454 $text = trim(str_replace(" ", " ", $text));
457 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
461 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
463 call_hooks("getsiteinfo", $siteinfo);
469 * @brief Convert tags from CSV to an array
471 * @param string $string Tags
472 * @return array with formatted Hashtags
474 public static function convertTagsToArray($string) {
475 $arr_tags = str_getcsv($string);
476 if (count($arr_tags)) {
477 // add the # sign to every tag
478 array_walk($arr_tags, array("self", "arrAddHashes"));
485 * @brief Add a hasht sign to a string
487 * This method is used as callback function
489 * @param string $tag The pure tag name
490 * @param int $k Counter for internal use
492 private static function arrAddHashes(&$tag, $k) {
497 * @brief Add a scheme to an url
499 * The src attribute of some html elements (e.g. images)
500 * can miss the scheme so we need to add the correct
503 * @param string $url The url which possibly does have
504 * a missing scheme (a link to an image)
505 * @param string $scheme The url with a correct scheme
506 * (e.g. the url from the webpage which does contain the image)
508 * @return string The url with a scheme
510 private static function completeUrl($url, $scheme) {
511 $urlarr = parse_url($url);
513 // If the url does allready have an scheme
514 // we can stop the process here
515 if (isset($urlarr["scheme"])) {
519 $schemearr = parse_url($scheme);
521 $complete = $schemearr["scheme"]."://".$schemearr["host"];
523 if (@$schemearr["port"] != "") {
524 $complete .= ":".$schemearr["port"];
527 if (strpos($urlarr["path"],"/") !== 0) {
531 $complete .= $urlarr["path"];
533 if (@$urlarr["query"] != "") {
534 $complete .= "?".$urlarr["query"];
537 if (@$urlarr["fragment"] != "") {
538 $complete .= "#".$urlarr["fragment"];