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