]> git.mxchange.org Git - friendica.git/blob - mod/parse_url.php
Merge branch 'release-3.3.2'
[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 "thumbnail":
191                                         $siteinfo["image"] = $attr["content"];
192                                         break;
193                                 case "twitter:image":
194                                         $siteinfo["image"] = $attr["content"];
195                                         break;
196                                 case "twitter:image:src":
197                                         $siteinfo["image"] = $attr["content"];
198                                         break;
199                                 case "twitter:card":
200                                         if (($siteinfo["type"] == "") OR ($attr["content"] == "photo"))
201                                                 $siteinfo["type"] = $attr["content"];
202                                         break;
203                                 case "twitter:description":
204                                         $siteinfo["text"] = $attr["content"];
205                                         break;
206                                 case "twitter:title":
207                                         $siteinfo["title"] = $attr["content"];
208                                         break;
209                                 case "dc.title":
210                                         $siteinfo["title"] = $attr["content"];
211                                         break;
212                                 case "dc.description":
213                                         $siteinfo["text"] = $attr["content"];
214                                         break;
215                                 case "keywords":
216                                         $keywords = explode(",", $attr["content"]);
217                                         break;
218                                 case "news_keywords":
219                                         $keywords = explode(",", $attr["content"]);
220                                         break;
221                         }
222                 if ($siteinfo["type"] == "summary")
223                         $siteinfo["type"] = "link";
224         }
225
226         if (isset($keywords)) {
227                 $siteinfo["keywords"] = array();
228                 foreach ($keywords as $keyword)
229                         $siteinfo["keywords"][] = trim($keyword);
230         }
231
232         //$list = $xpath->query("head/meta[@property]");
233         $list = $xpath->query("//meta[@property]");
234         foreach ($list as $node) {
235                 $attr = array();
236                 if ($node->attributes->length)
237                         foreach ($node->attributes as $attribute)
238                                 $attr[$attribute->name] = $attribute->value;
239
240                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
241
242                 if ($attr["content"] != "")
243                         switch (strtolower($attr["property"])) {
244                                 case "og:image":
245                                         $siteinfo["image"] = $attr["content"];
246                                         break;
247                                 case "og:title":
248                                         $siteinfo["title"] = $attr["content"];
249                                         break;
250                                 case "og:description":
251                                         $siteinfo["text"] = $attr["content"];
252                                         break;
253                         }
254         }
255
256         if (isset($oembed_data) AND ($oembed_data->type == "link") AND ($siteinfo["type"] != "photo")) {
257                 if (isset($oembed_data->title) AND (trim($oembed_data->title) != ""))
258                         $siteinfo["title"] = $oembed_data->title;
259                 if (isset($oembed_data->description) AND (trim($oembed_data->description) != ""))
260                         $siteinfo["text"] = trim($oembed_data->description);
261                 if (isset($oembed_data->thumbnail_url) AND (trim($oembed_data->thumbnail_url) != ""))
262                         $siteinfo["image"] = $oembed_data->thumbnail_url;
263         }
264
265         if ((@$siteinfo["image"] == "") AND !$no_guessing) {
266             $list = $xpath->query("//img[@src]");
267             foreach ($list as $node) {
268                 $attr = array();
269                 if ($node->attributes->length)
270                     foreach ($node->attributes as $attribute)
271                         $attr[$attribute->name] = $attribute->value;
272
273                         $src = completeurl($attr["src"], $url);
274                         $photodata = @getimagesize($src);
275
276                         if (($photodata) && ($photodata[0] > 150) and ($photodata[1] > 150)) {
277                                 if ($photodata[0] > 300) {
278                                         $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
279                                         $photodata[0] = 300;
280                                 }
281                                 if ($photodata[1] > 300) {
282                                         $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
283                                         $photodata[1] = 300;
284                                 }
285                                 $siteinfo["images"][] = array("src"=>$src,
286                                                                 "width"=>$photodata[0],
287                                                                 "height"=>$photodata[1]);
288                         }
289
290                 }
291     } else {
292                 $src = completeurl($siteinfo["image"], $url);
293
294                 unset($siteinfo["image"]);
295
296                 $photodata = @getimagesize($src);
297
298                 if (($photodata) && ($photodata[0] > 10) and ($photodata[1] > 10))
299                         $siteinfo["images"][] = array("src"=>$src,
300                                                         "width"=>$photodata[0],
301                                                         "height"=>$photodata[1]);
302         }
303
304         if ((@$siteinfo["text"] == "") AND (@$siteinfo["title"] != "") AND !$no_guessing) {
305                 $text = "";
306
307                 $list = $xpath->query("//div[@class='article']");
308                 foreach ($list as $node)
309                         if (strlen($node->nodeValue) > 40)
310                                 $text .= " ".trim($node->nodeValue);
311
312                 if ($text == "") {
313                         $list = $xpath->query("//div[@class='content']");
314                         foreach ($list as $node)
315                                 if (strlen($node->nodeValue) > 40)
316                                         $text .= " ".trim($node->nodeValue);
317                 }
318
319                 // If none text was found then take the paragraph content
320                 if ($text == "") {
321                         $list = $xpath->query("//p");
322                         foreach ($list as $node)
323                                 if (strlen($node->nodeValue) > 40)
324                                         $text .= " ".trim($node->nodeValue);
325                 }
326
327                 if ($text != "") {
328                         $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
329
330                         while (strpos($text, "  "))
331                                 $text = trim(str_replace("  ", " ", $text));
332
333                         $siteinfo["text"] = trim(html_entity_decode(substr($text,0,350), ENT_QUOTES, "UTF-8").'...');
334                 }
335         }
336
337         logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
338
339         call_hooks('getsiteinfo', $siteinfo);
340
341         return($siteinfo);
342 }
343
344 function arr_add_hashes(&$item,$k) {
345         $item = '#' . $item;
346 }
347
348 function parse_url_content(&$a) {
349
350         $text = null;
351         $str_tags = '';
352
353         $textmode = false;
354
355         if(local_user() && (! feature_enabled(local_user(),'richtext')))
356                 $textmode = true;
357
358         //if($textmode)
359         $br = (($textmode) ? "\n" : '<br />');
360
361         if(x($_GET,'binurl'))
362                 $url = trim(hex2bin($_GET['binurl']));
363         else
364                 $url = trim($_GET['url']);
365
366         if($_GET['title'])
367                 $title = strip_tags(trim($_GET['title']));
368
369         if($_GET['description'])
370                 $text = strip_tags(trim($_GET['description']));
371
372         if($_GET['tags']) {
373                 $arr_tags = str_getcsv($_GET['tags']);
374                 if(count($arr_tags)) {
375                         array_walk($arr_tags,'arr_add_hashes');
376                         $str_tags = $br . implode(' ',$arr_tags) . $br;
377                 }
378         }
379
380         logger('parse_url: ' . $url);
381
382         if($textmode)
383                 $template = '[bookmark=%s]%s[/bookmark]%s';
384         else
385                 $template = "<a class=\"bookmark\" href=\"%s\" >%s</a>%s";
386
387         $arr = array('url' => $url, 'text' => '');
388
389         call_hooks('parse_link', $arr);
390
391         if(strlen($arr['text'])) {
392                 echo $arr['text'];
393                 killme();
394         }
395
396
397         if($url && $title && $text) {
398
399                 $title = str_replace(array("\r","\n"),array('',''),$title);
400
401                 if($textmode)
402                         $text = '[quote]' . trim($text) . '[/quote]' . $br;
403                 else {
404                         $text = '<blockquote>' . htmlspecialchars(trim($text)) . '</blockquote><br />';
405                         $title = htmlspecialchars($title);
406                 }
407
408                 $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
409
410                 logger('parse_url (unparsed): returns: ' . $result);
411
412                 echo $result;
413                 killme();
414         }
415
416         $siteinfo = parseurl_getsiteinfo($url);
417
418 //      if ($textmode) {
419 //              require_once("include/items.php");
420 //
421 //              echo add_page_info_data($siteinfo);
422 //              killme();
423 //      }
424
425         $url= $siteinfo["url"];
426
427         // If the link contains BBCode stuff, make a short link out of this to avoid parsing problems
428         if (strpos($url, '[') OR strpos($url, ']')) {
429                 require_once("include/network.php");
430                 $url = short_link($url);
431         }
432
433         $sitedata = "";
434
435         if($siteinfo["title"] == "") {
436                 $sitedata .= sprintf($template,$url,$url,'') . $str_tags;
437                 killme();
438         } else {
439                 $text = $siteinfo["text"];
440                 $title = $siteinfo["title"];
441         }
442
443         $image = "";
444
445         if (($siteinfo["type"] != "video") AND (sizeof($siteinfo["images"]) > 0)){
446                 /* Execute below code only if image is present in siteinfo */
447
448                 $total_images = 0;
449                 $max_images = get_config('system','max_bookmark_images');
450                 if($max_images === false)
451                         $max_images = 2;
452                 else
453                         $max_images = intval($max_images);
454
455                 foreach ($siteinfo["images"] as $imagedata) {
456                         if($textmode)
457                                 $image .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
458                         else
459                                 $image .= '<img height="'.$imagedata["height"].'" width="'.$imagedata["width"].'" src="'.$imagedata["src"].'" alt="photo" /><br />';
460                         $total_images ++;
461                         if($max_images && $max_images >= $total_images)
462                                 break;
463                 }
464         }
465
466         if(strlen($text)) {
467                 if($textmode)
468                         $text = '[quote]'.trim($text).'[/quote]';
469                 else
470                         $text = '<blockquote>'.htmlspecialchars(trim($text)).'</blockquote>';
471         }
472
473         if($image)
474                 $text = $br.$br.$image.$text;
475         else
476                 $text = $br.$text;
477
478         $title = str_replace(array("\r","\n"),array('',''),$title);
479
480         $result = sprintf($template,$url,($title) ? $title : $url,$text) . $str_tags;
481
482         logger('parse_url: returns: ' . $result);
483
484         $sitedata .=  trim($result);
485
486         if (($siteinfo["type"] == "video") AND ($url != ""))
487                 echo "[class=type-video]".$sitedata."[/class]";
488         elseif (($siteinfo["type"] != "photo"))
489                 echo "[class=type-link]".$sitedata."[/class]";
490         else
491                 echo "[class=type-photo]".$title.$br.$image."[/class]";
492
493         killme();
494 }
495 ?>