]> git.mxchange.org Git - friendica.git/blob - include/ParseUrl.php
move function deletenode() to the xml class
[friendica.git] / include / ParseUrl.php
1 <?php
2
3 /**
4  * @file include/ParseUrl.php
5  * @brief Get informations about a given URL
6  */
7
8 namespace Friendica;
9
10 use \Friendica\Core\Config;
11
12 require_once("include/network.php");
13 require_once("include/Photo.php");
14 require_once("include/oembed.php");
15 require_once("include/xml.php");
16
17 /**
18  * @brief Class with methods for extracting certain content from an url
19  */
20 class ParseUrl {
21
22         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
23
24                 if ($url == "") {
25                         return false;
26                 }
27
28                 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
29                         dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
30
31                 if ($r) {
32                         $data = $r[0]["content"];
33                 }
34
35                 if (!is_null($data)) {
36                         $data = unserialize($data);
37                         return $data;
38                 }
39
40                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
41
42                 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
43                          ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
44                         dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
45                         dbesc(serialize($data)), dbesc(datetime_convert()),
46                         dbesc(serialize($data)), dbesc(datetime_convert()));
47
48                 return $data;
49         }
50
51         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
52
53                 $a = get_app();
54
55                 $siteinfo = array();
56
57                 // Check if the URL does contain a scheme
58                 $scheme = parse_url($url, PHP_URL_SCHEME);
59
60                 if ($scheme == "") {
61                         $url = "http://".trim($url, "/");
62                 }
63
64                 if ($count > 10) {
65                         logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
66                         return($siteinfo);
67                 }
68
69                 $url = trim($url, "'");
70                 $url = trim($url, '"');
71
72                 $url = original_url($url);
73
74                 $siteinfo["url"] = $url;
75                 $siteinfo["type"] = "link";
76
77                 $check_cert = Config::get("system", "verifyssl");
78
79                 $stamp1 = microtime(true);
80
81                 $ch = curl_init();
82                 curl_setopt($ch, CURLOPT_URL, $url);
83                 curl_setopt($ch, CURLOPT_HEADER, 1);
84                 curl_setopt($ch, CURLOPT_NOBODY, 1);
85                 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
86                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
87                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
88                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
89                 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
90
91                 $header = curl_exec($ch);
92                 $curl_info = @curl_getinfo($ch);
93                 $http_code = $curl_info["http_code"];
94                 curl_close($ch);
95
96                 $a->save_timestamp($stamp1, "network");
97
98                 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
99                         && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
100                         if ($curl_info["redirect_url"] != "") {
101                                 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
102                         } else {
103                                 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
104                         }
105                         return($siteinfo);
106                 }
107
108                 // If the file is too large then exit
109                 if ($curl_info["download_content_length"] > 1000000) {
110                         return($siteinfo);
111                 }
112
113                 // If it isn't a HTML file then exit
114                 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
115                         return($siteinfo);
116                 }
117
118                 if ($do_oembed) {
119
120                         $oembed_data = oembed_fetch_url($url);
121
122                         if (!in_array($oembed_data->type, array("error", "rich"))) {
123                                 $siteinfo["type"] = $oembed_data->type;
124                         }
125
126                         if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
127                                 if (isset($oembed_data->title)) {
128                                         $siteinfo["title"] = $oembed_data->title;
129                                 }
130                                 if (isset($oembed_data->description)) {
131                                         $siteinfo["text"] = trim($oembed_data->description);
132                                 }
133                                 if (isset($oembed_data->thumbnail_url)) {
134                                         $siteinfo["image"] = $oembed_data->thumbnail_url;
135                                 }
136                         }
137                 }
138
139                 $stamp1 = microtime(true);
140
141                 // Now fetch the body as well
142                 $ch = curl_init();
143                 curl_setopt($ch, CURLOPT_URL, $url);
144                 curl_setopt($ch, CURLOPT_HEADER, 1);
145                 curl_setopt($ch, CURLOPT_NOBODY, 0);
146                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
147                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
148                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
149                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
150                 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
151
152                 $header = curl_exec($ch);
153                 $curl_info = @curl_getinfo($ch);
154                 $http_code = $curl_info["http_code"];
155                 curl_close($ch);
156
157                 $a->save_timestamp($stamp1, "network");
158
159                 // Fetch the first mentioned charset. Can be in body or header
160                 $charset = "";
161                 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
162                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
163                 }
164
165                 if ($charset == "") {
166                         $charset = "utf-8";
167                 }
168
169                 $pos = strpos($header, "\r\n\r\n");
170
171                 if ($pos) {
172                         $body = trim(substr($header, $pos));
173                 } else {
174                         $body = $header;
175                 }
176
177                 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
178                         logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
179                         //$body = mb_convert_encoding($body, "UTF-8", $charset);
180                         $body = iconv($charset, "UTF-8//TRANSLIT", $body);
181                 }
182
183                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
184
185                 $doc = new \DOMDocument();
186                 @$doc->loadHTML($body);
187
188                 \xml::deleteNode($doc, "style");
189                 \xml::deleteNode($doc, "script");
190                 \xml::deleteNode($doc, "option");
191                 \xml::deleteNode($doc, "h1");
192                 \xml::deleteNode($doc, "h2");
193                 \xml::deleteNode($doc, "h3");
194                 \xml::deleteNode($doc, "h4");
195                 \xml::deleteNode($doc, "h5");
196                 \xml::deleteNode($doc, "h6");
197                 \xml::deleteNode($doc, "ol");
198                 \xml::deleteNode($doc, "ul");
199
200                 $xpath = new \DomXPath($doc);
201
202                 $list = $xpath->query("//meta[@content]");
203                 foreach ($list as $node) {
204                         $attr = array();
205                         if ($node->attributes->length) {
206                                 foreach ($node->attributes as $attribute) {
207                                         $attr[$attribute->name] = $attribute->value;
208                                 }
209                         }
210
211                         if (@$attr["http-equiv"] == "refresh") {
212                                 $path = $attr["content"];
213                                 $pathinfo = explode(";", $path);
214                                 $content = "";
215                                 foreach ($pathinfo as $value) {
216                                         if (substr(strtolower($value), 0, 4) == "url=") {
217                                                 $content = substr($value, 4);
218                                         }
219                                 }
220                                 if ($content != "") {
221                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
222                                         return($siteinfo);
223                                 }
224                         }
225                 }
226
227                 $list = $xpath->query("//title");
228                 if ($list->length > 0) {
229                         $siteinfo["title"] = $list->item(0)->nodeValue;
230                 }
231
232                 //$list = $xpath->query("head/meta[@name]");
233                 $list = $xpath->query("//meta[@name]");
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                         }
241
242                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
243
244                         if ($attr["content"] != "") {
245                                 switch (strtolower($attr["name"])) {
246                                         case "fulltitle":
247                                                 $siteinfo["title"] = $attr["content"];
248                                                 break;
249                                         case "description":
250                                                 $siteinfo["text"] = $attr["content"];
251                                                 break;
252                                         case "thumbnail":
253                                                 $siteinfo["image"] = $attr["content"];
254                                                 break;
255                                         case "twitter:image":
256                                                 $siteinfo["image"] = $attr["content"];
257                                                 break;
258                                         case "twitter:image:src":
259                                                 $siteinfo["image"] = $attr["content"];
260                                                 break;
261                                         case "twitter:card":
262                                                 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
263                                                         $siteinfo["type"] = $attr["content"];
264                                                 }
265                                                 break;
266                                         case "twitter:description":
267                                                 $siteinfo["text"] = $attr["content"];
268                                                 break;
269                                         case "twitter:title":
270                                                 $siteinfo["title"] = $attr["content"];
271                                                 break;
272                                         case "dc.title":
273                                                 $siteinfo["title"] = $attr["content"];
274                                                 break;
275                                         case "dc.description":
276                                                 $siteinfo["text"] = $attr["content"];
277                                                 break;
278                                         case "keywords":
279                                                 $keywords = explode(",", $attr["content"]);
280                                                 break;
281                                         case "news_keywords":
282                                                 $keywords = explode(",", $attr["content"]);
283                                                 break;
284                                 }
285                         }
286                         if ($siteinfo["type"] == "summary") {
287                                 $siteinfo["type"] = "link";
288                         }
289                 }
290
291                 if (isset($keywords)) {
292                         $siteinfo["keywords"] = array();
293                         foreach ($keywords as $keyword) {
294                                 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
295                                         $siteinfo["keywords"][] = trim($keyword);
296                                 }
297                         }
298                 }
299
300                 //$list = $xpath->query("head/meta[@property]");
301                 $list = $xpath->query("//meta[@property]");
302                 foreach ($list as $node) {
303                         $attr = array();
304                         if ($node->attributes->length) {
305                                 foreach ($node->attributes as $attribute) {
306                                         $attr[$attribute->name] = $attribute->value;
307                                 }
308                         }
309
310                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
311
312                         if ($attr["content"] != "") {
313                                 switch (strtolower($attr["property"])) {
314                                         case "og:image":
315                                                 $siteinfo["image"] = $attr["content"];
316                                                 break;
317                                         case "og:title":
318                                                 $siteinfo["title"] = $attr["content"];
319                                                 break;
320                                         case "og:description":
321                                                 $siteinfo["text"] = $attr["content"];
322                                                 break;
323                                 }
324                         }
325                 }
326
327                 if ((@$siteinfo["image"] == "") && !$no_guessing) {
328                         $list = $xpath->query("//img[@src]");
329                         foreach ($list as $node) {
330                                 $attr = array();
331                                 if ($node->attributes->length) {
332                                         foreach ($node->attributes as $attribute) {
333                                                 $attr[$attribute->name] = $attribute->value;
334                                         }
335                                 }
336
337                                 $src = self::completeUrl($attr["src"], $url);
338                                 $photodata = get_photo_info($src);
339
340                                 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
341                                         if ($photodata[0] > 300) {
342                                                 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
343                                                 $photodata[0] = 300;
344                                         }
345                                         if ($photodata[1] > 300) {
346                                                 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
347                                                 $photodata[1] = 300;
348                                         }
349                                         $siteinfo["images"][] = array("src" => $src,
350                                                                         "width" => $photodata[0],
351                                                                         "height" => $photodata[1]);
352                                 }
353
354                                 }
355                 } elseif ($siteinfo["image"] != "") {
356                         $src = self::completeUrl($siteinfo["image"], $url);
357
358                         unset($siteinfo["image"]);
359
360                         $photodata = get_photo_info($src);
361
362                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
363                                 $siteinfo["images"][] = array("src" => $src,
364                                                                 "width" => $photodata[0],
365                                                                 "height" => $photodata[1]);
366                         }
367                 }
368
369                 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
370                         $text = "";
371
372                         $list = $xpath->query("//div[@class='article']");
373                         foreach ($list as $node) {
374                                 if (strlen($node->nodeValue) > 40) {
375                                         $text .= " ".trim($node->nodeValue);
376                                 }
377                         }
378
379                         if ($text == "") {
380                                 $list = $xpath->query("//div[@class='content']");
381                                 foreach ($list as $node) {
382                                         if (strlen($node->nodeValue) > 40) {
383                                                 $text .= " ".trim($node->nodeValue);
384                                         }
385                                 }
386                         }
387
388                         // If none text was found then take the paragraph content
389                         if ($text == "") {
390                                 $list = $xpath->query("//p");
391                                 foreach ($list as $node) {
392                                         if (strlen($node->nodeValue) > 40) {
393                                                 $text .= " ".trim($node->nodeValue);
394                                         }
395                                 }
396                         }
397
398                         if ($text != "") {
399                                 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
400
401                                 while (strpos($text, "  ")) {
402                                         $text = trim(str_replace("  ", " ", $text));
403                                 }
404
405                                 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
406                         }
407                 }
408
409                 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
410
411                 call_hooks("getsiteinfo", $siteinfo);
412
413                 return($siteinfo);
414         }
415
416         /**
417          * @brief Convert tags from CSV to an array
418          * 
419          * @param string $string Tags
420          * @return array with formatted Hashtags
421          */
422         public static function convertTagsToArray($string) {
423                 $arr_tags = str_getcsv($string);
424                 if (count($arr_tags)) {
425                         // add the # sign to every tag
426                         array_walk($arr_tags, array("self", "arrAddHashes"));
427
428                         return $arr_tags;
429                 }
430         }
431
432         /**
433          * @brief Add a hasht sign to a string
434          * 
435          *  This method is used as callback function
436          * 
437          * @param string $tag The pure tag name
438          * @param int $k Counter for internal use
439          */
440         private static function arrAddHashes(&$tag, $k) {
441                 $tag = "#" . $tag;
442         }
443
444         private static function completeUrl($url, $scheme) {
445                 $urlarr = parse_url($url);
446
447                 if (isset($urlarr["scheme"])) {
448                         return($url);
449                 }
450
451                 $schemearr = parse_url($scheme);
452
453                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
454
455                 if (@$schemearr["port"] != "") {
456                         $complete .= ":".$schemearr["port"];
457                 }
458
459                 if (strpos($urlarr["path"],"/") !== 0) {
460                         $complete .= "/";
461                 }
462
463                 $complete .= $urlarr["path"];
464
465                 if (@$urlarr["query"] != "") {
466                         $complete .= "?".$urlarr["query"];
467                 }
468
469                 if (@$urlarr["fragment"] != "") {
470                         $complete .= "#".$urlarr["fragment"];
471                 }
472
473                 return($complete);
474         }
475 }