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 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed), dbesc(serialize($data)), dbesc(datetime_convert()));
81 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
82 require_once("include/network.php");
83 require_once("include/Photo.php");
90 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
94 $url = trim($url, "'");
95 $url = trim($url, '"');
97 $url = original_url($url);
99 $siteinfo["url"] = $url;
100 $siteinfo["type"] = "link";
102 $stamp1 = microtime(true);
105 curl_setopt($ch, CURLOPT_URL, $url);
106 curl_setopt($ch, CURLOPT_HEADER, 1);
107 curl_setopt($ch, CURLOPT_NOBODY, 1);
108 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
109 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
110 //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
111 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
113 $header = curl_exec($ch);
114 $curl_info = @curl_getinfo($ch);
115 $http_code = $curl_info['http_code'];
118 $a->save_timestamp($stamp1, "network");
120 if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
121 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
122 if ($curl_info['redirect_url'] != "")
123 $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
125 $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
129 // if the file is too large then exit
130 if ($curl_info["download_content_length"] > 1000000)
133 // if it isn't a HTML file then exit
134 if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
138 require_once("include/oembed.php");
140 $oembed_data = oembed_fetch_url($url);
142 if ($oembed_data->type != "error")
143 $siteinfo["type"] = $oembed_data->type;
145 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
146 if (isset($oembed_data->title))
147 $siteinfo["title"] = $oembed_data->title;
148 if (isset($oembed_data->description))
149 $siteinfo["text"] = trim($oembed_data->description);
150 if (isset($oembed_data->thumbnail_url))
151 $siteinfo["image"] = $oembed_data->thumbnail_url;
155 $stamp1 = microtime(true);
157 // Now fetch the body as well
159 curl_setopt($ch, CURLOPT_URL, $url);
160 curl_setopt($ch, CURLOPT_HEADER, 1);
161 curl_setopt($ch, CURLOPT_NOBODY, 0);
162 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
163 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
164 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
166 $header = curl_exec($ch);
167 $curl_info = @curl_getinfo($ch);
168 $http_code = $curl_info['http_code'];
171 $a->save_timestamp($stamp1, "network");
173 // Fetch the first mentioned charset. Can be in body or header
175 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
176 $charset = trim(trim(trim(array_pop($matches)), ';,'));
181 $pos = strpos($header, "\r\n\r\n");
184 $body = trim(substr($header, $pos));
188 if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
189 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
190 //$body = mb_convert_encoding($body, "UTF-8", $charset);
191 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
194 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
196 $doc = new DOMDocument();
197 @$doc->loadHTML($body);
199 deletenode($doc, 'style');
200 deletenode($doc, 'script');
201 deletenode($doc, 'option');
202 deletenode($doc, 'h1');
203 deletenode($doc, 'h2');
204 deletenode($doc, 'h3');
205 deletenode($doc, 'h4');
206 deletenode($doc, 'h5');
207 deletenode($doc, 'h6');
208 deletenode($doc, 'ol');
209 deletenode($doc, 'ul');
211 $xpath = new DomXPath($doc);
213 $list = $xpath->query("//meta[@content]");
214 foreach ($list as $node) {
216 if ($node->attributes->length)
217 foreach ($node->attributes as $attribute)
218 $attr[$attribute->name] = $attribute->value;
220 if (@$attr["http-equiv"] == 'refresh') {
221 $path = $attr["content"];
222 $pathinfo = explode(";", $path);
224 foreach ($pathinfo AS $value) {
225 if (substr(strtolower($value), 0, 4) == "url=")
226 $content = substr($value, 4);
228 if ($content != "") {
229 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
235 //$list = $xpath->query("head/title");
236 $list = $xpath->query("//title");
237 foreach ($list as $node)
238 $siteinfo["title"] = html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
240 //$list = $xpath->query("head/meta[@name]");
241 $list = $xpath->query("//meta[@name]");
242 foreach ($list as $node) {
244 if ($node->attributes->length)
245 foreach ($node->attributes as $attribute)
246 $attr[$attribute->name] = $attribute->value;
248 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
250 if ($attr["content"] != "")
251 switch (strtolower($attr["name"])) {
253 $siteinfo["title"] = $attr["content"];
256 $siteinfo["text"] = $attr["content"];
259 $siteinfo["image"] = $attr["content"];
261 case "twitter:image":
262 $siteinfo["image"] = $attr["content"];
264 case "twitter:image:src":
265 $siteinfo["image"] = $attr["content"];
268 if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
269 $siteinfo["type"] = $attr["content"];
271 case "twitter:description":
272 $siteinfo["text"] = $attr["content"];
274 case "twitter:title":
275 $siteinfo["title"] = $attr["content"];
278 $siteinfo["title"] = $attr["content"];
280 case "dc.description":
281 $siteinfo["text"] = $attr["content"];
284 $keywords = explode(",", $attr["content"]);
286 case "news_keywords":
287 $keywords = explode(",", $attr["content"]);
290 if ($siteinfo["type"] == "summary")
291 $siteinfo["type"] = "link";
294 if (isset($keywords)) {
295 $siteinfo["keywords"] = array();
296 foreach ($keywords as $keyword)
297 if (!in_array(trim($keyword), $siteinfo["keywords"]))
298 $siteinfo["keywords"][] = trim($keyword);
301 //$list = $xpath->query("head/meta[@property]");
302 $list = $xpath->query("//meta[@property]");
303 foreach ($list as $node) {
305 if ($node->attributes->length)
306 foreach ($node->attributes as $attribute)
307 $attr[$attribute->name] = $attribute->value;
309 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
311 if ($attr["content"] != "")
312 switch (strtolower($attr["property"])) {
314 $siteinfo["image"] = $attr["content"];
317 $siteinfo["title"] = $attr["content"];
319 case "og:description":
320 $siteinfo["text"] = $attr["content"];
325 if ((@$siteinfo["image"] == "") AND !$no_guessing) {
326 $list = $xpath->query("//img[@src]");
327 foreach ($list as $node) {
329 if ($node->attributes->length)
330 foreach ($node->attributes as $attribute)
331 $attr[$attribute->name] = $attribute->value;
333 $src = completeurl($attr["src"], $url);
334 $photodata = get_photo_info($src);
336 if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
337 if ($photodata[0] > 300) {
338 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
341 if ($photodata[1] > 300) {
342 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
345 $siteinfo["images"][] = array("src"=>$src,
346 "width"=>$photodata[0],
347 "height"=>$photodata[1]);
351 } elseif ($siteinfo["image"] != "") {
352 $src = completeurl($siteinfo["image"], $url);
354 unset($siteinfo["image"]);
356 $photodata = get_photo_info($src);
358 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
359 $siteinfo["images"][] = array("src"=>$src,
360 "width"=>$photodata[0],
361 "height"=>$photodata[1]);
364 if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
367 $list = $xpath->query("//div[@class='article']");
368 foreach ($list as $node)
369 if (strlen($node->nodeValue) > 40)
370 $text .= " ".trim($node->nodeValue);
373 $list = $xpath->query("//div[@class='content']");
374 foreach ($list as $node)
375 if (strlen($node->nodeValue) > 40)
376 $text .= " ".trim($node->nodeValue);
379 // If none text was found then take the paragraph content
381 $list = $xpath->query("//p");
382 foreach ($list as $node)
383 if (strlen($node->nodeValue) > 40)
384 $text .= " ".trim($node->nodeValue);
388 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
390 while (strpos($text, " "))
391 $text = trim(str_replace(" ", " ", $text));
393 $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
397 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
399 call_hooks('getsiteinfo', $siteinfo);
404 function arr_add_hashes(&$item,$k) {
408 function parse_url_content(&$a) {
415 if(local_user() && (! feature_enabled(local_user(),'richtext')))
419 $br = (($textmode) ? "\n" : '<br />');
421 if(x($_GET,'binurl'))
422 $url = trim(hex2bin($_GET['binurl']));
424 $url = trim($_GET['url']);
427 $title = strip_tags(trim($_GET['title']));
429 if($_GET['description'])
430 $text = strip_tags(trim($_GET['description']));
433 $arr_tags = str_getcsv($_GET['tags']);
434 if(count($arr_tags)) {
435 array_walk($arr_tags,'arr_add_hashes');
436 $str_tags = $br . implode(' ',$arr_tags) . $br;
440 // add url scheme if missing
441 $arrurl = parse_url($url);
442 if (!x($arrurl, 'scheme')) {
443 if (x($arrurl, 'host'))
446 $url = "http://".$url;
449 logger('parse_url: ' . $url);
452 $template = '[bookmark=%s]%s[/bookmark]%s';
454 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
456 $arr = array('url' => $url, 'text' => '');
458 call_hooks('parse_link', $arr);
460 if(strlen($arr['text'])) {
466 if($url && $title && $text) {
468 $title = str_replace(array("\r","\n"),array('',''),$title);
471 $text = '[quote]' . trim($text) . '[/quote]' . $br;
473 $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
474 $title = htmlspecialchars($title);
477 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
479 logger('parse_url (unparsed): returns: ' . $result);
485 $siteinfo = parseurl_getsiteinfo($url);
488 // require_once("include/items.php");
490 // echo add_page_info_data($siteinfo);
494 $url= $siteinfo["url"];
496 // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
497 if (strpos($url, '[') OR strpos($url, ']')) {
498 require_once("include/network.php");
499 $url = short_link($url);
504 if($siteinfo["title"] != "") {
505 $text = $siteinfo["text"];
506 $title = $siteinfo["title"];
511 if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
512 /* Execute below code only if image is present in siteinfo */
515 $max_images = get_config('system','max_bookmark_images');
516 if($max_images === false)
519 $max_images = intval($max_images);
521 foreach ($siteinfo["images"] as $imagedata) {
523 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
525 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
527 if($max_images && $max_images >= $total_images)
534 $text = '[quote]'.trim($text).'[/quote]';
536 $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
540 $text = $br.$br.$image.$text;
544 $title = str_replace(array("\r","\n"),array('',''),$title);
546 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
548 logger('parse_url: returns: ' . $result);
550 $sitedata .= trim($result);
552 if (($siteinfo["type"] == "video") AND ($url != ""))
553 echo "[class=type-video]".$sitedata."[/class]";
554 elseif (($siteinfo["type"] != "photo"))
555 echo "[class=type-link]".$sitedata."[/class]";
557 echo "[class=type-photo]".$title.$br.$image."[/class]";