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