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