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