]> git.mxchange.org Git - friendica.git/blob - include/ParseUrl.php
Merge pull request #2978 from annando/issue-2518
[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 = original_url($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_NOBODY, 1);
146                 curl_setopt($ch, CURLOPT_TIMEOUT, 3);
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                 if ((($curl_info["http_code"] == "301") || ($curl_info["http_code"] == "302") || ($curl_info["http_code"] == "303") || ($curl_info["http_code"] == "307"))
160                         && (($curl_info["redirect_url"] != "") || ($curl_info["location"] != ""))) {
161                         if ($curl_info["redirect_url"] != "") {
162                                 $siteinfo = self::getSiteinfo($curl_info["redirect_url"], $no_guessing, $do_oembed, ++$count);
163                         } else {
164                                 $siteinfo = self::getSiteinfo($curl_info["location"], $no_guessing, $do_oembed, ++$count);
165                         }
166                         return($siteinfo);
167                 }
168
169                 // If the file is too large then exit
170                 if ($curl_info["download_content_length"] > 1000000) {
171                         return($siteinfo);
172                 }
173
174                 // If it isn't a HTML file then exit
175                 if (($curl_info["content_type"] != "") && !strstr(strtolower($curl_info["content_type"]), "html")) {
176                         return($siteinfo);
177                 }
178
179                 if ($do_oembed) {
180
181                         $oembed_data = oembed_fetch_url($url);
182
183                         if (!in_array($oembed_data->type, array("error", "rich"))) {
184                                 $siteinfo["type"] = $oembed_data->type;
185                         }
186
187                         if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
188                                 if (isset($oembed_data->title)) {
189                                         $siteinfo["title"] = $oembed_data->title;
190                                 }
191                                 if (isset($oembed_data->description)) {
192                                         $siteinfo["text"] = trim($oembed_data->description);
193                                 }
194                                 if (isset($oembed_data->thumbnail_url)) {
195                                         $siteinfo["image"] = $oembed_data->thumbnail_url;
196                                 }
197                         }
198                 }
199
200                 $stamp1 = microtime(true);
201
202                 // Now fetch the body as well
203                 $ch = curl_init();
204                 curl_setopt($ch, CURLOPT_URL, $url);
205                 curl_setopt($ch, CURLOPT_HEADER, 1);
206                 curl_setopt($ch, CURLOPT_NOBODY, 0);
207                 curl_setopt($ch, CURLOPT_TIMEOUT, 10);
208                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
209                 curl_setopt($ch, CURLOPT_USERAGENT, $a->get_useragent());
210                 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, (($check_cert) ? true : false));
211                 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, (($check_cert) ? 2 : false));
212
213                 $header = curl_exec($ch);
214                 $curl_info = @curl_getinfo($ch);
215                 $http_code = $curl_info["http_code"];
216                 curl_close($ch);
217
218                 $a->save_timestamp($stamp1, "network");
219
220                 // Fetch the first mentioned charset. Can be in body or header
221                 $charset = "";
222                 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
223                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
224                 }
225
226                 if ($charset == "") {
227                         $charset = "utf-8";
228                 }
229
230                 $pos = strpos($header, "\r\n\r\n");
231
232                 if ($pos) {
233                         $body = trim(substr($header, $pos));
234                 } else {
235                         $body = $header;
236                 }
237
238                 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
239                         logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
240                         //$body = mb_convert_encoding($body, "UTF-8", $charset);
241                         $body = iconv($charset, "UTF-8//TRANSLIT", $body);
242                 }
243
244                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
245
246                 $doc = new \DOMDocument();
247                 @$doc->loadHTML($body);
248
249                 \xml::deleteNode($doc, "style");
250                 \xml::deleteNode($doc, "script");
251                 \xml::deleteNode($doc, "option");
252                 \xml::deleteNode($doc, "h1");
253                 \xml::deleteNode($doc, "h2");
254                 \xml::deleteNode($doc, "h3");
255                 \xml::deleteNode($doc, "h4");
256                 \xml::deleteNode($doc, "h5");
257                 \xml::deleteNode($doc, "h6");
258                 \xml::deleteNode($doc, "ol");
259                 \xml::deleteNode($doc, "ul");
260
261                 $xpath = new \DomXPath($doc);
262
263                 $list = $xpath->query("//meta[@content]");
264                 foreach ($list as $node) {
265                         $attr = array();
266                         if ($node->attributes->length) {
267                                 foreach ($node->attributes as $attribute) {
268                                         $attr[$attribute->name] = $attribute->value;
269                                 }
270                         }
271
272                         if (@$attr["http-equiv"] == "refresh") {
273                                 $path = $attr["content"];
274                                 $pathinfo = explode(";", $path);
275                                 $content = "";
276                                 foreach ($pathinfo as $value) {
277                                         if (substr(strtolower($value), 0, 4) == "url=") {
278                                                 $content = substr($value, 4);
279                                         }
280                                 }
281                                 if ($content != "") {
282                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
283                                         return($siteinfo);
284                                 }
285                         }
286                 }
287
288                 $list = $xpath->query("//title");
289                 if ($list->length > 0) {
290                         $siteinfo["title"] = $list->item(0)->nodeValue;
291                 }
292
293                 //$list = $xpath->query("head/meta[@name]");
294                 $list = $xpath->query("//meta[@name]");
295                 foreach ($list as $node) {
296                         $attr = array();
297                         if ($node->attributes->length) {
298                                 foreach ($node->attributes as $attribute) {
299                                         $attr[$attribute->name] = $attribute->value;
300                                 }
301                         }
302
303                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
304
305                         if ($attr["content"] != "") {
306                                 switch (strtolower($attr["name"])) {
307                                         case "fulltitle":
308                                                 $siteinfo["title"] = $attr["content"];
309                                                 break;
310                                         case "description":
311                                                 $siteinfo["text"] = $attr["content"];
312                                                 break;
313                                         case "thumbnail":
314                                                 $siteinfo["image"] = $attr["content"];
315                                                 break;
316                                         case "twitter:image":
317                                                 $siteinfo["image"] = $attr["content"];
318                                                 break;
319                                         case "twitter:image:src":
320                                                 $siteinfo["image"] = $attr["content"];
321                                                 break;
322                                         case "twitter:card":
323                                                 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
324                                                         $siteinfo["type"] = $attr["content"];
325                                                 }
326                                                 break;
327                                         case "twitter:description":
328                                                 $siteinfo["text"] = $attr["content"];
329                                                 break;
330                                         case "twitter:title":
331                                                 $siteinfo["title"] = $attr["content"];
332                                                 break;
333                                         case "dc.title":
334                                                 $siteinfo["title"] = $attr["content"];
335                                                 break;
336                                         case "dc.description":
337                                                 $siteinfo["text"] = $attr["content"];
338                                                 break;
339                                         case "keywords":
340                                                 $keywords = explode(",", $attr["content"]);
341                                                 break;
342                                         case "news_keywords":
343                                                 $keywords = explode(",", $attr["content"]);
344                                                 break;
345                                 }
346                         }
347                         if ($siteinfo["type"] == "summary") {
348                                 $siteinfo["type"] = "link";
349                         }
350                 }
351
352                 if (isset($keywords)) {
353                         $siteinfo["keywords"] = array();
354                         foreach ($keywords as $keyword) {
355                                 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
356                                         $siteinfo["keywords"][] = trim($keyword);
357                                 }
358                         }
359                 }
360
361                 //$list = $xpath->query("head/meta[@property]");
362                 $list = $xpath->query("//meta[@property]");
363                 foreach ($list as $node) {
364                         $attr = array();
365                         if ($node->attributes->length) {
366                                 foreach ($node->attributes as $attribute) {
367                                         $attr[$attribute->name] = $attribute->value;
368                                 }
369                         }
370
371                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
372
373                         if ($attr["content"] != "") {
374                                 switch (strtolower($attr["property"])) {
375                                         case "og:image":
376                                                 $siteinfo["image"] = $attr["content"];
377                                                 break;
378                                         case "og:title":
379                                                 $siteinfo["title"] = $attr["content"];
380                                                 break;
381                                         case "og:description":
382                                                 $siteinfo["text"] = $attr["content"];
383                                                 break;
384                                 }
385                         }
386                 }
387
388                 if ((@$siteinfo["image"] == "") && !$no_guessing) {
389                         $list = $xpath->query("//img[@src]");
390                         foreach ($list as $node) {
391                                 $attr = array();
392                                 if ($node->attributes->length) {
393                                         foreach ($node->attributes as $attribute) {
394                                                 $attr[$attribute->name] = $attribute->value;
395                                         }
396                                 }
397
398                                 $src = self::completeUrl($attr["src"], $url);
399                                 $photodata = get_photo_info($src);
400
401                                 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
402                                         if ($photodata[0] > 300) {
403                                                 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
404                                                 $photodata[0] = 300;
405                                         }
406                                         if ($photodata[1] > 300) {
407                                                 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
408                                                 $photodata[1] = 300;
409                                         }
410                                         $siteinfo["images"][] = array("src" => $src,
411                                                                         "width" => $photodata[0],
412                                                                         "height" => $photodata[1]);
413                                 }
414
415                                 }
416                 } elseif ($siteinfo["image"] != "") {
417                         $src = self::completeUrl($siteinfo["image"], $url);
418
419                         unset($siteinfo["image"]);
420
421                         $photodata = get_photo_info($src);
422
423                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
424                                 $siteinfo["images"][] = array("src" => $src,
425                                                                 "width" => $photodata[0],
426                                                                 "height" => $photodata[1]);
427                         }
428                 }
429
430                 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
431                         $text = "";
432
433                         $list = $xpath->query("//div[@class='article']");
434                         foreach ($list as $node) {
435                                 if (strlen($node->nodeValue) > 40) {
436                                         $text .= " ".trim($node->nodeValue);
437                                 }
438                         }
439
440                         if ($text == "") {
441                                 $list = $xpath->query("//div[@class='content']");
442                                 foreach ($list as $node) {
443                                         if (strlen($node->nodeValue) > 40) {
444                                                 $text .= " ".trim($node->nodeValue);
445                                         }
446                                 }
447                         }
448
449                         // If none text was found then take the paragraph content
450                         if ($text == "") {
451                                 $list = $xpath->query("//p");
452                                 foreach ($list as $node) {
453                                         if (strlen($node->nodeValue) > 40) {
454                                                 $text .= " ".trim($node->nodeValue);
455                                         }
456                                 }
457                         }
458
459                         if ($text != "") {
460                                 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
461
462                                 while (strpos($text, "  ")) {
463                                         $text = trim(str_replace("  ", " ", $text));
464                                 }
465
466                                 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
467                         }
468                 }
469
470                 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
471
472                 call_hooks("getsiteinfo", $siteinfo);
473
474                 return($siteinfo);
475         }
476
477         /**
478          * @brief Convert tags from CSV to an array
479          * 
480          * @param string $string Tags
481          * @return array with formatted Hashtags
482          */
483         public static function convertTagsToArray($string) {
484                 $arr_tags = str_getcsv($string);
485                 if (count($arr_tags)) {
486                         // add the # sign to every tag
487                         array_walk($arr_tags, array("self", "arrAddHashes"));
488
489                         return $arr_tags;
490                 }
491         }
492
493         /**
494          * @brief Add a hasht sign to a string
495          * 
496          *  This method is used as callback function
497          * 
498          * @param string $tag The pure tag name
499          * @param int $k Counter for internal use
500          */
501         private static function arrAddHashes(&$tag, $k) {
502                 $tag = "#" . $tag;
503         }
504
505         /**
506          * @brief Add a scheme to an url
507          * 
508          * The src attribute of some html elements (e.g. images)
509          * can miss the scheme so we need to add the correct
510          * scheme
511          * 
512          * @param string $url The url which possibly does have
513          *    a missing scheme (a link to an image)
514          * @param string $scheme The url with a correct scheme
515          *    (e.g. the url from the webpage which does contain the image)
516          * 
517          * @return string The url with a scheme
518          */
519         private static function completeUrl($url, $scheme) {
520                 $urlarr = parse_url($url);
521
522                 // If the url does allready have an scheme
523                 // we can stop the process here
524                 if (isset($urlarr["scheme"])) {
525                         return($url);
526                 }
527
528                 $schemearr = parse_url($scheme);
529
530                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
531
532                 if (@$schemearr["port"] != "") {
533                         $complete .= ":".$schemearr["port"];
534                 }
535
536                 if (strpos($urlarr["path"],"/") !== 0) {
537                         $complete .= "/";
538                 }
539
540                 $complete .= $urlarr["path"];
541
542                 if (@$urlarr["query"] != "") {
543                         $complete .= "?".$urlarr["query"];
544                 }
545
546                 if (@$urlarr["fragment"] != "") {
547                         $complete .= "#".$urlarr["fragment"];
548                 }
549
550                 return($complete);
551         }
552 }