]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Don't guess the site info / restrict the description length
[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 DOMDocument;
9 use DOMXPath;
10 use Friendica\Content\OEmbed;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Database\DBA;
14
15 /**
16  * @brief Class with methods for extracting certain content from an url
17  */
18 class ParseUrl
19 {
20         /**
21          * Maximum number of characters for the description
22          */
23         const MAX_DESC_COUNT = 250;
24
25         /**
26          * Minimum number of characters for the description
27          */
28         const MIN_DESC_COUNT = 100;
29
30         /**
31          * @brief Search for chached embeddable data of an url otherwise fetch it
32          *
33          * @param string $url         The url of the page which should be scraped
34          * @param bool   $no_guessing If true the parse doens't search for
35          *                            preview pictures
36          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
37          *                            to avoid endless loops
38          *
39          * @return array which contains needed data for embedding
40          *    string 'url' => The url of the parsed page
41          *    string 'type' => Content type
42          *    string 'title' => The title of the content
43          *    string 'text' => The description for the content
44          *    string 'image' => A preview image of the content (only available
45          *                if $no_geuessing = false
46          *    array'images' = Array of preview pictures
47          *    string 'keywords' => The tags which belong to the content
48          *
49          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50          * @see   ParseUrl::getSiteinfo() for more information about scraping
51          * embeddable content
52          */
53         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
54         {
55                 if ($url == "") {
56                         return false;
57                 }
58
59                 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
60                         ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
61                 );
62                 if (!empty($parsed_url['content'])) {
63                         $data = unserialize($parsed_url['content']);
64                         return $data;
65                 }
66
67                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
68
69                 DBA::insert(
70                         'parsed_url',
71                         [
72                                 'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
73                                 'oembed' => $do_oembed, 'content' => serialize($data),
74                                 'created' => DateTimeFormat::utcNow()
75                         ],
76                         true
77                 );
78
79                 return $data;
80         }
81
82         /**
83          * @brief Parse a page for embeddable content information
84          *
85          * This method parses to url for meta data which can be used to embed
86          * the content. If available it prioritizes Open Graph meta tags.
87          * If this is not available it uses the twitter cards meta tags.
88          * As fallback it uses standard html elements with meta informations
89          * like \<title\>Awesome Title\</title\> or
90          * \<meta name="description" content="An awesome description"\>
91          *
92          * @param string $url         The url of the page which should be scraped
93          * @param bool   $no_guessing If true the parse doens't search for
94          *                            preview pictures
95          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
96          *                            to avoid endless loops
97          * @param int    $count       Internal counter to avoid endless loops
98          *
99          * @return array which contains needed data for embedding
100          *    string 'url' => The url of the parsed page
101          *    string 'type' => Content type
102          *    string 'title' => The title of the content
103          *    string 'text' => The description for the content
104          *    string 'image' => A preview image of the content (only available
105          *                if $no_geuessing = false
106          *    array'images' = Array of preview pictures
107          *    string 'keywords' => The tags which belong to the content
108          *
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          * @todo  https://developers.google.com/+/plugins/snippet/
111          * @verbatim
112          * <meta itemprop="name" content="Awesome title">
113          * <meta itemprop="description" content="An awesome description">
114          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
115          *
116          * <body itemscope itemtype="http://schema.org/Product">
117          *   <h1 itemprop="name">Shiny Trinket</h1>
118          *   <img itemprop="image" src="{image-url}" />
119          *   <p itemprop="description">Shiny trinkets are shiny.</p>
120          * </body>
121          * @endverbatim
122          */
123         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
124         {
125                 $siteinfo = [];
126
127                 // Check if the URL does contain a scheme
128                 $scheme = parse_url($url, PHP_URL_SCHEME);
129
130                 if ($scheme == '') {
131                         $url = 'http://' . trim($url, '/');
132                 }
133
134                 if ($count > 10) {
135                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
136                         return $siteinfo;
137                 }
138
139                 $url = trim($url, "'");
140                 $url = trim($url, '"');
141
142                 $url = Network::stripTrackingQueryParams($url);
143
144                 $siteinfo['url'] = $url;
145                 $siteinfo['type'] = 'link';
146
147                 $curlResult = Network::curl($url);
148                 if (!$curlResult->isSuccess()) {
149                         return $siteinfo;
150                 }
151
152                 // If the file is too large then exit
153                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
154                         return $siteinfo;
155                 }
156
157                 // If it isn't a HTML file then exit
158                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
159                         return $siteinfo;
160                 }
161
162                 $header = $curlResult->getHeader();
163                 $body = $curlResult->getBody();
164
165                 if ($do_oembed) {
166                         $oembed_data = OEmbed::fetchURL($url);
167
168                         if (!empty($oembed_data->type)) {
169                                 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
170                                         $siteinfo['type'] = $oembed_data->type;
171                                 }
172
173                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
174                                 if ($siteinfo['type'] != 'photo') {
175                                         if (isset($oembed_data->title)) {
176                                                 $siteinfo['title'] = trim($oembed_data->title);
177                                         }
178                                         if (isset($oembed_data->description)) {
179                                                 $siteinfo['text'] = trim($oembed_data->description);
180                                         }
181                                         if (isset($oembed_data->thumbnail_url)) {
182                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
183                                         }
184                                 }
185                         }
186                 }
187
188                 // Fetch the first mentioned charset. Can be in body or header
189                 $charset = '';
190                 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
191                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
192                 }
193
194                 if ($charset && strtoupper($charset) != 'UTF-8') {
195                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
196                         $charset = str_ireplace('latin-1', 'latin1', $charset);
197
198                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
199                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
200                 }
201
202                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
203
204                 $doc = new DOMDocument();
205                 @$doc->loadHTML($body);
206
207                 XML::deleteNode($doc, 'style');
208                 XML::deleteNode($doc, 'script');
209                 XML::deleteNode($doc, 'option');
210                 XML::deleteNode($doc, 'h1');
211                 XML::deleteNode($doc, 'h2');
212                 XML::deleteNode($doc, 'h3');
213                 XML::deleteNode($doc, 'h4');
214                 XML::deleteNode($doc, 'h5');
215                 XML::deleteNode($doc, 'h6');
216                 XML::deleteNode($doc, 'ol');
217                 XML::deleteNode($doc, 'ul');
218
219                 $xpath = new DOMXPath($doc);
220
221                 $list = $xpath->query('//meta[@content]');
222                 foreach ($list as $node) {
223                         $meta_tag = [];
224                         if ($node->attributes->length) {
225                                 foreach ($node->attributes as $attribute) {
226                                         $meta_tag[$attribute->name] = $attribute->value;
227                                 }
228                         }
229
230                         if (@$meta_tag['http-equiv'] == 'refresh') {
231                                 $path = $meta_tag['content'];
232                                 $pathinfo = explode(';', $path);
233                                 $content = '';
234                                 foreach ($pathinfo as $value) {
235                                         if (substr(strtolower($value), 0, 4) == 'url=') {
236                                                 $content = substr($value, 4);
237                                         }
238                                 }
239                                 if ($content != '') {
240                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
241                                         return $siteinfo;
242                                 }
243                         }
244                 }
245
246                 $list = $xpath->query('//title');
247                 if ($list->length > 0) {
248                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
249                 }
250
251                 $list = $xpath->query('//meta[@name]');
252                 foreach ($list as $node) {
253                         $meta_tag = [];
254                         if ($node->attributes->length) {
255                                 foreach ($node->attributes as $attribute) {
256                                         $meta_tag[$attribute->name] = $attribute->value;
257                                 }
258                         }
259
260                         if (empty($meta_tag['content'])) {
261                                 continue;
262                         }
263
264                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
265
266                         switch (strtolower($meta_tag['name'])) {
267                                 case 'fulltitle':
268                                         $siteinfo['title'] = trim($meta_tag['content']);
269                                         break;
270                                 case 'description':
271                                         $siteinfo['text'] = trim($meta_tag['content']);
272                                         break;
273                                 case 'thumbnail':
274                                         $siteinfo['image'] = $meta_tag['content'];
275                                         break;
276                                 case 'twitter:image':
277                                         $siteinfo['image'] = $meta_tag['content'];
278                                         break;
279                                 case 'twitter:image:src':
280                                         $siteinfo['image'] = $meta_tag['content'];
281                                         break;
282                                 case 'twitter:card':
283                                         // Detect photo pages
284                                         if ($meta_tag['content'] == 'summary_large_image') {
285                                                 $siteinfo['type'] = 'photo';
286                                         }
287                                         break;
288                                 case 'twitter:description':
289                                         $siteinfo['text'] = trim($meta_tag['content']);
290                                         break;
291                                 case 'twitter:title':
292                                         $siteinfo['title'] = trim($meta_tag['content']);
293                                         break;
294                                 case 'dc.title':
295                                         $siteinfo['title'] = trim($meta_tag['content']);
296                                         break;
297                                 case 'dc.description':
298                                         $siteinfo['text'] = trim($meta_tag['content']);
299                                         break;
300                                 case 'keywords':
301                                         $keywords = explode(',', $meta_tag['content']);
302                                         break;
303                                 case 'news_keywords':
304                                         $keywords = explode(',', $meta_tag['content']);
305                                         break;
306                         }
307                 }
308
309                 if (isset($keywords)) {
310                         $siteinfo['keywords'] = [];
311                         foreach ($keywords as $keyword) {
312                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
313                                         $siteinfo['keywords'][] = trim($keyword);
314                                 }
315                         }
316                 }
317
318                 $list = $xpath->query('//meta[@property]');
319                 foreach ($list as $node) {
320                         $meta_tag = [];
321                         if ($node->attributes->length) {
322                                 foreach ($node->attributes as $attribute) {
323                                         $meta_tag[$attribute->name] = $attribute->value;
324                                 }
325                         }
326
327                         if (!empty($meta_tag['content'])) {
328                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
329
330                                 switch (strtolower($meta_tag['property'])) {
331                                         case 'og:image':
332                                                 $siteinfo['image'] = $meta_tag['content'];
333                                                 break;
334                                         case 'og:title':
335                                                 $siteinfo['title'] = trim($meta_tag['content']);
336                                                 break;
337                                         case 'og:description':
338                                                 $siteinfo['text'] = trim($meta_tag['content']);
339                                                 break;
340                                 }
341                         }
342                 }
343
344                 // Prevent to have a photo type without an image
345                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
346                         $siteinfo['type'] = 'link';
347                 }
348
349                 if (!empty($siteinfo['image'])) {
350                         $src = self::completeUrl($siteinfo['image'], $url);
351
352                         unset($siteinfo['image']);
353
354                         $photodata = Images::getInfoFromURLCached($src);
355
356                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
357                                 $siteinfo['images'][] = ['src' => $src,
358                                         'width' => $photodata[0],
359                                         'height' => $photodata[1]];
360                         }
361                 }
362
363                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
364                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
365                         $pos = mb_strrpos($siteinfo['text'], '.');
366                         if ($pos > self::MIN_DESC_COUNT) {
367                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
368                         }
369                 }
370
371                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
372
373                 Hook::callAll('getsiteinfo', $siteinfo);
374
375                 return $siteinfo;
376         }
377
378         /**
379          * @brief Convert tags from CSV to an array
380          *
381          * @param string $string Tags
382          * @return array with formatted Hashtags
383          */
384         public static function convertTagsToArray($string)
385         {
386                 $arr_tags = str_getcsv($string);
387                 if (count($arr_tags)) {
388                         // add the # sign to every tag
389                         array_walk($arr_tags, ["self", "arrAddHashes"]);
390
391                         return $arr_tags;
392                 }
393         }
394
395         /**
396          * @brief Add a hasht sign to a string
397          *
398          *  This method is used as callback function
399          *
400          * @param string $tag The pure tag name
401          * @param int    $k   Counter for internal use
402          * @return void
403          */
404         private static function arrAddHashes(&$tag, $k)
405         {
406                 $tag = "#" . $tag;
407         }
408
409         /**
410          * @brief Add a scheme to an url
411          *
412          * The src attribute of some html elements (e.g. images)
413          * can miss the scheme so we need to add the correct
414          * scheme
415          *
416          * @param string $url    The url which possibly does have
417          *                       a missing scheme (a link to an image)
418          * @param string $scheme The url with a correct scheme
419          *                       (e.g. the url from the webpage which does contain the image)
420          *
421          * @return string The url with a scheme
422          */
423         private static function completeUrl($url, $scheme)
424         {
425                 $urlarr = parse_url($url);
426
427                 // If the url does allready have an scheme
428                 // we can stop the process here
429                 if (isset($urlarr["scheme"])) {
430                         return($url);
431                 }
432
433                 $schemearr = parse_url($scheme);
434
435                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
436
437                 if (!empty($schemearr["port"])) {
438                         $complete .= ":".$schemearr["port"];
439                 }
440
441                 if (!empty($urlarr["path"])) {
442                         if (strpos($urlarr["path"], "/") !== 0) {
443                                 $complete .= "/";
444                         }
445
446                         $complete .= $urlarr["path"];
447                 }
448
449                 if (!empty($urlarr["query"])) {
450                         $complete .= "?".$urlarr["query"];
451                 }
452
453                 if (!empty($urlarr["fragment"])) {
454                         $complete .= "#".$urlarr["fragment"];
455                 }
456
457                 return($complete);
458         }
459 }