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