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