]> git.mxchange.org Git - friendica.git/blobdiff - src/Util/ParseUrl.php
Merge pull request #8898 from annando/spool-log
[friendica.git] / src / Util / ParseUrl.php
index 1188214200cdc7d7971f65737886b0591008530e..b6d172a3a1da36402a011bab916ba881ceb04223 100644 (file)
@@ -1,46 +1,70 @@
 <?php
 /**
- * @file src/Util/ParseUrl.php
- * @brief Get informations about a given URL
+ * @copyright Copyright (C) 2020, Friendica
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  */
+
 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;
-use Friendica\Util\Strings;
-
-require_once 'include/dba.php';
 
 /**
- * @brief Class with methods for extracting certain content from an url
+ * Get information about a given URL
+ *
+ * Class with methods for extracting certain content from an url
  */
 class ParseUrl
 {
        /**
-        * @brief Search for chached embeddable data of an url otherwise fetch it
+        * Maximum number of characters for the description
+        */
+       const MAX_DESC_COUNT = 250;
+
+       /**
+        * Minimum number of characters for the description
+        */
+       const MIN_DESC_COUNT = 100;
+
+       /**
+        * 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
-        *    string 'type' => Content type
-        *    string 'title' => The title of the content
-        *    string 'text' => The description for the content
-        *    string 'image' => A preview image of the content (only available
-        *                if $no_geuessing = false
-        *    array'images' = Array of preview pictures
-        *    string 'keywords' => The tags which belong to the content
+        *    string 'url'      => The url of the parsed page
+        *    string 'type'     => Content type
+        *    string 'title'    => (optional) The title of the content
+        *    string 'text'     => (optional) The description for the content
+        *    string 'image'    => (optional) A preview image of the content (only available if $no_geuessing = false)
+        *    array  'images'   => (optional) Array of preview pictures
+        *    string 'keywords' => (optional) 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)
@@ -62,7 +86,7 @@ class ParseUrl
                DBA::insert(
                        'parsed_url',
                        [
-                               'url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing,
+                               'url' => substr(Strings::normaliseLink($url), 0, 255), 'guessing' => !$no_guessing,
                                'oembed' => $do_oembed, 'content' => serialize($data),
                                'created' => DateTimeFormat::utcNow()
                        ],
@@ -71,8 +95,9 @@ class ParseUrl
 
                return $data;
        }
+
        /**
-        * @brief Parse a page for embeddable content information
+        * Parse a page for embeddable content information
         *
         * This method parses to url for meta data which can be used to embed
         * the content. If available it prioritizes Open Graph meta tags.
@@ -82,23 +107,23 @@ 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
-        *    string 'type' => Content type
-        *    string 'title' => The title of the content
-        *    string 'text' => The description for the content
-        *    string 'image' => A preview image of the content (only available
-        *                if $no_geuessing = false
-        *    array'images' = Array of preview pictures
-        *    string 'keywords' => The tags which belong to the content
+        *    string 'url'      => The url of the parsed page
+        *    string 'type'     => Content type
+        *    string 'title'    => (optional) The title of the content
+        *    string 'text'     => (optional) The description for the content
+        *    string 'image'    => (optional) A preview image of the content (only available if $no_guessing = false)
+        *    array  'images'   => (optional) Array of preview pictures
+        *    string 'keywords' => (optional) 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">
@@ -113,37 +138,34 @@ 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
                $scheme = parse_url($url, PHP_URL_SCHEME);
 
                if ($scheme == '') {
-                       $url = 'http://' . trim($url, '/');
+                       $url = 'http://' . ltrim($url, '/');
                }
 
+               $url = trim($url, "'\"");
+
+               $url = Network::stripTrackingQueryParams($url);
+
+               $siteinfo = [
+                       'url' => $url,
+                       'type' => 'link',
+               ];
+
                if ($count > 10) {
                        Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
                        return $siteinfo;
                }
 
-               $url = trim($url, "'");
-               $url = trim($url, '"');
-
-               $url = Network::stripTrackingQueryParams($url);
-
-               $siteinfo['url'] = $url;
-               $siteinfo['type'] = 'link';
-
                $curlResult = Network::curl($url);
                if (!$curlResult->isSuccess()) {
                        return $siteinfo;
                }
 
                // 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;
                }
 
@@ -184,11 +206,10 @@ 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::log('detected charset ' . $charset, Logger::DEBUG);
                        $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
                }
@@ -340,41 +361,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,
@@ -383,55 +375,23 @@ 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::log('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;
        }
 
        /**
-        * @brief Convert tags from CSV to an array
+        * Convert tags from CSV to an array
         *
         * @param string $string Tags
         * @return array with formatted Hashtags
@@ -448,9 +408,9 @@ class ParseUrl
        }
 
        /**
-        * @brief Add a hasht sign to a string
+        * Add a hasht sign to a string
         *
-        *  This method is used as callback function
+        * This method is used as callback function
         *
         * @param string $tag The pure tag name
         * @param int    $k   Counter for internal use
@@ -462,7 +422,7 @@ class ParseUrl
        }
 
        /**
-        * @brief Add a scheme to an url
+        * Add a scheme to an url
         *
         * The src attribute of some html elements (e.g. images)
         * can miss the scheme so we need to add the correct