]> git.mxchange.org Git - friendica.git/blobdiff - src/Model/Item.php
in "getidforurl" "no update" is now "update"
[friendica.git] / src / Model / Item.php
index 94fe567f66fe5e21c59fe37af6eb808e7a604e39..332c734fa5b8db976fe97c92b7a6239af285b4d6 100644 (file)
@@ -1,16 +1,29 @@
 <?php
-
 /**
- * @file src/Model/Item.php
+ * @copyright Copyright (C) 2020, Friendica
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  */
 
 namespace Friendica\Model;
 
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\HTML;
-use Friendica\Core\Config;
 use Friendica\Core\Hook;
-use Friendica\Core\L10n;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
 use Friendica\Core\Renderer;
@@ -19,18 +32,18 @@ use Friendica\Core\System;
 use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\DI;
+use Friendica\Model\Post\Category;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\ActivityPub;
 use Friendica\Protocol\Diaspora;
-use Friendica\Protocol\OStatus;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Map;
 use Friendica\Util\Network;
 use Friendica\Util\Security;
 use Friendica\Util\Strings;
-use Friendica\Util\XML;
 use Friendica\Worker\Delivery;
 use Text_LanguageDetect;
+use Friendica\Repository\PermissionSet as RepPermissionSet;
 
 class Item
 {
@@ -47,7 +60,7 @@ class Item
 
        // Field list that is used to display the items
        const DISPLAY_FIELDLIST = [
-               'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
+               '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',
                'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
@@ -63,10 +76,10 @@ class Item
        ];
 
        // Field list that is used to deliver items via the protocols
-       const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
+       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', 'tag', 'deleted', 'extid', 'post-type',
+                       'attach', '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'];
@@ -80,10 +93,11 @@ class Item
        const CONTENT_FIELDLIST = ['language'];
 
        // All fields in the item table
-       const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
-                       'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
+       const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
+                       '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', 'tag', 'attach', 'inform',
+                       'postopts', 'plink', 'resource-id', 'event-id', 'attach', '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',
@@ -92,20 +106,24 @@ class Item
                        'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
                        'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
 
+       // List of all verbs that don't need additional content data.
        // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
-       // The item-activity table only stores the index and needs this array to know the matching activity.
        const ACTIVITIES = [
                Activity::LIKE, Activity::DISLIKE,
                Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
                Activity::FOLLOW,
                Activity::ANNOUNCE];
 
+       const PUBLIC = 0;
+       const PRIVATE = 1;
+       const UNLISTED = 2;
+
        private static $legacy_mode = null;
 
        public static function isLegacyMode()
        {
                if (is_null(self::$legacy_mode)) {
-                       self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
+                       self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
                }
 
                return self::$legacy_mode;
@@ -141,7 +159,7 @@ class Item
        }
 
        /**
-        * @brief Select pinned rows from the item table for a given user
+        * Select pinned rows from the item table for a given user
         *
         * @param integer $uid       User ID
         * @param array   $selected  Array of selected fields, empty for all
@@ -159,7 +177,7 @@ class Item
                }
 
                $pinned = [];
-               while ($useritem = self::fetch($useritems)) {
+               while ($useritem = DBA::fetch($useritems)) {
                        $pinned[] = $useritem['iid'];
                }
                DBA::close($useritems);
@@ -186,39 +204,7 @@ class Item
        }
 
        /**
-        * @brief returns an activity index from an activity string
-        *
-        * @param string $activity activity string
-        * @return integer Activity index
-        */
-       public static function activityToIndex($activity)
-       {
-               $index = array_search($activity, self::ACTIVITIES);
-
-               if (is_bool($index)) {
-                       $index = -1;
-               }
-
-               return $index;
-       }
-
-       /**
-        * @brief returns an activity string from an activity index
-        *
-        * @param integer $index activity index
-        * @return string Activity string
-        */
-       private static function indexToActivity($index)
-       {
-               if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
-                       return '';
-               }
-
-               return self::ACTIVITIES[$index];
-       }
-
-       /**
-        * @brief Fetch a single item row
+        * Fetch a single item row
         *
         * @param mixed $stmt statement object
         * @return array current row
@@ -264,7 +250,7 @@ class Item
 
                // Fetch data from the item-content table whenever there is content there
                if (self::isLegacyMode()) {
-                       $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
+                       $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];
@@ -273,44 +259,56 @@ class Item
                        }
                }
 
-               if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
-                       $row['verb'] = self::indexToActivity($row['internal-activity']);
-                       if (array_key_exists('title', $row)) {
-                               $row['title'] = '';
-                       }
-                       if (array_key_exists('body', $row)) {
-                               $row['body'] = $row['verb'];
-                       }
-                       if (array_key_exists('object', $row)) {
-                               $row['object'] = '';
+               if (array_key_exists('verb', $row)) {
+                       if (!is_null($row['internal-verb'])) {
+                               $row['verb'] = $row['internal-verb'];
                        }
-                       if (array_key_exists('object-type', $row)) {
-                               $row['object-type'] = Activity\ObjectType::NOTE;
-                       }
-               } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
-                       // Posts don't have a target - but having tags or files.
-                       // We safe some performance by building tag and file strings only here.
-                       // We remove the target since they aren't used for this type.
-                       // In mail posts we do store some mail header data in the object.
-                       if (array_key_exists('target', $row)) {
-                               $row['target'] = '';
+
+                       if (in_array($row['verb'], self::ACTIVITIES)) {
+                               if (array_key_exists('title', $row)) {
+                                       $row['title'] = '';
+                               }
+                               if (array_key_exists('body', $row)) {
+                                       $row['body'] = $row['verb'];
+                               }
+                               if (array_key_exists('object', $row)) {
+                                       $row['object'] = '';
+                               }
+                               if (array_key_exists('object-type', $row)) {
+                                       $row['object-type'] = Activity\ObjectType::NOTE;
+                               }
+                       } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
+                               // Posts don't have a target - but having tags or files.
+                               if (array_key_exists('target', $row)) {
+                                       $row['target'] = '';
+                               }
                        }
                }
 
+               if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
+                       $row['vid'] = Verb::getID($row['verb']);
+               }
+                       
                if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
-                       // Build the tag string out of the term entries
-                       if (array_key_exists('tag', $row) && empty($row['tag'])) {
-                               $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
-                       }
-
                        // Build the file string out of the term entries
                        if (array_key_exists('file', $row) && empty($row['file'])) {
-                               $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
+                               $row['file'] = Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
                        }
                }
 
-               if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
-                       $row['signed_text'] = $row['interaction'];
+               if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
+                       if (array_key_exists('allow_cid', $row)) {
+                               $row['allow_cid'] = '';
+                       }
+                       if (array_key_exists('allow_gid', $row)) {
+                               $row['allow_gid'] = '';
+                       }
+                       if (array_key_exists('deny_cid', $row)) {
+                               $row['deny_cid'] = '';
+                       }
+                       if (array_key_exists('deny_gid', $row)) {
+                               $row['deny_gid'] = '';
+                       }
                }
 
                if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
@@ -318,11 +316,11 @@ class Item
                }
 
                // Remove internal fields
-               unset($row['internal-activity']);
                unset($row['internal-network']);
-               unset($row['internal-iid']);
-               unset($row['internal-iaid']);
-               unset($row['internal-icid']);
+               unset($row['internal-uri-id']);
+               unset($row['internal-uid']);
+               unset($row['internal-psid']);
+               unset($row['internal-verb']);
                unset($row['internal-user-ignored']);
                unset($row['interaction']);
 
@@ -330,7 +328,7 @@ class Item
        }
 
        /**
-        * @brief Fills an array with data from an item query
+        * Fills an array with data from an item query
         *
         * @param object $stmt statement object
         * @param bool   $do_close
@@ -352,7 +350,7 @@ class Item
        }
 
        /**
-        * @brief Check if item data exists
+        * Check if item data exists
         *
         * @param array $condition array of fields for condition
         *
@@ -376,7 +374,6 @@ class Item
        /**
         * Retrieve a single record from the item table for a given user and returns it in an associative array
         *
-        * @brief Retrieve a single record from a table
         * @param integer $uid User ID
         * @param array   $selected
         * @param array   $condition
@@ -397,7 +394,7 @@ class Item
        }
 
        /**
-        * @brief Select rows from the item table for a given user
+        * 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
@@ -421,7 +418,6 @@ class Item
        /**
         * Retrieve a single record from the item table and returns it in an associative array
         *
-        * @brief Retrieve a single record from a table
         * @param array $fields
         * @param array $condition
         * @param array $params
@@ -445,7 +441,7 @@ class Item
        }
 
        /**
-        * @brief Select rows from the item table and returns them as an array
+        * Select rows from the item table and returns them as an array
         *
         * @param array $selected  Array of selected fields, empty for all
         * @param array $condition Array of fields for condition
@@ -472,7 +468,7 @@ class Item
        }
 
        /**
-        * @brief Select rows from the item table
+        * Select rows from the item table
         *
         * @param array $selected  Array of selected fields, empty for all
         * @param array $condition Array of fields for condition
@@ -513,7 +509,7 @@ class Item
        }
 
        /**
-        * @brief Select rows from the starting post in the item table
+        * Select rows from the starting post in the item table
         *
         * @param integer $uid       User ID
         * @param array   $selected
@@ -537,7 +533,6 @@ class Item
        /**
         * Retrieve a single record from the starting post in the item table and returns it in an associative array
         *
-        * @brief Retrieve a single record from a table
         * @param integer $uid User ID
         * @param array   $selected
         * @param array   $condition
@@ -560,7 +555,6 @@ class Item
        /**
         * Retrieve a single record from the starting post in the item table and returns it in an associative array
         *
-        * @brief Retrieve a single record from a table
         * @param array $fields
         * @param array $condition
         * @param array $params
@@ -583,7 +577,7 @@ class Item
        }
 
        /**
-        * @brief Select rows from the starting post in the item table
+        * Select rows from the starting post in the item table
         *
         * @param array $selected  Array of selected fields, empty for all
         * @param array $condition Array of fields for condition
@@ -634,7 +628,7 @@ class Item
        }
 
        /**
-        * @brief Returns a list of fields that are associated with the item table
+        * Returns a list of fields that are associated with the item table
         *
         * @param $usermode
         * @return array field list
@@ -643,25 +637,26 @@ class Item
        {
                $fields = [];
 
-               $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
+               $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
+                       'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
                        'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
                        'created', 'edited', 'commented', 'received', 'changed', 'psid',
-                       'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
+                       'resource-id', 'event-id', 'attach', 'post-type', 'file',
                        'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
                        'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
-                       'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
-                       'network' => 'internal-network', 'icid' => 'internal-icid',
-                       'iaid' => 'internal-iaid'];
+                       'id' => 'item_id', 'network', 'icid',
+                       'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
+                       'network' => 'internal-network', 'psid' => 'internal-psid'];
 
                if ($usermode) {
                        $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
                }
 
-               $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
-
                $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
 
-               $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
+               $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
+
+               $fields['verb'] = ['name' => 'internal-verb'];
 
                $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
 
@@ -677,7 +672,8 @@ class Item
 
                $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
 
-               $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
+               $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
+                       'network' => 'parent-author-network'];
 
                $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
                        'start' => 'event-start','finish' => 'event-finish',
@@ -686,15 +682,13 @@ class Item
                        'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
                        'ignore' => 'event-ignore', 'id' => 'event-id'];
 
-               $fields['sign'] = ['signed_text', 'signature', 'signer'];
-
-               $fields['diaspora-interaction'] = ['interaction'];
+               $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
 
                return $fields;
        }
 
        /**
-        * @brief Returns SQL condition for the "select" functions
+        * Returns SQL condition for the "select" functions
         *
         * @param boolean $thread_mode Called for the items (false) or for the threads (true)
         *
@@ -717,7 +711,7 @@ class Item
        }
 
        /**
-        * @brief Returns all needed "JOIN" commands for the "select" functions
+        * Returns all needed "JOIN" commands for the "select" functions
         *
         * @param integer $uid          User ID
         * @param string  $sql_commands The parts of the built SQL commands in the "select" functions
@@ -773,71 +767,60 @@ class Item
                        $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
                }
 
-               if (strpos($sql_commands, "`sign`.") !== false) {
-                       $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
-               }
-
                if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
                        $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
                }
 
-               if (strpos($sql_commands, "`item-activity`.") !== false) {
-                       $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
-               }
-
                if (strpos($sql_commands, "`item-content`.") !== false) {
                        $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
                }
 
-               if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
-                       $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
+               if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
+                       $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
+               }
+
+               if (strpos($sql_commands, "`verb`.") !== false) {
+                       $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
                }
 
                if (strpos($sql_commands, "`permissionset`.") !== false) {
                        $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
                }
 
-               if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
+               if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
                        $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
-               }
 
-               if (strpos($sql_commands, "`parent-item-author`.") !== false) {
-                       $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
+                       if (strpos($sql_commands, "`parent-item-author`.") !== false) {
+                               $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
+                       }
                }
 
                return $joins;
        }
 
        /**
-        * @brief Add the field list for the "select" functions
+        * Add the field list for the "select" functions
         *
         * @param array $fields The field definition array
         * @param array $selected The array with the selected fields from the "select" functions
         *
         * @return string The field list
         */
-       private static function constructSelectFields($fields, $selected)
+       private static function constructSelectFields(array $fields, array $selected)
        {
                if (!empty($selected)) {
-                       $selected[] = 'internal-iid';
-                       $selected[] = 'internal-iaid';
-                       $selected[] = 'internal-icid';
-                       $selected[] = 'internal-network';
+                       $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
                }
 
                if (in_array('verb', $selected)) {
-                       $selected[] = 'internal-activity';
+                       $selected = array_merge($selected, ['internal-verb']);
                }
 
                if (in_array('ignored', $selected)) {
                        $selected[] = 'internal-user-ignored';
                }
 
-               if (in_array('signed_text', $selected)) {
-                       $selected[] = 'interaction';
-               }
-
-               $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
+               $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
 
                $selection = [];
                foreach ($fields as $table => $table_fields) {
@@ -858,7 +841,7 @@ class Item
        }
 
        /**
-        * @brief add table definition to fields in an SQL query
+        * add table definition to fields in an SQL query
         *
         * @param string $query SQL query
         * @param array $fields The field definition array
@@ -884,7 +867,7 @@ class Item
        }
 
        /**
-        * @brief Update existing item entries
+        * Update existing item entries
         *
         * @param array $fields    The fields that are to be changed
         * @param array $condition The condition for finding the item entries
@@ -909,7 +892,7 @@ class Item
                // We cannot simply expand the condition to check for origin entries
                // The condition needn't to be a simple array but could be a complex condition.
                // And we have to execute this query before the update to ensure to fetch the same data.
-               $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
+               $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
 
                $content_fields = [];
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
@@ -923,7 +906,7 @@ class Item
                        }
                }
 
-               $delivery_data = ItemDeliveryData::extractFields($fields);
+               $delivery_data = Post\DeliveryData::extractFields($fields);
 
                $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
                foreach ($clear_fields as $field) {
@@ -932,13 +915,6 @@ class Item
                        }
                }
 
-               if (array_key_exists('tag', $fields)) {
-                       $tags = $fields['tag'];
-                       $fields['tag'] = null;
-               } else {
-                       $tags = null;
-               }
-
                if (array_key_exists('file', $fields)) {
                        $files = $fields['file'];
                        $fields['file'] = null;
@@ -946,6 +922,10 @@ class Item
                        $files = null;
                }
 
+               if (!empty($content_fields['verb'])) {
+                       $fields['vid'] = Verb::getID($content_fields['verb']);
+               }
+
                if (!empty($fields)) {
                        $success = DBA::update('item', $fields, $condition);
 
@@ -962,34 +942,7 @@ class Item
                $notify_items = [];
 
                while ($item = DBA::fetch($items)) {
-                       if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
-                               self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
-
-                               if (empty($item['iaid'])) {
-                                       $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
-                                       if (DBA::isResult($item_activity)) {
-                                               $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
-                                               foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
-                                                       if (self::isLegacyMode()) {
-                                                               $item_fields[$field] = null;
-                                                       } else {
-                                                               unset($item_fields[$field]);
-                                                       }
-                                               }
-                                               DBA::update('item', $item_fields, ['id' => $item['id']]);
-
-                                               if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
-                                                       DBA::delete('item-content', ['id' => $item['icid']]);
-                                               }
-                                       }
-                               } elseif (!empty($item['icid'])) {
-                                       DBA::update('item', ['icid' => null], ['id' => $item['id']]);
-
-                                       if (!DBA::exists('item', ['icid' => $item['icid']])) {
-                                               DBA::delete('item-content', ['id' => $item['icid']]);
-                                       }
-                               }
-                       } else {
+                       if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
                                self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
 
                                if (empty($item['icid'])) {
@@ -997,12 +950,10 @@ class Item
                                        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
-                                               foreach ($item_content as $field => $content) {
-                                                       if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
-                                                               if (self::isLegacyMode()) {
+                                               if (self::isLegacyMode()) {
+                                                       foreach ($item_content as $field => $content) {
+                                                               if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
                                                                        $item_fields[$field] = null;
-                                                               } else {
-                                                                       unset($item_fields[$field]);
                                                                }
                                                        }
                                                }
@@ -1011,21 +962,14 @@ class Item
                                }
                        }
 
-                       if (!is_null($tags)) {
-                               Term::insertFromTagFieldByItemId($item['id'], $tags);
-                               if (!empty($item['tag'])) {
-                                       DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
-                               }
-                       }
-
                        if (!is_null($files)) {
-                               Term::insertFromFileFieldByItemId($item['id'], $files);
+                               Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
                                if (!empty($item['file'])) {
                                        DBA::update('item', ['file' => ''], ['id' => $item['id']]);
                                }
                        }
 
-                       ItemDeliveryData::update($item['id'], $delivery_data);
+                       Post\DeliveryData::update($item['uri-id'], $delivery_data);
 
                        self::updateThread($item['id']);
 
@@ -1047,23 +991,23 @@ class Item
        }
 
        /**
-        * @brief Delete an item and notify others about it - if it was ours
+        * Delete an item and notify others about it - if it was ours
         *
         * @param array   $condition The condition for finding the item entries
         * @param integer $priority  Priority for the notification
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public static function delete($condition, $priority = PRIORITY_HIGH)
+       public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
        {
                $items = self::select(['id'], $condition);
                while ($item = self::fetch($items)) {
-                       self::deleteById($item['id'], $priority);
+                       self::markForDeletionById($item['id'], $priority);
                }
                DBA::close($items);
        }
 
        /**
-        * @brief Delete an item for an user and notify others about it - if it was ours
+        * Delete an item for an user and notify others about it - if it was ours
         *
         * @param array   $condition The condition for finding the item entries
         * @param integer $uid       User who wants to delete this item
@@ -1084,7 +1028,7 @@ class Item
                                // Delete notifications
                                DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
                        } elseif ($item['uid'] == $uid) {
-                               self::deleteById($item['id'], PRIORITY_HIGH);
+                               self::markForDeletionById($item['id'], PRIORITY_HIGH);
                        } else {
                                Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
                        }
@@ -1093,29 +1037,30 @@ class Item
        }
 
        /**
-        * @brief Delete an item and notify others about it - if it was ours
+        * Mark an item for deletion, delete related data and notify others about it - if it was ours
         *
-        * @param integer $item_id  Item ID that should be delete
+        * @param integer $item_id
         * @param integer $priority Priority for the notification
         *
         * @return boolean success
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         */
-       public static function deleteById($item_id, $priority = PRIORITY_HIGH)
+       public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
        {
+               Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
                // locate item to be deleted
-               $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
+               $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
                        'deleted', 'file', 'resource-id', 'event-id', 'attach',
                        'verb', 'object-type', 'object', 'target', 'contact-id',
-                       'icid', 'iaid', 'psid'];
+                       'icid', 'psid', 'gravity'];
                $item = self::selectFirst($fields, ['id' => $item_id]);
                if (!DBA::isResult($item)) {
-                       Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
+                       Logger::info('Item not found.', ['id' => $item_id]);
                        return false;
                }
 
                if ($item['deleted']) {
-                       Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
+                       Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
                        return false;
                }
 
@@ -1126,7 +1071,7 @@ class Item
 
                // clean up categories and tags so they don't end up as orphans
 
-               $matches = false;
+               $matches = [];
                $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
 
                if ($cnt) {
@@ -1135,7 +1080,7 @@ class Item
                        }
                }
 
-               $matches = false;
+               $matches = [];
 
                $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
 
@@ -1170,9 +1115,6 @@ class Item
                        }
                }
 
-               // Delete tags that had been attached to other items
-               self::deleteTagsFromItem($item);
-
                // Delete notifications
                DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
 
@@ -1180,17 +1122,14 @@ class Item
                $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
                DBA::update('item', $item_fields, ['id' => $item['id']]);
 
-               Term::insertFromTagFieldByItemId($item['id'], '');
-               Term::insertFromFileFieldByItemId($item['id'], '');
+               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']])) {
-                       self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
+                       self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
                }
 
-               ItemDeliveryData::delete($item['id']);
-
-               // We don't delete the item-activity here, since we need some of the data for ActivityPub
+               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]);
@@ -1204,15 +1143,14 @@ class Item
                //}
 
                // If it's the parent of a comment thread, kill all the kids
-               if ($item['id'] == $item['parent']) {
-                       self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
+               if ($item['gravity'] == GRAVITY_PARENT) {
+                       self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
                }
 
                // Is it our comment and/or our thread?
                if ($item['origin'] || $parent['origin']) {
-
                        // When we delete the original post we will delete all existing copies on the server as well
-                       self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
+                       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']));
@@ -1225,48 +1163,11 @@ class Item
                        }
                }
 
-               Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
+               Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
 
                return true;
        }
 
-       private static function deleteTagsFromItem($item)
-       {
-               if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity\ObjectType::TAGTERM)) {
-                       return;
-               }
-
-               $xo = XML::parseString($item["object"], false);
-               $xt = XML::parseString($item["target"], false);
-
-               if ($xt->type != Activity\ObjectType::NOTE) {
-                       return;
-               }
-
-               $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
-               if (!DBA::isResult($i)) {
-                       return;
-               }
-
-               // For tags, the owner cannot remove the tag on the author's copy of the post.
-               $owner_remove = ($item["contact-id"] == $i["contact-id"]);
-               $author_copy = $item["origin"];
-
-               if (($owner_remove && $author_copy) || !$owner_remove) {
-                       return;
-               }
-
-               $tags = explode(',', $i["tag"]);
-               $newtags = [];
-               if (count($tags)) {
-                       foreach ($tags as $tag) {
-                               if (trim($tag) !== trim($xo->body)) {
-                                      $newtags[] = trim($tag);
-                               }
-                       }
-               }
-               self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
-       }
 
        private static function guid($item, $notify)
        {
@@ -1377,88 +1278,80 @@ class Item
                }
        }
 
-       public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
+       /**
+        * Check if the item array is a duplicate
+        *
+        * @param array $item
+        * @return boolean is it a duplicate?
+        */
+       private static function isDuplicate(array $item)
        {
-               $orig_item = $item;
-
-               $priority = PRIORITY_HIGH;
-
-               // If it is a posting where users should get notifications, then define it as wall posting
-               if ($notify) {
-                       $item['wall'] = 1;
-                       $item['origin'] = 1;
-                       $item['network'] = Protocol::DFRN;
-                       $item['protocol'] = Conversation::PARCEL_DFRN;
-
-                       if (is_int($notify)) {
-                               $priority = $notify;
-                       }
-               } else {
-                       $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
-               }
-
-               $item['guid'] = self::guid($item, $notify);
-               $item['uri'] = Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid'])));
-
-               // Store URI data
-               $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
-
-               // Store conversation data
-               $item = Conversation::insert($item);
-
-               /*
-                * If a Diaspora signature structure was passed in, pull it out of the
-                * item array and set it aside for later storage.
-                */
-
-               $dsprsig = null;
-               if (isset($item['dsprsig'])) {
-                       $encoded_signature = $item['dsprsig'];
-                       $dsprsig = json_decode(base64_decode($item['dsprsig']));
-                       unset($item['dsprsig']);
+               // 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)) {
+                       Logger::notice('Found already existing item', [
+                               'guid' => $item['guid'],
+                               'uid' => $item['uid'],
+                               'network' => $item['network']
+                       ]);
+                       return true;
                }
 
-               $diaspora_signed_text = '';
-               if (isset($item['diaspora_signed_text'])) {
-                       $diaspora_signed_text = $item['diaspora_signed_text'];
-                       unset($item['diaspora_signed_text']);
+               $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
+                       $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
+               if (self::exists($condition)) {
+                       Logger::notice('duplicated item with the same uri found.', $item);
+                       return true;
                }
 
-               // Converting the plink
-               /// @TODO Check if this is really still needed
-               if ($item['network'] == Protocol::OSTATUS) {
-                       if (isset($item['plink'])) {
-                               $item['plink'] = OStatus::convertHref($item['plink']);
-                       } elseif (isset($item['uri'])) {
-                               $item['plink'] = OStatus::convertHref($item['uri']);
+               // 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)) {
+                               Logger::notice('duplicated item with the same guid found.', $item);
+                               return true;
+                       }
+               } elseif ($item['network'] == Protocol::OSTATUS) {
+                       // 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)) {
+                               Logger::notice('duplicated item with the same body found.', $item);
+                               return true;
                        }
                }
 
-               if (!empty($item['thr-parent'])) {
-                       $item['parent-uri'] = $item['thr-parent'];
+               /*
+                * Check for already added items.
+                * 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])) {
+                       Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
+                       return true;
                }
 
-               $activity = DI::activity();
+               return false;
+       }
 
-               if (isset($item['gravity'])) {
-                       $item['gravity'] = intval($item['gravity']);
-               } elseif ($item['parent-uri'] === $item['uri']) {
-                       $item['gravity'] = GRAVITY_PARENT;
-               } elseif ($activity->match($item['verb'], Activity::POST)) {
-                       $item['gravity'] = GRAVITY_COMMENT;
-               } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
-                       $item['gravity'] = GRAVITY_ACTIVITY;
-               } else {
-                       $item['gravity'] = GRAVITY_UNKNOWN;   // Should not happen
-                       Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
+       /**
+        * Check if the item array is valid
+        *
+        * @param array $item
+        * @return boolean item is valid
+        */
+       private static function isValid(array $item)
+       {
+               // When there is no content then we don't post it
+               if ($item['body'].$item['title'] == '') {
+                       Logger::notice('No body, no title.');
+                       return false;
                }
 
-               $uid = intval($item['uid']);
-
                // check for create date and expire time
-               $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
+               $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
 
-               $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
+               $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'];
                }
@@ -1472,15 +1365,78 @@ class Item
                                        'expired' => date('c', $expire_date),
                                        '$item' => $item
                                ]);
-                               return 0;
+                               return false;
                        }
                }
 
-               /*
-                * Do we already have this item?
-                * We have to check several networks since Friendica posts could be repeated
-                * via OStatus (maybe Diasporsa as well)
-                */
+               if (Contact::isBlocked($item['author-id'])) {
+                       Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
+                       Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['uid']) && Contact::isBlockedByUser($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 (Contact::isBlocked($item['owner-id'])) {
+                       Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
+                       Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['uid']) && Contact::isBlockedByUser($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::isBlockedByUser($item['causer-id'], $item['uid'])) {
+                       Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
+                       return false;
+               }
+
+               if (!empty($item['uid']) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($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.
+                               Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
+                               return false;
+                       }
+
+                       $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
+                               'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
+                       if (self::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;
+                       }
+               }
+
+               return true;
+       }
+
+       /**
+        * Return the id of the given item array if it has been stored before
+        *
+        * @param array $item
+        * @return integer item id
+        */
+       private static function getDuplicateID(array $item)
+       {
                if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
                        $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
                                trim($item['uri']), $item['uid'],
@@ -1488,10 +1444,10 @@ class Item
                        $existing = self::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 ($uid != 0) {
+                               if ($item['uid'] != 0) {
                                        Logger::notice('Item already existed for user', [
                                                'uri' => $item['uri'],
-                                               'uid' => $uid,
+                                               'uid' => $item['uid'],
                                                'network' => $item['network'],
                                                'existing_id' => $existing["id"],
                                                'existing_network' => $existing["network"]
@@ -1501,6 +1457,169 @@ class Item
                                return $existing["id"];
                        }
                }
+               return 0;
+       }
+
+       /**
+        * Fetch parent data for the given item array
+        *
+        * @param array $item
+        * @return array item array with parent data
+        */
+       private static function getParentData(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',
+                       'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
+                       'wall', 'private', 'forum_mode', 'origin', 'author-id'];
+               $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
+               $params = ['order' => ['id' => false]];
+               $parent = self::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']]);
+                       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']]);
+                       }
+
+                       // Update the contact relations
+                       if ($item['author-id'] != $parent['author-id']) {
+                               DBA::update('contact-relation', ['last-interaction' => $item['created']], ['cid' => $parent['author-id'], 'relation-cid' => $item['author-id']], true);
+                       }
+               }
+
+               return $item;
+       }
+
+       /**
+        * Get the gravity for the given item array
+        *
+        * @param array $item
+        * @return integer gravity
+        */
+       private static function getGravity(array $item)
+       {
+               $activity = DI::activity();
+
+               if (isset($item['gravity'])) {
+                       return intval($item['gravity']);
+               } elseif ($item['parent-uri'] === $item['uri']) {
+                       return GRAVITY_PARENT;
+               } elseif ($activity->match($item['verb'], Activity::POST)) {
+                       return GRAVITY_COMMENT;
+               } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
+                       return GRAVITY_ACTIVITY;
+               }
+               Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
+               return GRAVITY_UNKNOWN;   // Should not happen
+       }
+
+       public static function insert($item, $notify = false, $dontcache = false)
+       {
+               $orig_item = $item;
+
+               $priority = PRIORITY_HIGH;
+
+               // If it is a posting where users should get notifications, then define it as wall posting
+               if ($notify) {
+                       $item['wall'] = 1;
+                       $item['origin'] = 1;
+                       $item['network'] = Protocol::DFRN;
+                       $item['protocol'] = Conversation::PARCEL_DFRN;
+
+                       if (is_int($notify)) {
+                               $priority = $notify;
+                       }
+               } else {
+                       $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
+               }
+
+               $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);
+
+               // Store URI data
+               $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
+
+               // 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
+                * via OStatus (maybe Diasporsa as well)
+                */
+               $duplicate = self::getDuplicateID($item);
+               if ($duplicate) {
+                       return $duplicate;
+               }
+
+               // Additional duplicate checks
+               /// @todo Check why the first duplication check returns the item number and the second a 0
+               if (self::isDuplicate($item)) {
+                       return 0;
+               }
 
                $item['wall']          = intval($item['wall'] ?? 0);
                $item['extid']         = trim($item['extid'] ?? '');
@@ -1515,7 +1634,7 @@ class Item
                $item['edited']        = (isset($item['edited'])    ? DateTimeFormat::utc($item['edited'])    : $item['created']);
                $item['changed']       = (isset($item['changed'])   ? DateTimeFormat::utc($item['changed'])   : $item['created']);
                $item['commented']     = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
-               $item['title']         = trim($item['title'] ?? '');
+               $item['title']         = substr(trim($item['title'] ?? ''), 0, 255);
                $item['location']      = trim($item['location'] ?? '');
                $item['coord']         = trim($item['coord'] ?? '');
                $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
@@ -1527,14 +1646,13 @@ class Item
                $item['object']        = trim($item['object'] ?? '');
                $item['target-type']   = trim($item['target-type'] ?? '');
                $item['target']        = trim($item['target'] ?? '');
-               $item['plink']         = trim($item['plink'] ?? '');
+               $item['plink']         = substr(trim($item['plink'] ?? ''), 0, 255);
                $item['allow_cid']     = trim($item['allow_cid'] ?? '');
                $item['allow_gid']     = trim($item['allow_gid'] ?? '');
                $item['deny_cid']      = trim($item['deny_cid'] ?? '');
                $item['deny_gid']      = trim($item['deny_gid'] ?? '');
-               $item['private']       = intval($item['private'] ?? 0);
+               $item['private']       = intval($item['private'] ?? self::PUBLIC);
                $item['body']          = trim($item['body'] ?? '');
-               $item['tag']           = trim($item['tag'] ?? '');
                $item['attach']        = trim($item['attach'] ?? '');
                $item['app']           = trim($item['app'] ?? '');
                $item['origin']        = intval($item['origin'] ?? 0);
@@ -1544,14 +1662,6 @@ class Item
                $item['inform']        = trim($item['inform'] ?? '');
                $item['file']          = trim($item['file'] ?? '');
 
-               // When there is no content then we don't post it
-               if ($item['body'].$item['title'] == '') {
-                       Logger::notice('No body, no title.');
-                       return 0;
-               }
-
-               self::addLanguageToItemArray($item);
-
                // Items cannot be stored before they happen ...
                if ($item['created'] > DateTimeFormat::utcNow()) {
                        $item['created'] = DateTimeFormat::utcNow();
@@ -1564,229 +1674,59 @@ class Item
 
                $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
 
-               $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
-                       'photo' => $item['author-avatar'], 'network' => $item['network']];
-
-               $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, false, $default);
+               $item['language'] = self::getLanguage($item);
 
-               if (Contact::isBlocked($item['author-id'])) {
-                       Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
-                       return 0;
-               }
+               $item['gravity'] = self::getGravity($item);
 
-               if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
-                       Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
-                       Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
-                       return 0;
-               }
+               $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
+                       'photo' => $item['author-avatar'], 'network' => $item['network']];
+               $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
 
                $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
                        'photo' => $item['owner-avatar'], 'network' => $item['network']];
-
-               $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, false, $default);
-
-               if (Contact::isBlocked($item['owner-id'])) {
-                       Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
-                       Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
-                       Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
-               if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
-                       Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
-                       Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
-                       return 0;
-               }
-
-               // We don't store the causer, we only have it here for the checks above
-               unset($item['causer-id']);
-               unset($item['causer-link']);
+               $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
 
                // 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 ($item['network'] == Protocol::PHANTOM) {
-                       $item['network'] = Protocol::DFRN;
-                       Logger::notice('Missing network, setting to {network}.', [
-                               'uri' => $item["uri"],
-                               'network' => $item['network'],
-                               'callstack' => System::callstack()
-                       ]);
-               }
-
-               // 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)) {
-                       Logger::notice('Found already existing item', [
-                               'guid' => $item['guid'],
-                               'uid' => $item['uid'],
-                               'network' => $item['network']
-                       ]);
+               if (!self::isValid($item)) {
                        return 0;
                }
 
-               if ($item['verb'] == Activity::FOLLOW) {
-                       if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
-                               // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
-                               Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
-                               return 0;
-                       }
+               // We don't store the causer, we only have it here for the checks in the function above
+               unset($item['causer-id']);
+               unset($item['causer-link']);
 
-                       $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
-                               'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
-                       if (self::exists($condition)) {
-                               // It happens that we receive multiple follow requests by the same author - we only store one.
-                               Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
-                               return 0;
-                       }
-               }
+               // We don't store these fields anymore in the item table
+               unset($item['author-link']);
+               unset($item['author-name']);
+               unset($item['author-avatar']);
+               unset($item['author-network']);
 
-               // Check for hashtags in the body and repair or add hashtag links
-               self::setHashtags($item);
+               unset($item['owner-link']);
+               unset($item['owner-name']);
+               unset($item['owner-avatar']);
 
                $item['thr-parent'] = $item['parent-uri'];
 
-               $notify_type = Delivery::POST;
-               $allow_cid = '';
-               $allow_gid = '';
-               $deny_cid  = '';
-               $deny_gid  = '';
-
-               if ($item['parent-uri'] === $item['uri']) {
-                       $parent_id = 0;
-                       $parent_deleted = 0;
-                       $allow_cid = $item['allow_cid'];
-                       $allow_gid = $item['allow_gid'];
-                       $deny_cid  = $item['deny_cid'];
-                       $deny_gid  = $item['deny_gid'];
-               } else {
-                       // find the parent and snarf the item id and ACLs
-                       // and anything else we need to inherit
-
-                       $fields = ['uri', 'parent-uri', 'id', 'deleted',
-                               'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
-                               'wall', 'private', 'forum_mode', 'origin'];
-                       $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
-                       $params = ['order' => ['id' => false]];
-                       $parent = self::selectFirst($fields, $condition, $params);
-
-                       if (DBA::isResult($parent)) {
-                               // 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;
-                                       }
-                               }
-
-                               $parent_id      = $parent['id'];
-                               $parent_deleted = $parent['deleted'];
-                               $allow_cid      = $parent['allow_cid'];
-                               $allow_gid      = $parent['allow_gid'];
-                               $deny_cid       = $parent['deny_cid'];
-                               $deny_gid       = $parent['deny_gid'];
-                               $item['wall']   = $parent['wall'];
-
-                               /*
-                                * 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']) {
-                                       $item['private'] = 0;
-                               }
-
-                               // 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::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
-                               }
-                       } else {
-                               /*
-                                * Allow one to see reply tweets from status.net even when
-                                * we don't have or can't see the original post.
-                                */
-                               if ($force_parent) {
-                                       Logger::log('$force_parent=true, reply converted to top-level post.');
-                                       $parent_id = 0;
-                                       $item['parent-uri'] = $item['uri'];
-                                       $item['gravity'] = GRAVITY_PARENT;
-                               } else {
-                                       Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
-                                       return 0;
-                               }
-
-                               $parent_deleted = 0;
-                       }
-               }
-
-               if (stristr($item['verb'], Activity::POKE)) {
-                       $notify_type = Delivery::POKE;
-               }
-
-               $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
-               $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
-
-               $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
-                       $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
-               if (self::exists($condition)) {
-                       Logger::log('duplicated item with the same uri found. '.print_r($item,true));
-                       return 0;
-               }
-
-               // 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)) {
-                               Logger::log('duplicated item with the same guid found. '.print_r($item,true));
-                               return 0;
-                       }
-               } elseif ($item['network'] == Protocol::OSTATUS) {
-                       // 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)) {
-                               Logger::log('duplicated item with the same body found. '.print_r($item,true));
+               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']);
+
                // Is this item available in the global items (with uid=0)?
                if ($item["uid"] == 0) {
                        $item["global"] = true;
@@ -1798,22 +1738,10 @@ class Item
                }
 
                // ACL settings
-               if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
-                       $private = 1;
-               } else {
-                       $private = $item['private'];
+               if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
+                       $item["private"] = self::PRIVATE;
                }
 
-               $item["allow_cid"] = $allow_cid;
-               $item["allow_gid"] = $allow_gid;
-               $item["deny_cid"] = $deny_cid;
-               $item["deny_gid"] = $deny_gid;
-               $item["private"] = $private;
-               $item["deleted"] = $parent_deleted;
-
-               // Fill the cache field
-               self::putInCache($item);
-
                if ($notify) {
                        $item['edit'] = false;
                        $item['parent'] = $parent_id;
@@ -1824,69 +1752,93 @@ class Item
                        Hook::callAll('post_remote', $item);
                }
 
-               // This array field is used to trigger some automatic reactions
-               // It is mainly used in the "post_local" hook.
-               unset($item['api_source']);
-
                if (!empty($item['cancel'])) {
                        Logger::log('post cancelled by addon.');
                        return 0;
                }
 
-               /*
-                * Check for already added items.
-                * 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) {
-                       if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
-                               Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
-                               return 0;
-                       }
+               if (empty($item['vid']) && !empty($item['verb'])) {
+                       $item['vid'] = Verb::getID($item['verb']);
                }
 
-               Logger::log('' . print_r($item,true), Logger::DATA);
+               // Creates or assigns the permission set
+               $item['psid'] = PermissionSet::getIdFromACL(
+                       $item['uid'],
+                       $item['allow_cid'],
+                       $item['allow_gid'],
+                       $item['deny_cid'],
+                       $item['deny_gid']
+               );
+
+               unset($item['allow_cid']);
+               unset($item['allow_gid']);
+               unset($item['deny_cid']);
+               unset($item['deny_gid']);
+
+               // This array field is used to trigger some automatic reactions
+               // It is mainly used in the "post_local" hook.
+               unset($item['api_source']);
+
+
+               // Check for hashtags in the body and repair or add hashtag links
+               $item['body'] = self::setHashtags($item['body']);
+
+               // Fill the cache field
+               self::putInCache($item);
 
-               if (array_key_exists('tag', $item)) {
-                       $tags = $item['tag'];
-                       unset($item['tag']);
+               if (stristr($item['verb'], Activity::POKE)) {
+                       $notify_type = Delivery::POKE;
                } else {
-                       $tags = '';
+                       $notify_type = Delivery::POST;
                }
 
-               if (array_key_exists('file', $item)) {
-                       $files = $item['file'];
-                       unset($item['file']);
-               } else {
-                       $files = '';
+               $like_no_comment = DI::config()->get('system', 'like_no_comment');
+
+               DBA::transaction();
+
+               if (!in_array($item['verb'], self::ACTIVITIES)) {
+                       $item['icid'] = self::insertContent($item);
                }
 
-               // Creates or assigns the permission set
-               $item['psid'] = PermissionSet::fetchIDForPost($item);
+               $body = $item['body'];
+
+               // We just remove everything that is content
+               foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
+                       unset($item[$field]);
+               }
+
+               unset($item['activity']);
 
-               // We are doing this outside of the transaction to avoid timing problems
-               if (!self::insertActivity($item)) {
-                       self::insertContent($item);
+               // Filling item related side tables
+
+               // Diaspora signature
+               if (!empty($item['diaspora_signed_text'])) {
+                       DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']], true);
+               }
+
+               unset($item['diaspora_signed_text']);
+
+               // Attached file links
+               if (!empty($item['file'])) {
+                       Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
                }
 
-               $delivery_data = ItemDeliveryData::extractFields($item);
+               unset($item['file']);
 
+               // Delivery relevant data
+               $delivery_data = Post\DeliveryData::extractFields($item);
                unset($item['postopts']);
                unset($item['inform']);
 
-               // These fields aren't stored anymore in the item table, they are fetched upon request
-               unset($item['author-link']);
-               unset($item['author-name']);
-               unset($item['author-avatar']);
-               unset($item['author-network']);
-
-               unset($item['owner-link']);
-               unset($item['owner-name']);
-               unset($item['owner-avatar']);
+               if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
+                       Post\DeliveryData::insert($item['uri-id'], $delivery_data);
+               }
 
-               $like_no_comment = Config::get('system', 'like_no_comment');
+               // Store tags from the body if this hadn't been handled previously in the protocol classes
+               if (!Tag::existsForPost($item['uri-id'])) {
+                       Tag::storeFromBody($item['uri-id'], $body);
+               }
 
-               DBA::transaction();
                $ret = DBA::insert('item', $item);
 
                // When the item was successfully stored we fetch the ID of the item.
@@ -1914,9 +1866,9 @@ class Item
 
                if ($entries > 1) {
                        // There are duplicates. We delete our just created entry.
-                       Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
+                       Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
 
-                       // Yes, we could do a rollback here - but we are having many users with MyISAM.
+                       // Yes, we could do a rollback here - but we possibly are still having users with MyISAM.
                        DBA::delete('item', ['id' => $current_post]);
                        DBA::commit();
                        return 0;
@@ -1947,53 +1899,13 @@ class Item
                        DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
                }
 
-               if ($dsprsig) {
-                       /*
-                        * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
-                        * We can check for this condition when we decode and encode the stuff again.
-                        */
-                       if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
-                               $dsprsig->signature = base64_decode($dsprsig->signature);
-                               Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
-                       }
-
-                       if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
-                               DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
-                       } else {
-                               // The other fields are used by very old Friendica servers, so we currently store them differently
-                               DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
-                                       'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
-                       }
-               }
-
-               if (!empty($diaspora_signed_text)) {
-                       DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
-               }
-
                if ($item['parent-uri'] === $item['uri']) {
                        self::addThread($current_post);
                } else {
                        self::updateThread($parent_id);
                }
-
-               if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
-                       ItemDeliveryData::insert($current_post, $delivery_data);
-               }
-
                DBA::commit();
 
-               /*
-                * Due to deadlock issues with the "term" table we are doing these steps after the commit.
-                * This is not perfect - but a workable solution until we found the reason for the problem.
-                */
-               if (!empty($tags)) {
-                       Term::insertFromTagFieldByItemId($current_post, $tags);
-               }
-
-               if (!empty($files)) {
-                       Term::insertFromFileFieldByItemId($current_post, $files);
-               }
-
                // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
                if (self::tagDeliver($item['uid'], $current_post)) {
                        // Get the user information for the logging
@@ -2028,131 +1940,72 @@ class Item
 
                check_user_notification($current_post);
 
-               if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
-                       Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
-               }
-
-               return $current_post;
-       }
-
-       /**
-        * @brief Insert a new item content entry
-        *
-        * @param array $item The item fields that are to be inserted
-        * @return bool
-        * @throws \Exception
-        */
-       private static function insertActivity(&$item)
-       {
-               $activity_index = self::activityToIndex($item['verb']);
-
-               if ($activity_index < 0) {
-                       return false;
-               }
-
-               $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
+               $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
 
-               // We just remove everything that is content
-               foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
-                       unset($item[$field]);
+               if ($transmit) {
+                       $transmit_item = Item::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)))) {
+                               Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
+                               $transmit = false;
+                       }
                }
 
-               // To avoid timing problems, we are using locks.
-               $locked = DI::lock()->acquire('item_insert_activity');
-               if (!$locked) {
-                       Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
+               if ($transmit) {
+                       Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
                }
 
-               // Do we already have this content?
-               $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
-               if (DBA::isResult($item_activity)) {
-                       $item['iaid'] = $item_activity['id'];
-                       Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
-               } elseif (DBA::insert('item-activity', $fields)) {
-                       $item['iaid'] = DBA::lastInsertId();
-                       Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
-               } else {
-                       // This shouldn't happen.
-                       Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
-                       DI::lock()->release('item_insert_activity');
-                       return false;
-               }
-               if ($locked) {
-                       DI::lock()->release('item_insert_activity');
-               }
-               return true;
+               return $current_post;
        }
 
        /**
-        * @brief Insert a new item content entry
+        * Insert a new item content entry
         *
         * @param array $item The item fields that are to be inserted
         * @throws \Exception
         */
-       private static function insertContent(&$item)
+       private static function insertContent(array $item)
        {
                $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
 
                foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
                        if (isset($item[$field])) {
                                $fields[$field] = $item[$field];
-                               unset($item[$field]);
                        }
                }
 
-               // To avoid timing problems, we are using locks.
-               $locked = DI::lock()->acquire('item_insert_content');
-               if (!$locked) {
-                       Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
-               }
-
-               // Do we already have this content?
                $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
                if (DBA::isResult($item_content)) {
-                       $item['icid'] = $item_content['id'];
-                       Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
-               } elseif (DBA::insert('item-content', $fields)) {
-                       $item['icid'] = DBA::lastInsertId();
-                       Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
-               } else {
-                       // This shouldn't happen.
-                       Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
-               }
-               if ($locked) {
-                       DI::lock()->release('item_insert_content');
+                       $icid = $item_content['id'];
+                       Logger::info('Content found', ['icid' => $icid, 'uri' => $item['uri']]);
+                       return $icid;
                }
-       }
 
-       /**
-        * @brief Update existing item content entries
-        *
-        * @param array $item      The item fields that are to be changed
-        * @param array $condition The condition for finding the item content entries
-        * @return bool
-        * @throws \Exception
-        */
-       private static function updateActivity($item, $condition)
-       {
-               if (empty($item['verb'])) {
-                       return false;
+               DBA::insert('item-content', $fields, true);
+               $icid = DBA::lastInsertId();
+               if ($icid != 0) {
+                       Logger::info('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
+                       return $icid;
                }
-               $activity_index = self::activityToIndex($item['verb']);
 
-               if ($activity_index < 0) {
-                       return false;
+               // Possibly there can be timing issues. Then the same content could be inserted multiple times.
+               // Due to the indexes this doesn't happen, but "lastInsertId" will be empty in these situations.
+               // So we have to fetch the id manually. This is no bug and there is no data loss.
+               $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
+               if (DBA::isResult($item_content)) {
+                       $icid = $item_content['id'];
+                       Logger::notice('Content inserted with empty lastInsertId', ['icid' => $icid, 'uri' => $item['uri']]);
+                       return $icid;
                }
 
-               $fields = ['activity' => $activity_index];
-
-               Logger::log('Update activity for ' . json_encode($condition));
-
-               DBA::update('item-activity', $fields, $condition, true);
-
-               return true;
+               // This shouldn't happen.
+               Logger::error("Content wasn't inserted", $item);
+               return null;
        }
 
        /**
-        * @brief Update existing item content entries
+        * Update existing item content entries
         *
         * @param array $item      The item fields that are to be changed
         * @param array $condition The condition for finding the item content entries
@@ -2169,18 +2022,15 @@ class Item
                }
 
                if (empty($fields)) {
-                       // when there are no fields at all, just use the condition
-                       // This is to ensure that we always store content.
-                       $fields = $condition;
+                       return;
                }
 
-               Logger::log('Update content for ' . json_encode($condition));
-
                DBA::update('item-content', $fields, $condition, true);
+               Logger::info('Updated content', ['condition' => $condition]);
        }
 
        /**
-        * @brief Distributes public items to the receivers
+        * Distributes public items to the receivers
         *
         * @param integer $itemid      Item ID that should be added
         * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
@@ -2197,7 +2047,7 @@ class Item
                // Only distribute public items from native networks
                $condition = ['id' => $itemid, 'uid' => 0,
                        'network' => array_merge(Protocol::FEDERATED ,['']),
-                       'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
+                       'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
                $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
                if (!DBA::isResult($item)) {
                        return;
@@ -2276,7 +2126,7 @@ class Item
        }
 
        /**
-        * @brief Store public items for the receivers
+        * Store public items for the receivers
         *
         * @param integer $itemid Item ID that should be added
         * @param array   $item   The item entry that will be stored
@@ -2312,17 +2162,17 @@ class Item
                        }
                }
 
-               $distributed = self::insert($item, false, $notify, true);
+               $distributed = self::insert($item, $notify, true);
 
                if (!$distributed) {
-                       Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
+                       Logger::info("Distributed public item wasn't stored", ['id' => $itemid, 'user' => $uid]);
                } else {
-                       Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
+                       Logger::info('Distributed public item was stored', ['id' => $itemid, 'user' => $uid, 'stored' => $distributed]);
                }
        }
 
        /**
-        * @brief Add a shadow entry for a given item id that is a thread starter
+        * Add a shadow entry for a given item id that is a thread starter
         *
         * We store every public item entry additionally with the user id "0".
         * This is used for the community page and for the search.
@@ -2347,7 +2197,7 @@ class Item
                }
 
                // Is it a visible public post?
-               if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
+               if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
                        return;
                }
 
@@ -2379,14 +2229,14 @@ class Item
                                $item['contact-id'] = $item['author-id'];
                        }
 
-                       $public_shadow = self::insert($item, false, false, true);
+                       $public_shadow = self::insert($item, false, true);
 
-                       Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
+                       Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
                }
        }
 
        /**
-        * @brief Add a shadow entry for a given item id that is a comment
+        * Add a shadow entry for a given item id that is a comment
         *
         * This function does the same like the function above - but for comments
         *
@@ -2401,7 +2251,7 @@ class Item
                }
 
                // Is it a toplevel post?
-               if ($item['id'] == $item['parent']) {
+               if ($item['gravity'] == GRAVITY_PARENT) {
                        self::addShadow($itemid);
                        return;
                }
@@ -2437,9 +2287,9 @@ class Item
                unset($item['inform']);
                $item['contact-id'] = Contact::getIdForURL($item['author-link']);
 
-               $public_shadow = self::insert($item, false, false, true);
+               $public_shadow = self::insert($item, false, true);
 
-               Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
+               Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
 
                // 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.
@@ -2452,24 +2302,26 @@ class Item
         * Adds a language specification in a "language" element of given $arr.
         * Expects "body" element to exist in $arr.
         *
-        * @param $item
+        * @param array $item
+        * @return string detected language
         * @throws \Text_LanguageDetect_Exception
         */
-       private static function addLanguageToItemArray(&$item)
+       private static function getLanguage(array $item)
        {
                $naked_body = BBCode::toPlaintext($item['body'], false);
 
                $ld = new Text_LanguageDetect();
                $ld->setNameMode(2);
                $languages = $ld->detect($naked_body, 3);
-
                if (is_array($languages)) {
-                       $item['language'] = json_encode($languages);
+                       return json_encode($languages);
                }
+
+               return '';
        }
 
        /**
-        * @brief Creates an unique guid out of a given uri
+        * Creates an unique guid out of a given uri
         *
         * @param string $uri uri of an item entry
         * @param string $host hostname for the GUID prefix
@@ -2515,7 +2367,7 @@ class Item
        }
 
        /**
-        * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
+        * Set "success_update" and "last-item" to the date of the last time we heard from this contact
         *
         * This can be used to filter for inactive contacts.
         * Only do this for public postings to avoid privacy problems, since poco data is public.
@@ -2538,7 +2390,8 @@ class Item
                        Contact::unmarkForArchival($contact);
                }
 
-               $update = (!$arr['private'] && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"])));
+               /// @todo On private posts we could obfuscate the date
+               $update = ($arr['private'] != self::PRIVATE);
 
                // Is it a forum? Then we don't care about the rules from above
                if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
@@ -2548,11 +2401,18 @@ class Item
                }
 
                if ($update) {
-                       DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
-                               ['id' => $arr['contact-id']]);
+                       // The "self" contact id is used (for example in the connectors) when the contact is unknown
+                       // So we have to ensure to only update the last item when it had been our own post,
+                       // or it had been done by a "regular" contact.
+                       if (!empty($arr['wall'])) {
+                               $condition = ['id' => $arr['contact-id']];
+                       } else { 
+                               $condition = ['id' => $arr['contact-id'], 'self' => false];
+                       }
+                       DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
                }
                // Now do the same for the system wide contacts with uid=0
-               if (!$arr['private']) {
+               if ($arr['private'] != self::PRIVATE) {
                        DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
                                ['id' => $arr['owner-id']]);
 
@@ -2563,91 +2423,69 @@ class Item
                }
        }
 
-       public static function setHashtags(&$item)
+       public static function setHashtags($body)
        {
-               $tags = BBCode::getTags($item["body"]);
+               $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
+                       $tags = BBCode::getTags($body);
 
-               // No hashtags?
-               if (!count($tags)) {
-                       return false;
-               }
+                       // No hashtags?
+                       if (!count($tags)) {
+                               return $body;
+                       }
 
-               // What happens in [code], stays in [code]!
-               // escape the # and the [
-               // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
-               $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
-                       function ($match) {
-                               // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
-                               $find = ['#', '['];
-                               $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
-                               return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
-                       }, $item["body"]);
+                       // This sorting is important when there are hashtags that are part of other hashtags
+                       // Otherwise there could be problems with hashtags like #test and #test2
+                       // Because of this we are sorting from the longest to the shortest tag.
+                       usort($tags, function ($a, $b) {
+                               return strlen($b) <=> strlen($a);
+                       });
 
-               // This sorting is important when there are hashtags that are part of other hashtags
-               // Otherwise there could be problems with hashtags like #test and #test2
-               rsort($tags);
+                       $URLSearchString = "^\[\]";
 
-               $URLSearchString = "^\[\]";
+                       // All hashtags should point to the home server if "local_tags" is activated
+                       if (DI::config()->get('system', 'local_tags')) {
+                               $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
+                                       "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
+                       }
 
-               // All hashtags should point to the home server if "local_tags" is activated
-               if (Config::get('system', 'local_tags')) {
-                       $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
-                                       "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
+                       // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
+                       $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
+                               function ($match) {
+                                       return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
+                               }, $body);
 
-                       $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
-                                       "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
-               }
+                       $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
+                               function ($match) {
+                                       return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
+                               }, $body);
 
-               // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
-               $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
-                       function ($match) {
-                               return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
-                       }, $item["body"]);
+                       $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
+                               function ($match) {
+                                       return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
+                               }, $body);
 
-               $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
-                       function ($match) {
-                               return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
-                       }, $item["body"]);
+                       // Repair recursive urls
+                       $body = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
+                               "&num;$2", $body);
 
-               $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
-                       function ($match) {
-                               return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
-                       }, $item["body"]);
+                       foreach ($tags as $tag) {
+                               if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
+                                       continue;
+                               }
 
-               // Repair recursive urls
-               $item["body"] = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
-                               "&num;$2", $item["body"]);
+                               $basetag = str_replace('_', ' ', substr($tag, 1));
+                               $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
 
-               foreach ($tags as $tag) {
-                       if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
-                               continue;
+                               $body = str_replace($tag, $newtag, $body);
                        }
 
-                       $basetag = str_replace('_',' ',substr($tag,1));
-                       $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
-
-                       $item["body"] = str_replace($tag, $newtag, $item["body"]);
-
-                       if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
-                               if (strlen($item["tag"])) {
-                                       $item["tag"] = ',' . $item["tag"];
-                               }
-                               $item["tag"] = $newtag . $item["tag"];
-                       }
-               }
+                       // Convert back the masked hashtags
+                       $body = str_replace("&num;", "#", $body);
 
-               // Convert back the masked hashtags
-               $item["body"] = str_replace("&num;", "#", $item["body"]);
+                       return $body;
+               });
 
-               // Remember! What happens in [code], stays in [code]
-               // roleback the # and [
-               $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
-                       function ($match) {
-                               // we truly unESCape all sharp and leftsquarebracket
-                               $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
-                               $replace = ['#', '['];
-                               return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
-                       }, $item["body"]);
+               return $body;
        }
 
        /**
@@ -2696,10 +2534,8 @@ class Item
 
                if (!$mention) {
                        if (($community_page || $prvgroup) &&
-                                 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
-                               // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
-                               // delete it!
-                               Logger::log("no-mention top-level post to community or private group. delete.");
+                                 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
+                               Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
                                DBA::delete('item', ['id' => $item_id]);
                                return true;
                        }
@@ -2733,9 +2569,15 @@ class Item
 
                // also reset all the privacy bits to the forum default permissions
 
-               $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
+               $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
 
-               $psid = PermissionSet::fetchIDForPost($user);
+               $psid = PermissionSet::getIdFromACL(
+                       $user['uid'],
+                       $user['allow_cid'],
+                       $user['allow_gid'],
+                       $user['deny_cid'],
+                       $user['deny_gid']
+               );
 
                $forum_mode = ($prvgroup ? 2 : 1);
 
@@ -2758,29 +2600,29 @@ class Item
 
                // Prevent the forwarding of posts that are forwarded
                if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
-                       Logger::log('Already forwarded', Logger::DEBUG);
+                       Logger::info('Already forwarded');
                        return false;
                }
 
                // Prevent to forward already forwarded posts
                if ($datarray["app"] == DI::baseUrl()->getHostname()) {
-                       Logger::log('Already forwarded (second test)', Logger::DEBUG);
+                       Logger::info('Already forwarded (second test)');
                        return false;
                }
 
                // Only forward posts
                if ($datarray["verb"] != Activity::POST) {
-                       Logger::log('No post', Logger::DEBUG);
+                       Logger::info('No post');
                        return false;
                }
 
-               if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
-                       Logger::log('Not public', Logger::DEBUG);
+               if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
+                       Logger::info('Not public');
                        return false;
                }
 
                $datarray2 = $datarray;
-               Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
+               Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
                if ($contact['remote_self'] == 2) {
                        $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
                                        ['uid' => $contact['uid'], 'self' => true]);
@@ -2812,14 +2654,14 @@ class Item
                                $urlpart = parse_url($datarray2['author-link']);
                                $datarray["app"] = $urlpart["host"];
                        } else {
-                               $datarray['private'] = 0;
+                               $datarray['private'] = self::PUBLIC;
                        }
                }
 
                if ($contact['network'] != Protocol::FEED) {
                        // Store the original post
-                       $result = self::insert($datarray2, false, false);
-                       Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
+                       $result = self::insert($datarray2);
+                       Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
                } else {
                        $datarray["app"] = "Feed";
                        $result = true;
@@ -2847,11 +2689,11 @@ class Item
         */
        public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
        {
-               if (Config::get('system', 'disable_embedded')) {
+               if (DI::config()->get('system', 'disable_embedded')) {
                        return $s;
                }
 
-               Logger::log('check for photos', Logger::DEBUG);
+               Logger::info('check for photos');
                $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
 
                $orig_body = $s;
@@ -2865,7 +2707,7 @@ class Item
                        $img_st_close++; // make it point to AFTER the closing bracket
                        $image = substr($orig_body, $img_start + $img_st_close, $img_len);
 
-                       Logger::log('found photo ' . $image, Logger::DEBUG);
+                       Logger::info('found photo', ['image' => $image]);
 
                        if (stristr($image, $site . '/photo/')) {
                                // Only embed locally hosted photos
@@ -2904,7 +2746,7 @@ class Item
                                                        $photo_img = Photo::getImageForPhoto($photo);
                                                        // If a custom width and height were specified, apply before embedding
                                                        if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
-                                                               Logger::log('scaling photo', Logger::DEBUG);
+                                                               Logger::info('scaling photo');
 
                                                                $width = intval($match[1]);
                                                                $height = intval($match[2]);
@@ -2915,9 +2757,9 @@ class Item
                                                        $data = $photo_img->asString();
                                                        $type = $photo_img->getType();
 
-                                                       Logger::log('replacing photo', Logger::DEBUG);
+                                                       Logger::info('replacing photo');
                                                        $image = 'data:' . $type . ';base64,' . base64_encode($data);
-                                                       Logger::log('replaced: ' . $image, Logger::DATA);
+                                                       Logger::debug('replaced', ['image' => $image]);
                                                }
                                        }
                                }
@@ -2987,37 +2829,13 @@ class Item
                return $recipients;
        }
 
-       public static function getFeedTags($item)
-       {
-               $ret = [];
-               $matches = false;
-               $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
-               if ($cnt) {
-                       for ($x = 0; $x < $cnt; $x ++) {
-                               if ($matches[1][$x]) {
-                                       $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
-                               }
-                       }
-               }
-               $matches = false;
-               $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
-               if ($cnt) {
-                       for ($x = 0; $x < $cnt; $x ++) {
-                               if ($matches[1][$x]) {
-                                       $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
-                               }
-                       }
-               }
-               return $ret;
-       }
-
        public static function expire($uid, $days, $network = "", $force = false)
        {
                if (!$uid || ($days < 1)) {
                        return;
                }
 
-               $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
+               $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
                        $uid, GRAVITY_PARENT];
 
                /*
@@ -3076,7 +2894,7 @@ class Item
                                continue;
                        }
 
-                       self::deleteById($item['id'], PRIORITY_LOW);
+                       self::markForDeletionById($item['id'], PRIORITY_LOW);
 
                        ++$expired;
                }
@@ -3096,7 +2914,7 @@ class Item
        }
 
        /**
-        * @brief add/remove activity to an item
+        * add/remove activity to an item
         *
         * Toggle activities as like,dislike,attend of an item
         *
@@ -3112,41 +2930,12 @@ class Item
         *            array $arr
         *            'post_id' => ID of posted item
         */
-       public static function performLike($item_id, $verb)
+       public static function performActivity($item_id, $verb)
        {
                if (!Session::isAuthenticated()) {
                        return false;
                }
 
-               switch ($verb) {
-                       case 'like':
-                       case 'unlike':
-                               $activity = Activity::LIKE;
-                               break;
-                       case 'dislike':
-                       case 'undislike':
-                               $activity = Activity::DISLIKE;
-                               break;
-                       case 'attendyes':
-                       case 'unattendyes':
-                               $activity = Activity::ATTEND;
-                               break;
-                       case 'attendno':
-                       case 'unattendno':
-                               $activity = Activity::ATTENDNO;
-                               break;
-                       case 'attendmaybe':
-                       case 'unattendmaybe':
-                               $activity = Activity::ATTENDMAYBE;
-                               break;
-                       default:
-                               Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
-                               return false;
-               }
-
-               // Enable activity toggling instead of on/off
-               $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
-
                Logger::log('like: verb ' . $verb . ' item ' . $item_id);
 
                $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
@@ -3187,7 +2976,7 @@ class Item
                if (local_user() == $uid) {
                        $item_contact_id = $owner_self_contact['id'];
                } else {
-                       $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
+                       $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, false);
                        $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
                        if (!DBA::isResult($item_contact)) {
                                Logger::log('like: unknown item contact ' . $item_contact_id);
@@ -3195,37 +2984,95 @@ class Item
                        }
                }
 
+               $activity = null;
+               switch ($verb) {
+                       case 'like':
+                       case 'unlike':
+                               $activity = Activity::LIKE;
+                               break;
+                       case 'dislike':
+                       case 'undislike':
+                               $activity = Activity::DISLIKE;
+                               break;
+                       case 'attendyes':
+                       case 'unattendyes':
+                               $activity = Activity::ATTEND;
+                               break;
+                       case 'attendno':
+                       case 'unattendno':
+                               $activity = Activity::ATTENDNO;
+                               break;
+                       case 'attendmaybe':
+                       case 'unattendmaybe':
+                               $activity = Activity::ATTENDMAYBE;
+                               break;
+                       case 'follow':
+                       case 'unfollow':
+                               $activity = Activity::FOLLOW;
+                               break;
+                       default:
+                               Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
+                               return false;
+               }
+
+               $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
+
+               // Enable activity toggling instead of on/off
+               $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
+
                // Look for an existing verb row
-               // event participation are essentially radio toggles. If you make a subsequent choice,
-               // we need to eradicate your first choice.
+               // Event participation activities are mutually exclusive, only one of them can exist at all times.
                if ($event_verb_flag) {
                        $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
 
                        // Translate to the index based activity index
-                       $activities = [];
+                       $vids = [];
                        foreach ($verbs as $verb) {
-                               $activities[] = self::activityToIndex($verb);
+                               $vids[] = Verb::getID($verb);
                        }
                } else {
-                       $activities = self::activityToIndex($activity);
+                       $vids = Verb::getID($activity);
                }
 
-               $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
+               $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);
 
-               // If it exists, mark it as deleted
                if (DBA::isResult($like_item)) {
-                       self::deleteById($like_item['id']);
+                       /**
+                        * Truth table for existing activities
+                        *
+                        * |          Inputs            ||      Outputs      |
+                        * |----------------------------||-------------------|
+                        * |  Mode  | Event | Same verb || Delete? | Return? |
+                        * |--------|-------|-----------||---------|---------|
+                        * | create |  Yes  |    Yes    ||   No    |   Yes   |
+                        * | create |  Yes  |    No     ||   Yes   |   No    |
+                        * | create |  No   |    Yes    ||   No    |   Yes   |
+                        * | create |  No   |    No     ||        N/A†       |
+                        * | delete |  Yes  |    Yes    ||   Yes   |   N/A‡  |
+                        * | delete |  Yes  |    No     ||   No    |   N/A‡  |
+                        * | delete |  No   |    Yes    ||   Yes   |   N/A‡  |
+                        * | delete |  No   |    No     ||        N/A†       |
+                        * |--------|-------|-----------||---------|---------|
+                        * |   A    |   B   |     C     || A xor C | !B or C |
+                        *
+                        * † Can't happen: It's impossible to find an existing non-event activity without
+                        *                 the same verb because we are only looking for this single verb.
+                        *
+                        * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
+                        */
+                       if ($mode == 'create' xor $like_item['verb'] == $activity) {
+                               self::markForDeletionById($like_item['id']);
+                       }
 
                        if (!$event_verb_flag || $like_item['verb'] == $activity) {
                                return true;
                        }
                }
 
-               // Verb is "un-something", just trying to delete existing entries
-               if (strpos($verb, 'un') === 0) {
+               // No need to go further if we aren't creating anything
+               if ($mode == 'delete') {
                        return true;
                }
 
@@ -3278,7 +3125,7 @@ class Item
        private static function addThread($itemid, $onlyshadow = false)
        {
                $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
-                       'moderated', 'visible', 'starred', 'contact-id', 'post-type',
+                       '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);
@@ -3292,14 +3139,14 @@ class Item
                if (!$onlyshadow) {
                        $result = DBA::insert('thread', $item);
 
-                       Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
+                       Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
                }
        }
 
        private static function updateThread($itemid, $setmention = false)
        {
                $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
-                       'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
+                       'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
                        'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
                $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
 
@@ -3322,26 +3169,26 @@ class Item
 
                $result = DBA::update('thread', $fields, ['iid' => $itemid]);
 
-               Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
+               Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
        }
 
        private static function deleteThread($itemid, $itemuri = "")
        {
                $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
                if (!DBA::isResult($item)) {
-                       Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
+                       Logger::info('No thread found', ['id' => $itemid]);
                        return;
                }
 
                $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
 
-               Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
+               Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
 
                if ($itemuri != "") {
                        $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
                        if (!self::exists($condition)) {
                                DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
-                               Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
+                               Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
                        }
                }
        }
@@ -3356,7 +3203,7 @@ class Item
                 *
                 * default permissions - anonymous user
                 */
-               $sql = " AND NOT `item`.`private`";
+               $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
 
                // Profile owner - everything is visible
                if ($local_user && ($local_user == $owner_id)) {
@@ -3372,12 +3219,12 @@ class Item
                        $set = PermissionSet::get($owner_id, $remote_user);
 
                        if (!empty($set)) {
-                               $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
+                               $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
                        } else {
                                $sql_set = '';
                        }
 
-                       $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
+                       $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
                }
 
                return $sql;
@@ -3392,16 +3239,16 @@ class Item
        public static function postType($item)
        {
                if (!empty($item['event-id'])) {
-                       return L10n::t('event');
+                       return DI::l10n()->t('event');
                } elseif (!empty($item['resource-id'])) {
-                       return L10n::t('photo');
-               } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) {
-                       return L10n::t('activity');
-               } elseif ($item['id'] != $item['parent']) {
-                       return L10n::t('comment');
+                       return DI::l10n()->t('photo');
+               } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
+                       return DI::l10n()->t('activity');
+               } elseif ($item['gravity'] == GRAVITY_COMMENT) {
+                       return DI::l10n()->t('comment');
                }
 
-               return L10n::t('post');
+               return DI::l10n()->t('post');
        }
 
        /**
@@ -3425,7 +3272,7 @@ class Item
                if ($rendered_hash == ''
                        || $rendered_html == ""
                        || $rendered_hash != hash("md5", $item["body"])
-                       || Config::get("system", "ignore_cache")
+                       || DI::config()->get("system", "ignore_cache")
                ) {
                        self::addRedirToImageTags($item);
 
@@ -3444,7 +3291,7 @@ class Item
                        }
 
                        // Only compare the HTML when we forcefully ignore the cache
-                       if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
+                       if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
                                $update = true;
                        }
 
@@ -3463,7 +3310,7 @@ class Item
        }
 
        /**
-        * @brief Find any non-embedded images in private items and add redir links to them
+        * Find any non-embedded images in private items and add redir links to them
         *
         * @param array &$item The field array of an item row
         */
@@ -3479,7 +3326,7 @@ class Item
                                        continue;
                                }
 
-                               if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
+                               if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
                                        $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
                                        $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
                                }
@@ -3488,7 +3335,7 @@ class Item
        }
 
        /**
-        * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
+        * Given an item array, convert the body element from bbcode to html and add smilie icons.
         * If attach is true, also add icons for item attachments.
         *
         * @param array   $item
@@ -3514,7 +3361,7 @@ class Item
                        return $ev;
                }
 
-               $tags = Term::populateTagsFromItem($item);
+               $tags = Tag::populateFromItem($item);
 
                $item['tags'] = $tags['tags'];
                $item['hashtags'] = $tags['hashtags'];
@@ -3524,7 +3371,7 @@ class Item
                $filter_reasons = [];
                if (!$is_preview && public_contact() != $item['author-id']) {
                        if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
-                               $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
+                               $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
                        }
 
                        $hook_data = [
@@ -3584,7 +3431,7 @@ class Item
                                $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
                                        '$video' => [
                                                'id'     => $id,
-                                               'title'  => L10n::t('View Video'),
+                                               'title'  => DI::l10n()->t('View Video'),
                                                'src'    => $the_url,
                                                'mime'   => $mime,
                                        ],
@@ -3601,10 +3448,10 @@ class Item
                        }
 
                        $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
-                       $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
+                       $title .= ' ' . $mtch[2] . ' ' . 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" >' . $icon . '</a>';
+                       $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
                }
 
                if ($as != '') {
@@ -3642,26 +3489,23 @@ class Item
         */
        public static function getPlink($item)
        {
-               $a = DI::app();
-
-               if ($a->user['nickname'] != "") {
+               if (local_user()) {
                        $ret = [
                                'href' => "display/" . $item['guid'],
                                'orig' => "display/" . $item['guid'],
-                               'title' => L10n::t('View on separate page'),
-                               'orig_title' => L10n::t('view on separate page'),
+                               'title' => DI::l10n()->t('View on separate page'),
+                               'orig_title' => DI::l10n()->t('view on separate page'),
                        ];
 
                        if (!empty($item['plink'])) {
                                $ret["href"] = DI::baseUrl()->remove($item['plink']);
-                               $ret["title"] = L10n::t('link to source');
+                               $ret["title"] = DI::l10n()->t('link to source');
                        }
-
-               } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
+               } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
                        $ret = [
                                'href' => $item['plink'],
                                'orig' => $item['plink'],
-                               'title' => L10n::t('link to source'),
+                               'title' => DI::l10n()->t('link to source'),
                        ];
                } else {
                        $ret = [];
@@ -3733,6 +3577,36 @@ class Item
                return 0;
        }
 
+       /**
+        * Return the URI for a link to the post 
+        * 
+        * @param string $uri URI or link to post
+        *
+        * @return string URI
+        */
+       public static function getURIByLink(string $uri)
+       {
+               $ssl_uri = str_replace('http://', 'https://', $uri);
+               $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
+
+               $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
+               if (DBA::isResult($item)) {
+                       return $item['uri'];
+               }
+
+               $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
+               if (!DBA::isResult($itemcontent)) {
+                       return '';
+               }
+
+               $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
+               if (DBA::isResult($itemuri)) {
+                       return $itemuri['uri'];
+               }
+
+               return '';
+       }
+
        /**
         * Fetches item for given URI or plink
         *
@@ -3748,8 +3622,8 @@ class Item
                        return $item_id;
                }
 
-               if (ActivityPub\Processor::fetchMissingActivity($uri)) {
-                       $item_id = self::searchByLink($uri, $uid);
+               if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
+                       $item_id = self::searchByLink($fetched_uri, $uid);
                } else {
                        $item_id = Diaspora::fetchByURL($uri);
                }
@@ -3811,6 +3685,10 @@ class Item
                // 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]]);
                if (!DBA::isResult($shared_item)) {
+                       if (empty($shared['link'])) {
+                               return $item;
+                       }
+
                        // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
                        $id = self::fetchByLink($shared['link'], $uid);
                        if (empty($id)) {