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