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