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