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