]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Merge pull request #9974 from annando/slow-queries
[friendica.git] / src / Util / ParseUrl.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\OEmbed;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Network\HTTPException;
33
34 /**
35  * Get information about a given URL
36  *
37  * Class with methods for extracting certain content from an url
38  */
39 class ParseUrl
40 {
41         const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42         const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
43
44         /**
45          * Maximum number of characters for the description
46          */
47         const MAX_DESC_COUNT = 250;
48
49         /**
50          * Minimum number of characters for the description
51          */
52         const MIN_DESC_COUNT = 100;
53
54         /**
55          * Search for chached embeddable data of an url otherwise fetch it
56          *
57          * @param string $url         The url of the page which should be scraped
58          * @param bool   $no_guessing If true the parse doens't search for
59          *                            preview pictures
60          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
61          *                            to avoid endless loops
62          *
63          * @return array which contains needed data for embedding
64          *    string 'url'      => The url of the parsed page
65          *    string 'type'     => Content type
66          *    string 'title'    => (optional) The title of the content
67          *    string 'text'     => (optional) The description for the content
68          *    string 'image'    => (optional) A preview image of the content (only available if $no_geuessing = false)
69          *    array  'images'   => (optional) Array of preview pictures
70          *    string 'keywords' => (optional) The tags which belong to the content
71          *
72          * @throws HTTPException\InternalServerErrorException
73          * @see   ParseUrl::getSiteinfo() for more information about scraping
74          * embeddable content
75          */
76         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
77         {
78                 if (empty($url)) {
79                         return [
80                                 'url' => '',
81                                 'type' => 'error',
82                         ];
83                 }
84
85                 $urlHash = hash('sha256', $url);
86
87                 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
88                         ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
89                 );
90                 if (!empty($parsed_url['content'])) {
91                         $data = unserialize($parsed_url['content']);
92                         return $data;
93                 }
94
95                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
96
97                 $expires = $data['expires'];
98
99                 unset($data['expires']);
100
101                 DI::dba()->insert(
102                         'parsed_url',
103                         [
104                                 'url_hash' => $urlHash,
105                                 'guessing' => !$no_guessing,
106                                 'oembed'   => $do_oembed,
107                                 'url'      => $url,
108                                 'content'  => serialize($data),
109                                 'created'  => DateTimeFormat::utcNow(),
110                                 'expires'  => $expires,
111                         ],
112                         Database::INSERT_UPDATE
113                 );
114
115                 return $data;
116         }
117
118         /**
119          * Parse a page for embeddable content information
120          *
121          * This method parses to url for meta data which can be used to embed
122          * the content. If available it prioritizes Open Graph meta tags.
123          * If this is not available it uses the twitter cards meta tags.
124          * As fallback it uses standard html elements with meta informations
125          * like \<title\>Awesome Title\</title\> or
126          * \<meta name="description" content="An awesome description"\>
127          *
128          * @param string $url         The url of the page which should be scraped
129          * @param bool   $no_guessing If true the parse doens't search for
130          *                            preview pictures
131          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
132          *                            to avoid endless loops
133          * @param int    $count       Internal counter to avoid endless loops
134          *
135          * @return array which contains needed data for embedding
136          *    string 'url'      => The url of the parsed page
137          *    string 'type'     => Content type (error, link, photo, image, audio, video)
138          *    string 'title'    => (optional) The title of the content
139          *    string 'text'     => (optional) The description for the content
140          *    string 'image'    => (optional) A preview image of the content (only available if $no_guessing = false)
141          *    array  'images'   => (optional) Array of preview pictures
142          *    string 'keywords' => (optional) The tags which belong to the content
143          *
144          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145          * @todo  https://developers.google.com/+/plugins/snippet/
146          * @verbatim
147          * <meta itemprop="name" content="Awesome title">
148          * <meta itemprop="description" content="An awesome description">
149          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
150          *
151          * <body itemscope itemtype="http://schema.org/Product">
152          *   <h1 itemprop="name">Shiny Trinket</h1>
153          *   <img itemprop="image" src="{image-url}" />
154          *   <p itemprop="description">Shiny trinkets are shiny.</p>
155          * </body>
156          * @endverbatim
157          */
158         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
159         {
160                 if (empty($url)) {
161                         return [
162                                 'url' => '',
163                                 'type' => 'error',
164                         ];
165                 }
166
167                 // Check if the URL does contain a scheme
168                 $scheme = parse_url($url, PHP_URL_SCHEME);
169
170                 if ($scheme == '') {
171                         $url = 'http://' . ltrim($url, '/');
172                 }
173
174                 $url = trim($url, "'\"");
175
176                 $url = Network::stripTrackingQueryParams($url);
177
178                 $siteinfo = [
179                         'url' => $url,
180                         'type' => 'link',
181                         'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
182                 ];
183
184                 if ($count > 10) {
185                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
186                         return $siteinfo;
187                 }
188
189                 $curlResult = DI::httpRequest()->get($url);
190                 if (!$curlResult->isSuccess()) {
191                         return $siteinfo;
192                 }
193
194                 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
195
196                 // If the file is too large then exit
197                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
198                         return $siteinfo;
199                 }
200
201                 // Native media type, no need for HTML parsing
202                 $type = $curlResult->getHeader('Content-Type');
203                 if ($type) {
204                         preg_match('#(image|video|audio)/#i', $type, $matches);
205                         if ($matches) {
206                                 $siteinfo['type'] = array_pop($matches);
207                                 return $siteinfo;
208                         }
209                 }
210
211                 // If it isn't a HTML file then exit
212                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
213                         return $siteinfo;
214                 }
215
216                 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
217                         if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
218                                 $maxAge = max(86400, (int)array_pop($matches));
219                                 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
220                         }
221                 }
222
223                 $header = $curlResult->getHeader();
224                 $body = $curlResult->getBody();
225
226                 if ($do_oembed) {
227                         $oembed_data = OEmbed::fetchURL($url);
228
229                         if (!empty($oembed_data->type)) {
230                                 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
231                                         $siteinfo['type'] = $oembed_data->type;
232                                 }
233
234                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
235                                 if ($siteinfo['type'] != 'photo') {
236                                         if (isset($oembed_data->title)) {
237                                                 $siteinfo['title'] = trim($oembed_data->title);
238                                         }
239                                         if (isset($oembed_data->description)) {
240                                                 $siteinfo['text'] = trim($oembed_data->description);
241                                         }
242                                         if (isset($oembed_data->thumbnail_url)) {
243                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
244                                         }
245                                 }
246                         }
247                 }
248
249                 $charset = '';
250                 // Look for a charset, first in headers
251                 // Expected form: Content-Type: text/html; charset=ISO-8859-4
252                 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
253                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
254                 }
255
256                 // Then in body that gets precedence
257                 // Expected forms:
258                 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
259                 // - <meta charset="utf-8">
260                 // - <meta charset=utf-8>
261                 // - <meta charSet="utf-8">
262                 // We escape <style> and <script> tags since they can contain irrelevant charset information
263                 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
264                 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
265                         if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
266                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
267                         }
268                 });
269
270                 $siteinfo['charset'] = $charset;
271
272                 if ($charset && strtoupper($charset) != 'UTF-8') {
273                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
274                         $charset = str_ireplace('latin-1', 'latin1', $charset);
275
276                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
277                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
278                 }
279
280                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
281
282                 $doc = new DOMDocument();
283                 @$doc->loadHTML($body);
284
285                 XML::deleteNode($doc, 'style');
286                 XML::deleteNode($doc, 'script');
287                 XML::deleteNode($doc, 'option');
288                 XML::deleteNode($doc, 'h1');
289                 XML::deleteNode($doc, 'h2');
290                 XML::deleteNode($doc, 'h3');
291                 XML::deleteNode($doc, 'h4');
292                 XML::deleteNode($doc, 'h5');
293                 XML::deleteNode($doc, 'h6');
294                 XML::deleteNode($doc, 'ol');
295                 XML::deleteNode($doc, 'ul');
296
297                 $xpath = new DOMXPath($doc);
298
299                 $list = $xpath->query('//meta[@content]');
300                 foreach ($list as $node) {
301                         $meta_tag = [];
302                         if ($node->attributes->length) {
303                                 foreach ($node->attributes as $attribute) {
304                                         $meta_tag[$attribute->name] = $attribute->value;
305                                 }
306                         }
307
308                         if (@$meta_tag['http-equiv'] == 'refresh') {
309                                 $path = $meta_tag['content'];
310                                 $pathinfo = explode(';', $path);
311                                 $content = '';
312                                 foreach ($pathinfo as $value) {
313                                         if (substr(strtolower($value), 0, 4) == 'url=') {
314                                                 $content = substr($value, 4);
315                                         }
316                                 }
317                                 if ($content != '') {
318                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
319                                         return $siteinfo;
320                                 }
321                         }
322                 }
323
324                 $list = $xpath->query('//title');
325                 if ($list->length > 0) {
326                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
327                 }
328
329                 $list = $xpath->query('//meta[@name]');
330                 foreach ($list as $node) {
331                         $meta_tag = [];
332                         if ($node->attributes->length) {
333                                 foreach ($node->attributes as $attribute) {
334                                         $meta_tag[$attribute->name] = $attribute->value;
335                                 }
336                         }
337
338                         if (empty($meta_tag['content'])) {
339                                 continue;
340                         }
341
342                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
343
344                         switch (strtolower($meta_tag['name'])) {
345                                 case 'fulltitle':
346                                         $siteinfo['title'] = trim($meta_tag['content']);
347                                         break;
348                                 case 'description':
349                                         $siteinfo['text'] = trim($meta_tag['content']);
350                                         break;
351                                 case 'thumbnail':
352                                         $siteinfo['image'] = $meta_tag['content'];
353                                         break;
354                                 case 'twitter:image':
355                                         $siteinfo['image'] = $meta_tag['content'];
356                                         break;
357                                 case 'twitter:image:src':
358                                         $siteinfo['image'] = $meta_tag['content'];
359                                         break;
360                                 case 'twitter:card':
361                                         // Detect photo pages
362                                         if ($meta_tag['content'] == 'summary_large_image') {
363                                                 $siteinfo['type'] = 'photo';
364                                         }
365                                         break;
366                                 case 'twitter:description':
367                                         $siteinfo['text'] = trim($meta_tag['content']);
368                                         break;
369                                 case 'twitter:title':
370                                         $siteinfo['title'] = trim($meta_tag['content']);
371                                         break;
372                                 case 'dc.title':
373                                         $siteinfo['title'] = trim($meta_tag['content']);
374                                         break;
375                                 case 'dc.description':
376                                         $siteinfo['text'] = trim($meta_tag['content']);
377                                         break;
378                                 case 'keywords':
379                                         $keywords = explode(',', $meta_tag['content']);
380                                         break;
381                                 case 'news_keywords':
382                                         $keywords = explode(',', $meta_tag['content']);
383                                         break;
384                         }
385                 }
386
387                 if (isset($keywords)) {
388                         $siteinfo['keywords'] = [];
389                         foreach ($keywords as $keyword) {
390                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
391                                         $siteinfo['keywords'][] = trim($keyword);
392                                 }
393                         }
394                 }
395
396                 $list = $xpath->query('//meta[@property]');
397                 foreach ($list as $node) {
398                         $meta_tag = [];
399                         if ($node->attributes->length) {
400                                 foreach ($node->attributes as $attribute) {
401                                         $meta_tag[$attribute->name] = $attribute->value;
402                                 }
403                         }
404
405                         if (!empty($meta_tag['content'])) {
406                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
407
408                                 switch (strtolower($meta_tag['property'])) {
409                                         case 'og:image':
410                                                 $siteinfo['image'] = $meta_tag['content'];
411                                                 break;
412                                         case 'og:title':
413                                                 $siteinfo['title'] = trim($meta_tag['content']);
414                                                 break;
415                                         case 'og:description':
416                                                 $siteinfo['text'] = trim($meta_tag['content']);
417                                                 break;
418                                 }
419                         }
420                 }
421
422                 // Prevent to have a photo type without an image
423                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
424                         $siteinfo['type'] = 'link';
425                 }
426
427                 if (!empty($siteinfo['image'])) {
428                         $src = self::completeUrl($siteinfo['image'], $url);
429
430                         unset($siteinfo['image']);
431
432                         $photodata = Images::getInfoFromURLCached($src);
433
434                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
435                                 $siteinfo['images'][] = ['src' => $src,
436                                         'width' => $photodata[0],
437                                         'height' => $photodata[1]];
438                         }
439                 }
440
441                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
442                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
443                         $pos = mb_strrpos($siteinfo['text'], '.');
444                         if ($pos > self::MIN_DESC_COUNT) {
445                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
446                         }
447                 }
448
449                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
450
451                 Hook::callAll('getsiteinfo', $siteinfo);
452
453                 return $siteinfo;
454         }
455
456         /**
457          * Convert tags from CSV to an array
458          *
459          * @param string $string Tags
460          * @return array with formatted Hashtags
461          */
462         public static function convertTagsToArray($string)
463         {
464                 $arr_tags = str_getcsv($string);
465                 if (count($arr_tags)) {
466                         // add the # sign to every tag
467                         array_walk($arr_tags, ["self", "arrAddHashes"]);
468
469                         return $arr_tags;
470                 }
471         }
472
473         /**
474          * Add a hasht sign to a string
475          *
476          * This method is used as callback function
477          *
478          * @param string $tag The pure tag name
479          * @param int    $k   Counter for internal use
480          * @return void
481          */
482         private static function arrAddHashes(&$tag, $k)
483         {
484                 $tag = "#" . $tag;
485         }
486
487         /**
488          * Add a scheme to an url
489          *
490          * The src attribute of some html elements (e.g. images)
491          * can miss the scheme so we need to add the correct
492          * scheme
493          *
494          * @param string $url    The url which possibly does have
495          *                       a missing scheme (a link to an image)
496          * @param string $scheme The url with a correct scheme
497          *                       (e.g. the url from the webpage which does contain the image)
498          *
499          * @return string The url with a scheme
500          */
501         private static function completeUrl($url, $scheme)
502         {
503                 $urlarr = parse_url($url);
504
505                 // If the url does allready have an scheme
506                 // we can stop the process here
507                 if (isset($urlarr["scheme"])) {
508                         return($url);
509                 }
510
511                 $schemearr = parse_url($scheme);
512
513                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
514
515                 if (!empty($schemearr["port"])) {
516                         $complete .= ":".$schemearr["port"];
517                 }
518
519                 if (!empty($urlarr["path"])) {
520                         if (strpos($urlarr["path"], "/") !== 0) {
521                                 $complete .= "/";
522                         }
523
524                         $complete .= $urlarr["path"];
525                 }
526
527                 if (!empty($urlarr["query"])) {
528                         $complete .= "?".$urlarr["query"];
529                 }
530
531                 if (!empty($urlarr["fragment"])) {
532                         $complete .= "#".$urlarr["fragment"];
533                 }
534
535                 return($complete);
536         }
537 }