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