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