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