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("head/title");
239 $list = $xpath->query("//title");
240 foreach ($list as $node)
241 $siteinfo["title"] = html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
243 //$list = $xpath->query("head/meta[@name]");
244 $list = $xpath->query("//meta[@name]");
245 foreach ($list as $node) {
247 if ($node->attributes->length)
248 foreach ($node->attributes as $attribute)
249 $attr[$attribute->name] = $attribute->value;
251 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
253 if ($attr["content"] != "")
254 switch (strtolower($attr["name"])) {
256 $siteinfo["title"] = $attr["content"];
259 $siteinfo["text"] = $attr["content"];
262 $siteinfo["image"] = $attr["content"];
264 case "twitter:image":
265 $siteinfo["image"] = $attr["content"];
267 case "twitter:image:src":
268 $siteinfo["image"] = $attr["content"];
271 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
272 $siteinfo["type"] = $attr["content"];
274 case "twitter:description":
275 $siteinfo["text"] = $attr["content"];
277 case "twitter:title":
278 $siteinfo["title"] = $attr["content"];
281 $siteinfo["title"] = $attr["content"];
283 case "dc.description":
284 $siteinfo["text"] = $attr["content"];
287 $keywords = explode(",", $attr["content"]);
289 case "news_keywords":
290 $keywords = explode(",", $attr["content"]);
293 if ($siteinfo["type"] == "summary")
294 $siteinfo["type"] = "link";
297 if (isset($keywords)) {
298 $siteinfo["keywords"] = array();
299 foreach ($keywords as $keyword)
300 if (!in_array(trim($keyword), $siteinfo["keywords"]))
301 $siteinfo["keywords"][] = trim($keyword);
304 //$list = $xpath->query("head/meta[@property]");
305 $list = $xpath->query("//meta[@property]");
306 foreach ($list as $node) {
308 if ($node->attributes->length)
309 foreach ($node->attributes as $attribute)
310 $attr[$attribute->name] = $attribute->value;
312 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
314 if ($attr["content"] != "")
315 switch (strtolower($attr["property"])) {
317 $siteinfo["image"] = $attr["content"];
320 $siteinfo["title"] = $attr["content"];
322 case "og:description":
323 $siteinfo["text"] = $attr["content"];
328 if ((@$siteinfo["image"] == "") AND !$no_guessing) {
329 $list = $xpath->query("//img[@src]");
330 foreach ($list as $node) {
332 if ($node->attributes->length)
333 foreach ($node->attributes as $attribute)
334 $attr[$attribute->name] = $attribute->value;
336 $src = completeurl($attr["src"], $url);
337 $photodata = get_photo_info($src);
339 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
340 if ($photodata[0] > 300) {
341 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
344 if ($photodata[1] > 300) {
345 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
348 $siteinfo["images"][] = array("src"=>$src,
349 "width"=>$photodata[0],
350 "height"=>$photodata[1]);
354 } elseif ($siteinfo["image"] != "") {
355 $src = completeurl($siteinfo["image"], $url);
357 unset($siteinfo["image"]);
359 $photodata = get_photo_info($src);
361 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
362 $siteinfo["images"][] = array("src"=>$src,
363 "width"=>$photodata[0],
364 "height"=>$photodata[1]);
367 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
370 $list = $xpath->query("//div[@class='article']");
371 foreach ($list as $node)
372 if (strlen($node->nodeValue) > 40)
373 $text .= " ".trim($node->nodeValue);
376 $list = $xpath->query("//div[@class='content']");
377 foreach ($list as $node)
378 if (strlen($node->nodeValue) > 40)
379 $text .= " ".trim($node->nodeValue);
382 // If none text was found then take the paragraph content
384 $list = $xpath->query("//p");
385 foreach ($list as $node)
386 if (strlen($node->nodeValue) > 40)
387 $text .= " ".trim($node->nodeValue);
391 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
393 while (strpos($text, " "))
394 $text = trim(str_replace(" ", " ", $text));
396 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
400 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
402 call_hooks('getsiteinfo', $siteinfo);
407 function arr_add_hashes(&$item,$k) {
411 function parse_url_content(&$a) {
413 require_once("include/items.php");
420 if(local_user() && (! feature_enabled(local_user(),'richtext')))
424 $br = (($textmode) ? "\n" : '<br />');
426 if(x($_GET,'binurl'))
427 $url = trim(hex2bin($_GET['binurl']));
429 $url = trim($_GET['url']);
432 $title = strip_tags(trim($_GET['title']));
434 if($_GET['description'])
435 $text = strip_tags(trim($_GET['description']));
438 $arr_tags = str_getcsv($_GET['tags']);
439 if(count($arr_tags)) {
440 array_walk($arr_tags,'arr_add_hashes');
441 $str_tags = $br . implode(' ',$arr_tags) . $br;
445 // add url scheme if missing
446 $arrurl = parse_url($url);
447 if (!x($arrurl, 'scheme')) {
448 if (x($arrurl, 'host'))
451 $url = "http://".$url;
454 logger('parse_url: ' . $url);
457 $template = '[bookmark=%s]%s[/bookmark]%s';
459 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
461 $arr = array('url' => $url, 'text' => '');
463 call_hooks('parse_link', $arr);
465 if(strlen($arr['text'])) {
471 if($url && $title && $text) {
473 $title = str_replace(array("\r","\n"),array('',''),$title);
476 $text = '[quote]' . trim($text) . '[/quote]' . $br;
478 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
479 $title = htmlspecialchars($title);
482 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
484 logger('parse_url (unparsed): returns: ' . $result);
490 $siteinfo = parseurl_getsiteinfo($url);
492 unset($siteinfo["keywords"]);
494 $info = add_page_info_data($siteinfo);
497 // Replace ' with ’ - not perfect - but the richtext editor has problems otherwise
498 $info = str_replace(array("'"), array("’"), $info);