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