4 * @file include/ParseUrl.php
5 * @brief Get informations about a given URL
10 use \Friendica\Core\Config;
12 require_once("include/network.php");
13 require_once("include/Photo.php");
14 require_once("include/oembed.php");
17 * @brief Class with methods for extracting certain content from an url
21 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
27 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
28 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
31 $data = $r[0]["content"];
34 if (!is_null($data)) {
35 $data = unserialize($data);
39 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
41 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
42 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
43 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
44 dbesc(serialize($data)), dbesc(datetime_convert()),
45 dbesc(serialize($data)), dbesc(datetime_convert()));
50 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
56 // Check if the URL does contain a scheme
57 $scheme = parse_url($url, PHP_URL_SCHEME);
60 $url = "http://".trim($url, "/");
64 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
68 $url = trim($url, "'");
69 $url = trim($url, '"');
71 $url = original_url($url);
73 $siteinfo["url"] = $url;
74 $siteinfo["type"] = "link";
76 $check_cert = Config::get("system", "verifyssl");
78 $stamp1 = microtime(true);
81 curl_setopt($ch, CURLOPT_URL, $url);
82 curl_setopt($ch, CURLOPT_HEADER, 1);
83 curl_setopt($ch, CURLOPT_NOBODY, 1);
84 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
85 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
86 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
87 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
88 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
90 $header = curl_exec($ch);
91 $curl_info = @curl_getinfo($ch);
92 $http_code = $curl_info["http_code"];
95 $a->save_timestamp($stamp1, "network");
97 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
98 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
99 if ($curl_info["redirect_url"] != "") {
100 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
102 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
107 // If the file is too large then exit
108 if ($curl_info["download_content_length"] > 1000000) {
112 // If it isn't a HTML file then exit
113 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
119 $oembed_data = oembed_fetch_url($url);
121 if (!in_array($oembed_data->type, array("error", "rich"))) {
122 $siteinfo["type"] = $oembed_data->type;
125 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
126 if (isset($oembed_data->title)) {
127 $siteinfo["title"] = $oembed_data->title;
129 if (isset($oembed_data->description)) {
130 $siteinfo["text"] = trim($oembed_data->description);
132 if (isset($oembed_data->thumbnail_url)) {
133 $siteinfo["image"] = $oembed_data->thumbnail_url;
138 $stamp1 = microtime(true);
140 // Now fetch the body as well
142 curl_setopt($ch, CURLOPT_URL, $url);
143 curl_setopt($ch, CURLOPT_HEADER, 1);
144 curl_setopt($ch, CURLOPT_NOBODY, 0);
145 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
146 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
147 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
148 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
149 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
151 $header = curl_exec($ch);
152 $curl_info = @curl_getinfo($ch);
153 $http_code = $curl_info["http_code"];
156 $a->save_timestamp($stamp1, "network");
158 // Fetch the first mentioned charset. Can be in body or header
160 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
161 $charset = trim(trim(trim(array_pop($matches)), ';,'));
164 if ($charset == "") {
168 $pos = strpos($header, "\r\n\r\n");
171 $body = trim(substr($header, $pos));
176 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
177 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
178 //$body = mb_convert_encoding($body, "UTF-8", $charset);
179 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
182 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
184 $doc = new \DOMDocument();
185 @$doc->loadHTML($body);
187 self::deleteNode($doc, "style");
188 self::deleteNode($doc, "script");
189 self::deleteNode($doc, "option");
190 self::deleteNode($doc, "h1");
191 self::deleteNode($doc, "h2");
192 self::deleteNode($doc, "h3");
193 self::deleteNode($doc, "h4");
194 self::deleteNode($doc, "h5");
195 self::deleteNode($doc, "h6");
196 self::deleteNode($doc, "ol");
197 self::deleteNode($doc, "ul");
199 $xpath = new \DomXPath($doc);
201 $list = $xpath->query("//meta[@content]");
202 foreach ($list as $node) {
204 if ($node->attributes->length) {
205 foreach ($node->attributes as $attribute) {
206 $attr[$attribute->name] = $attribute->value;
210 if (@$attr["http-equiv"] == "refresh") {
211 $path = $attr["content"];
212 $pathinfo = explode(";", $path);
214 foreach ($pathinfo as $value) {
215 if (substr(strtolower($value), 0, 4) == "url=") {
216 $content = substr($value, 4);
219 if ($content != "") {
220 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
226 $list = $xpath->query("//title");
227 if ($list->length > 0) {
228 $siteinfo["title"] = $list->item(0)->nodeValue;
231 //$list = $xpath->query("head/meta[@name]");
232 $list = $xpath->query("//meta[@name]");
233 foreach ($list as $node) {
235 if ($node->attributes->length) {
236 foreach ($node->attributes as $attribute) {
237 $attr[$attribute->name] = $attribute->value;
241 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
243 if ($attr["content"] != "") {
244 switch (strtolower($attr["name"])) {
246 $siteinfo["title"] = $attr["content"];
249 $siteinfo["text"] = $attr["content"];
252 $siteinfo["image"] = $attr["content"];
254 case "twitter:image":
255 $siteinfo["image"] = $attr["content"];
257 case "twitter:image:src":
258 $siteinfo["image"] = $attr["content"];
261 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
262 $siteinfo["type"] = $attr["content"];
265 case "twitter:description":
266 $siteinfo["text"] = $attr["content"];
268 case "twitter:title":
269 $siteinfo["title"] = $attr["content"];
272 $siteinfo["title"] = $attr["content"];
274 case "dc.description":
275 $siteinfo["text"] = $attr["content"];
278 $keywords = explode(",", $attr["content"]);
280 case "news_keywords":
281 $keywords = explode(",", $attr["content"]);
285 if ($siteinfo["type"] == "summary") {
286 $siteinfo["type"] = "link";
290 if (isset($keywords)) {
291 $siteinfo["keywords"] = array();
292 foreach ($keywords as $keyword) {
293 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
294 $siteinfo["keywords"][] = trim($keyword);
299 //$list = $xpath->query("head/meta[@property]");
300 $list = $xpath->query("//meta[@property]");
301 foreach ($list as $node) {
303 if ($node->attributes->length) {
304 foreach ($node->attributes as $attribute) {
305 $attr[$attribute->name] = $attribute->value;
309 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
311 if ($attr["content"] != "") {
312 switch (strtolower($attr["property"])) {
314 $siteinfo["image"] = $attr["content"];
317 $siteinfo["title"] = $attr["content"];
319 case "og:description":
320 $siteinfo["text"] = $attr["content"];
326 if ((@$siteinfo["image"] == "") && !$no_guessing) {
327 $list = $xpath->query("//img[@src]");
328 foreach ($list as $node) {
330 if ($node->attributes->length) {
331 foreach ($node->attributes as $attribute) {
332 $attr[$attribute->name] = $attribute->value;
336 $src = self::completeUrl($attr["src"], $url);
337 $photodata = get_photo_info($src);
339 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
340 if ($photodata[0] > 300) {
341 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
344 if ($photodata[1] > 300) {
345 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
348 $siteinfo["images"][] = array("src" => $src,
349 "width" => $photodata[0],
350 "height" => $photodata[1]);
354 } elseif ($siteinfo["image"] != "") {
355 $src = self::completeUrl($siteinfo["image"], $url);
357 unset($siteinfo["image"]);
359 $photodata = get_photo_info($src);
361 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
362 $siteinfo["images"][] = array("src" => $src,
363 "width" => $photodata[0],
364 "height" => $photodata[1]);
368 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
371 $list = $xpath->query("//div[@class='article']");
372 foreach ($list as $node) {
373 if (strlen($node->nodeValue) > 40) {
374 $text .= " ".trim($node->nodeValue);
379 $list = $xpath->query("//div[@class='content']");
380 foreach ($list as $node) {
381 if (strlen($node->nodeValue) > 40) {
382 $text .= " ".trim($node->nodeValue);
387 // If none text was found then take the paragraph content
389 $list = $xpath->query("//p");
390 foreach ($list as $node) {
391 if (strlen($node->nodeValue) > 40) {
392 $text .= " ".trim($node->nodeValue);
398 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
400 while (strpos($text, " ")) {
401 $text = trim(str_replace(" ", " ", $text));
404 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
408 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
410 call_hooks("getsiteinfo", $siteinfo);
416 * @brief Convert tags from CSV to an array
418 * @param string $string Tags
419 * @return array with formatted Hashtags
421 public static function convertTagsToArray($string) {
422 $arr_tags = str_getcsv($string);
423 if (count($arr_tags)) {
424 // add the # sign to every tag
425 array_walk($arr_tags, array("self", "arrAddHashes"));
432 * @brief Add a hasht sign to a string
434 * This method is used as callback function
436 * @param string $tag The pure tag name
437 * @param int $k Counter for internal use
439 private static function arrAddHashes(&$tag, $k) {
443 private static function deleteNode(&$doc, $node) {
444 $xpath = new \DomXPath($doc);
445 $list = $xpath->query("//".$node);
446 foreach ($list as $child) {
447 $child->parentNode->removeChild($child);
451 private static function completeUrl($url, $scheme) {
452 $urlarr = parse_url($url);
454 if (isset($urlarr["scheme"])) {
458 $schemearr = parse_url($scheme);
460 $complete = $schemearr["scheme"]."://".$schemearr["host"];
462 if (@$schemearr["port"] != "") {
463 $complete .= ":".$schemearr["port"];
466 if (strpos($urlarr["path"],"/") !== 0) {
470 $complete .= $urlarr["path"];
472 if (@$urlarr["query"] != "") {
473 $complete .= "?".$urlarr["query"];
476 if (@$urlarr["fragment"] != "") {
477 $complete .= "#".$urlarr["fragment"];