X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=src%2FModel%2FItem.php;h=f7e7ae8737d0d7647f373a5ffd23deee9e381a5d;hb=a98957eeb29cfb142dfc4cd3e03c5bdfbc373466;hp=db569babb21dda8480c6273ad03fd3545024470b;hpb=2f8c6f00b560647185526357849eb2a0747fb44b;p=friendica.git diff --git a/src/Model/Item.php b/src/Model/Item.php index db569babb2..f7e7ae8737 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -31,6 +31,7 @@ use Friendica\Core\Session; use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; +use Friendica\Database\DBStructure; use Friendica\DI; use Friendica\Model\Post\Category; use Friendica\Protocol\Activity; @@ -72,14 +73,14 @@ class Item 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish', 'event-summary', 'event-desc', 'event-location', 'event-type', 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id', - 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed', 'activity' + 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed' ]; // Field list that is used to deliver items via the protocols const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target', 'private', 'title', 'body', 'location', 'coord', 'app', - 'attach', 'deleted', 'extid', 'post-type', + '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']; @@ -94,8 +95,8 @@ class Item // All fields in the item table const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', - 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', - 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid', + 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid', + 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid', 'created', 'edited', 'commented', 'received', 'changed', 'verb', 'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform', 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', @@ -106,8 +107,8 @@ 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, @@ -118,8 +119,22 @@ class Item const PRIVATE = 1; const UNLISTED = 2; + const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction']; + private static $legacy_mode = null; + private static function getItemFields() + { + $definition = DBStructure::definition('', false); + + $postfields = []; + foreach (self::TABLES as $table) { + $postfields[$table] = array_keys($definition[$table]['fields']); + } + + return $postfields; + } + public static function isLegacyMode() { if (is_null(self::$legacy_mode)) { @@ -203,38 +218,6 @@ class Item return self::selectThreadForUser($uid, $selected, $condition, $params); } - /** - * 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; - } - - /** - * 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]; - } - /** * Fetch a single item row * @@ -294,8 +277,6 @@ class Item if (array_key_exists('verb', $row)) { if (!is_null($row['internal-verb'])) { $row['verb'] = $row['internal-verb']; - } elseif (!is_null($row['internal-activity'])) { - $row['verb'] = self::indexToActivity($row['internal-activity']); } if (in_array($row['verb'], self::ACTIVITIES)) { @@ -319,6 +300,10 @@ class Item } } + 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 file string out of the term entries if (array_key_exists('file', $row) && empty($row['file'])) { @@ -346,7 +331,6 @@ class Item } // Remove internal fields - unset($row['internal-activity']); unset($row['internal-network']); unset($row['internal-uri-id']); unset($row['internal-uid']); @@ -669,13 +653,13 @@ class Item $fields = []; $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', - 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', + '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', 'attach', 'post-type', 'file', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', - 'id' => 'item_id', 'network', 'icid', 'iaid', + 'id' => 'item_id', 'network', 'icid', 'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid', 'network' => 'internal-network', 'psid' => 'internal-psid']; @@ -683,8 +667,6 @@ class Item $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['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST); @@ -705,7 +687,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', @@ -803,10 +786,6 @@ class Item $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`"; } @@ -823,12 +802,12 @@ class Item $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; @@ -849,7 +828,7 @@ class Item } if (in_array('verb', $selected)) { - $selected = array_merge($selected, ['internal-activity', 'internal-verb']); + $selected = array_merge($selected, ['internal-verb']); } if (in_array('ignored', $selected)) { @@ -928,7 +907,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', 'uid', '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) { @@ -958,6 +937,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); @@ -974,34 +957,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'])) { @@ -1009,12 +965,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]); } } } @@ -1113,7 +1067,7 @@ class Item $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::info('Item not found.', ['id' => $item_id]); @@ -1132,7 +1086,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) { @@ -1141,7 +1095,7 @@ class Item } } - $matches = false; + $matches = []; $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER); @@ -1192,8 +1146,6 @@ class Item Post\DeliveryData::delete($item['uri-id']); - // We don't delete the item-activity here, since we need some of the data for ActivityPub - if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) { DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]); } @@ -1206,7 +1158,7 @@ class Item //} // If it's the parent of a comment thread, kill all the kids - if ($item['id'] == $item['parent']) { + if ($item['gravity'] == GRAVITY_PARENT) { self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority); } @@ -1562,7 +1514,7 @@ class Item } } - $item["parent"] = $parent['id']; + $item['parent'] = $parent['id']; $item["deleted"] = $parent['deleted']; $item["allow_cid"] = $parent['allow_cid']; $item['allow_gid'] = $parent['allow_gid']; @@ -1597,8 +1549,8 @@ class Item // 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']]); + DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]); + Logger::info('tagged thread as mention', ['parent' => $item['parent'], 'uid' => $item['uid']]); } // Update the contact relations @@ -1635,6 +1587,8 @@ class Item public static function insert($item, $notify = false, $dontcache = false) { + $structure = self::getItemFields(); + $orig_item = $item; $priority = PRIORITY_HIGH; @@ -1743,11 +1697,11 @@ class Item $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['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); + $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); @@ -1844,8 +1798,8 @@ class Item // Check for hashtags in the body and repair or add hashtag links - self::setHashtags($item); - + $item['body'] = self::setHashtags($item['body']); + // Fill the cache field self::putInCache($item); @@ -1855,23 +1809,22 @@ class Item $notify_type = Delivery::POST; } - // We are doing this outside of the transaction to avoid timing problems - if (in_array($item['verb'], self::ACTIVITIES)) { - $item['iaid'] = self::insertActivity($item); - } else { + $like_no_comment = DI::config()->get('system', 'like_no_comment'); + + DBA::transaction(); + + if (!in_array($item['verb'], self::ACTIVITIES)) { $item['icid'] = self::insertContent($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]); } - $like_no_comment = DI::config()->get('system', 'like_no_comment'); - - DBA::transaction(); + unset($item['activity']); // Filling item related side tables @@ -1902,7 +1855,14 @@ class Item if (!Tag::existsForPost($item['uri-id'])) { Tag::storeFromBody($item['uri-id'], $body); } - + + // Remove all fields that aren't part of the item table + foreach ($item as $field => $value) { + if (!in_array($field, $structure['item'])) { + unset($item[$field]); + } + } + $ret = DBA::insert('item', $item); // When the item was successfully stored we fetch the ID of the item. @@ -2004,6 +1964,9 @@ class Item check_user_notification($current_post); + // Distribute items to users who subscribed to their tags + self::distributeByTags($item, $orig_item); + $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin'])); if ($transmit) { @@ -2024,45 +1987,23 @@ class Item } /** - * Insert a new item content entry + * Distribute the given item to users who subscribed to their tags * - * @param array $item The item fields that are to be inserted - * @return bool - * @throws \Exception + * @param array $item Processed item + * @param array $original Original item */ - private static function insertActivity(array $item) + private static function distributeByTags(array $item, array $original) { - $activity_index = self::activityToIndex($item['verb']); - if ($activity_index < 0) { - // SHouldn't happen at all - return null; - } - - $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']]; - - // 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 (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) { + return; } - // Do we already have this content? - $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]); - if (DBA::isResult($item_activity)) { - $iaid = $item_activity['id']; - Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $iaid . ')'); - } elseif (DBA::insert('item-activity', $fields)) { - $iaid = DBA::lastInsertId(); - Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $iaid . ')'); - } else { - // This shouldn't happen. - $iaid = null; - Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen'); - } - if ($locked) { - DI::lock()->release('item_insert_activity'); + $uids = Tag::getUIDListByURIId($item['uri-id']); + foreach ($uids as $uid) { + $original['uri-id'] = $item['uri-id']; + $stored = self::storeForUser($original, $uid); + Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]); } - return $iaid; } /** @@ -2081,57 +2022,33 @@ class Item } } - // 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)) { $icid = $item_content['id']; - Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $icid . ')'); - } elseif (DBA::insert('item-content', $fields)) { - $icid = DBA::lastInsertId(); - Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $icid . ')'); - } else { - // This shouldn't happen. - $icid = null; - Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen'); + Logger::info('Content found', ['icid' => $icid, 'uri' => $item['uri']]); + return $icid; } - if ($locked) { - DI::lock()->release('item_insert_content'); - } - return $icid; - } - /** - * 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; } /** @@ -2152,14 +2069,11 @@ 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]); } /** @@ -2188,13 +2102,6 @@ class Item $origin = $item['origin']; - unset($item['id']); - unset($item['parent']); - unset($item['mention']); - unset($item['wall']); - unset($item['origin']); - unset($item['starred']); - $users = []; /// @todo add a field "pcid" in the contact table that referrs to the public contact id. @@ -2226,7 +2133,7 @@ class Item DBA::close($contacts); if (!empty($owner['alias'])) { - $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]]; + $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]]; $contacts = DBA::select('contact', ['uid'], $condition); while ($contact = DBA::fetch($contacts)) { if ($contact['uid'] == 0) { @@ -2254,33 +2161,50 @@ class Item if ($origin_uid == $uid) { $item['diaspora_signed_text'] = $signed_text; } - self::storeForUser($itemid, $item, $uid); + self::storeForUser($item, $uid); } } /** * 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 * @param integer $uid The user that will receive the item entry + * @return integer stored item id * @throws \Exception */ - private static function storeForUser($itemid, $item, $uid) + private static function storeForUser(array $item, int $uid) { + if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) { + Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]); + return 0; + } + + unset($item['id']); + unset($item['parent']); + unset($item['mention']); + unset($item['starred']); + $item['uid'] = $uid; $item['origin'] = 0; $item['wall'] = 0; + if ($item['uri'] == $item['parent-uri']) { - $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid); + $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']); } else { - $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid); + $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']); } - if (empty($item['contact-id'])) { + if (!empty($contact['id'])) { + $item['contact-id'] = $contact['id']; + } else { + // Shouldn't happen at all + Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]); $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]); if (!DBA::isResult($self)) { - return; + // Shouldn't happen even less + Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]); + return 0; } $item['contact-id'] = $self['id']; } @@ -2298,10 +2222,11 @@ class Item $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", ['uri-id' => $item['uri-id'], 'user' => $uid]); } else { - Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG); + Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]); } + return $distributed; } /** @@ -2364,7 +2289,7 @@ class Item $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]); } } @@ -2384,7 +2309,7 @@ class Item } // Is it a toplevel post? - if ($item['id'] == $item['parent']) { + if ($item['gravity'] == GRAVITY_PARENT) { self::addShadow($itemid); return; } @@ -2422,7 +2347,7 @@ class Item $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. @@ -2524,7 +2449,7 @@ class Item } /// @todo On private posts we could obfuscate the date - $update = ($arr['private'] != self::PRIVATE); + $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED); // 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"])) { @@ -2542,98 +2467,83 @@ class Item } else { $condition = ['id' => $arr['contact-id'], 'self' => false]; } - DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], $condition); + DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition); } // Now do the same for the system wide contacts with uid=0 if ($arr['private'] != self::PRIVATE) { - DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], + DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], ['id' => $arr['owner-id']]); if ($arr['owner-id'] != $arr['author-id']) { - DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], + DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], ['id' => $arr['author-id']]); } } } - 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 + // Because of this we are sorting from the longest to the shortest tag. + usort($tags, function ($a, $b) { + return strlen($b) <=> strlen($a); + }); - $URLSearchString = "^\[\]"; + $URLSearchString = "^\[\]"; - // All hashtags should point to the home server if "local_tags" is activated - if (DI::config()->get('system', 'local_tags')) { - $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", - "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]); - } + // 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); + } - // 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("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[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("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]"); + }, $body); - $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", - function ($match) { - return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]"); - }, $item["body"]); + $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", + function ($match) { + return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]"); + }, $body); - $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism", - function ($match) { - return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]"); - }, $item["body"]); + $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism", + function ($match) { + return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]"); + }, $body); - // Repair recursive urls - $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", - "#$2", $item["body"]); + // Repair recursive urls + $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", + "#$2", $body); - foreach ($tags as $tag) { - if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') { - continue; - } + foreach ($tags as $tag) { + if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') { + continue; + } - $basetag = str_replace('_',' ',substr($tag,1)); - $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]'; + $basetag = str_replace('_', ' ', substr($tag, 1)); + $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]'; - $item["body"] = str_replace($tag, $newtag, $item["body"]); - } + $body = str_replace($tag, $newtag, $body); + } - // Convert back the masked hashtags - $item["body"] = str_replace("#", "#", $item["body"]); + // Convert back the masked hashtags + $body = str_replace("#", "#", $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; } /** @@ -2682,7 +2592,7 @@ class Item if (!$mention) { if (($community_page || $prvgroup) && - !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) { + !$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; @@ -2748,29 +2658,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'] == self::PRIVATE)) { - Logger::log('Not public', Logger::DEBUG); + 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]); @@ -2809,7 +2719,7 @@ class Item if ($contact['network'] != Protocol::FEED) { // Store the original post $result = self::insert($datarray2); - Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG); + Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]); } else { $datarray["app"] = "Feed"; $result = true; @@ -2841,7 +2751,7 @@ class Item return $s; } - Logger::log('check for photos', Logger::DEBUG); + Logger::info('check for photos'); $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://')); $orig_body = $s; @@ -2855,7 +2765,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 @@ -2894,7 +2804,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]); @@ -2905,9 +2815,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]); } } } @@ -2983,7 +2893,7 @@ class Item return; } - $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?", + $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?", $uid, GRAVITY_PARENT]; /* @@ -3084,39 +2994,6 @@ class Item 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; - case 'follow': - case 'unfollow': - $activity = Activity::FOLLOW; - 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]); @@ -3157,7 +3034,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); @@ -3165,37 +3042,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::markForDeletionById($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; } @@ -3248,7 +3183,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); @@ -3262,14 +3197,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]; @@ -3292,20 +3227,20 @@ 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"]]; @@ -3365,9 +3300,9 @@ class Item return DI::l10n()->t('event'); } elseif (!empty($item['resource-id'])) { return DI::l10n()->t('photo'); - } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) { + } elseif ($item['gravity'] == GRAVITY_ACTIVITY) { return DI::l10n()->t('activity'); - } elseif ($item['id'] != $item['parent']) { + } elseif ($item['gravity'] == GRAVITY_COMMENT) { return DI::l10n()->t('comment'); } @@ -3612,9 +3547,7 @@ 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'], @@ -3626,7 +3559,6 @@ class Item $ret["href"] = DI::baseUrl()->remove($item['plink']); $ret["title"] = DI::l10n()->t('link to source'); } - } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) { $ret = [ 'href' => $item['plink'],