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 if(! function_exists('completeurl')) {
31 function completeurl($url, $scheme) {
32 $urlarr = parse_url($url);
34 if (isset($urlarr["scheme"]))
37 $schemearr = parse_url($scheme);
39 $complete = $schemearr["scheme"]."://".$schemearr["host"];
41 if (@$schemearr["port"] != "")
42 $complete .= ":".$schemearr["port"];
44 if(strpos($urlarr['path'],'/') !== 0)
47 $complete .= $urlarr["path"];
49 if (@$urlarr["query"] != "")
50 $complete .= "?".$urlarr["query"];
52 if (@$urlarr["fragment"] != "")
53 $complete .= "#".$urlarr["fragment"];
59 if(! function_exists('parseurl_getsiteinfo_cached')) {
60 function parseurl_getsiteinfo_cached($url, $no_guessing = false, $do_oembed = true) {
65 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
66 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
69 $data = $r[0]["content"];
71 if (!is_null($data)) {
72 $data = unserialize($data);
76 $data = parseurl_getsiteinfo($url, $no_guessing, $do_oembed);
78 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')",
79 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed), dbesc(serialize($data)), dbesc(datetime_convert()));
85 if(! function_exists('parseurl_getsiteinfo')) {
86 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
87 require_once("include/network.php");
88 require_once("include/Photo.php");
95 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
99 $url = trim($url, "'");
100 $url = trim($url, '"');
102 $url = original_url($url);
104 $siteinfo["url"] = $url;
105 $siteinfo["type"] = "link";
107 $stamp1 = microtime(true);
110 curl_setopt($ch, CURLOPT_URL, $url);
111 curl_setopt($ch, CURLOPT_HEADER, 1);
112 curl_setopt($ch, CURLOPT_NOBODY, 1);
113 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
114 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
115 //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
116 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
118 $header = curl_exec($ch);
119 $curl_info = @curl_getinfo($ch);
120 $http_code = $curl_info['http_code'];
123 $a->save_timestamp($stamp1, "network");
125 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
126 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
127 if ($curl_info['redirect_url'] != "")
128 $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
130 $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
134 // if the file is too large then exit
135 if ($curl_info["download_content_length"] > 1000000)
138 // if it isn't a HTML file then exit
139 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
143 require_once("include/oembed.php");
145 $oembed_data = oembed_fetch_url($url);
147 if ($oembed_data->type != "error")
148 $siteinfo["type"] = $oembed_data->type;
150 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
151 if (isset($oembed_data->title))
152 $siteinfo["title"] = $oembed_data->title;
153 if (isset($oembed_data->description))
154 $siteinfo["text"] = trim($oembed_data->description);
155 if (isset($oembed_data->thumbnail_url))
156 $siteinfo["image"] = $oembed_data->thumbnail_url;
160 $stamp1 = microtime(true);
162 // Now fetch the body as well
164 curl_setopt($ch, CURLOPT_URL, $url);
165 curl_setopt($ch, CURLOPT_HEADER, 1);
166 curl_setopt($ch, CURLOPT_NOBODY, 0);
167 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
168 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
169 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
171 $header = curl_exec($ch);
172 $curl_info = @curl_getinfo($ch);
173 $http_code = $curl_info['http_code'];
176 $a->save_timestamp($stamp1, "network");
178 // Fetch the first mentioned charset. Can be in body or header
180 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
181 $charset = trim(trim(trim(array_pop($matches)), ';,'));
186 $pos = strpos($header, "\r\n\r\n");
189 $body = trim(substr($header, $pos));
193 if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
194 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
195 //$body = mb_convert_encoding($body, "UTF-8", $charset);
196 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
199 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
201 $doc = new DOMDocument();
202 @$doc->loadHTML($body);
204 deletenode($doc, 'style');
205 deletenode($doc, 'script');
206 deletenode($doc, 'option');
207 deletenode($doc, 'h1');
208 deletenode($doc, 'h2');
209 deletenode($doc, 'h3');
210 deletenode($doc, 'h4');
211 deletenode($doc, 'h5');
212 deletenode($doc, 'h6');
213 deletenode($doc, 'ol');
214 deletenode($doc, 'ul');
216 $xpath = new DomXPath($doc);
218 $list = $xpath->query("//meta[@content]");
219 foreach ($list as $node) {
221 if ($node->attributes->length)
222 foreach ($node->attributes as $attribute)
223 $attr[$attribute->name] = $attribute->value;
225 if (@$attr["http-equiv"] == 'refresh') {
226 $path = $attr["content"];
227 $pathinfo = explode(";", $path);
229 foreach ($pathinfo AS $value) {
230 if (substr(strtolower($value), 0, 4) == "url=")
231 $content = substr($value, 4);
233 if ($content != "") {
234 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
240 //$list = $xpath->query("head/title");
241 $list = $xpath->query("//title");
242 foreach ($list as $node)
243 $siteinfo["title"] = html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
245 //$list = $xpath->query("head/meta[@name]");
246 $list = $xpath->query("//meta[@name]");
247 foreach ($list as $node) {
249 if ($node->attributes->length)
250 foreach ($node->attributes as $attribute)
251 $attr[$attribute->name] = $attribute->value;
253 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
255 if ($attr["content"] != "")
256 switch (strtolower($attr["name"])) {
258 $siteinfo["title"] = $attr["content"];
261 $siteinfo["text"] = $attr["content"];
264 $siteinfo["image"] = $attr["content"];
266 case "twitter:image":
267 $siteinfo["image"] = $attr["content"];
269 case "twitter:image:src":
270 $siteinfo["image"] = $attr["content"];
273 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
274 $siteinfo["type"] = $attr["content"];
276 case "twitter:description":
277 $siteinfo["text"] = $attr["content"];
279 case "twitter:title":
280 $siteinfo["title"] = $attr["content"];
283 $siteinfo["title"] = $attr["content"];
285 case "dc.description":
286 $siteinfo["text"] = $attr["content"];
289 $keywords = explode(",", $attr["content"]);
291 case "news_keywords":
292 $keywords = explode(",", $attr["content"]);
295 if ($siteinfo["type"] == "summary")
296 $siteinfo["type"] = "link";
299 if (isset($keywords)) {
300 $siteinfo["keywords"] = array();
301 foreach ($keywords as $keyword)
302 if (!in_array(trim($keyword), $siteinfo["keywords"]))
303 $siteinfo["keywords"][] = trim($keyword);
306 //$list = $xpath->query("head/meta[@property]");
307 $list = $xpath->query("//meta[@property]");
308 foreach ($list as $node) {
310 if ($node->attributes->length)
311 foreach ($node->attributes as $attribute)
312 $attr[$attribute->name] = $attribute->value;
314 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
316 if ($attr["content"] != "")
317 switch (strtolower($attr["property"])) {
319 $siteinfo["image"] = $attr["content"];
322 $siteinfo["title"] = $attr["content"];
324 case "og:description":
325 $siteinfo["text"] = $attr["content"];
330 if ((@$siteinfo["image"] == "") AND !$no_guessing) {
331 $list = $xpath->query("//img[@src]");
332 foreach ($list as $node) {
334 if ($node->attributes->length)
335 foreach ($node->attributes as $attribute)
336 $attr[$attribute->name] = $attribute->value;
338 $src = completeurl($attr["src"], $url);
339 $photodata = get_photo_info($src);
341 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
342 if ($photodata[0] > 300) {
343 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
346 if ($photodata[1] > 300) {
347 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
350 $siteinfo["images"][] = array("src"=>$src,
351 "width"=>$photodata[0],
352 "height"=>$photodata[1]);
356 } elseif ($siteinfo["image"] != "") {
357 $src = completeurl($siteinfo["image"], $url);
359 unset($siteinfo["image"]);
361 $photodata = get_photo_info($src);
363 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
364 $siteinfo["images"][] = array("src"=>$src,
365 "width"=>$photodata[0],
366 "height"=>$photodata[1]);
369 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
372 $list = $xpath->query("//div[@class='article']");
373 foreach ($list as $node)
374 if (strlen($node->nodeValue) > 40)
375 $text .= " ".trim($node->nodeValue);
378 $list = $xpath->query("//div[@class='content']");
379 foreach ($list as $node)
380 if (strlen($node->nodeValue) > 40)
381 $text .= " ".trim($node->nodeValue);
384 // If none text was found then take the paragraph content
386 $list = $xpath->query("//p");
387 foreach ($list as $node)
388 if (strlen($node->nodeValue) > 40)
389 $text .= " ".trim($node->nodeValue);
393 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
395 while (strpos($text, " "))
396 $text = trim(str_replace(" ", " ", $text));
398 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
402 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
404 call_hooks('getsiteinfo', $siteinfo);
410 if(! function_exists('arr_add_hashes')) {
411 function arr_add_hashes(&$item,$k) {
416 if(! function_exists('parse_url_content')) {
417 function parse_url_content(&$a) {
424 if(local_user() && (! feature_enabled(local_user(),'richtext')))
428 $br = (($textmode) ? "\n" : '<br />');
430 if(x($_GET,'binurl'))
431 $url = trim(hex2bin($_GET['binurl']));
433 $url = trim($_GET['url']);
436 $title = strip_tags(trim($_GET['title']));
438 if($_GET['description'])
439 $text = strip_tags(trim($_GET['description']));
442 $arr_tags = str_getcsv($_GET['tags']);
443 if(count($arr_tags)) {
444 array_walk($arr_tags,'arr_add_hashes');
445 $str_tags = $br . implode(' ',$arr_tags) . $br;
449 // add url scheme if missing
450 $arrurl = parse_url($url);
451 if (!x($arrurl, 'scheme')) {
452 if (x($arrurl, 'host'))
455 $url = "http://".$url;
458 logger('parse_url: ' . $url);
461 $template = '[bookmark=%s]%s[/bookmark]%s';
463 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
465 $arr = array('url' => $url, 'text' => '');
467 call_hooks('parse_link', $arr);
469 if(strlen($arr['text'])) {
475 if($url && $title && $text) {
477 $title = str_replace(array("\r","\n"),array('',''),$title);
480 $text = '[quote]' . trim($text) . '[/quote]' . $br;
482 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
483 $title = htmlspecialchars($title);
486 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
488 logger('parse_url (unparsed): returns: ' . $result);
494 $siteinfo = parseurl_getsiteinfo($url);
497 // require_once("include/items.php");
499 // echo add_page_info_data($siteinfo);
503 $url= $siteinfo["url"];
505 // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
506 if (strpos($url, '[') OR strpos($url, ']')) {
507 require_once("include/network.php");
508 $url = short_link($url);
513 if($siteinfo["title"] != "") {
514 $text = $siteinfo["text"];
515 $title = $siteinfo["title"];
520 if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
521 /* Execute below code only if image is present in siteinfo */
524 $max_images = get_config('system','max_bookmark_images');
525 if($max_images === false)
528 $max_images = intval($max_images);
530 foreach ($siteinfo["images"] as $imagedata) {
532 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
534 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
536 if($max_images && $max_images >= $total_images)
543 $text = '[quote]'.trim($text).'[/quote]';
545 $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
549 $text = $br.$br.$image.$text;
553 $title = str_replace(array("\r","\n"),array('',''),$title);
555 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
557 logger('parse_url: returns: ' . $result);
559 $sitedata .= trim($result);
561 if (($siteinfo["type"] == "video") AND ($url != ""))
562 echo "[class=type-video]".$sitedata."[/class]";
563 elseif (($siteinfo["type"] != "photo"))
564 echo "[class=type-link]".$sitedata."[/class]";
566 echo "[class=type-photo]".$title.$br.$image."[/class]";