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