]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
parse_url: Removing of warnings with invalid charsets
[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
55         $siteinfo = array();
56
57         if ($count > 10) {
58                 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
59                 return($siteinfo);
60         }
61
62         $url = trim($url, "'");
63         $url = trim($url, '"');
64         $siteinfo["url"] = $url;
65         $siteinfo["type"] = "link";
66
67         $ch = curl_init();
68         curl_setopt($ch, CURLOPT_URL, $url);
69         curl_setopt($ch, CURLOPT_HEADER, 1);
70         curl_setopt($ch, CURLOPT_NOBODY, 0);
71         curl_setopt($ch, CURLOPT_TIMEOUT, 3);
72         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
73         //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
74         //curl_setopt($ch,CURLOPT_USERAGENT,' Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0');
75         curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Friendica)");
76
77         $header = curl_exec($ch);
78         $curl_info = @curl_getinfo($ch);
79         $http_code = $curl_info['http_code'];
80         curl_close($ch);
81
82         if ((($curl_info['http_code'] == "301") OR ($curl_info['http_code'] == "302") OR ($curl_info['http_code'] == "303") OR ($curl_info['http_code'] == "307"))
83                 AND (($curl_info['redirect_url'] != "") OR ($curl_info['location'] != ""))) {
84                 if ($curl_info['redirect_url'] != "")
85                         $siteinfo = parseurl_getsiteinfo($curl_info['redirect_url'], $no_guessing, $do_oembed, ++$count);
86                 else
87                         $siteinfo = parseurl_getsiteinfo($curl_info['location'], $no_guessing, $do_oembed, ++$count);
88                 return($siteinfo);
89         }
90
91         if ($do_oembed) {
92                 require_once("include/oembed.php");
93
94                 $oembed_data = oembed_fetch_url($url);
95
96                 if ($oembed_data->type != "error")
97                         $siteinfo["type"] = $oembed_data->type;
98         }
99
100         // Fetch the first mentioned charset. Can be in body or header
101         $charset = "";
102         if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches))
103                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
104
105         if ($charset == "")
106                 $charset = "utf-8";
107
108         $pos = strpos($header, "\r\n\r\n");
109
110         if ($pos)
111                 $body = trim(substr($header, $pos));
112         else
113                 $body = $header;
114
115         if (($charset != '') AND (strtoupper($charset) != "UTF-8")) {
116                 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
117                 //$body = mb_convert_encoding($body, "UTF-8", $charset);
118                 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
119         }
120
121         $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
122
123         $doc = new DOMDocument();
124         @$doc->loadHTML($body);
125
126         deletenode($doc, 'style');
127         deletenode($doc, 'script');
128         deletenode($doc, 'option');
129         deletenode($doc, 'h1');
130         deletenode($doc, 'h2');
131         deletenode($doc, 'h3');
132         deletenode($doc, 'h4');
133         deletenode($doc, 'h5');
134         deletenode($doc, 'h6');
135         deletenode($doc, 'ol');
136         deletenode($doc, 'ul');
137
138         $xpath = new DomXPath($doc);
139
140         $list = $xpath->query("//meta[@content]");
141         foreach ($list as $node) {
142                 $attr = array();
143                 if ($node->attributes->length)
144                         foreach ($node->attributes as $attribute)
145                                 $attr[$attribute->name] = $attribute->value;
146
147                 if (@$attr["http-equiv"] == 'refresh') {
148                         $path = $attr["content"];
149                         $pathinfo = explode(";", $path);
150                         $content = "";
151                         foreach ($pathinfo AS $value) {
152                                 if (substr(strtolower($value), 0, 4) == "url=")
153                                         $content = substr($value, 4);
154                         }
155                         if ($content != "") {
156                                 $siteinfo = parseurl_getsiteinfo($content, $no_guessing, $do_oembed, ++$count);
157                                 return($siteinfo);
158                         }
159                 }
160         }
161
162         //$list = $xpath->query("head/title");
163         $list = $xpath->query("//title");
164         foreach ($list as $node)
165                 $siteinfo["title"] =  html_entity_decode($node->nodeValue, ENT_QUOTES, "UTF-8");
166
167         //$list = $xpath->query("head/meta[@name]");
168         $list = $xpath->query("//meta[@name]");
169         foreach ($list as $node) {
170                 $attr = array();
171                 if ($node->attributes->length)
172                         foreach ($node->attributes as $attribute)
173                                 $attr[$attribute->name] = $attribute->value;
174
175                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
176
177                 if ($attr["content"] != "")
178                         switch (strtolower($attr["name"])) {
179                                 case "fulltitle":
180                                         $siteinfo["title"] = $attr["content"];
181                                         break;
182                                 case "description":
183                                         $siteinfo["text"] = $attr["content"];
184                                         break;
185                                 case "twitter:image":
186                                         $siteinfo["image"] = $attr["content"];
187                                         break;
188                                 case "twitter:card":
189                                         if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
190                                                 $siteinfo["type"] = $attr["content"];
191                                         break;
192                                 case "twitter:description":
193                                         $siteinfo["text"] = $attr["content"];
194                                         break;
195                                 case "twitter:title":
196                                         $siteinfo["title"] = $attr["content"];
197                                         break;
198                                 case "dc.title":
199                                         $siteinfo["title"] = $attr["content"];
200                                         break;
201                                 case "dc.description":
202                                         $siteinfo["text"] = $attr["content"];
203                                         break;
204                         }
205                 if ($siteinfo["type"] == "summary")
206                         $siteinfo["type"] = "link";
207         }
208
209         //$list = $xpath->query("head/meta[@property]");
210         $list = $xpath->query("//meta[@property]");
211         foreach ($list as $node) {
212                 $attr = array();
213                 if ($node->attributes->length)
214                         foreach ($node->attributes as $attribute)
215                                 $attr[$attribute->name] = $attribute->value;
216
217                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
218
219                 if ($attr["content"] != "")
220                         switch (strtolower($attr["property"])) {
221                                 case "og:image":
222                                         $siteinfo["image"] = $attr["content"];
223                                         break;
224                                 case "og:title":
225                                         $siteinfo["title"] = $attr["content"];
226                                         break;
227                                 case "og:description":
228                                         $siteinfo["text"] = $attr["content"];
229                                         break;
230                         }
231         }
232
233         if (isset($oembed_data) AND ($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
234                 if (isset($oembed_data->title) AND (trim($oembed_data->title) != ""))
235                         $siteinfo["title"] = $oembed_data->title;
236                 if (isset($oembed_data->description) AND (trim($oembed_data->description) != ""))
237                         $siteinfo["text"] = trim($oembed_data->description);
238                 if (isset($oembed_data->thumbnail_url) AND (trim($oembed_data->thumbnail_url) != ""))
239                         $siteinfo["image"] = $oembed_data->thumbnail_url;
240         }
241
242         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
243             $list = $xpath->query("//img[@src]");
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                         $src = completeurl($attr["src"], $url);
251                         $photodata = @getimagesize($src);
252
253                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
254                                 if ($photodata[0] > 300) {
255                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
256                                         $photodata[0] = 300;
257                                 }
258                                 if ($photodata[1] > 300) {
259                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
260                                         $photodata[1] = 300;
261                                 }
262                                 $siteinfo["images"][] = array("src"=>$src,
263                                                                 "width"=>$photodata[0],
264                                                                 "height"=>$photodata[1]);
265                         }
266
267                 }
268     } else {
269                 $src = completeurl($siteinfo["image"], $url);
270
271                 unset($siteinfo["image"]);
272
273                 $photodata = @getimagesize($src);
274
275                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
276                         $siteinfo["images"][] = array("src"=>$src,
277                                                         "width"=>$photodata[0],
278                                                         "height"=>$photodata[1]);
279         }
280
281         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
282                 $text = "";
283
284                 $list = $xpath->query("//div[@class='article']");
285                 foreach ($list as $node)
286                         if (strlen($node->nodeValue) > 40)
287                                 $text .= " ".trim($node->nodeValue);
288
289                 if ($text == "") {
290                         $list = $xpath->query("//div[@class='content']");
291                         foreach ($list as $node)
292                                 if (strlen($node->nodeValue) > 40)
293                                         $text .= " ".trim($node->nodeValue);
294                 }
295
296                 // If none text was found then take the paragraph content
297                 if ($text == "") {
298                         $list = $xpath->query("//p");
299                         foreach ($list as $node)
300                                 if (strlen($node->nodeValue) > 40)
301                                         $text .= " ".trim($node->nodeValue);
302                 }
303
304                 if ($text != "") {
305                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
306
307                         while (strpos($text, "  "))
308                                 $text = trim(str_replace("  ", " ", $text));
309
310                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
311                 }
312         }
313
314         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
315
316         return($siteinfo);
317 }
318
319 function arr_add_hashes(&$item,$k) {
320         $item = '#' . $item;
321 }
322
323 function parse_url_content(&$a) {
324
325         $text = null;
326         $str_tags = '';
327
328         $textmode = false;
329
330         if(local_user() && (! feature_enabled(local_user(),'richtext')))
331                 $textmode = true;
332
333         //if($textmode)
334         $br = (($textmode) ? "\n" : '<br />');
335
336         if(x($_GET,'binurl'))
337                 $url = trim(hex2bin($_GET['binurl']));
338         else
339                 $url = trim($_GET['url']);
340
341         if($_GET['title'])
342                 $title = strip_tags(trim($_GET['title']));
343
344         if($_GET['description'])
345                 $text = strip_tags(trim($_GET['description']));
346
347         if($_GET['tags']) {
348                 $arr_tags = str_getcsv($_GET['tags']);
349                 if(count($arr_tags)) {
350                         array_walk($arr_tags,'arr_add_hashes');
351                         $str_tags = $br . implode(' ',$arr_tags) . $br;
352                 }
353         }
354
355         logger('parse_url: ' . $url);
356
357         if($textmode)
358                 $template = '[bookmark=%s]%s[/bookmark]%s';
359         else
360                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
361
362         $arr = array('url' => $url, 'text' => '');
363
364         call_hooks('parse_link', $arr);
365
366         if(strlen($arr['text'])) {
367                 echo $arr['text'];
368                 killme();
369         }
370
371
372         if($url && $title && $text) {
373
374                 $title = str_replace(array("\r","\n"),array('',''),$title);
375
376                 if($textmode)
377                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
378                 else {
379                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
380                         $title = htmlspecialchars($title);
381                 }
382
383                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
384
385                 logger('parse_url (unparsed): returns: ' . $result);
386
387                 echo $result;
388                 killme();
389         }
390
391         $siteinfo = parseurl_getsiteinfo($url);
392
393         $url= $siteinfo["url"];
394
395         $sitedata = "";
396
397         if($siteinfo["title"] == "") {
398                 $sitedata .= sprintf($template,$url,$url,'') . $str_tags;
399                 killme();
400         } else {
401                 $text = $siteinfo["text"];
402                 $title = $siteinfo["title"];
403         }
404
405         $image = "";
406
407         if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
408                 /* Execute below code only if image is present in siteinfo */
409
410                 $total_images = 0;
411                 $max_images = get_config('system','max_bookmark_images');
412                 if($max_images === false)
413                         $max_images = 2;
414                 else
415                         $max_images = intval($max_images);
416
417                 foreach ($siteinfo["images"] as $imagedata) {
418                         if($textmode)
419                                 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
420                         else
421                                 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
422                         $total_images ++;
423                         if($max_images && $max_images >= $total_images)
424                                 break;
425                 }
426         }
427
428         if(strlen($text)) {
429                 if($textmode)
430                         $text = '[quote]'.trim($text).'[/quote]';
431                 else
432                         $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
433         }
434
435         if($image)
436                 $text = $br.$br.$image.$text;
437         else
438                 $text = $br.$text;
439
440         $title = str_replace(array("\r","\n"),array('',''),$title);
441
442         $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
443
444         logger('parse_url: returns: ' . $result);
445
446         $sitedata .=  trim($result);
447
448         if (($siteinfo["type"] == "video") AND ($url != ""))
449                 echo "[class=type-video]".$sitedata."[/class]";
450         elseif (($siteinfo["type"] != "photo"))
451                 echo "[class=type-link]".$sitedata."[/class]";
452         else
453                 echo "[class=type-photo]".$title.$br.$image."[/class]";
454
455         killme();
456 }
457 ?>