]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
481cb89361b6f70be3b104891f923af8661499ef
[friendica.git] / mod / parse_url.php
1 <?php
2 /**
3  * @file mod/parse_url.php
4  *
5  * @todo https://developers.google.com/+/plugins/snippet/
6  *
7  * @verbatim
8  * <meta itemprop="name" content="Toller Titel">
9  * <meta itemprop="description" content="Eine tolle Beschreibung">
10  * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
11  *
12  * <body itemscope itemtype="http://schema.org/Product">
13  *   <h1 itemprop="name">Shiny Trinket</h1>
14  *   <img itemprop="image" src="{image-url}" />
15  *   <p itemprop="description">Shiny trinkets are shiny.</p>
16  * </body>
17  * @endverbatim
18 */
19
20 if(!function_exists('deletenode')) {
21         function deletenode(&$doc, $node)
22         {
23                 $xpath = new DomXPath($doc);
24                 $list = $xpath->query("//".$node);
25                 foreach ($list as $child)
26                         $child->parentNode->removeChild($child);
27         }
28 }
29
30 if(! function_exists('completeurl')) {
31 function completeurl($url, $scheme) {
32         $urlarr = parse_url($url);
33
34         if (isset($urlarr["scheme"]))
35                 return($url);
36
37         $schemearr = parse_url($scheme);
38
39         $complete = $schemearr["scheme"]."://".$schemearr["host"];
40
41         if (@$schemearr["port"] != "")
42                 $complete .= ":".$schemearr["port"];
43
44                 if(strpos($urlarr['path'],'/') !== 0)
45                         $complete .= '/';
46
47         $complete .= $urlarr["path"];
48
49         if (@$urlarr["query"] != "")
50                 $complete .= "?".$urlarr["query"];
51
52         if (@$urlarr["fragment"] != "")
53                 $complete .= "#".$urlarr["fragment"];
54
55         return($complete);
56 }
57 }
58
59 if(! function_exists('parseurl_getsiteinfo_cached')) {
60 function parseurl_getsiteinfo_cached($url, $no_guessing = false, $do_oembed = true) {
61
62         if ($url == "")
63                 return false;
64
65         $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
66                 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
67
68         if ($r)
69                 $data = $r[0]["content"];
70
71         if (!is_null($data)) {
72                 $data = unserialize($data);
73                 return $data;
74         }
75
76         $data = parseurl_getsiteinfo($url, $no_guessing, $do_oembed);
77
78         q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')",
79                 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed), dbesc(serialize($data)), dbesc(datetime_convert()));
80
81         return $data;
82 }
83 }
84
85 if(! function_exists('parseurl_getsiteinfo')) {
86 function parseurl_getsiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
87         require_once("include/network.php");
88         require_once("include/Photo.php");
89
90         $a = get_app();
91
92         $siteinfo = array();
93
94         if ($count > 10) {
95                 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
96                 return($siteinfo);
97         }
98
99         $url = trim($url, "'");
100         $url = trim($url, '"');
101
102         $url = original_url($url);
103
104         $siteinfo["url"] = $url;
105         $siteinfo["type"] = "link";
106
107         $stamp1 = microtime(true);
108
109         $ch = curl_init();
110         curl_setopt($ch, CURLOPT_URL, $url);
111         curl_setopt($ch, CURLOPT_HEADER, 1);
112         curl_setopt($ch, CURLOPT_NOBODY, 1);
113         curl_setopt($ch, CURLOPT_TIMEOUT, 3);
114         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
115         //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
116         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
117
118         $header = curl_exec($ch);
119         $curl_info = @curl_getinfo($ch);
120         $http_code = $curl_info['http_code'];
121         curl_close($ch);
122
123         $a->save_timestamp($stamp1, "network");
124
125         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
126                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
127                 if ($curl_info['redirect_url'] != "")
128                         $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
129                 else
130                         $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
131                 return($siteinfo);
132         }
133
134         // if the file is too large then exit
135         if ($curl_info["download_content_length"] > 1000000)
136                 return($siteinfo);
137
138         // if it isn't a HTML file then exit
139         if (($curl_info["content_type"] != "") AND !strstr(strtolower($curl_info["content_type"]),"html"))
140                 return($siteinfo);
141
142         if ($do_oembed) {
143                 require_once("include/oembed.php");
144
145                 $oembed_data = oembed_fetch_url($url);
146
147                 if ($oembed_data->type != "error")
148                         $siteinfo["type"] = $oembed_data->type;
149
150                 if (($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
151                         if (isset($oembed_data->title))
152                                 $siteinfo["title"] = $oembed_data->title;
153                         if (isset($oembed_data->description))
154                                 $siteinfo["text"] = trim($oembed_data->description);
155                         if (isset($oembed_data->thumbnail_url))
156                                 $siteinfo["image"] = $oembed_data->thumbnail_url;
157                 }
158         }
159
160         $stamp1 = microtime(true);
161
162         // Now fetch the body as well
163         $ch = curl_init();
164         curl_setopt($ch, CURLOPT_URL, $url);
165         curl_setopt($ch, CURLOPT_HEADER, 1);
166         curl_setopt($ch, CURLOPT_NOBODY, 0);
167         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
168         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
169         curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
170
171         $header = curl_exec($ch);
172         $curl_info = @curl_getinfo($ch);
173         $http_code = $curl_info['http_code'];
174         curl_close($ch);
175
176         $a->save_timestamp($stamp1, "network");
177
178         // Fetch the first mentioned charset. Can be in body or header
179         $charset = "";
180         if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
181                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
182
183         if ($charset == "")
184                 $charset = "utf-8";
185
186         $pos = strpos($header, "\r\n\r\n");
187
188         if ($pos)
189                 $body = trim(substr($header, $pos));
190         else
191                 $body = $header;
192
193         if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
194                 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
195                 //$body = mb_convert_encoding($body, "UTF-8", $charset);
196                 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
197         }
198
199         $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
200
201         $doc = new DOMDocument();
202         @$doc->loadHTML($body);
203
204         deletenode($doc, 'style');
205         deletenode($doc, 'script');
206         deletenode($doc, 'option');
207         deletenode($doc, 'h1');
208         deletenode($doc, 'h2');
209         deletenode($doc, 'h3');
210         deletenode($doc, 'h4');
211         deletenode($doc, 'h5');
212         deletenode($doc, 'h6');
213         deletenode($doc, 'ol');
214         deletenode($doc, 'ul');
215
216         $xpath = new DomXPath($doc);
217
218         $list = $xpath->query("//meta[@content]");
219         foreach ($list as $node) {
220                 $attr = array();
221                 if ($node->attributes->length)
222                         foreach ($node->attributes as $attribute)
223                                 $attr[$attribute->name] = $attribute->value;
224
225                 if (@$attr["http-equiv"] == 'refresh') {
226                         $path = $attr["content"];
227                         $pathinfo = explode(";", $path);
228                         $content = "";
229                         foreach ($pathinfo AS $value) {
230                                 if (substr(strtolower($value), 0, 4) == "url=")
231                                         $content = substr($value, 4);
232                         }
233                         if ($content != "") {
234                                 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
235                                 return($siteinfo);
236                         }
237                 }
238         }
239
240         //$list = $xpath->query("head/title");
241         $list = $xpath->query("//title");
242         foreach ($list as $node)
243                 $siteinfo["title"] =  html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
244
245         //$list = $xpath->query("head/meta[@name]");
246         $list = $xpath->query("//meta[@name]");
247         foreach ($list as $node) {
248                 $attr = array();
249                 if ($node->attributes->length)
250                         foreach ($node->attributes as $attribute)
251                                 $attr[$attribute->name] = $attribute->value;
252
253                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
254
255                 if ($attr["content"] != "")
256                         switch (strtolower($attr["name"])) {
257                                 case "fulltitle":
258                                         $siteinfo["title"] = $attr["content"];
259                                         break;
260                                 case "description":
261                                         $siteinfo["text"] = $attr["content"];
262                                         break;
263                                 case "thumbnail":
264                                         $siteinfo["image"] = $attr["content"];
265                                         break;
266                                 case "twitter:image":
267                                         $siteinfo["image"] = $attr["content"];
268                                         break;
269                                 case "twitter:image:src":
270                                         $siteinfo["image"] = $attr["content"];
271                                         break;
272                                 case "twitter:card":
273                                         if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
274                                                 $siteinfo["type"] = $attr["content"];
275                                         break;
276                                 case "twitter:description":
277                                         $siteinfo["text"] = $attr["content"];
278                                         break;
279                                 case "twitter:title":
280                                         $siteinfo["title"] = $attr["content"];
281                                         break;
282                                 case "dc.title":
283                                         $siteinfo["title"] = $attr["content"];
284                                         break;
285                                 case "dc.description":
286                                         $siteinfo["text"] = $attr["content"];
287                                         break;
288                                 case "keywords":
289                                         $keywords = explode(",", $attr["content"]);
290                                         break;
291                                 case "news_keywords":
292                                         $keywords = explode(",", $attr["content"]);
293                                         break;
294                         }
295                 if ($siteinfo["type"] == "summary")
296                         $siteinfo["type"] = "link";
297         }
298
299         if (isset($keywords)) {
300                 $siteinfo["keywords"] = array();
301                 foreach ($keywords as $keyword)
302                         if (!in_array(trim($keyword), $siteinfo["keywords"]))
303                                 $siteinfo["keywords"][] = trim($keyword);
304         }
305
306         //$list = $xpath->query("head/meta[@property]");
307         $list = $xpath->query("//meta[@property]");
308         foreach ($list as $node) {
309                 $attr = array();
310                 if ($node->attributes->length)
311                         foreach ($node->attributes as $attribute)
312                                 $attr[$attribute->name] = $attribute->value;
313
314                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
315
316                 if ($attr["content"] != "")
317                         switch (strtolower($attr["property"])) {
318                                 case "og:image":
319                                         $siteinfo["image"] = $attr["content"];
320                                         break;
321                                 case "og:title":
322                                         $siteinfo["title"] = $attr["content"];
323                                         break;
324                                 case "og:description":
325                                         $siteinfo["text"] = $attr["content"];
326                                         break;
327                         }
328         }
329
330         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
331             $list = $xpath->query("//img[@src]");
332             foreach ($list as $node) {
333                 $attr = array();
334                 if ($node->attributes->length)
335                     foreach ($node->attributes as $attribute)
336                         $attr[$attribute->name] = $attribute->value;
337
338                         $src = completeurl($attr["src"], $url);
339                         $photodata = get_photo_info($src);
340
341                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
342                                 if ($photodata[0] > 300) {
343                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
344                                         $photodata[0] = 300;
345                                 }
346                                 if ($photodata[1] > 300) {
347                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
348                                         $photodata[1] = 300;
349                                 }
350                                 $siteinfo["images"][] = array("src"=>$src,
351                                                                 "width"=>$photodata[0],
352                                                                 "height"=>$photodata[1]);
353                         }
354
355                 }
356     } elseif ($siteinfo["image"] != "") {
357                 $src = completeurl($siteinfo["image"], $url);
358
359                 unset($siteinfo["image"]);
360
361                 $photodata = get_photo_info($src);
362
363                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
364                         $siteinfo["images"][] = array("src"=>$src,
365                                                         "width"=>$photodata[0],
366                                                         "height"=>$photodata[1]);
367         }
368
369         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
370                 $text = "";
371
372                 $list = $xpath->query("//div[@class='article']");
373                 foreach ($list as $node)
374                         if (strlen($node->nodeValue) > 40)
375                                 $text .= " ".trim($node->nodeValue);
376
377                 if ($text == "") {
378                         $list = $xpath->query("//div[@class='content']");
379                         foreach ($list as $node)
380                                 if (strlen($node->nodeValue) > 40)
381                                         $text .= " ".trim($node->nodeValue);
382                 }
383
384                 // If none text was found then take the paragraph content
385                 if ($text == "") {
386                         $list = $xpath->query("//p");
387                         foreach ($list as $node)
388                                 if (strlen($node->nodeValue) > 40)
389                                         $text .= " ".trim($node->nodeValue);
390                 }
391
392                 if ($text != "") {
393                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
394
395                         while (strpos($text, "  "))
396                                 $text = trim(str_replace("  ", " ", $text));
397
398                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
399                 }
400         }
401
402         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
403
404         call_hooks('getsiteinfo', $siteinfo);
405
406         return($siteinfo);
407 }
408 }
409
410 if(! function_exists('arr_add_hashes')) {
411 function arr_add_hashes(&$item,$k) {
412         $item = '#' . $item;
413 }
414 }
415
416 if(! function_exists('parse_url_content')) {
417 function parse_url_content(&$a) {
418
419         $text = null;
420         $str_tags = '';
421
422         $textmode = false;
423
424         if(local_user() && (! feature_enabled(local_user(),'richtext')))
425                 $textmode = true;
426
427         //if($textmode)
428         $br = (($textmode) ? "\n" : '<br />');
429
430         if(x($_GET,'binurl'))
431                 $url = trim(hex2bin($_GET['binurl']));
432         else
433                 $url = trim($_GET['url']);
434
435         if($_GET['title'])
436                 $title = strip_tags(trim($_GET['title']));
437
438         if($_GET['description'])
439                 $text = strip_tags(trim($_GET['description']));
440
441         if($_GET['tags']) {
442                 $arr_tags = str_getcsv($_GET['tags']);
443                 if(count($arr_tags)) {
444                         array_walk($arr_tags,'arr_add_hashes');
445                         $str_tags = $br . implode(' ',$arr_tags) . $br;
446                 }
447         }
448
449         // add url scheme if missing
450         $arrurl = parse_url($url);
451         if (!x($arrurl, 'scheme')) {
452                 if (x($arrurl, 'host'))
453                         $url = "http:".$url;
454                 else
455                         $url = "http://".$url;
456         }
457
458         logger('parse_url: ' . $url);
459
460         if($textmode)
461                 $template = '[bookmark=%s]%s[/bookmark]%s';
462         else
463                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
464
465         $arr = array('url' => $url, 'text' => '');
466
467         call_hooks('parse_link', $arr);
468
469         if(strlen($arr['text'])) {
470                 echo $arr['text'];
471                 killme();
472         }
473
474
475         if($url && $title && $text) {
476
477                 $title = str_replace(array("\r","\n"),array('',''),$title);
478
479                 if($textmode)
480                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
481                 else {
482                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
483                         $title = htmlspecialchars($title);
484                 }
485
486                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
487
488                 logger('parse_url (unparsed): returns: ' . $result);
489
490                 echo $result;
491                 killme();
492         }
493
494         $siteinfo = parseurl_getsiteinfo($url);
495
496 //      if ($textmode) {
497 //              require_once("include/items.php");
498 //
499 //              echo add_page_info_data($siteinfo);
500 //              killme();
501 //      }
502
503         $url= $siteinfo["url"];
504
505         // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
506         if (strpos($url, '[') OR strpos($url, ']')) {
507                 require_once("include/network.php");
508                 $url = short_link($url);
509         }
510
511         $sitedata = "";
512
513         if($siteinfo["title"] != "") {
514                 $text = $siteinfo["text"];
515                 $title = $siteinfo["title"];
516         }
517
518         $image = "";
519
520         if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
521                 /* Execute below code only if image is present in siteinfo */
522
523                 $total_images = 0;
524                 $max_images = get_config('system','max_bookmark_images');
525                 if($max_images === false)
526                         $max_images = 2;
527                 else
528                         $max_images = intval($max_images);
529
530                 foreach ($siteinfo["images"] as $imagedata) {
531                         if($textmode)
532                                 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
533                         else
534                                 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
535                         $total_images ++;
536                         if($max_images && $max_images >= $total_images)
537                                 break;
538                 }
539         }
540
541         if(strlen($text)) {
542                 if($textmode)
543                         $text = '[quote]'.trim($text).'[/quote]';
544                 else
545                         $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
546         }
547
548         if($image)
549                 $text = $br.$br.$image.$text;
550         else
551                 $text = $br.$text;
552
553         $title = str_replace(array("\r","\n"),array('',''),$title);
554
555         $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
556
557         logger('parse_url: returns: ' . $result);
558
559         $sitedata .=  trim($result);
560
561         if (($siteinfo["type"] == "video") AND ($url != ""))
562                 echo "[class=type-video]".$sitedata."[/class]";
563         elseif (($siteinfo["type"] != "photo"))
564                 echo "[class=type-link]".$sitedata."[/class]";
565         else
566                 echo "[class=type-photo]".$title.$br.$image."[/class]";
567
568         killme();
569 }
570 }
571 ?>