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");
15 require_once("include/xml.php");
18 * @brief Class with methods for extracting certain content from an url
22 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
28 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
29 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
32 $data = $r[0]["content"];
35 if (!is_null($data)) {
36 $data = unserialize($data);
40 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
42 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
43 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
44 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
45 dbesc(serialize($data)), dbesc(datetime_convert()),
46 dbesc(serialize($data)), dbesc(datetime_convert()));
51 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
57 // Check if the URL does contain a scheme
58 $scheme = parse_url($url, PHP_URL_SCHEME);
61 $url = "http://".trim($url, "/");
65 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
69 $url = trim($url, "'");
70 $url = trim($url, '"');
72 $url = original_url($url);
74 $siteinfo["url"] = $url;
75 $siteinfo["type"] = "link";
77 $check_cert = Config::get("system", "verifyssl");
79 $stamp1 = microtime(true);
82 curl_setopt($ch, CURLOPT_URL, $url);
83 curl_setopt($ch, CURLOPT_HEADER, 1);
84 curl_setopt($ch, CURLOPT_NOBODY, 1);
85 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
86 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
87 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
88 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
89 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
91 $header = curl_exec($ch);
92 $curl_info = @curl_getinfo($ch);
93 $http_code = $curl_info["http_code"];
96 $a->save_timestamp($stamp1, "network");
98 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
99 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
100 if ($curl_info["redirect_url"] != "") {
101 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
103 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
108 // If the file is too large then exit
109 if ($curl_info["download_content_length"] > 1000000) {
113 // If it isn't a HTML file then exit
114 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
120 $oembed_data = oembed_fetch_url($url);
122 if (!in_array($oembed_data->type, array("error", "rich"))) {
123 $siteinfo["type"] = $oembed_data->type;
126 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
127 if (isset($oembed_data->title)) {
128 $siteinfo["title"] = $oembed_data->title;
130 if (isset($oembed_data->description)) {
131 $siteinfo["text"] = trim($oembed_data->description);
133 if (isset($oembed_data->thumbnail_url)) {
134 $siteinfo["image"] = $oembed_data->thumbnail_url;
139 $stamp1 = microtime(true);
141 // Now fetch the body as well
143 curl_setopt($ch, CURLOPT_URL, $url);
144 curl_setopt($ch, CURLOPT_HEADER, 1);
145 curl_setopt($ch, CURLOPT_NOBODY, 0);
146 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
147 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
148 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
149 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
150 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
152 $header = curl_exec($ch);
153 $curl_info = @curl_getinfo($ch);
154 $http_code = $curl_info["http_code"];
157 $a->save_timestamp($stamp1, "network");
159 // Fetch the first mentioned charset. Can be in body or header
161 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
162 $charset = trim(trim(trim(array_pop($matches)), ';,'));
165 if ($charset == "") {
169 $pos = strpos($header, "\r\n\r\n");
172 $body = trim(substr($header, $pos));
177 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
178 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
179 //$body = mb_convert_encoding($body, "UTF-8", $charset);
180 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
183 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
185 $doc = new \DOMDocument();
186 @$doc->loadHTML($body);
188 \xml::deleteNode($doc, "style");
189 \xml::deleteNode($doc, "script");
190 \xml::deleteNode($doc, "option");
191 \xml::deleteNode($doc, "h1");
192 \xml::deleteNode($doc, "h2");
193 \xml::deleteNode($doc, "h3");
194 \xml::deleteNode($doc, "h4");
195 \xml::deleteNode($doc, "h5");
196 \xml::deleteNode($doc, "h6");
197 \xml::deleteNode($doc, "ol");
198 \xml::deleteNode($doc, "ul");
200 $xpath = new \DomXPath($doc);
202 $list = $xpath->query("//meta[@content]");
203 foreach ($list as $node) {
205 if ($node->attributes->length) {
206 foreach ($node->attributes as $attribute) {
207 $attr[$attribute->name] = $attribute->value;
211 if (@$attr["http-equiv"] == "refresh") {
212 $path = $attr["content"];
213 $pathinfo = explode(";", $path);
215 foreach ($pathinfo as $value) {
216 if (substr(strtolower($value), 0, 4) == "url=") {
217 $content = substr($value, 4);
220 if ($content != "") {
221 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
227 $list = $xpath->query("//title");
228 if ($list->length > 0) {
229 $siteinfo["title"] = $list->item(0)->nodeValue;
232 //$list = $xpath->query("head/meta[@name]");
233 $list = $xpath->query("//meta[@name]");
234 foreach ($list as $node) {
236 if ($node->attributes->length) {
237 foreach ($node->attributes as $attribute) {
238 $attr[$attribute->name] = $attribute->value;
242 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
244 if ($attr["content"] != "") {
245 switch (strtolower($attr["name"])) {
247 $siteinfo["title"] = $attr["content"];
250 $siteinfo["text"] = $attr["content"];
253 $siteinfo["image"] = $attr["content"];
255 case "twitter:image":
256 $siteinfo["image"] = $attr["content"];
258 case "twitter:image:src":
259 $siteinfo["image"] = $attr["content"];
262 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
263 $siteinfo["type"] = $attr["content"];
266 case "twitter:description":
267 $siteinfo["text"] = $attr["content"];
269 case "twitter:title":
270 $siteinfo["title"] = $attr["content"];
273 $siteinfo["title"] = $attr["content"];
275 case "dc.description":
276 $siteinfo["text"] = $attr["content"];
279 $keywords = explode(",", $attr["content"]);
281 case "news_keywords":
282 $keywords = explode(",", $attr["content"]);
286 if ($siteinfo["type"] == "summary") {
287 $siteinfo["type"] = "link";
291 if (isset($keywords)) {
292 $siteinfo["keywords"] = array();
293 foreach ($keywords as $keyword) {
294 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
295 $siteinfo["keywords"][] = trim($keyword);
300 //$list = $xpath->query("head/meta[@property]");
301 $list = $xpath->query("//meta[@property]");
302 foreach ($list as $node) {
304 if ($node->attributes->length) {
305 foreach ($node->attributes as $attribute) {
306 $attr[$attribute->name] = $attribute->value;
310 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
312 if ($attr["content"] != "") {
313 switch (strtolower($attr["property"])) {
315 $siteinfo["image"] = $attr["content"];
318 $siteinfo["title"] = $attr["content"];
320 case "og:description":
321 $siteinfo["text"] = $attr["content"];
327 if ((@$siteinfo["image"] == "") && !$no_guessing) {
328 $list = $xpath->query("//img[@src]");
329 foreach ($list as $node) {
331 if ($node->attributes->length) {
332 foreach ($node->attributes as $attribute) {
333 $attr[$attribute->name] = $attribute->value;
337 $src = self::completeUrl($attr["src"], $url);
338 $photodata = get_photo_info($src);
340 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
341 if ($photodata[0] > 300) {
342 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
345 if ($photodata[1] > 300) {
346 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
349 $siteinfo["images"][] = array("src" => $src,
350 "width" => $photodata[0],
351 "height" => $photodata[1]);
355 } elseif ($siteinfo["image"] != "") {
356 $src = self::completeUrl($siteinfo["image"], $url);
358 unset($siteinfo["image"]);
360 $photodata = get_photo_info($src);
362 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
363 $siteinfo["images"][] = array("src" => $src,
364 "width" => $photodata[0],
365 "height" => $photodata[1]);
369 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
372 $list = $xpath->query("//div[@class='article']");
373 foreach ($list as $node) {
374 if (strlen($node->nodeValue) > 40) {
375 $text .= " ".trim($node->nodeValue);
380 $list = $xpath->query("//div[@class='content']");
381 foreach ($list as $node) {
382 if (strlen($node->nodeValue) > 40) {
383 $text .= " ".trim($node->nodeValue);
388 // If none text was found then take the paragraph content
390 $list = $xpath->query("//p");
391 foreach ($list as $node) {
392 if (strlen($node->nodeValue) > 40) {
393 $text .= " ".trim($node->nodeValue);
399 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
401 while (strpos($text, " ")) {
402 $text = trim(str_replace(" ", " ", $text));
405 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
409 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
411 call_hooks("getsiteinfo", $siteinfo);
417 * @brief Convert tags from CSV to an array
419 * @param string $string Tags
420 * @return array with formatted Hashtags
422 public static function convertTagsToArray($string) {
423 $arr_tags = str_getcsv($string);
424 if (count($arr_tags)) {
425 // add the # sign to every tag
426 array_walk($arr_tags, array("self", "arrAddHashes"));
433 * @brief Add a hasht sign to a string
435 * This method is used as callback function
437 * @param string $tag The pure tag name
438 * @param int $k Counter for internal use
440 private static function arrAddHashes(&$tag, $k) {
444 private static function completeUrl($url, $scheme) {
445 $urlarr = parse_url($url);
447 if (isset($urlarr["scheme"])) {
451 $schemearr = parse_url($scheme);
453 $complete = $schemearr["scheme"]."://".$schemearr["host"];
455 if (@$schemearr["port"] != "") {
456 $complete .= ":".$schemearr["port"];
459 if (strpos($urlarr["path"],"/") !== 0) {
463 $complete .= $urlarr["path"];
465 if (@$urlarr["query"] != "") {
466 $complete .= "?".$urlarr["query"];
469 if (@$urlarr["fragment"] != "") {
470 $complete .= "#".$urlarr["fragment"];