4 * @file include/ParseUrl.php
5 * @brief Get informations about a given URL
10 use Friendica\Core\Config;
18 require_once("include/network.php");
19 require_once("include/Photo.php");
20 require_once("include/oembed.php");
21 require_once("include/xml.php");
24 * @brief Class with methods for extracting certain content from an url
29 * @brief Search for chached embeddable data of an url otherwise fetch it
31 * @param type $url The url of the page which should be scraped
32 * @param type $no_guessing If true the parse doens't search for
34 * @param type $do_oembed The false option is used by the function fetch_oembed()
35 * to avoid endless loops
37 * @return array which contains needed data for embedding
38 * string 'url' => The url of the parsed page
39 * string 'type' => Content type
40 * string 'title' => The title of the content
41 * string 'text' => The description for the content
42 * string 'image' => A preview image of the content (only available
43 * if $no_geuessing = false
44 * array'images' = Array of preview pictures
45 * string 'keywords' => The tags which belong to the content
47 * @see ParseUrl::getSiteinfo() for more information about scraping
50 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
56 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
57 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
60 $data = $r[0]["content"];
63 if (!is_null($data)) {
64 $data = unserialize($data);
68 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
70 dba::insert('parsed_url', array('url' => normalise_link($url), 'guessing' => !$no_guessing,
71 'oembed' => $do_oembed, 'content' => serialize($data),
72 'created' => datetime_convert()), true);
77 * @brief Parse a page for embeddable content information
79 * This method parses to url for meta data which can be used to embed
80 * the content. If available it prioritizes Open Graph meta tags.
81 * If this is not available it uses the twitter cards meta tags.
82 * As fallback it uses standard html elements with meta informations
83 * like \<title\>Awesome Title\</title\> or
84 * \<meta name="description" content="An awesome description"\>
86 * @param type $url The url of the page which should be scraped
87 * @param type $no_guessing If true the parse doens't search for
89 * @param type $do_oembed The false option is used by the function fetch_oembed()
90 * to avoid endless loops
91 * @param type $count Internal counter to avoid endless loops
93 * @return array which contains needed data for embedding
94 * string 'url' => The url of the parsed page
95 * string 'type' => Content type
96 * string 'title' => The title of the content
97 * string 'text' => The description for the content
98 * string 'image' => A preview image of the content (only available
99 * if $no_geuessing = false
100 * array'images' = Array of preview pictures
101 * string 'keywords' => The tags which belong to the content
103 * @todo https://developers.google.com/+/plugins/snippet/
105 * <meta itemprop="name" content="Awesome title">
106 * <meta itemprop="description" content="An awesome description">
107 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
109 * <body itemscope itemtype="http://schema.org/Product">
110 * <h1 itemprop="name">Shiny Trinket</h1>
111 * <img itemprop="image" src="{image-url}" />
112 * <p itemprop="description">Shiny trinkets are shiny.</p>
116 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
122 // Check if the URL does contain a scheme
123 $scheme = parse_url($url, PHP_URL_SCHEME);
126 $url = "http://".trim($url, "/");
130 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
134 $url = trim($url, "'");
135 $url = trim($url, '"');
137 $url = strip_tracking_query_params($url);
139 $siteinfo["url"] = $url;
140 $siteinfo["type"] = "link";
142 $check_cert = Config::get("system", "verifyssl");
144 $stamp1 = microtime(true);
147 curl_setopt($ch, CURLOPT_URL, $url);
148 curl_setopt($ch, CURLOPT_HEADER, 1);
149 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
150 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
151 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
152 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
154 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
157 $range = intval(Config::get('system', 'curl_range_bytes', 0));
160 curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
163 $header = curl_exec($ch);
164 $curl_info = @curl_getinfo($ch);
167 $a->save_timestamp($stamp1, "network");
169 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
170 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
171 if ($curl_info["redirect_url"] != "") {
172 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
174 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
179 // If the file is too large then exit
180 if ($curl_info["download_content_length"] > 1000000) {
184 // If it isn't a HTML file then exit
185 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
191 $oembed_data = oembed_fetch_url($url);
193 if (!in_array($oembed_data->type, array("error", "rich"))) {
194 $siteinfo["type"] = $oembed_data->type;
197 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
198 if (isset($oembed_data->title)) {
199 $siteinfo["title"] = $oembed_data->title;
201 if (isset($oembed_data->description)) {
202 $siteinfo["text"] = trim($oembed_data->description);
204 if (isset($oembed_data->thumbnail_url)) {
205 $siteinfo["image"] = $oembed_data->thumbnail_url;
210 // Fetch the first mentioned charset. Can be in body or header
212 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
213 $charset = trim(trim(trim(array_pop($matches)), ';,'));
216 if ($charset == "") {
220 $pos = strpos($header, "\r\n\r\n");
223 $body = trim(substr($header, $pos));
228 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
229 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
230 //$body = mb_convert_encoding($body, "UTF-8", $charset);
231 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
234 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
236 $doc = new DOMDocument();
237 @$doc->loadHTML($body);
239 xml::deleteNode($doc, "style");
240 xml::deleteNode($doc, "script");
241 xml::deleteNode($doc, "option");
242 xml::deleteNode($doc, "h1");
243 xml::deleteNode($doc, "h2");
244 xml::deleteNode($doc, "h3");
245 xml::deleteNode($doc, "h4");
246 xml::deleteNode($doc, "h5");
247 xml::deleteNode($doc, "h6");
248 xml::deleteNode($doc, "ol");
249 xml::deleteNode($doc, "ul");
251 $xpath = new DomXPath($doc);
253 $list = $xpath->query("//meta[@content]");
254 foreach ($list as $node) {
256 if ($node->attributes->length) {
257 foreach ($node->attributes as $attribute) {
258 $attr[$attribute->name] = $attribute->value;
262 if (@$attr["http-equiv"] == "refresh") {
263 $path = $attr["content"];
264 $pathinfo = explode(";", $path);
266 foreach ($pathinfo as $value) {
267 if (substr(strtolower($value), 0, 4) == "url=") {
268 $content = substr($value, 4);
271 if ($content != "") {
272 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
278 $list = $xpath->query("//title");
279 if ($list->length > 0) {
280 $siteinfo["title"] = $list->item(0)->nodeValue;
283 //$list = $xpath->query("head/meta[@name]");
284 $list = $xpath->query("//meta[@name]");
285 foreach ($list as $node) {
287 if ($node->attributes->length) {
288 foreach ($node->attributes as $attribute) {
289 $attr[$attribute->name] = $attribute->value;
293 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
295 if ($attr["content"] != "") {
296 switch (strtolower($attr["name"])) {
298 $siteinfo["title"] = $attr["content"];
301 $siteinfo["text"] = $attr["content"];
304 $siteinfo["image"] = $attr["content"];
306 case "twitter:image":
307 $siteinfo["image"] = $attr["content"];
309 case "twitter:image:src":
310 $siteinfo["image"] = $attr["content"];
313 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
314 $siteinfo["type"] = $attr["content"];
317 case "twitter:description":
318 $siteinfo["text"] = $attr["content"];
320 case "twitter:title":
321 $siteinfo["title"] = $attr["content"];
324 $siteinfo["title"] = $attr["content"];
326 case "dc.description":
327 $siteinfo["text"] = $attr["content"];
330 $keywords = explode(",", $attr["content"]);
332 case "news_keywords":
333 $keywords = explode(",", $attr["content"]);
337 if ($siteinfo["type"] == "summary") {
338 $siteinfo["type"] = "link";
342 if (isset($keywords)) {
343 $siteinfo["keywords"] = array();
344 foreach ($keywords as $keyword) {
345 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
346 $siteinfo["keywords"][] = trim($keyword);
351 //$list = $xpath->query("head/meta[@property]");
352 $list = $xpath->query("//meta[@property]");
353 foreach ($list as $node) {
355 if ($node->attributes->length) {
356 foreach ($node->attributes as $attribute) {
357 $attr[$attribute->name] = $attribute->value;
361 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
363 if ($attr["content"] != "") {
364 switch (strtolower($attr["property"])) {
366 $siteinfo["image"] = $attr["content"];
369 $siteinfo["title"] = $attr["content"];
371 case "og:description":
372 $siteinfo["text"] = $attr["content"];
378 if ((@$siteinfo["image"] == "") && !$no_guessing) {
379 $list = $xpath->query("//img[@src]");
380 foreach ($list as $node) {
382 if ($node->attributes->length) {
383 foreach ($node->attributes as $attribute) {
384 $attr[$attribute->name] = $attribute->value;
388 $src = self::completeUrl($attr["src"], $url);
389 $photodata = get_photo_info($src);
391 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
392 if ($photodata[0] > 300) {
393 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
396 if ($photodata[1] > 300) {
397 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
400 $siteinfo["images"][] = array("src" => $src,
401 "width" => $photodata[0],
402 "height" => $photodata[1]);
406 } elseif ($siteinfo["image"] != "") {
407 $src = self::completeUrl($siteinfo["image"], $url);
409 unset($siteinfo["image"]);
411 $photodata = get_photo_info($src);
413 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
414 $siteinfo["images"][] = array("src" => $src,
415 "width" => $photodata[0],
416 "height" => $photodata[1]);
420 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
423 $list = $xpath->query("//div[@class='article']");
424 foreach ($list as $node) {
425 if (strlen($node->nodeValue) > 40) {
426 $text .= " ".trim($node->nodeValue);
431 $list = $xpath->query("//div[@class='content']");
432 foreach ($list as $node) {
433 if (strlen($node->nodeValue) > 40) {
434 $text .= " ".trim($node->nodeValue);
439 // If none text was found then take the paragraph content
441 $list = $xpath->query("//p");
442 foreach ($list as $node) {
443 if (strlen($node->nodeValue) > 40) {
444 $text .= " ".trim($node->nodeValue);
450 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
452 while (strpos($text, " ")) {
453 $text = trim(str_replace(" ", " ", $text));
456 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
460 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
462 call_hooks("getsiteinfo", $siteinfo);
468 * @brief Convert tags from CSV to an array
470 * @param string $string Tags
471 * @return array with formatted Hashtags
473 public static function convertTagsToArray($string) {
474 $arr_tags = str_getcsv($string);
475 if (count($arr_tags)) {
476 // add the # sign to every tag
477 array_walk($arr_tags, array("self", "arrAddHashes"));
484 * @brief Add a hasht sign to a string
486 * This method is used as callback function
488 * @param string $tag The pure tag name
489 * @param int $k Counter for internal use
491 private static function arrAddHashes(&$tag, $k) {
496 * @brief Add a scheme to an url
498 * The src attribute of some html elements (e.g. images)
499 * can miss the scheme so we need to add the correct
502 * @param string $url The url which possibly does have
503 * a missing scheme (a link to an image)
504 * @param string $scheme The url with a correct scheme
505 * (e.g. the url from the webpage which does contain the image)
507 * @return string The url with a scheme
509 private static function completeUrl($url, $scheme) {
510 $urlarr = parse_url($url);
512 // If the url does allready have an scheme
513 // we can stop the process here
514 if (isset($urlarr["scheme"])) {
518 $schemearr = parse_url($scheme);
520 $complete = $schemearr["scheme"]."://".$schemearr["host"];
522 if (@$schemearr["port"] != "") {
523 $complete .= ":".$schemearr["port"];
526 if (strpos($urlarr["path"],"/") !== 0) {
530 $complete .= $urlarr["path"];
532 if (@$urlarr["query"] != "") {
533 $complete .= "?".$urlarr["query"];
536 if (@$urlarr["fragment"] != "") {
537 $complete .= "#".$urlarr["fragment"];