]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
Merge pull request #1067 from Beanow/feature/noscrape
[friendica.git] / mod / parse_url.php
1 <?php
2 /* To-Do
3 https://developers.google.com/+/plugins/snippet/
4
5 <meta itemprop="name" content="Toller Titel">
6 <meta itemprop="description" content="Eine tolle Beschreibung">
7 <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
8
9 <body itemscope itemtype="http://schema.org/Product">
10   <h1 itemprop="name">Shiny Trinket</h1>
11   <img itemprop="image" src="{image-url}" />
12   <p itemprop="description">Shiny trinkets are shiny.</p>
13 </body>
14 */
15
16 if(!function_exists('deletenode')) {
17         function deletenode(&$doc, $node)
18         {
19                 $xpath = new DomXPath($doc);
20                 $list = $xpath->query("//".$node);
21                 foreach ($list as $child)
22                         $child->parentNode->removeChild($child);
23         }
24 }
25
26 function completeurl($url, $scheme) {
27         $urlarr = parse_url($url);
28
29         if (isset($urlarr["scheme"]))
30                 return($url);
31
32         $schemearr = parse_url($scheme);
33
34         $complete = $schemearr["scheme"]."://".$schemearr["host"];
35
36         if (@$schemearr["port"] != "")
37                 $complete .= ":".$schemearr["port"];
38
39                 if(strpos($urlarr['path'],'/') !== 0)
40                         $complete .= '/';
41
42         $complete .= $urlarr["path"];
43
44         if (@$urlarr["query"] != "")
45                 $complete .= "?".$urlarr["query"];
46
47         if (@$urlarr["fragment"] != "")
48                 $complete .= "#".$urlarr["fragment"];
49
50         return($complete);
51 }
52
53 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
54
55         $siteinfo = array();
56
57         if ($count > 10) {
58                 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
59                 return($siteinfo);
60         }
61
62         $url = trim($url, "'");
63         $url = trim($url, '"');
64         $siteinfo["url"] = $url;
65         $siteinfo["type"] = "link";
66
67         $ch = curl_init();
68         curl_setopt($ch, CURLOPT_URL, $url);
69         curl_setopt($ch, CURLOPT_HEADER, 1);
70         curl_setopt($ch, CURLOPT_NOBODY, 0);
71         curl_setopt($ch, CURLOPT_TIMEOUT, 3);
72         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
73         //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
74         curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; ".FRIENDICA_PLATFORM." ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION.")");
75
76         $header = curl_exec($ch);
77         $curl_info = @curl_getinfo($ch);
78         $http_code = $curl_info['http_code'];
79         curl_close($ch);
80
81         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
82                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
83                 if ($curl_info['redirect_url'] != "")
84                         $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
85                 else
86                         $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
87                 return($siteinfo);
88         }
89
90         if ($do_oembed) {
91                 require_once("include/oembed.php");
92
93                 $oembed_data = oembed_fetch_url($url);
94
95                 if ($oembed_data->type != "error")
96                         $siteinfo["type"] = $oembed_data->type;
97         }
98
99         // Fetch the first mentioned charset. Can be in body or header
100         $charset = "";
101         if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
102                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
103
104         if ($charset == "")
105                 $charset = "utf-8";
106
107         $pos = strpos($header, "\r\n\r\n");
108
109         if ($pos)
110                 $body = trim(substr($header, $pos));
111         else
112                 $body = $header;
113
114         if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
115                 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
116                 //$body = mb_convert_encoding($body, "UTF-8", $charset);
117                 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
118         }
119
120         $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
121
122         $doc = new DOMDocument();
123         @$doc->loadHTML($body);
124
125         deletenode($doc, 'style');
126         deletenode($doc, 'script');
127         deletenode($doc, 'option');
128         deletenode($doc, 'h1');
129         deletenode($doc, 'h2');
130         deletenode($doc, 'h3');
131         deletenode($doc, 'h4');
132         deletenode($doc, 'h5');
133         deletenode($doc, 'h6');
134         deletenode($doc, 'ol');
135         deletenode($doc, 'ul');
136
137         $xpath = new DomXPath($doc);
138
139         $list = $xpath->query("//meta[@content]");
140         foreach ($list as $node) {
141                 $attr = array();
142                 if ($node->attributes->length)
143                         foreach ($node->attributes as $attribute)
144                                 $attr[$attribute->name] = $attribute->value;
145
146                 if (@$attr["http-equiv"] == 'refresh') {
147                         $path = $attr["content"];
148                         $pathinfo = explode(";", $path);
149                         $content = "";
150                         foreach ($pathinfo AS $value) {
151                                 if (substr(strtolower($value), 0, 4) == "url=")
152                                         $content = substr($value, 4);
153                         }
154                         if ($content != "") {
155                                 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
156                                 return($siteinfo);
157                         }
158                 }
159         }
160
161         //$list = $xpath->query("head/title");
162         $list = $xpath->query("//title");
163         foreach ($list as $node)
164                 $siteinfo["title"] =  html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
165
166         //$list = $xpath->query("head/meta[@name]");
167         $list = $xpath->query("//meta[@name]");
168         foreach ($list as $node) {
169                 $attr = array();
170                 if ($node->attributes->length)
171                         foreach ($node->attributes as $attribute)
172                                 $attr[$attribute->name] = $attribute->value;
173
174                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
175
176                 if ($attr["content"] != "")
177                         switch (strtolower($attr["name"])) {
178                                 case "fulltitle":
179                                         $siteinfo["title"] = $attr["content"];
180                                         break;
181                                 case "description":
182                                         $siteinfo["text"] = $attr["content"];
183                                         break;
184                                 case "twitter:image":
185                                         $siteinfo["image"] = $attr["content"];
186                                         break;
187                                 case "twitter:card":
188                                         if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
189                                                 $siteinfo["type"] = $attr["content"];
190                                         break;
191                                 case "twitter:description":
192                                         $siteinfo["text"] = $attr["content"];
193                                         break;
194                                 case "twitter:title":
195                                         $siteinfo["title"] = $attr["content"];
196                                         break;
197                                 case "dc.title":
198                                         $siteinfo["title"] = $attr["content"];
199                                         break;
200                                 case "dc.description":
201                                         $siteinfo["text"] = $attr["content"];
202                                         break;
203                         }
204                 if ($siteinfo["type"] == "summary")
205                         $siteinfo["type"] = "link";
206         }
207
208         //$list = $xpath->query("head/meta[@property]");
209         $list = $xpath->query("//meta[@property]");
210         foreach ($list as $node) {
211                 $attr = array();
212                 if ($node->attributes->length)
213                         foreach ($node->attributes as $attribute)
214                                 $attr[$attribute->name] = $attribute->value;
215
216                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
217
218                 if ($attr["content"] != "")
219                         switch (strtolower($attr["property"])) {
220                                 case "og:image":
221                                         $siteinfo["image"] = $attr["content"];
222                                         break;
223                                 case "og:title":
224                                         $siteinfo["title"] = $attr["content"];
225                                         break;
226                                 case "og:description":
227                                         $siteinfo["text"] = $attr["content"];
228                                         break;
229                         }
230         }
231
232         if (isset($oembed_data) AND ($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
233                 if (isset($oembed_data->title) AND (trim($oembed_data->title) != ""))
234                         $siteinfo["title"] = $oembed_data->title;
235                 if (isset($oembed_data->description) AND (trim($oembed_data->description) != ""))
236                         $siteinfo["text"] = trim($oembed_data->description);
237                 if (isset($oembed_data->thumbnail_url) AND (trim($oembed_data->thumbnail_url) != ""))
238                         $siteinfo["image"] = $oembed_data->thumbnail_url;
239         }
240
241         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
242             $list = $xpath->query("//img[@src]");
243             foreach ($list as $node) {
244                 $attr = array();
245                 if ($node->attributes->length)
246                     foreach ($node->attributes as $attribute)
247                         $attr[$attribute->name] = $attribute->value;
248
249                         $src = completeurl($attr["src"], $url);
250                         $photodata = @getimagesize($src);
251
252                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
253                                 if ($photodata[0] > 300) {
254                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
255                                         $photodata[0] = 300;
256                                 }
257                                 if ($photodata[1] > 300) {
258                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
259                                         $photodata[1] = 300;
260                                 }
261                                 $siteinfo["images"][] = array("src"=>$src,
262                                                                 "width"=>$photodata[0],
263                                                                 "height"=>$photodata[1]);
264                         }
265
266                 }
267     } else {
268                 $src = completeurl($siteinfo["image"], $url);
269
270                 unset($siteinfo["image"]);
271
272                 $photodata = @getimagesize($src);
273
274                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
275                         $siteinfo["images"][] = array("src"=>$src,
276                                                         "width"=>$photodata[0],
277                                                         "height"=>$photodata[1]);
278         }
279
280         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
281                 $text = "";
282
283                 $list = $xpath->query("//div[@class='article']");
284                 foreach ($list as $node)
285                         if (strlen($node->nodeValue) > 40)
286                                 $text .= " ".trim($node->nodeValue);
287
288                 if ($text == "") {
289                         $list = $xpath->query("//div[@class='content']");
290                         foreach ($list as $node)
291                                 if (strlen($node->nodeValue) > 40)
292                                         $text .= " ".trim($node->nodeValue);
293                 }
294
295                 // If none text was found then take the paragraph content
296                 if ($text == "") {
297                         $list = $xpath->query("//p");
298                         foreach ($list as $node)
299                                 if (strlen($node->nodeValue) > 40)
300                                         $text .= " ".trim($node->nodeValue);
301                 }
302
303                 if ($text != "") {
304                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
305
306                         while (strpos($text, "  "))
307                                 $text = trim(str_replace("  ", " ", $text));
308
309                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
310                 }
311         }
312
313         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
314
315         return($siteinfo);
316 }
317
318 function arr_add_hashes(&$item,$k) {
319         $item = '#' . $item;
320 }
321
322 function parse_url_content(&$a) {
323
324         $text = null;
325         $str_tags = '';
326
327         $textmode = false;
328
329         if(local_user() && (! feature_enabled(local_user(),'richtext')))
330                 $textmode = true;
331
332         //if($textmode)
333         $br = (($textmode) ? "\n" : '<br />');
334
335         if(x($_GET,'binurl'))
336                 $url = trim(hex2bin($_GET['binurl']));
337         else
338                 $url = trim($_GET['url']);
339
340         if($_GET['title'])
341                 $title = strip_tags(trim($_GET['title']));
342
343         if($_GET['description'])
344                 $text = strip_tags(trim($_GET['description']));
345
346         if($_GET['tags']) {
347                 $arr_tags = str_getcsv($_GET['tags']);
348                 if(count($arr_tags)) {
349                         array_walk($arr_tags,'arr_add_hashes');
350                         $str_tags = $br . implode(' ',$arr_tags) . $br;
351                 }
352         }
353
354         logger('parse_url: ' . $url);
355
356         if($textmode)
357                 $template = '[bookmark=%s]%s[/bookmark]%s';
358         else
359                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
360
361         $arr = array('url' => $url, 'text' => '');
362
363         call_hooks('parse_link', $arr);
364
365         if(strlen($arr['text'])) {
366                 echo $arr['text'];
367                 killme();
368         }
369
370
371         if($url && $title && $text) {
372
373                 $title = str_replace(array("\r","\n"),array('',''),$title);
374
375                 if($textmode)
376                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
377                 else {
378                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
379                         $title = htmlspecialchars($title);
380                 }
381
382                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
383
384                 logger('parse_url (unparsed): returns: ' . $result);
385
386                 echo $result;
387                 killme();
388         }
389
390         $siteinfo = parseurl_getsiteinfo($url);
391
392         $url= $siteinfo["url"];
393
394         $sitedata = "";
395
396         if($siteinfo["title"] == "") {
397                 $sitedata .= sprintf($template,$url,$url,'') . $str_tags;
398                 killme();
399         } else {
400                 $text = $siteinfo["text"];
401                 $title = $siteinfo["title"];
402         }
403
404         $image = "";
405
406         if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
407                 /* Execute below code only if image is present in siteinfo */
408
409                 $total_images = 0;
410                 $max_images = get_config('system','max_bookmark_images');
411                 if($max_images === false)
412                         $max_images = 2;
413                 else
414                         $max_images = intval($max_images);
415
416                 foreach ($siteinfo["images"] as $imagedata) {
417                         if($textmode)
418                                 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
419                         else
420                                 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
421                         $total_images ++;
422                         if($max_images && $max_images >= $total_images)
423                                 break;
424                 }
425         }
426
427         if(strlen($text)) {
428                 if($textmode)
429                         $text = '[quote]'.trim($text).'[/quote]';
430                 else
431                         $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
432         }
433
434         if($image)
435                 $text = $br.$br.$image.$text;
436         else
437                 $text = $br.$text;
438
439         $title = str_replace(array("\r","\n"),array('',''),$title);
440
441         $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
442
443         logger('parse_url: returns: ' . $result);
444
445         $sitedata .=  trim($result);
446
447         if (($siteinfo["type"] == "video") AND ($url != ""))
448                 echo "[class=type-video]".$sitedata."[/class]";
449         elseif (($siteinfo["type"] != "photo"))
450                 echo "[class=type-link]".$sitedata."[/class]";
451         else
452                 echo "[class=type-photo]".$title.$br.$image."[/class]";
453
454         killme();
455 }
456 ?>