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