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 dba::insert('parsed_url', array('url' => normalise_link($url), 'guessing' => !$no_guessing,
70 'oembed' => $do_oembed, 'content' => serialize($data),
71 'created' => datetime_convert()), true);
76 * @brief Parse a page for embeddable content information
78 * This method parses to url for meta data which can be used to embed
79 * the content. If available it prioritizes Open Graph meta tags.
80 * If this is not available it uses the twitter cards meta tags.
81 * As fallback it uses standard html elements with meta informations
82 * like \<title\>Awesome Title\</title\> or
83 * \<meta name="description" content="An awesome description"\>
85 * @param type $url The url of the page which should be scraped
86 * @param type $no_guessing If true the parse doens't search for
88 * @param type $do_oembed The false option is used by the function fetch_oembed()
89 * to avoid endless loops
90 * @param type $count Internal counter to avoid endless loops
92 * @return array which contains needed data for embedding
93 * string 'url' => The url of the parsed page
94 * string 'type' => Content type
95 * string 'title' => The title of the content
96 * string 'text' => The description for the content
97 * string 'image' => A preview image of the content (only available
98 * if $no_geuessing = false
99 * array'images' = Array of preview pictures
100 * string 'keywords' => The tags which belong to the content
102 * @todo https://developers.google.com/+/plugins/snippet/
104 * <meta itemprop="name" content="Awesome title">
105 * <meta itemprop="description" content="An awesome description">
106 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
108 * <body itemscope itemtype="http://schema.org/Product">
109 * <h1 itemprop="name">Shiny Trinket</h1>
110 * <img itemprop="image" src="{image-url}" />
111 * <p itemprop="description">Shiny trinkets are shiny.</p>
115 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
121 // Check if the URL does contain a scheme
122 $scheme = parse_url($url, PHP_URL_SCHEME);
125 $url = "http://".trim($url, "/");
129 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
133 $url = trim($url, "'");
134 $url = trim($url, '"');
136 $url = strip_tracking_query_params($url);
138 $siteinfo["url"] = $url;
139 $siteinfo["type"] = "link";
141 $check_cert = Config::get("system", "verifyssl");
143 $stamp1 = microtime(true);
146 curl_setopt($ch, CURLOPT_URL, $url);
147 curl_setopt($ch, CURLOPT_HEADER, 1);
148 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
149 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
150 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
151 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
153 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
156 $range = intval(Config::get('system', 'curl_range_bytes', 0));
159 curl_setopt($ch, CURLOPT_RANGE, '0-' . $range);
162 $header = curl_exec($ch);
163 $curl_info = @curl_getinfo($ch);
166 $a->save_timestamp($stamp1, "network");
168 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
169 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
170 if ($curl_info["redirect_url"] != "") {
171 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
173 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
178 // If the file is too large then exit
179 if ($curl_info["download_content_length"] > 1000000) {
183 // If it isn't a HTML file then exit
184 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
190 $oembed_data = oembed_fetch_url($url);
192 if (!in_array($oembed_data->type, array("error", "rich"))) {
193 $siteinfo["type"] = $oembed_data->type;
196 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
197 if (isset($oembed_data->title)) {
198 $siteinfo["title"] = $oembed_data->title;
200 if (isset($oembed_data->description)) {
201 $siteinfo["text"] = trim($oembed_data->description);
203 if (isset($oembed_data->thumbnail_url)) {
204 $siteinfo["image"] = $oembed_data->thumbnail_url;
209 // Fetch the first mentioned charset. Can be in body or header
211 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
212 $charset = trim(trim(trim(array_pop($matches)), ';,'));
215 if ($charset == "") {
219 $pos = strpos($header, "\r\n\r\n");
222 $body = trim(substr($header, $pos));
227 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
228 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
229 //$body = mb_convert_encoding($body, "UTF-8", $charset);
230 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
233 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
235 $doc = new DOMDocument();
236 @$doc->loadHTML($body);
238 xml::deleteNode($doc, "style");
239 xml::deleteNode($doc, "script");
240 xml::deleteNode($doc, "option");
241 xml::deleteNode($doc, "h1");
242 xml::deleteNode($doc, "h2");
243 xml::deleteNode($doc, "h3");
244 xml::deleteNode($doc, "h4");
245 xml::deleteNode($doc, "h5");
246 xml::deleteNode($doc, "h6");
247 xml::deleteNode($doc, "ol");
248 xml::deleteNode($doc, "ul");
250 $xpath = new DomXPath($doc);
252 $list = $xpath->query("//meta[@content]");
253 foreach ($list as $node) {
255 if ($node->attributes->length) {
256 foreach ($node->attributes as $attribute) {
257 $attr[$attribute->name] = $attribute->value;
261 if (@$attr["http-equiv"] == "refresh") {
262 $path = $attr["content"];
263 $pathinfo = explode(";", $path);
265 foreach ($pathinfo as $value) {
266 if (substr(strtolower($value), 0, 4) == "url=") {
267 $content = substr($value, 4);
270 if ($content != "") {
271 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
277 $list = $xpath->query("//title");
278 if ($list->length > 0) {
279 $siteinfo["title"] = $list->item(0)->nodeValue;
282 //$list = $xpath->query("head/meta[@name]");
283 $list = $xpath->query("//meta[@name]");
284 foreach ($list as $node) {
286 if ($node->attributes->length) {
287 foreach ($node->attributes as $attribute) {
288 $attr[$attribute->name] = $attribute->value;
292 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
294 if ($attr["content"] != "") {
295 switch (strtolower($attr["name"])) {
297 $siteinfo["title"] = $attr["content"];
300 $siteinfo["text"] = $attr["content"];
303 $siteinfo["image"] = $attr["content"];
305 case "twitter:image":
306 $siteinfo["image"] = $attr["content"];
308 case "twitter:image:src":
309 $siteinfo["image"] = $attr["content"];
312 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
313 $siteinfo["type"] = $attr["content"];
316 case "twitter:description":
317 $siteinfo["text"] = $attr["content"];
319 case "twitter:title":
320 $siteinfo["title"] = $attr["content"];
323 $siteinfo["title"] = $attr["content"];
325 case "dc.description":
326 $siteinfo["text"] = $attr["content"];
329 $keywords = explode(",", $attr["content"]);
331 case "news_keywords":
332 $keywords = explode(",", $attr["content"]);
336 if ($siteinfo["type"] == "summary") {
337 $siteinfo["type"] = "link";
341 if (isset($keywords)) {
342 $siteinfo["keywords"] = array();
343 foreach ($keywords as $keyword) {
344 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
345 $siteinfo["keywords"][] = trim($keyword);
350 //$list = $xpath->query("head/meta[@property]");
351 $list = $xpath->query("//meta[@property]");
352 foreach ($list as $node) {
354 if ($node->attributes->length) {
355 foreach ($node->attributes as $attribute) {
356 $attr[$attribute->name] = $attribute->value;
360 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
362 if ($attr["content"] != "") {
363 switch (strtolower($attr["property"])) {
365 $siteinfo["image"] = $attr["content"];
368 $siteinfo["title"] = $attr["content"];
370 case "og:description":
371 $siteinfo["text"] = $attr["content"];
377 if ((@$siteinfo["image"] == "") && !$no_guessing) {
378 $list = $xpath->query("//img[@src]");
379 foreach ($list as $node) {
381 if ($node->attributes->length) {
382 foreach ($node->attributes as $attribute) {
383 $attr[$attribute->name] = $attribute->value;
387 $src = self::completeUrl($attr["src"], $url);
388 $photodata = get_photo_info($src);
390 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
391 if ($photodata[0] > 300) {
392 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
395 if ($photodata[1] > 300) {
396 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
399 $siteinfo["images"][] = array("src" => $src,
400 "width" => $photodata[0],
401 "height" => $photodata[1]);
405 } elseif ($siteinfo["image"] != "") {
406 $src = self::completeUrl($siteinfo["image"], $url);
408 unset($siteinfo["image"]);
410 $photodata = get_photo_info($src);
412 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
413 $siteinfo["images"][] = array("src" => $src,
414 "width" => $photodata[0],
415 "height" => $photodata[1]);
419 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
422 $list = $xpath->query("//div[@class='article']");
423 foreach ($list as $node) {
424 if (strlen($node->nodeValue) > 40) {
425 $text .= " ".trim($node->nodeValue);
430 $list = $xpath->query("//div[@class='content']");
431 foreach ($list as $node) {
432 if (strlen($node->nodeValue) > 40) {
433 $text .= " ".trim($node->nodeValue);
438 // If none text was found then take the paragraph content
440 $list = $xpath->query("//p");
441 foreach ($list as $node) {
442 if (strlen($node->nodeValue) > 40) {
443 $text .= " ".trim($node->nodeValue);
449 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
451 while (strpos($text, " ")) {
452 $text = trim(str_replace(" ", " ", $text));
455 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
459 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
461 call_hooks("getsiteinfo", $siteinfo);
467 * @brief Convert tags from CSV to an array
469 * @param string $string Tags
470 * @return array with formatted Hashtags
472 public static function convertTagsToArray($string) {
473 $arr_tags = str_getcsv($string);
474 if (count($arr_tags)) {
475 // add the # sign to every tag
476 array_walk($arr_tags, array("self", "arrAddHashes"));
483 * @brief Add a hasht sign to a string
485 * This method is used as callback function
487 * @param string $tag The pure tag name
488 * @param int $k Counter for internal use
490 private static function arrAddHashes(&$tag, $k) {
495 * @brief Add a scheme to an url
497 * The src attribute of some html elements (e.g. images)
498 * can miss the scheme so we need to add the correct
501 * @param string $url The url which possibly does have
502 * a missing scheme (a link to an image)
503 * @param string $scheme The url with a correct scheme
504 * (e.g. the url from the webpage which does contain the image)
506 * @return string The url with a scheme
508 private static function completeUrl($url, $scheme) {
509 $urlarr = parse_url($url);
511 // If the url does allready have an scheme
512 // we can stop the process here
513 if (isset($urlarr["scheme"])) {
517 $schemearr = parse_url($scheme);
519 $complete = $schemearr["scheme"]."://".$schemearr["host"];
521 if (@$schemearr["port"] != "") {
522 $complete .= ":".$schemearr["port"];
525 if (strpos($urlarr["path"],"/") !== 0) {
529 $complete .= $urlarr["path"];
531 if (@$urlarr["query"] != "") {
532 $complete .= "?".$urlarr["query"];
535 if (@$urlarr["fragment"] != "") {
536 $complete .= "#".$urlarr["fragment"];