]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Improve help/Config page
[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 (!empty($oembed_data->type)) {
163                                 if (!in_array($oembed_data->type, ["error", "rich", ""])) {
164                                         $siteinfo["type"] = $oembed_data->type;
165                                 }
166
167                                 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
168                                         if (isset($oembed_data->title)) {
169                                                 $siteinfo["title"] = trim($oembed_data->title);
170                                         }
171                                         if (isset($oembed_data->description)) {
172                                                 $siteinfo["text"] = trim($oembed_data->description);
173                                         }
174                                         if (isset($oembed_data->thumbnail_url)) {
175                                                 $siteinfo["image"] = $oembed_data->thumbnail_url;
176                                         }
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 = [];
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"] = trim($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 = [];
250                         if ($node->attributes->length) {
251                                 foreach ($node->attributes as $attribute) {
252                                         $attr[$attribute->name] = $attribute->value;
253                                 }
254                         }
255
256                         if (!empty($attr["content"])) {
257                                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
258
259                                 switch (strtolower($attr["name"])) {
260                                         case "fulltitle":
261                                                 $siteinfo["title"] = trim($attr["content"]);
262                                                 break;
263                                         case "description":
264                                                 $siteinfo["text"] = trim($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"] = trim($attr["content"]);
282                                                 break;
283                                         case "twitter:title":
284                                                 $siteinfo["title"] = trim($attr["content"]);
285                                                 break;
286                                         case "dc.title":
287                                                 $siteinfo["title"] = trim($attr["content"]);
288                                                 break;
289                                         case "dc.description":
290                                                 $siteinfo["text"] = trim($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"] = [];
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 = [];
318                         if ($node->attributes->length) {
319                                 foreach ($node->attributes as $attribute) {
320                                         $attr[$attribute->name] = $attribute->value;
321                                 }
322                         }
323
324                         if (!empty($attr["content"])) {
325                                 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
326
327                                 switch (strtolower($attr["property"])) {
328                                         case "og:image":
329                                                 $siteinfo["image"] = $attr["content"];
330                                                 break;
331                                         case "og:title":
332                                                 $siteinfo["title"] = trim($attr["content"]);
333                                                 break;
334                                         case "og:description":
335                                                 $siteinfo["text"] = trim($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 = [];
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 = Image::getInfoFromURL($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"][] = ["src" => $src,
364                                                                         "width" => $photodata[0],
365                                                                         "height" => $photodata[1]];
366                                 }
367                         }
368                 } elseif (!empty($siteinfo["image"])) {
369                         $src = self::completeUrl($siteinfo["image"], $url);
370
371                         unset($siteinfo["image"]);
372
373                         $photodata = Image::getInfoFromURL($src);
374
375                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
376                                 $siteinfo["images"][] = ["src" => $src,
377                                                                 "width" => $photodata[0],
378                                                                 "height" => $photodata[1]];
379                         }
380                 }
381
382                 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
383                         $text = "";
384
385                         $list = $xpath->query("//div[@class='article']");
386                         foreach ($list as $node) {
387                                 if (strlen($node->nodeValue) > 40) {
388                                         $text .= " ".trim($node->nodeValue);
389                                 }
390                         }
391
392                         if ($text == "") {
393                                 $list = $xpath->query("//div[@class='content']");
394                                 foreach ($list as $node) {
395                                         if (strlen($node->nodeValue) > 40) {
396                                                 $text .= " ".trim($node->nodeValue);
397                                         }
398                                 }
399                         }
400
401                         // If none text was found then take the paragraph content
402                         if ($text == "") {
403                                 $list = $xpath->query("//p");
404                                 foreach ($list as $node) {
405                                         if (strlen($node->nodeValue) > 40) {
406                                                 $text .= " ".trim($node->nodeValue);
407                                         }
408                                 }
409                         }
410
411                         if ($text != "") {
412                                 $text = trim(str_replace(["\n", "\r"], [" ", " "], $text));
413
414                                 while (strpos($text, "  ")) {
415                                         $text = trim(str_replace("  ", " ", $text));
416                                 }
417
418                                 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
419                         }
420                 }
421
422                 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
423
424                 Addon::callHooks("getsiteinfo", $siteinfo);
425
426                 return($siteinfo);
427         }
428
429         /**
430          * @brief Convert tags from CSV to an array
431          *
432          * @param string $string Tags
433          * @return array with formatted Hashtags
434          */
435         public static function convertTagsToArray($string)
436         {
437                 $arr_tags = str_getcsv($string);
438                 if (count($arr_tags)) {
439                         // add the # sign to every tag
440                         array_walk($arr_tags, ["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          * @return void
454          */
455         private static function arrAddHashes(&$tag, $k)
456         {
457                 $tag = "#" . $tag;
458         }
459
460         /**
461          * @brief Add a scheme to an url
462          *
463          * The src attribute of some html elements (e.g. images)
464          * can miss the scheme so we need to add the correct
465          * scheme
466          *
467          * @param string $url    The url which possibly does have
468          *                       a missing scheme (a link to an image)
469          * @param string $scheme The url with a correct scheme
470          *                       (e.g. the url from the webpage which does contain the image)
471          *
472          * @return string The url with a scheme
473          */
474         private static function completeUrl($url, $scheme)
475         {
476                 $urlarr = parse_url($url);
477
478                 // If the url does allready have an scheme
479                 // we can stop the process here
480                 if (isset($urlarr["scheme"])) {
481                         return($url);
482                 }
483
484                 $schemearr = parse_url($scheme);
485
486                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
487
488                 if (@$schemearr["port"] != "") {
489                         $complete .= ":".$schemearr["port"];
490                 }
491
492                 if (strpos($urlarr["path"], "/") !== 0) {
493                         $complete .= "/";
494                 }
495
496                 $complete .= $urlarr["path"];
497
498                 if (@$urlarr["query"] != "") {
499                         $complete .= "?".$urlarr["query"];
500                 }
501
502                 if (@$urlarr["fragment"] != "") {
503                         $complete .= "#".$urlarr["fragment"];
504                 }
505
506                 return($complete);
507         }
508 }