]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Rename "HTTPRequest::curl()" to HTTPRequest::get()
[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);
164                 if (!$curlResult->isSuccess()) {
165                         return $siteinfo;
166                 }
167
168                 // If the file is too large then exit
169                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
170                         return $siteinfo;
171                 }
172
173                 // If it isn't a HTML file then exit
174                 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
175                         return $siteinfo;
176                 }
177
178                 $header = $curlResult->getHeader();
179                 $body = $curlResult->getBody();
180
181                 if ($do_oembed) {
182                         $oembed_data = OEmbed::fetchURL($url);
183
184                         if (!empty($oembed_data->type)) {
185                                 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
186                                         $siteinfo['type'] = $oembed_data->type;
187                                 }
188
189                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
190                                 if ($siteinfo['type'] != 'photo') {
191                                         if (isset($oembed_data->title)) {
192                                                 $siteinfo['title'] = trim($oembed_data->title);
193                                         }
194                                         if (isset($oembed_data->description)) {
195                                                 $siteinfo['text'] = trim($oembed_data->description);
196                                         }
197                                         if (isset($oembed_data->thumbnail_url)) {
198                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
199                                         }
200                                 }
201                         }
202                 }
203
204                 // Fetch the first mentioned charset. Can be in body or header
205                 $charset = '';
206                 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
207                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
208                 }
209
210                 if ($charset && strtoupper($charset) != 'UTF-8') {
211                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
212                         $charset = str_ireplace('latin-1', 'latin1', $charset);
213
214                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
215                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
216                 }
217
218                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
219
220                 $doc = new DOMDocument();
221                 @$doc->loadHTML($body);
222
223                 XML::deleteNode($doc, 'style');
224                 XML::deleteNode($doc, 'script');
225                 XML::deleteNode($doc, 'option');
226                 XML::deleteNode($doc, 'h1');
227                 XML::deleteNode($doc, 'h2');
228                 XML::deleteNode($doc, 'h3');
229                 XML::deleteNode($doc, 'h4');
230                 XML::deleteNode($doc, 'h5');
231                 XML::deleteNode($doc, 'h6');
232                 XML::deleteNode($doc, 'ol');
233                 XML::deleteNode($doc, 'ul');
234
235                 $xpath = new DOMXPath($doc);
236
237                 $list = $xpath->query('//meta[@content]');
238                 foreach ($list as $node) {
239                         $meta_tag = [];
240                         if ($node->attributes->length) {
241                                 foreach ($node->attributes as $attribute) {
242                                         $meta_tag[$attribute->name] = $attribute->value;
243                                 }
244                         }
245
246                         if (@$meta_tag['http-equiv'] == 'refresh') {
247                                 $path = $meta_tag['content'];
248                                 $pathinfo = explode(';', $path);
249                                 $content = '';
250                                 foreach ($pathinfo as $value) {
251                                         if (substr(strtolower($value), 0, 4) == 'url=') {
252                                                 $content = substr($value, 4);
253                                         }
254                                 }
255                                 if ($content != '') {
256                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
257                                         return $siteinfo;
258                                 }
259                         }
260                 }
261
262                 $list = $xpath->query('//title');
263                 if ($list->length > 0) {
264                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
265                 }
266
267                 $list = $xpath->query('//meta[@name]');
268                 foreach ($list as $node) {
269                         $meta_tag = [];
270                         if ($node->attributes->length) {
271                                 foreach ($node->attributes as $attribute) {
272                                         $meta_tag[$attribute->name] = $attribute->value;
273                                 }
274                         }
275
276                         if (empty($meta_tag['content'])) {
277                                 continue;
278                         }
279
280                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
281
282                         switch (strtolower($meta_tag['name'])) {
283                                 case 'fulltitle':
284                                         $siteinfo['title'] = trim($meta_tag['content']);
285                                         break;
286                                 case 'description':
287                                         $siteinfo['text'] = trim($meta_tag['content']);
288                                         break;
289                                 case 'thumbnail':
290                                         $siteinfo['image'] = $meta_tag['content'];
291                                         break;
292                                 case 'twitter:image':
293                                         $siteinfo['image'] = $meta_tag['content'];
294                                         break;
295                                 case 'twitter:image:src':
296                                         $siteinfo['image'] = $meta_tag['content'];
297                                         break;
298                                 case 'twitter:card':
299                                         // Detect photo pages
300                                         if ($meta_tag['content'] == 'summary_large_image') {
301                                                 $siteinfo['type'] = 'photo';
302                                         }
303                                         break;
304                                 case 'twitter:description':
305                                         $siteinfo['text'] = trim($meta_tag['content']);
306                                         break;
307                                 case 'twitter:title':
308                                         $siteinfo['title'] = trim($meta_tag['content']);
309                                         break;
310                                 case 'dc.title':
311                                         $siteinfo['title'] = trim($meta_tag['content']);
312                                         break;
313                                 case 'dc.description':
314                                         $siteinfo['text'] = trim($meta_tag['content']);
315                                         break;
316                                 case 'keywords':
317                                         $keywords = explode(',', $meta_tag['content']);
318                                         break;
319                                 case 'news_keywords':
320                                         $keywords = explode(',', $meta_tag['content']);
321                                         break;
322                         }
323                 }
324
325                 if (isset($keywords)) {
326                         $siteinfo['keywords'] = [];
327                         foreach ($keywords as $keyword) {
328                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
329                                         $siteinfo['keywords'][] = trim($keyword);
330                                 }
331                         }
332                 }
333
334                 $list = $xpath->query('//meta[@property]');
335                 foreach ($list as $node) {
336                         $meta_tag = [];
337                         if ($node->attributes->length) {
338                                 foreach ($node->attributes as $attribute) {
339                                         $meta_tag[$attribute->name] = $attribute->value;
340                                 }
341                         }
342
343                         if (!empty($meta_tag['content'])) {
344                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
345
346                                 switch (strtolower($meta_tag['property'])) {
347                                         case 'og:image':
348                                                 $siteinfo['image'] = $meta_tag['content'];
349                                                 break;
350                                         case 'og:title':
351                                                 $siteinfo['title'] = trim($meta_tag['content']);
352                                                 break;
353                                         case 'og:description':
354                                                 $siteinfo['text'] = trim($meta_tag['content']);
355                                                 break;
356                                 }
357                         }
358                 }
359
360                 // Prevent to have a photo type without an image
361                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
362                         $siteinfo['type'] = 'link';
363                 }
364
365                 if (!empty($siteinfo['image'])) {
366                         $src = self::completeUrl($siteinfo['image'], $url);
367
368                         unset($siteinfo['image']);
369
370                         $photodata = Images::getInfoFromURLCached($src);
371
372                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
373                                 $siteinfo['images'][] = ['src' => $src,
374                                         'width' => $photodata[0],
375                                         'height' => $photodata[1]];
376                         }
377                 }
378
379                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
380                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
381                         $pos = mb_strrpos($siteinfo['text'], '.');
382                         if ($pos > self::MIN_DESC_COUNT) {
383                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
384                         }
385                 }
386
387                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
388
389                 Hook::callAll('getsiteinfo', $siteinfo);
390
391                 return $siteinfo;
392         }
393
394         /**
395          * Convert tags from CSV to an array
396          *
397          * @param string $string Tags
398          * @return array with formatted Hashtags
399          */
400         public static function convertTagsToArray($string)
401         {
402                 $arr_tags = str_getcsv($string);
403                 if (count($arr_tags)) {
404                         // add the # sign to every tag
405                         array_walk($arr_tags, ["self", "arrAddHashes"]);
406
407                         return $arr_tags;
408                 }
409         }
410
411         /**
412          * Add a hasht sign to a string
413          *
414          * This method is used as callback function
415          *
416          * @param string $tag The pure tag name
417          * @param int    $k   Counter for internal use
418          * @return void
419          */
420         private static function arrAddHashes(&$tag, $k)
421         {
422                 $tag = "#" . $tag;
423         }
424
425         /**
426          * Add a scheme to an url
427          *
428          * The src attribute of some html elements (e.g. images)
429          * can miss the scheme so we need to add the correct
430          * scheme
431          *
432          * @param string $url    The url which possibly does have
433          *                       a missing scheme (a link to an image)
434          * @param string $scheme The url with a correct scheme
435          *                       (e.g. the url from the webpage which does contain the image)
436          *
437          * @return string The url with a scheme
438          */
439         private static function completeUrl($url, $scheme)
440         {
441                 $urlarr = parse_url($url);
442
443                 // If the url does allready have an scheme
444                 // we can stop the process here
445                 if (isset($urlarr["scheme"])) {
446                         return($url);
447                 }
448
449                 $schemearr = parse_url($scheme);
450
451                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
452
453                 if (!empty($schemearr["port"])) {
454                         $complete .= ":".$schemearr["port"];
455                 }
456
457                 if (!empty($urlarr["path"])) {
458                         if (strpos($urlarr["path"], "/") !== 0) {
459                                 $complete .= "/";
460                         }
461
462                         $complete .= $urlarr["path"];
463                 }
464
465                 if (!empty($urlarr["query"])) {
466                         $complete .= "?".$urlarr["query"];
467                 }
468
469                 if (!empty($urlarr["fragment"])) {
470                         $complete .= "#".$urlarr["fragment"];
471                 }
472
473                 return($complete);
474         }
475 }