<?php
/**
- * @copyright Copyright (C) 2020, Friendica
+ * @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
namespace Friendica\Model;
+use Friendica\Content\PageInfo;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
use Friendica\Core\Hook;
use Friendica\Model\Tag;
use Friendica\Core\Worker;
use Friendica\Database\DBA;
-use Friendica\Database\DBStructure;
use Friendica\DI;
use Friendica\Model\Post;
use Friendica\Protocol\Activity;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Map;
use Friendica\Util\Network;
+use Friendica\Util\Proxy;
use Friendica\Util\Strings;
use Friendica\Worker\Delivery;
-use Friendica\Repository\PermissionSet as RepPermissionSet;
use LanguageDetection\Language;
class Item
const PT_VIDEO = 18;
const PT_DOCUMENT = 19;
const PT_EVENT = 32;
- const PT_TAG = 64;
- const PT_TO = 65;
- const PT_CC = 66;
- const PT_BTO = 67;
- const PT_BCC = 68;
- const PT_FOLLOWER = 69;
- const PT_ANNOUNCEMENT = 70;
- const PT_COMMENT = 71;
- const PT_STORED = 72;
- const PT_GLOBAL = 73;
- const PT_RELAY = 74;
- const PT_FETCHED = 75;
const PT_PERSONAL_NOTE = 128;
+ // Posting reasons (Why had a post been stored for a user?)
+ const PR_NONE = 0;
+ const PR_TAG = 64;
+ const PR_TO = 65;
+ const PR_CC = 66;
+ const PR_BTO = 67;
+ const PR_BCC = 68;
+ const PR_FOLLOWER = 69;
+ const PR_ANNOUNCEMENT = 70;
+ const PR_COMMENT = 71;
+ const PR_STORED = 72;
+ const PR_GLOBAL = 73;
+ const PR_RELAY = 74;
+ const PR_FETCHED = 75;
+
// Field list that is used to display the items
const DISPLAY_FIELDLIST = [
- 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
+ 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
+ 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri',
'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
- 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'language',
+ 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
- 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
+ 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention',
'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
- 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
- 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type',
+ 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type',
+ 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
- 'writable', 'self', 'cid', 'alias', 'pinned',
- 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
+ 'writable', 'self', 'cid', 'alias',
+ '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'
// 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',
- 'deleted', 'extid', 'post-type', 'gravity',
+ 'parent-guid', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
+ 'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
+ 'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
- 'author-id', 'author-link', 'owner-link', 'contact-uid',
- 'signed_text', 'signature', 'signer', 'network'];
-
- // Field list for "item-content" table that is mixed with the item table
- const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
- 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
- 'object-type', 'object', 'target-type', 'target', 'plink'];
-
- // Field list for "item-content" table that is not present in the "item" table
- const CONTENT_FIELDLIST = ['language', 'raw-body'];
+ 'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
+ 'signed_text', 'network', 'wall', 'contact-id', 'plink', 'forum_mode', 'origin',
+ 'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
+ 'event-created', 'event-edited', 'event-start', 'event-finish',
+ 'event-summary', 'event-desc', 'event-location', 'event-type',
+ 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
// 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', 'vid',
- 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
+ 'contact-id', 'wall', 'gravity', 'extid', 'psid',
'created', 'edited', 'commented', 'received', 'changed', 'verb',
'postopts', 'plink', 'resource-id', 'event-id', 'inform',
- 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
- 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
+ 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
+ 'private', 'pubmail', 'visible', 'starred',
'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
'title', 'content-warning', 'body', 'location', 'coord', 'app',
'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
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)) {
- self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
- }
-
- return self::$legacy_mode;
- }
-
- /**
- * Set the pinned state of an item
- *
- * @param integer $iid Item ID
- * @param integer $uid User ID
- * @param boolean $pinned Pinned state
- */
- public static function setPinned(int $iid, int $uid, bool $pinned)
- {
- DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
- }
-
- /**
- * Get the pinned state
- *
- * @param integer $iid Item ID
- * @param integer $uid User ID
- *
- * @return boolean pinned state
- */
- public static function getPinned(int $iid, int $uid)
- {
- $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
- if (!DBA::isResult($useritem)) {
- return false;
- }
- return (bool)$useritem['pinned'];
- }
-
- /**
- * 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
- * @param array $condition Array of fields for condition
- * @param array $params Array of several parameters
- *
- * @return boolean|object
- * @throws \Exception
- */
- public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
- {
- $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
- if (!DBA::isResult($useritems)) {
- return $useritems;
- }
-
- $pinned = [];
- while ($useritem = DBA::fetch($useritems)) {
- $pinned[] = $useritem['iid'];
- }
- DBA::close($useritems);
-
- if (empty($pinned)) {
- return [];
- }
-
- $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
-
- return self::selectThreadForUser($uid, $selected, $condition, $params);
- }
-
- /**
- * Fetch a single item row
- *
- * @param mixed $stmt statement object
- * @return array|false current row or false
- * @throws \Exception
- */
- public static function fetch($stmt)
- {
- $row = DBA::fetch($stmt);
-
- if (!is_array($row)) {
- return $row;
- }
-
- $row = DBA::castFields('item', $row);
-
- // ---------------------- Transform item structure data ----------------------
-
- // We prefer the data from the user's contact over the public one
- if (!empty($row['author-link']) && !empty($row['contact-link']) &&
- ($row['author-link'] == $row['contact-link'])) {
- if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
- $row['author-avatar'] = $row['contact-avatar'];
- }
- if (isset($row['author-name']) && !empty($row['contact-name'])) {
- $row['author-name'] = $row['contact-name'];
- }
- }
-
- if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
- ($row['owner-link'] == $row['contact-link'])) {
- if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
- $row['owner-avatar'] = $row['contact-avatar'];
- }
- if (isset($row['owner-name']) && !empty($row['contact-name'])) {
- $row['owner-name'] = $row['contact-name'];
- }
- }
-
- // We can always comment on posts from these networks
- if (array_key_exists('writable', $row) &&
- in_array($row['internal-network'], Protocol::FEDERATED)) {
- $row['writable'] = true;
- }
-
- // ---------------------- Transform item content data ----------------------
-
- // Fetch data from the item-content table whenever there is content there
- if (self::isLegacyMode()) {
- $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
- foreach ($legacy_fields as $field) {
- if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
- $row[$field] = $row['internal-item-' . $field];
- }
- unset($row['internal-item-' . $field]);
- }
- }
-
- if (array_key_exists('verb', $row)) {
- if (!is_null($row['internal-verb'])) {
- $row['verb'] = $row['internal-verb'];
- }
-
- 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 file string out of the term entries
- if (array_key_exists('file', $row) && empty($row['file'])) {
- $row['file'] = Post\Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
- }
- }
-
- 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'])) {
- $row['ignored'] = $row['internal-user-ignored'];
- }
-
- // Remove internal fields
- unset($row['internal-network']);
- 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']);
-
- return $row;
- }
-
- /**
- * Fills an array with data from an item query
- *
- * @param object $stmt statement object
- * @param bool $do_close
- * @return array Data array
- */
- public static function inArray($stmt, $do_close = true) {
- if (is_bool($stmt)) {
- return $stmt;
- }
-
- $data = [];
- while ($row = self::fetch($stmt)) {
- $data[] = $row;
- }
- if ($do_close) {
- DBA::close($stmt);
- }
- return $data;
- }
-
- /**
- * Check if item data exists
- *
- * @param array $condition array of fields for condition
- *
- * @return boolean Are there rows for that condition?
- * @throws \Exception
- */
- public static function exists($condition) {
- $stmt = self::select(['id'], $condition, ['limit' => 1]);
-
- if (is_bool($stmt)) {
- $retval = $stmt;
- } else {
- $retval = (DBA::numRows($stmt) > 0);
- }
-
- DBA::close($stmt);
-
- return $retval;
- }
-
- /**
- * Retrieve a single record from the item table for a given user and returns it in an associative array
- *
- * @param integer $uid User ID
- * @param array $selected
- * @param array $condition
- * @param array $params
- * @return bool|array
- * @throws \Exception
- * @see DBA::select
- */
- public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
- {
- $params['uid'] = $uid;
-
- if (empty($selected)) {
- $selected = Item::DISPLAY_FIELDLIST;
- }
-
- return self::selectFirst($selected, $condition, $params);
- }
-
- /**
- * Select rows from the item table for a given user
- *
- * @param integer $uid User ID
- * @param array $selected Array of selected fields, empty for all
- * @param array $condition Array of fields for condition
- * @param array $params Array of several parameters
- *
- * @return boolean|object
- * @throws \Exception
- */
- public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
- {
- $params['uid'] = $uid;
-
- if (empty($selected)) {
- $selected = Item::DISPLAY_FIELDLIST;
- }
-
- return self::select($selected, $condition, $params);
- }
-
- /**
- * Retrieve a single record from the item table and returns it in an associative array
- *
- * @param array $fields
- * @param array $condition
- * @param array $params
- * @return bool|array
- * @throws \Exception
- * @see DBA::select
- */
- public static function selectFirst(array $fields = [], array $condition = [], $params = [])
- {
- $params['limit'] = 1;
-
- $result = self::select($fields, $condition, $params);
-
- if (is_bool($result)) {
- return $result;
- } else {
- $row = self::fetch($result);
- DBA::close($result);
- return $row;
- }
- }
-
- /**
- * Select rows from the item table and returns them as an array
- *
- * @param array $selected Array of selected fields, empty for all
- * @param array $condition Array of fields for condition
- * @param array $params Array of several parameters
- *
- * @return array
- * @throws \Exception
- */
- public static function selectToArray(array $fields = [], array $condition = [], $params = [])
- {
- $result = self::select($fields, $condition, $params);
-
- if (is_bool($result)) {
- return [];
- }
-
- $data = [];
- while ($row = self::fetch($result)) {
- $data[] = $row;
- }
- DBA::close($result);
-
- return $data;
- }
-
- /**
- * Select rows from the item table
- *
- * @param array $selected Array of selected fields, empty for all
- * @param array $condition Array of fields for condition
- * @param array $params Array of several parameters
- *
- * @return boolean|object
- * @throws \Exception
- */
- public static function select(array $selected = [], array $condition = [], $params = [])
- {
- $uid = 0;
- $usermode = false;
-
- if (isset($params['uid'])) {
- $uid = $params['uid'];
- $usermode = true;
- }
-
- $fields = self::fieldlist($usermode);
-
- $select_fields = self::constructSelectFields($fields, $selected);
-
- $condition_string = DBA::buildCondition($condition);
-
- $condition_string = self::addTablesToFields($condition_string, $fields);
-
- if ($usermode) {
- $condition_string = $condition_string . ' AND ' . self::condition(false);
- }
-
- $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
-
- $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
-
- $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
-
- return DBA::p($sql, $condition);
- }
-
- /**
- * Select rows from the starting post in the item table
- *
- * @param integer $uid User ID
- * @param array $selected
- * @param array $condition Array of fields for condition
- * @param array $params Array of several parameters
- *
- * @return boolean|object
- * @throws \Exception
- */
- public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
- {
- $params['uid'] = $uid;
-
- if (empty($selected)) {
- $selected = Item::DISPLAY_FIELDLIST;
- }
-
- return self::selectThread($selected, $condition, $params);
- }
-
- /**
- * Retrieve a single record from the starting post in the item table and returns it in an associative array
- *
- * @param integer $uid User ID
- * @param array $selected
- * @param array $condition
- * @param array $params
- * @return bool|array
- * @throws \Exception
- * @see DBA::select
- */
- public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
- {
- $params['uid'] = $uid;
-
- if (empty($selected)) {
- $selected = Item::DISPLAY_FIELDLIST;
- }
-
- return self::selectFirstThread($selected, $condition, $params);
- }
-
- /**
- * Retrieve a single record from the starting post in the item table and returns it in an associative array
- *
- * @param array $fields
- * @param array $condition
- * @param array $params
- * @return bool|array
- * @throws \Exception
- * @see DBA::select
- */
- public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
- {
- $params['limit'] = 1;
- $result = self::selectThread($fields, $condition, $params);
-
- if (is_bool($result)) {
- return $result;
- } else {
- $row = self::fetch($result);
- DBA::close($result);
- return $row;
- }
- }
-
- /**
- * 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
- * @param array $params Array of several parameters
- *
- * @return boolean|object
- * @throws \Exception
- */
- public static function selectThread(array $selected = [], array $condition = [], $params = [])
- {
- $uid = 0;
- $usermode = false;
-
- if (isset($params['uid'])) {
- $uid = $params['uid'];
- $usermode = true;
- }
-
- $fields = self::fieldlist($usermode);
-
- $fields['thread'] = ['mention', 'ignored', 'iid'];
-
- $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
- 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
- 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
- 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
-
- $select_fields = self::constructSelectFields($fields, $selected);
-
- $condition_string = DBA::buildCondition($condition);
-
- $condition_string = self::addTablesToFields($condition_string, $threadfields);
- $condition_string = self::addTablesToFields($condition_string, $fields);
-
- if ($usermode) {
- $condition_string = $condition_string . ' AND ' . self::condition(true);
- }
-
- $param_string = DBA::buildParameter($params);
- $param_string = self::addTablesToFields($param_string, $threadfields);
- $param_string = self::addTablesToFields($param_string, $fields);
-
- $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
-
- $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
-
- return DBA::p($sql, $condition);
- }
-
- /**
- * Returns a list of fields that are associated with the item table
- *
- * @param $usermode
- * @return array field list
- */
- private static function fieldlist($usermode)
- {
- $fields = [];
-
- $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
- 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid', 'causer-id',
- 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
- 'created', 'edited', 'commented', 'received', 'changed', 'psid',
- 'resource-id', 'event-id', 'post-type', 'file',
- 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
- 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
- '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-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);
-
- $fields['verb'] = ['name' => 'internal-verb'];
-
- $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
-
- $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
- 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
-
- $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
- 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
-
- $fields['causer'] = ['url' => 'causer-link', 'name' => 'causer-name', 'addr' => 'causer-addr',
- 'thumb' => 'causer-avatar', 'nick' => 'causer-nick', 'network' => 'causer-network',
- 'contact-type' => 'causer-contact-type'];
-
- $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
- 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
- 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
-
- $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
-
- $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',
- 'summary' => 'event-summary','desc' => 'event-desc',
- 'location' => 'event-location', 'type' => 'event-type',
- 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
- 'ignore' => 'event-ignore', 'id' => 'event-id'];
-
- $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
-
- return $fields;
- }
-
- /**
- * Returns SQL condition for the "select" functions
- *
- * @param boolean $thread_mode Called for the items (false) or for the threads (true)
- *
- * @return string SQL condition
- */
- private static function condition($thread_mode)
- {
- if ($thread_mode) {
- $master_table = "`thread`";
- } else {
- $master_table = "`item`";
- }
- return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
- AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
- AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
- AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
- AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
- AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
- GRAVITY_PARENT, GRAVITY_PARENT);
- }
-
- /**
- * 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
- * @param boolean $thread_mode Called for the items (false) or for the threads (true)
- *
- * @param $user_mode
- * @return string The SQL joins for the "select" functions
- */
- private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
- {
- if ($thread_mode) {
- $master_table = "`thread`";
- $master_table_key = "`thread`.`iid`";
- $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
- } else {
- $master_table = "`item`";
- $master_table_key = "`item`.`id`";
- $joins = '';
- }
-
- if ($user_mode) {
- $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
- AND NOT `contact`.`blocked`
- AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
- OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
- STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
- STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
- LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
- LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
- LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
- Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
- } else {
- if (strpos($sql_commands, "`contact`.") !== false) {
- $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
- }
- if (strpos($sql_commands, "`author`.") !== false) {
- $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
- }
- if (strpos($sql_commands, "`owner`.") !== false) {
- $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
- }
- }
- if (strpos($sql_commands, "`causer`.") !== false) {
- $joins .= " LEFT JOIN `contact` AS `causer` ON `causer`.`id` = `item`.`causer-id`";
- }
-
- if (strpos($sql_commands, "`group_member`.") !== false) {
- $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
- }
-
- if (strpos($sql_commands, "`user`.") !== false) {
- $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
- }
-
- if (strpos($sql_commands, "`event`.") !== false) {
- $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`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-content`.") !== false) {
- $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-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-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`";
- }
- }
-
- return $joins;
- }
-
- /**
- * 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(array $fields, array $selected)
- {
- if (!empty($selected)) {
- $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
- }
-
- if (in_array('verb', $selected)) {
- $selected = array_merge($selected, ['internal-verb']);
- }
-
- if (in_array('ignored', $selected)) {
- $selected[] = 'internal-user-ignored';
- }
-
- $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
-
- $selection = [];
- foreach ($fields as $table => $table_fields) {
- foreach ($table_fields as $field => $select) {
- if (empty($selected) || in_array($select, $selected)) {
- if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
- $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
- }
- if (is_int($field)) {
- $selection[] = "`" . $table . "`.`" . $select . "`";
- } else {
- $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
- }
- }
- }
- }
- return implode(", ", $selection);
- }
-
- /**
- * add table definition to fields in an SQL query
- *
- * @param string $query SQL query
- * @param array $fields The field definition array
- *
- * @return string the changed SQL query
- */
- private static function addTablesToFields($query, $fields)
- {
- foreach ($fields as $table => $table_fields) {
- foreach ($table_fields as $alias => $field) {
- if (is_int($alias)) {
- $replace_field = $field;
- } else {
- $replace_field = $alias;
- }
-
- $search = "/([^\.])`" . $field . "`/i";
- $replace = "$1`" . $table . "`.`" . $replace_field . "`";
- $query = preg_replace($search, $replace, $query);
- }
- }
- return $query;
- }
-
/**
* Update existing item entries
*
return false;
}
- $data_fields = $fields;
-
- // To ensure the data integrity we do it in an transaction
- DBA::transaction();
-
- // 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', 'icid', 'uid', 'file'], $condition);
-
- $content_fields = [];
- foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
- if (isset($fields[$field])) {
- $content_fields[$field] = $fields[$field];
- if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
- unset($fields[$field]);
- } else {
- $fields[$field] = null;
- }
- }
+ if (isset($fields['extid'])) {
+ $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
}
- $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) {
- if (array_key_exists($field, $fields)) {
- $fields[$field] = null;
- }
+ if (!empty($fields['verb'])) {
+ $fields['vid'] = Verb::getID($fields['verb']);
}
- if (array_key_exists('file', $fields)) {
- $files = $fields['file'];
- $fields['file'] = null;
- } else {
- $files = null;
+ $rows = Post::update($fields, $condition);
+ if (is_bool($rows)) {
+ return $rows;
}
- if (!empty($content_fields['verb'])) {
- $fields['vid'] = Verb::getID($content_fields['verb']);
+ // We only need to call the line by line update for specific fields
+ if (empty($fields['body']) && empty($fields['file']) &&
+ empty($fields['attach']) && empty($fields['edited'])) {
+ return $rows;
}
- if (!empty($fields)) {
- $success = DBA::update('item', $fields, $condition);
+ Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
- if (!$success) {
- DBA::close($items);
- DBA::rollback();
- return false;
- }
- }
-
- // When there is no content for the "old" item table, this will count the fetched items
- $rows = DBA::affectedRows();
+ $items = Post::select(['id', 'origin', 'uri-id', 'uid'], $condition);
$notify_items = [];
while ($item = DBA::fetch($items)) {
- Post\User::update($item['uri-id'], $item['uid'], $data_fields);
-
- if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
- if (!empty($content_fields['body'])) {
- $content_fields['raw-body'] = trim($content_fields['raw-body'] ?? $content_fields['body']);
-
- // Remove all media attachments from the body and store them in the post-media table
- $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
- $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
- }
-
- self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
-
- if (empty($item['icid'])) {
- $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
- if (DBA::isResult($item_content)) {
- $item_fields = ['icid' => $item_content['id']];
- // Clear all fields in the item table that have a content in the item-content table
- if (self::isLegacyMode()) {
- foreach ($item_content as $field => $content) {
- if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
- $item_fields[$field] = null;
- }
- }
- }
- DBA::update('item', $item_fields, ['id' => $item['id']]);
- }
- }
+ if (!empty($fields['body'])) {
+ Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
+
+ $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
+
+ // Remove all media attachments from the body and store them in the post-media table
+ // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
+ $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
+ $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
}
- if (!is_null($files)) {
- Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
- if (!empty($item['file'])) {
- DBA::update('item', ['file' => ''], ['id' => $item['id']]);
- }
+ if (!empty($fields['file'])) {
+ Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
}
if (!empty($fields['attach'])) {
Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
}
- Post\DeliveryData::update($item['uri-id'], $delivery_data);
-
- self::updateThread($item['id']);
-
// We only need to notfiy others when it is an original entry from us.
// Only call the notifier when the item has some content relevant change.
if ($item['origin'] && in_array('edited', array_keys($fields))) {
}
DBA::close($items);
- DBA::commit();
foreach ($notify_items as $notify_item) {
- Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
+ $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
+ Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
}
return $rows;
*/
public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
{
- $items = self::select(['id'], $condition);
- while ($item = self::fetch($items)) {
+ $items = Post::select(['id'], $condition);
+ while ($item = Post::fetch($items)) {
self::markForDeletionById($item['id'], $priority);
}
DBA::close($items);
return;
}
- $items = self::select(['id', 'uid', 'uri-id'], $condition);
- while ($item = self::fetch($items)) {
- Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
+ $items = Post::select(['id', 'uid', 'uri-id'], $condition);
+ while ($item = Post::fetch($items)) {
+ if (in_array($item['uid'], [$uid, 0])) {
+ Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
+ Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
+ }
- // "Deleting" global items just means hiding them
- if ($item['uid'] == 0) {
- DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
- } elseif ($item['uid'] == $uid) {
+ if ($item['uid'] == $uid) {
self::markForDeletionById($item['id'], PRIORITY_HIGH);
- } else {
- Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
+ } elseif ($item['uid'] != 0) {
+ Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
}
}
DBA::close($items);
{
Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
// locate item to be deleted
- $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
- 'deleted', 'file', 'resource-id', 'event-id',
- 'verb', 'object-type', 'object', 'target', 'contact-id',
- 'icid', 'psid', 'gravity'];
- $item = self::selectFirst($fields, ['id' => $item_id]);
+ $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
+ 'deleted', 'resource-id', 'event-id',
+ 'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
+ $item = Post::selectFirst($fields, ['id' => $item_id]);
if (!DBA::isResult($item)) {
Logger::info('Item not found.', ['id' => $item_id]);
return false;
return false;
}
- $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
+ $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
if (!DBA::isResult($parent)) {
$parent = ['origin' => false];
}
// clean up categories and tags so they don't end up as orphans
-
- $matches = [];
- $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
-
- if ($cnt) {
- foreach ($matches as $mtch) {
- FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
- }
- }
-
- $matches = [];
-
- $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
-
- if ($cnt) {
- foreach ($matches as $mtch) {
- FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
- }
- }
+ Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
/*
* If item is a link to a photo resource, nuke all the associated photos
// Set the item to "deleted"
$item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
- DBA::update('item', $item_fields, ['id' => $item['id']]);
+ Post::update($item_fields, ['id' => $item['id']]);
Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
- self::deleteThread($item['id'], $item['parent-uri']);
- if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
- self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
+ if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
+ self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
}
Post\DeliveryData::delete($item['uri-id']);
- // When the permission set will be used in photo and events as well,
- // this query here needs to be extended.
- // @todo Currently deactivated. We need the permission set in the deletion process.
- // This is a reminder to add the removal somewhere else.
- //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
- // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
- //}
-
// If it's the parent of a comment thread, kill all the kids
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']) && ($item['uid'] != 0)) {
// When we delete the original post we will delete all existing copies on the server as well
- self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
+ self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
// send the notification upstream/downstream
if ($priority) {
- Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
+ Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
}
} elseif ($item['uid'] != 0) {
Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
-
- // When we delete just our local user copy of an item, we have to set a marker to hide it
- $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
- if (DBA::isResult($global_item)) {
- DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
- }
+ Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
}
Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
return true;
}
-
private static function guid($item, $notify)
{
if (!empty($item['guid'])) {
return $item['author-id'];
}
- // This function will finally cover most of the preparation functionality in mod/item.php
- public static function prepare(&$item)
- {
- /*
- * @TODO: Unused code triggering inspection errors
- *
- $data = BBCode::getAttachmentData($item['body']);
- if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
- && ($posttype != Item::PT_PERSONAL_NOTE)) {
- $posttype = Item::PT_PAGE;
- $objecttype = ACTIVITY_OBJ_BOOKMARK;
- }
- */
- }
-
/**
* Write an item array into a spool file to be inserted later.
* This command is called whenever there are issues storing an item.
{
// Checking if there is already an item with the same guid
$condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
- if (self::exists($condition)) {
+ if (Post::exists($condition)) {
Logger::notice('Found already existing item', [
'guid' => $item['guid'],
'uid' => $item['uid'],
return true;
}
- $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
- $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
- if (self::exists($condition)) {
+ $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
+ 'network' => [$item['network'], Protocol::DFRN]];
+ if (Post::exists($condition)) {
Logger::notice('duplicated item with the same uri found.', $item);
return true;
}
// On Friendica and Diaspora the GUID is unique
if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
$condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
- if (self::exists($condition)) {
+ if (Post::exists($condition)) {
Logger::notice('duplicated item with the same guid found.', $item);
return true;
}
// Check for an existing post with the same content. There seems to be a problem with OStatus.
$condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
$item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
- if (self::exists($condition)) {
+ if (Post::exists($condition)) {
Logger::notice('duplicated item with the same body found.', $item);
return true;
}
* 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']]);
+ if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
+ Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
return true;
}
public static function isValid(array $item)
{
// When there is no content then we don't post it
- if ($item['body'] . $item['title'] == '') {
+ if (($item['body'] . $item['title'] == '') && !Post\Media::existsByURIId($item['uri-id'])) {
Logger::notice('No body, no title.');
return false;
}
$condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
- if (self::exists($condition)) {
+ if (Post::exists($condition)) {
// It happens that we receive multiple follow requests by the same author - we only store one.
Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
return false;
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'],
+ $condition = ["`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
+ $item['uri-id'], $item['uid'],
Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
- $existing = self::selectFirst(['id', 'network'], $condition);
+ $existing = Post::selectFirst(['id', 'network'], $condition);
if (DBA::isResult($existing)) {
// We only log the entries with a different user id than 0. Otherwise we would have too many false positives
if ($item['uid'] != 0) {
Logger::notice('Item already existed for user', [
- 'uri' => $item['uri'],
+ 'uri-id' => $item['uri-id'],
'uid' => $item['uid'],
'network' => $item['network'],
'existing_id' => $existing["id"],
private static function getTopLevelParent(array $item)
{
$fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
+ 'uri-id', 'parent-uri-id',
'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
'wall', 'private', 'forum_mode', 'origin', 'author-id'];
- $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid']];
+ $condition = ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']];
$params = ['order' => ['id' => false]];
- $parent = self::selectFirst($fields, $condition, $params);
+ $parent = Post::selectFirst($fields, $condition, $params);
if (!DBA::isResult($parent)) {
- Logger::notice('item parent was not found - ignoring item', ['thr-parent' => $item['thr-parent'], 'uid' => $item['uid']]);
+ Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return [];
}
- if ($parent['uri'] == $parent['parent-uri']) {
+ if ($parent['uri-id'] == $parent['parent-uri-id']) {
return $parent;
}
- $condition = ['uri' => $parent['parent-uri'],
- 'parent-uri' => $parent['parent-uri'],
+ $condition = ['uri-id' => $parent['parent-uri-id'],
+ 'parent-uri-id' => $parent['parent-uri-id'],
'uid' => $parent['uid']];
$params = ['order' => ['id' => false]];
- $toplevel_parent = self::selectFirst($fields, $condition, $params);
+ $toplevel_parent = Post::selectFirst($fields, $condition, $params);
if (!DBA::isResult($toplevel_parent)) {
- Logger::notice('item top level parent was not found - ignoring item', ['parent-uri' => $parent['parent-uri'], 'uid' => $parent['uid']]);
+ Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
return [];
}
if (isset($item['gravity'])) {
return intval($item['gravity']);
- } elseif ($item['parent-uri'] === $item['uri']) {
+ } elseif ($item['parent-uri-id'] === $item['uri-id']) {
return GRAVITY_PARENT;
} elseif ($activity->match($item['verb'], Activity::POST)) {
return GRAVITY_COMMENT;
public static function insert($item, $notify = false, $dontcache = false)
{
- $structure = self::getItemFields();
-
$orig_item = $item;
$priority = PRIORITY_HIGH;
$item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
$item['parent-uri'] = $item['thr-parent'];
+ $item['thr-parent-id'] = $item['parent-uri-id'] = ItemURI::getIdByURI($item['thr-parent']);
+
// Store conversation data
$item = Conversation::insert($item);
return 0;
}
+ if (!isset($item['post-type'])) {
+ $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
+ }
+
$item['wall'] = intval($item['wall'] ?? 0);
$item['extid'] = trim($item['extid'] ?? '');
$item['author-name'] = trim($item['author-name'] ?? '');
$item['coord'] = trim($item['coord'] ?? '');
$item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
$item['deleted'] = 0;
- $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
$item['verb'] = trim($item['verb'] ?? '');
$item['object-type'] = trim($item['object-type'] ?? '');
$item['object'] = trim($item['object'] ?? '');
$actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
- $item['post-type'] = self::PT_FOLLOWER;
+ $item['post-reason'] = self::PR_FOLLOWER;
}
// Ensure that there is an avatar cache
}
// If the thread originated from this node, we check the permission against the thread starter
- $condition = ['uri' => $toplevel_parent['uri'], 'wall' => true];
- $localTopLevelParent = self::selectFirst(['uid'], $condition);
+ $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
+ $localTopLevelParent = Post::selectFirst(['uid'], $condition);
if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
return 0;
}
- $parent_id = $toplevel_parent['id'];
- $item['parent-uri'] = $toplevel_parent['uri'];
- $item['deleted'] = $toplevel_parent['deleted'];
- $item['allow_cid'] = $toplevel_parent['allow_cid'];
- $item['allow_gid'] = $toplevel_parent['allow_gid'];
- $item['deny_cid'] = $toplevel_parent['deny_cid'];
- $item['deny_gid'] = $toplevel_parent['deny_gid'];
- $parent_origin = $toplevel_parent['origin'];
+ $parent_id = $toplevel_parent['id'];
+ $item['parent-uri'] = $toplevel_parent['uri'];
+ $item['parent-uri-id'] = $toplevel_parent['uri-id'];
+ $item['deleted'] = $toplevel_parent['deleted'];
+ $item['allow_cid'] = $toplevel_parent['allow_cid'];
+ $item['allow_gid'] = $toplevel_parent['allow_gid'];
+ $item['deny_cid'] = $toplevel_parent['deny_cid'];
+ $item['deny_gid'] = $toplevel_parent['deny_gid'];
+ $parent_origin = $toplevel_parent['origin'];
// Don't federate received participation messages
if ($item['verb'] != Activity::FOLLOW) {
$item['wall'] = $toplevel_parent['wall'];
} else {
$item['wall'] = false;
+ // Participations are technical messages, so they are set to "seen" automatically
+ $item['unseen'] = false;
}
/*
// If its a post that originated here then tag the thread as "mention"
if ($item['origin'] && $item['uid']) {
- DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
- Logger::info('tagged thread as mention', ['parent' => $parent_id, 'uid' => $item['uid']]);
+ DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
+ Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
}
// Update the contact relations
Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
-
- unset($item['parent_origin']);
} else {
$parent_id = 0;
$parent_origin = $item['origin'];
}
- // We don't store the causer link, only the id
- unset($item['causer-link']);
-
- // 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']);
-
- unset($item['owner-link']);
- unset($item['owner-name']);
- unset($item['owner-avatar']);
-
$item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
$item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
$item["global"] = true;
// Set the global flag on all items if this was a global item entry
- DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
+ Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
} else {
- $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
+ $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
}
// ACL settings
$item['edit'] = false;
$item['parent'] = $parent_id;
Hook::callAll('post_local', $item);
- unset($item['edit']);
} else {
Hook::callAll('post_remote', $item);
}
- // Set after the insert because top-level posts are self-referencing
- unset($item['parent']);
-
if (!empty($item['cancel'])) {
Logger::log('post cancelled by addon.');
return 0;
$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']);
+ if (!empty($item['extid'])) {
+ $item['external-id'] = ItemURI::getIdByURI($item['extid']);
+ }
if ($item['verb'] == Activity::ANNOUNCE) {
self::setOwnerforResharedItem($item);
}
+ Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
+
// Remove all media attachments from the body and store them in the post-media table
$item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
$item['raw-body'] = self::setHashtags($item['raw-body']);
// Check for hashtags in the body and repair or add hashtag links
$item['body'] = self::setHashtags($item['body']);
- if (!empty($item['attach'])) {
- Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
- }
-
// Fill the cache field
self::putInCache($item);
$notify_type = Delivery::POST;
}
- if (!in_array($item['verb'], self::ACTIVITIES)) {
- $item['icid'] = self::insertContent($item);
- if (empty($item['icid'])) {
- // This shouldn't happen
- Logger::warning('No content stored, quitting', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'causer-id' => ($item['causer-id'] ?? 0), 'post-type' => $item['post-type'], 'network' => $item['network']]);
- return 0;
- }
+ // Filling item related side tables
+ if (!empty($item['attach'])) {
+ Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
}
- $body = $item['body'];
- $verb = $item['verb'];
+ if (empty($item['event-id'])) {
+ unset($item['event-id']);
+ }
- // We just remove everything that is content
- foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
- unset($item[$field]);
+ if (empty($item['causer-id'])) {
+ unset($item['causer-id']);
}
- unset($item['activity']);
+ Post::insert($item['uri-id'], $item);
- // Filling item related side tables
+ if ($item['gravity'] == GRAVITY_PARENT) {
+ Post\Thread::insert($item['uri-id'], $item);
+ }
+
+ if (!in_array($item['verb'], self::ACTIVITIES)) {
+ Post\Content::insert($item['uri-id'], $item);
+ }
// Diaspora signature
if (!empty($item['diaspora_signed_text'])) {
DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
}
- unset($item['diaspora_signed_text']);
-
// Attached file links
if (!empty($item['file'])) {
Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
}
- unset($item['file']);
-
// Delivery relevant data
$delivery_data = Post\DeliveryData::extractFields($item);
- unset($item['postopts']);
- unset($item['inform']);
if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
Post\DeliveryData::insert($item['uri-id'], $delivery_data);
// 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);
+ Tag::storeFromBody($item['uri-id'], $item['body']);
}
- if (Post\User::insert($item['uri-id'], $item['uid'], $item)) {
- // Remove all fields that aren't part of the item table
- foreach ($item as $field => $value) {
- if (!in_array($field, $structure['item'])) {
- unset($item[$field]);
- }
- }
-
- $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network']];
- if (DBA::exists('item', $condition)) {
- Logger::notice('Item is already inserted - aborting', $condition);
- return 0;
- }
-
- $result = DBA::insert('item', $item);
-
- // When the item was successfully stored we fetch the ID of the item.
- $current_post = DBA::lastInsertId();
- } else {
- Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
+ $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
+ if (Post::exists($condition)) {
+ Logger::notice('Item is already inserted - aborting', $condition);
return 0;
}
- if (empty($current_post) || !DBA::isResult($result)) {
- // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
- Logger::warning('Could not store item. it will be spooled', ['result' => $result, 'id' => $current_post]);
- self::spool($orig_item);
+ $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
+ if (!$post_user_id) {
+ Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
return 0;
}
- Logger::notice('created item', ['id' => $current_post, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
-
- if (!$parent_id || ($item['gravity'] === GRAVITY_PARENT)) {
- $parent_id = $current_post;
+ if ($item['gravity'] == GRAVITY_PARENT) {
+ $item['post-user-id'] = $post_user_id;
+ Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
}
- // Set parent id
- DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
+ Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
- $item['id'] = $current_post;
- $item['parent'] = $parent_id;
+ $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
+ if (!DBA::isResult($posted_item)) {
+ // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
+ Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
+ self::spool($orig_item);
+ return 0;
+ }
// update the commented timestamp on the parent
if (DI::config()->get('system', 'like_no_comment')) {
// Update when it is a comment
- $update_commented = in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
+ $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
} else {
// Update when it isn't a follow or tag verb
- $update_commented = !in_array($verb, [Activity::FOLLOW, Activity::TAG]);
+ $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
}
if ($update_commented) {
- DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
+ $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
} else {
- DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
+ $fields = ['changed' => DateTimeFormat::utcNow()];
}
- if ($item['gravity'] === GRAVITY_PARENT) {
- self::addThread($current_post);
- } else {
- self::updateThread($parent_id);
- }
+ Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
// 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)) {
+ if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
// Get the user information for the logging
$user = User::getById($uid);
- Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
+ Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
return 0;
}
if (!$dontcache) {
- $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
- if (DBA::isResult($posted_item)) {
- if ($notify) {
- Hook::callAll('post_local_end', $posted_item);
- } else {
- Hook::callAll('post_remote_end', $posted_item);
- }
+ if ($notify) {
+ Hook::callAll('post_local_end', $posted_item);
} else {
- Logger::log('new item not found in DB, id ' . $current_post);
+ Hook::callAll('post_remote_end', $posted_item);
}
}
- if ($item['gravity'] === GRAVITY_PARENT) {
- self::addShadow($current_post);
+ if ($posted_item['gravity'] === GRAVITY_PARENT) {
+ self::addShadow($post_user_id);
} else {
- self::addShadowPost($current_post);
+ self::addShadowPost($post_user_id);
}
- self::updateContact($item);
+ self::updateContact($posted_item);
- UserItem::setNotification($current_post);
+ Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
- check_user_notification($current_post);
+ check_user_notification($posted_item['uri-id'], $posted_item['uid']);
// Distribute items to users who subscribed to their tags
- self::distributeByTags($item);
+ self::distributeByTags($posted_item);
// Automatically reshare the item if the "remote_self" option is selected
- self::autoReshare($item);
+ self::autoReshare($posted_item);
- $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
+ $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
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']]);
+ if (($posted_item['verb'] == Activity::FOLLOW) &&
+ (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
+ Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
$transmit = false;
}
}
if ($transmit) {
- Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
+ Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
}
- return $current_post;
+ return $post_user_id;
}
/**
*/
private static function setOwnerforResharedItem(array $item)
{
- $parent = self::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
+ $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
if (!DBA::isResult($parent)) {
Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return;
}
- $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
+ $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
if (!DBA::isResult($author)) {
Logger::error('Author not found', ['id' => $item['author-id']]);
return;
$cid = Contact::getIdForURL($author['url'], $item['uid']);
if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
- Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
+ Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
return;
}
if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
- if ($parent['post-type'] == self::PT_ANNOUNCEMENT) {
+ if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
return;
}
Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
return;
}
- self::update(['post-type' => self::PT_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
- Logger::info('Set announcement post-type', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
+ self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
+ Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return;
}
if (Contact::isSharing($item['author-id'], $uid)) {
$fields = [];
} else {
- $fields = ['post-type' => self::PT_TAG];
+ $fields = ['post-reason' => self::PR_TAG];
}
$stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
}
}
- /**
- * Insert a new item content entry
- *
- * @param array $item The item fields that are to be inserted
- * @throws \Exception
- */
- 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];
- }
- }
-
- $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
- if (DBA::isResult($item_content)) {
- $icid = $item_content['id'];
- Logger::info('Existing content found', ['icid' => $icid, 'uri' => $item['uri']]);
- return $icid;
- }
-
- DBA::replace('item-content', $fields);
-
- $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', ['icid' => $icid, 'uri' => $item['uri']]);
- return $icid;
- }
-
- // This shouldn't happen.
- Logger::error("Content wasn't inserted", $item);
- return null;
- }
-
- /**
- * 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
- * @throws \Exception
- */
- private static function updateContent($item, $condition)
- {
- // We have to select only the fields from the "item-content" table
- $fields = [];
- foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
- if (isset($item[$field])) {
- $fields[$field] = $item[$field];
- }
- }
-
- if (empty($fields)) {
- return;
- }
-
- DBA::update('item-content', $fields, $condition, true);
- Logger::info('Updated content', ['condition' => $condition]);
- }
-
/**
* Distributes public items to the receivers
*
*/
public static function distribute($itemid, $signed_text = '')
{
- $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
- $parent = self::selectFirst(['owner-id'], $condition);
+ $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
+ $parent = Post::selectFirst(['owner-id'], $condition);
if (!DBA::isResult($parent)) {
+ Logger::warning('Item not found', ['condition' => $condition]);
return;
}
// Only distribute public items from native networks
$condition = ['id' => $itemid, 'uid' => 0,
'network' => array_merge(Protocol::FEDERATED ,['']),
- 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
- $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
+ 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
if (!DBA::isResult($item)) {
+ Logger::warning('Item not found', ['condition' => $condition]);
return;
}
$origin_uid = 0;
- if ($item['uri'] != $item['parent-uri']) {
- $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
- while ($parent = self::fetch($parents)) {
+ if ($item['uri-id'] != $item['parent-uri-id']) {
+ $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
+ while ($parent = Post::fetch($parents)) {
$users[$parent['uid']] = $parent['uid'];
if ($parent['origin'] && !$origin) {
$origin_uid = $parent['uid'];
}
}
+ DBA::close($parents);
}
foreach ($users as $uid) {
*/
public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
{
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
if (!DBA::isResult($item)) {
return 0;
}
return 0;
}
- $item['post-type'] = self::PT_STORED;
+ $item['post-reason'] = self::PR_STORED;
$item = array_merge($item, $fields);
*/
private static function storeForUser(array $item, int $uid)
{
- if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
+ if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
return 0;
}
*/
private static function addShadow($itemid)
{
- $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
- $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
- $item = self::selectFirst($fields, $condition);
+ $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
+ $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
+ $item = Post::selectFirst($fields, $condition);
if (!DBA::isResult($item)) {
return;
}
// Is it a visible public post?
- if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
+ if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) {
return;
}
return;
}
- if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
+ if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
return;
}
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
if (DBA::isResult($item)) {
// Preparing public shadow (removing user specific data)
unset($item['starred']);
unset($item['postopts']);
unset($item['inform']);
- unset($item['post-type']);
- if ($item['uri'] == $item['parent-uri']) {
+ unset($item['post-reason']);
+ if ($item['uri-id'] == $item['parent-uri-id']) {
$item['contact-id'] = $item['owner-id'];
} else {
$item['contact-id'] = $item['author-id'];
*/
private static function addShadowPost($itemid)
{
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
if (!DBA::isResult($item)) {
return;
}
}
// Is there a shadow parent?
- if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
+ if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
return;
}
// Is there already a shadow entry?
- if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
+ if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
return;
}
unset($item['starred']);
unset($item['postopts']);
unset($item['inform']);
- unset($item['post-type']);
+ unset($item['post-reason']);
$item['contact-id'] = Contact::getIdForURL($item['author-link']);
$public_shadow = self::insert($item, false, true);
- Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
+ Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], '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.
- if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
+ if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
self::distribute($public_shadow);
}
}
*/
private static function getLanguage(array $item)
{
+ if (!empty($item['language'])) {
+ return $item['language'];
+ }
+
if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
return '';
}
$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"])) {
+ if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
$update = true;
}
// or it had been done by a "regular" contact.
if (!empty($arr['wall'])) {
$condition = ['id' => $arr['contact-id']];
- } else {
+ } else {
$condition = ['id' => $arr['contact-id'], 'self' => false];
}
DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
public static function setHashtags($body)
{
- $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
+ $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
$tags = BBCode::getTags($body);
// No hashtags?
return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
}, $body);
- $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
+ $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
function ($match) {
return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
}, $body);
$community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
$prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
if (!DBA::isResult($item)) {
return false;
}
}
}
}
-
+
if (!$mention) {
if (($community_page || $prvgroup) &&
!$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]);
+ Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item['id'], 'guid'=> $item['guid']]);
+ Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
return true;
}
return false;
$fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
- self::update($fields, ['id' => $item_id]);
+ self::update($fields, ['id' => $item['id']]);
- Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
+ Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, (int)$item['uri-id'], (int)$item['uid']);
- Item::performActivity($item_id, 'announce', $uid);
+ self::performActivity($item['id'], 'announce', $uid);
return false;
}
Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
- Item::performActivity($item['id'], 'announce', $item['uid']);
+ self::performActivity($item['id'], 'announce', $item['uid']);
}
public static function isRemoteSelf($contact, &$datarray)
$condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
$condition[] = $days;
- $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
+ $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
if (!DBA::isResult($items)) {
return;
$priority = DI::config()->get('system', 'expire-notify-priority');
- while ($item = Item::fetch($items)) {
+ while ($item = Post::fetch($items)) {
// don't expire filed items
-
- if (strpos($item['file'], '[') !== false) {
+ if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
continue;
}
// Only expire posts, not photos and photo comments
- if (!$expire_photos && strlen($item['resource-id'])) {
+ if (!$expire_photos && !empty($item['resource-id'])) {
continue;
} elseif (!$expire_starred && intval($item['starred'])) {
continue;
- } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
+ } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
continue;
- } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
+ } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
continue;
}
public static function firstPostDate($uid, $wall = false)
{
- $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
+ $user = User::getById($uid, ['register_date']);
+ if (empty($user)) {
+ return false;
+ }
+
+ $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
+ $uid, $wall, $user['register_date']];
$params = ['order' => ['received' => false]];
- $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
+ $thread = Post::selectFirstThread(['received'], $condition, $params);
if (DBA::isResult($thread)) {
- return substr(DateTimeFormat::local($thread['received']), 0, 10);
+ $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
+ return $postdate;
}
return false;
}
Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
if (!DBA::isResult($item)) {
Logger::log('like: unknown item ' . $item_id);
return false;
}
- $item_uri = $item['uri'];
+ $uri_id = $item['uri-id'];
if (!in_array($item['uid'], [0, $uid])) {
return false;
}
- if (!Item::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
+ if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
$stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
- $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
+ $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
if (!DBA::isResult($item)) {
- Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
+ Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
return false;
}
}
}
$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);
+ 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
+ $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
if (DBA::isResult($like_item)) {
/**
return true;
}
- private static function addThread($itemid, $onlyshadow = false)
- {
- $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
- '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);
-
- if (!DBA::isResult($item)) {
- return;
- }
-
- $item['iid'] = $itemid;
-
- if (!$onlyshadow) {
- $result = DBA::replace('thread', $item);
-
- 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', 'uri-id',
- 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
-
- $item = self::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
- if (!DBA::isResult($item)) {
- return;
- }
-
- if ($setmention) {
- $item["mention"] = 1;
- }
-
- $fields = [];
-
- foreach ($item as $field => $data) {
- if (!in_array($field, ["guid"])) {
- $fields[$field] = $data;
- }
- }
-
- $result = DBA::update('thread', $fields, ['iid' => $itemid]);
-
- 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::info('No thread found', ['id' => $itemid]);
- return;
- }
-
- $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
-
- 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::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
- }
- }
- }
-
/**
* Fetch the SQL condition for the given user id
*
if (!empty($set)) {
$condition = ["(`private` != ? OR (`private` = ? AND `wall`
AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
- Item::PRIVATE, Item::PRIVATE];
+ self::PRIVATE, self::PRIVATE];
$condition = array_merge($condition, $set);
}
}
return $condition;
}
- public static function getPermissionsSQLByUserId($owner_id)
+ /**
+ * Get a permission SQL string for the given user
+ *
+ * @param int $owner_id
+ * @param string $table
+ * @return string
+ */
+ public static function getPermissionsSQLByUserId(int $owner_id, string $table = '')
{
$local_user = local_user();
$remote_user = Session::getRemoteContactID($owner_id);
+ if (!empty($table)) {
+ $table = DBA::quoteIdentifier($table) . '.';
+ }
+
/*
* Construct permissions
*
* default permissions - anonymous user
*/
- $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
+ $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
// Profile owner - everything is visible
if ($local_user && ($local_user == $owner_id)) {
$set = PermissionSet::get($owner_id, $remote_user);
if (!empty($set)) {
- $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
+ $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
} else {
$sql_set = '';
}
- $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
+ $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
}
return $sql;
/**
* get translated item type
*
- * @param $item
+ * @param array $item
+ * @param \Friendica\Core\L10n $l10n
* @return string
*/
- public static function postType($item)
+ public static function postType(array $item, \Friendica\Core\L10n $l10n)
{
if (!empty($item['event-id'])) {
- return DI::l10n()->t('event');
+ return $l10n->t('event');
} elseif (!empty($item['resource-id'])) {
- return DI::l10n()->t('photo');
+ return $l10n->t('photo');
} elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
- return DI::l10n()->t('activity');
+ return $l10n->t('activity');
} elseif ($item['gravity'] == GRAVITY_COMMENT) {
- return DI::l10n()->t('comment');
+ return $l10n->t('comment');
}
- return DI::l10n()->t('post');
+ return $l10n->t('post');
}
/**
* Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
*
* @param array $item
- * @param bool $update
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Remove reference, simply return "rendered-html" and "rendered-hash"
*/
- public static function putInCache(&$item, $update = false)
+ public static function putInCache(&$item)
{
// Save original body to prevent addons to modify it
$body = $item['body'];
$item['rendered-hash'] = $hook_data['rendered-hash'];
unset($hook_data);
- // Force an update if the generated values differ from the existing ones
- if ($rendered_hash != $item['rendered-hash']) {
- $update = true;
- }
-
- // Only compare the HTML when we forcefully ignore the cache
- if (DI::config()->get('system', 'ignore_cache') && ($rendered_html != $item['rendered-html'])) {
- $update = true;
- }
-
- if ($update && !empty($item['id'])) {
+ // Update if the generated values differ from the existing ones
+ if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
self::update(
[
'rendered-html' => $item['rendered-html'],
unset($hook_data);
}
- // Update the cached values if there is no "zrl=..." on the links.
- $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
-
- // Or update it if the current viewer is the intented viewer.
- if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
- $update = true;
- }
-
- self::putInCache($item, $update);
+ $body = $item['body'] ?? '';
+ $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $item['body']);
+ self::putInCache($item);
+ $item['body'] = $body;
$s = $item["rendered-html"];
$hook_data = [
return $s;
}
- $as = '';
- $vhead = false;
- foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
- $mime = $attachment['mimetype'];
-
- $the_url = Contact::magicLinkById($item['author-id'], $attachment['url']);
-
- if (strpos($mime, 'video') !== false) {
- if (!$vhead) {
- $vhead = true;
- DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
- }
-
- $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
- '$video' => [
- 'id' => $item['author-id'],
- 'title' => DI::l10n()->t('View Video'),
- 'src' => $the_url,
- 'mime' => $mime,
- ],
- ]);
- }
-
- $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
- if ($filetype) {
- $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
- $filesubtype = str_replace('.', '-', $filesubtype);
- } else {
- $filetype = 'unkn';
- $filesubtype = 'unkn';
- }
-
- $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
- $title .= ' ' . ($attachment['size'] ?? 0) . ' ' . DI::l10n()->t('bytes');
-
- $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
- $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
+ $shared = BBCode::fetchShareAttributes($item['body']);
+ if (!empty($shared['guid'])) {
+ $shared_item = Post::selectFirst(['uri-id', 'plink'], ['guid' => $shared['guid']]);
+ $shared_uri_id = $shared_item['uri-id'] ?? 0;
+ $shared_links = [strtolower($shared_item['plink'] ?? '')];
+ $attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid']);
+ $s = self::addVisualAttachments($attachments, $item, $s, true);
+ $s = self::addLinkAttachment($attachments, $body, $s, true, []);
+ $s = self::addNonVisualAttachments($attachments, $item, $s, true);
+ $shared_links = array_merge($shared_links, array_column($attachments['visual'], 'url'));
+ $shared_links = array_merge($shared_links, array_column($attachments['link'], 'url'));
+ $shared_links = array_merge($shared_links, array_column($attachments['additional'], 'url'));
+ $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
+ } else {
+ $shared_uri_id = 0;
+ $shared_links = [];
}
- if ($as != '') {
- $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
- }
+ $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'], $shared_links);
+ $s = self::addVisualAttachments($attachments, $item, $s, false);
+ $s = self::addLinkAttachment($attachments, $body, $s, false, $shared_links);
+ $s = self::addNonVisualAttachments($attachments, $item, $s, false);
// Map.
if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
return $hook_data['html'];
}
+ /**
+ * Check if the body contains a link
+ *
+ * @param string $body
+ * @param string $url
+ * @return bool
+ */
+ public static function containsLink(string $body, string $url)
+ {
+ if (strpos($body, $url)) {
+ return true;
+ }
+ foreach ([0, 1, 2] as $size) {
+ if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
+ strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Add visual attachments to the content
+ *
+ * @param array $attachments
+ * @param array $item
+ * @param string $content
+ * @return string modified content
+ */
+ private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared)
+ {
+ $stamp1 = microtime(true);
+ $leading = '';
+ $trailing = '';
+
+ // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
+ foreach ($attachments['visual'] as $attachment) {
+ if (self::containsLink($item['body'], $attachment['url'])) {
+ continue;
+ }
+
+ $author = ['uid' => 0, 'id' => $item['author-id'],
+ 'network' => $item['author-network'], 'url' => $item['author-link']];
+ $the_url = Contact::magicLinkByContact($author, $attachment['url']);
+
+ if (!empty($attachment['preview'])) {
+ $preview_url = Proxy::proxifyUrl(Contact::magicLinkByContact($author, $attachment['preview']));
+ } else {
+ $preview_url = '';
+ }
+
+ if (($attachment['filetype'] == 'video')) {
+ /// @todo Move the template to /content as well
+ $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
+ '$video' => [
+ 'id' => $attachment['id'],
+ 'src' => $the_url,
+ 'name' => $attachment['name'] ?: $attachment['url'],
+ 'preview' => $preview_url,
+ 'mime' => $attachment['mimetype'],
+ ],
+ ]);
+ if ($item['post-type'] == Item::PT_VIDEO) {
+ $leading .= $media;
+ } else {
+ $trailing .= $media;
+ }
+ } elseif ($attachment['filetype'] == 'audio') {
+ $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
+ '$audio' => [
+ 'id' => $attachment['id'],
+ 'src' => $the_url,
+ 'name' => $attachment['name'] ?: $attachment['url'],
+ 'mime' => $attachment['mimetype'],
+ ],
+ ]);
+ if ($item['post-type'] == Item::PT_AUDIO) {
+ $leading .= $media;
+ } else {
+ $trailing .= $media;
+ }
+ } elseif ($attachment['filetype'] == 'image') {
+ if (empty($preview_url) && (max($attachment['width'], $attachment['height']) > 600)) {
+ $preview_url = Proxy::proxifyUrl($the_url, false, ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE);
+ }
+ $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
+ '$image' => [
+ 'src' => Proxy::proxifyUrl($the_url),
+ 'preview' => $preview_url,
+ 'attachment' => $attachment,
+ ],
+ ]);
+ // On Diaspora posts the attached pictures are leading
+ if ($item['network'] == Protocol::DIASPORA) {
+ $leading .= $media;
+ } else {
+ $trailing .= $media;
+ }
+ }
+ }
+
+ if ($shared) {
+ $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
+ $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
+ } else {
+ if ($leading != '') {
+ $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
+ }
+
+ if ($trailing != '') {
+ $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
+ }
+ }
+
+ DI::profiler()->saveTimestamp($stamp1, 'rendering');
+ return $content;
+ }
+
+ /**
+ * Add link attachment to the content
+ *
+ * @param array $attachments
+ * @param string $body
+ * @param string $content
+ * @param bool $shared
+ * @param array $ignore_links A list of URLs to ignore
+ * @return string modified content
+ */
+ private static function addLinkAttachment(array $attachments, string $body, string $content, bool $shared, array $ignore_links)
+ {
+ $stamp1 = microtime(true);
+ // @ToDo Check only for audio and video
+ $preview = empty($attachments['visual']);
+
+ if (!empty($attachments['link'])) {
+ foreach ($attachments['link'] as $link) {
+ $found = false;
+ foreach ($ignore_links as $ignore_link) {
+ if (Strings::compareLink($link['url'], $ignore_link)) {
+ $found = true;
+ }
+ }
+ if (!$found) {
+ $attachment = $link;
+ }
+ }
+ }
+
+ if (!empty($attachment)) {
+ $data = [
+ 'after' => '',
+ 'author_name' => $attachment['author-name'] ?? '',
+ 'author_url' => $attachment['author-url'] ?? '',
+ 'description' => $attachment['description'] ?? '',
+ 'image' => '',
+ 'preview' => '',
+ 'provider_name' => $attachment['publisher-name'] ?? '',
+ 'provider_url' => $attachment['publisher-url'] ?? '',
+ 'text' => '',
+ 'title' => $attachment['name'] ?? '',
+ 'type' => 'link',
+ 'url' => $attachment['url']];
+
+ if ($preview) {
+ if ($attachment['preview-width'] >= 500) {
+ $data['image'] = $attachment['preview'] ?? '';
+ } else {
+ $data['preview'] = $attachment['preview'] ?? '';
+ }
+ }
+ } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
+ $data = BBCode::getAttachmentData($match[1]);
+ }
+ DI::profiler()->saveTimestamp($stamp1, 'rendering');
+
+ if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
+ // @todo Use a template
+ $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data);
+ if ($shared) {
+ return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
+ } else {
+ return $content . $rendered;
+ }
+ }
+ return $content;
+ }
+
+ /**
+ * Add non visual attachments to the content
+ *
+ * @param array $attachments
+ * @param array $item
+ * @param string $content
+ * @return string modified content
+ */
+ private static function addNonVisualAttachments(array $attachments, array $item, string $content)
+ {
+ $stamp1 = microtime(true);
+ $trailing = '';
+ foreach ($attachments['additional'] as $attachment) {
+ if (strpos($item['body'], $attachment['url'])) {
+ continue;
+ }
+
+ $author = ['uid' => 0, 'id' => $item['author-id'],
+ 'network' => $item['author-network'], 'url' => $item['author-link']];
+ $the_url = Contact::magicLinkByContact($author, $attachment['url']);
+
+ $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
+
+ if (!empty($attachment['size'])) {
+ $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
+ }
+
+ /// @todo Use a template
+ $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
+ $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
+ }
+
+ if ($trailing != '') {
+ $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
+ }
+
+ DI::profiler()->saveTimestamp($stamp1, 'rendering');
+ return $content;
+ }
+
/**
* get private link for item
*
if (($item['author-id'] == $item['owner-id']) ||
($owner['id'] == $item['contact-id']) ||
- ($item['uri'] != $item['parent-uri']) ||
+ ($item['uri-id'] != $item['parent-uri-id']) ||
$item['origin']) {
return false;
}
$ssl_uri = str_replace('http://', 'https://', $uri);
$uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
- $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
+ $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
if (DBA::isResult($item)) {
return $item['id'];
}
- $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
- if (!DBA::isResult($itemcontent)) {
- return 0;
- }
-
- $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
- if (!DBA::isResult($itemuri)) {
- return 0;
- }
-
- $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
+ $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
if (DBA::isResult($item)) {
return $item['id'];
}
}
/**
- * Return the URI for a link to the post
- *
+ * Return the URI for a link to the post
+ *
* @param string $uri URI or link to post
*
* @return string URI
$ssl_uri = str_replace('http://', 'https://', $uri);
$uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
- $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
+ $item = Post::selectFirst(['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'];
+ $item = Post::selectFirst(['uri'], ['plink' => $uris]);
+ if (DBA::isResult($item)) {
+ return $item['uri'];
}
return '';
$uid = $item['uid'] ?? 0;
// first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
- $shared_item = self::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
+ $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
if (!DBA::isResult($shared_item)) {
if (empty($shared['link'])) {
return $item;
return $item;
}
- $shared_item = self::selectFirst(['title', 'body'], ['id' => $id]);
+ $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
if (!DBA::isResult($shared_item)) {
return $item;
}