]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Item.php
Apply suggestions from code review
[friendica.git] / src / Model / Item.php
index 8867a2caa125b5e6e8564acccea0ad491df97373..1d8742926db6944ddba0600927b55e59ba37ff1e 100644 (file)
@@ -21,6 +21,7 @@
 
 namespace Friendica\Model;
 
+use Friendica\Content\PageInfo;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
 use Friendica\Core\Hook;
@@ -40,6 +41,7 @@ use Friendica\Protocol\Diaspora;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Map;
 use Friendica\Util\Network;
+use Friendica\Util\Proxy;
 use Friendica\Util\Strings;
 use Friendica\Worker\Delivery;
 use LanguageDetection\Language;
@@ -150,7 +152,7 @@ class Item
                        return false;
                }
 
-               if (!empty($fields['extid']) && empty($fields['external-id'])) {
+               if (isset($fields['extid'])) {
                        $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
                }
 
@@ -177,9 +179,12 @@ class Item
 
                while ($item = DBA::fetch($items)) {
                        if (!empty($fields['body'])) {
+                               Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
+
                                $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
-       
+
                                // Remove all media attachments from the body and store them in the post-media table
+                               // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
                                $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
                                $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
                        }
@@ -508,7 +513,7 @@ class Item
        public static function isValid(array $item)
        {
                // When there is no content then we don't post it
-               if ($item['body'] . $item['title'] == '') {
+               if (($item['body'] . $item['title'] == '') && !Post\Media::existsByURIId($item['uri-id'])) {
                        Logger::notice('No body, no title.');
                        return false;
                }
@@ -955,6 +960,8 @@ class Item
                        self::setOwnerforResharedItem($item);
                }
 
+               Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
+
                // Remove all media attachments from the body and store them in the post-media table
                $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
                $item['raw-body'] = self::setHashtags($item['raw-body']);
@@ -1074,7 +1081,7 @@ class Item
                                Hook::callAll('post_local_end', $posted_item);
                        } else {
                                Hook::callAll('post_remote_end', $posted_item);
-                       }               
+                       }
                }
 
                if ($posted_item['gravity'] === GRAVITY_PARENT) {
@@ -1099,7 +1106,7 @@ class Item
 
                if ($transmit) {
                        // Don't relay participation messages
-                       if (($posted_item['verb'] == Activity::FOLLOW) && 
+                       if (($posted_item['verb'] == Activity::FOLLOW) &&
                                (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
                                Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
                                $transmit = false;
@@ -1647,7 +1654,7 @@ class Item
                        // or it had been done by a "regular" contact.
                        if (!empty($arr['wall'])) {
                                $condition = ['id' => $arr['contact-id']];
-                       } else { 
+                       } else {
                                $condition = ['id' => $arr['contact-id'], 'self' => false];
                        }
                        DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
@@ -1700,7 +1707,7 @@ class Item
                                        return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
                                }, $body);
 
-                       $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
+                       $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
                                function ($match) {
                                        return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
                                }, $body);
@@ -1782,7 +1789,7 @@ class Item
                                }
                        }
                }
-               
+
                if (!$mention) {
                        if (($community_page || $prvgroup) &&
                                  !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
@@ -2442,10 +2449,10 @@ class Item
 
        /**
         * Get a permission SQL string for the given user
-        * 
-        * @param int $owner_id 
-        * @param string $table 
-        * @return string 
+        *
+        * @param int $owner_id
+        * @param string $table
+        * @return string
         */
        public static function getPermissionsSQLByUserId(int $owner_id, string $table = '')
        {
@@ -2633,7 +2640,10 @@ class Item
                        unset($hook_data);
                }
 
+               $body = $item['body'] ?? '';
+               $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $item['body']);
                self::putInCache($item);
+               $item['body'] = $body;
                $s = $item["rendered-html"];
 
                $hook_data = [
@@ -2653,7 +2663,28 @@ class Item
                        return $s;
                }
 
-               $s = self::addMediaAttachments($item, $s);
+               $shared = BBCode::fetchShareAttributes($item['body']);
+               if (!empty($shared['guid'])) {
+                       $shared_item = Post::selectFirst(['uri-id', 'plink'], ['guid' => $shared['guid']]);
+                       $shared_uri_id = $shared_item['uri-id'] ?? 0;
+                       $shared_links = [strtolower($shared_item['plink'] ?? '')];
+                       $attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid']);
+                       $s = self::addVisualAttachments($attachments, $item, $s, true);
+                       $s = self::addLinkAttachment($attachments, $body, $s, true, []);
+                       $s = self::addNonVisualAttachments($attachments, $item, $s, true);
+                       $shared_links = array_merge($shared_links, array_column($attachments['visual'], 'url'));
+                       $shared_links = array_merge($shared_links, array_column($attachments['link'], 'url'));
+                       $shared_links = array_merge($shared_links, array_column($attachments['additional'], 'url'));
+                       $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
+               } else {
+                       $shared_uri_id = 0;
+                       $shared_links = [];
+               }
+
+               $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'], $shared_links);
+               $s = self::addVisualAttachments($attachments, $item, $s, false);
+               $s = self::addLinkAttachment($attachments, $body, $s, false, $shared_links);
+               $s = self::addNonVisualAttachments($attachments, $item, $s, false);
 
                // Map.
                if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
@@ -2678,45 +2709,65 @@ class Item
        }
 
        /**
-        * Add media attachments to the content
+        * Check if the body contains a link
         *
+        * @param string $body
+        * @param string $url
+        * @return bool
+        */
+       public static function containsLink(string $body, string $url)
+       {
+               if (strpos($body, $url)) {
+                       return true;
+               }
+               foreach ([0, 1, 2] as $size) {
+                       if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
+                               strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
+                               return true;
+                       }
+               }
+               return false;
+       }
+
+       /**
+        * Add visual attachments to the content
+        *
+        * @param array $attachments
         * @param array $item
         * @param string $content
-        * @return modified content
+        * @return string modified content
         */
-       private static function addMediaAttachments(array $item, string $content)
+       private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared)
        {
+               $stamp1 = microtime(true);
                $leading = '';
                $trailing = '';
-               // currently deactivated the request for Post\Media::VIDEO since it creates mutliple videos from Peertube
-               foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, 
-                       Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
-                       if (in_array($attachment['type'], [Post\Media::AUDIO, Post\Media::VIDEO]) && strpos($item['body'], $attachment['url'])) {
+
+               // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
+               foreach ($attachments['visual'] as $attachment) {
+                       if (self::containsLink($item['body'], $attachment['url'])) {
                                continue;
                        }
 
-                       $mime = $attachment['mimetype'];
-
                        $author = ['uid' => 0, 'id' => $item['author-id'],
                                'network' => $item['author-network'], 'url' => $item['author-link']];
                        $the_url = Contact::magicLinkByContact($author, $attachment['url']);
 
-                       $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
-                       if ($filetype) {
-                               $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
-                               $filesubtype = str_replace('.', '-', $filesubtype);
+                       if (!empty($attachment['preview'])) {
+                               $preview_url = Proxy::proxifyUrl(Contact::magicLinkByContact($author, $attachment['preview']));
                        } else {
-                               $filetype = 'unkn';
-                               $filesubtype = 'unkn';
+                               $preview_url = '';
                        }
 
-                       if (($filetype == 'video')) {
+                       if (($attachment['filetype'] == 'video')) {
                                /// @todo Move the template to /content as well
                                $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
                                        '$video' => [
-                                               'id'     => $item['author-id'],
-                                               'src'    => $the_url,
-                                               'mime'   => $mime,
+                                               'id'      => $attachment['id'],
+                                               'src'     => $the_url,
+                                               'name'    => $attachment['name'] ?: $attachment['url'],
+                                               'preview' => $preview_url,
+                                               'mime'    => $attachment['mimetype'],
                                        ],
                                ]);
                                if ($item['post-type'] == Item::PT_VIDEO) {
@@ -2724,12 +2775,13 @@ class Item
                                } else {
                                        $trailing .= $media;
                                }
-                       } elseif ($filetype == 'audio') {
+                       } elseif ($attachment['filetype'] == 'audio') {
                                $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
                                        '$audio' => [
-                                               'id'     => $item['author-id'],
+                                               'id'     => $attachment['id'],
                                                'src'    => $the_url,
-                                               'mime'   => $mime,
+                                               'name'    => $attachment['name'] ?: $attachment['url'],
+                                               'mime'   => $attachment['mimetype'],
                                        ],
                                ]);
                                if ($item['post-type'] == Item::PT_AUDIO) {
@@ -2737,27 +2789,149 @@ class Item
                                } else {
                                        $trailing .= $media;
                                }
-                       } else {
-                               $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
+                       } elseif ($attachment['filetype'] == 'image') {
+                               if (empty($preview_url) && (max($attachment['width'], $attachment['height']) > 600)) {
+                                       $preview_url = Proxy::proxifyUrl($the_url, false, ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
+                               }
+                               $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
+                                       '$image' => [
+                                               'src'    => Proxy::proxifyUrl($the_url),
+                                               'preview' => $preview_url,
+                                               'attachment'   => $attachment,
+                                       ],
+                               ]);
+                               // On Diaspora posts the attached pictures are leading
+                               if ($item['network'] == Protocol::DIASPORA) {
+                                       $leading .= $media;
+                               } else {
+                                       $trailing .= $media;
+                               }
+                       }
+               }
+
+               if ($shared) {
+                       $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
+                       $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
+               } else {
+                       if ($leading != '') {
+                               $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
+                       }
 
-                               if (!empty($attachment['size'])) {
-                                       $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
+                       if ($trailing != '') {
+                               $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
+                       }
+               }
+
+               DI::profiler()->saveTimestamp($stamp1, 'rendering');
+               return $content;
+       }
+
+       /**
+        * Add link attachment to the content
+        *
+        * @param array  $attachments
+        * @param string $body
+        * @param string $content
+        * @param bool   $shared
+        * @param array  $ignore_links A list of URLs to ignore
+        * @return string modified content
+        */
+       private static function addLinkAttachment(array $attachments, string $body, string $content, bool $shared, array $ignore_links)
+       {
+               $stamp1 = microtime(true);
+               // @ToDo Check only for audio and video
+               $preview = empty($attachments['visual']);
+
+               if (!empty($attachments['link'])) {
+                       foreach ($attachments['link'] as $link) {
+                               $found = false;
+                               foreach ($ignore_links as $ignore_link) {
+                                       if (Strings::compareLink($link['url'], $ignore_link)) {
+                                               $found = true;
+                                       }
+                               }
+                               if (!$found) {
+                                       $attachment = $link;
                                }
+                       }
+               }
 
-                               /// @todo Use a template
-                               $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
-                               $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
+               if (!empty($attachment)) {
+                       $data = [
+                               'after' => '',
+                               'author_name' => $attachment['author-name'] ?? '',
+                               'author_url' =>  $attachment['author-url'] ?? '',
+                               'description' => $attachment['description'] ?? '',
+                               'image' => '',
+                               'preview' => '',
+                               'provider_name' => $attachment['publisher-name'] ?? '',
+                               'provider_url' => $attachment['publisher-url'] ?? '',
+                               'text' => '',
+                               'title' => $attachment['name'] ?? '',
+                               'type' => 'link',
+                               'url' => $attachment['url']];
+
+                       if ($preview) {
+                               if ($attachment['preview-width'] >= 500) {
+                                       $data['image'] = $attachment['preview'] ?? '';
+                               } else {
+                                       $data['preview'] = $attachment['preview'] ?? '';
+                               }
                        }
+               } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
+                       $data = BBCode::getAttachmentData($match[1]);
                }
+               DI::profiler()->saveTimestamp($stamp1, 'rendering');
 
-               if ($leading != '') {
-                       $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
+               if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
+                       // @todo Use a template
+                       $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data);
+                       if ($shared) {
+                               return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
+                       } else {
+                               return $content . $rendered;
+                       }
+               }
+               return $content;
+       }
+
+       /**
+        * Add non visual attachments to the content
+        *
+        * @param array $attachments
+        * @param array $item
+        * @param string $content
+        * @return string modified content
+        */
+       private static function addNonVisualAttachments(array $attachments, array $item, string $content)
+       {
+               $stamp1 = microtime(true);
+               $trailing = '';
+               foreach ($attachments['additional'] as $attachment) {
+                       if (strpos($item['body'], $attachment['url'])) {
+                               continue;
+                       }
+
+                       $author = ['uid' => 0, 'id' => $item['author-id'],
+                               'network' => $item['author-network'], 'url' => $item['author-link']];
+                       $the_url = Contact::magicLinkByContact($author, $attachment['url']);
+
+                       $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
+
+                       if (!empty($attachment['size'])) {
+                               $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
+                       }
+
+                       /// @todo Use a template
+                       $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
+                       $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
                }
 
                if ($trailing != '') {
                        $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
                }
 
+               DI::profiler()->saveTimestamp($stamp1, 'rendering');
                return $content;
        }
 
@@ -2849,8 +3023,8 @@ class Item
        }
 
        /**
-        * Return the URI for a link to the post 
-        * 
+        * Return the URI for a link to the post
+        *
         * @param string $uri URI or link to post
         *
         * @return string URI