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