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