]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Item.php
Avoid multiple lines in post-view, added thread view
[friendica.git] / src / Model / Item.php
index a282762135e4c77f9414aee3294c45198547950f..888a81831ad00a3c519705d1c7a8dd14ba054523 100644 (file)
@@ -34,7 +34,7 @@ use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\Database\DBStructure;
 use Friendica\DI;
-use Friendica\Model\Post\Category;
+use Friendica\Model\Post;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\ActivityPub;
 use Friendica\Protocol\Diaspora;
@@ -75,14 +75,14 @@ class Item
        const DISPLAY_FIELDLIST = [
                'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
                'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
-               'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
+               'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'language',
                'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
                'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
                'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
                'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
                'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type',
                'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
-               'writable', 'self', 'cid', 'alias', 'pinned',
+               'writable', 'self', 'cid', 'alias',
                'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
                'event-summary', 'event-desc', 'event-location', 'event-type',
                'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
@@ -93,10 +93,10 @@ class Item
        const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
                        'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
                        'private', 'title', 'body', 'location', 'coord', 'app',
-                       'attach', 'deleted', 'extid', 'post-type', 'gravity',
+                       'deleted', 'extid', 'post-type', 'gravity',
                        'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
                        'author-id', 'author-link', 'owner-link', 'contact-uid',
-                       'signed_text', 'signature', 'signer', 'network'];
+                       'signed_text', 'network'];
 
        // Field list for "item-content" table that is mixed with the item table
        const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
@@ -111,7 +111,7 @@ class Item
                        'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
                        'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
                        'created', 'edited', 'commented', 'received', 'changed', 'verb',
-                       'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform',
+                       'postopts', 'plink', 'resource-id', 'event-id', 'inform',
                        'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
                        'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
                        'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
@@ -148,15 +148,6 @@ class Item
                return $postfields;
        }
 
-       public static function isLegacyMode()
-       {
-               if (is_null(self::$legacy_mode)) {
-                       self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
-               }
-
-               return self::$legacy_mode;
-       }
-
        /**
         * Set the pinned state of an item
         *
@@ -223,16 +214,19 @@ class Item
         * Fetch a single item row
         *
         * @param mixed $stmt statement object
-        * @return array current row
+        * @return array|false current row or false
+        * @throws \Exception
         */
        public static function fetch($stmt)
        {
                $row = DBA::fetch($stmt);
 
-               if (is_bool($row)) {
+               if (!is_array($row)) {
                        return $row;
                }
 
+               $row = DBA::castFields('item', $row);
+
                // ---------------------- Transform item structure data ----------------------
 
                // We prefer the data from the user's contact over the public one
@@ -259,22 +253,11 @@ class Item
                // We can always comment on posts from these networks
                if (array_key_exists('writable', $row) &&
                        in_array($row['internal-network'], Protocol::FEDERATED)) {
-                       $row['writable'] = true;
+                       $row['writable'] = 1;
                }
 
                // ---------------------- Transform item content data ----------------------
 
-               // Fetch data from the item-content table whenever there is content there
-               if (self::isLegacyMode()) {
-                       $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
-                       foreach ($legacy_fields as $field) {
-                               if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
-                                       $row[$field] = $row['internal-item-' . $field];
-                               }
-                               unset($row['internal-item-' . $field]);
-                       }
-               }
-
                if (array_key_exists('verb', $row)) {
                        if (!is_null($row['internal-verb'])) {
                                $row['verb'] = $row['internal-verb'];
@@ -308,7 +291,7 @@ class Item
                if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
                        // Build the file string out of the term entries
                        if (array_key_exists('file', $row) && empty($row['file'])) {
-                               $row['file'] = Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
+                               $row['file'] = Post\Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
                        }
                }
 
@@ -350,7 +333,7 @@ class Item
         * @param bool   $do_close
         * @return array Data array
         */
-       public static function inArray($stmt, $do_close = true) {
+       public static function toArray($stmt, $do_close = true) {
                if (is_bool($stmt)) {
                        return $stmt;
                }
@@ -387,75 +370,6 @@ class Item
                return $retval;
        }
 
-       /**
-        * Retrieve a single record from the item table for a given user and returns it in an associative array
-        *
-        * @param integer $uid User ID
-        * @param array   $selected
-        * @param array   $condition
-        * @param array   $params
-        * @return bool|array
-        * @throws \Exception
-        * @see   DBA::select
-        */
-       public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
-       {
-               $params['uid'] = $uid;
-
-               if (empty($selected)) {
-                       $selected = Item::DISPLAY_FIELDLIST;
-               }
-
-               return self::selectFirst($selected, $condition, $params);
-       }
-
-       /**
-        * Select rows from the item table for a given user
-        *
-        * @param integer $uid       User ID
-        * @param array   $selected  Array of selected fields, empty for all
-        * @param array   $condition Array of fields for condition
-        * @param array   $params    Array of several parameters
-        *
-        * @return boolean|object
-        * @throws \Exception
-        */
-       public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
-       {
-               $params['uid'] = $uid;
-
-               if (empty($selected)) {
-                       $selected = Item::DISPLAY_FIELDLIST;
-               }
-
-               return self::select($selected, $condition, $params);
-       }
-
-       /**
-        * Retrieve a single record from the item table and returns it in an associative array
-        *
-        * @param array $fields
-        * @param array $condition
-        * @param array $params
-        * @return bool|array
-        * @throws \Exception
-        * @see   DBA::select
-        */
-       public static function selectFirst(array $fields = [], array $condition = [], $params = [])
-       {
-               $params['limit'] = 1;
-
-               $result = self::select($fields, $condition, $params);
-
-               if (is_bool($result)) {
-                       return $result;
-               } else {
-                       $row = self::fetch($result);
-                       DBA::close($result);
-                       return $row;
-               }
-       }
-
        /**
         * Select rows from the item table and returns them as an array
         *
@@ -540,7 +454,7 @@ class Item
                $params['uid'] = $uid;
 
                if (empty($selected)) {
-                       $selected = Item::DISPLAY_FIELDLIST;
+                       $selected = self::DISPLAY_FIELDLIST;
                }
 
                return self::selectThread($selected, $condition, $params);
@@ -562,7 +476,7 @@ class Item
                $params['uid'] = $uid;
 
                if (empty($selected)) {
-                       $selected = Item::DISPLAY_FIELDLIST;
+                       $selected = self::DISPLAY_FIELDLIST;
                }
 
                return self::selectFirstThread($selected, $condition, $params);
@@ -657,10 +571,10 @@ class Item
                        'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid', 'causer-id',
                        'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
                        'created', 'edited', 'commented', 'received', 'changed', 'psid',
-                       'resource-id', 'event-id', 'attach', 'post-type', 'file',
+                       'resource-id', 'event-id', 'post-type', 'file',
                        'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
                        'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
-                       'id' => 'item_id', 'network', 'icid',
+                       'id' => 'item_id', 'network', 'icid', 'event-id',
                        'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
                        'network' => 'internal-network', 'psid' => 'internal-psid'];
 
@@ -700,7 +614,7 @@ class Item
                        'summary' => 'event-summary','desc' => 'event-desc',
                        'location' => 'event-location', 'type' => 'event-type',
                        'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
-                       'ignore' => 'event-ignore', 'id' => 'event-id'];
+                       'ignore' => 'event-ignore'];
 
                $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
 
@@ -849,9 +763,6 @@ class Item
                foreach ($fields as $table => $table_fields) {
                        foreach ($table_fields as $field => $select) {
                                if (empty($selected) || in_array($select, $selected)) {
-                                       if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
-                                               $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
-                                       }
                                        if (is_int($field)) {
                                                $selection[] = "`" . $table . "`.`" . $select . "`";
                                        } else {
@@ -909,6 +820,8 @@ class Item
                        return false;
                }
 
+               $data_fields = $fields;
+
                // To ensure the data integrity we do it in an transaction
                DBA::transaction();
 
@@ -921,7 +834,7 @@ class Item
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
                        if (isset($fields[$field])) {
                                $content_fields[$field] = $fields[$field];
-                               if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
+                               if (in_array($field, self::CONTENT_FIELDLIST)) {
                                        unset($fields[$field]);
                                } else {
                                        $fields[$field] = null;
@@ -965,33 +878,39 @@ class Item
                $notify_items = [];
 
                while ($item = DBA::fetch($items)) {
+                       Post\User::update($item['uri-id'], $item['uid'], $data_fields);
+
                        if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
+                               if (!empty($content_fields['body'])) {
+                                       $content_fields['raw-body'] = trim($content_fields['raw-body'] ?? $content_fields['body']);
+               
+                                       // Remove all media attachments from the body and store them in the post-media table
+                                       $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
+                                       $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
+                               }
+               
                                self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
 
                                if (empty($item['icid'])) {
                                        $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
                                        if (DBA::isResult($item_content)) {
                                                $item_fields = ['icid' => $item_content['id']];
-                                               // Clear all fields in the item table that have a content in the item-content table
-                                               if (self::isLegacyMode()) {
-                                                       foreach ($item_content as $field => $content) {
-                                                               if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
-                                                                       $item_fields[$field] = null;
-                                                               }
-                                                       }
-                                               }
                                                DBA::update('item', $item_fields, ['id' => $item['id']]);
                                        }
                                }
                        }
 
                        if (!is_null($files)) {
-                               Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
+                               Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
                                if (!empty($item['file'])) {
                                        DBA::update('item', ['file' => ''], ['id' => $item['id']]);
                                }
                        }
 
+                       if (!empty($fields['attach'])) {
+                               Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
+                       }
+
                        Post\DeliveryData::update($item['uri-id'], $delivery_data);
 
                        self::updateThread($item['id']);
@@ -1022,8 +941,8 @@ class Item
         */
        public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
        {
-               $items = self::select(['id'], $condition);
-               while ($item = self::fetch($items)) {
+               $items = Post::select(['id'], $condition);
+               while ($item = Post::fetch($items)) {
                        self::markForDeletionById($item['id'], $priority);
                }
                DBA::close($items);
@@ -1042,14 +961,13 @@ class Item
                        return;
                }
 
-               $items = self::select(['id', 'uid'], $condition);
-               while ($item = self::fetch($items)) {
+               $items = Post::select(['id', 'uid', 'uri-id'], $condition);
+               while ($item = Post::fetch($items)) {
+                       Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
+
                        // "Deleting" global items just means hiding them
                        if ($item['uid'] == 0) {
                                DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
-
-                               // Delete notifications
-                               DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
                        } elseif ($item['uid'] == $uid) {
                                self::markForDeletionById($item['id'], PRIORITY_HIGH);
                        } else {
@@ -1073,10 +991,10 @@ class Item
                Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
                // locate item to be deleted
                $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
-                       'deleted', 'file', 'resource-id', 'event-id', 'attach',
+                       'deleted', 'file', 'resource-id', 'event-id',
                        'verb', 'object-type', 'object', 'target', 'contact-id',
                        'icid', 'psid', 'gravity'];
-               $item = self::selectFirst($fields, ['id' => $item_id]);
+               $item = Post::selectFirst($fields, ['id' => $item_id]);
                if (!DBA::isResult($item)) {
                        Logger::info('Item not found.', ['id' => $item_id]);
                        return false;
@@ -1087,7 +1005,7 @@ class Item
                        return false;
                }
 
-               $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
+               $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
                if (!DBA::isResult($parent)) {
                        $parent = ['origin' => false];
                }
@@ -1130,33 +1048,26 @@ class Item
                }
 
                // If item has attachments, drop them
-               /// @TODO: this should first check if attachment is used elsewhere
-               foreach (explode(",", $item['attach']) as $attach) {
-                       preg_match("|attach/(\d+)|", $attach, $matches);
-                       if (is_array($matches) && count($matches) > 1) {
+               $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
+               foreach($attachments as $attachment) {
+                       if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
                                Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
                        }
                }
 
-               // Delete notifications
-               DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
-
                // Set the item to "deleted"
                $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
                DBA::update('item', $item_fields, ['id' => $item['id']]);
 
-               Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
+               Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
                self::deleteThread($item['id'], $item['parent-uri']);
 
-               if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
+               if (!Post::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
                        self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
                }
 
                Post\DeliveryData::delete($item['uri-id']);
 
-               if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
-                       DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
-               }
                // When the permission set will be used in photo and events as well,
                // this query here needs to be extended.
                // @todo Currently deactivated. We need the permission set in the deletion process.
@@ -1171,16 +1082,19 @@ class Item
                }
 
                // Is it our comment and/or our thread?
-               if ($item['origin'] || $parent['origin']) {
+               if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
                        // When we delete the original post we will delete all existing copies on the server as well
                        self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
 
                        // send the notification upstream/downstream
-                       Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
+                       if ($priority) {
+                               Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
+                       }
                } elseif ($item['uid'] != 0) {
+                       Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
 
                        // When we delete just our local user copy of an item, we have to set a marker to hide it
-                       $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
+                       $global_item = Post::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
                        if (DBA::isResult($global_item)) {
                                DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
                        }
@@ -1272,8 +1186,8 @@ class Item
                 *
                $data = BBCode::getAttachmentData($item['body']);
                if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
-                       && ($posttype != Item::PT_PERSONAL_NOTE)) {
-                       $posttype = Item::PT_PAGE;
+                       && ($posttype != self::PT_PERSONAL_NOTE)) {
+                       $posttype = self::PT_PAGE;
                        $objecttype = ACTIVITY_OBJ_BOOKMARK;
                }
                 */
@@ -1311,7 +1225,7 @@ class Item
        {
                // Checking if there is already an item with the same guid
                $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
-               if (self::exists($condition)) {
+               if (Post::exists($condition)) {
                        Logger::notice('Found already existing item', [
                                'guid' => $item['guid'],
                                'uid' => $item['uid'],
@@ -1322,7 +1236,7 @@ class Item
 
                $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
                        $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
-               if (self::exists($condition)) {
+               if (Post::exists($condition)) {
                        Logger::notice('duplicated item with the same uri found.', $item);
                        return true;
                }
@@ -1330,7 +1244,7 @@ class Item
                // On Friendica and Diaspora the GUID is unique
                if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
                        $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
-                       if (self::exists($condition)) {
+                       if (Post::exists($condition)) {
                                Logger::notice('duplicated item with the same guid found.', $item);
                                return true;
                        }
@@ -1338,7 +1252,7 @@ class Item
                        // Check for an existing post with the same content. There seems to be a problem with OStatus.
                        $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
                                        $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
-                       if (self::exists($condition)) {
+                       if (Post::exists($condition)) {
                                Logger::notice('duplicated item with the same body found.', $item);
                                return true;
                        }
@@ -1349,7 +1263,7 @@ class Item
                 * There is a timing issue here that sometimes creates double postings.
                 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
                 */
-               if (($item['uid'] == 0) && self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
+               if (($item['uid'] == 0) && Post::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
                        Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
                        return true;
                }
@@ -1366,28 +1280,20 @@ 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'] == '') {
                        Logger::notice('No body, no title.');
                        return false;
                }
 
-               // check for create date and expire time
-               $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
-
-               $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
-               if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
-                       $expire_interval = $user['expire'];
-               }
+               if (!empty($item['uid'])) {
+                       $owner = User::getOwnerDataById($item['uid'], false);
+                       if (!$owner) {
+                               Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
+                               return false;
+                       }
 
-               if (($expire_interval > 0) && !empty($item['created'])) {
-                       $expire_date = time() - ($expire_interval * 86400);
-                       $created_date = strtotime($item['created']);
-                       if ($created_date < $expire_date) {
-                               Logger::notice('Item created before expiration interval.', [
-                                       'created' => date('c', $created_date),
-                                       'expired' => date('c', $expire_date),
-                                       '$item' => $item
-                               ]);
+                       if ($owner['account_expired'] || $owner['account_removed']) {
+                               Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
                                return false;
                        }
                }
@@ -1402,11 +1308,6 @@ class Item
                        return false;
                }
 
-               if (!empty($item['uid']) && !empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $item['uid'])) {
-                       Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
-                       return false;
-               }
-
                if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
                        Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
                        return false;
@@ -1417,22 +1318,10 @@ class Item
                        return false;
                }
 
-               if (!empty($item['uid']) && !empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $item['uid'])) {
-                       Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
-                       return false;
-               }
-
-               // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
-               if (!empty($item['uid']) && !empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $item['uid'])) {
-                       Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
+               if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
                        return false;
                }
 
-               if (!empty($item['uid']) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact\User::isIgnored($item['causer-id'], $item['uid'])) {
-                       Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
-                       return false;
-               }
-               
                if ($item['verb'] == Activity::FOLLOW) {
                        if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
                                // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
@@ -1442,7 +1331,7 @@ class Item
 
                        $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
                                'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
-                       if (self::exists($condition)) {
+                       if (Post::exists($condition)) {
                                // It happens that we receive multiple follow requests by the same author - we only store one.
                                Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
                                return false;
@@ -1452,6 +1341,38 @@ class Item
                return true;
        }
 
+       /**
+        * Check if the item array is too old
+        *
+        * @param array $item
+        * @return boolean item is too old
+        */
+       public static function isTooOld(array $item)
+       {
+               // check for create date and expire time
+               $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
+
+               $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
+               if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
+                       $expire_interval = $user['expire'];
+               }
+
+               if (($expire_interval > 0) && !empty($item['created'])) {
+                       $expire_date = time() - ($expire_interval * 86400);
+                       $created_date = strtotime($item['created']);
+                       if ($created_date < $expire_date) {
+                               Logger::notice('Item created before expiration interval.', [
+                                       'created' => date('c', $created_date),
+                                       'expired' => date('c', $expire_date),
+                                       '$item' => $item
+                               ]);
+                               return true;
+                       }
+               }
+
+               return false;
+       }
+
        /**
         * Return the id of the given item array if it has been stored before
         *
@@ -1464,7 +1385,7 @@ class Item
                        $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
                                trim($item['uri']), $item['uid'],
                                Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
-                       $existing = self::selectFirst(['id', 'network'], $condition);
+                       $existing = Post::selectFirst(['id', 'network'], $condition);
                        if (DBA::isResult($existing)) {
                                // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
                                if ($item['uid'] != 0) {
@@ -1484,88 +1405,41 @@ class Item
        }
 
        /**
-        * Fetch parent data for the given item array
+        * Fetch top-level parent data for the given item array
         *
         * @param array $item
         * @return array item array with parent data
+        * @throws \Exception
         */
-       private static function getParentData(array $item)
+       private static function getTopLevelParent(array $item)
        {
-               // find the parent and snarf the item id and ACLs
-               // and anything else we need to inherit
-
-               $fields = ['uri', 'parent-uri', 'id', 'deleted',
+               $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
                        'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
                        'wall', 'private', 'forum_mode', 'origin', 'author-id'];
-               $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
+               $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid']];
                $params = ['order' => ['id' => false]];
-               $parent = self::selectFirst($fields, $condition, $params);
+               $parent = Post::selectFirst($fields, $condition, $params);
 
                if (!DBA::isResult($parent)) {
-                       Logger::info('item parent was not found - ignoring item', ['parent-uri' => $item['parent-uri'], 'uid' => $item['uid']]);
+                       Logger::notice('item parent was not found - ignoring item', ['thr-parent' => $item['thr-parent'], 'uid' => $item['uid']]);
                        return [];
-               } else {
-                       // is the new message multi-level threaded?
-                       // even though we don't support it now, preserve the info
-                       // and re-attach to the conversation parent.
-                       if ($parent['uri'] != $parent['parent-uri']) {
-                               $item['parent-uri'] = $parent['parent-uri'];
-
-                               $condition = ['uri' => $item['parent-uri'],
-                                       'parent-uri' => $item['parent-uri'],
-                                       'uid' => $item['uid']];
-                               $params = ['order' => ['id' => false]];
-                               $toplevel_parent = self::selectFirst($fields, $condition, $params);
-
-                               if (DBA::isResult($toplevel_parent)) {
-                                       $parent = $toplevel_parent;
-                               }
-                       }
-
-                       $item['parent']        = $parent['id'];
-                       $item["deleted"]       = $parent['deleted'];
-                       $item["allow_cid"]     = $parent['allow_cid'];
-                       $item['allow_gid']     = $parent['allow_gid'];
-                       $item['deny_cid']      = $parent['deny_cid'];
-                       $item['deny_gid']      = $parent['deny_gid'];
-                       $item['parent_origin'] = $parent['origin'];
-
-                       // Don't federate received participation messages
-                       if ($item['verb'] != Activity::FOLLOW) {
-                               $item['wall'] = $parent['wall'];
-                       } else {
-                               $item['wall'] = false;
-                       }
-
-                       /*
-                        * If the parent is private, force privacy for the entire conversation
-                        * This differs from the above settings as it subtly allows comments from
-                        * email correspondents to be private even if the overall thread is not.
-                        */
-                       if ($parent['private']) {
-                               $item['private'] = $parent['private'];
-                       }
-
-                       /*
-                        * Edge case. We host a public forum that was originally posted to privately.
-                        * The original author commented, but as this is a comment, the permissions
-                        * weren't fixed up so it will still show the comment as private unless we fix it here.
-                        */
-                       if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
-                               $item['private'] = self::PUBLIC;
-                       }
+               }
 
-                       // If its a post that originated here then tag the thread as "mention"
-                       if ($item['origin'] && $item['uid']) {
-                               DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
-                               Logger::info('tagged thread as mention', ['parent' => $item['parent'], 'uid' => $item['uid']]);
-                       }
+               if ($parent['uri'] == $parent['parent-uri']) {
+                       return $parent;
+               }
 
-                       // Update the contact relations
-                       Contact\Relation::store($parent['author-id'], $item['author-id'], $item['created']);
+               $condition = ['uri' => $parent['parent-uri'],
+                       'parent-uri' => $parent['parent-uri'],
+                       'uid' => $parent['uid']];
+               $params = ['order' => ['id' => false]];
+               $toplevel_parent = Post::selectFirst($fields, $condition, $params);
+               if (!DBA::isResult($toplevel_parent)) {
+                       Logger::notice('item top level parent was not found - ignoring item', ['parent-uri' => $parent['parent-uri'], 'uid' => $parent['uid']]);
+                       return [];
                }
 
-               return $item;
+               return $toplevel_parent;
        }
 
        /**
@@ -1606,9 +1480,10 @@ class Item
                        $item['wall'] = 1;
                        $item['origin'] = 1;
                        $item['network'] = Protocol::DFRN;
-                       $item['protocol'] = Conversation::PARCEL_DFRN;
+                       $item['protocol'] = Conversation::PARCEL_DIRECT;
+                       $item['direction'] = Conversation::PUSH;
 
-                       if (is_int($notify)) {
+                       if (in_array($notify, PRIORITIES)) {
                                $priority = $notify;
                        }
                } else {
@@ -1618,18 +1493,19 @@ class Item
                $uid = intval($item['uid']);
 
                $item['guid'] = self::guid($item, $notify);
-               $item['uri'] = substr(Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']))), 0, 255);
+               $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
 
                // Store URI data
                $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
 
+               // Backward compatibility: parent-uri used to be the direct parent uri.
+               // If it is provided without a thr-parent, it probably is the old behavior.
+               $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
+               $item['parent-uri'] = $item['thr-parent'];
+
                // Store conversation data
                $item = Conversation::insert($item);
 
-               if (!empty($item['thr-parent'])) {
-                       $item['parent-uri'] = $item['thr-parent'];
-               }
-
                /*
                 * Do we already have this item?
                 * We have to check several networks since Friendica posts could be repeated
@@ -1664,7 +1540,6 @@ class Item
                $item['coord']         = trim($item['coord'] ?? '');
                $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
                $item['deleted']       = 0;
-               $item['parent-uri']    = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
                $item['post-type']     = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
                $item['verb']          = trim($item['verb'] ?? '');
                $item['object-type']   = trim($item['object-type'] ?? '');
@@ -1679,7 +1554,6 @@ class Item
                $item['private']       = intval($item['private'] ?? self::PUBLIC);
                $item['body']          = trim($item['body'] ?? '');
                $item['raw-body']      = trim($item['raw-body'] ?? $item['body']);
-               $item['attach']        = trim($item['attach'] ?? '');
                $item['app']           = trim($item['app'] ?? '');
                $item['origin']        = intval($item['origin'] ?? 0);
                $item['postopts']      = trim($item['postopts'] ?? '');
@@ -1724,10 +1598,78 @@ class Item
                // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
                $item["contact-id"] = self::contactId($item);
 
+               if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
+                       self::isTooOld($item)) {
+                       Logger::info('Item is too old', ['item' => $item]);
+                       return 0;
+               }
+
                if (!self::isValid($item)) {
                        return 0;
                }
 
+               if ($item['gravity'] !== GRAVITY_PARENT) {
+                       $toplevel_parent = self::getTopLevelParent($item);
+                       if (empty($toplevel_parent)) {
+                               return 0;
+                       }
+
+                       // If the thread originated from this node, we check the permission against the thread starter
+                       $condition = ['uri' => $toplevel_parent['uri'], 'wall' => true];
+                       $localTopLevelParent = Post::selectFirst(['uid'], $condition);
+                       if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
+                               return 0;
+                       }
+
+                       $parent_id          = $toplevel_parent['id'];
+                       $item['parent-uri'] = $toplevel_parent['uri'];
+                       $item['deleted']    = $toplevel_parent['deleted'];
+                       $item['allow_cid']  = $toplevel_parent['allow_cid'];
+                       $item['allow_gid']  = $toplevel_parent['allow_gid'];
+                       $item['deny_cid']   = $toplevel_parent['deny_cid'];
+                       $item['deny_gid']   = $toplevel_parent['deny_gid'];
+                       $parent_origin      = $toplevel_parent['origin'];
+
+                       // Don't federate received participation messages
+                       if ($item['verb'] != Activity::FOLLOW) {
+                               $item['wall'] = $toplevel_parent['wall'];
+                       } else {
+                               $item['wall'] = false;
+                       }
+
+                       /*
+                        * If the parent is private, force privacy for the entire conversation
+                        * This differs from the above settings as it subtly allows comments from
+                        * email correspondents to be private even if the overall thread is not.
+                        */
+                       if ($toplevel_parent['private']) {
+                               $item['private'] = $toplevel_parent['private'];
+                       }
+
+                       /*
+                        * Edge case. We host a public forum that was originally posted to privately.
+                        * The original author commented, but as this is a comment, the permissions
+                        * weren't fixed up so it will still show the comment as private unless we fix it here.
+                        */
+                       if ((intval($toplevel_parent['forum_mode']) == 1) && ($toplevel_parent['private'] != self::PUBLIC)) {
+                               $item['private'] = self::PUBLIC;
+                       }
+
+                       // If its a post that originated here then tag the thread as "mention"
+                       if ($item['origin'] && $item['uid']) {
+                               DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
+                               Logger::info('tagged thread as mention', ['parent' => $parent_id, 'uid' => $item['uid']]);
+                       }
+
+                       // Update the contact relations
+                       Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
+
+                       unset($item['parent_origin']);
+               } else {
+                       $parent_id = 0;
+                       $parent_origin = $item['origin'];
+               }
+
                // We don't store the causer link, only the id
                unset($item['causer-link']);
 
@@ -1741,23 +1683,6 @@ class Item
                unset($item['owner-name']);
                unset($item['owner-avatar']);
 
-               $item['thr-parent'] = $item['parent-uri'];
-
-               if ($item['parent-uri'] != $item['uri']) {
-                       $item = self::getParentData($item);
-                       if (empty($item)) {
-                               return 0;
-                       }
-
-                       $parent_id = $item['parent'];
-                       unset($item['parent']);
-                       $parent_origin = $item['parent_origin'];
-                       unset($item['parent_origin']);
-               } else {
-                       $parent_id = 0;
-                       $parent_origin = $item['origin'];
-               }
-
                $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
                $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
 
@@ -1768,7 +1693,7 @@ class Item
                        // Set the global flag on all items if this was a global item entry
                        DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
                } else {
-                       $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
+                       $item["global"] = Post::exists(['uid' => 0, 'uri' => $item["uri"]]);
                }
 
                // ACL settings
@@ -1781,11 +1706,13 @@ class Item
                        $item['parent'] = $parent_id;
                        Hook::callAll('post_local', $item);
                        unset($item['edit']);
-                       unset($item['parent']);
                } else {
                        Hook::callAll('post_remote', $item);
                }
 
+               // Set after the insert because top-level posts are self-referencing
+               unset($item['parent']);
+
                if (!empty($item['cancel'])) {
                        Logger::log('post cancelled by addon.');
                        return 0;
@@ -1824,6 +1751,10 @@ class Item
                // Check for hashtags in the body and repair or add hashtag links
                $item['body'] = self::setHashtags($item['body']);
 
+               if (!empty($item['attach'])) {
+                       Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
+               }
+
                // Fill the cache field
                self::putInCache($item);
 
@@ -1863,7 +1794,7 @@ class Item
 
                // Attached file links
                if (!empty($item['file'])) {
-                       Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
+                       Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
                }
 
                unset($item['file']);
@@ -1882,38 +1813,39 @@ class Item
                        Tag::storeFromBody($item['uri-id'], $body);
                }
 
-               // Remove all fields that aren't part of the item table
-               foreach ($item as $field => $value) {
-                       if (!in_array($field, $structure['item'])) {
-                               unset($item[$field]);
+               if (Post\User::insert($item['uri-id'], $item['uid'], $item)) {
+                       // Remove all fields that aren't part of the item table
+                       foreach ($item as $field => $value) {
+                               if (!in_array($field, $structure['item'])) {
+                                       unset($item[$field]);
+                               }
                        }
-               }
 
-               DBA::lock('item');
+                       $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network']];
+                       if (DBA::exists('item', $condition)) {
+                               Logger::notice('Item is already inserted - aborting', $condition);
+                               return 0;
+                       }
+
+                       $result = DBA::insert('item', $item);
 
-               $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network']];
-               if (DBA::exists('item', $condition)) {
-                       DBA::unlock();
-                       Logger::notice('Item is already inserted - aborting', $condition);
+                       // When the item was successfully stored we fetch the ID of the item.
+                       $current_post = DBA::lastInsertId();
+               } else {
+                       Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
                        return 0;
                }
 
-               $ret = DBA::insert('item', $item);
-
-               // When the item was successfully stored we fetch the ID of the item.
-               $current_post = DBA::lastInsertId();
-               DBA::unlock();
-
-               if (!DBA::isResult($ret) || ($current_post == 0)) {
+               if (empty($current_post) || !DBA::isResult($result)) {
                        // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
-                       Logger::warning('Could not store item. it will be spooled', ['ret' => $ret, 'id' => $current_post]);
+                       Logger::warning('Could not store item. it will be spooled', ['result' => $result, 'id' => $current_post]);
                        self::spool($orig_item);
                        return 0;
                }
 
                Logger::notice('created item', ['id' => $current_post, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
 
-               if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
+               if (!$parent_id || ($item['gravity'] === GRAVITY_PARENT)) {
                        $parent_id = $current_post;
                }
 
@@ -1938,7 +1870,7 @@ class Item
                        DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
                }
 
-               if ($item['parent-uri'] === $item['uri']) {
+               if ($item['gravity'] === GRAVITY_PARENT) {
                        self::addThread($current_post);
                } else {
                        self::updateThread($parent_id);
@@ -1954,7 +1886,7 @@ class Item
                }
 
                if (!$dontcache) {
-                       $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
+                       $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
                        if (DBA::isResult($posted_item)) {
                                if ($notify) {
                                        Hook::callAll('post_local_end', $posted_item);
@@ -1966,7 +1898,7 @@ class Item
                        }
                }
 
-               if ($item['parent-uri'] === $item['uri']) {
+               if ($item['gravity'] === GRAVITY_PARENT) {
                        self::addShadow($current_post);
                } else {
                        self::addShadowPost($current_post);
@@ -1981,10 +1913,13 @@ class Item
                // Distribute items to users who subscribed to their tags
                self::distributeByTags($item);
 
+               // Automatically reshare the item if the "remote_self" option is selected
+               self::autoReshare($item);
+
                $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
 
                if ($transmit) {
-                       $transmit_item = Item::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
+                       $transmit_item = Post::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
                        // Don't relay participation messages
                        if (($transmit_item['verb'] == Activity::FOLLOW) && 
                                (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
@@ -2012,7 +1947,7 @@ class Item
         */
        private static function setOwnerforResharedItem(array $item)
        {
-               $parent = self::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
+               $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
                        ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
                if (!DBA::isResult($parent)) {
                        Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
@@ -2146,7 +2081,7 @@ class Item
        public static function distribute($itemid, $signed_text = '')
        {
                $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
-               $parent = self::selectFirst(['owner-id'], $condition);
+               $parent = Post::selectFirst(['owner-id'], $condition);
                if (!DBA::isResult($parent)) {
                        return;
                }
@@ -2155,7 +2090,7 @@ class Item
                $condition = ['id' => $itemid, 'uid' => 0,
                        'network' => array_merge(Protocol::FEDERATED ,['']),
                        'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
-               $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
                if (!DBA::isResult($item)) {
                        return;
                }
@@ -2208,13 +2143,14 @@ class Item
                $origin_uid = 0;
 
                if ($item['uri'] != $item['parent-uri']) {
-                       $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
-                       while ($parent = self::fetch($parents)) {
+                       $parents = Post::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
+                       while ($parent = Post::fetch($parents)) {
                                $users[$parent['uid']] = $parent['uid'];
                                if ($parent['origin'] && !$origin) {
                                        $origin_uid = $parent['uid'];
                                }
                        }
+                       DBA::close($parents);
                }
 
                foreach ($users as $uid) {
@@ -2235,7 +2171,7 @@ class Item
         */
        public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
        {
-               $item = self::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
                if (!DBA::isResult($item)) {
                        return 0;
                }
@@ -2264,7 +2200,7 @@ class Item
         */
        private static function storeForUser(array $item, int $uid)
        {
-               if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
+               if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
                        Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
                        return 0;
                }
@@ -2334,7 +2270,7 @@ class Item
        {
                $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
                $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
-               $item = self::selectFirst($fields, $condition);
+               $item = Post::selectFirst($fields, $condition);
 
                if (!DBA::isResult($item)) {
                        return;
@@ -2346,7 +2282,7 @@ class Item
                }
 
                // Is it a visible public post?
-               if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
+               if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == self::PRIVATE)) {
                        return;
                }
 
@@ -2355,11 +2291,11 @@ class Item
                        return;
                }
 
-               if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
+               if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
                        return;
                }
 
-               $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
 
                if (DBA::isResult($item)) {
                        // Preparing public shadow (removing user specific data)
@@ -2395,7 +2331,7 @@ class Item
         */
        private static function addShadowPost($itemid)
        {
-               $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
                if (!DBA::isResult($item)) {
                        return;
                }
@@ -2412,12 +2348,12 @@ class Item
                }
 
                // Is there a shadow parent?
-               if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
+               if (!Post::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
                        return;
                }
 
                // Is there already a shadow entry?
-               if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
+               if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
                        return;
                }
 
@@ -2444,7 +2380,7 @@ class Item
 
                // If this was a comment to a Diaspora post we don't get our comment back.
                // This means that we have to distribute the comment by ourselves.
-               if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
+               if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
                        self::distribute($public_shadow);
                }
        }
@@ -2459,12 +2395,15 @@ class Item
         */
        private static function getLanguage(array $item)
        {
-               if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
+               if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
                        return '';
                }
 
                // Convert attachments to links
                $naked_body = BBCode::removeAttachment($item['body']);
+               if (empty($naked_body)) {
+                       return '';
+               }
 
                // Remove links and pictures
                $naked_body = BBCode::removeLinks($naked_body);
@@ -2689,7 +2628,7 @@ class Item
                $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
                $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
 
-               $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
                if (!DBA::isResult($item)) {
                        return false;
                }
@@ -2777,11 +2716,36 @@ class Item
 
                Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
 
-               Item::performActivity($item_id, 'announce', $uid);
+               self::performActivity($item_id, 'announce', $uid);
 
                return false;
        }
 
+       /**
+        * Automatically reshare the item if the "remote_self" option is selected
+        *
+        * @param array $item
+        * @return void
+        */
+       private static function autoReshare(array $item)
+       {
+               if ($item['gravity'] != GRAVITY_PARENT) {
+                       return;
+               }
+
+               if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
+                       return;
+               }
+
+               if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
+                       return;
+               }
+
+               Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
+
+               self::performActivity($item['id'], 'announce', $item['uid']);
+       }
+
        public static function isRemoteSelf($contact, &$datarray)
        {
                if (!$contact['remote_self']) {
@@ -2813,7 +2777,7 @@ class Item
 
                $datarray2 = $datarray;
                Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
-               if ($contact['remote_self'] == 2) {
+               if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
                        $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
                                        ['uid' => $contact['uid'], 'self' => true]);
                        if (DBA::isResult($self)) {
@@ -2835,14 +2799,20 @@ class Item
                        }
 
                        if ($contact['network'] != Protocol::FEED) {
+                               $old_uri_id = $datarray["uri-id"] ?? 0;
                                $datarray["guid"] = System::createUUID();
                                unset($datarray["plink"]);
                                $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
-                               $datarray["parent-uri"] = $datarray["uri"];
-                               $datarray["thr-parent"] = $datarray["uri"];
+                               $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
                                $datarray["extid"] = Protocol::DFRN;
                                $urlpart = parse_url($datarray2['author-link']);
                                $datarray["app"] = $urlpart["host"];
+                               if (!empty($old_uri_id)) {
+                                       Post\Media::copy($old_uri_id, $datarray["uri-id"]);
+                               }
+
+                               unset($datarray["parent-uri"]);
+                               unset($datarray["thr-parent"]);
                        } else {
                                $datarray['private'] = self::PUBLIC;
                        }
@@ -2861,10 +2831,10 @@ class Item
                $datarray['api_source'] = true;
 
                // We have to tell the hooks who we are - this really should be improved
-               $_SESSION["authenticated"] = true;
-               $_SESSION["uid"] = $contact['uid'];
+               $_SESSION['authenticated'] = true;
+               $_SESSION['uid'] = $contact['uid'];
 
-               return $result;
+               return (bool)$result;
        }
 
        /**
@@ -3019,7 +2989,7 @@ class Item
                return $recipients;
        }
 
-       public static function expire($uid, $days, $network = "", $force = false)
+       public static function expire(int $uid, int $days, string $network = "", bool $force = false)
        {
                if (!$uid || ($days < 1)) {
                        return;
@@ -3046,7 +3016,7 @@ class Item
                $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
                $condition[] = $days;
 
-               $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
+               $items = Post::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
 
                if (!DBA::isResult($items)) {
                        return;
@@ -3065,7 +3035,9 @@ class Item
 
                $expired = 0;
 
-               while ($item = Item::fetch($items)) {
+               $priority = DI::config()->get('system', 'expire-notify-priority');
+
+               while ($item = Post::fetch($items)) {
                        // don't expire filed items
 
                        if (strpos($item['file'], '[') !== false) {
@@ -3078,13 +3050,13 @@ class Item
                                continue;
                        } elseif (!$expire_starred && intval($item['starred'])) {
                                continue;
-                       } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
+                       } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == self::PT_PERSONAL_NOTE))) {
                                continue;
-                       } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
+                       } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
                                continue;
                        }
 
-                       self::markForDeletionById($item['id'], PRIORITY_LOW);
+                       self::markForDeletionById($item['id'], $priority);
 
                        ++$expired;
                }
@@ -3129,7 +3101,7 @@ class Item
 
                Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
 
-               $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
+               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
                if (!DBA::isResult($item)) {
                        Logger::log('like: unknown item ' . $item_id);
                        return false;
@@ -3141,10 +3113,10 @@ class Item
                        return false;
                }
 
-               if (!Item::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
+               if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
                        $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
                        if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
-                               $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
+                               $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
                                if (!DBA::isResult($item)) {
                                        Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
                                        return false;
@@ -3222,7 +3194,7 @@ class Item
 
                $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
                        'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
-               $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
+               $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
 
                if (DBA::isResult($like_item)) {
                        /**
@@ -3272,9 +3244,10 @@ class Item
                        'wall'          => $item['wall'],
                        'origin'        => 1,
                        'network'       => Protocol::DFRN,
+                       'protocol'      => Conversation::PARCEL_DIRECT,
+                       'direction'     => Conversation::PUSH,
                        'gravity'       => GRAVITY_ACTIVITY,
                        'parent'        => $item['id'],
-                       'parent-uri'    => $item['uri'],
                        'thr-parent'    => $item['uri'],
                        'owner-id'      => $author_id,
                        'author-id'     => $author_id,
@@ -3314,7 +3287,7 @@ class Item
                        'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
                        'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
                $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
-               $item = self::selectFirst($fields, $condition);
+               $item = Post::selectFirst($fields, $condition);
 
                if (!DBA::isResult($item)) {
                        return;
@@ -3335,7 +3308,7 @@ class Item
                        'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
                        'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
 
-               $item = self::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
+               $item = Post::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
                if (!DBA::isResult($item)) {
                        return;
                }
@@ -3371,13 +3344,44 @@ class Item
 
                if ($itemuri != "") {
                        $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
-                       if (!self::exists($condition)) {
+                       if (!Post::exists($condition)) {
                                DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
                                Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
                        }
                }
        }
 
+       /**
+        * Fetch the SQL condition for the given user id
+        *
+        * @param integer $owner_id User ID for which the permissions should be fetched
+        * @return array condition
+        */
+       public static function getPermissionsConditionArrayByUserId(int $owner_id)
+       {
+               $local_user = local_user();
+               $remote_user = Session::getRemoteContactID($owner_id);
+
+               // default permissions - anonymous user
+               $condition = ["`private` != ?", self::PRIVATE];
+
+               if ($local_user && ($local_user == $owner_id)) {
+                       // Profile owner - everything is visible
+                       $condition = [];
+               } elseif ($remote_user) {
+                        // Authenticated visitor - fetch the matching permissionsets
+                       $set = PermissionSet::get($owner_id, $remote_user);
+                       if (!empty($set)) {
+                               $condition = ["(`private` != ? OR (`private` = ? AND `wall`
+                                       AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
+                                       self::PRIVATE, self::PRIVATE];
+                               $condition = array_merge($condition, $set);
+                       }
+               }
+
+               return $condition;
+       }
+
        public static function getPermissionsSQLByUserId($owner_id)
        {
                $local_user = local_user();
@@ -3388,7 +3392,7 @@ class Item
                 *
                 * default permissions - anonymous user
                 */
-               $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
+               $sql = sprintf(" AND `private` != %d", self::PRIVATE);
 
                // Profile owner - everything is visible
                if ($local_user && ($local_user == $owner_id)) {
@@ -3404,12 +3408,12 @@ class Item
                        $set = PermissionSet::get($owner_id, $remote_user);
 
                        if (!empty($set)) {
-                               $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
+                               $sql_set = sprintf(" OR (`private` = %d AND `wall` AND `psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
                        } else {
                                $sql_set = '';
                        }
 
-                       $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
+                       $sql = sprintf(" AND (`private` != %d", self::PRIVATE) . $sql_set . ")";
                }
 
                return $sql;
@@ -3449,20 +3453,21 @@ class Item
         */
        public static function putInCache(&$item, $update = false)
        {
-               $body = $item["body"];
+               // Save original body to prevent addons to modify it
+               $body = $item['body'];
 
                $rendered_hash = $item['rendered-hash'] ?? '';
                $rendered_html = $item['rendered-html'] ?? '';
 
                if ($rendered_hash == ''
-                       || $rendered_html == ""
-                       || $rendered_hash != hash("md5", $item["body"])
-                       || DI::config()->get("system", "ignore_cache")
+                       || $rendered_html == ''
+                       || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
+                       || DI::config()->get('system', 'ignore_cache')
                ) {
                        self::addRedirToImageTags($item);
 
-                       $item["rendered-html"] = BBCode::convert($item["body"]);
-                       $item["rendered-hash"] = hash("md5", $item["body"]);
+                       $item['rendered-html'] = BBCode::convert($item['body']);
+                       $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
 
                        $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
                        Hook::callAll('put_item_in_cache', $hook_data);
@@ -3471,27 +3476,27 @@ class Item
                        unset($hook_data);
 
                        // Force an update if the generated values differ from the existing ones
-                       if ($rendered_hash != $item["rendered-hash"]) {
+                       if ($rendered_hash != $item['rendered-hash']) {
                                $update = true;
                        }
 
                        // Only compare the HTML when we forcefully ignore the cache
-                       if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
+                       if (DI::config()->get('system', 'ignore_cache') && ($rendered_html != $item['rendered-html'])) {
                                $update = true;
                        }
 
-                       if ($update && !empty($item["id"])) {
+                       if ($update && !empty($item['id'])) {
                                self::update(
                                        [
-                                               'rendered-html' => $item["rendered-html"],
-                                               'rendered-hash' => $item["rendered-hash"]
+                                               'rendered-html' => $item['rendered-html'],
+                                               'rendered-hash' => $item['rendered-hash']
                                        ],
-                                       ['id' => $item["id"]]
+                                       ['id' => $item['id']]
                                );
                        }
                }
 
-               $item["body"] = $body;
+               $item['body'] = $body;
        }
 
        /**
@@ -3598,12 +3603,10 @@ class Item
 
                $as = '';
                $vhead = false;
-               $matches = [];
-               preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
-               foreach ($matches as $mtch) {
-                       $mime = $mtch[3];
+               foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
+                       $mime = $attachment['mimetype'];
 
-                       $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
+                       $the_url = Contact::magicLinkById($item['author-id'], $attachment['url']);
 
                        if (strpos($mime, 'video') !== false) {
                                if (!$vhead) {
@@ -3630,8 +3633,8 @@ class Item
                                $filesubtype = 'unkn';
                        }
 
-                       $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
-                       $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
+                       $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
+                       $title .= ' ' . ($attachment['size'] ?? 0) . ' ' . DI::l10n()->t('bytes');
 
                        $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
                        $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
@@ -3870,7 +3873,7 @@ class Item
                $uid = $item['uid'] ?? 0;
 
                // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
-               $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
+               $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
                if (!DBA::isResult($shared_item)) {
                        if (empty($shared['link'])) {
                                return $item;
@@ -3883,7 +3886,7 @@ class Item
                                return $item;
                        }
 
-                       $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
+                       $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
                        if (!DBA::isResult($shared_item)) {
                                return $item;
                        }
@@ -3904,4 +3907,41 @@ class Item
 
                return array_merge($item, $shared_item);
        }
+
+       /**
+        * Check a prospective item array against user-level permissions
+        *
+        * @param array $item Expected keys: uri, gravity, and
+        *                    author-link if is author-id is set,
+        *                    owner-link if is owner-id is set,
+        *                    causer-link if is causer-id is set.
+        * @param int   $user_id Local user ID
+        * @return bool
+        * @throws \Exception
+        */
+       protected static function isAllowedByUser(array $item, int $user_id)
+       {
+               if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
+                       Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
+                       Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
+               if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
+                       Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
+                       Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               return true;
+       }
 }