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