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