]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
new version of the ShaShape iconset
[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                         $siteinfo["keywords"][] = trim($keyword);
284         }
285
286         //$list = $xpath->query("head/meta[@property]");
287         $list = $xpath->query("//meta[@property]");
288         foreach ($list as $node) {
289                 $attr = array();
290                 if ($node->attributes->length)
291                         foreach ($node->attributes as $attribute)
292                                 $attr[$attribute->name] = $attribute->value;
293
294                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
295
296                 if ($attr["content"] != "")
297                         switch (strtolower($attr["property"])) {
298                                 case "og:image":
299                                         $siteinfo["image"] = $attr["content"];
300                                         break;
301                                 case "og:title":
302                                         $siteinfo["title"] = $attr["content"];
303                                         break;
304                                 case "og:description":
305                                         $siteinfo["text"] = $attr["content"];
306                                         break;
307                         }
308         }
309
310         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
311             $list = $xpath->query("//img[@src]");
312             foreach ($list as $node) {
313                 $attr = array();
314                 if ($node->attributes->length)
315                     foreach ($node->attributes as $attribute)
316                         $attr[$attribute->name] = $attribute->value;
317
318                         $src = completeurl($attr["src"], $url);
319                         $photodata = @getimagesize($src);
320
321                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
322                                 if ($photodata[0] > 300) {
323                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
324                                         $photodata[0] = 300;
325                                 }
326                                 if ($photodata[1] > 300) {
327                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
328                                         $photodata[1] = 300;
329                                 }
330                                 $siteinfo["images"][] = array("src"=>$src,
331                                                                 "width"=>$photodata[0],
332                                                                 "height"=>$photodata[1]);
333                         }
334
335                 }
336     } else {
337                 $src = completeurl($siteinfo["image"], $url);
338
339                 unset($siteinfo["image"]);
340
341                 $photodata = @getimagesize($src);
342
343                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
344                         $siteinfo["images"][] = array("src"=>$src,
345                                                         "width"=>$photodata[0],
346                                                         "height"=>$photodata[1]);
347         }
348
349         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
350                 $text = "";
351
352                 $list = $xpath->query("//div[@class='article']");
353                 foreach ($list as $node)
354                         if (strlen($node->nodeValue) > 40)
355                                 $text .= " ".trim($node->nodeValue);
356
357                 if ($text == "") {
358                         $list = $xpath->query("//div[@class='content']");
359                         foreach ($list as $node)
360                                 if (strlen($node->nodeValue) > 40)
361                                         $text .= " ".trim($node->nodeValue);
362                 }
363
364                 // If none text was found then take the paragraph content
365                 if ($text == "") {
366                         $list = $xpath->query("//p");
367                         foreach ($list as $node)
368                                 if (strlen($node->nodeValue) > 40)
369                                         $text .= " ".trim($node->nodeValue);
370                 }
371
372                 if ($text != "") {
373                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
374
375                         while (strpos($text, "  "))
376                                 $text = trim(str_replace("  ", " ", $text));
377
378                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
379                 }
380         }
381
382         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
383
384         call_hooks('getsiteinfo', $siteinfo);
385
386         return($siteinfo);
387 }
388
389 function arr_add_hashes(&$item,$k) {
390         $item = '#' . $item;
391 }
392
393 function parse_url_content(&$a) {
394
395         $text = null;
396         $str_tags = '';
397
398         $textmode = false;
399
400         if(local_user() && (! feature_enabled(local_user(),'richtext')))
401                 $textmode = true;
402
403         //if($textmode)
404         $br = (($textmode) ? "\n" : '<br />');
405
406         if(x($_GET,'binurl'))
407                 $url = trim(hex2bin($_GET['binurl']));
408         else
409                 $url = trim($_GET['url']);
410
411         if($_GET['title'])
412                 $title = strip_tags(trim($_GET['title']));
413
414         if($_GET['description'])
415                 $text = strip_tags(trim($_GET['description']));
416
417         if($_GET['tags']) {
418                 $arr_tags = str_getcsv($_GET['tags']);
419                 if(count($arr_tags)) {
420                         array_walk($arr_tags,'arr_add_hashes');
421                         $str_tags = $br . implode(' ',$arr_tags) . $br;
422                 }
423         }
424
425         // add url scheme if missing
426         $arrurl = parse_url($url);
427         if (!x($arrurl, 'scheme')) {
428                 if (x($arrurl, 'host'))
429                         $url = "http:".$url;
430                 else
431                         $url = "http://".$url;
432         }
433
434         logger('parse_url: ' . $url);
435
436         if($textmode)
437                 $template = '[bookmark=%s]%s[/bookmark]%s';
438         else
439                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
440
441         $arr = array('url' => $url, 'text' => '');
442
443         call_hooks('parse_link', $arr);
444
445         if(strlen($arr['text'])) {
446                 echo $arr['text'];
447                 killme();
448         }
449
450
451         if($url && $title && $text) {
452
453                 $title = str_replace(array("\r","\n"),array('',''),$title);
454
455                 if($textmode)
456                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
457                 else {
458                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
459                         $title = htmlspecialchars($title);
460                 }
461
462                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
463
464                 logger('parse_url (unparsed): returns: ' . $result);
465
466                 echo $result;
467                 killme();
468         }
469
470         $siteinfo = parseurl_getsiteinfo($url);
471
472 //      if ($textmode) {
473 //              require_once("include/items.php");
474 //
475 //              echo add_page_info_data($siteinfo);
476 //              killme();
477 //      }
478
479         $url= $siteinfo["url"];
480
481         // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
482         if (strpos($url, '[') OR strpos($url, ']')) {
483                 require_once("include/network.php");
484                 $url = short_link($url);
485         }
486
487         $sitedata = "";
488
489         if($siteinfo["title"] != "") {
490                 $text = $siteinfo["text"];
491                 $title = $siteinfo["title"];
492         }
493
494         $image = "";
495
496         if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
497                 /* Execute below code only if image is present in siteinfo */
498
499                 $total_images = 0;
500                 $max_images = get_config('system','max_bookmark_images');
501                 if($max_images === false)
502                         $max_images = 2;
503                 else
504                         $max_images = intval($max_images);
505
506                 foreach ($siteinfo["images"] as $imagedata) {
507                         if($textmode)
508                                 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
509                         else
510                                 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
511                         $total_images ++;
512                         if($max_images && $max_images >= $total_images)
513                                 break;
514                 }
515         }
516
517         if(strlen($text)) {
518                 if($textmode)
519                         $text = '[quote]'.trim($text).'[/quote]';
520                 else
521                         $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
522         }
523
524         if($image)
525                 $text = $br.$br.$image.$text;
526         else
527                 $text = $br.$text;
528
529         $title = str_replace(array("\r","\n"),array('',''),$title);
530
531         $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
532
533         logger('parse_url: returns: ' . $result);
534
535         $sitedata .=  trim($result);
536
537         if (($siteinfo["type"] == "video") AND ($url != ""))
538                 echo "[class=type-video]".$sitedata."[/class]";
539         elseif (($siteinfo["type"] != "photo"))
540                 echo "[class=type-link]".$sitedata."[/class]";
541         else
542                 echo "[class=type-photo]".$title.$br.$image."[/class]";
543
544         killme();
545 }
546 ?>