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