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