]> git.mxchange.org Git - friendica.git/blob - include/ParseUrl.php
3a2fe9d53c6b818b39613d7d4f769bd34691ab6e
[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         /**
23          * @brief Search for chached embeddable data of an url otherwise fetch it
24          *
25          * @param type $url The url of the page which should be scraped
26          * @param type $no_guessing If true the parse doens't search for
27          *    preview pictures
28          * @param type $do_oembed The false option is used by the function fetch_oembed()
29          *    to avoid endless loops
30          *
31          * @return array which contains needed data for embedding
32          *    string 'url' => The url of the parsed page
33          *    string 'type' => Content type
34          *    string 'title' => The title of the content
35          *    string 'text' => The description for the content
36          *    string 'image' => A preview image of the content (only available
37          *                if $no_geuessing = false
38          *    array'images' = Array of preview pictures
39          *    string 'keywords' => The tags which belong to the content
40          *
41          * @see ParseUrl::getSiteinfo() for more information about scraping
42          * embeddable content
43          */
44         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
45
46                 if ($url == "") {
47                         return false;
48                 }
49
50                 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
51                         dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
52
53                 if ($r) {
54                         $data = $r[0]["content"];
55                 }
56
57                 if (!is_null($data)) {
58                         $data = unserialize($data);
59                         return $data;
60                 }
61
62                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
63
64                 q("INSERT INTO `parsed_url` (`url`, `guessing`, `oembed`, `content`, `created`) VALUES ('%s', %d, %d, '%s', '%s')
65                          ON DUPLICATE KEY UPDATE `content` = '%s', `created` = '%s'",
66                         dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed),
67                         dbesc(serialize($data)), dbesc(datetime_convert()),
68                         dbesc(serialize($data)), dbesc(datetime_convert()));
69
70                 return $data;
71         }
72         /**
73          * @brief Parse a page for embeddable content information
74          *
75          * This method parses to url for meta data which can be used to embed
76          * the content. If available it prioritizes Open Graph meta tags.
77          * If this is not available it uses the twitter cards meta tags.
78          * As fallback it uses standard html elements with meta informations
79          * like \<title\>Awesome Title\</title\> or
80          * \<meta name="description" content="An awesome description"\>
81          *
82          * @param type $url The url of the page which should be scraped
83          * @param type $no_guessing If true the parse doens't search for
84          *    preview pictures
85          * @param type $do_oembed The false option is used by the function fetch_oembed()
86          *    to avoid endless loops
87          * @param type $count Internal counter to avoid endless loops
88          *
89          * @return array which contains needed data for embedding
90          *    string 'url' => The url of the parsed page
91          *    string 'type' => Content type
92          *    string 'title' => The title of the content
93          *    string 'text' => The description for the content
94          *    string 'image' => A preview image of the content (only available
95          *                if $no_geuessing = false
96          *    array'images' = Array of preview pictures
97          *    string 'keywords' => The tags which belong to the content
98          *
99          * @todo https://developers.google.com/+/plugins/snippet/
100          * @verbatim
101          * <meta itemprop="name" content="Awesome title">
102          * <meta itemprop="description" content="An awesome description">
103          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
104          *
105          * <body itemscope itemtype="http://schema.org/Product">
106          *   <h1 itemprop="name">Shiny Trinket</h1>
107          *   <img itemprop="image" src="{image-url}" />
108          *   <p itemprop="description">Shiny trinkets are shiny.</p>
109          * </body>
110          * @endverbatim
111          */
112         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
113
114                 $a = get_app();
115
116                 $siteinfo = array();
117
118                 // Check if the URL does contain a scheme
119                 $scheme = parse_url($url, PHP_URL_SCHEME);
120
121                 if ($scheme == "") {
122                         $url = "http://".trim($url, "/");
123                 }
124
125                 if ($count > 10) {
126                         logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
127                         return($siteinfo);
128                 }
129
130                 $url = trim($url, "'");
131                 $url = trim($url, '"');
132
133                 $url = strip_tracking_query_params($url);
134
135                 $siteinfo["url"] = $url;
136                 $siteinfo["type"] = "link";
137
138                 $check_cert = Config::get("system", "verifyssl");
139
140                 $stamp1 = microtime(true);
141
142                 $ch = curl_init();
143                 curl_setopt($ch, CURLOPT_URL, $url);
144                 curl_setopt($ch, CURLOPT_HEADER, 1);
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                 curl_close($ch);
154
155                 $a->save_timestamp($stamp1, "network");
156
157                 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
158                         && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
159                         if ($curl_info["redirect_url"] != "") {
160                                 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
161                         } else {
162                                 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
163                         }
164                         return($siteinfo);
165                 }
166
167                 // If the file is too large then exit
168                 if ($curl_info["download_content_length"] > 1000000) {
169                         return($siteinfo);
170                 }
171
172                 // If it isn't a HTML file then exit
173                 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
174                         return($siteinfo);
175                 }
176
177                 if ($do_oembed) {
178
179                         $oembed_data = oembed_fetch_url($url);
180
181                         if (!in_array($oembed_data->type, array("error", "rich"))) {
182                                 $siteinfo["type"] = $oembed_data->type;
183                         }
184
185                         if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
186                                 if (isset($oembed_data->title)) {
187                                         $siteinfo["title"] = $oembed_data->title;
188                                 }
189                                 if (isset($oembed_data->description)) {
190                                         $siteinfo["text"] = trim($oembed_data->description);
191                                 }
192                                 if (isset($oembed_data->thumbnail_url)) {
193                                         $siteinfo["image"] = $oembed_data->thumbnail_url;
194                                 }
195                         }
196                 }
197
198                 // Fetch the first mentioned charset. Can be in body or header
199                 $charset = "";
200                 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
201                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
202                 }
203
204                 if ($charset == "") {
205                         $charset = "utf-8";
206                 }
207
208                 $pos = strpos($header, "\r\n\r\n");
209
210                 if ($pos) {
211                         $body = trim(substr($header, $pos));
212                 } else {
213                         $body = $header;
214                 }
215
216                 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
217                         logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
218                         //$body = mb_convert_encoding($body, "UTF-8", $charset);
219                         $body = iconv($charset, "UTF-8//TRANSLIT", $body);
220                 }
221
222                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
223
224                 $doc = new \DOMDocument();
225                 @$doc->loadHTML($body);
226
227                 \xml::deleteNode($doc, "style");
228                 \xml::deleteNode($doc, "script");
229                 \xml::deleteNode($doc, "option");
230                 \xml::deleteNode($doc, "h1");
231                 \xml::deleteNode($doc, "h2");
232                 \xml::deleteNode($doc, "h3");
233                 \xml::deleteNode($doc, "h4");
234                 \xml::deleteNode($doc, "h5");
235                 \xml::deleteNode($doc, "h6");
236                 \xml::deleteNode($doc, "ol");
237                 \xml::deleteNode($doc, "ul");
238
239                 $xpath = new \DomXPath($doc);
240
241                 $list = $xpath->query("//meta[@content]");
242                 foreach ($list as $node) {
243                         $attr = array();
244                         if ($node->attributes->length) {
245                                 foreach ($node->attributes as $attribute) {
246                                         $attr[$attribute->name] = $attribute->value;
247                                 }
248                         }
249
250                         if (@$attr["http-equiv"] == "refresh") {
251                                 $path = $attr["content"];
252                                 $pathinfo = explode(";", $path);
253                                 $content = "";
254                                 foreach ($pathinfo as $value) {
255                                         if (substr(strtolower($value), 0, 4) == "url=") {
256                                                 $content = substr($value, 4);
257                                         }
258                                 }
259                                 if ($content != "") {
260                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
261                                         return($siteinfo);
262                                 }
263                         }
264                 }
265
266                 $list = $xpath->query("//title");
267                 if ($list->length > 0) {
268                         $siteinfo["title"] = $list->item(0)->nodeValue;
269                 }
270
271                 //$list = $xpath->query("head/meta[@name]");
272                 $list = $xpath->query("//meta[@name]");
273                 foreach ($list as $node) {
274                         $attr = array();
275                         if ($node->attributes->length) {
276                                 foreach ($node->attributes as $attribute) {
277                                         $attr[$attribute->name] = $attribute->value;
278                                 }
279                         }
280
281                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
282
283                         if ($attr["content"] != "") {
284                                 switch (strtolower($attr["name"])) {
285                                         case "fulltitle":
286                                                 $siteinfo["title"] = $attr["content"];
287                                                 break;
288                                         case "description":
289                                                 $siteinfo["text"] = $attr["content"];
290                                                 break;
291                                         case "thumbnail":
292                                                 $siteinfo["image"] = $attr["content"];
293                                                 break;
294                                         case "twitter:image":
295                                                 $siteinfo["image"] = $attr["content"];
296                                                 break;
297                                         case "twitter:image:src":
298                                                 $siteinfo["image"] = $attr["content"];
299                                                 break;
300                                         case "twitter:card":
301                                                 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
302                                                         $siteinfo["type"] = $attr["content"];
303                                                 }
304                                                 break;
305                                         case "twitter:description":
306                                                 $siteinfo["text"] = $attr["content"];
307                                                 break;
308                                         case "twitter:title":
309                                                 $siteinfo["title"] = $attr["content"];
310                                                 break;
311                                         case "dc.title":
312                                                 $siteinfo["title"] = $attr["content"];
313                                                 break;
314                                         case "dc.description":
315                                                 $siteinfo["text"] = $attr["content"];
316                                                 break;
317                                         case "keywords":
318                                                 $keywords = explode(",", $attr["content"]);
319                                                 break;
320                                         case "news_keywords":
321                                                 $keywords = explode(",", $attr["content"]);
322                                                 break;
323                                 }
324                         }
325                         if ($siteinfo["type"] == "summary") {
326                                 $siteinfo["type"] = "link";
327                         }
328                 }
329
330                 if (isset($keywords)) {
331                         $siteinfo["keywords"] = array();
332                         foreach ($keywords as $keyword) {
333                                 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
334                                         $siteinfo["keywords"][] = trim($keyword);
335                                 }
336                         }
337                 }
338
339                 //$list = $xpath->query("head/meta[@property]");
340                 $list = $xpath->query("//meta[@property]");
341                 foreach ($list as $node) {
342                         $attr = array();
343                         if ($node->attributes->length) {
344                                 foreach ($node->attributes as $attribute) {
345                                         $attr[$attribute->name] = $attribute->value;
346                                 }
347                         }
348
349                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
350
351                         if ($attr["content"] != "") {
352                                 switch (strtolower($attr["property"])) {
353                                         case "og:image":
354                                                 $siteinfo["image"] = $attr["content"];
355                                                 break;
356                                         case "og:title":
357                                                 $siteinfo["title"] = $attr["content"];
358                                                 break;
359                                         case "og:description":
360                                                 $siteinfo["text"] = $attr["content"];
361                                                 break;
362                                 }
363                         }
364                 }
365
366                 if ((@$siteinfo["image"] == "") && !$no_guessing) {
367                         $list = $xpath->query("//img[@src]");
368                         foreach ($list as $node) {
369                                 $attr = array();
370                                 if ($node->attributes->length) {
371                                         foreach ($node->attributes as $attribute) {
372                                                 $attr[$attribute->name] = $attribute->value;
373                                         }
374                                 }
375
376                                 $src = self::completeUrl($attr["src"], $url);
377                                 $photodata = get_photo_info($src);
378
379                                 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
380                                         if ($photodata[0] > 300) {
381                                                 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
382                                                 $photodata[0] = 300;
383                                         }
384                                         if ($photodata[1] > 300) {
385                                                 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
386                                                 $photodata[1] = 300;
387                                         }
388                                         $siteinfo["images"][] = array("src" => $src,
389                                                                         "width" => $photodata[0],
390                                                                         "height" => $photodata[1]);
391                                 }
392
393                                 }
394                 } elseif ($siteinfo["image"] != "") {
395                         $src = self::completeUrl($siteinfo["image"], $url);
396
397                         unset($siteinfo["image"]);
398
399                         $photodata = get_photo_info($src);
400
401                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
402                                 $siteinfo["images"][] = array("src" => $src,
403                                                                 "width" => $photodata[0],
404                                                                 "height" => $photodata[1]);
405                         }
406                 }
407
408                 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
409                         $text = "";
410
411                         $list = $xpath->query("//div[@class='article']");
412                         foreach ($list as $node) {
413                                 if (strlen($node->nodeValue) > 40) {
414                                         $text .= " ".trim($node->nodeValue);
415                                 }
416                         }
417
418                         if ($text == "") {
419                                 $list = $xpath->query("//div[@class='content']");
420                                 foreach ($list as $node) {
421                                         if (strlen($node->nodeValue) > 40) {
422                                                 $text .= " ".trim($node->nodeValue);
423                                         }
424                                 }
425                         }
426
427                         // If none text was found then take the paragraph content
428                         if ($text == "") {
429                                 $list = $xpath->query("//p");
430                                 foreach ($list as $node) {
431                                         if (strlen($node->nodeValue) > 40) {
432                                                 $text .= " ".trim($node->nodeValue);
433                                         }
434                                 }
435                         }
436
437                         if ($text != "") {
438                                 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
439
440                                 while (strpos($text, "  ")) {
441                                         $text = trim(str_replace("  ", " ", $text));
442                                 }
443
444                                 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
445                         }
446                 }
447
448                 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
449
450                 call_hooks("getsiteinfo", $siteinfo);
451
452                 return($siteinfo);
453         }
454
455         /**
456          * @brief Convert tags from CSV to an array
457          *
458          * @param string $string Tags
459          * @return array with formatted Hashtags
460          */
461         public static function convertTagsToArray($string) {
462                 $arr_tags = str_getcsv($string);
463                 if (count($arr_tags)) {
464                         // add the # sign to every tag
465                         array_walk($arr_tags, array("self", "arrAddHashes"));
466
467                         return $arr_tags;
468                 }
469         }
470
471         /**
472          * @brief Add a hasht sign to a string
473          *
474          *  This method is used as callback function
475          *
476          * @param string $tag The pure tag name
477          * @param int $k Counter for internal use
478          */
479         private static function arrAddHashes(&$tag, $k) {
480                 $tag = "#" . $tag;
481         }
482
483         /**
484          * @brief Add a scheme to an url
485          *
486          * The src attribute of some html elements (e.g. images)
487          * can miss the scheme so we need to add the correct
488          * scheme
489          *
490          * @param string $url The url which possibly does have
491          *    a missing scheme (a link to an image)
492          * @param string $scheme The url with a correct scheme
493          *    (e.g. the url from the webpage which does contain the image)
494          *
495          * @return string The url with a scheme
496          */
497         private static function completeUrl($url, $scheme) {
498                 $urlarr = parse_url($url);
499
500                 // If the url does allready have an scheme
501                 // we can stop the process here
502                 if (isset($urlarr["scheme"])) {
503                         return($url);
504                 }
505
506                 $schemearr = parse_url($scheme);
507
508                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
509
510                 if (@$schemearr["port"] != "") {
511                         $complete .= ":".$schemearr["port"];
512                 }
513
514                 if (strpos($urlarr["path"],"/") !== 0) {
515                         $complete .= "/";
516                 }
517
518                 $complete .= $urlarr["path"];
519
520                 if (@$urlarr["query"] != "") {
521                         $complete .= "?".$urlarr["query"];
522                 }
523
524                 if (@$urlarr["fragment"] != "") {
525                         $complete .= "#".$urlarr["fragment"];
526                 }
527
528                 return($complete);
529         }
530 }