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
23 * @brief Search for chached embeddable data of an url otherwise fetch it
25 * @param type $url The url of the page which should be scraped
26 * @param type $no_guessing If true the parse doens't search for
28 * @param type $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 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
51 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
54 $data = $r[0]["content"];
57 if (!is_null($data)) {
58 $data = unserialize($data);
62 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
64 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
65 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
66 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
67 dbesc(serialize($data)), dbesc(datetime_convert()),
68 dbesc(serialize($data)), dbesc(datetime_convert()));
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 type $url The url of the page which should be scraped
83 * @param type $no_guessing If true the parse doens't search for
85 * @param type $do_oembed The false option is used by the function fetch_oembed()
86 * to avoid endless loops
87 * @param type $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("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
130 $url = trim($url, "'");
131 $url = trim($url, '"');
133 $url = strip_tracking_query_params($url);
135 $siteinfo["url"] = $url;
136 $siteinfo["type"] = "link";
138 $check_cert = Config::get("system", "verifyssl");
140 $stamp1 = microtime(true);
143 curl_setopt($ch, CURLOPT_URL, $url);
144 curl_setopt($ch, CURLOPT_HEADER, 1);
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));
150 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
153 $header = curl_exec($ch);
154 $curl_info = @curl_getinfo($ch);
157 $a->save_timestamp($stamp1, "network");
159 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
160 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
161 if ($curl_info["redirect_url"] != "") {
162 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
164 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
169 // If the file is too large then exit
170 if ($curl_info["download_content_length"] > 1000000) {
174 // If it isn't a HTML file then exit
175 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
181 $oembed_data = oembed_fetch_url($url);
183 if (!in_array($oembed_data->type, array("error", "rich"))) {
184 $siteinfo["type"] = $oembed_data->type;
187 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
188 if (isset($oembed_data->title)) {
189 $siteinfo["title"] = $oembed_data->title;
191 if (isset($oembed_data->description)) {
192 $siteinfo["text"] = trim($oembed_data->description);
194 if (isset($oembed_data->thumbnail_url)) {
195 $siteinfo["image"] = $oembed_data->thumbnail_url;
200 // Fetch the first mentioned charset. Can be in body or header
202 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
203 $charset = trim(trim(trim(array_pop($matches)), ';,'));
206 if ($charset == "") {
210 $pos = strpos($header, "\r\n\r\n");
213 $body = trim(substr($header, $pos));
218 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
219 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
220 //$body = mb_convert_encoding($body, "UTF-8", $charset);
221 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
224 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
226 $doc = new \DOMDocument();
227 @$doc->loadHTML($body);
229 \xml::deleteNode($doc, "style");
230 \xml::deleteNode($doc, "script");
231 \xml::deleteNode($doc, "option");
232 \xml::deleteNode($doc, "h1");
233 \xml::deleteNode($doc, "h2");
234 \xml::deleteNode($doc, "h3");
235 \xml::deleteNode($doc, "h4");
236 \xml::deleteNode($doc, "h5");
237 \xml::deleteNode($doc, "h6");
238 \xml::deleteNode($doc, "ol");
239 \xml::deleteNode($doc, "ul");
241 $xpath = new \DomXPath($doc);
243 $list = $xpath->query("//meta[@content]");
244 foreach ($list as $node) {
246 if ($node->attributes->length) {
247 foreach ($node->attributes as $attribute) {
248 $attr[$attribute->name] = $attribute->value;
252 if (@$attr["http-equiv"] == "refresh") {
253 $path = $attr["content"];
254 $pathinfo = explode(";", $path);
256 foreach ($pathinfo as $value) {
257 if (substr(strtolower($value), 0, 4) == "url=") {
258 $content = substr($value, 4);
261 if ($content != "") {
262 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
268 $list = $xpath->query("//title");
269 if ($list->length > 0) {
270 $siteinfo["title"] = $list->item(0)->nodeValue;
273 //$list = $xpath->query("head/meta[@name]");
274 $list = $xpath->query("//meta[@name]");
275 foreach ($list as $node) {
277 if ($node->attributes->length) {
278 foreach ($node->attributes as $attribute) {
279 $attr[$attribute->name] = $attribute->value;
283 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
285 if ($attr["content"] != "") {
286 switch (strtolower($attr["name"])) {
288 $siteinfo["title"] = $attr["content"];
291 $siteinfo["text"] = $attr["content"];
294 $siteinfo["image"] = $attr["content"];
296 case "twitter:image":
297 $siteinfo["image"] = $attr["content"];
299 case "twitter:image:src":
300 $siteinfo["image"] = $attr["content"];
303 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
304 $siteinfo["type"] = $attr["content"];
307 case "twitter:description":
308 $siteinfo["text"] = $attr["content"];
310 case "twitter:title":
311 $siteinfo["title"] = $attr["content"];
314 $siteinfo["title"] = $attr["content"];
316 case "dc.description":
317 $siteinfo["text"] = $attr["content"];
320 $keywords = explode(",", $attr["content"]);
322 case "news_keywords":
323 $keywords = explode(",", $attr["content"]);
327 if ($siteinfo["type"] == "summary") {
328 $siteinfo["type"] = "link";
332 if (isset($keywords)) {
333 $siteinfo["keywords"] = array();
334 foreach ($keywords as $keyword) {
335 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
336 $siteinfo["keywords"][] = trim($keyword);
341 //$list = $xpath->query("head/meta[@property]");
342 $list = $xpath->query("//meta[@property]");
343 foreach ($list as $node) {
345 if ($node->attributes->length) {
346 foreach ($node->attributes as $attribute) {
347 $attr[$attribute->name] = $attribute->value;
351 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
353 if ($attr["content"] != "") {
354 switch (strtolower($attr["property"])) {
356 $siteinfo["image"] = $attr["content"];
359 $siteinfo["title"] = $attr["content"];
361 case "og:description":
362 $siteinfo["text"] = $attr["content"];
368 if ((@$siteinfo["image"] == "") && !$no_guessing) {
369 $list = $xpath->query("//img[@src]");
370 foreach ($list as $node) {
372 if ($node->attributes->length) {
373 foreach ($node->attributes as $attribute) {
374 $attr[$attribute->name] = $attribute->value;
378 $src = self::completeUrl($attr["src"], $url);
379 $photodata = get_photo_info($src);
381 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
382 if ($photodata[0] > 300) {
383 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
386 if ($photodata[1] > 300) {
387 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
390 $siteinfo["images"][] = array("src" => $src,
391 "width" => $photodata[0],
392 "height" => $photodata[1]);
396 } elseif ($siteinfo["image"] != "") {
397 $src = self::completeUrl($siteinfo["image"], $url);
399 unset($siteinfo["image"]);
401 $photodata = get_photo_info($src);
403 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
404 $siteinfo["images"][] = array("src" => $src,
405 "width" => $photodata[0],
406 "height" => $photodata[1]);
410 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
413 $list = $xpath->query("//div[@class='article']");
414 foreach ($list as $node) {
415 if (strlen($node->nodeValue) > 40) {
416 $text .= " ".trim($node->nodeValue);
421 $list = $xpath->query("//div[@class='content']");
422 foreach ($list as $node) {
423 if (strlen($node->nodeValue) > 40) {
424 $text .= " ".trim($node->nodeValue);
429 // If none text was found then take the paragraph content
431 $list = $xpath->query("//p");
432 foreach ($list as $node) {
433 if (strlen($node->nodeValue) > 40) {
434 $text .= " ".trim($node->nodeValue);
440 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
442 while (strpos($text, " ")) {
443 $text = trim(str_replace(" ", " ", $text));
446 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
450 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
452 call_hooks("getsiteinfo", $siteinfo);
458 * @brief Convert tags from CSV to an array
460 * @param string $string Tags
461 * @return array with formatted Hashtags
463 public static function convertTagsToArray($string) {
464 $arr_tags = str_getcsv($string);
465 if (count($arr_tags)) {
466 // add the # sign to every tag
467 array_walk($arr_tags, array("self", "arrAddHashes"));
474 * @brief Add a hasht sign to a string
476 * This method is used as callback function
478 * @param string $tag The pure tag name
479 * @param int $k Counter for internal use
481 private static function arrAddHashes(&$tag, $k) {
486 * @brief Add a scheme to an url
488 * The src attribute of some html elements (e.g. images)
489 * can miss the scheme so we need to add the correct
492 * @param string $url The url which possibly does have
493 * a missing scheme (a link to an image)
494 * @param string $scheme The url with a correct scheme
495 * (e.g. the url from the webpage which does contain the image)
497 * @return string The url with a scheme
499 private static function completeUrl($url, $scheme) {
500 $urlarr = parse_url($url);
502 // If the url does allready have an scheme
503 // we can stop the process here
504 if (isset($urlarr["scheme"])) {
508 $schemearr = parse_url($scheme);
510 $complete = $schemearr["scheme"]."://".$schemearr["host"];
512 if (@$schemearr["port"] != "") {
513 $complete .= ":".$schemearr["port"];
516 if (strpos($urlarr["path"],"/") !== 0) {
520 $complete .= $urlarr["path"];
522 if (@$urlarr["query"] != "") {
523 $complete .= "?".$urlarr["query"];
526 if (@$urlarr["fragment"] != "") {
527 $complete .= "#".$urlarr["fragment"];