]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
[Scrutinizer] Fix undeclared variables in src/ (except Protocol/)
[friendica.git] / src / Util / ParseUrl.php
1 <?php
2 /**
3  * @file src/Util/ParseUrl.php
4  * @brief Get informations about a given URL
5  */
6 namespace Friendica\Util;
7
8 use Friendica\Content\OEmbed;
9 use Friendica\Core\Addon;
10 use Friendica\Object\Image;
11 use Friendica\Util\Network;
12 use Friendica\Util\XML;
13
14 use dba;
15 use DOMXPath;
16 use DOMDocument;
17
18 require_once 'include/dba.php';
19
20 /**
21  * @brief Class with methods for extracting certain content from an url
22  */
23 class ParseUrl
24 {
25         /**
26          * @brief Search for chached embeddable data of an url otherwise fetch it
27          *
28          * @param string $url         The url of the page which should be scraped
29          * @param bool $no_guessing If true the parse doens't search for
30          *                          preview pictures
31          * @param bool $do_oembed   The false option is used by the function fetch_oembed()
32          *                          to avoid endless loops
33          *
34          * @return array which contains needed data for embedding
35          *    string 'url' => The url of the parsed page
36          *    string 'type' => Content type
37          *    string 'title' => The title of the content
38          *    string 'text' => The description for the content
39          *    string 'image' => A preview image of the content (only available
40          *                if $no_geuessing = false
41          *    array'images' = Array of preview pictures
42          *    string 'keywords' => The tags which belong to the content
43          *
44          * @see ParseUrl::getSiteinfo() for more information about scraping
45          * embeddable content
46          */
47         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
48         {
49                 if ($url == "") {
50                         return false;
51                 }
52
53                 $parsed_url = dba::selectFirst('parsed_url', ['content'],
54                         ['url' => normalise_link($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
55                 );
56                 if (!empty($parsed_url['content'])) {
57                         $data = unserialize($parsed_url['content']);
58                         return $data;
59                 }
60
61                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
62
63                 dba::insert(
64                         'parsed_url',
65                         [
66                                 'url' => normalise_link($url), 'guessing' => !$no_guessing,
67                                 'oembed' => $do_oembed, 'content' => serialize($data),
68                                 'created' => DateTimeFormat::utcNow()
69                         ],
70                         true
71                 );
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 string $url         The url of the page which should be scraped
86          * @param bool $no_guessing If true the parse doens't search for
87          *                          preview pictures
88          * @param bool $do_oembed   The false option is used by the function fetch_oembed()
89          *                          to avoid endless loops
90          * @param int $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 = [];
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 = Network::stripTrackingQueryParams($url);
137
138                 $siteinfo["url"] = $url;
139                 $siteinfo["type"] = "link";
140
141                 $data = Network::curl($url);
142                 if (!$data['success']) {
143                         return($siteinfo);
144                 }
145
146                 // If the file is too large then exit
147                 if ($data["info"]["download_content_length"] > 1000000) {
148                         return($siteinfo);
149                 }
150
151                 // If it isn't a HTML file then exit
152                 if (($data["info"]["content_type"] != "") && !strstr(strtolower($data["info"]["content_type"]), "html")) {
153                         return($siteinfo);
154                 }
155
156                 $header = $data["header"];
157                 $body = $data["body"];
158
159                 if ($do_oembed) {
160                         $oembed_data = OEmbed::fetchURL($url);
161
162                         if (!in_array($oembed_data->type, ["error", "rich", ""])) {
163                                 $siteinfo["type"] = $oembed_data->type;
164                         }
165
166                         if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
167                                 if (isset($oembed_data->title)) {
168                                         $siteinfo["title"] = trim($oembed_data->title);
169                                 }
170                                 if (isset($oembed_data->description)) {
171                                         $siteinfo["text"] = trim($oembed_data->description);
172                                 }
173                                 if (isset($oembed_data->thumbnail_url)) {
174                                         $siteinfo["image"] = $oembed_data->thumbnail_url;
175                                 }
176                         }
177                 }
178
179                 // Fetch the first mentioned charset. Can be in body or header
180                 $charset = "";
181                 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
182                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
183                 }
184
185                 if ($charset == "") {
186                         $charset = "utf-8";
187                 }
188
189                 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
190                         logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
191                         //$body = mb_convert_encoding($body, "UTF-8", $charset);
192                         $body = iconv($charset, "UTF-8//TRANSLIT", $body);
193                 }
194
195                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
196
197                 $doc = new DOMDocument();
198                 @$doc->loadHTML($body);
199
200                 XML::deleteNode($doc, "style");
201                 XML::deleteNode($doc, "script");
202                 XML::deleteNode($doc, "option");
203                 XML::deleteNode($doc, "h1");
204                 XML::deleteNode($doc, "h2");
205                 XML::deleteNode($doc, "h3");
206                 XML::deleteNode($doc, "h4");
207                 XML::deleteNode($doc, "h5");
208                 XML::deleteNode($doc, "h6");
209                 XML::deleteNode($doc, "ol");
210                 XML::deleteNode($doc, "ul");
211
212                 $xpath = new DOMXPath($doc);
213
214                 $list = $xpath->query("//meta[@content]");
215                 foreach ($list as $node) {
216                         $attr = [];
217                         if ($node->attributes->length) {
218                                 foreach ($node->attributes as $attribute) {
219                                         $attr[$attribute->name] = $attribute->value;
220                                 }
221                         }
222
223                         if (@$attr["http-equiv"] == "refresh") {
224                                 $path = $attr["content"];
225                                 $pathinfo = explode(";", $path);
226                                 $content = "";
227                                 foreach ($pathinfo as $value) {
228                                         if (substr(strtolower($value), 0, 4) == "url=") {
229                                                 $content = substr($value, 4);
230                                         }
231                                 }
232                                 if ($content != "") {
233                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
234                                         return($siteinfo);
235                                 }
236                         }
237                 }
238
239                 $list = $xpath->query("//title");
240                 if ($list->length > 0) {
241                         $siteinfo["title"] = trim($list->item(0)->nodeValue);
242                 }
243
244                 //$list = $xpath->query("head/meta[@name]");
245                 $list = $xpath->query("//meta[@name]");
246                 foreach ($list as $node) {
247                         $attr = [];
248                         if ($node->attributes->length) {
249                                 foreach ($node->attributes as $attribute) {
250                                         $attr[$attribute->name] = $attribute->value;
251                                 }
252                         }
253
254                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
255
256                         if ($attr["content"] != "") {
257                                 switch (strtolower($attr["name"])) {
258                                         case "fulltitle":
259                                                 $siteinfo["title"] = trim($attr["content"]);
260                                                 break;
261                                         case "description":
262                                                 $siteinfo["text"] = trim($attr["content"]);
263                                                 break;
264                                         case "thumbnail":
265                                                 $siteinfo["image"] = $attr["content"];
266                                                 break;
267                                         case "twitter:image":
268                                                 $siteinfo["image"] = $attr["content"];
269                                                 break;
270                                         case "twitter:image:src":
271                                                 $siteinfo["image"] = $attr["content"];
272                                                 break;
273                                         case "twitter:card":
274                                                 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
275                                                         $siteinfo["type"] = $attr["content"];
276                                                 }
277                                                 break;
278                                         case "twitter:description":
279                                                 $siteinfo["text"] = trim($attr["content"]);
280                                                 break;
281                                         case "twitter:title":
282                                                 $siteinfo["title"] = trim($attr["content"]);
283                                                 break;
284                                         case "dc.title":
285                                                 $siteinfo["title"] = trim($attr["content"]);
286                                                 break;
287                                         case "dc.description":
288                                                 $siteinfo["text"] = trim($attr["content"]);
289                                                 break;
290                                         case "keywords":
291                                                 $keywords = explode(",", $attr["content"]);
292                                                 break;
293                                         case "news_keywords":
294                                                 $keywords = explode(",", $attr["content"]);
295                                                 break;
296                                 }
297                         }
298                         if ($siteinfo["type"] == "summary") {
299                                 $siteinfo["type"] = "link";
300                         }
301                 }
302
303                 if (isset($keywords)) {
304                         $siteinfo["keywords"] = [];
305                         foreach ($keywords as $keyword) {
306                                 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
307                                         $siteinfo["keywords"][] = trim($keyword);
308                                 }
309                         }
310                 }
311
312                 //$list = $xpath->query("head/meta[@property]");
313                 $list = $xpath->query("//meta[@property]");
314                 foreach ($list as $node) {
315                         $attr = [];
316                         if ($node->attributes->length) {
317                                 foreach ($node->attributes as $attribute) {
318                                         $attr[$attribute->name] = $attribute->value;
319                                 }
320                         }
321
322                         $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
323
324                         if ($attr["content"] != "") {
325                                 switch (strtolower($attr["property"])) {
326                                         case "og:image":
327                                                 $siteinfo["image"] = $attr["content"];
328                                                 break;
329                                         case "og:title":
330                                                 $siteinfo["title"] = trim($attr["content"]);
331                                                 break;
332                                         case "og:description":
333                                                 $siteinfo["text"] = trim($attr["content"]);
334                                                 break;
335                                 }
336                         }
337                 }
338
339                 if ((@$siteinfo["image"] == "") && !$no_guessing) {
340                         $list = $xpath->query("//img[@src]");
341                         foreach ($list as $node) {
342                                 $attr = [];
343                                 if ($node->attributes->length) {
344                                         foreach ($node->attributes as $attribute) {
345                                                 $attr[$attribute->name] = $attribute->value;
346                                         }
347                                 }
348
349                                 $src = self::completeUrl($attr["src"], $url);
350                                 $photodata = Image::getInfoFromURL($src);
351
352                                 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
353                                         if ($photodata[0] > 300) {
354                                                 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
355                                                 $photodata[0] = 300;
356                                         }
357                                         if ($photodata[1] > 300) {
358                                                 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
359                                                 $photodata[1] = 300;
360                                         }
361                                         $siteinfo["images"][] = ["src" => $src,
362                                                                         "width" => $photodata[0],
363                                                                         "height" => $photodata[1]];
364                                 }
365                         }
366                 } elseif ($siteinfo["image"] != "") {
367                         $src = self::completeUrl($siteinfo["image"], $url);
368
369                         unset($siteinfo["image"]);
370
371                         $photodata = Image::getInfoFromURL($src);
372
373                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
374                                 $siteinfo["images"][] = ["src" => $src,
375                                                                 "width" => $photodata[0],
376                                                                 "height" => $photodata[1]];
377                         }
378                 }
379
380                 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
381                         $text = "";
382
383                         $list = $xpath->query("//div[@class='article']");
384                         foreach ($list as $node) {
385                                 if (strlen($node->nodeValue) > 40) {
386                                         $text .= " ".trim($node->nodeValue);
387                                 }
388                         }
389
390                         if ($text == "") {
391                                 $list = $xpath->query("//div[@class='content']");
392                                 foreach ($list as $node) {
393                                         if (strlen($node->nodeValue) > 40) {
394                                                 $text .= " ".trim($node->nodeValue);
395                                         }
396                                 }
397                         }
398
399                         // If none text was found then take the paragraph content
400                         if ($text == "") {
401                                 $list = $xpath->query("//p");
402                                 foreach ($list as $node) {
403                                         if (strlen($node->nodeValue) > 40) {
404                                                 $text .= " ".trim($node->nodeValue);
405                                         }
406                                 }
407                         }
408
409                         if ($text != "") {
410                                 $text = trim(str_replace(["\n", "\r"], [" ", " "], $text));
411
412                                 while (strpos($text, "  ")) {
413                                         $text = trim(str_replace("  ", " ", $text));
414                                 }
415
416                                 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
417                         }
418                 }
419
420                 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
421
422                 Addon::callHooks("getsiteinfo", $siteinfo);
423
424                 return($siteinfo);
425         }
426
427         /**
428          * @brief Convert tags from CSV to an array
429          *
430          * @param string $string Tags
431          * @return array with formatted Hashtags
432          */
433         public static function convertTagsToArray($string)
434         {
435                 $arr_tags = str_getcsv($string);
436                 if (count($arr_tags)) {
437                         // add the # sign to every tag
438                         array_walk($arr_tags, ["self", "arrAddHashes"]);
439
440                         return $arr_tags;
441                 }
442         }
443
444         /**
445          * @brief Add a hasht sign to a string
446          *
447          *  This method is used as callback function
448          *
449          * @param string $tag The pure tag name
450          * @param int    $k   Counter for internal use
451          * @return void
452          */
453         private static function arrAddHashes(&$tag, $k)
454         {
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         {
474                 $urlarr = parse_url($url);
475
476                 // If the url does allready have an scheme
477                 // we can stop the process here
478                 if (isset($urlarr["scheme"])) {
479                         return($url);
480                 }
481
482                 $schemearr = parse_url($scheme);
483
484                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
485
486                 if (@$schemearr["port"] != "") {
487                         $complete .= ":".$schemearr["port"];
488                 }
489
490                 if (strpos($urlarr["path"], "/") !== 0) {
491                         $complete .= "/";
492                 }
493
494                 $complete .= $urlarr["path"];
495
496                 if (@$urlarr["query"] != "") {
497                         $complete .= "?".$urlarr["query"];
498                 }
499
500                 if (@$urlarr["fragment"] != "") {
501                         $complete .= "#".$urlarr["fragment"];
502                 }
503
504                 return($complete);
505         }
506 }