3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
34 use Friendica\Database\DBStructure;
36 use Friendica\Model\Post\Category;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Map;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
44 use Friendica\Worker\Delivery;
45 use Text_LanguageDetect;
46 use Friendica\Repository\PermissionSet as RepPermissionSet;
50 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
57 const PT_DOCUMENT = 19;
64 const PT_FOLLOWER = 69;
65 const PT_ANNOUNCEMENT = 70;
66 const PT_COMMENT = 71;
68 const PT_PERSONAL_NOTE = 128;
70 // Field list that is used to display the items
71 const DISPLAY_FIELDLIST = [
72 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
73 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
74 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
75 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
76 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
77 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
78 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
79 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
80 'writable', 'self', 'cid', 'alias', 'pinned',
81 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
82 'event-summary', 'event-desc', 'event-location', 'event-type',
83 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
84 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
87 // Field list that is used to deliver items via the protocols
88 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
89 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
90 'private', 'title', 'body', 'location', 'coord', 'app',
91 'attach', 'deleted', 'extid', 'post-type', 'gravity',
92 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
93 'author-id', 'author-link', 'owner-link', 'contact-uid',
94 'signed_text', 'signature', 'signer', 'network'];
96 // Field list for "item-content" table that is mixed with the item table
97 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
98 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
99 'object-type', 'object', 'target-type', 'target', 'plink'];
101 // Field list for "item-content" table that is not present in the "item" table
102 const CONTENT_FIELDLIST = ['language'];
104 // All fields in the item table
105 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
106 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
107 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
108 'created', 'edited', 'commented', 'received', 'changed', 'verb',
109 'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform',
110 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
111 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
112 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
113 'title', 'content-warning', 'body', 'location', 'coord', 'app',
114 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
115 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
116 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
118 // List of all verbs that don't need additional content data.
119 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
121 Activity::LIKE, Activity::DISLIKE,
122 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
130 const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction'];
132 private static $legacy_mode = null;
134 private static function getItemFields()
136 $definition = DBStructure::definition('', false);
139 foreach (self::TABLES as $table) {
140 $postfields[$table] = array_keys($definition[$table]['fields']);
146 public static function isLegacyMode()
148 if (is_null(self::$legacy_mode)) {
149 self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
152 return self::$legacy_mode;
156 * Set the pinned state of an item
158 * @param integer $iid Item ID
159 * @param integer $uid User ID
160 * @param boolean $pinned Pinned state
162 public static function setPinned(int $iid, int $uid, bool $pinned)
164 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
168 * Get the pinned state
170 * @param integer $iid Item ID
171 * @param integer $uid User ID
173 * @return boolean pinned state
175 public static function getPinned(int $iid, int $uid)
177 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
178 if (!DBA::isResult($useritem)) {
181 return (bool)$useritem['pinned'];
185 * Select pinned rows from the item table for a given user
187 * @param integer $uid User ID
188 * @param array $selected Array of selected fields, empty for all
189 * @param array $condition Array of fields for condition
190 * @param array $params Array of several parameters
192 * @return boolean|object
195 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
197 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
198 if (!DBA::isResult($useritems)) {
203 while ($useritem = DBA::fetch($useritems)) {
204 $pinned[] = $useritem['iid'];
206 DBA::close($useritems);
208 if (empty($pinned)) {
212 $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
214 return self::selectThreadForUser($uid, $selected, $condition, $params);
218 * Fetch a single item row
220 * @param mixed $stmt statement object
221 * @return array current row
223 public static function fetch($stmt)
225 $row = DBA::fetch($stmt);
231 // ---------------------- Transform item structure data ----------------------
233 // We prefer the data from the user's contact over the public one
234 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
235 ($row['author-link'] == $row['contact-link'])) {
236 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
237 $row['author-avatar'] = $row['contact-avatar'];
239 if (isset($row['author-name']) && !empty($row['contact-name'])) {
240 $row['author-name'] = $row['contact-name'];
244 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
245 ($row['owner-link'] == $row['contact-link'])) {
246 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
247 $row['owner-avatar'] = $row['contact-avatar'];
249 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
250 $row['owner-name'] = $row['contact-name'];
254 // We can always comment on posts from these networks
255 if (array_key_exists('writable', $row) &&
256 in_array($row['internal-network'], Protocol::FEDERATED)) {
257 $row['writable'] = true;
260 // ---------------------- Transform item content data ----------------------
262 // Fetch data from the item-content table whenever there is content there
263 if (self::isLegacyMode()) {
264 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
265 foreach ($legacy_fields as $field) {
266 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
267 $row[$field] = $row['internal-item-' . $field];
269 unset($row['internal-item-' . $field]);
273 if (array_key_exists('verb', $row)) {
274 if (!is_null($row['internal-verb'])) {
275 $row['verb'] = $row['internal-verb'];
278 if (in_array($row['verb'], self::ACTIVITIES)) {
279 if (array_key_exists('title', $row)) {
282 if (array_key_exists('body', $row)) {
283 $row['body'] = $row['verb'];
285 if (array_key_exists('object', $row)) {
288 if (array_key_exists('object-type', $row)) {
289 $row['object-type'] = Activity\ObjectType::NOTE;
291 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
292 // Posts don't have a target - but having tags or files.
293 if (array_key_exists('target', $row)) {
299 if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
300 $row['vid'] = Verb::getID($row['verb']);
303 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
304 // Build the file string out of the term entries
305 if (array_key_exists('file', $row) && empty($row['file'])) {
306 $row['file'] = Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
310 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
311 if (array_key_exists('allow_cid', $row)) {
312 $row['allow_cid'] = '';
314 if (array_key_exists('allow_gid', $row)) {
315 $row['allow_gid'] = '';
317 if (array_key_exists('deny_cid', $row)) {
318 $row['deny_cid'] = '';
320 if (array_key_exists('deny_gid', $row)) {
321 $row['deny_gid'] = '';
325 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
326 $row['ignored'] = $row['internal-user-ignored'];
329 // Remove internal fields
330 unset($row['internal-network']);
331 unset($row['internal-uri-id']);
332 unset($row['internal-uid']);
333 unset($row['internal-psid']);
334 unset($row['internal-verb']);
335 unset($row['internal-user-ignored']);
336 unset($row['interaction']);
342 * Fills an array with data from an item query
344 * @param object $stmt statement object
345 * @param bool $do_close
346 * @return array Data array
348 public static function inArray($stmt, $do_close = true) {
349 if (is_bool($stmt)) {
354 while ($row = self::fetch($stmt)) {
364 * Check if item data exists
366 * @param array $condition array of fields for condition
368 * @return boolean Are there rows for that condition?
371 public static function exists($condition) {
372 $stmt = self::select(['id'], $condition, ['limit' => 1]);
374 if (is_bool($stmt)) {
377 $retval = (DBA::numRows($stmt) > 0);
386 * Retrieve a single record from the item table for a given user and returns it in an associative array
388 * @param integer $uid User ID
389 * @param array $selected
390 * @param array $condition
391 * @param array $params
396 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
398 $params['uid'] = $uid;
400 if (empty($selected)) {
401 $selected = Item::DISPLAY_FIELDLIST;
404 return self::selectFirst($selected, $condition, $params);
408 * Select rows from the item table for a given user
410 * @param integer $uid User ID
411 * @param array $selected Array of selected fields, empty for all
412 * @param array $condition Array of fields for condition
413 * @param array $params Array of several parameters
415 * @return boolean|object
418 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
420 $params['uid'] = $uid;
422 if (empty($selected)) {
423 $selected = Item::DISPLAY_FIELDLIST;
426 return self::select($selected, $condition, $params);
430 * Retrieve a single record from the item table and returns it in an associative array
432 * @param array $fields
433 * @param array $condition
434 * @param array $params
439 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
441 $params['limit'] = 1;
443 $result = self::select($fields, $condition, $params);
445 if (is_bool($result)) {
448 $row = self::fetch($result);
455 * Select rows from the item table and returns them as an array
457 * @param array $selected Array of selected fields, empty for all
458 * @param array $condition Array of fields for condition
459 * @param array $params Array of several parameters
464 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
466 $result = self::select($fields, $condition, $params);
468 if (is_bool($result)) {
473 while ($row = self::fetch($result)) {
482 * Select rows from the item table
484 * @param array $selected Array of selected fields, empty for all
485 * @param array $condition Array of fields for condition
486 * @param array $params Array of several parameters
488 * @return boolean|object
491 public static function select(array $selected = [], array $condition = [], $params = [])
496 if (isset($params['uid'])) {
497 $uid = $params['uid'];
501 $fields = self::fieldlist($usermode);
503 $select_fields = self::constructSelectFields($fields, $selected);
505 $condition_string = DBA::buildCondition($condition);
507 $condition_string = self::addTablesToFields($condition_string, $fields);
510 $condition_string = $condition_string . ' AND ' . self::condition(false);
513 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
515 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
517 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
519 return DBA::p($sql, $condition);
523 * Select rows from the starting post in the item table
525 * @param integer $uid User ID
526 * @param array $selected
527 * @param array $condition Array of fields for condition
528 * @param array $params Array of several parameters
530 * @return boolean|object
533 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
535 $params['uid'] = $uid;
537 if (empty($selected)) {
538 $selected = Item::DISPLAY_FIELDLIST;
541 return self::selectThread($selected, $condition, $params);
545 * Retrieve a single record from the starting post in the item table and returns it in an associative array
547 * @param integer $uid User ID
548 * @param array $selected
549 * @param array $condition
550 * @param array $params
555 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
557 $params['uid'] = $uid;
559 if (empty($selected)) {
560 $selected = Item::DISPLAY_FIELDLIST;
563 return self::selectFirstThread($selected, $condition, $params);
567 * Retrieve a single record from the starting post in the item table and returns it in an associative array
569 * @param array $fields
570 * @param array $condition
571 * @param array $params
576 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
578 $params['limit'] = 1;
579 $result = self::selectThread($fields, $condition, $params);
581 if (is_bool($result)) {
584 $row = self::fetch($result);
591 * Select rows from the starting post in the item table
593 * @param array $selected Array of selected fields, empty for all
594 * @param array $condition Array of fields for condition
595 * @param array $params Array of several parameters
597 * @return boolean|object
600 public static function selectThread(array $selected = [], array $condition = [], $params = [])
605 if (isset($params['uid'])) {
606 $uid = $params['uid'];
610 $fields = self::fieldlist($usermode);
612 $fields['thread'] = ['mention', 'ignored', 'iid'];
614 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
615 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
616 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
617 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
619 $select_fields = self::constructSelectFields($fields, $selected);
621 $condition_string = DBA::buildCondition($condition);
623 $condition_string = self::addTablesToFields($condition_string, $threadfields);
624 $condition_string = self::addTablesToFields($condition_string, $fields);
627 $condition_string = $condition_string . ' AND ' . self::condition(true);
630 $param_string = DBA::buildParameter($params);
631 $param_string = self::addTablesToFields($param_string, $threadfields);
632 $param_string = self::addTablesToFields($param_string, $fields);
634 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
636 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
638 return DBA::p($sql, $condition);
642 * Returns a list of fields that are associated with the item table
645 * @return array field list
647 private static function fieldlist($usermode)
651 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
652 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
653 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
654 'created', 'edited', 'commented', 'received', 'changed', 'psid',
655 'resource-id', 'event-id', 'attach', 'post-type', 'file',
656 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
657 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
658 'id' => 'item_id', 'network', 'icid',
659 'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
660 'network' => 'internal-network', 'psid' => 'internal-psid'];
663 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
666 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
668 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
670 $fields['verb'] = ['name' => 'internal-verb'];
672 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
674 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
675 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
677 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
678 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
680 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
681 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
682 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
684 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
686 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
687 'network' => 'parent-author-network'];
689 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
690 'start' => 'event-start','finish' => 'event-finish',
691 'summary' => 'event-summary','desc' => 'event-desc',
692 'location' => 'event-location', 'type' => 'event-type',
693 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
694 'ignore' => 'event-ignore', 'id' => 'event-id'];
696 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
702 * Returns SQL condition for the "select" functions
704 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
706 * @return string SQL condition
708 private static function condition($thread_mode)
711 $master_table = "`thread`";
713 $master_table = "`item`";
715 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
716 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
717 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
718 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
719 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
720 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
721 GRAVITY_PARENT, GRAVITY_PARENT);
725 * Returns all needed "JOIN" commands for the "select" functions
727 * @param integer $uid User ID
728 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
729 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
732 * @return string The SQL joins for the "select" functions
734 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
737 $master_table = "`thread`";
738 $master_table_key = "`thread`.`iid`";
739 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
741 $master_table = "`item`";
742 $master_table_key = "`item`.`id`";
747 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
748 AND NOT `contact`.`blocked`
749 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
750 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
751 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
752 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
753 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
754 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
755 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
756 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
758 if (strpos($sql_commands, "`contact`.") !== false) {
759 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
761 if (strpos($sql_commands, "`author`.") !== false) {
762 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
764 if (strpos($sql_commands, "`owner`.") !== false) {
765 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
769 if (strpos($sql_commands, "`group_member`.") !== false) {
770 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
773 if (strpos($sql_commands, "`user`.") !== false) {
774 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
777 if (strpos($sql_commands, "`event`.") !== false) {
778 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
781 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
782 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
785 if (strpos($sql_commands, "`item-content`.") !== false) {
786 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
789 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
790 $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
793 if (strpos($sql_commands, "`verb`.") !== false) {
794 $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
797 if (strpos($sql_commands, "`permissionset`.") !== false) {
798 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
801 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
802 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
804 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
805 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
813 * Add the field list for the "select" functions
815 * @param array $fields The field definition array
816 * @param array $selected The array with the selected fields from the "select" functions
818 * @return string The field list
820 private static function constructSelectFields(array $fields, array $selected)
822 if (!empty($selected)) {
823 $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
826 if (in_array('verb', $selected)) {
827 $selected = array_merge($selected, ['internal-verb']);
830 if (in_array('ignored', $selected)) {
831 $selected[] = 'internal-user-ignored';
834 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
837 foreach ($fields as $table => $table_fields) {
838 foreach ($table_fields as $field => $select) {
839 if (empty($selected) || in_array($select, $selected)) {
840 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
841 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
843 if (is_int($field)) {
844 $selection[] = "`" . $table . "`.`" . $select . "`";
846 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
851 return implode(", ", $selection);
855 * add table definition to fields in an SQL query
857 * @param string $query SQL query
858 * @param array $fields The field definition array
860 * @return string the changed SQL query
862 private static function addTablesToFields($query, $fields)
864 foreach ($fields as $table => $table_fields) {
865 foreach ($table_fields as $alias => $field) {
866 if (is_int($alias)) {
867 $replace_field = $field;
869 $replace_field = $alias;
872 $search = "/([^\.])`" . $field . "`/i";
873 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
874 $query = preg_replace($search, $replace, $query);
881 * Update existing item entries
883 * @param array $fields The fields that are to be changed
884 * @param array $condition The condition for finding the item entries
886 * In the future we may have to change permissions as well.
887 * Then we had to add the user id as third parameter.
889 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
891 * @return integer|boolean number of affected rows - or "false" if there was an error
892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
894 public static function update(array $fields, array $condition)
896 if (empty($condition) || empty($fields)) {
900 // To ensure the data integrity we do it in an transaction
903 // We cannot simply expand the condition to check for origin entries
904 // The condition needn't to be a simple array but could be a complex condition.
905 // And we have to execute this query before the update to ensure to fetch the same data.
906 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
908 $content_fields = [];
909 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
910 if (isset($fields[$field])) {
911 $content_fields[$field] = $fields[$field];
912 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
913 unset($fields[$field]);
915 $fields[$field] = null;
920 $delivery_data = Post\DeliveryData::extractFields($fields);
922 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
923 foreach ($clear_fields as $field) {
924 if (array_key_exists($field, $fields)) {
925 $fields[$field] = null;
929 if (array_key_exists('file', $fields)) {
930 $files = $fields['file'];
931 $fields['file'] = null;
936 if (!empty($content_fields['verb'])) {
937 $fields['vid'] = Verb::getID($content_fields['verb']);
940 if (!empty($fields)) {
941 $success = DBA::update('item', $fields, $condition);
950 // When there is no content for the "old" item table, this will count the fetched items
951 $rows = DBA::affectedRows();
955 while ($item = DBA::fetch($items)) {
956 if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
957 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
959 if (empty($item['icid'])) {
960 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
961 if (DBA::isResult($item_content)) {
962 $item_fields = ['icid' => $item_content['id']];
963 // Clear all fields in the item table that have a content in the item-content table
964 if (self::isLegacyMode()) {
965 foreach ($item_content as $field => $content) {
966 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
967 $item_fields[$field] = null;
971 DBA::update('item', $item_fields, ['id' => $item['id']]);
976 if (!is_null($files)) {
977 Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
978 if (!empty($item['file'])) {
979 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
983 Post\DeliveryData::update($item['uri-id'], $delivery_data);
985 self::updateThread($item['id']);
987 // We only need to notfiy others when it is an original entry from us.
988 // Only call the notifier when the item has some content relevant change.
989 if ($item['origin'] && in_array('edited', array_keys($fields))) {
990 $notify_items[] = $item['id'];
997 foreach ($notify_items as $notify_item) {
998 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1005 * Delete an item and notify others about it - if it was ours
1007 * @param array $condition The condition for finding the item entries
1008 * @param integer $priority Priority for the notification
1009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1011 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
1013 $items = self::select(['id'], $condition);
1014 while ($item = self::fetch($items)) {
1015 self::markForDeletionById($item['id'], $priority);
1021 * Delete an item for an user and notify others about it - if it was ours
1023 * @param array $condition The condition for finding the item entries
1024 * @param integer $uid User who wants to delete this item
1025 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1027 public static function deleteForUser($condition, $uid)
1033 $items = self::select(['id', 'uid'], $condition);
1034 while ($item = self::fetch($items)) {
1035 // "Deleting" global items just means hiding them
1036 if ($item['uid'] == 0) {
1037 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1039 // Delete notifications
1040 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
1041 } elseif ($item['uid'] == $uid) {
1042 self::markForDeletionById($item['id'], PRIORITY_HIGH);
1044 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1051 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1053 * @param integer $item_id
1054 * @param integer $priority Priority for the notification
1056 * @return boolean success
1057 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1059 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1061 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1062 // locate item to be deleted
1063 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1064 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1065 'verb', 'object-type', 'object', 'target', 'contact-id',
1066 'icid', 'psid', 'gravity'];
1067 $item = self::selectFirst($fields, ['id' => $item_id]);
1068 if (!DBA::isResult($item)) {
1069 Logger::info('Item not found.', ['id' => $item_id]);
1073 if ($item['deleted']) {
1074 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1078 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1079 if (!DBA::isResult($parent)) {
1080 $parent = ['origin' => false];
1083 // clean up categories and tags so they don't end up as orphans
1086 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1089 foreach ($matches as $mtch) {
1090 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1096 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1099 foreach ($matches as $mtch) {
1100 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1105 * If item is a link to a photo resource, nuke all the associated photos
1106 * (visitors will not have photo resources)
1107 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1108 * generate a resource-id and therefore aren't intimately linked to the item.
1110 /// @TODO: this should first check if photo is used elsewhere
1111 if (strlen($item['resource-id'])) {
1112 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1115 // If item is a link to an event, delete the event.
1116 if (intval($item['event-id'])) {
1117 Event::delete($item['event-id']);
1120 // If item has attachments, drop them
1121 /// @TODO: this should first check if attachment is used elsewhere
1122 foreach (explode(",", $item['attach']) as $attach) {
1123 preg_match("|attach/(\d+)|", $attach, $matches);
1124 if (is_array($matches) && count($matches) > 1) {
1125 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1129 // Delete notifications
1130 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
1132 // Set the item to "deleted"
1133 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1134 DBA::update('item', $item_fields, ['id' => $item['id']]);
1136 Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
1137 self::deleteThread($item['id'], $item['parent-uri']);
1139 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1140 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1143 Post\DeliveryData::delete($item['uri-id']);
1145 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1146 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1148 // When the permission set will be used in photo and events as well,
1149 // this query here needs to be extended.
1150 // @todo Currently deactivated. We need the permission set in the deletion process.
1151 // This is a reminder to add the removal somewhere else.
1152 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1153 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1156 // If it's the parent of a comment thread, kill all the kids
1157 if ($item['gravity'] == GRAVITY_PARENT) {
1158 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1161 // Is it our comment and/or our thread?
1162 if ($item['origin'] || $parent['origin']) {
1163 // When we delete the original post we will delete all existing copies on the server as well
1164 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1166 // send the notification upstream/downstream
1167 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1168 } elseif ($item['uid'] != 0) {
1170 // When we delete just our local user copy of an item, we have to set a marker to hide it
1171 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1172 if (DBA::isResult($global_item)) {
1173 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1177 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1183 private static function guid($item, $notify)
1185 if (!empty($item['guid'])) {
1186 return Strings::escapeTags(trim($item['guid']));
1190 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1191 // We add the hash of our own host because our host is the original creator of the post.
1192 $prefix_host = DI::baseUrl()->getHostname();
1196 // We are only storing the post so we create a GUID from the original hostname.
1197 if (!empty($item['author-link'])) {
1198 $parsed = parse_url($item['author-link']);
1199 if (!empty($parsed['host'])) {
1200 $prefix_host = $parsed['host'];
1204 if (empty($prefix_host) && !empty($item['plink'])) {
1205 $parsed = parse_url($item['plink']);
1206 if (!empty($parsed['host'])) {
1207 $prefix_host = $parsed['host'];
1211 if (empty($prefix_host) && !empty($item['uri'])) {
1212 $parsed = parse_url($item['uri']);
1213 if (!empty($parsed['host'])) {
1214 $prefix_host = $parsed['host'];
1218 // Is it in the format data@host.tld? - Used for mail contacts
1219 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1220 $mailparts = explode('@', $item['author-link']);
1221 $prefix_host = array_pop($mailparts);
1225 if (!empty($item['plink'])) {
1226 $guid = self::guidFromUri($item['plink'], $prefix_host);
1227 } elseif (!empty($item['uri'])) {
1228 $guid = self::guidFromUri($item['uri'], $prefix_host);
1230 $guid = System::createUUID(hash('crc32', $prefix_host));
1236 private static function contactId($item)
1238 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1239 return $item['contact-id'];
1240 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1241 return $item['contact-id'];
1242 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1243 return $item['author-id'];
1244 } elseif (!empty($item['contact-id'])) {
1245 return $item['contact-id'];
1247 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1248 if (!empty($contact_id)) {
1252 return $item['author-id'];
1255 // This function will finally cover most of the preparation functionality in mod/item.php
1256 public static function prepare(&$item)
1259 * @TODO: Unused code triggering inspection errors
1261 $data = BBCode::getAttachmentData($item['body']);
1262 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1263 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1264 $posttype = Item::PT_PAGE;
1265 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1271 * Write an item array into a spool file to be inserted later.
1272 * This command is called whenever there are issues storing an item.
1274 * @param array $item The item fields that are to be inserted
1275 * @throws \Exception
1277 private static function spool($orig_item)
1279 // Now we store the data in the spool directory
1280 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1281 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1283 $spoolpath = get_spoolpath();
1284 if ($spoolpath != "") {
1285 $spool = $spoolpath . '/' . $file;
1287 file_put_contents($spool, json_encode($orig_item));
1288 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1293 * Check if the item array is a duplicate
1295 * @param array $item
1296 * @return boolean is it a duplicate?
1298 private static function isDuplicate(array $item)
1300 // Checking if there is already an item with the same guid
1301 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1302 if (self::exists($condition)) {
1303 Logger::notice('Found already existing item', [
1304 'guid' => $item['guid'],
1305 'uid' => $item['uid'],
1306 'network' => $item['network']
1311 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1312 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1313 if (self::exists($condition)) {
1314 Logger::notice('duplicated item with the same uri found.', $item);
1318 // On Friendica and Diaspora the GUID is unique
1319 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1320 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1321 if (self::exists($condition)) {
1322 Logger::notice('duplicated item with the same guid found.', $item);
1325 } elseif ($item['network'] == Protocol::OSTATUS) {
1326 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1327 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1328 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1329 if (self::exists($condition)) {
1330 Logger::notice('duplicated item with the same body found.', $item);
1336 * Check for already added items.
1337 * There is a timing issue here that sometimes creates double postings.
1338 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1340 if (($item['uid'] == 0) && self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1341 Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
1349 * Check if the item array is valid
1351 * @param array $item
1352 * @return boolean item is valid
1354 public static function isValid(array $item)
1356 // When there is no content then we don't post it
1357 if ($item['body'].$item['title'] == '') {
1358 Logger::notice('No body, no title.');
1362 // check for create date and expire time
1363 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1365 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
1366 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1367 $expire_interval = $user['expire'];
1370 if (($expire_interval > 0) && !empty($item['created'])) {
1371 $expire_date = time() - ($expire_interval * 86400);
1372 $created_date = strtotime($item['created']);
1373 if ($created_date < $expire_date) {
1374 Logger::notice('Item created before expiration interval.', [
1375 'created' => date('c', $created_date),
1376 'expired' => date('c', $expire_date),
1383 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
1384 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1388 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1389 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1393 if (!empty($item['uid']) && !empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $item['uid'])) {
1394 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1398 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
1399 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1403 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1404 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1408 if (!empty($item['uid']) && !empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $item['uid'])) {
1409 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1413 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1414 if (!empty($item['uid']) && !empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $item['uid'])) {
1415 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1419 if (!empty($item['uid']) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact\User::isIgnored($item['causer-id'], $item['uid'])) {
1420 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1424 if ($item['verb'] == Activity::FOLLOW) {
1425 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
1426 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1427 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
1431 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1432 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1433 if (self::exists($condition)) {
1434 // It happens that we receive multiple follow requests by the same author - we only store one.
1435 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
1444 * Return the id of the given item array if it has been stored before
1446 * @param array $item
1447 * @return integer item id
1449 private static function getDuplicateID(array $item)
1451 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1452 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1453 trim($item['uri']), $item['uid'],
1454 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1455 $existing = self::selectFirst(['id', 'network'], $condition);
1456 if (DBA::isResult($existing)) {
1457 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1458 if ($item['uid'] != 0) {
1459 Logger::notice('Item already existed for user', [
1460 'uri' => $item['uri'],
1461 'uid' => $item['uid'],
1462 'network' => $item['network'],
1463 'existing_id' => $existing["id"],
1464 'existing_network' => $existing["network"]
1468 return $existing["id"];
1475 * Fetch parent data for the given item array
1477 * @param array $item
1478 * @return array item array with parent data
1480 private static function getParentData(array $item)
1482 // find the parent and snarf the item id and ACLs
1483 // and anything else we need to inherit
1485 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1486 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1487 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1488 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1489 $params = ['order' => ['id' => false]];
1490 $parent = self::selectFirst($fields, $condition, $params);
1492 if (!DBA::isResult($parent)) {
1493 Logger::info('item parent was not found - ignoring item', ['parent-uri' => $item['parent-uri'], 'uid' => $item['uid']]);
1496 // is the new message multi-level threaded?
1497 // even though we don't support it now, preserve the info
1498 // and re-attach to the conversation parent.
1499 if ($parent['uri'] != $parent['parent-uri']) {
1500 $item['parent-uri'] = $parent['parent-uri'];
1502 $condition = ['uri' => $item['parent-uri'],
1503 'parent-uri' => $item['parent-uri'],
1504 'uid' => $item['uid']];
1505 $params = ['order' => ['id' => false]];
1506 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1508 if (DBA::isResult($toplevel_parent)) {
1509 $parent = $toplevel_parent;
1513 $item['parent'] = $parent['id'];
1514 $item["deleted"] = $parent['deleted'];
1515 $item["allow_cid"] = $parent['allow_cid'];
1516 $item['allow_gid'] = $parent['allow_gid'];
1517 $item['deny_cid'] = $parent['deny_cid'];
1518 $item['deny_gid'] = $parent['deny_gid'];
1519 $item['parent_origin'] = $parent['origin'];
1521 // Don't federate received participation messages
1522 if ($item['verb'] != Activity::FOLLOW) {
1523 $item['wall'] = $parent['wall'];
1525 $item['wall'] = false;
1529 * If the parent is private, force privacy for the entire conversation
1530 * This differs from the above settings as it subtly allows comments from
1531 * email correspondents to be private even if the overall thread is not.
1533 if ($parent['private']) {
1534 $item['private'] = $parent['private'];
1538 * Edge case. We host a public forum that was originally posted to privately.
1539 * The original author commented, but as this is a comment, the permissions
1540 * weren't fixed up so it will still show the comment as private unless we fix it here.
1542 if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
1543 $item['private'] = self::PUBLIC;
1546 // If its a post that originated here then tag the thread as "mention"
1547 if ($item['origin'] && $item['uid']) {
1548 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
1549 Logger::info('tagged thread as mention', ['parent' => $item['parent'], 'uid' => $item['uid']]);
1552 // Update the contact relations
1553 Contact\Relation::store($parent['author-id'], $item['author-id'], $item['created']);
1560 * Get the gravity for the given item array
1562 * @param array $item
1563 * @return integer gravity
1565 private static function getGravity(array $item)
1567 $activity = DI::activity();
1569 if (isset($item['gravity'])) {
1570 return intval($item['gravity']);
1571 } elseif ($item['parent-uri'] === $item['uri']) {
1572 return GRAVITY_PARENT;
1573 } elseif ($activity->match($item['verb'], Activity::POST)) {
1574 return GRAVITY_COMMENT;
1575 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1576 return GRAVITY_ACTIVITY;
1577 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
1578 return GRAVITY_ACTIVITY;
1580 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
1581 return GRAVITY_UNKNOWN; // Should not happen
1584 public static function insert($item, $notify = false, $dontcache = false)
1586 $structure = self::getItemFields();
1590 $priority = PRIORITY_HIGH;
1592 // If it is a posting where users should get notifications, then define it as wall posting
1595 $item['origin'] = 1;
1596 $item['network'] = Protocol::DFRN;
1597 $item['protocol'] = Conversation::PARCEL_DFRN;
1599 if (is_int($notify)) {
1600 $priority = $notify;
1603 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1606 $uid = intval($item['uid']);
1608 $item['guid'] = self::guid($item, $notify);
1609 $item['uri'] = substr(Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']))), 0, 255);
1612 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1614 // Store conversation data
1615 $item = Conversation::insert($item);
1617 if (!empty($item['thr-parent'])) {
1618 $item['parent-uri'] = $item['thr-parent'];
1622 * Do we already have this item?
1623 * We have to check several networks since Friendica posts could be repeated
1624 * via OStatus (maybe Diasporsa as well)
1626 $duplicate = self::getDuplicateID($item);
1631 // Additional duplicate checks
1632 /// @todo Check why the first duplication check returns the item number and the second a 0
1633 if (self::isDuplicate($item)) {
1637 $item['wall'] = intval($item['wall'] ?? 0);
1638 $item['extid'] = trim($item['extid'] ?? '');
1639 $item['author-name'] = trim($item['author-name'] ?? '');
1640 $item['author-link'] = trim($item['author-link'] ?? '');
1641 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1642 $item['owner-name'] = trim($item['owner-name'] ?? '');
1643 $item['owner-link'] = trim($item['owner-link'] ?? '');
1644 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1645 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1646 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1647 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1648 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1649 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1650 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
1651 $item['location'] = trim($item['location'] ?? '');
1652 $item['coord'] = trim($item['coord'] ?? '');
1653 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1654 $item['deleted'] = 0;
1655 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1656 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1657 $item['verb'] = trim($item['verb'] ?? '');
1658 $item['object-type'] = trim($item['object-type'] ?? '');
1659 $item['object'] = trim($item['object'] ?? '');
1660 $item['target-type'] = trim($item['target-type'] ?? '');
1661 $item['target'] = trim($item['target'] ?? '');
1662 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
1663 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1664 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1665 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1666 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1667 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1668 $item['body'] = trim($item['body'] ?? '');
1669 $item['attach'] = trim($item['attach'] ?? '');
1670 $item['app'] = trim($item['app'] ?? '');
1671 $item['origin'] = intval($item['origin'] ?? 0);
1672 $item['postopts'] = trim($item['postopts'] ?? '');
1673 $item['resource-id'] = trim($item['resource-id'] ?? '');
1674 $item['event-id'] = intval($item['event-id'] ?? 0);
1675 $item['inform'] = trim($item['inform'] ?? '');
1676 $item['file'] = trim($item['file'] ?? '');
1678 // Items cannot be stored before they happen ...
1679 if ($item['created'] > DateTimeFormat::utcNow()) {
1680 $item['created'] = DateTimeFormat::utcNow();
1683 // We haven't invented time travel by now.
1684 if ($item['edited'] > DateTimeFormat::utcNow()) {
1685 $item['edited'] = DateTimeFormat::utcNow();
1688 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1690 $item['language'] = self::getLanguage($item);
1692 $item['gravity'] = self::getGravity($item);
1694 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1695 'photo' => $item['author-avatar'], 'network' => $item['network']];
1696 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1698 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1699 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1700 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1702 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1703 if (!$item['origin'] && in_array($item['post-type'], [self::PT_ARTICLE, self::PT_COMMENT]) && Contact::isSharing($actor, $item['uid'])) {
1704 $item['post-type'] = self::PT_FOLLOWER;
1707 // Ensure that there is an avatar cache
1708 Contact::checkAvatarCache($item['author-id']);
1709 Contact::checkAvatarCache($item['owner-id']);
1711 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1712 $item["contact-id"] = self::contactId($item);
1714 if (!self::isValid($item)) {
1718 // We don't store the causer, we only have it here for the checks in the function above
1719 unset($item['causer-id']);
1720 unset($item['causer-link']);
1722 // We don't store these fields anymore in the item table
1723 unset($item['author-link']);
1724 unset($item['author-name']);
1725 unset($item['author-avatar']);
1726 unset($item['author-network']);
1728 unset($item['owner-link']);
1729 unset($item['owner-name']);
1730 unset($item['owner-avatar']);
1732 $item['thr-parent'] = $item['parent-uri'];
1734 if ($item['parent-uri'] != $item['uri']) {
1735 $item = self::getParentData($item);
1740 $parent_id = $item['parent'];
1741 unset($item['parent']);
1742 $parent_origin = $item['parent_origin'];
1743 unset($item['parent_origin']);
1746 $parent_origin = $item['origin'];
1749 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1750 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1752 // Is this item available in the global items (with uid=0)?
1753 if ($item["uid"] == 0) {
1754 $item["global"] = true;
1756 // Set the global flag on all items if this was a global item entry
1757 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1759 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1763 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
1764 $item["private"] = self::PRIVATE;
1768 $item['edit'] = false;
1769 $item['parent'] = $parent_id;
1770 Hook::callAll('post_local', $item);
1771 unset($item['edit']);
1772 unset($item['parent']);
1774 Hook::callAll('post_remote', $item);
1777 if (!empty($item['cancel'])) {
1778 Logger::log('post cancelled by addon.');
1782 if (empty($item['vid']) && !empty($item['verb'])) {
1783 $item['vid'] = Verb::getID($item['verb']);
1786 // Creates or assigns the permission set
1787 $item['psid'] = PermissionSet::getIdFromACL(
1795 unset($item['allow_cid']);
1796 unset($item['allow_gid']);
1797 unset($item['deny_cid']);
1798 unset($item['deny_gid']);
1800 // This array field is used to trigger some automatic reactions
1801 // It is mainly used in the "post_local" hook.
1802 unset($item['api_source']);
1804 if ($item['verb'] == Activity::ANNOUNCE) {
1805 self::setOwnerforResharedItem($item);
1808 // Check for hashtags in the body and repair or add hashtag links
1809 $item['body'] = self::setHashtags($item['body']);
1811 // Fill the cache field
1812 self::putInCache($item);
1814 if (stristr($item['verb'], Activity::POKE)) {
1815 $notify_type = Delivery::POKE;
1817 $notify_type = Delivery::POST;
1820 $like_no_comment = DI::config()->get('system', 'like_no_comment');
1824 if (!in_array($item['verb'], self::ACTIVITIES)) {
1825 $item['icid'] = self::insertContent($item);
1828 $body = $item['body'];
1830 // We just remove everything that is content
1831 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1832 unset($item[$field]);
1835 unset($item['activity']);
1837 // Filling item related side tables
1839 // Diaspora signature
1840 if (!empty($item['diaspora_signed_text'])) {
1841 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']], true);
1844 unset($item['diaspora_signed_text']);
1846 // Attached file links
1847 if (!empty($item['file'])) {
1848 Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1851 unset($item['file']);
1853 // Delivery relevant data
1854 $delivery_data = Post\DeliveryData::extractFields($item);
1855 unset($item['postopts']);
1856 unset($item['inform']);
1858 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1859 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1862 // Store tags from the body if this hadn't been handled previously in the protocol classes
1863 if (!Tag::existsForPost($item['uri-id'])) {
1864 Tag::storeFromBody($item['uri-id'], $body);
1867 // Remove all fields that aren't part of the item table
1868 foreach ($item as $field => $value) {
1869 if (!in_array($field, $structure['item'])) {
1870 unset($item[$field]);
1874 $ret = DBA::insert('item', $item);
1876 // When the item was successfully stored we fetch the ID of the item.
1877 if (DBA::isResult($ret)) {
1878 $current_post = DBA::lastInsertId();
1880 // This can happen - for example - if there are locking timeouts.
1883 // Store the data into a spool file so that we can try again later.
1884 self::spool($orig_item);
1888 if ($current_post == 0) {
1889 // This is one of these error messages that never should occur.
1890 Logger::log("couldn't find created item - we better quit now.");
1895 // How much entries have we created?
1896 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1897 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1900 // There are duplicates. We delete our just created entry.
1901 Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
1903 // Yes, we could do a rollback here - but we possibly are still having users with MyISAM.
1904 DBA::delete('item', ['id' => $current_post]);
1907 } elseif ($entries == 0) {
1908 // This really should never happen since we quit earlier if there were problems.
1909 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1914 Logger::log('created item '.$current_post);
1916 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1917 $parent_id = $current_post;
1921 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1923 $item['id'] = $current_post;
1924 $item['parent'] = $parent_id;
1926 // update the commented timestamp on the parent
1927 // Only update "commented" if it is really a comment
1928 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1929 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1931 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1934 if ($item['parent-uri'] === $item['uri']) {
1935 self::addThread($current_post);
1937 self::updateThread($parent_id);
1941 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1942 if (self::tagDeliver($item['uid'], $current_post)) {
1943 // Get the user information for the logging
1944 $user = User::getById($uid);
1946 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1951 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1952 if (DBA::isResult($posted_item)) {
1954 Hook::callAll('post_local_end', $posted_item);
1956 Hook::callAll('post_remote_end', $posted_item);
1959 Logger::log('new item not found in DB, id ' . $current_post);
1963 if ($item['parent-uri'] === $item['uri']) {
1964 self::addShadow($current_post);
1966 self::addShadowPost($current_post);
1969 self::updateContact($item);
1971 UserItem::setNotification($current_post);
1973 check_user_notification($current_post);
1975 // Distribute items to users who subscribed to their tags
1976 self::distributeByTags($item);
1978 $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
1981 $transmit_item = Item::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
1982 // Don't relay participation messages
1983 if (($transmit_item['verb'] == Activity::FOLLOW) &&
1984 (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1985 Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
1991 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1994 return $current_post;
1998 * Change the owner of a parent item if it had been shared by a forum
2000 * (public) forum posts in the new format consist of the regular post by the author
2001 * followed by an announce message sent from the forum account.
2002 * Changing the owner helps in grouping forum posts.
2004 * @param array $item
2007 private static function setOwnerforResharedItem(array $item)
2009 $parent = self::selectFirst(['id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
2010 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2011 if (!DBA::isResult($parent)) {
2012 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2016 $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
2017 if (!DBA::isResult($author)) {
2018 Logger::error('Author not found', ['id' => $item['author-id']]);
2022 $cid = Contact::getIdForURL($author['url'], $item['uid']);
2023 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
2024 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
2028 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
2029 if (!in_array($parent['post-type'], [self::PT_ARTICLE, self::PT_COMMENT]) || Contact::isSharing($parent['owner-id'], $item['uid'])) {
2030 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2033 self::update(['post-type' => self::PT_ANNOUNCEMENT], ['id' => $parent['id']]);
2034 Logger::info('Set announcement post-type', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2038 self::update(['owner-id' => $item['author-id'], 'contact-id' => $cid], ['id' => $parent['id']]);
2039 Logger::info('Change owner of the parent', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'owner-id' => $item['author-id'], 'contact-id' => $cid]);
2043 * Distribute the given item to users who subscribed to their tags
2045 * @param array $item Processed item
2047 private static function distributeByTags(array $item)
2049 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
2053 $uids = Tag::getUIDListByURIId($item['uri-id']);
2054 foreach ($uids as $uid) {
2055 if (Contact::isSharing($item['author-id'], $uid)) {
2058 $fields = ['post-type' => self::PT_TAG];
2061 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
2062 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
2067 * Insert a new item content entry
2069 * @param array $item The item fields that are to be inserted
2070 * @throws \Exception
2072 private static function insertContent(array $item)
2074 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2076 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2077 if (isset($item[$field])) {
2078 $fields[$field] = $item[$field];
2082 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2083 if (DBA::isResult($item_content)) {
2084 $icid = $item_content['id'];
2085 Logger::info('Content found', ['icid' => $icid, 'uri' => $item['uri']]);
2089 DBA::insert('item-content', $fields, true);
2090 $icid = DBA::lastInsertId();
2092 Logger::info('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
2096 // Possibly there can be timing issues. Then the same content could be inserted multiple times.
2097 // Due to the indexes this doesn't happen, but "lastInsertId" will be empty in these situations.
2098 // So we have to fetch the id manually. This is no bug and there is no data loss.
2099 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2100 if (DBA::isResult($item_content)) {
2101 $icid = $item_content['id'];
2102 Logger::notice('Content inserted with empty lastInsertId', ['icid' => $icid, 'uri' => $item['uri']]);
2106 // This shouldn't happen.
2107 Logger::error("Content wasn't inserted", $item);
2112 * Update existing item content entries
2114 * @param array $item The item fields that are to be changed
2115 * @param array $condition The condition for finding the item content entries
2116 * @throws \Exception
2118 private static function updateContent($item, $condition)
2120 // We have to select only the fields from the "item-content" table
2122 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2123 if (isset($item[$field])) {
2124 $fields[$field] = $item[$field];
2128 if (empty($fields)) {
2132 DBA::update('item-content', $fields, $condition, true);
2133 Logger::info('Updated content', ['condition' => $condition]);
2137 * Distributes public items to the receivers
2139 * @param integer $itemid Item ID that should be added
2140 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2141 * @throws \Exception
2143 public static function distribute($itemid, $signed_text = '')
2145 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2146 $parent = self::selectFirst(['owner-id'], $condition);
2147 if (!DBA::isResult($parent)) {
2151 // Only distribute public items from native networks
2152 $condition = ['id' => $itemid, 'uid' => 0,
2153 'network' => array_merge(Protocol::FEDERATED ,['']),
2154 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2155 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2156 if (!DBA::isResult($item)) {
2160 $origin = $item['origin'];
2164 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2165 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2166 if (!DBA::isResult($owner)) {
2170 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2171 $contacts = DBA::select('contact', ['uid'], $condition);
2172 while ($contact = DBA::fetch($contacts)) {
2173 if ($contact['uid'] == 0) {
2177 $users[$contact['uid']] = $contact['uid'];
2179 DBA::close($contacts);
2181 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2182 $contacts = DBA::select('contact', ['uid'], $condition);
2183 while ($contact = DBA::fetch($contacts)) {
2184 if ($contact['uid'] == 0) {
2188 $users[$contact['uid']] = $contact['uid'];
2190 DBA::close($contacts);
2192 if (!empty($owner['alias'])) {
2193 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
2194 $contacts = DBA::select('contact', ['uid'], $condition);
2195 while ($contact = DBA::fetch($contacts)) {
2196 if ($contact['uid'] == 0) {
2200 $users[$contact['uid']] = $contact['uid'];
2202 DBA::close($contacts);
2207 if ($item['uri'] != $item['parent-uri']) {
2208 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2209 while ($parent = self::fetch($parents)) {
2210 $users[$parent['uid']] = $parent['uid'];
2211 if ($parent['origin'] && !$origin) {
2212 $origin_uid = $parent['uid'];
2217 foreach ($users as $uid) {
2218 if ($origin_uid == $uid) {
2219 $item['diaspora_signed_text'] = $signed_text;
2221 self::storeForUser($item, $uid);
2226 * Store a public item defined by their URI-ID for the given users
2228 * @param integer $uri_id URI-ID of the given item
2229 * @param integer $uid The user that will receive the item entry
2230 * @param array $fields Additional fields to be stored
2231 * @return integer stored item id
2233 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
2235 $item = self::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
2236 if (!DBA::isResult($item)) {
2240 if (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED)) {
2241 Logger::notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]);
2245 $item['post-type'] = self::PT_STORED;
2247 $item = array_merge($item, $fields);
2249 $stored = self::storeForUser($item, $uid);
2250 Logger::info('Public item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
2255 * Store a public item array for the given users
2257 * @param array $item The item entry that will be stored
2258 * @param integer $uid The user that will receive the item entry
2259 * @return integer stored item id
2260 * @throws \Exception
2262 private static function storeForUser(array $item, int $uid)
2264 if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
2265 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
2270 unset($item['parent']);
2271 unset($item['mention']);
2272 unset($item['starred']);
2273 unset($item['unseen']);
2274 unset($item['psid']);
2276 $item['uid'] = $uid;
2277 $item['origin'] = 0;
2280 if ($item['gravity'] == GRAVITY_PARENT) {
2281 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
2283 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
2286 if (!empty($contact['id'])) {
2287 $item['contact-id'] = $contact['id'];
2289 // Shouldn't happen at all
2290 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
2291 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2292 if (!DBA::isResult($self)) {
2293 // Shouldn't happen even less
2294 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
2297 $item['contact-id'] = $self['id'];
2300 /// @todo Handling of "event-id"
2303 if ($item['gravity'] == GRAVITY_PARENT) {
2304 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2305 if (DBA::isResult($contact)) {
2306 $notify = self::isRemoteSelf($contact, $item);
2310 $distributed = self::insert($item, $notify, true);
2312 if (!$distributed) {
2313 Logger::info("Distributed public item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
2315 Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
2317 return $distributed;
2321 * Add a shadow entry for a given item id that is a thread starter
2323 * We store every public item entry additionally with the user id "0".
2324 * This is used for the community page and for the search.
2325 * It is planned that in the future we will store public item entries only once.
2327 * @param integer $itemid Item ID that should be added
2328 * @throws \Exception
2330 public static function addShadow($itemid)
2332 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2333 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2334 $item = self::selectFirst($fields, $condition);
2336 if (!DBA::isResult($item)) {
2340 // is it already a copy?
2341 if (($itemid == 0) || ($item['uid'] == 0)) {
2345 // Is it a visible public post?
2346 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
2350 // is it an entry from a connector? Only add an entry for natively connected networks
2351 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2355 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2359 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2361 if (DBA::isResult($item)) {
2362 // Preparing public shadow (removing user specific data)
2365 unset($item['parent']);
2366 unset($item['wall']);
2367 unset($item['mention']);
2368 unset($item['origin']);
2369 unset($item['starred']);
2370 unset($item['postopts']);
2371 unset($item['inform']);
2372 if ($item['uri'] == $item['parent-uri']) {
2373 $item['contact-id'] = $item['owner-id'];
2375 $item['contact-id'] = $item['author-id'];
2378 $public_shadow = self::insert($item, false, true);
2380 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
2385 * Add a shadow entry for a given item id that is a comment
2387 * This function does the same like the function above - but for comments
2389 * @param integer $itemid Item ID that should be added
2390 * @throws \Exception
2392 public static function addShadowPost($itemid)
2394 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2395 if (!DBA::isResult($item)) {
2399 // Is it a toplevel post?
2400 if ($item['gravity'] == GRAVITY_PARENT) {
2401 self::addShadow($itemid);
2405 // Is this a shadow entry?
2406 if ($item['uid'] == 0) {
2410 // Is there a shadow parent?
2411 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2415 // Is there already a shadow entry?
2416 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2420 // Save "origin" and "parent" state
2421 $origin = $item['origin'];
2422 $parent = $item['parent'];
2424 // Preparing public shadow (removing user specific data)
2427 unset($item['parent']);
2428 unset($item['wall']);
2429 unset($item['mention']);
2430 unset($item['origin']);
2431 unset($item['starred']);
2432 unset($item['postopts']);
2433 unset($item['inform']);
2434 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2436 $public_shadow = self::insert($item, false, true);
2438 Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
2440 // If this was a comment to a Diaspora post we don't get our comment back.
2441 // This means that we have to distribute the comment by ourselves.
2442 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2443 self::distribute($public_shadow);
2448 * Adds a language specification in a "language" element of given $arr.
2449 * Expects "body" element to exist in $arr.
2451 * @param array $item
2452 * @return string detected language
2453 * @throws \Text_LanguageDetect_Exception
2455 private static function getLanguage(array $item)
2457 $naked_body = BBCode::toPlaintext($item['body'], false);
2459 $ld = new Text_LanguageDetect();
2460 $ld->setNameMode(2);
2461 $languages = $ld->detect($naked_body, 3);
2462 if (is_array($languages)) {
2463 return json_encode($languages);
2470 * Creates an unique guid out of a given uri
2472 * @param string $uri uri of an item entry
2473 * @param string $host hostname for the GUID prefix
2474 * @return string unique guid
2476 public static function guidFromUri($uri, $host)
2478 // Our regular guid routine is using this kind of prefix as well
2479 // We have to avoid that different routines could accidentally create the same value
2480 $parsed = parse_url($uri);
2482 // We use a hash of the hostname as prefix for the guid
2483 $guid_prefix = hash("crc32", $host);
2485 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2486 unset($parsed["scheme"]);
2488 // Glue it together to be able to make a hash from it
2489 $host_id = implode("/", $parsed);
2491 // We could use any hash algorithm since it isn't a security issue
2492 $host_hash = hash("ripemd128", $host_id);
2494 return $guid_prefix.$host_hash;
2498 * generate an unique URI
2500 * @param integer $uid User id
2501 * @param string $guid An existing GUID (Otherwise it will be generated)
2504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2506 public static function newURI($uid, $guid = "")
2509 $guid = System::createUUID();
2512 return DI::baseUrl()->get() . '/objects/' . $guid;
2516 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2518 * This can be used to filter for inactive contacts.
2519 * Only do this for public postings to avoid privacy problems, since poco data is public.
2520 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2522 * @param array $arr Contains the just posted item record
2523 * @throws \Exception
2525 private static function updateContact($arr)
2527 // Unarchive the author
2528 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2529 if (DBA::isResult($contact)) {
2530 Contact::unmarkForArchival($contact);
2533 // Unarchive the contact if it's not our own contact
2534 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2535 if (DBA::isResult($contact)) {
2536 Contact::unmarkForArchival($contact);
2539 /// @todo On private posts we could obfuscate the date
2540 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2542 // Is it a forum? Then we don't care about the rules from above
2543 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2544 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2550 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2551 // So we have to ensure to only update the last item when it had been our own post,
2552 // or it had been done by a "regular" contact.
2553 if (!empty($arr['wall'])) {
2554 $condition = ['id' => $arr['contact-id']];
2556 $condition = ['id' => $arr['contact-id'], 'self' => false];
2558 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2560 // Now do the same for the system wide contacts with uid=0
2561 if ($arr['private'] != self::PRIVATE) {
2562 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2563 ['id' => $arr['owner-id']]);
2565 if ($arr['owner-id'] != $arr['author-id']) {
2566 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2567 ['id' => $arr['author-id']]);
2572 public static function setHashtags($body)
2574 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
2575 $tags = BBCode::getTags($body);
2578 if (!count($tags)) {
2582 // This sorting is important when there are hashtags that are part of other hashtags
2583 // Otherwise there could be problems with hashtags like #test and #test2
2584 // Because of this we are sorting from the longest to the shortest tag.
2585 usort($tags, function ($a, $b) {
2586 return strlen($b) <=> strlen($a);
2589 $URLSearchString = "^\[\]";
2591 // All hashtags should point to the home server if "local_tags" is activated
2592 if (DI::config()->get('system', 'local_tags')) {
2593 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2594 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2597 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2598 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2600 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2603 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2605 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2608 $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2610 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2613 // Repair recursive urls
2614 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2617 foreach ($tags as $tag) {
2618 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2622 $basetag = str_replace('_', ' ', substr($tag, 1));
2623 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2625 $body = str_replace($tag, $newtag, $body);
2628 // Convert back the masked hashtags
2629 $body = str_replace("#", "#", $body);
2638 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2641 * @param int $item_id
2642 * @return boolean true if item was deleted, else false
2643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2644 * @throws \ImagickException
2646 private static function tagDeliver($uid, $item_id)
2650 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2651 if (!DBA::isResult($user)) {
2655 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2656 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2658 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2659 if (!DBA::isResult($item)) {
2663 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2666 * Diaspora uses their own hardwired link URL in @-tags
2667 * instead of the one we supply with webfinger
2669 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2671 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2673 foreach ($matches as $mtch) {
2674 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2676 Logger::log('mention found: ' . $mtch[2]);
2682 if (($community_page || $prvgroup) &&
2683 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
2684 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2685 DBA::delete('item', ['id' => $item_id]);
2691 $arr = ['item' => $item, 'user' => $user];
2693 Hook::callAll('tagged', $arr);
2695 if (!$community_page && !$prvgroup) {
2700 * tgroup delivery - setup a second delivery chain
2701 * prevent delivery looping - only proceed
2702 * if the message originated elsewhere and is a top-level post
2704 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2708 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2709 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2710 if (!DBA::isResult($self)) {
2714 $owner_id = Contact::getIdForURL($self['url']);
2716 // also reset all the privacy bits to the forum default permissions
2718 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2720 $psid = PermissionSet::getIdFromACL(
2728 $forum_mode = ($prvgroup ? 2 : 1);
2730 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2731 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2732 self::update($fields, ['id' => $item_id]);
2734 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2736 Item::performActivity($item_id, 'announce', $uid);
2741 public static function isRemoteSelf($contact, &$datarray)
2743 if (!$contact['remote_self']) {
2747 // Prevent the forwarding of posts that are forwarded
2748 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2749 Logger::info('Already forwarded');
2753 // Prevent to forward already forwarded posts
2754 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2755 Logger::info('Already forwarded (second test)');
2759 // Only forward posts
2760 if ($datarray["verb"] != Activity::POST) {
2761 Logger::info('No post');
2765 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2766 Logger::info('Not public');
2770 $datarray2 = $datarray;
2771 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2772 if ($contact['remote_self'] == 2) {
2773 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2774 ['uid' => $contact['uid'], 'self' => true]);
2775 if (DBA::isResult($self)) {
2776 $datarray['contact-id'] = $self["id"];
2778 $datarray['owner-name'] = $self["name"];
2779 $datarray['owner-link'] = $self["url"];
2780 $datarray['owner-avatar'] = $self["thumb"];
2782 $datarray['author-name'] = $datarray['owner-name'];
2783 $datarray['author-link'] = $datarray['owner-link'];
2784 $datarray['author-avatar'] = $datarray['owner-avatar'];
2786 unset($datarray['edited']);
2788 unset($datarray['network']);
2789 unset($datarray['owner-id']);
2790 unset($datarray['author-id']);
2793 if ($contact['network'] != Protocol::FEED) {
2794 $datarray["guid"] = System::createUUID();
2795 unset($datarray["plink"]);
2796 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2797 $datarray["parent-uri"] = $datarray["uri"];
2798 $datarray["thr-parent"] = $datarray["uri"];
2799 $datarray["extid"] = Protocol::DFRN;
2800 $urlpart = parse_url($datarray2['author-link']);
2801 $datarray["app"] = $urlpart["host"];
2803 $datarray['private'] = self::PUBLIC;
2807 if ($contact['network'] != Protocol::FEED) {
2808 // Store the original post
2809 $result = self::insert($datarray2);
2810 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2812 $datarray["app"] = "Feed";
2816 // Trigger automatic reactions for addons
2817 $datarray['api_source'] = true;
2819 // We have to tell the hooks who we are - this really should be improved
2820 $_SESSION["authenticated"] = true;
2821 $_SESSION["uid"] = $contact['uid'];
2830 * @param array $item
2833 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2834 * @throws \ImagickException
2836 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2838 if (DI::config()->get('system', 'disable_embedded')) {
2842 Logger::info('check for photos');
2843 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2848 $img_start = strpos($orig_body, '[img');
2849 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2850 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2852 while (($img_st_close !== false) && ($img_len !== false)) {
2853 $img_st_close++; // make it point to AFTER the closing bracket
2854 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2856 Logger::info('found photo', ['image' => $image]);
2858 if (stristr($image, $site . '/photo/')) {
2859 // Only embed locally hosted photos
2861 $i = basename($image);
2862 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2863 $x = strpos($i, '-');
2866 $res = substr($i, $x + 1);
2867 $i = substr($i, 0, $x);
2868 $photo = Photo::getPhotoForUser($uid, $i, $res);
2869 if (DBA::isResult($photo)) {
2871 * Check to see if we should replace this photo link with an embedded image
2872 * 1. No need to do so if the photo is public
2873 * 2. If there's a contact-id provided, see if they're in the access list
2874 * for the photo. If so, embed it.
2875 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2876 * permissions, regardless of order but first check to see if they're an exact
2877 * match to save some processing overhead.
2879 if (self::hasPermissions($photo)) {
2881 $recips = self::enumeratePermissions($photo);
2882 if (in_array($cid, $recips)) {
2886 if (self::samePermissions($uid, $item, $photo)) {
2892 $photo_img = Photo::getImageForPhoto($photo);
2893 // If a custom width and height were specified, apply before embedding
2894 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2895 Logger::info('scaling photo');
2897 $width = intval($match[1]);
2898 $height = intval($match[2]);
2900 $photo_img->scaleDown(max($width, $height));
2903 $data = $photo_img->asString();
2904 $type = $photo_img->getType();
2906 Logger::info('replacing photo');
2907 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2908 Logger::debug('replaced', ['image' => $image]);
2914 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2915 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2916 if ($orig_body === false) {
2920 $img_start = strpos($orig_body, '[img');
2921 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2922 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2925 $new_body = $new_body . $orig_body;
2930 private static function hasPermissions($obj)
2932 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2933 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2936 private static function samePermissions($uid, $obj1, $obj2)
2938 // first part is easy. Check that these are exactly the same.
2939 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2940 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2941 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2942 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2946 // This is harder. Parse all the permissions and compare the resulting set.
2947 $recipients1 = self::enumeratePermissions($obj1);
2948 $recipients2 = self::enumeratePermissions($obj2);
2952 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2953 return ($recipients1 == $recipients2);
2957 * Returns an array of contact-ids that are allowed to see this object
2959 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2960 * @param bool $check_dead Prunes unavailable contacts from the result
2962 * @throws \Exception
2964 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2966 $aclFormater = DI::aclFormatter();
2968 $allow_people = $aclFormater->expand($obj['allow_cid']);
2969 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2970 $deny_people = $aclFormater->expand($obj['deny_cid']);
2971 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2972 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2973 $deny = array_unique(array_merge($deny_people, $deny_groups));
2974 $recipients = array_diff($recipients, $deny);
2978 public static function expire($uid, $days, $network = "", $force = false)
2980 if (!$uid || ($days < 1)) {
2984 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2985 $uid, GRAVITY_PARENT];
2988 * $expire_network_only = save your own wall posts
2989 * and just expire conversations started by others
2991 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2993 if ($expire_network_only) {
2994 $condition[0] .= " AND NOT `wall`";
2997 if ($network != "") {
2998 $condition[0] .= " AND `network` = ?";
2999 $condition[] = $network;
3002 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3003 $condition[] = $days;
3005 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3007 if (!DBA::isResult($items)) {
3011 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
3013 // Forcing expiring of items - but not notes and marked items
3015 $expire_items = true;
3018 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3019 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3020 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3024 while ($item = Item::fetch($items)) {
3025 // don't expire filed items
3027 if (strpos($item['file'], '[') !== false) {
3031 // Only expire posts, not photos and photo comments
3033 if (!$expire_photos && strlen($item['resource-id'])) {
3035 } elseif (!$expire_starred && intval($item['starred'])) {
3037 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3039 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3043 self::markForDeletionById($item['id'], PRIORITY_LOW);
3048 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3051 public static function firstPostDate($uid, $wall = false)
3053 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3054 $params = ['order' => ['received' => false]];
3055 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3056 if (DBA::isResult($thread)) {
3057 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3063 * add/remove activity to an item
3065 * Toggle activities as like,dislike,attend of an item
3067 * @param int $item_id
3068 * @param string $verb
3069 * Activity verb. One of
3070 * like, unlike, dislike, undislike, attendyes, unattendyes,
3071 * attendno, unattendno, attendmaybe, unattendmaybe,
3072 * announce, unannouce
3074 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3075 * @throws \ImagickException
3076 * @hook 'post_local_end'
3078 * 'post_id' => ID of posted item
3080 public static function performActivity(int $item_id, string $verb, int $uid)
3086 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
3088 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
3089 if (!DBA::isResult($item)) {
3090 Logger::log('like: unknown item ' . $item_id);
3094 $item_uri = $item['uri'];
3096 if (!in_array($item['uid'], [0, $uid])) {
3100 if (!Item::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
3101 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
3102 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
3103 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
3104 if (!DBA::isResult($item)) {
3105 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
3111 // Retrieves the local post owner
3112 $owner = User::getOwnerDataById($uid);
3113 if (empty($owner)) {
3114 Logger::info('Empty owner for user', ['uid' => $uid]);
3118 // Retrieve the current logged in user's public contact
3119 $author_id = Contact::getIdForURL($owner['url']);
3120 if (empty($author_id)) {
3121 Logger::info('Empty public contact');
3129 $activity = Activity::LIKE;
3133 $activity = Activity::DISLIKE;
3137 $activity = Activity::ATTEND;
3141 $activity = Activity::ATTENDNO;
3144 case 'unattendmaybe':
3145 $activity = Activity::ATTENDMAYBE;
3149 $activity = Activity::FOLLOW;
3153 $activity = Activity::ANNOUNCE;
3156 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3160 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3162 // Enable activity toggling instead of on/off
3163 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3165 // Look for an existing verb row
3166 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3167 if ($event_verb_flag) {
3168 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3170 // Translate to the index based activity index
3172 foreach ($verbs as $verb) {
3173 $vids[] = Verb::getID($verb);
3176 $vids = Verb::getID($activity);
3179 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3180 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3181 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3183 if (DBA::isResult($like_item)) {
3185 * Truth table for existing activities
3187 * | Inputs || Outputs |
3188 * |----------------------------||-------------------|
3189 * | Mode | Event | Same verb || Delete? | Return? |
3190 * |--------|-------|-----------||---------|---------|
3191 * | create | Yes | Yes || No | Yes |
3192 * | create | Yes | No || Yes | No |
3193 * | create | No | Yes || No | Yes |
3194 * | create | No | No || N/A†|
3195 * | delete | Yes | Yes || Yes | N/A‡ |
3196 * | delete | Yes | No || No | N/A‡ |
3197 * | delete | No | Yes || Yes | N/A‡ |
3198 * | delete | No | No || N/A†|
3199 * |--------|-------|-----------||---------|---------|
3200 * | A | B | C || A xor C | !B or C |
3202 * †Can't happen: It's impossible to find an existing non-event activity without
3203 * the same verb because we are only looking for this single verb.
3205 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
3207 if ($mode == 'create' xor $like_item['verb'] == $activity) {
3208 self::markForDeletionById($like_item['id']);
3211 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3216 // No need to go further if we aren't creating anything
3217 if ($mode == 'delete') {
3221 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3224 'guid' => System::createUUID(),
3225 'uri' => self::newURI($item['uid']),
3226 'uid' => $item['uid'],
3227 'contact-id' => $owner['id'],
3228 'wall' => $item['wall'],
3230 'network' => Protocol::DFRN,
3231 'gravity' => GRAVITY_ACTIVITY,
3232 'parent' => $item['id'],
3233 'parent-uri' => $item['uri'],
3234 'thr-parent' => $item['uri'],
3235 'owner-id' => $author_id,
3236 'author-id' => $author_id,
3237 'body' => $activity,
3238 'verb' => $activity,
3239 'object-type' => $objtype,
3240 'allow_cid' => $item['allow_cid'],
3241 'allow_gid' => $item['allow_gid'],
3242 'deny_cid' => $item['deny_cid'],
3243 'deny_gid' => $item['deny_gid'],
3248 $signed = Diaspora::createLikeSignature($uid, $new_item);
3249 if (!empty($signed)) {
3250 $new_item['diaspora_signed_text'] = json_encode($signed);
3253 $new_item_id = self::insert($new_item);
3255 // If the parent item isn't visible then set it to visible
3256 if (!$item['visible']) {
3257 self::update(['visible' => true], ['id' => $item['id']]);
3260 $new_item['id'] = $new_item_id;
3262 Hook::callAll('post_local_end', $new_item);
3267 private static function addThread($itemid, $onlyshadow = false)
3269 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3270 'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
3271 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3272 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3273 $item = self::selectFirst($fields, $condition);
3275 if (!DBA::isResult($item)) {
3279 $item['iid'] = $itemid;
3282 $result = DBA::insert('thread', $item);
3284 Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
3288 private static function updateThread($itemid, $setmention = false)
3290 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3291 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
3292 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3294 $item = self::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
3295 if (!DBA::isResult($item)) {
3300 $item["mention"] = 1;
3305 foreach ($item as $field => $data) {
3306 if (!in_array($field, ["guid"])) {
3307 $fields[$field] = $data;
3311 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3313 Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
3316 private static function deleteThread($itemid, $itemuri = "")
3318 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3319 if (!DBA::isResult($item)) {
3320 Logger::info('No thread found', ['id' => $itemid]);
3324 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3326 Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
3328 if ($itemuri != "") {
3329 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3330 if (!self::exists($condition)) {
3331 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3332 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3337 public static function getPermissionsSQLByUserId($owner_id)
3339 $local_user = local_user();
3340 $remote_user = Session::getRemoteContactID($owner_id);
3343 * Construct permissions
3345 * default permissions - anonymous user
3347 $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
3349 // Profile owner - everything is visible
3350 if ($local_user && ($local_user == $owner_id)) {
3352 } elseif ($remote_user) {
3354 * Authenticated visitor. Unless pre-verified,
3355 * check that the contact belongs to this $owner_id
3356 * and load the groups the visitor belongs to.
3357 * If pre-verified, the caller is expected to have already
3358 * done this and passed the groups into this function.
3360 $set = PermissionSet::get($owner_id, $remote_user);
3363 $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3368 $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
3375 * get translated item type
3380 public static function postType($item)
3382 if (!empty($item['event-id'])) {
3383 return DI::l10n()->t('event');
3384 } elseif (!empty($item['resource-id'])) {
3385 return DI::l10n()->t('photo');
3386 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
3387 return DI::l10n()->t('activity');
3388 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
3389 return DI::l10n()->t('comment');
3392 return DI::l10n()->t('post');
3396 * Sets the "rendered-html" field of the provided item
3398 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3400 * @param array $item
3401 * @param bool $update
3403 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3404 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3406 public static function putInCache(&$item, $update = false)
3408 $body = $item["body"];
3410 $rendered_hash = $item['rendered-hash'] ?? '';
3411 $rendered_html = $item['rendered-html'] ?? '';
3413 if ($rendered_hash == ''
3414 || $rendered_html == ""
3415 || $rendered_hash != hash("md5", $item["body"])
3416 || DI::config()->get("system", "ignore_cache")
3418 self::addRedirToImageTags($item);
3420 $item["rendered-html"] = BBCode::convert($item["body"]);
3421 $item["rendered-hash"] = hash("md5", $item["body"]);
3423 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3424 Hook::callAll('put_item_in_cache', $hook_data);
3425 $item['rendered-html'] = $hook_data['rendered-html'];
3426 $item['rendered-hash'] = $hook_data['rendered-hash'];
3429 // Force an update if the generated values differ from the existing ones
3430 if ($rendered_hash != $item["rendered-hash"]) {
3434 // Only compare the HTML when we forcefully ignore the cache
3435 if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3439 if ($update && !empty($item["id"])) {
3442 'rendered-html' => $item["rendered-html"],
3443 'rendered-hash' => $item["rendered-hash"]
3445 ['id' => $item["id"]]
3450 $item["body"] = $body;
3454 * Find any non-embedded images in private items and add redir links to them
3456 * @param array &$item The field array of an item row
3458 private static function addRedirToImageTags(array &$item)
3463 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3465 foreach ($matches as $mtch) {
3466 if (strpos($mtch[1], '/redir') !== false) {
3470 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3471 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3472 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3479 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3480 * If attach is true, also add icons for item attachments.
3482 * @param array $item
3483 * @param boolean $attach
3484 * @param boolean $is_preview
3485 * @return string item body html
3486 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3487 * @throws \ImagickException
3488 * @hook prepare_body_init item array before any work
3489 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3490 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3491 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3493 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3496 Hook::callAll('prepare_body_init', $item);
3498 // In order to provide theme developers more possibilities, event items
3499 // are treated differently.
3500 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3501 $ev = Event::getItemHTML($item);
3505 $tags = Tag::populateFromItem($item);
3507 $item['tags'] = $tags['tags'];
3508 $item['hashtags'] = $tags['hashtags'];
3509 $item['mentions'] = $tags['mentions'];
3511 // Compile eventual content filter reasons
3512 $filter_reasons = [];
3513 if (!$is_preview && public_contact() != $item['author-id']) {
3514 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3515 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3520 'filter_reasons' => $filter_reasons
3522 Hook::callAll('prepare_body_content_filter', $hook_data);
3523 $filter_reasons = $hook_data['filter_reasons'];
3527 // Update the cached values if there is no "zrl=..." on the links.
3528 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3530 // Or update it if the current viewer is the intented viewer.
3531 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3535 self::putInCache($item, $update);
3536 $s = $item["rendered-html"];
3541 'preview' => $is_preview,
3542 'filter_reasons' => $filter_reasons
3544 Hook::callAll('prepare_body', $hook_data);
3545 $s = $hook_data['html'];
3549 // Replace the blockquotes with quotes that are used in mails.
3550 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3551 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3558 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3559 foreach ($matches as $mtch) {
3562 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3564 if (strpos($mime, 'video') !== false) {
3567 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3570 $url_parts = explode('/', $the_url);
3571 $id = end($url_parts);
3572 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3575 'title' => DI::l10n()->t('View Video'),
3582 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3584 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3585 $filesubtype = str_replace('.', '-', $filesubtype);
3588 $filesubtype = 'unkn';
3591 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3592 $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
3594 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3595 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3599 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3603 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3604 $x = Map::byCoordinates(trim($item['coord']));
3606 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3610 // Replace friendica image url size with theme preference.
3611 if (!empty($a->theme_info['item_image_size'])) {
3612 $ps = $a->theme_info['item_image_size'];
3613 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3616 $s = HTML::applyContentFilter($s, $filter_reasons);
3618 $hook_data = ['item' => $item, 'html' => $s];
3619 Hook::callAll('prepare_body_final', $hook_data);
3621 return $hook_data['html'];
3625 * get private link for item
3627 * @param array $item
3628 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3629 * @throws \Exception
3631 public static function getPlink($item)
3635 'href' => "display/" . $item['guid'],
3636 'orig' => "display/" . $item['guid'],
3637 'title' => DI::l10n()->t('View on separate page'),
3638 'orig_title' => DI::l10n()->t('view on separate page'),
3641 if (!empty($item['plink'])) {
3642 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3643 $ret["title"] = DI::l10n()->t('link to source');
3645 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3647 'href' => $item['plink'],
3648 'orig' => $item['plink'],
3649 'title' => DI::l10n()->t('link to source'),
3659 * Is the given item array a post that is sent as starting post to a forum?
3661 * @param array $item
3662 * @param array $owner
3664 * @return boolean "true" when it is a forum post
3666 public static function isForumPost(array $item, array $owner = [])
3668 if (empty($owner)) {
3669 $owner = User::getOwnerDataById($item['uid']);
3670 if (empty($owner)) {
3675 if (($item['author-id'] == $item['owner-id']) ||
3676 ($owner['id'] == $item['contact-id']) ||
3677 ($item['uri'] != $item['parent-uri']) ||
3682 return Contact::isForum($item['contact-id']);
3686 * Search item id for given URI or plink
3688 * @param string $uri
3689 * @param integer $uid
3691 * @return integer item id
3693 public static function searchByLink($uri, $uid = 0)
3695 $ssl_uri = str_replace('http://', 'https://', $uri);
3696 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3698 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3699 if (DBA::isResult($item)) {
3703 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3704 if (!DBA::isResult($itemcontent)) {
3708 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3709 if (!DBA::isResult($itemuri)) {
3713 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3714 if (DBA::isResult($item)) {
3722 * Return the URI for a link to the post
3724 * @param string $uri URI or link to post
3726 * @return string URI
3728 public static function getURIByLink(string $uri)
3730 $ssl_uri = str_replace('http://', 'https://', $uri);
3731 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3733 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3734 if (DBA::isResult($item)) {
3735 return $item['uri'];
3738 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3739 if (!DBA::isResult($itemcontent)) {
3743 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3744 if (DBA::isResult($itemuri)) {
3745 return $itemuri['uri'];
3752 * Fetches item for given URI or plink
3754 * @param string $uri
3755 * @param integer $uid
3757 * @return integer item id
3759 public static function fetchByLink(string $uri, int $uid = 0)
3761 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3762 $item_id = self::searchByLink($uri, $uid);
3763 if (!empty($item_id)) {
3764 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3768 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3769 $item_id = self::searchByLink($fetched_uri, $uid);
3771 $item_id = Diaspora::fetchByURL($uri);
3774 if (!empty($item_id)) {
3775 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3779 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3784 * Return share data from an item array (if the item is shared item)
3785 * We are providing the complete Item array, because at some time in the future
3786 * we hopefully will define these values not in the body anymore but in some item fields.
3787 * This function is meant to replace all similar functions in the system.
3789 * @param array $item
3791 * @return array with share information
3793 public static function getShareArray($item)
3795 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3799 $attribute_string = $matches[2];
3800 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3801 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3802 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3803 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3810 * Fetch item information for shared items from the original items and adds it.
3812 * @param array $item
3814 * @return array item array with data from the original item
3816 public static function addShareDataFromOriginal(array $item)
3818 $shared = self::getShareArray($item);
3819 if (empty($shared)) {
3823 // Real reshares always have got a GUID.
3824 if (empty($shared['guid'])) {
3828 $uid = $item['uid'] ?? 0;
3830 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3831 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3832 if (!DBA::isResult($shared_item)) {
3833 if (empty($shared['link'])) {
3837 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3838 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3840 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3844 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
3845 if (!DBA::isResult($shared_item)) {
3848 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3850 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3853 if (!empty($shared_item['title'])) {
3854 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3855 unset($shared_item['title']);
3857 $body = $shared_item['body'];
3860 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3861 unset($shared_item['body']);
3863 return array_merge($item, $shared_item);