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