]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
Better detection for remote user
[friendica.git] / mod / parse_url.php
1 <?php
2 /** 
3  * @file mod/parse_url.php
4  * 
5  * @todo https://developers.google.com/+/plugins/snippet/
6  * 
7  * @verbatim
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">
11  * 
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>
16  * </body>
17  * @endverbatim
18 */
19
20 if(!function_exists('deletenode')) {
21         function deletenode(&$doc, $node)
22         {
23                 $xpath = new DomXPath($doc);
24                 $list = $xpath->query("//".$node);
25                 foreach ($list as $child)
26                         $child->parentNode->removeChild($child);
27         }
28 }
29
30 function completeurl($url, $scheme) {
31         $urlarr = parse_url($url);
32
33         if (isset($urlarr["scheme"]))
34                 return($url);
35
36         $schemearr = parse_url($scheme);
37
38         $complete = $schemearr["scheme"]."://".$schemearr["host"];
39
40         if (@$schemearr["port"] != "")
41                 $complete .= ":".$schemearr["port"];
42
43                 if(strpos($urlarr['path'],'/') !== 0)
44                         $complete .= '/';
45
46         $complete .= $urlarr["path"];
47
48         if (@$urlarr["query"] != "")
49                 $complete .= "?".$urlarr["query"];
50
51         if (@$urlarr["fragment"] != "")
52                 $complete .= "#".$urlarr["fragment"];
53
54         return($complete);
55 }
56
57 function parseurl_getsiteinfo_cached($url, $no_guessing = false, $do_oembed = true) {
58
59         if ($url == "")
60                 return false;
61
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));
64
65         if ($r)
66                 $data = $r[0]["content"];
67
68         if (!is_null($data)) {
69                 $data = unserialize($data);
70                 return $data;
71         }
72
73         $data = parseurl_getsiteinfo($url, $no_guessing, $do_oembed);
74
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()));
80
81         return $data;
82 }
83
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");
87
88         $a = get_app();
89
90         $siteinfo = array();
91
92         if ($count > 10) {
93                 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
94                 return($siteinfo);
95         }
96
97         $url = trim($url, "'");
98         $url = trim($url, '"');
99
100         $url = original_url($url);
101
102         $siteinfo["url"] = $url;
103         $siteinfo["type"] = "link";
104
105         $stamp1 = microtime(true);
106
107         $ch = curl_init();
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());
115
116         $header = curl_exec($ch);
117         $curl_info = @curl_getinfo($ch);
118         $http_code = $curl_info['http_code'];
119         curl_close($ch);
120
121         $a->save_timestamp($stamp1, "network");
122
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);
127                 else
128                         $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
129                 return($siteinfo);
130         }
131
132         // if the file is too large then exit
133         if ($curl_info["download_content_length"] > 1000000)
134                 return($siteinfo);
135
136         // if it isn't a HTML file then exit
137         if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
138                 return($siteinfo);
139
140         if ($do_oembed) {
141                 require_once("include/oembed.php");
142
143                 $oembed_data = oembed_fetch_url($url);
144
145                 if ($oembed_data->type != "error")
146                         $siteinfo["type"] = $oembed_data->type;
147
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;
155                 }
156         }
157
158         $stamp1 = microtime(true);
159
160         // Now fetch the body as well
161         $ch = curl_init();
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());
168
169         $header = curl_exec($ch);
170         $curl_info = @curl_getinfo($ch);
171         $http_code = $curl_info['http_code'];
172         curl_close($ch);
173
174         $a->save_timestamp($stamp1, "network");
175
176         // Fetch the first mentioned charset. Can be in body or header
177         $charset = "";
178         if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
179                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
180
181         if ($charset == "")
182                 $charset = "utf-8";
183
184         $pos = strpos($header, "\r\n\r\n");
185
186         if ($pos)
187                 $body = trim(substr($header, $pos));
188         else
189                 $body = $header;
190
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);
195         }
196
197         $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
198
199         $doc = new DOMDocument();
200         @$doc->loadHTML($body);
201
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');
213
214         $xpath = new DomXPath($doc);
215
216         $list = $xpath->query("//meta[@content]");
217         foreach ($list as $node) {
218                 $attr = array();
219                 if ($node->attributes->length)
220                         foreach ($node->attributes as $attribute)
221                                 $attr[$attribute->name] = $attribute->value;
222
223                 if (@$attr["http-equiv"] == 'refresh') {
224                         $path = $attr["content"];
225                         $pathinfo = explode(";", $path);
226                         $content = "";
227                         foreach ($pathinfo AS $value) {
228                                 if (substr(strtolower($value), 0, 4) == "url=")
229                                         $content = substr($value, 4);
230                         }
231                         if ($content != "") {
232                                 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
233                                 return($siteinfo);
234                         }
235                 }
236         }
237
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");
242
243         //$list = $xpath->query("head/meta[@name]");
244         $list = $xpath->query("//meta[@name]");
245         foreach ($list as $node) {
246                 $attr = array();
247                 if ($node->attributes->length)
248                         foreach ($node->attributes as $attribute)
249                                 $attr[$attribute->name] = $attribute->value;
250
251                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
252
253                 if ($attr["content"] != "")
254                         switch (strtolower($attr["name"])) {
255                                 case "fulltitle":
256                                         $siteinfo["title"] = $attr["content"];
257                                         break;
258                                 case "description":
259                                         $siteinfo["text"] = $attr["content"];
260                                         break;
261                                 case "thumbnail":
262                                         $siteinfo["image"] = $attr["content"];
263                                         break;
264                                 case "twitter:image":
265                                         $siteinfo["image"] = $attr["content"];
266                                         break;
267                                 case "twitter:image:src":
268                                         $siteinfo["image"] = $attr["content"];
269                                         break;
270                                 case "twitter:card":
271                                         if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
272                                                 $siteinfo["type"] = $attr["content"];
273                                         break;
274                                 case "twitter:description":
275                                         $siteinfo["text"] = $attr["content"];
276                                         break;
277                                 case "twitter:title":
278                                         $siteinfo["title"] = $attr["content"];
279                                         break;
280                                 case "dc.title":
281                                         $siteinfo["title"] = $attr["content"];
282                                         break;
283                                 case "dc.description":
284                                         $siteinfo["text"] = $attr["content"];
285                                         break;
286                                 case "keywords":
287                                         $keywords = explode(",", $attr["content"]);
288                                         break;
289                                 case "news_keywords":
290                                         $keywords = explode(",", $attr["content"]);
291                                         break;
292                         }
293                 if ($siteinfo["type"] == "summary")
294                         $siteinfo["type"] = "link";
295         }
296
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);
302         }
303
304         //$list = $xpath->query("head/meta[@property]");
305         $list = $xpath->query("//meta[@property]");
306         foreach ($list as $node) {
307                 $attr = array();
308                 if ($node->attributes->length)
309                         foreach ($node->attributes as $attribute)
310                                 $attr[$attribute->name] = $attribute->value;
311
312                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
313
314                 if ($attr["content"] != "")
315                         switch (strtolower($attr["property"])) {
316                                 case "og:image":
317                                         $siteinfo["image"] = $attr["content"];
318                                         break;
319                                 case "og:title":
320                                         $siteinfo["title"] = $attr["content"];
321                                         break;
322                                 case "og:description":
323                                         $siteinfo["text"] = $attr["content"];
324                                         break;
325                         }
326         }
327
328         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
329             $list = $xpath->query("//img[@src]");
330             foreach ($list as $node) {
331                 $attr = array();
332                 if ($node->attributes->length)
333                     foreach ($node->attributes as $attribute)
334                         $attr[$attribute->name] = $attribute->value;
335
336                         $src = completeurl($attr["src"], $url);
337                         $photodata = get_photo_info($src);
338
339                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
340                                 if ($photodata[0] > 300) {
341                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
342                                         $photodata[0] = 300;
343                                 }
344                                 if ($photodata[1] > 300) {
345                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
346                                         $photodata[1] = 300;
347                                 }
348                                 $siteinfo["images"][] = array("src"=>$src,
349                                                                 "width"=>$photodata[0],
350                                                                 "height"=>$photodata[1]);
351                         }
352
353                 }
354     } elseif ($siteinfo["image"] != "") {
355                 $src = completeurl($siteinfo["image"], $url);
356
357                 unset($siteinfo["image"]);
358
359                 $photodata = get_photo_info($src);
360
361                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
362                         $siteinfo["images"][] = array("src"=>$src,
363                                                         "width"=>$photodata[0],
364                                                         "height"=>$photodata[1]);
365         }
366
367         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
368                 $text = "";
369
370                 $list = $xpath->query("//div[@class='article']");
371                 foreach ($list as $node)
372                         if (strlen($node->nodeValue) > 40)
373                                 $text .= " ".trim($node->nodeValue);
374
375                 if ($text == "") {
376                         $list = $xpath->query("//div[@class='content']");
377                         foreach ($list as $node)
378                                 if (strlen($node->nodeValue) > 40)
379                                         $text .= " ".trim($node->nodeValue);
380                 }
381
382                 // If none text was found then take the paragraph content
383                 if ($text == "") {
384                         $list = $xpath->query("//p");
385                         foreach ($list as $node)
386                                 if (strlen($node->nodeValue) > 40)
387                                         $text .= " ".trim($node->nodeValue);
388                 }
389
390                 if ($text != "") {
391                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
392
393                         while (strpos($text, "  "))
394                                 $text = trim(str_replace("  ", " ", $text));
395
396                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
397                 }
398         }
399
400         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
401
402         call_hooks('getsiteinfo', $siteinfo);
403
404         return($siteinfo);
405 }
406
407 function arr_add_hashes(&$item,$k) {
408         $item = '#' . $item;
409 }
410
411 function parse_url_content(&$a) {
412
413         require_once("include/items.php");
414
415         $text = null;
416         $str_tags = '';
417
418         $textmode = false;
419
420         if(local_user() && (! feature_enabled(local_user(),'richtext')))
421                 $textmode = true;
422
423         //if($textmode)
424         $br = (($textmode) ? "\n" : '<br />');
425
426         if(x($_GET,'binurl'))
427                 $url = trim(hex2bin($_GET['binurl']));
428         else
429                 $url = trim($_GET['url']);
430
431         if($_GET['title'])
432                 $title = strip_tags(trim($_GET['title']));
433
434         if($_GET['description'])
435                 $text = strip_tags(trim($_GET['description']));
436
437         if($_GET['tags']) {
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;
442                 }
443         }
444
445         // add url scheme if missing
446         $arrurl = parse_url($url);
447         if (!x($arrurl, 'scheme')) {
448                 if (x($arrurl, 'host'))
449                         $url = "http:".$url;
450                 else
451                         $url = "http://".$url;
452         }
453
454         logger('parse_url: ' . $url);
455
456         if($textmode)
457                 $template = '[bookmark=%s]%s[/bookmark]%s';
458         else
459                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
460
461         $arr = array('url' => $url, 'text' => '');
462
463         call_hooks('parse_link', $arr);
464
465         if(strlen($arr['text'])) {
466                 echo $arr['text'];
467                 killme();
468         }
469
470
471         if($url && $title && $text) {
472
473                 $title = str_replace(array("\r","\n"),array('',''),$title);
474
475                 if($textmode)
476                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
477                 else {
478                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
479                         $title = htmlspecialchars($title);
480                 }
481
482                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
483
484                 logger('parse_url (unparsed): returns: ' . $result);
485
486                 echo $result;
487                 killme();
488         }
489
490         $siteinfo = parseurl_getsiteinfo($url);
491
492         unset($siteinfo["keywords"]);
493
494         $info = add_page_info_data($siteinfo);
495
496         if (!$textmode)
497                 // Replace ' with ’ - not perfect - but the richtext editor has problems otherwise
498                 $info = str_replace(array("&#039;"), array("&#8217;"), $info);
499
500         echo $info;
501
502         killme();
503 }
504 ?>