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