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