]> git.mxchange.org Git - friendica.git/blobdiff - src/Util/ParseUrl.php
Move PConfig::get() to DI::pConfig()->get()
[friendica.git] / src / Util / ParseUrl.php
index 24089b9cbd2a92bb33c22fe4e41ee3b501987cff..569136e6d13da5b67ebfd16f94a7823747326f45 100644 (file)
@@ -8,25 +8,33 @@ namespace Friendica\Util;
 use DOMDocument;
 use DOMXPath;
 use Friendica\Content\OEmbed;
-use Friendica\Core\Addon;
+use Friendica\Core\Hook;
+use Friendica\Core\Logger;
 use Friendica\Database\DBA;
-use Friendica\Object\Image;
-
-require_once 'include/dba.php';
 
 /**
  * @brief Class with methods for extracting certain content from an url
  */
 class ParseUrl
 {
+       /**
+        * Maximum number of characters for the description
+        */
+       const MAX_DESC_COUNT = 250;
+
+       /**
+        * Minimum number of characters for the description
+        */
+       const MIN_DESC_COUNT = 100;
+
        /**
         * @brief Search for chached embeddable data of an url otherwise fetch it
         *
         * @param string $url         The url of the page which should be scraped
-        * @param bool $no_guessing If true the parse doens't search for
-        *                          preview pictures
-        * @param bool $do_oembed   The false option is used by the function fetch_oembed()
-        *                          to avoid endless loops
+        * @param bool   $no_guessing If true the parse doens't search for
+        *                            preview pictures
+        * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
+        *                            to avoid endless loops
         *
         * @return array which contains needed data for embedding
         *    string 'url' => The url of the parsed page
@@ -38,7 +46,8 @@ class ParseUrl
         *    array'images' = Array of preview pictures
         *    string 'keywords' => The tags which belong to the content
         *
-        * @see ParseUrl::getSiteinfo() for more information about scraping
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @see   ParseUrl::getSiteinfo() for more information about scraping
         * embeddable content
         */
        public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
@@ -48,7 +57,7 @@ class ParseUrl
                }
 
                $parsed_url = DBA::selectFirst('parsed_url', ['content'],
-                       ['url' => normalise_link($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
+                       ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
                );
                if (!empty($parsed_url['content'])) {
                        $data = unserialize($parsed_url['content']);
@@ -60,7 +69,7 @@ class ParseUrl
                DBA::insert(
                        'parsed_url',
                        [
-                               'url' => normalise_link($url), 'guessing' => !$no_guessing,
+                               'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
                                'oembed' => $do_oembed, 'content' => serialize($data),
                                'created' => DateTimeFormat::utcNow()
                        ],
@@ -69,6 +78,7 @@ class ParseUrl
 
                return $data;
        }
+
        /**
         * @brief Parse a page for embeddable content information
         *
@@ -80,11 +90,11 @@ class ParseUrl
         * \<meta name="description" content="An awesome description"\>
         *
         * @param string $url         The url of the page which should be scraped
-        * @param bool $no_guessing If true the parse doens't search for
-        *                          preview pictures
-        * @param bool $do_oembed   The false option is used by the function fetch_oembed()
-        *                          to avoid endless loops
-        * @param int $count       Internal counter to avoid endless loops
+        * @param bool   $no_guessing If true the parse doens't search for
+        *                            preview pictures
+        * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
+        *                            to avoid endless loops
+        * @param int    $count       Internal counter to avoid endless loops
         *
         * @return array which contains needed data for embedding
         *    string 'url' => The url of the parsed page
@@ -96,7 +106,8 @@ class ParseUrl
         *    array'images' = Array of preview pictures
         *    string 'keywords' => The tags which belong to the content
         *
-        * @todo https://developers.google.com/+/plugins/snippet/
+        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @todo  https://developers.google.com/+/plugins/snippet/
         * @verbatim
         * <meta itemprop="name" content="Awesome title">
         * <meta itemprop="description" content="An awesome description">
@@ -111,8 +122,6 @@ class ParseUrl
         */
        public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
        {
-               $a = get_app();
-
                $siteinfo = [];
 
                // Check if the URL does contain a scheme
@@ -123,7 +132,7 @@ class ParseUrl
                }
 
                if ($count > 10) {
-                       logger('Endless loop detected for ' . $url, LOGGER_DEBUG);
+                       Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
                        return $siteinfo;
                }
 
@@ -141,7 +150,7 @@ class ParseUrl
                }
 
                // If the file is too large then exit
-               if (defaults($curlResult->getInfo(), 'download_content_length', 0) > 1000000) {
+               if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
                        return $siteinfo;
                }
 
@@ -182,12 +191,11 @@ class ParseUrl
                        $charset = trim(trim(trim(array_pop($matches)), ';,'));
                }
 
-               if ($charset == '') {
-                       $charset = 'utf-8';
-               }
+               if ($charset && strtoupper($charset) != 'UTF-8') {
+                       // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
+                       $charset = str_ireplace('latin-1', 'latin1', $charset);
 
-               if (($charset != '') && (strtoupper($charset) != 'UTF-8')) {
-                       logger('detected charset ' . $charset, LOGGER_DEBUG);
+                       Logger::log('detected charset ' . $charset, Logger::DEBUG);
                        $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
                }
 
@@ -338,41 +346,12 @@ class ParseUrl
                        $siteinfo['type'] = 'link';
                }
 
-               if (empty($siteinfo['image']) && !$no_guessing) {
-                       $list = $xpath->query('//img[@src]');
-                       foreach ($list as $node) {
-                               $img_tag = [];
-                               if ($node->attributes->length) {
-                                       foreach ($node->attributes as $attribute) {
-                                               $img_tag[$attribute->name] = $attribute->value;
-                                       }
-                               }
-
-                               $src = self::completeUrl($img_tag['src'], $url);
-                               $photodata = Image::getInfoFromURL($src);
-
-                               if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
-                                       if ($photodata[0] > 300) {
-                                               $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
-                                               $photodata[0] = 300;
-                                       }
-                                       if ($photodata[1] > 300) {
-                                               $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
-                                               $photodata[1] = 300;
-                                       }
-                                       $siteinfo['images'][] = [
-                                               'src'    => $src,
-                                               'width'  => $photodata[0],
-                                               'height' => $photodata[1]
-                                       ];
-                               }
-                       }
-               } elseif (!empty($siteinfo['image'])) {
+               if (!empty($siteinfo['image'])) {
                        $src = self::completeUrl($siteinfo['image'], $url);
 
                        unset($siteinfo['image']);
 
-                       $photodata = Image::getInfoFromURL($src);
+                       $photodata = Images::getInfoFromURLCached($src);
 
                        if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
                                $siteinfo['images'][] = ['src' => $src,
@@ -381,49 +360,17 @@ class ParseUrl
                        }
                }
 
-               if ((@$siteinfo['text'] == '') && (@$siteinfo['title'] != '') && !$no_guessing) {
-                       $text = '';
-
-                       $list = $xpath->query('//div[@class="article"]');
-                       foreach ($list as $node) {
-                               if (strlen($node->nodeValue) > 40) {
-                                       $text .= ' ' . trim($node->nodeValue);
-                               }
-                       }
-
-                       if ($text == '') {
-                               $list = $xpath->query('//div[@class="content"]');
-                               foreach ($list as $node) {
-                                       if (strlen($node->nodeValue) > 40) {
-                                               $text .= ' ' . trim($node->nodeValue);
-                                       }
-                               }
-                       }
-
-                       // If none text was found then take the paragraph content
-                       if ($text == '') {
-                               $list = $xpath->query('//p');
-                               foreach ($list as $node) {
-                                       if (strlen($node->nodeValue) > 40) {
-                                               $text .= ' ' . trim($node->nodeValue);
-                                       }
-                               }
-                       }
-
-                       if ($text != '') {
-                               $text = trim(str_replace(["\n", "\r"], [' ', ' '], $text));
-
-                               while (strpos($text, '  ')) {
-                                       $text = trim(str_replace('  ', ' ', $text));
-                               }
-
-                               $siteinfo['text'] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, 'UTF-8') . '...');
+               if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
+                       $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
+                       $pos = mb_strrpos($siteinfo['text'], '.');
+                       if ($pos > self::MIN_DESC_COUNT) {
+                               $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
                        }
                }
 
-               logger('Siteinfo for ' . $url . ' ' . print_r($siteinfo, true), LOGGER_DEBUG);
+               Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
 
-               Addon::callHooks('getsiteinfo', $siteinfo);
+               Hook::callAll('getsiteinfo', $siteinfo);
 
                return $siteinfo;
        }