]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Fix PHPDoc comments project-wide
[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 use Friendica\Object\Image;
15
16 /**
17  * @brief Class with methods for extracting certain content from an url
18  */
19 class ParseUrl
20 {
21         /**
22          * @brief Search for chached embeddable data of an url otherwise fetch it
23          *
24          * @param string $url         The url of the page which should be scraped
25          * @param bool   $no_guessing If true the parse doens't search for
26          *                            preview pictures
27          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
28          *                            to avoid endless loops
29          *
30          * @return array which contains needed data for embedding
31          *    string 'url' => The url of the parsed page
32          *    string 'type' => Content type
33          *    string 'title' => The title of the content
34          *    string 'text' => The description for the content
35          *    string 'image' => A preview image of the content (only available
36          *                if $no_geuessing = false
37          *    array'images' = Array of preview pictures
38          *    string 'keywords' => The tags which belong to the content
39          *
40          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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' => Strings::normaliseLink($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' => Strings::normaliseLink($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         /**
74          * @brief Parse a page for embeddable content information
75          *
76          * This method parses to url for meta data which can be used to embed
77          * the content. If available it prioritizes Open Graph meta tags.
78          * If this is not available it uses the twitter cards meta tags.
79          * As fallback it uses standard html elements with meta informations
80          * like \<title\>Awesome Title\</title\> or
81          * \<meta name="description" content="An awesome description"\>
82          *
83          * @param string $url         The url of the page which should be scraped
84          * @param bool   $no_guessing If true the parse doens't search for
85          *                            preview pictures
86          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
87          *                            to avoid endless loops
88          * @param int    $count       Internal counter to avoid endless loops
89          *
90          * @return array which contains needed data for embedding
91          *    string 'url' => The url of the parsed page
92          *    string 'type' => Content type
93          *    string 'title' => The title of the content
94          *    string 'text' => The description for the content
95          *    string 'image' => A preview image of the content (only available
96          *                if $no_geuessing = false
97          *    array'images' = Array of preview pictures
98          *    string 'keywords' => The tags which belong to the content
99          *
100          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101          * @todo  https://developers.google.com/+/plugins/snippet/
102          * @verbatim
103          * <meta itemprop="name" content="Awesome title">
104          * <meta itemprop="description" content="An awesome description">
105          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
106          *
107          * <body itemscope itemtype="http://schema.org/Product">
108          *   <h1 itemprop="name">Shiny Trinket</h1>
109          *   <img itemprop="image" src="{image-url}" />
110          *   <p itemprop="description">Shiny trinkets are shiny.</p>
111          * </body>
112          * @endverbatim
113          */
114         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
115         {
116                 $a = \get_app();
117
118                 $siteinfo = [];
119
120                 // Check if the URL does contain a scheme
121                 $scheme = parse_url($url, PHP_URL_SCHEME);
122
123                 if ($scheme == '') {
124                         $url = 'http://' . trim($url, '/');
125                 }
126
127                 if ($count > 10) {
128                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
129                         return $siteinfo;
130                 }
131
132                 $url = trim($url, "'");
133                 $url = trim($url, '"');
134
135                 $url = Network::stripTrackingQueryParams($url);
136
137                 $siteinfo['url'] = $url;
138                 $siteinfo['type'] = 'link';
139
140                 $curlResult = Network::curl($url);
141                 if (!$curlResult->isSuccess()) {
142                         return $siteinfo;
143                 }
144
145                 // If the file is too large then exit
146                 if (defaults($curlResult->getInfo(), 'download_content_length', 0) > 1000000) {
147                         return $siteinfo;
148                 }
149
150                 // If it isn't a HTML file then exit
151                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
152                         return $siteinfo;
153                 }
154
155                 $header = $curlResult->getHeader();
156                 $body = $curlResult->getBody();
157
158                 if ($do_oembed) {
159                         $oembed_data = OEmbed::fetchURL($url);
160
161                         if (!empty($oembed_data->type)) {
162                                 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
163                                         $siteinfo['type'] = $oembed_data->type;
164                                 }
165
166                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
167                                 if ($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 && strtoupper($charset) != 'UTF-8') {
188                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
189                         $charset = str_ireplace('latin-1', 'latin1', $charset);
190
191                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
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                         $meta_tag = [];
217                         if ($node->attributes->length) {
218                                 foreach ($node->attributes as $attribute) {
219                                         $meta_tag[$attribute->name] = $attribute->value;
220                                 }
221                         }
222
223                         if (@$meta_tag['http-equiv'] == 'refresh') {
224                                 $path = $meta_tag['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('//meta[@name]');
245                 foreach ($list as $node) {
246                         $meta_tag = [];
247                         if ($node->attributes->length) {
248                                 foreach ($node->attributes as $attribute) {
249                                         $meta_tag[$attribute->name] = $attribute->value;
250                                 }
251                         }
252
253                         if (empty($meta_tag['content'])) {
254                                 continue;
255                         }
256
257                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
258
259                         switch (strtolower($meta_tag['name'])) {
260                                 case 'fulltitle':
261                                         $siteinfo['title'] = trim($meta_tag['content']);
262                                         break;
263                                 case 'description':
264                                         $siteinfo['text'] = trim($meta_tag['content']);
265                                         break;
266                                 case 'thumbnail':
267                                         $siteinfo['image'] = $meta_tag['content'];
268                                         break;
269                                 case 'twitter:image':
270                                         $siteinfo['image'] = $meta_tag['content'];
271                                         break;
272                                 case 'twitter:image:src':
273                                         $siteinfo['image'] = $meta_tag['content'];
274                                         break;
275                                 case 'twitter:card':
276                                         // Detect photo pages
277                                         if ($meta_tag['content'] == 'summary_large_image') {
278                                                 $siteinfo['type'] = 'photo';
279                                         }
280                                         break;
281                                 case 'twitter:description':
282                                         $siteinfo['text'] = trim($meta_tag['content']);
283                                         break;
284                                 case 'twitter:title':
285                                         $siteinfo['title'] = trim($meta_tag['content']);
286                                         break;
287                                 case 'dc.title':
288                                         $siteinfo['title'] = trim($meta_tag['content']);
289                                         break;
290                                 case 'dc.description':
291                                         $siteinfo['text'] = trim($meta_tag['content']);
292                                         break;
293                                 case 'keywords':
294                                         $keywords = explode(',', $meta_tag['content']);
295                                         break;
296                                 case 'news_keywords':
297                                         $keywords = explode(',', $meta_tag['content']);
298                                         break;
299                         }
300                 }
301
302                 if (isset($keywords)) {
303                         $siteinfo['keywords'] = [];
304                         foreach ($keywords as $keyword) {
305                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
306                                         $siteinfo['keywords'][] = trim($keyword);
307                                 }
308                         }
309                 }
310
311                 $list = $xpath->query('//meta[@property]');
312                 foreach ($list as $node) {
313                         $meta_tag = [];
314                         if ($node->attributes->length) {
315                                 foreach ($node->attributes as $attribute) {
316                                         $meta_tag[$attribute->name] = $attribute->value;
317                                 }
318                         }
319
320                         if (!empty($meta_tag['content'])) {
321                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
322
323                                 switch (strtolower($meta_tag['property'])) {
324                                         case 'og:image':
325                                                 $siteinfo['image'] = $meta_tag['content'];
326                                                 break;
327                                         case 'og:title':
328                                                 $siteinfo['title'] = trim($meta_tag['content']);
329                                                 break;
330                                         case 'og:description':
331                                                 $siteinfo['text'] = trim($meta_tag['content']);
332                                                 break;
333                                 }
334                         }
335                 }
336
337                 // Prevent to have a photo type without an image
338                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
339                         $siteinfo['type'] = 'link';
340                 }
341
342                 if (empty($siteinfo['image']) && !$no_guessing) {
343                         $list = $xpath->query('//img[@src]');
344                         foreach ($list as $node) {
345                                 $img_tag = [];
346                                 if ($node->attributes->length) {
347                                         foreach ($node->attributes as $attribute) {
348                                                 $img_tag[$attribute->name] = $attribute->value;
349                                         }
350                                 }
351
352                                 $src = self::completeUrl($img_tag['src'], $url);
353                                 $photodata = Image::getInfoFromURL($src);
354
355                                 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
356                                         if ($photodata[0] > 300) {
357                                                 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
358                                                 $photodata[0] = 300;
359                                         }
360                                         if ($photodata[1] > 300) {
361                                                 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
362                                                 $photodata[1] = 300;
363                                         }
364                                         $siteinfo['images'][] = [
365                                                 'src'    => $src,
366                                                 'width'  => $photodata[0],
367                                                 'height' => $photodata[1]
368                                         ];
369                                 }
370                         }
371                 } elseif (!empty($siteinfo['image'])) {
372                         $src = self::completeUrl($siteinfo['image'], $url);
373
374                         unset($siteinfo['image']);
375
376                         $photodata = Image::getInfoFromURL($src);
377
378                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
379                                 $siteinfo['images'][] = ['src' => $src,
380                                         'width' => $photodata[0],
381                                         'height' => $photodata[1]];
382                         }
383                 }
384
385                 if ((@$siteinfo['text'] == '') && (@$siteinfo['title'] != '') && !$no_guessing) {
386                         $text = '';
387
388                         $list = $xpath->query('//div[@class="article"]');
389                         foreach ($list as $node) {
390                                 if (strlen($node->nodeValue) > 40) {
391                                         $text .= ' ' . trim($node->nodeValue);
392                                 }
393                         }
394
395                         if ($text == '') {
396                                 $list = $xpath->query('//div[@class="content"]');
397                                 foreach ($list as $node) {
398                                         if (strlen($node->nodeValue) > 40) {
399                                                 $text .= ' ' . trim($node->nodeValue);
400                                         }
401                                 }
402                         }
403
404                         // If none text was found then take the paragraph content
405                         if ($text == '') {
406                                 $list = $xpath->query('//p');
407                                 foreach ($list as $node) {
408                                         if (strlen($node->nodeValue) > 40) {
409                                                 $text .= ' ' . trim($node->nodeValue);
410                                         }
411                                 }
412                         }
413
414                         if ($text != '') {
415                                 $text = trim(str_replace(["\n", "\r"], [' ', ' '], $text));
416
417                                 while (strpos($text, '  ')) {
418                                         $text = trim(str_replace('  ', ' ', $text));
419                                 }
420
421                                 $siteinfo['text'] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, 'UTF-8') . '...');
422                         }
423                 }
424
425                 Logger::log('Siteinfo for ' . $url . ' ' . print_r($siteinfo, true), Logger::DEBUG);
426
427                 Hook::callAll('getsiteinfo', $siteinfo);
428
429                 return $siteinfo;
430         }
431
432         /**
433          * @brief Convert tags from CSV to an array
434          *
435          * @param string $string Tags
436          * @return array with formatted Hashtags
437          */
438         public static function convertTagsToArray($string)
439         {
440                 $arr_tags = str_getcsv($string);
441                 if (count($arr_tags)) {
442                         // add the # sign to every tag
443                         array_walk($arr_tags, ["self", "arrAddHashes"]);
444
445                         return $arr_tags;
446                 }
447         }
448
449         /**
450          * @brief Add a hasht sign to a string
451          *
452          *  This method is used as callback function
453          *
454          * @param string $tag The pure tag name
455          * @param int    $k   Counter for internal use
456          * @return void
457          */
458         private static function arrAddHashes(&$tag, $k)
459         {
460                 $tag = "#" . $tag;
461         }
462
463         /**
464          * @brief Add a scheme to an url
465          *
466          * The src attribute of some html elements (e.g. images)
467          * can miss the scheme so we need to add the correct
468          * scheme
469          *
470          * @param string $url    The url which possibly does have
471          *                       a missing scheme (a link to an image)
472          * @param string $scheme The url with a correct scheme
473          *                       (e.g. the url from the webpage which does contain the image)
474          *
475          * @return string The url with a scheme
476          */
477         private static function completeUrl($url, $scheme)
478         {
479                 $urlarr = parse_url($url);
480
481                 // If the url does allready have an scheme
482                 // we can stop the process here
483                 if (isset($urlarr["scheme"])) {
484                         return($url);
485                 }
486
487                 $schemearr = parse_url($scheme);
488
489                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
490
491                 if (!empty($schemearr["port"])) {
492                         $complete .= ":".$schemearr["port"];
493                 }
494
495                 if (!empty($urlarr["path"])) {
496                         if (strpos($urlarr["path"], "/") !== 0) {
497                                 $complete .= "/";
498                         }
499
500                         $complete .= $urlarr["path"];
501                 }
502
503                 if (!empty($urlarr["query"])) {
504                         $complete .= "?".$urlarr["query"];
505                 }
506
507                 if (!empty($urlarr["fragment"])) {
508                         $complete .= "#".$urlarr["fragment"];
509                 }
510
511                 return($complete);
512         }
513 }