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 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
70 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
71 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
72 dbesc(serialize($data)), dbesc(datetime_convert()),
73 dbesc(serialize($data)), dbesc(datetime_convert()));
78 * @brief Parse a page for embeddable content information
80 * This method parses to url for meta data which can be used to embed
81 * the content. If available it prioritizes Open Graph meta tags.
82 * If this is not available it uses the twitter cards meta tags.
83 * As fallback it uses standard html elements with meta informations
84 * like \<title\>Awesome Title\</title\> or
85 * \<meta name="description" content="An awesome description"\>
87 * @param type $url The url of the page which should be scraped
88 * @param type $no_guessing If true the parse doens't search for
90 * @param type $do_oembed The false option is used by the function fetch_oembed()
91 * to avoid endless loops
92 * @param type $count Internal counter to avoid endless loops
94 * @return array which contains needed data for embedding
95 * string 'url' => The url of the parsed page
96 * string 'type' => Content type
97 * string 'title' => The title of the content
98 * string 'text' => The description for the content
99 * string 'image' => A preview image of the content (only available
100 * if $no_geuessing = false
101 * array'images' = Array of preview pictures
102 * string 'keywords' => The tags which belong to the content
104 * @todo https://developers.google.com/+/plugins/snippet/
106 * <meta itemprop="name" content="Awesome title">
107 * <meta itemprop="description" content="An awesome description">
108 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
110 * <body itemscope itemtype="http://schema.org/Product">
111 * <h1 itemprop="name">Shiny Trinket</h1>
112 * <img itemprop="image" src="{image-url}" />
113 * <p itemprop="description">Shiny trinkets are shiny.</p>
117 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
123 // Check if the URL does contain a scheme
124 $scheme = parse_url($url, PHP_URL_SCHEME);
127 $url = "http://".trim($url, "/");
131 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
135 $url = trim($url, "'");
136 $url = trim($url, '"');
138 $url = strip_tracking_query_params($url);
140 $siteinfo["url"] = $url;
141 $siteinfo["type"] = "link";
143 $check_cert = Config::get("system", "verifyssl");
145 $stamp1 = microtime(true);
148 curl_setopt($ch, CURLOPT_URL, $url);
149 curl_setopt($ch, CURLOPT_HEADER, 1);
150 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
151 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
152 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
153 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
155 @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
158 $header = curl_exec($ch);
159 $curl_info = @curl_getinfo($ch);
162 $a->save_timestamp($stamp1, "network");
164 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
165 && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
166 if ($curl_info["redirect_url"] != "") {
167 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
169 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
174 // If the file is too large then exit
175 if ($curl_info["download_content_length"] > 1000000) {
179 // If it isn't a HTML file then exit
180 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
186 $oembed_data = oembed_fetch_url($url);
188 if (!in_array($oembed_data->type, array("error", "rich"))) {
189 $siteinfo["type"] = $oembed_data->type;
192 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
193 if (isset($oembed_data->title)) {
194 $siteinfo["title"] = $oembed_data->title;
196 if (isset($oembed_data->description)) {
197 $siteinfo["text"] = trim($oembed_data->description);
199 if (isset($oembed_data->thumbnail_url)) {
200 $siteinfo["image"] = $oembed_data->thumbnail_url;
205 // Fetch the first mentioned charset. Can be in body or header
207 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
208 $charset = trim(trim(trim(array_pop($matches)), ';,'));
211 if ($charset == "") {
215 $pos = strpos($header, "\r\n\r\n");
218 $body = trim(substr($header, $pos));
223 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
224 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
225 //$body = mb_convert_encoding($body, "UTF-8", $charset);
226 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
229 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
231 $doc = new DOMDocument();
232 @$doc->loadHTML($body);
234 xml::deleteNode($doc, "style");
235 xml::deleteNode($doc, "script");
236 xml::deleteNode($doc, "option");
237 xml::deleteNode($doc, "h1");
238 xml::deleteNode($doc, "h2");
239 xml::deleteNode($doc, "h3");
240 xml::deleteNode($doc, "h4");
241 xml::deleteNode($doc, "h5");
242 xml::deleteNode($doc, "h6");
243 xml::deleteNode($doc, "ol");
244 xml::deleteNode($doc, "ul");
246 $xpath = new DomXPath($doc);
248 $list = $xpath->query("//meta[@content]");
249 foreach ($list as $node) {
251 if ($node->attributes->length) {
252 foreach ($node->attributes as $attribute) {
253 $attr[$attribute->name] = $attribute->value;
257 if (@$attr["http-equiv"] == "refresh") {
258 $path = $attr["content"];
259 $pathinfo = explode(";", $path);
261 foreach ($pathinfo as $value) {
262 if (substr(strtolower($value), 0, 4) == "url=") {
263 $content = substr($value, 4);
266 if ($content != "") {
267 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
273 $list = $xpath->query("//title");
274 if ($list->length > 0) {
275 $siteinfo["title"] = $list->item(0)->nodeValue;
278 //$list = $xpath->query("head/meta[@name]");
279 $list = $xpath->query("//meta[@name]");
280 foreach ($list as $node) {
282 if ($node->attributes->length) {
283 foreach ($node->attributes as $attribute) {
284 $attr[$attribute->name] = $attribute->value;
288 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
290 if ($attr["content"] != "") {
291 switch (strtolower($attr["name"])) {
293 $siteinfo["title"] = $attr["content"];
296 $siteinfo["text"] = $attr["content"];
299 $siteinfo["image"] = $attr["content"];
301 case "twitter:image":
302 $siteinfo["image"] = $attr["content"];
304 case "twitter:image:src":
305 $siteinfo["image"] = $attr["content"];
308 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
309 $siteinfo["type"] = $attr["content"];
312 case "twitter:description":
313 $siteinfo["text"] = $attr["content"];
315 case "twitter:title":
316 $siteinfo["title"] = $attr["content"];
319 $siteinfo["title"] = $attr["content"];
321 case "dc.description":
322 $siteinfo["text"] = $attr["content"];
325 $keywords = explode(",", $attr["content"]);
327 case "news_keywords":
328 $keywords = explode(",", $attr["content"]);
332 if ($siteinfo["type"] == "summary") {
333 $siteinfo["type"] = "link";
337 if (isset($keywords)) {
338 $siteinfo["keywords"] = array();
339 foreach ($keywords as $keyword) {
340 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
341 $siteinfo["keywords"][] = trim($keyword);
346 //$list = $xpath->query("head/meta[@property]");
347 $list = $xpath->query("//meta[@property]");
348 foreach ($list as $node) {
350 if ($node->attributes->length) {
351 foreach ($node->attributes as $attribute) {
352 $attr[$attribute->name] = $attribute->value;
356 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
358 if ($attr["content"] != "") {
359 switch (strtolower($attr["property"])) {
361 $siteinfo["image"] = $attr["content"];
364 $siteinfo["title"] = $attr["content"];
366 case "og:description":
367 $siteinfo["text"] = $attr["content"];
373 if ((@$siteinfo["image"] == "") && !$no_guessing) {
374 $list = $xpath->query("//img[@src]");
375 foreach ($list as $node) {
377 if ($node->attributes->length) {
378 foreach ($node->attributes as $attribute) {
379 $attr[$attribute->name] = $attribute->value;
383 $src = self::completeUrl($attr["src"], $url);
384 $photodata = get_photo_info($src);
386 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
387 if ($photodata[0] > 300) {
388 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
391 if ($photodata[1] > 300) {
392 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
395 $siteinfo["images"][] = array("src" => $src,
396 "width" => $photodata[0],
397 "height" => $photodata[1]);
401 } elseif ($siteinfo["image"] != "") {
402 $src = self::completeUrl($siteinfo["image"], $url);
404 unset($siteinfo["image"]);
406 $photodata = get_photo_info($src);
408 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
409 $siteinfo["images"][] = array("src" => $src,
410 "width" => $photodata[0],
411 "height" => $photodata[1]);
415 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
418 $list = $xpath->query("//div[@class='article']");
419 foreach ($list as $node) {
420 if (strlen($node->nodeValue) > 40) {
421 $text .= " ".trim($node->nodeValue);
426 $list = $xpath->query("//div[@class='content']");
427 foreach ($list as $node) {
428 if (strlen($node->nodeValue) > 40) {
429 $text .= " ".trim($node->nodeValue);
434 // If none text was found then take the paragraph content
436 $list = $xpath->query("//p");
437 foreach ($list as $node) {
438 if (strlen($node->nodeValue) > 40) {
439 $text .= " ".trim($node->nodeValue);
445 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
447 while (strpos($text, " ")) {
448 $text = trim(str_replace(" ", " ", $text));
451 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
455 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
457 call_hooks("getsiteinfo", $siteinfo);
463 * @brief Convert tags from CSV to an array
465 * @param string $string Tags
466 * @return array with formatted Hashtags
468 public static function convertTagsToArray($string) {
469 $arr_tags = str_getcsv($string);
470 if (count($arr_tags)) {
471 // add the # sign to every tag
472 array_walk($arr_tags, array("self", "arrAddHashes"));
479 * @brief Add a hasht sign to a string
481 * This method is used as callback function
483 * @param string $tag The pure tag name
484 * @param int $k Counter for internal use
486 private static function arrAddHashes(&$tag, $k) {
491 * @brief Add a scheme to an url
493 * The src attribute of some html elements (e.g. images)
494 * can miss the scheme so we need to add the correct
497 * @param string $url The url which possibly does have
498 * a missing scheme (a link to an image)
499 * @param string $scheme The url with a correct scheme
500 * (e.g. the url from the webpage which does contain the image)
502 * @return string The url with a scheme
504 private static function completeUrl($url, $scheme) {
505 $urlarr = parse_url($url);
507 // If the url does allready have an scheme
508 // we can stop the process here
509 if (isset($urlarr["scheme"])) {
513 $schemearr = parse_url($scheme);
515 $complete = $schemearr["scheme"]."://".$schemearr["host"];
517 if (@$schemearr["port"] != "") {
518 $complete .= ":".$schemearr["port"];
521 if (strpos($urlarr["path"],"/") !== 0) {
525 $complete .= $urlarr["path"];
527 if (@$urlarr["query"] != "") {
528 $complete .= "?".$urlarr["query"];
531 if (@$urlarr["fragment"] != "") {
532 $complete .= "#".$urlarr["fragment"];