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) {
59 $data = Cache::get("parse_url:".$no_guessing.":".$do_oembed.":".$url);
60 if (!is_null($data)) {
61 $data = unserialize($data);
65 $data = parseurl_getsiteinfo($url, $no_guessing, $do_oembed);
67 Cache::set("parse_url:".$no_guessing.":".$do_oembed.":".$url,serialize($data), CACHE_DAY);
72 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
73 require_once("include/network.php");
80 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
84 $url = trim($url, "'");
85 $url = trim($url, '"');
87 $url = original_url($url);
89 $siteinfo["url"] = $url;
90 $siteinfo["type"] = "link";
92 $stamp1 = microtime(true);
95 curl_setopt($ch, CURLOPT_URL, $url);
96 curl_setopt($ch, CURLOPT_HEADER, 1);
97 curl_setopt($ch, CURLOPT_NOBODY, 1);
98 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
99 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
100 //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
101 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
103 $header = curl_exec($ch);
104 $curl_info = @curl_getinfo($ch);
105 $http_code = $curl_info['http_code'];
108 $a->save_timestamp($stamp1, "network");
110 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
111 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
112 if ($curl_info['redirect_url'] != "")
113 $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
115 $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
119 // if the file is too large then exit
120 if ($curl_info["download_content_length"] > 1000000)
123 // if it isn't a HTML file then exit
124 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
128 require_once("include/oembed.php");
130 $oembed_data = oembed_fetch_url($url);
132 if ($oembed_data->type != "error")
133 $siteinfo["type"] = $oembed_data->type;
135 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
136 if (isset($oembed_data->title))
137 $siteinfo["title"] = $oembed_data->title;
138 if (isset($oembed_data->description))
139 $siteinfo["text"] = trim($oembed_data->description);
140 if (isset($oembed_data->thumbnail_url))
141 $siteinfo["image"] = $oembed_data->thumbnail_url;
145 $stamp1 = microtime(true);
147 // Now fetch the body as well
149 curl_setopt($ch, CURLOPT_URL, $url);
150 curl_setopt($ch, CURLOPT_HEADER, 1);
151 curl_setopt($ch, CURLOPT_NOBODY, 0);
152 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
153 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
154 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
156 $header = curl_exec($ch);
157 $curl_info = @curl_getinfo($ch);
158 $http_code = $curl_info['http_code'];
161 $a->save_timestamp($stamp1, "network");
163 // Fetch the first mentioned charset. Can be in body or header
165 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
166 $charset = trim(trim(trim(array_pop($matches)), ';,'));
171 $pos = strpos($header, "\r\n\r\n");
174 $body = trim(substr($header, $pos));
178 if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
179 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
180 //$body = mb_convert_encoding($body, "UTF-8", $charset);
181 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
184 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
186 $doc = new DOMDocument();
187 @$doc->loadHTML($body);
189 deletenode($doc, 'style');
190 deletenode($doc, 'script');
191 deletenode($doc, 'option');
192 deletenode($doc, 'h1');
193 deletenode($doc, 'h2');
194 deletenode($doc, 'h3');
195 deletenode($doc, 'h4');
196 deletenode($doc, 'h5');
197 deletenode($doc, 'h6');
198 deletenode($doc, 'ol');
199 deletenode($doc, 'ul');
201 $xpath = new DomXPath($doc);
203 $list = $xpath->query("//meta[@content]");
204 foreach ($list as $node) {
206 if ($node->attributes->length)
207 foreach ($node->attributes as $attribute)
208 $attr[$attribute->name] = $attribute->value;
210 if (@$attr["http-equiv"] == 'refresh') {
211 $path = $attr["content"];
212 $pathinfo = explode(";", $path);
214 foreach ($pathinfo AS $value) {
215 if (substr(strtolower($value), 0, 4) == "url=")
216 $content = substr($value, 4);
218 if ($content != "") {
219 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
225 //$list = $xpath->query("head/title");
226 $list = $xpath->query("//title");
227 foreach ($list as $node)
228 $siteinfo["title"] = html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
230 //$list = $xpath->query("head/meta[@name]");
231 $list = $xpath->query("//meta[@name]");
232 foreach ($list as $node) {
234 if ($node->attributes->length)
235 foreach ($node->attributes as $attribute)
236 $attr[$attribute->name] = $attribute->value;
238 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
240 if ($attr["content"] != "")
241 switch (strtolower($attr["name"])) {
243 $siteinfo["title"] = $attr["content"];
246 $siteinfo["text"] = $attr["content"];
249 $siteinfo["image"] = $attr["content"];
251 case "twitter:image":
252 $siteinfo["image"] = $attr["content"];
254 case "twitter:image:src":
255 $siteinfo["image"] = $attr["content"];
258 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
259 $siteinfo["type"] = $attr["content"];
261 case "twitter:description":
262 $siteinfo["text"] = $attr["content"];
264 case "twitter:title":
265 $siteinfo["title"] = $attr["content"];
268 $siteinfo["title"] = $attr["content"];
270 case "dc.description":
271 $siteinfo["text"] = $attr["content"];
274 $keywords = explode(",", $attr["content"]);
276 case "news_keywords":
277 $keywords = explode(",", $attr["content"]);
280 if ($siteinfo["type"] == "summary")
281 $siteinfo["type"] = "link";
284 if (isset($keywords)) {
285 $siteinfo["keywords"] = array();
286 foreach ($keywords as $keyword)
287 if (!in_array(trim($keyword), $siteinfo["keywords"]))
288 $siteinfo["keywords"][] = trim($keyword);
291 //$list = $xpath->query("head/meta[@property]");
292 $list = $xpath->query("//meta[@property]");
293 foreach ($list as $node) {
295 if ($node->attributes->length)
296 foreach ($node->attributes as $attribute)
297 $attr[$attribute->name] = $attribute->value;
299 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
301 if ($attr["content"] != "")
302 switch (strtolower($attr["property"])) {
304 $siteinfo["image"] = $attr["content"];
307 $siteinfo["title"] = $attr["content"];
309 case "og:description":
310 $siteinfo["text"] = $attr["content"];
315 if ((@$siteinfo["image"] == "") AND !$no_guessing) {
316 $list = $xpath->query("//img[@src]");
317 foreach ($list as $node) {
319 if ($node->attributes->length)
320 foreach ($node->attributes as $attribute)
321 $attr[$attribute->name] = $attribute->value;
323 $src = completeurl($attr["src"], $url);
324 $photodata = @getimagesize($src);
326 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
327 if ($photodata[0] > 300) {
328 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
331 if ($photodata[1] > 300) {
332 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
335 $siteinfo["images"][] = array("src"=>$src,
336 "width"=>$photodata[0],
337 "height"=>$photodata[1]);
342 $src = completeurl($siteinfo["image"], $url);
344 unset($siteinfo["image"]);
346 $photodata = @getimagesize($src);
348 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
349 $siteinfo["images"][] = array("src"=>$src,
350 "width"=>$photodata[0],
351 "height"=>$photodata[1]);
354 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
357 $list = $xpath->query("//div[@class='article']");
358 foreach ($list as $node)
359 if (strlen($node->nodeValue) > 40)
360 $text .= " ".trim($node->nodeValue);
363 $list = $xpath->query("//div[@class='content']");
364 foreach ($list as $node)
365 if (strlen($node->nodeValue) > 40)
366 $text .= " ".trim($node->nodeValue);
369 // If none text was found then take the paragraph content
371 $list = $xpath->query("//p");
372 foreach ($list as $node)
373 if (strlen($node->nodeValue) > 40)
374 $text .= " ".trim($node->nodeValue);
378 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
380 while (strpos($text, " "))
381 $text = trim(str_replace(" ", " ", $text));
383 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
387 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
389 call_hooks('getsiteinfo', $siteinfo);
394 function arr_add_hashes(&$item,$k) {
398 function parse_url_content(&$a) {
405 if(local_user() && (! feature_enabled(local_user(),'richtext')))
409 $br = (($textmode) ? "\n" : '<br />');
411 if(x($_GET,'binurl'))
412 $url = trim(hex2bin($_GET['binurl']));
414 $url = trim($_GET['url']);
417 $title = strip_tags(trim($_GET['title']));
419 if($_GET['description'])
420 $text = strip_tags(trim($_GET['description']));
423 $arr_tags = str_getcsv($_GET['tags']);
424 if(count($arr_tags)) {
425 array_walk($arr_tags,'arr_add_hashes');
426 $str_tags = $br . implode(' ',$arr_tags) . $br;
430 // add url scheme if missing
431 $arrurl = parse_url($url);
432 if (!x($arrurl, 'scheme')) {
433 if (x($arrurl, 'host'))
436 $url = "http://".$url;
439 logger('parse_url: ' . $url);
442 $template = '[bookmark=%s]%s[/bookmark]%s';
444 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
446 $arr = array('url' => $url, 'text' => '');
448 call_hooks('parse_link', $arr);
450 if(strlen($arr['text'])) {
456 if($url && $title && $text) {
458 $title = str_replace(array("\r","\n"),array('',''),$title);
461 $text = '[quote]' . trim($text) . '[/quote]' . $br;
463 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
464 $title = htmlspecialchars($title);
467 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
469 logger('parse_url (unparsed): returns: ' . $result);
475 $siteinfo = parseurl_getsiteinfo($url);
478 // require_once("include/items.php");
480 // echo add_page_info_data($siteinfo);
484 $url= $siteinfo["url"];
486 // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
487 if (strpos($url, '[') OR strpos($url, ']')) {
488 require_once("include/network.php");
489 $url = short_link($url);
494 if($siteinfo["title"] != "") {
495 $text = $siteinfo["text"];
496 $title = $siteinfo["title"];
501 if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
502 /* Execute below code only if image is present in siteinfo */
505 $max_images = get_config('system','max_bookmark_images');
506 if($max_images === false)
509 $max_images = intval($max_images);
511 foreach ($siteinfo["images"] as $imagedata) {
513 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
515 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
517 if($max_images && $max_images >= $total_images)
524 $text = '[quote]'.trim($text).'[/quote]';
526 $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
530 $text = $br.$br.$image.$text;
534 $title = str_replace(array("\r","\n"),array('',''),$title);
536 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
538 logger('parse_url: returns: ' . $result);
540 $sitedata .= trim($result);
542 if (($siteinfo["type"] == "video") AND ($url != ""))
543 echo "[class=type-video]".$sitedata."[/class]";
544 elseif (($siteinfo["type"] != "photo"))
545 echo "[class=type-link]".$sitedata."[/class]";
547 echo "[class=type-photo]".$title.$br.$image."[/class]";