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