3 * @file mod/parse_url.php
5 * @todo https://developers.google.com/+/plugins/snippet/
8 * <meta itemprop="name" content="Toller Titel">
9 * <meta itemprop="description" content="Eine tolle Beschreibung">
10 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
12 * <body itemscope itemtype="http://schema.org/Product">
13 * <h1 itemprop="name">Shiny Trinket</h1>
14 * <img itemprop="image" src="{image-url}" />
15 * <p itemprop="description">Shiny trinkets are shiny.</p>
20 if(!function_exists('deletenode')) {
21 function deletenode(&$doc, $node)
23 $xpath = new DomXPath($doc);
24 $list = $xpath->query("//".$node);
25 foreach ($list as $child)
26 $child->parentNode->removeChild($child);
30 function completeurl($url, $scheme) {
31 $urlarr = parse_url($url);
33 if (isset($urlarr["scheme"]))
36 $schemearr = parse_url($scheme);
38 $complete = $schemearr["scheme"]."://".$schemearr["host"];
40 if (@$schemearr["port"] != "")
41 $complete .= ":".$schemearr["port"];
43 if(strpos($urlarr['path'],'/') !== 0)
46 $complete .= $urlarr["path"];
48 if (@$urlarr["query"] != "")
49 $complete .= "?".$urlarr["query"];
51 if (@$urlarr["fragment"] != "")
52 $complete .= "#".$urlarr["fragment"];
57 function parseurl_getsiteinfo_cached($url, $no_guessing = false, $do_oembed = true) {
62 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
63 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
66 $data = $r[0]["content"];
68 if (!is_null($data)) {
69 $data = unserialize($data);
73 $data = parseurl_getsiteinfo($url, $no_guessing, $do_oembed);
75 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
76 ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
77 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
78 dbesc(serialize($data)), dbesc(datetime_convert()),
79 dbesc(serialize($data)), dbesc(datetime_convert()));
84 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
85 require_once("include/network.php");
86 require_once("include/Photo.php");
93 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
97 $url = trim($url, "'");
98 $url = trim($url, '"');
100 $url = original_url($url);
102 $siteinfo["url"] = $url;
103 $siteinfo["type"] = "link";
105 $stamp1 = microtime(true);
108 curl_setopt($ch, CURLOPT_URL, $url);
109 curl_setopt($ch, CURLOPT_HEADER, 1);
110 curl_setopt($ch, CURLOPT_NOBODY, 1);
111 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
112 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
113 //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
114 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
116 $header = curl_exec($ch);
117 $curl_info = @curl_getinfo($ch);
118 $http_code = $curl_info['http_code'];
121 $a->save_timestamp($stamp1, "network");
123 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
124 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
125 if ($curl_info['redirect_url'] != "")
126 $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
128 $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
132 // if the file is too large then exit
133 if ($curl_info["download_content_length"] > 1000000)
136 // if it isn't a HTML file then exit
137 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
141 require_once("include/oembed.php");
143 $oembed_data = oembed_fetch_url($url);
145 if ($oembed_data->type != "error")
146 $siteinfo["type"] = $oembed_data->type;
148 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
149 if (isset($oembed_data->title))
150 $siteinfo["title"] = $oembed_data->title;
151 if (isset($oembed_data->description))
152 $siteinfo["text"] = trim($oembed_data->description);
153 if (isset($oembed_data->thumbnail_url))
154 $siteinfo["image"] = $oembed_data->thumbnail_url;
158 $stamp1 = microtime(true);
160 // Now fetch the body as well
162 curl_setopt($ch, CURLOPT_URL, $url);
163 curl_setopt($ch, CURLOPT_HEADER, 1);
164 curl_setopt($ch, CURLOPT_NOBODY, 0);
165 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
166 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
167 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
169 $header = curl_exec($ch);
170 $curl_info = @curl_getinfo($ch);
171 $http_code = $curl_info['http_code'];
174 $a->save_timestamp($stamp1, "network");
176 // Fetch the first mentioned charset. Can be in body or header
178 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
179 $charset = trim(trim(trim(array_pop($matches)), ';,'));
184 $pos = strpos($header, "\r\n\r\n");
187 $body = trim(substr($header, $pos));
191 if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
192 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
193 //$body = mb_convert_encoding($body, "UTF-8", $charset);
194 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
197 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
199 $doc = new DOMDocument();
200 @$doc->loadHTML($body);
202 deletenode($doc, 'style');
203 deletenode($doc, 'script');
204 deletenode($doc, 'option');
205 deletenode($doc, 'h1');
206 deletenode($doc, 'h2');
207 deletenode($doc, 'h3');
208 deletenode($doc, 'h4');
209 deletenode($doc, 'h5');
210 deletenode($doc, 'h6');
211 deletenode($doc, 'ol');
212 deletenode($doc, 'ul');
214 $xpath = new DomXPath($doc);
216 $list = $xpath->query("//meta[@content]");
217 foreach ($list as $node) {
219 if ($node->attributes->length)
220 foreach ($node->attributes as $attribute)
221 $attr[$attribute->name] = $attribute->value;
223 if (@$attr["http-equiv"] == 'refresh') {
224 $path = $attr["content"];
225 $pathinfo = explode(";", $path);
227 foreach ($pathinfo AS $value) {
228 if (substr(strtolower($value), 0, 4) == "url=")
229 $content = substr($value, 4);
231 if ($content != "") {
232 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
238 $list = $xpath->query("//title");
239 if ($list->length > 0)
240 $siteinfo["title"] = $list->item(0)->nodeValue;
242 //$list = $xpath->query("head/meta[@name]");
243 $list = $xpath->query("//meta[@name]");
244 foreach ($list as $node) {
246 if ($node->attributes->length)
247 foreach ($node->attributes as $attribute)
248 $attr[$attribute->name] = $attribute->value;
250 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
252 if ($attr["content"] != "")
253 switch (strtolower($attr["name"])) {
255 $siteinfo["title"] = $attr["content"];
258 $siteinfo["text"] = $attr["content"];
261 $siteinfo["image"] = $attr["content"];
263 case "twitter:image":
264 $siteinfo["image"] = $attr["content"];
266 case "twitter:image:src":
267 $siteinfo["image"] = $attr["content"];
270 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
271 $siteinfo["type"] = $attr["content"];
273 case "twitter:description":
274 $siteinfo["text"] = $attr["content"];
276 case "twitter:title":
277 $siteinfo["title"] = $attr["content"];
280 $siteinfo["title"] = $attr["content"];
282 case "dc.description":
283 $siteinfo["text"] = $attr["content"];
286 $keywords = explode(",", $attr["content"]);
288 case "news_keywords":
289 $keywords = explode(",", $attr["content"]);
292 if ($siteinfo["type"] == "summary")
293 $siteinfo["type"] = "link";
296 if (isset($keywords)) {
297 $siteinfo["keywords"] = array();
298 foreach ($keywords as $keyword)
299 if (!in_array(trim($keyword), $siteinfo["keywords"]))
300 $siteinfo["keywords"][] = trim($keyword);
303 //$list = $xpath->query("head/meta[@property]");
304 $list = $xpath->query("//meta[@property]");
305 foreach ($list as $node) {
307 if ($node->attributes->length)
308 foreach ($node->attributes as $attribute)
309 $attr[$attribute->name] = $attribute->value;
311 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
313 if ($attr["content"] != "")
314 switch (strtolower($attr["property"])) {
316 $siteinfo["image"] = $attr["content"];
319 $siteinfo["title"] = $attr["content"];
321 case "og:description":
322 $siteinfo["text"] = $attr["content"];
327 if ((@$siteinfo["image"] == "") AND !$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;
335 $src = completeurl($attr["src"], $url);
336 $photodata = get_photo_info($src);
338 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
339 if ($photodata[0] > 300) {
340 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
343 if ($photodata[1] > 300) {
344 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
347 $siteinfo["images"][] = array("src"=>$src,
348 "width"=>$photodata[0],
349 "height"=>$photodata[1]);
353 } elseif ($siteinfo["image"] != "") {
354 $src = completeurl($siteinfo["image"], $url);
356 unset($siteinfo["image"]);
358 $photodata = get_photo_info($src);
360 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
361 $siteinfo["images"][] = array("src"=>$src,
362 "width"=>$photodata[0],
363 "height"=>$photodata[1]);
366 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
369 $list = $xpath->query("//div[@class='article']");
370 foreach ($list as $node)
371 if (strlen($node->nodeValue) > 40)
372 $text .= " ".trim($node->nodeValue);
375 $list = $xpath->query("//div[@class='content']");
376 foreach ($list as $node)
377 if (strlen($node->nodeValue) > 40)
378 $text .= " ".trim($node->nodeValue);
381 // If none text was found then take the paragraph content
383 $list = $xpath->query("//p");
384 foreach ($list as $node)
385 if (strlen($node->nodeValue) > 40)
386 $text .= " ".trim($node->nodeValue);
390 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
392 while (strpos($text, " "))
393 $text = trim(str_replace(" ", " ", $text));
395 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
399 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
401 call_hooks('getsiteinfo', $siteinfo);
406 function arr_add_hashes(&$item,$k) {
410 function parse_url_content(&$a) {
412 require_once("include/items.php");
419 if(local_user() && (! feature_enabled(local_user(),'richtext')))
423 $br = (($textmode) ? "\n" : '<br />');
425 if(x($_GET,'binurl'))
426 $url = trim(hex2bin($_GET['binurl']));
428 $url = trim($_GET['url']);
431 $title = strip_tags(trim($_GET['title']));
433 if($_GET['description'])
434 $text = strip_tags(trim($_GET['description']));
437 $arr_tags = str_getcsv($_GET['tags']);
438 if(count($arr_tags)) {
439 array_walk($arr_tags,'arr_add_hashes');
440 $str_tags = $br . implode(' ',$arr_tags) . $br;
444 // add url scheme if missing
445 $arrurl = parse_url($url);
446 if (!x($arrurl, 'scheme')) {
447 if (x($arrurl, 'host'))
450 $url = "http://".$url;
453 logger('parse_url: ' . $url);
456 $template = '[bookmark=%s]%s[/bookmark]%s';
458 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
460 $arr = array('url' => $url, 'text' => '');
462 call_hooks('parse_link', $arr);
464 if(strlen($arr['text'])) {
470 if($url && $title && $text) {
472 $title = str_replace(array("\r","\n"),array('',''),$title);
475 $text = '[quote]' . trim($text) . '[/quote]' . $br;
477 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
478 $title = htmlspecialchars($title);
481 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
483 logger('parse_url (unparsed): returns: ' . $result);
489 $siteinfo = parseurl_getsiteinfo($url);
491 unset($siteinfo["keywords"]);
493 $info = add_page_info_data($siteinfo);
496 // Replace ' with ’ - not perfect - but the richtext editor has problems otherwise
497 $info = str_replace(array("'"), array("’"), $info);