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