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");
92 // Check if the URL does contain a scheme
93 $scheme = parse_url($url, PHP_URL_SCHEME);
96 $url = "http://".trim($url, "/");
100 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
104 $url = trim($url, "'");
105 $url = trim($url, '"');
107 $url = original_url($url);
109 $siteinfo["url"] = $url;
110 $siteinfo["type"] = "link";
112 $check_cert = get_config('system','verifyssl');
114 $stamp1 = microtime(true);
117 curl_setopt($ch, CURLOPT_URL, $url);
118 curl_setopt($ch, CURLOPT_HEADER, 1);
119 curl_setopt($ch, CURLOPT_NOBODY, 1);
120 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
121 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
122 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
123 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
124 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
126 $header = curl_exec($ch);
127 $curl_info = @curl_getinfo($ch);
128 $http_code = $curl_info['http_code'];
131 $a->save_timestamp($stamp1, "network");
133 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
134 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
135 if ($curl_info['redirect_url'] != "")
136 $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
138 $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
142 // if the file is too large then exit
143 if ($curl_info["download_content_length"] > 1000000)
146 // if it isn't a HTML file then exit
147 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
151 require_once("include/oembed.php");
153 $oembed_data = oembed_fetch_url($url);
155 if (!in_array($oembed_data->type, array("error", "rich"))) {
156 $siteinfo["type"] = $oembed_data->type;
159 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
160 if (isset($oembed_data->title))
161 $siteinfo["title"] = $oembed_data->title;
162 if (isset($oembed_data->description))
163 $siteinfo["text"] = trim($oembed_data->description);
164 if (isset($oembed_data->thumbnail_url))
165 $siteinfo["image"] = $oembed_data->thumbnail_url;
169 $stamp1 = microtime(true);
171 // Now fetch the body as well
173 curl_setopt($ch, CURLOPT_URL, $url);
174 curl_setopt($ch, CURLOPT_HEADER, 1);
175 curl_setopt($ch, CURLOPT_NOBODY, 0);
176 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
177 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
178 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
179 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
180 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
182 $header = curl_exec($ch);
183 $curl_info = @curl_getinfo($ch);
184 $http_code = $curl_info['http_code'];
187 $a->save_timestamp($stamp1, "network");
189 // Fetch the first mentioned charset. Can be in body or header
191 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
192 $charset = trim(trim(trim(array_pop($matches)), ';,'));
197 $pos = strpos($header, "\r\n\r\n");
200 $body = trim(substr($header, $pos));
204 if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
205 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
206 //$body = mb_convert_encoding($body, "UTF-8", $charset);
207 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
210 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
212 $doc = new DOMDocument();
213 @$doc->loadHTML($body);
215 deletenode($doc, 'style');
216 deletenode($doc, 'script');
217 deletenode($doc, 'option');
218 deletenode($doc, 'h1');
219 deletenode($doc, 'h2');
220 deletenode($doc, 'h3');
221 deletenode($doc, 'h4');
222 deletenode($doc, 'h5');
223 deletenode($doc, 'h6');
224 deletenode($doc, 'ol');
225 deletenode($doc, 'ul');
227 $xpath = new DomXPath($doc);
229 $list = $xpath->query("//meta[@content]");
230 foreach ($list as $node) {
232 if ($node->attributes->length)
233 foreach ($node->attributes as $attribute)
234 $attr[$attribute->name] = $attribute->value;
236 if (@$attr["http-equiv"] == 'refresh') {
237 $path = $attr["content"];
238 $pathinfo = explode(";", $path);
240 foreach ($pathinfo AS $value) {
241 if (substr(strtolower($value), 0, 4) == "url=")
242 $content = substr($value, 4);
244 if ($content != "") {
245 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
251 $list = $xpath->query("//title");
252 if ($list->length > 0)
253 $siteinfo["title"] = $list->item(0)->nodeValue;
255 //$list = $xpath->query("head/meta[@name]");
256 $list = $xpath->query("//meta[@name]");
257 foreach ($list as $node) {
259 if ($node->attributes->length)
260 foreach ($node->attributes as $attribute)
261 $attr[$attribute->name] = $attribute->value;
263 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
265 if ($attr["content"] != "")
266 switch (strtolower($attr["name"])) {
268 $siteinfo["title"] = $attr["content"];
271 $siteinfo["text"] = $attr["content"];
274 $siteinfo["image"] = $attr["content"];
276 case "twitter:image":
277 $siteinfo["image"] = $attr["content"];
279 case "twitter:image:src":
280 $siteinfo["image"] = $attr["content"];
283 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
284 $siteinfo["type"] = $attr["content"];
286 case "twitter:description":
287 $siteinfo["text"] = $attr["content"];
289 case "twitter:title":
290 $siteinfo["title"] = $attr["content"];
293 $siteinfo["title"] = $attr["content"];
295 case "dc.description":
296 $siteinfo["text"] = $attr["content"];
299 $keywords = explode(",", $attr["content"]);
301 case "news_keywords":
302 $keywords = explode(",", $attr["content"]);
305 if ($siteinfo["type"] == "summary")
306 $siteinfo["type"] = "link";
309 if (isset($keywords)) {
310 $siteinfo["keywords"] = array();
311 foreach ($keywords as $keyword)
312 if (!in_array(trim($keyword), $siteinfo["keywords"]))
313 $siteinfo["keywords"][] = trim($keyword);
316 //$list = $xpath->query("head/meta[@property]");
317 $list = $xpath->query("//meta[@property]");
318 foreach ($list as $node) {
320 if ($node->attributes->length)
321 foreach ($node->attributes as $attribute)
322 $attr[$attribute->name] = $attribute->value;
324 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
326 if ($attr["content"] != "")
327 switch (strtolower($attr["property"])) {
329 $siteinfo["image"] = $attr["content"];
332 $siteinfo["title"] = $attr["content"];
334 case "og:description":
335 $siteinfo["text"] = $attr["content"];
340 if ((@$siteinfo["image"] == "") AND !$no_guessing) {
341 $list = $xpath->query("//img[@src]");
342 foreach ($list as $node) {
344 if ($node->attributes->length)
345 foreach ($node->attributes as $attribute)
346 $attr[$attribute->name] = $attribute->value;
348 $src = completeurl($attr["src"], $url);
349 $photodata = get_photo_info($src);
351 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
352 if ($photodata[0] > 300) {
353 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
356 if ($photodata[1] > 300) {
357 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
360 $siteinfo["images"][] = array("src"=>$src,
361 "width"=>$photodata[0],
362 "height"=>$photodata[1]);
366 } elseif ($siteinfo["image"] != "") {
367 $src = completeurl($siteinfo["image"], $url);
369 unset($siteinfo["image"]);
371 $photodata = get_photo_info($src);
373 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
374 $siteinfo["images"][] = array("src"=>$src,
375 "width"=>$photodata[0],
376 "height"=>$photodata[1]);
379 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
382 $list = $xpath->query("//div[@class='article']");
383 foreach ($list as $node)
384 if (strlen($node->nodeValue) > 40)
385 $text .= " ".trim($node->nodeValue);
388 $list = $xpath->query("//div[@class='content']");
389 foreach ($list as $node)
390 if (strlen($node->nodeValue) > 40)
391 $text .= " ".trim($node->nodeValue);
394 // If none text was found then take the paragraph content
396 $list = $xpath->query("//p");
397 foreach ($list as $node)
398 if (strlen($node->nodeValue) > 40)
399 $text .= " ".trim($node->nodeValue);
403 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
405 while (strpos($text, " "))
406 $text = trim(str_replace(" ", " ", $text));
408 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
412 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
414 call_hooks('getsiteinfo', $siteinfo);
419 function arr_add_hashes(&$item,$k) {
423 function parse_url_content(&$a) {
425 require_once("include/items.php");
432 if(local_user() && (! feature_enabled(local_user(),'richtext')))
436 $br = (($textmode) ? "\n" : '<br />');
438 if(x($_GET,'binurl'))
439 $url = trim(hex2bin($_GET['binurl']));
441 $url = trim($_GET['url']);
444 $title = strip_tags(trim($_GET['title']));
446 if($_GET['description'])
447 $text = strip_tags(trim($_GET['description']));
450 $arr_tags = str_getcsv($_GET['tags']);
451 if(count($arr_tags)) {
452 array_walk($arr_tags,'arr_add_hashes');
453 $str_tags = $br . implode(' ',$arr_tags) . $br;
457 // add url scheme if missing
458 $arrurl = parse_url($url);
459 if (!x($arrurl, 'scheme')) {
460 if (x($arrurl, 'host'))
463 $url = "http://".$url;
466 logger('parse_url: ' . $url);
469 $template = '[bookmark=%s]%s[/bookmark]%s';
471 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
473 $arr = array('url' => $url, 'text' => '');
475 call_hooks('parse_link', $arr);
477 if(strlen($arr['text'])) {
483 if($url && $title && $text) {
485 $title = str_replace(array("\r","\n"),array('',''),$title);
488 $text = '[quote]' . trim($text) . '[/quote]' . $br;
490 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
491 $title = htmlspecialchars($title);
494 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
496 logger('parse_url (unparsed): returns: ' . $result);
502 $siteinfo = parseurl_getsiteinfo($url);
504 unset($siteinfo["keywords"]);
506 $info = add_page_info_data($siteinfo);
509 // Replace ' with ’ - not perfect - but the richtext editor has problems otherwise
510 $info = str_replace(array("'"), array("’"), $info);