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