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;
69 const PT_PERSONAL_NOTE = 128;
71 // Field list that is used to display the items
72 const DISPLAY_FIELDLIST = [
73 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
74 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
75 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
76 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
77 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
78 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
79 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
80 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
81 'writable', 'self', 'cid', 'alias', 'pinned',
82 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
83 'event-summary', 'event-desc', 'event-location', 'event-type',
84 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
85 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
88 // Field list that is used to deliver items via the protocols
89 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
90 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
91 'private', 'title', 'body', 'location', 'coord', 'app',
92 'attach', 'deleted', 'extid', 'post-type', 'gravity',
93 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
94 'author-id', 'author-link', 'owner-link', 'contact-uid',
95 'signed_text', 'signature', 'signer', 'network'];
97 // Field list for "item-content" table that is mixed with the item table
98 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
99 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
100 'object-type', 'object', 'target-type', 'target', 'plink'];
102 // Field list for "item-content" table that is not present in the "item" table
103 const CONTENT_FIELDLIST = ['language'];
105 // All fields in the item table
106 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
107 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
108 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
109 'created', 'edited', 'commented', 'received', 'changed', 'verb',
110 'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform',
111 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
112 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
113 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
114 'title', 'content-warning', 'body', 'location', 'coord', 'app',
115 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
116 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
117 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
119 // List of all verbs that don't need additional content data.
120 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
122 Activity::LIKE, Activity::DISLIKE,
123 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
131 const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction'];
133 private static $legacy_mode = null;
135 private static function getItemFields()
137 $definition = DBStructure::definition('', false);
140 foreach (self::TABLES as $table) {
141 $postfields[$table] = array_keys($definition[$table]['fields']);
147 public static function isLegacyMode()
149 if (is_null(self::$legacy_mode)) {
150 self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
153 return self::$legacy_mode;
157 * Set the pinned state of an item
159 * @param integer $iid Item ID
160 * @param integer $uid User ID
161 * @param boolean $pinned Pinned state
163 public static function setPinned(int $iid, int $uid, bool $pinned)
165 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
169 * Get the pinned state
171 * @param integer $iid Item ID
172 * @param integer $uid User ID
174 * @return boolean pinned state
176 public static function getPinned(int $iid, int $uid)
178 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
179 if (!DBA::isResult($useritem)) {
182 return (bool)$useritem['pinned'];
186 * Select pinned rows from the item table for a given user
188 * @param integer $uid User ID
189 * @param array $selected Array of selected fields, empty for all
190 * @param array $condition Array of fields for condition
191 * @param array $params Array of several parameters
193 * @return boolean|object
196 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
198 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
199 if (!DBA::isResult($useritems)) {
204 while ($useritem = DBA::fetch($useritems)) {
205 $pinned[] = $useritem['iid'];
207 DBA::close($useritems);
209 if (empty($pinned)) {
213 $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
215 return self::selectThreadForUser($uid, $selected, $condition, $params);
219 * Fetch a single item row
221 * @param mixed $stmt statement object
222 * @return array current row
224 public static function fetch($stmt)
226 $row = DBA::fetch($stmt);
232 // ---------------------- Transform item structure data ----------------------
234 // We prefer the data from the user's contact over the public one
235 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
236 ($row['author-link'] == $row['contact-link'])) {
237 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
238 $row['author-avatar'] = $row['contact-avatar'];
240 if (isset($row['author-name']) && !empty($row['contact-name'])) {
241 $row['author-name'] = $row['contact-name'];
245 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
246 ($row['owner-link'] == $row['contact-link'])) {
247 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
248 $row['owner-avatar'] = $row['contact-avatar'];
250 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
251 $row['owner-name'] = $row['contact-name'];
255 // We can always comment on posts from these networks
256 if (array_key_exists('writable', $row) &&
257 in_array($row['internal-network'], Protocol::FEDERATED)) {
258 $row['writable'] = true;
261 // ---------------------- Transform item content data ----------------------
263 // Fetch data from the item-content table whenever there is content there
264 if (self::isLegacyMode()) {
265 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
266 foreach ($legacy_fields as $field) {
267 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
268 $row[$field] = $row['internal-item-' . $field];
270 unset($row['internal-item-' . $field]);
274 if (array_key_exists('verb', $row)) {
275 if (!is_null($row['internal-verb'])) {
276 $row['verb'] = $row['internal-verb'];
279 if (in_array($row['verb'], self::ACTIVITIES)) {
280 if (array_key_exists('title', $row)) {
283 if (array_key_exists('body', $row)) {
284 $row['body'] = $row['verb'];
286 if (array_key_exists('object', $row)) {
289 if (array_key_exists('object-type', $row)) {
290 $row['object-type'] = Activity\ObjectType::NOTE;
292 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
293 // Posts don't have a target - but having tags or files.
294 if (array_key_exists('target', $row)) {
300 if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
301 $row['vid'] = Verb::getID($row['verb']);
304 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
305 // Build the file string out of the term entries
306 if (array_key_exists('file', $row) && empty($row['file'])) {
307 $row['file'] = Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
311 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
312 if (array_key_exists('allow_cid', $row)) {
313 $row['allow_cid'] = '';
315 if (array_key_exists('allow_gid', $row)) {
316 $row['allow_gid'] = '';
318 if (array_key_exists('deny_cid', $row)) {
319 $row['deny_cid'] = '';
321 if (array_key_exists('deny_gid', $row)) {
322 $row['deny_gid'] = '';
326 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
327 $row['ignored'] = $row['internal-user-ignored'];
330 // Remove internal fields
331 unset($row['internal-network']);
332 unset($row['internal-uri-id']);
333 unset($row['internal-uid']);
334 unset($row['internal-psid']);
335 unset($row['internal-verb']);
336 unset($row['internal-user-ignored']);
337 unset($row['interaction']);
343 * Fills an array with data from an item query
345 * @param object $stmt statement object
346 * @param bool $do_close
347 * @return array Data array
349 public static function inArray($stmt, $do_close = true) {
350 if (is_bool($stmt)) {
355 while ($row = self::fetch($stmt)) {
365 * Check if item data exists
367 * @param array $condition array of fields for condition
369 * @return boolean Are there rows for that condition?
372 public static function exists($condition) {
373 $stmt = self::select(['id'], $condition, ['limit' => 1]);
375 if (is_bool($stmt)) {
378 $retval = (DBA::numRows($stmt) > 0);
387 * Retrieve a single record from the item table for a given user and returns it in an associative array
389 * @param integer $uid User ID
390 * @param array $selected
391 * @param array $condition
392 * @param array $params
397 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
399 $params['uid'] = $uid;
401 if (empty($selected)) {
402 $selected = Item::DISPLAY_FIELDLIST;
405 return self::selectFirst($selected, $condition, $params);
409 * Select rows from the item table for a given user
411 * @param integer $uid User ID
412 * @param array $selected Array of selected fields, empty for all
413 * @param array $condition Array of fields for condition
414 * @param array $params Array of several parameters
416 * @return boolean|object
419 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
421 $params['uid'] = $uid;
423 if (empty($selected)) {
424 $selected = Item::DISPLAY_FIELDLIST;
427 return self::select($selected, $condition, $params);
431 * Retrieve a single record from the item table and returns it in an associative array
433 * @param array $fields
434 * @param array $condition
435 * @param array $params
440 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
442 $params['limit'] = 1;
444 $result = self::select($fields, $condition, $params);
446 if (is_bool($result)) {
449 $row = self::fetch($result);
456 * Select rows from the item table and returns them as an array
458 * @param array $selected Array of selected fields, empty for all
459 * @param array $condition Array of fields for condition
460 * @param array $params Array of several parameters
465 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
467 $result = self::select($fields, $condition, $params);
469 if (is_bool($result)) {
474 while ($row = self::fetch($result)) {
483 * Select rows from the item table
485 * @param array $selected Array of selected fields, empty for all
486 * @param array $condition Array of fields for condition
487 * @param array $params Array of several parameters
489 * @return boolean|object
492 public static function select(array $selected = [], array $condition = [], $params = [])
497 if (isset($params['uid'])) {
498 $uid = $params['uid'];
502 $fields = self::fieldlist($usermode);
504 $select_fields = self::constructSelectFields($fields, $selected);
506 $condition_string = DBA::buildCondition($condition);
508 $condition_string = self::addTablesToFields($condition_string, $fields);
511 $condition_string = $condition_string . ' AND ' . self::condition(false);
514 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
516 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
518 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
520 return DBA::p($sql, $condition);
524 * Select rows from the starting post in the item table
526 * @param integer $uid User ID
527 * @param array $selected
528 * @param array $condition Array of fields for condition
529 * @param array $params Array of several parameters
531 * @return boolean|object
534 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
536 $params['uid'] = $uid;
538 if (empty($selected)) {
539 $selected = Item::DISPLAY_FIELDLIST;
542 return self::selectThread($selected, $condition, $params);
546 * Retrieve a single record from the starting post in the item table and returns it in an associative array
548 * @param integer $uid User ID
549 * @param array $selected
550 * @param array $condition
551 * @param array $params
556 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
558 $params['uid'] = $uid;
560 if (empty($selected)) {
561 $selected = Item::DISPLAY_FIELDLIST;
564 return self::selectFirstThread($selected, $condition, $params);
568 * Retrieve a single record from the starting post in the item table and returns it in an associative array
570 * @param array $fields
571 * @param array $condition
572 * @param array $params
577 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
579 $params['limit'] = 1;
580 $result = self::selectThread($fields, $condition, $params);
582 if (is_bool($result)) {
585 $row = self::fetch($result);
592 * Select rows from the starting post in the item table
594 * @param array $selected Array of selected fields, empty for all
595 * @param array $condition Array of fields for condition
596 * @param array $params Array of several parameters
598 * @return boolean|object
601 public static function selectThread(array $selected = [], array $condition = [], $params = [])
606 if (isset($params['uid'])) {
607 $uid = $params['uid'];
611 $fields = self::fieldlist($usermode);
613 $fields['thread'] = ['mention', 'ignored', 'iid'];
615 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
616 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
617 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
618 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
620 $select_fields = self::constructSelectFields($fields, $selected);
622 $condition_string = DBA::buildCondition($condition);
624 $condition_string = self::addTablesToFields($condition_string, $threadfields);
625 $condition_string = self::addTablesToFields($condition_string, $fields);
628 $condition_string = $condition_string . ' AND ' . self::condition(true);
631 $param_string = DBA::buildParameter($params);
632 $param_string = self::addTablesToFields($param_string, $threadfields);
633 $param_string = self::addTablesToFields($param_string, $fields);
635 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
637 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
639 return DBA::p($sql, $condition);
643 * Returns a list of fields that are associated with the item table
646 * @return array field list
648 private static function fieldlist($usermode)
652 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
653 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
654 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
655 'created', 'edited', 'commented', 'received', 'changed', 'psid',
656 'resource-id', 'event-id', 'attach', 'post-type', 'file',
657 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
658 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
659 'id' => 'item_id', 'network', 'icid',
660 'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
661 'network' => 'internal-network', 'psid' => 'internal-psid'];
664 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
667 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
669 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
671 $fields['verb'] = ['name' => 'internal-verb'];
673 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
675 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
676 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
678 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
679 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
681 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
682 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
683 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
685 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
687 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
688 'network' => 'parent-author-network'];
690 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
691 'start' => 'event-start','finish' => 'event-finish',
692 'summary' => 'event-summary','desc' => 'event-desc',
693 'location' => 'event-location', 'type' => 'event-type',
694 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
695 'ignore' => 'event-ignore', 'id' => 'event-id'];
697 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
703 * Returns SQL condition for the "select" functions
705 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
707 * @return string SQL condition
709 private static function condition($thread_mode)
712 $master_table = "`thread`";
714 $master_table = "`item`";
716 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
717 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
718 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
719 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
720 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
721 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
722 GRAVITY_PARENT, GRAVITY_PARENT);
726 * Returns all needed "JOIN" commands for the "select" functions
728 * @param integer $uid User ID
729 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
730 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
733 * @return string The SQL joins for the "select" functions
735 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
738 $master_table = "`thread`";
739 $master_table_key = "`thread`.`iid`";
740 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
742 $master_table = "`item`";
743 $master_table_key = "`item`.`id`";
748 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
749 AND NOT `contact`.`blocked`
750 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
751 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
752 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
753 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
754 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
755 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
756 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
757 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
759 if (strpos($sql_commands, "`contact`.") !== false) {
760 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
762 if (strpos($sql_commands, "`author`.") !== false) {
763 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
765 if (strpos($sql_commands, "`owner`.") !== false) {
766 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
770 if (strpos($sql_commands, "`group_member`.") !== false) {
771 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
774 if (strpos($sql_commands, "`user`.") !== false) {
775 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
778 if (strpos($sql_commands, "`event`.") !== false) {
779 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
782 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
783 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
786 if (strpos($sql_commands, "`item-content`.") !== false) {
787 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
790 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
791 $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
794 if (strpos($sql_commands, "`verb`.") !== false) {
795 $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
798 if (strpos($sql_commands, "`permissionset`.") !== false) {
799 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
802 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
803 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
805 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
806 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
814 * Add the field list for the "select" functions
816 * @param array $fields The field definition array
817 * @param array $selected The array with the selected fields from the "select" functions
819 * @return string The field list
821 private static function constructSelectFields(array $fields, array $selected)
823 if (!empty($selected)) {
824 $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
827 if (in_array('verb', $selected)) {
828 $selected = array_merge($selected, ['internal-verb']);
831 if (in_array('ignored', $selected)) {
832 $selected[] = 'internal-user-ignored';
835 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
838 foreach ($fields as $table => $table_fields) {
839 foreach ($table_fields as $field => $select) {
840 if (empty($selected) || in_array($select, $selected)) {
841 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
842 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
844 if (is_int($field)) {
845 $selection[] = "`" . $table . "`.`" . $select . "`";
847 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
852 return implode(", ", $selection);
856 * add table definition to fields in an SQL query
858 * @param string $query SQL query
859 * @param array $fields The field definition array
861 * @return string the changed SQL query
863 private static function addTablesToFields($query, $fields)
865 foreach ($fields as $table => $table_fields) {
866 foreach ($table_fields as $alias => $field) {
867 if (is_int($alias)) {
868 $replace_field = $field;
870 $replace_field = $alias;
873 $search = "/([^\.])`" . $field . "`/i";
874 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
875 $query = preg_replace($search, $replace, $query);
882 * Update existing item entries
884 * @param array $fields The fields that are to be changed
885 * @param array $condition The condition for finding the item entries
887 * In the future we may have to change permissions as well.
888 * Then we had to add the user id as third parameter.
890 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
892 * @return integer|boolean number of affected rows - or "false" if there was an error
893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 public static function update(array $fields, array $condition)
897 if (empty($condition) || empty($fields)) {
901 // To ensure the data integrity we do it in an transaction
904 // We cannot simply expand the condition to check for origin entries
905 // The condition needn't to be a simple array but could be a complex condition.
906 // And we have to execute this query before the update to ensure to fetch the same data.
907 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
909 $content_fields = [];
910 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
911 if (isset($fields[$field])) {
912 $content_fields[$field] = $fields[$field];
913 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
914 unset($fields[$field]);
916 $fields[$field] = null;
921 $delivery_data = Post\DeliveryData::extractFields($fields);
923 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
924 foreach ($clear_fields as $field) {
925 if (array_key_exists($field, $fields)) {
926 $fields[$field] = null;
930 if (array_key_exists('file', $fields)) {
931 $files = $fields['file'];
932 $fields['file'] = null;
937 if (!empty($content_fields['verb'])) {
938 $fields['vid'] = Verb::getID($content_fields['verb']);
941 if (!empty($fields)) {
942 $success = DBA::update('item', $fields, $condition);
951 // When there is no content for the "old" item table, this will count the fetched items
952 $rows = DBA::affectedRows();
956 while ($item = DBA::fetch($items)) {
957 if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
958 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
960 if (empty($item['icid'])) {
961 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
962 if (DBA::isResult($item_content)) {
963 $item_fields = ['icid' => $item_content['id']];
964 // Clear all fields in the item table that have a content in the item-content table
965 if (self::isLegacyMode()) {
966 foreach ($item_content as $field => $content) {
967 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
968 $item_fields[$field] = null;
972 DBA::update('item', $item_fields, ['id' => $item['id']]);
977 if (!is_null($files)) {
978 Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
979 if (!empty($item['file'])) {
980 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
984 Post\DeliveryData::update($item['uri-id'], $delivery_data);
986 self::updateThread($item['id']);
988 // We only need to notfiy others when it is an original entry from us.
989 // Only call the notifier when the item has some content relevant change.
990 if ($item['origin'] && in_array('edited', array_keys($fields))) {
991 $notify_items[] = $item['id'];
998 foreach ($notify_items as $notify_item) {
999 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1006 * Delete an item and notify others about it - if it was ours
1008 * @param array $condition The condition for finding the item entries
1009 * @param integer $priority Priority for the notification
1010 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1012 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
1014 $items = self::select(['id'], $condition);
1015 while ($item = self::fetch($items)) {
1016 self::markForDeletionById($item['id'], $priority);
1022 * Delete an item for an user and notify others about it - if it was ours
1024 * @param array $condition The condition for finding the item entries
1025 * @param integer $uid User who wants to delete this item
1026 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1028 public static function deleteForUser($condition, $uid)
1034 $items = self::select(['id', 'uid'], $condition);
1035 while ($item = self::fetch($items)) {
1036 // "Deleting" global items just means hiding them
1037 if ($item['uid'] == 0) {
1038 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1040 // Delete notifications
1041 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
1042 } elseif ($item['uid'] == $uid) {
1043 self::markForDeletionById($item['id'], PRIORITY_HIGH);
1045 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1052 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1054 * @param integer $item_id
1055 * @param integer $priority Priority for the notification
1057 * @return boolean success
1058 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1060 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1062 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1063 // locate item to be deleted
1064 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1065 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1066 'verb', 'object-type', 'object', 'target', 'contact-id',
1067 'icid', 'psid', 'gravity'];
1068 $item = self::selectFirst($fields, ['id' => $item_id]);
1069 if (!DBA::isResult($item)) {
1070 Logger::info('Item not found.', ['id' => $item_id]);
1074 if ($item['deleted']) {
1075 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1079 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1080 if (!DBA::isResult($parent)) {
1081 $parent = ['origin' => false];
1084 // clean up categories and tags so they don't end up as orphans
1087 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1090 foreach ($matches as $mtch) {
1091 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1097 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1100 foreach ($matches as $mtch) {
1101 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1106 * If item is a link to a photo resource, nuke all the associated photos
1107 * (visitors will not have photo resources)
1108 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1109 * generate a resource-id and therefore aren't intimately linked to the item.
1111 /// @TODO: this should first check if photo is used elsewhere
1112 if (strlen($item['resource-id'])) {
1113 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1116 // If item is a link to an event, delete the event.
1117 if (intval($item['event-id'])) {
1118 Event::delete($item['event-id']);
1121 // If item has attachments, drop them
1122 /// @TODO: this should first check if attachment is used elsewhere
1123 foreach (explode(",", $item['attach']) as $attach) {
1124 preg_match("|attach/(\d+)|", $attach, $matches);
1125 if (is_array($matches) && count($matches) > 1) {
1126 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1130 // Delete notifications
1131 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
1133 // Set the item to "deleted"
1134 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1135 DBA::update('item', $item_fields, ['id' => $item['id']]);
1137 Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
1138 self::deleteThread($item['id'], $item['parent-uri']);
1140 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1141 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1144 Post\DeliveryData::delete($item['uri-id']);
1146 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1147 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1149 // When the permission set will be used in photo and events as well,
1150 // this query here needs to be extended.
1151 // @todo Currently deactivated. We need the permission set in the deletion process.
1152 // This is a reminder to add the removal somewhere else.
1153 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1154 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1157 // If it's the parent of a comment thread, kill all the kids
1158 if ($item['gravity'] == GRAVITY_PARENT) {
1159 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1162 // Is it our comment and/or our thread?
1163 if ($item['origin'] || $parent['origin']) {
1164 // When we delete the original post we will delete all existing copies on the server as well
1165 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1167 // send the notification upstream/downstream
1168 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1169 } elseif ($item['uid'] != 0) {
1171 // When we delete just our local user copy of an item, we have to set a marker to hide it
1172 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1173 if (DBA::isResult($global_item)) {
1174 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1178 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1184 private static function guid($item, $notify)
1186 if (!empty($item['guid'])) {
1187 return Strings::escapeTags(trim($item['guid']));
1191 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1192 // We add the hash of our own host because our host is the original creator of the post.
1193 $prefix_host = DI::baseUrl()->getHostname();
1197 // We are only storing the post so we create a GUID from the original hostname.
1198 if (!empty($item['author-link'])) {
1199 $parsed = parse_url($item['author-link']);
1200 if (!empty($parsed['host'])) {
1201 $prefix_host = $parsed['host'];
1205 if (empty($prefix_host) && !empty($item['plink'])) {
1206 $parsed = parse_url($item['plink']);
1207 if (!empty($parsed['host'])) {
1208 $prefix_host = $parsed['host'];
1212 if (empty($prefix_host) && !empty($item['uri'])) {
1213 $parsed = parse_url($item['uri']);
1214 if (!empty($parsed['host'])) {
1215 $prefix_host = $parsed['host'];
1219 // Is it in the format data@host.tld? - Used for mail contacts
1220 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1221 $mailparts = explode('@', $item['author-link']);
1222 $prefix_host = array_pop($mailparts);
1226 if (!empty($item['plink'])) {
1227 $guid = self::guidFromUri($item['plink'], $prefix_host);
1228 } elseif (!empty($item['uri'])) {
1229 $guid = self::guidFromUri($item['uri'], $prefix_host);
1231 $guid = System::createUUID(hash('crc32', $prefix_host));
1237 private static function contactId($item)
1239 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1240 return $item['contact-id'];
1241 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1242 return $item['contact-id'];
1243 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1244 return $item['author-id'];
1245 } elseif (!empty($item['contact-id'])) {
1246 return $item['contact-id'];
1248 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1249 if (!empty($contact_id)) {
1253 return $item['author-id'];
1256 // This function will finally cover most of the preparation functionality in mod/item.php
1257 public static function prepare(&$item)
1260 * @TODO: Unused code triggering inspection errors
1262 $data = BBCode::getAttachmentData($item['body']);
1263 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1264 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1265 $posttype = Item::PT_PAGE;
1266 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1272 * Write an item array into a spool file to be inserted later.
1273 * This command is called whenever there are issues storing an item.
1275 * @param array $item The item fields that are to be inserted
1276 * @throws \Exception
1278 private static function spool($orig_item)
1280 // Now we store the data in the spool directory
1281 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1282 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1284 $spoolpath = get_spoolpath();
1285 if ($spoolpath != "") {
1286 $spool = $spoolpath . '/' . $file;
1288 file_put_contents($spool, json_encode($orig_item));
1289 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1294 * Check if the item array is a duplicate
1296 * @param array $item
1297 * @return boolean is it a duplicate?
1299 private static function isDuplicate(array $item)
1301 // Checking if there is already an item with the same guid
1302 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1303 if (self::exists($condition)) {
1304 Logger::notice('Found already existing item', [
1305 'guid' => $item['guid'],
1306 'uid' => $item['uid'],
1307 'network' => $item['network']
1312 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1313 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1314 if (self::exists($condition)) {
1315 Logger::notice('duplicated item with the same uri found.', $item);
1319 // On Friendica and Diaspora the GUID is unique
1320 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1321 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1322 if (self::exists($condition)) {
1323 Logger::notice('duplicated item with the same guid found.', $item);
1326 } elseif ($item['network'] == Protocol::OSTATUS) {
1327 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1328 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1329 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1330 if (self::exists($condition)) {
1331 Logger::notice('duplicated item with the same body found.', $item);
1337 * Check for already added items.
1338 * There is a timing issue here that sometimes creates double postings.
1339 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1341 if (($item['uid'] == 0) && self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1342 Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
1350 * Check if the item array is valid
1352 * @param array $item
1353 * @return boolean item is valid
1355 public static function isValid(array $item)
1357 // When there is no content then we don't post it
1358 if ($item['body'].$item['title'] == '') {
1359 Logger::notice('No body, no title.');
1363 // check for create date and expire time
1364 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1366 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
1367 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1368 $expire_interval = $user['expire'];
1371 if (($expire_interval > 0) && !empty($item['created'])) {
1372 $expire_date = time() - ($expire_interval * 86400);
1373 $created_date = strtotime($item['created']);
1374 if ($created_date < $expire_date) {
1375 Logger::notice('Item created before expiration interval.', [
1376 'created' => date('c', $created_date),
1377 'expired' => date('c', $expire_date),
1384 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
1385 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1389 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1390 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1394 if (!empty($item['uid']) && !empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $item['uid'])) {
1395 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1399 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
1400 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1404 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1405 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1409 if (!empty($item['uid']) && !empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $item['uid'])) {
1410 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1414 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1415 if (!empty($item['uid']) && !empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $item['uid'])) {
1416 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1420 if (!empty($item['uid']) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact\User::isIgnored($item['causer-id'], $item['uid'])) {
1421 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1425 if ($item['verb'] == Activity::FOLLOW) {
1426 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
1427 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1428 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
1432 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1433 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1434 if (self::exists($condition)) {
1435 // It happens that we receive multiple follow requests by the same author - we only store one.
1436 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
1445 * Return the id of the given item array if it has been stored before
1447 * @param array $item
1448 * @return integer item id
1450 private static function getDuplicateID(array $item)
1452 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1453 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1454 trim($item['uri']), $item['uid'],
1455 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1456 $existing = self::selectFirst(['id', 'network'], $condition);
1457 if (DBA::isResult($existing)) {
1458 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1459 if ($item['uid'] != 0) {
1460 Logger::notice('Item already existed for user', [
1461 'uri' => $item['uri'],
1462 'uid' => $item['uid'],
1463 'network' => $item['network'],
1464 'existing_id' => $existing["id"],
1465 'existing_network' => $existing["network"]
1469 return $existing["id"];
1476 * Fetch parent data for the given item array
1478 * @param array $item
1479 * @return array item array with parent data
1481 private static function getParentData(array $item)
1483 // find the parent and snarf the item id and ACLs
1484 // and anything else we need to inherit
1486 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1487 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1488 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1489 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1490 $params = ['order' => ['id' => false]];
1491 $parent = self::selectFirst($fields, $condition, $params);
1493 if (!DBA::isResult($parent)) {
1494 Logger::info('item parent was not found - ignoring item', ['parent-uri' => $item['parent-uri'], 'uid' => $item['uid']]);
1497 // is the new message multi-level threaded?
1498 // even though we don't support it now, preserve the info
1499 // and re-attach to the conversation parent.
1500 if ($parent['uri'] != $parent['parent-uri']) {
1501 $item['parent-uri'] = $parent['parent-uri'];
1503 $condition = ['uri' => $item['parent-uri'],
1504 'parent-uri' => $item['parent-uri'],
1505 'uid' => $item['uid']];
1506 $params = ['order' => ['id' => false]];
1507 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1509 if (DBA::isResult($toplevel_parent)) {
1510 $parent = $toplevel_parent;
1514 $item['parent'] = $parent['id'];
1515 $item["deleted"] = $parent['deleted'];
1516 $item["allow_cid"] = $parent['allow_cid'];
1517 $item['allow_gid'] = $parent['allow_gid'];
1518 $item['deny_cid'] = $parent['deny_cid'];
1519 $item['deny_gid'] = $parent['deny_gid'];
1520 $item['parent_origin'] = $parent['origin'];
1522 // Don't federate received participation messages
1523 if ($item['verb'] != Activity::FOLLOW) {
1524 $item['wall'] = $parent['wall'];
1526 $item['wall'] = false;
1530 * If the parent is private, force privacy for the entire conversation
1531 * This differs from the above settings as it subtly allows comments from
1532 * email correspondents to be private even if the overall thread is not.
1534 if ($parent['private']) {
1535 $item['private'] = $parent['private'];
1539 * Edge case. We host a public forum that was originally posted to privately.
1540 * The original author commented, but as this is a comment, the permissions
1541 * weren't fixed up so it will still show the comment as private unless we fix it here.
1543 if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
1544 $item['private'] = self::PUBLIC;
1547 // If its a post that originated here then tag the thread as "mention"
1548 if ($item['origin'] && $item['uid']) {
1549 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
1550 Logger::info('tagged thread as mention', ['parent' => $item['parent'], 'uid' => $item['uid']]);
1553 // Update the contact relations
1554 Contact\Relation::store($parent['author-id'], $item['author-id'], $item['created']);
1561 * Get the gravity for the given item array
1563 * @param array $item
1564 * @return integer gravity
1566 private static function getGravity(array $item)
1568 $activity = DI::activity();
1570 if (isset($item['gravity'])) {
1571 return intval($item['gravity']);
1572 } elseif ($item['parent-uri'] === $item['uri']) {
1573 return GRAVITY_PARENT;
1574 } elseif ($activity->match($item['verb'], Activity::POST)) {
1575 return GRAVITY_COMMENT;
1576 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1577 return GRAVITY_ACTIVITY;
1578 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
1579 return GRAVITY_ACTIVITY;
1581 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
1582 return GRAVITY_UNKNOWN; // Should not happen
1585 public static function insert($item, $notify = false, $dontcache = false)
1587 $structure = self::getItemFields();
1591 $priority = PRIORITY_HIGH;
1593 // If it is a posting where users should get notifications, then define it as wall posting
1596 $item['origin'] = 1;
1597 $item['network'] = Protocol::DFRN;
1598 $item['protocol'] = Conversation::PARCEL_DFRN;
1600 if (is_int($notify)) {
1601 $priority = $notify;
1604 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1607 $uid = intval($item['uid']);
1609 $item['guid'] = self::guid($item, $notify);
1610 $item['uri'] = substr(Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']))), 0, 255);
1613 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1615 // Store conversation data
1616 $item = Conversation::insert($item);
1618 if (!empty($item['thr-parent'])) {
1619 $item['parent-uri'] = $item['thr-parent'];
1623 * Do we already have this item?
1624 * We have to check several networks since Friendica posts could be repeated
1625 * via OStatus (maybe Diasporsa as well)
1627 $duplicate = self::getDuplicateID($item);
1632 // Additional duplicate checks
1633 /// @todo Check why the first duplication check returns the item number and the second a 0
1634 if (self::isDuplicate($item)) {
1638 $item['wall'] = intval($item['wall'] ?? 0);
1639 $item['extid'] = trim($item['extid'] ?? '');
1640 $item['author-name'] = trim($item['author-name'] ?? '');
1641 $item['author-link'] = trim($item['author-link'] ?? '');
1642 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1643 $item['owner-name'] = trim($item['owner-name'] ?? '');
1644 $item['owner-link'] = trim($item['owner-link'] ?? '');
1645 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1646 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1647 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1648 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1649 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1650 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1651 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
1652 $item['location'] = trim($item['location'] ?? '');
1653 $item['coord'] = trim($item['coord'] ?? '');
1654 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1655 $item['deleted'] = 0;
1656 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1657 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1658 $item['verb'] = trim($item['verb'] ?? '');
1659 $item['object-type'] = trim($item['object-type'] ?? '');
1660 $item['object'] = trim($item['object'] ?? '');
1661 $item['target-type'] = trim($item['target-type'] ?? '');
1662 $item['target'] = trim($item['target'] ?? '');
1663 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
1664 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1665 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1666 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1667 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1668 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1669 $item['body'] = trim($item['body'] ?? '');
1670 $item['attach'] = trim($item['attach'] ?? '');
1671 $item['app'] = trim($item['app'] ?? '');
1672 $item['origin'] = intval($item['origin'] ?? 0);
1673 $item['postopts'] = trim($item['postopts'] ?? '');
1674 $item['resource-id'] = trim($item['resource-id'] ?? '');
1675 $item['event-id'] = intval($item['event-id'] ?? 0);
1676 $item['inform'] = trim($item['inform'] ?? '');
1677 $item['file'] = trim($item['file'] ?? '');
1679 // Items cannot be stored before they happen ...
1680 if ($item['created'] > DateTimeFormat::utcNow()) {
1681 $item['created'] = DateTimeFormat::utcNow();
1684 // We haven't invented time travel by now.
1685 if ($item['edited'] > DateTimeFormat::utcNow()) {
1686 $item['edited'] = DateTimeFormat::utcNow();
1689 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1691 $item['language'] = self::getLanguage($item);
1693 $item['gravity'] = self::getGravity($item);
1695 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1696 'photo' => $item['author-avatar'], 'network' => $item['network']];
1697 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1699 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1700 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1701 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1703 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1704 if (!$item['origin'] && in_array($item['post-type'], [self::PT_ARTICLE, self::PT_COMMENT, self::PT_GLOBAL]) && Contact::isSharing($actor, $item['uid'])) {
1705 $item['post-type'] = self::PT_FOLLOWER;
1708 // Ensure that there is an avatar cache
1709 Contact::checkAvatarCache($item['author-id']);
1710 Contact::checkAvatarCache($item['owner-id']);
1712 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1713 $item["contact-id"] = self::contactId($item);
1715 if (!self::isValid($item)) {
1719 // We don't store the causer, we only have it here for the checks in the function above
1720 unset($item['causer-id']);
1721 unset($item['causer-link']);
1723 // We don't store these fields anymore in the item table
1724 unset($item['author-link']);
1725 unset($item['author-name']);
1726 unset($item['author-avatar']);
1727 unset($item['author-network']);
1729 unset($item['owner-link']);
1730 unset($item['owner-name']);
1731 unset($item['owner-avatar']);
1733 $item['thr-parent'] = $item['parent-uri'];
1735 if ($item['parent-uri'] != $item['uri']) {
1736 $item = self::getParentData($item);
1741 $parent_id = $item['parent'];
1742 unset($item['parent']);
1743 $parent_origin = $item['parent_origin'];
1744 unset($item['parent_origin']);
1747 $parent_origin = $item['origin'];
1750 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1751 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1753 // Is this item available in the global items (with uid=0)?
1754 if ($item["uid"] == 0) {
1755 $item["global"] = true;
1757 // Set the global flag on all items if this was a global item entry
1758 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1760 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1764 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
1765 $item["private"] = self::PRIVATE;
1769 $item['edit'] = false;
1770 $item['parent'] = $parent_id;
1771 Hook::callAll('post_local', $item);
1772 unset($item['edit']);
1773 unset($item['parent']);
1775 Hook::callAll('post_remote', $item);
1778 if (!empty($item['cancel'])) {
1779 Logger::log('post cancelled by addon.');
1783 if (empty($item['vid']) && !empty($item['verb'])) {
1784 $item['vid'] = Verb::getID($item['verb']);
1787 // Creates or assigns the permission set
1788 $item['psid'] = PermissionSet::getIdFromACL(
1796 unset($item['allow_cid']);
1797 unset($item['allow_gid']);
1798 unset($item['deny_cid']);
1799 unset($item['deny_gid']);
1801 // This array field is used to trigger some automatic reactions
1802 // It is mainly used in the "post_local" hook.
1803 unset($item['api_source']);
1805 if ($item['verb'] == Activity::ANNOUNCE) {
1806 self::setOwnerforResharedItem($item);
1809 // Check for hashtags in the body and repair or add hashtag links
1810 $item['body'] = self::setHashtags($item['body']);
1812 // Fill the cache field
1813 self::putInCache($item);
1815 if (stristr($item['verb'], Activity::POKE)) {
1816 $notify_type = Delivery::POKE;
1818 $notify_type = Delivery::POST;
1821 $like_no_comment = DI::config()->get('system', 'like_no_comment');
1825 if (!in_array($item['verb'], self::ACTIVITIES)) {
1826 $item['icid'] = self::insertContent($item);
1829 $body = $item['body'];
1831 // We just remove everything that is content
1832 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1833 unset($item[$field]);
1836 unset($item['activity']);
1838 // Filling item related side tables
1840 // Diaspora signature
1841 if (!empty($item['diaspora_signed_text'])) {
1842 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']], true);
1845 unset($item['diaspora_signed_text']);
1847 // Attached file links
1848 if (!empty($item['file'])) {
1849 Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1852 unset($item['file']);
1854 // Delivery relevant data
1855 $delivery_data = Post\DeliveryData::extractFields($item);
1856 unset($item['postopts']);
1857 unset($item['inform']);
1859 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1860 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1863 // Store tags from the body if this hadn't been handled previously in the protocol classes
1864 if (!Tag::existsForPost($item['uri-id'])) {
1865 Tag::storeFromBody($item['uri-id'], $body);
1868 // Remove all fields that aren't part of the item table
1869 foreach ($item as $field => $value) {
1870 if (!in_array($field, $structure['item'])) {
1871 unset($item[$field]);
1875 $ret = DBA::insert('item', $item);
1877 // When the item was successfully stored we fetch the ID of the item.
1878 if (DBA::isResult($ret)) {
1879 $current_post = DBA::lastInsertId();
1881 // This can happen - for example - if there are locking timeouts.
1884 // Store the data into a spool file so that we can try again later.
1885 self::spool($orig_item);
1889 if ($current_post == 0) {
1890 // This is one of these error messages that never should occur.
1891 Logger::log("couldn't find created item - we better quit now.");
1896 // How much entries have we created?
1897 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1898 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1901 // There are duplicates. We delete our just created entry.
1902 Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
1904 // Yes, we could do a rollback here - but we possibly are still having users with MyISAM.
1905 DBA::delete('item', ['id' => $current_post]);
1908 } elseif ($entries == 0) {
1909 // This really should never happen since we quit earlier if there were problems.
1910 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1915 Logger::log('created item '.$current_post);
1917 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1918 $parent_id = $current_post;
1922 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1924 $item['id'] = $current_post;
1925 $item['parent'] = $parent_id;
1927 // update the commented timestamp on the parent
1928 // Only update "commented" if it is really a comment
1929 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1930 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1932 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1935 if ($item['parent-uri'] === $item['uri']) {
1936 self::addThread($current_post);
1938 self::updateThread($parent_id);
1942 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1943 if (self::tagDeliver($item['uid'], $current_post)) {
1944 // Get the user information for the logging
1945 $user = User::getById($uid);
1947 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1952 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1953 if (DBA::isResult($posted_item)) {
1955 Hook::callAll('post_local_end', $posted_item);
1957 Hook::callAll('post_remote_end', $posted_item);
1960 Logger::log('new item not found in DB, id ' . $current_post);
1964 if ($item['parent-uri'] === $item['uri']) {
1965 self::addShadow($current_post);
1967 self::addShadowPost($current_post);
1970 self::updateContact($item);
1972 UserItem::setNotification($current_post);
1974 check_user_notification($current_post);
1976 // Distribute items to users who subscribed to their tags
1977 self::distributeByTags($item);
1979 $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
1982 $transmit_item = Item::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
1983 // Don't relay participation messages
1984 if (($transmit_item['verb'] == Activity::FOLLOW) &&
1985 (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1986 Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
1992 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1995 return $current_post;
1999 * Change the owner of a parent item if it had been shared by a forum
2001 * (public) forum posts in the new format consist of the regular post by the author
2002 * followed by an announce message sent from the forum account.
2003 * Changing the owner helps in grouping forum posts.
2005 * @param array $item
2008 private static function setOwnerforResharedItem(array $item)
2010 $parent = self::selectFirst(['id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
2011 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2012 if (!DBA::isResult($parent)) {
2013 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2017 $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
2018 if (!DBA::isResult($author)) {
2019 Logger::error('Author not found', ['id' => $item['author-id']]);
2023 $cid = Contact::getIdForURL($author['url'], $item['uid']);
2024 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
2025 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
2029 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
2030 if (!in_array($parent['post-type'], [self::PT_ARTICLE, self::PT_COMMENT]) || Contact::isSharing($parent['owner-id'], $item['uid'])) {
2031 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2034 self::update(['post-type' => self::PT_ANNOUNCEMENT], ['id' => $parent['id']]);
2035 Logger::info('Set announcement post-type', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2039 self::update(['owner-id' => $item['author-id'], 'contact-id' => $cid], ['id' => $parent['id']]);
2040 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]);
2044 * Distribute the given item to users who subscribed to their tags
2046 * @param array $item Processed item
2048 private static function distributeByTags(array $item)
2050 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
2054 $uids = Tag::getUIDListByURIId($item['uri-id']);
2055 foreach ($uids as $uid) {
2056 if (Contact::isSharing($item['author-id'], $uid)) {
2059 $fields = ['post-type' => self::PT_TAG];
2062 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
2063 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
2068 * Insert a new item content entry
2070 * @param array $item The item fields that are to be inserted
2071 * @throws \Exception
2073 private static function insertContent(array $item)
2075 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2077 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2078 if (isset($item[$field])) {
2079 $fields[$field] = $item[$field];
2083 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2084 if (DBA::isResult($item_content)) {
2085 $icid = $item_content['id'];
2086 Logger::info('Content found', ['icid' => $icid, 'uri' => $item['uri']]);
2090 DBA::insert('item-content', $fields, true);
2091 $icid = DBA::lastInsertId();
2093 Logger::info('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
2097 // Possibly there can be timing issues. Then the same content could be inserted multiple times.
2098 // Due to the indexes this doesn't happen, but "lastInsertId" will be empty in these situations.
2099 // So we have to fetch the id manually. This is no bug and there is no data loss.
2100 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2101 if (DBA::isResult($item_content)) {
2102 $icid = $item_content['id'];
2103 Logger::notice('Content inserted with empty lastInsertId', ['icid' => $icid, 'uri' => $item['uri']]);
2107 // This shouldn't happen.
2108 Logger::error("Content wasn't inserted", $item);
2113 * Update existing item content entries
2115 * @param array $item The item fields that are to be changed
2116 * @param array $condition The condition for finding the item content entries
2117 * @throws \Exception
2119 private static function updateContent($item, $condition)
2121 // We have to select only the fields from the "item-content" table
2123 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2124 if (isset($item[$field])) {
2125 $fields[$field] = $item[$field];
2129 if (empty($fields)) {
2133 DBA::update('item-content', $fields, $condition, true);
2134 Logger::info('Updated content', ['condition' => $condition]);
2138 * Distributes public items to the receivers
2140 * @param integer $itemid Item ID that should be added
2141 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2142 * @throws \Exception
2144 public static function distribute($itemid, $signed_text = '')
2146 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2147 $parent = self::selectFirst(['owner-id'], $condition);
2148 if (!DBA::isResult($parent)) {
2152 // Only distribute public items from native networks
2153 $condition = ['id' => $itemid, 'uid' => 0,
2154 'network' => array_merge(Protocol::FEDERATED ,['']),
2155 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2156 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2157 if (!DBA::isResult($item)) {
2161 $origin = $item['origin'];
2165 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2166 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2167 if (!DBA::isResult($owner)) {
2171 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2172 $contacts = DBA::select('contact', ['uid'], $condition);
2173 while ($contact = DBA::fetch($contacts)) {
2174 if ($contact['uid'] == 0) {
2178 $users[$contact['uid']] = $contact['uid'];
2180 DBA::close($contacts);
2182 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2183 $contacts = DBA::select('contact', ['uid'], $condition);
2184 while ($contact = DBA::fetch($contacts)) {
2185 if ($contact['uid'] == 0) {
2189 $users[$contact['uid']] = $contact['uid'];
2191 DBA::close($contacts);
2193 if (!empty($owner['alias'])) {
2194 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
2195 $contacts = DBA::select('contact', ['uid'], $condition);
2196 while ($contact = DBA::fetch($contacts)) {
2197 if ($contact['uid'] == 0) {
2201 $users[$contact['uid']] = $contact['uid'];
2203 DBA::close($contacts);
2208 if ($item['uri'] != $item['parent-uri']) {
2209 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2210 while ($parent = self::fetch($parents)) {
2211 $users[$parent['uid']] = $parent['uid'];
2212 if ($parent['origin'] && !$origin) {
2213 $origin_uid = $parent['uid'];
2218 foreach ($users as $uid) {
2219 if ($origin_uid == $uid) {
2220 $item['diaspora_signed_text'] = $signed_text;
2222 self::storeForUser($item, $uid);
2227 * Store a public item defined by their URI-ID for the given users
2229 * @param integer $uri_id URI-ID of the given item
2230 * @param integer $uid The user that will receive the item entry
2231 * @param array $fields Additional fields to be stored
2232 * @return integer stored item id
2234 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
2236 $item = self::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
2237 if (!DBA::isResult($item)) {
2241 if (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED)) {
2242 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']]);
2246 $item['post-type'] = self::PT_STORED;
2248 $item = array_merge($item, $fields);
2250 $stored = self::storeForUser($item, $uid);
2251 Logger::info('Public item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
2256 * Store a public item array for the given users
2258 * @param array $item The item entry that will be stored
2259 * @param integer $uid The user that will receive the item entry
2260 * @return integer stored item id
2261 * @throws \Exception
2263 private static function storeForUser(array $item, int $uid)
2265 if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
2266 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
2271 unset($item['parent']);
2272 unset($item['mention']);
2273 unset($item['starred']);
2274 unset($item['unseen']);
2275 unset($item['psid']);
2277 $item['uid'] = $uid;
2278 $item['origin'] = 0;
2281 if ($item['gravity'] == GRAVITY_PARENT) {
2282 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
2284 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
2287 if (!empty($contact['id'])) {
2288 $item['contact-id'] = $contact['id'];
2290 // Shouldn't happen at all
2291 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
2292 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2293 if (!DBA::isResult($self)) {
2294 // Shouldn't happen even less
2295 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
2298 $item['contact-id'] = $self['id'];
2301 /// @todo Handling of "event-id"
2304 if ($item['gravity'] == GRAVITY_PARENT) {
2305 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2306 if (DBA::isResult($contact)) {
2307 $notify = self::isRemoteSelf($contact, $item);
2311 $distributed = self::insert($item, $notify, true);
2313 if (!$distributed) {
2314 Logger::info("Distributed public item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
2316 Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
2318 return $distributed;
2322 * Add a shadow entry for a given item id that is a thread starter
2324 * We store every public item entry additionally with the user id "0".
2325 * This is used for the community page and for the search.
2326 * It is planned that in the future we will store public item entries only once.
2328 * @param integer $itemid Item ID that should be added
2329 * @throws \Exception
2331 public static function addShadow($itemid)
2333 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2334 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2335 $item = self::selectFirst($fields, $condition);
2337 if (!DBA::isResult($item)) {
2341 // is it already a copy?
2342 if (($itemid == 0) || ($item['uid'] == 0)) {
2346 // Is it a visible public post?
2347 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
2351 // is it an entry from a connector? Only add an entry for natively connected networks
2352 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2356 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2360 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2362 if (DBA::isResult($item)) {
2363 // Preparing public shadow (removing user specific data)
2366 unset($item['parent']);
2367 unset($item['wall']);
2368 unset($item['mention']);
2369 unset($item['origin']);
2370 unset($item['starred']);
2371 unset($item['postopts']);
2372 unset($item['inform']);
2373 if ($item['uri'] == $item['parent-uri']) {
2374 $item['contact-id'] = $item['owner-id'];
2376 $item['contact-id'] = $item['author-id'];
2379 $public_shadow = self::insert($item, false, true);
2381 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
2386 * Add a shadow entry for a given item id that is a comment
2388 * This function does the same like the function above - but for comments
2390 * @param integer $itemid Item ID that should be added
2391 * @throws \Exception
2393 public static function addShadowPost($itemid)
2395 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2396 if (!DBA::isResult($item)) {
2400 // Is it a toplevel post?
2401 if ($item['gravity'] == GRAVITY_PARENT) {
2402 self::addShadow($itemid);
2406 // Is this a shadow entry?
2407 if ($item['uid'] == 0) {
2411 // Is there a shadow parent?
2412 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2416 // Is there already a shadow entry?
2417 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2421 // Save "origin" and "parent" state
2422 $origin = $item['origin'];
2423 $parent = $item['parent'];
2425 // Preparing public shadow (removing user specific data)
2428 unset($item['parent']);
2429 unset($item['wall']);
2430 unset($item['mention']);
2431 unset($item['origin']);
2432 unset($item['starred']);
2433 unset($item['postopts']);
2434 unset($item['inform']);
2435 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2437 $public_shadow = self::insert($item, false, true);
2439 Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
2441 // If this was a comment to a Diaspora post we don't get our comment back.
2442 // This means that we have to distribute the comment by ourselves.
2443 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2444 self::distribute($public_shadow);
2449 * Adds a language specification in a "language" element of given $arr.
2450 * Expects "body" element to exist in $arr.
2452 * @param array $item
2453 * @return string detected language
2454 * @throws \Text_LanguageDetect_Exception
2456 private static function getLanguage(array $item)
2458 $naked_body = BBCode::toPlaintext($item['body'], false);
2460 $ld = new Text_LanguageDetect();
2461 $ld->setNameMode(2);
2462 $languages = $ld->detect($naked_body, 3);
2463 if (is_array($languages)) {
2464 return json_encode($languages);
2471 * Creates an unique guid out of a given uri
2473 * @param string $uri uri of an item entry
2474 * @param string $host hostname for the GUID prefix
2475 * @return string unique guid
2477 public static function guidFromUri($uri, $host)
2479 // Our regular guid routine is using this kind of prefix as well
2480 // We have to avoid that different routines could accidentally create the same value
2481 $parsed = parse_url($uri);
2483 // We use a hash of the hostname as prefix for the guid
2484 $guid_prefix = hash("crc32", $host);
2486 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2487 unset($parsed["scheme"]);
2489 // Glue it together to be able to make a hash from it
2490 $host_id = implode("/", $parsed);
2492 // We could use any hash algorithm since it isn't a security issue
2493 $host_hash = hash("ripemd128", $host_id);
2495 return $guid_prefix.$host_hash;
2499 * generate an unique URI
2501 * @param integer $uid User id
2502 * @param string $guid An existing GUID (Otherwise it will be generated)
2505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2507 public static function newURI($uid, $guid = "")
2510 $guid = System::createUUID();
2513 return DI::baseUrl()->get() . '/objects/' . $guid;
2517 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2519 * This can be used to filter for inactive contacts.
2520 * Only do this for public postings to avoid privacy problems, since poco data is public.
2521 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2523 * @param array $arr Contains the just posted item record
2524 * @throws \Exception
2526 private static function updateContact($arr)
2528 // Unarchive the author
2529 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2530 if (DBA::isResult($contact)) {
2531 Contact::unmarkForArchival($contact);
2534 // Unarchive the contact if it's not our own contact
2535 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2536 if (DBA::isResult($contact)) {
2537 Contact::unmarkForArchival($contact);
2540 /// @todo On private posts we could obfuscate the date
2541 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2543 // Is it a forum? Then we don't care about the rules from above
2544 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2545 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2551 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2552 // So we have to ensure to only update the last item when it had been our own post,
2553 // or it had been done by a "regular" contact.
2554 if (!empty($arr['wall'])) {
2555 $condition = ['id' => $arr['contact-id']];
2557 $condition = ['id' => $arr['contact-id'], 'self' => false];
2559 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2561 // Now do the same for the system wide contacts with uid=0
2562 if ($arr['private'] != self::PRIVATE) {
2563 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2564 ['id' => $arr['owner-id']]);
2566 if ($arr['owner-id'] != $arr['author-id']) {
2567 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2568 ['id' => $arr['author-id']]);
2573 public static function setHashtags($body)
2575 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
2576 $tags = BBCode::getTags($body);
2579 if (!count($tags)) {
2583 // This sorting is important when there are hashtags that are part of other hashtags
2584 // Otherwise there could be problems with hashtags like #test and #test2
2585 // Because of this we are sorting from the longest to the shortest tag.
2586 usort($tags, function ($a, $b) {
2587 return strlen($b) <=> strlen($a);
2590 $URLSearchString = "^\[\]";
2592 // All hashtags should point to the home server if "local_tags" is activated
2593 if (DI::config()->get('system', 'local_tags')) {
2594 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2595 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2598 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2599 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2601 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2604 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2606 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2609 $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2611 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2614 // Repair recursive urls
2615 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2618 foreach ($tags as $tag) {
2619 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2623 $basetag = str_replace('_', ' ', substr($tag, 1));
2624 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2626 $body = str_replace($tag, $newtag, $body);
2629 // Convert back the masked hashtags
2630 $body = str_replace("#", "#", $body);
2639 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2642 * @param int $item_id
2643 * @return boolean true if item was deleted, else false
2644 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2645 * @throws \ImagickException
2647 private static function tagDeliver($uid, $item_id)
2651 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2652 if (!DBA::isResult($user)) {
2656 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2657 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2659 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2660 if (!DBA::isResult($item)) {
2664 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2667 * Diaspora uses their own hardwired link URL in @-tags
2668 * instead of the one we supply with webfinger
2670 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2672 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2674 foreach ($matches as $mtch) {
2675 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2677 Logger::log('mention found: ' . $mtch[2]);
2683 if (($community_page || $prvgroup) &&
2684 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
2685 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2686 DBA::delete('item', ['id' => $item_id]);
2692 $arr = ['item' => $item, 'user' => $user];
2694 Hook::callAll('tagged', $arr);
2696 if (!$community_page && !$prvgroup) {
2701 * tgroup delivery - setup a second delivery chain
2702 * prevent delivery looping - only proceed
2703 * if the message originated elsewhere and is a top-level post
2705 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2709 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2710 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2711 if (!DBA::isResult($self)) {
2715 $owner_id = Contact::getIdForURL($self['url']);
2717 // also reset all the privacy bits to the forum default permissions
2719 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2721 $psid = PermissionSet::getIdFromACL(
2729 $forum_mode = ($prvgroup ? 2 : 1);
2731 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2732 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2733 self::update($fields, ['id' => $item_id]);
2735 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2737 Item::performActivity($item_id, 'announce', $uid);
2742 public static function isRemoteSelf($contact, &$datarray)
2744 if (!$contact['remote_self']) {
2748 // Prevent the forwarding of posts that are forwarded
2749 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2750 Logger::info('Already forwarded');
2754 // Prevent to forward already forwarded posts
2755 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2756 Logger::info('Already forwarded (second test)');
2760 // Only forward posts
2761 if ($datarray["verb"] != Activity::POST) {
2762 Logger::info('No post');
2766 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2767 Logger::info('Not public');
2771 $datarray2 = $datarray;
2772 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2773 if ($contact['remote_self'] == 2) {
2774 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2775 ['uid' => $contact['uid'], 'self' => true]);
2776 if (DBA::isResult($self)) {
2777 $datarray['contact-id'] = $self["id"];
2779 $datarray['owner-name'] = $self["name"];
2780 $datarray['owner-link'] = $self["url"];
2781 $datarray['owner-avatar'] = $self["thumb"];
2783 $datarray['author-name'] = $datarray['owner-name'];
2784 $datarray['author-link'] = $datarray['owner-link'];
2785 $datarray['author-avatar'] = $datarray['owner-avatar'];
2787 unset($datarray['edited']);
2789 unset($datarray['network']);
2790 unset($datarray['owner-id']);
2791 unset($datarray['author-id']);
2794 if ($contact['network'] != Protocol::FEED) {
2795 $datarray["guid"] = System::createUUID();
2796 unset($datarray["plink"]);
2797 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2798 $datarray["parent-uri"] = $datarray["uri"];
2799 $datarray["thr-parent"] = $datarray["uri"];
2800 $datarray["extid"] = Protocol::DFRN;
2801 $urlpart = parse_url($datarray2['author-link']);
2802 $datarray["app"] = $urlpart["host"];
2804 $datarray['private'] = self::PUBLIC;
2808 if ($contact['network'] != Protocol::FEED) {
2809 // Store the original post
2810 $result = self::insert($datarray2);
2811 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2813 $datarray["app"] = "Feed";
2817 // Trigger automatic reactions for addons
2818 $datarray['api_source'] = true;
2820 // We have to tell the hooks who we are - this really should be improved
2821 $_SESSION["authenticated"] = true;
2822 $_SESSION["uid"] = $contact['uid'];
2831 * @param array $item
2834 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2835 * @throws \ImagickException
2837 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2839 if (DI::config()->get('system', 'disable_embedded')) {
2843 Logger::info('check for photos');
2844 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2849 $img_start = strpos($orig_body, '[img');
2850 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2851 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2853 while (($img_st_close !== false) && ($img_len !== false)) {
2854 $img_st_close++; // make it point to AFTER the closing bracket
2855 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2857 Logger::info('found photo', ['image' => $image]);
2859 if (stristr($image, $site . '/photo/')) {
2860 // Only embed locally hosted photos
2862 $i = basename($image);
2863 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2864 $x = strpos($i, '-');
2867 $res = substr($i, $x + 1);
2868 $i = substr($i, 0, $x);
2869 $photo = Photo::getPhotoForUser($uid, $i, $res);
2870 if (DBA::isResult($photo)) {
2872 * Check to see if we should replace this photo link with an embedded image
2873 * 1. No need to do so if the photo is public
2874 * 2. If there's a contact-id provided, see if they're in the access list
2875 * for the photo. If so, embed it.
2876 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2877 * permissions, regardless of order but first check to see if they're an exact
2878 * match to save some processing overhead.
2880 if (self::hasPermissions($photo)) {
2882 $recips = self::enumeratePermissions($photo);
2883 if (in_array($cid, $recips)) {
2887 if (self::samePermissions($uid, $item, $photo)) {
2893 $photo_img = Photo::getImageForPhoto($photo);
2894 // If a custom width and height were specified, apply before embedding
2895 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2896 Logger::info('scaling photo');
2898 $width = intval($match[1]);
2899 $height = intval($match[2]);
2901 $photo_img->scaleDown(max($width, $height));
2904 $data = $photo_img->asString();
2905 $type = $photo_img->getType();
2907 Logger::info('replacing photo');
2908 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2909 Logger::debug('replaced', ['image' => $image]);
2915 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2916 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2917 if ($orig_body === false) {
2921 $img_start = strpos($orig_body, '[img');
2922 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2923 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2926 $new_body = $new_body . $orig_body;
2931 private static function hasPermissions($obj)
2933 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2934 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2937 private static function samePermissions($uid, $obj1, $obj2)
2939 // first part is easy. Check that these are exactly the same.
2940 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2941 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2942 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2943 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2947 // This is harder. Parse all the permissions and compare the resulting set.
2948 $recipients1 = self::enumeratePermissions($obj1);
2949 $recipients2 = self::enumeratePermissions($obj2);
2953 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2954 return ($recipients1 == $recipients2);
2958 * Returns an array of contact-ids that are allowed to see this object
2960 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2961 * @param bool $check_dead Prunes unavailable contacts from the result
2963 * @throws \Exception
2965 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2967 $aclFormater = DI::aclFormatter();
2969 $allow_people = $aclFormater->expand($obj['allow_cid']);
2970 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2971 $deny_people = $aclFormater->expand($obj['deny_cid']);
2972 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2973 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2974 $deny = array_unique(array_merge($deny_people, $deny_groups));
2975 $recipients = array_diff($recipients, $deny);
2979 public static function expire($uid, $days, $network = "", $force = false)
2981 if (!$uid || ($days < 1)) {
2985 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2986 $uid, GRAVITY_PARENT];
2989 * $expire_network_only = save your own wall posts
2990 * and just expire conversations started by others
2992 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2994 if ($expire_network_only) {
2995 $condition[0] .= " AND NOT `wall`";
2998 if ($network != "") {
2999 $condition[0] .= " AND `network` = ?";
3000 $condition[] = $network;
3003 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3004 $condition[] = $days;
3006 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3008 if (!DBA::isResult($items)) {
3012 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
3014 // Forcing expiring of items - but not notes and marked items
3016 $expire_items = true;
3019 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3020 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3021 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3025 while ($item = Item::fetch($items)) {
3026 // don't expire filed items
3028 if (strpos($item['file'], '[') !== false) {
3032 // Only expire posts, not photos and photo comments
3034 if (!$expire_photos && strlen($item['resource-id'])) {
3036 } elseif (!$expire_starred && intval($item['starred'])) {
3038 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3040 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3044 self::markForDeletionById($item['id'], PRIORITY_LOW);
3049 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3052 public static function firstPostDate($uid, $wall = false)
3054 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3055 $params = ['order' => ['received' => false]];
3056 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3057 if (DBA::isResult($thread)) {
3058 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3064 * add/remove activity to an item
3066 * Toggle activities as like,dislike,attend of an item
3068 * @param int $item_id
3069 * @param string $verb
3070 * Activity verb. One of
3071 * like, unlike, dislike, undislike, attendyes, unattendyes,
3072 * attendno, unattendno, attendmaybe, unattendmaybe,
3073 * announce, unannouce
3075 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3076 * @throws \ImagickException
3077 * @hook 'post_local_end'
3079 * 'post_id' => ID of posted item
3081 public static function performActivity(int $item_id, string $verb, int $uid)
3087 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
3089 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
3090 if (!DBA::isResult($item)) {
3091 Logger::log('like: unknown item ' . $item_id);
3095 $item_uri = $item['uri'];
3097 if (!in_array($item['uid'], [0, $uid])) {
3101 if (!Item::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
3102 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
3103 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
3104 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
3105 if (!DBA::isResult($item)) {
3106 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
3112 // Retrieves the local post owner
3113 $owner = User::getOwnerDataById($uid);
3114 if (empty($owner)) {
3115 Logger::info('Empty owner for user', ['uid' => $uid]);
3119 // Retrieve the current logged in user's public contact
3120 $author_id = Contact::getIdForURL($owner['url']);
3121 if (empty($author_id)) {
3122 Logger::info('Empty public contact');
3130 $activity = Activity::LIKE;
3134 $activity = Activity::DISLIKE;
3138 $activity = Activity::ATTEND;
3142 $activity = Activity::ATTENDNO;
3145 case 'unattendmaybe':
3146 $activity = Activity::ATTENDMAYBE;
3150 $activity = Activity::FOLLOW;
3154 $activity = Activity::ANNOUNCE;
3157 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3161 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3163 // Enable activity toggling instead of on/off
3164 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3166 // Look for an existing verb row
3167 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3168 if ($event_verb_flag) {
3169 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3171 // Translate to the index based activity index
3173 foreach ($verbs as $verb) {
3174 $vids[] = Verb::getID($verb);
3177 $vids = Verb::getID($activity);
3180 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3181 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3182 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3184 if (DBA::isResult($like_item)) {
3186 * Truth table for existing activities
3188 * | Inputs || Outputs |
3189 * |----------------------------||-------------------|
3190 * | Mode | Event | Same verb || Delete? | Return? |
3191 * |--------|-------|-----------||---------|---------|
3192 * | create | Yes | Yes || No | Yes |
3193 * | create | Yes | No || Yes | No |
3194 * | create | No | Yes || No | Yes |
3195 * | create | No | No || N/A†|
3196 * | delete | Yes | Yes || Yes | N/A‡ |
3197 * | delete | Yes | No || No | N/A‡ |
3198 * | delete | No | Yes || Yes | N/A‡ |
3199 * | delete | No | No || N/A†|
3200 * |--------|-------|-----------||---------|---------|
3201 * | A | B | C || A xor C | !B or C |
3203 * †Can't happen: It's impossible to find an existing non-event activity without
3204 * the same verb because we are only looking for this single verb.
3206 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
3208 if ($mode == 'create' xor $like_item['verb'] == $activity) {
3209 self::markForDeletionById($like_item['id']);
3212 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3217 // No need to go further if we aren't creating anything
3218 if ($mode == 'delete') {
3222 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3225 'guid' => System::createUUID(),
3226 'uri' => self::newURI($item['uid']),
3227 'uid' => $item['uid'],
3228 'contact-id' => $owner['id'],
3229 'wall' => $item['wall'],
3231 'network' => Protocol::DFRN,
3232 'gravity' => GRAVITY_ACTIVITY,
3233 'parent' => $item['id'],
3234 'parent-uri' => $item['uri'],
3235 'thr-parent' => $item['uri'],
3236 'owner-id' => $author_id,
3237 'author-id' => $author_id,
3238 'body' => $activity,
3239 'verb' => $activity,
3240 'object-type' => $objtype,
3241 'allow_cid' => $item['allow_cid'],
3242 'allow_gid' => $item['allow_gid'],
3243 'deny_cid' => $item['deny_cid'],
3244 'deny_gid' => $item['deny_gid'],
3249 $signed = Diaspora::createLikeSignature($uid, $new_item);
3250 if (!empty($signed)) {
3251 $new_item['diaspora_signed_text'] = json_encode($signed);
3254 $new_item_id = self::insert($new_item);
3256 // If the parent item isn't visible then set it to visible
3257 if (!$item['visible']) {
3258 self::update(['visible' => true], ['id' => $item['id']]);
3261 $new_item['id'] = $new_item_id;
3263 Hook::callAll('post_local_end', $new_item);
3268 private static function addThread($itemid, $onlyshadow = false)
3270 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3271 'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
3272 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3273 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3274 $item = self::selectFirst($fields, $condition);
3276 if (!DBA::isResult($item)) {
3280 $item['iid'] = $itemid;
3283 $result = DBA::insert('thread', $item);
3285 Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
3289 private static function updateThread($itemid, $setmention = false)
3291 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3292 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
3293 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3295 $item = self::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
3296 if (!DBA::isResult($item)) {
3301 $item["mention"] = 1;
3306 foreach ($item as $field => $data) {
3307 if (!in_array($field, ["guid"])) {
3308 $fields[$field] = $data;
3312 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3314 Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
3317 private static function deleteThread($itemid, $itemuri = "")
3319 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3320 if (!DBA::isResult($item)) {
3321 Logger::info('No thread found', ['id' => $itemid]);
3325 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3327 Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
3329 if ($itemuri != "") {
3330 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3331 if (!self::exists($condition)) {
3332 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3333 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3338 public static function getPermissionsSQLByUserId($owner_id)
3340 $local_user = local_user();
3341 $remote_user = Session::getRemoteContactID($owner_id);
3344 * Construct permissions
3346 * default permissions - anonymous user
3348 $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
3350 // Profile owner - everything is visible
3351 if ($local_user && ($local_user == $owner_id)) {
3353 } elseif ($remote_user) {
3355 * Authenticated visitor. Unless pre-verified,
3356 * check that the contact belongs to this $owner_id
3357 * and load the groups the visitor belongs to.
3358 * If pre-verified, the caller is expected to have already
3359 * done this and passed the groups into this function.
3361 $set = PermissionSet::get($owner_id, $remote_user);
3364 $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3369 $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
3376 * get translated item type
3381 public static function postType($item)
3383 if (!empty($item['event-id'])) {
3384 return DI::l10n()->t('event');
3385 } elseif (!empty($item['resource-id'])) {
3386 return DI::l10n()->t('photo');
3387 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
3388 return DI::l10n()->t('activity');
3389 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
3390 return DI::l10n()->t('comment');
3393 return DI::l10n()->t('post');
3397 * Sets the "rendered-html" field of the provided item
3399 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3401 * @param array $item
3402 * @param bool $update
3404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3405 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3407 public static function putInCache(&$item, $update = false)
3409 $body = $item["body"];
3411 $rendered_hash = $item['rendered-hash'] ?? '';
3412 $rendered_html = $item['rendered-html'] ?? '';
3414 if ($rendered_hash == ''
3415 || $rendered_html == ""
3416 || $rendered_hash != hash("md5", $item["body"])
3417 || DI::config()->get("system", "ignore_cache")
3419 self::addRedirToImageTags($item);
3421 $item["rendered-html"] = BBCode::convert($item["body"]);
3422 $item["rendered-hash"] = hash("md5", $item["body"]);
3424 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3425 Hook::callAll('put_item_in_cache', $hook_data);
3426 $item['rendered-html'] = $hook_data['rendered-html'];
3427 $item['rendered-hash'] = $hook_data['rendered-hash'];
3430 // Force an update if the generated values differ from the existing ones
3431 if ($rendered_hash != $item["rendered-hash"]) {
3435 // Only compare the HTML when we forcefully ignore the cache
3436 if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3440 if ($update && !empty($item["id"])) {
3443 'rendered-html' => $item["rendered-html"],
3444 'rendered-hash' => $item["rendered-hash"]
3446 ['id' => $item["id"]]
3451 $item["body"] = $body;
3455 * Find any non-embedded images in private items and add redir links to them
3457 * @param array &$item The field array of an item row
3459 private static function addRedirToImageTags(array &$item)
3464 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3466 foreach ($matches as $mtch) {
3467 if (strpos($mtch[1], '/redir') !== false) {
3471 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3472 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3473 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3480 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3481 * If attach is true, also add icons for item attachments.
3483 * @param array $item
3484 * @param boolean $attach
3485 * @param boolean $is_preview
3486 * @return string item body html
3487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3488 * @throws \ImagickException
3489 * @hook prepare_body_init item array before any work
3490 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3491 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3492 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3494 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3497 Hook::callAll('prepare_body_init', $item);
3499 // In order to provide theme developers more possibilities, event items
3500 // are treated differently.
3501 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3502 $ev = Event::getItemHTML($item);
3506 $tags = Tag::populateFromItem($item);
3508 $item['tags'] = $tags['tags'];
3509 $item['hashtags'] = $tags['hashtags'];
3510 $item['mentions'] = $tags['mentions'];
3512 // Compile eventual content filter reasons
3513 $filter_reasons = [];
3514 if (!$is_preview && public_contact() != $item['author-id']) {
3515 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3516 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3521 'filter_reasons' => $filter_reasons
3523 Hook::callAll('prepare_body_content_filter', $hook_data);
3524 $filter_reasons = $hook_data['filter_reasons'];
3528 // Update the cached values if there is no "zrl=..." on the links.
3529 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3531 // Or update it if the current viewer is the intented viewer.
3532 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3536 self::putInCache($item, $update);
3537 $s = $item["rendered-html"];
3542 'preview' => $is_preview,
3543 'filter_reasons' => $filter_reasons
3545 Hook::callAll('prepare_body', $hook_data);
3546 $s = $hook_data['html'];
3550 // Replace the blockquotes with quotes that are used in mails.
3551 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3552 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3559 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3560 foreach ($matches as $mtch) {
3563 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3565 if (strpos($mime, 'video') !== false) {
3568 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3571 $url_parts = explode('/', $the_url);
3572 $id = end($url_parts);
3573 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3576 'title' => DI::l10n()->t('View Video'),
3583 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3585 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3586 $filesubtype = str_replace('.', '-', $filesubtype);
3589 $filesubtype = 'unkn';
3592 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3593 $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
3595 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3596 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3600 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3604 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3605 $x = Map::byCoordinates(trim($item['coord']));
3607 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3611 // Replace friendica image url size with theme preference.
3612 if (!empty($a->theme_info['item_image_size'])) {
3613 $ps = $a->theme_info['item_image_size'];
3614 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3617 $s = HTML::applyContentFilter($s, $filter_reasons);
3619 $hook_data = ['item' => $item, 'html' => $s];
3620 Hook::callAll('prepare_body_final', $hook_data);
3622 return $hook_data['html'];
3626 * get private link for item
3628 * @param array $item
3629 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3630 * @throws \Exception
3632 public static function getPlink($item)
3636 'href' => "display/" . $item['guid'],
3637 'orig' => "display/" . $item['guid'],
3638 'title' => DI::l10n()->t('View on separate page'),
3639 'orig_title' => DI::l10n()->t('view on separate page'),
3642 if (!empty($item['plink'])) {
3643 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3644 $ret["title"] = DI::l10n()->t('link to source');
3646 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3648 'href' => $item['plink'],
3649 'orig' => $item['plink'],
3650 'title' => DI::l10n()->t('link to source'),
3660 * Is the given item array a post that is sent as starting post to a forum?
3662 * @param array $item
3663 * @param array $owner
3665 * @return boolean "true" when it is a forum post
3667 public static function isForumPost(array $item, array $owner = [])
3669 if (empty($owner)) {
3670 $owner = User::getOwnerDataById($item['uid']);
3671 if (empty($owner)) {
3676 if (($item['author-id'] == $item['owner-id']) ||
3677 ($owner['id'] == $item['contact-id']) ||
3678 ($item['uri'] != $item['parent-uri']) ||
3683 return Contact::isForum($item['contact-id']);
3687 * Search item id for given URI or plink
3689 * @param string $uri
3690 * @param integer $uid
3692 * @return integer item id
3694 public static function searchByLink($uri, $uid = 0)
3696 $ssl_uri = str_replace('http://', 'https://', $uri);
3697 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3699 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3700 if (DBA::isResult($item)) {
3704 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3705 if (!DBA::isResult($itemcontent)) {
3709 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3710 if (!DBA::isResult($itemuri)) {
3714 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3715 if (DBA::isResult($item)) {
3723 * Return the URI for a link to the post
3725 * @param string $uri URI or link to post
3727 * @return string URI
3729 public static function getURIByLink(string $uri)
3731 $ssl_uri = str_replace('http://', 'https://', $uri);
3732 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3734 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3735 if (DBA::isResult($item)) {
3736 return $item['uri'];
3739 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3740 if (!DBA::isResult($itemcontent)) {
3744 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3745 if (DBA::isResult($itemuri)) {
3746 return $itemuri['uri'];
3753 * Fetches item for given URI or plink
3755 * @param string $uri
3756 * @param integer $uid
3758 * @return integer item id
3760 public static function fetchByLink(string $uri, int $uid = 0)
3762 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3763 $item_id = self::searchByLink($uri, $uid);
3764 if (!empty($item_id)) {
3765 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3769 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3770 $item_id = self::searchByLink($fetched_uri, $uid);
3772 $item_id = Diaspora::fetchByURL($uri);
3775 if (!empty($item_id)) {
3776 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3780 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3785 * Return share data from an item array (if the item is shared item)
3786 * We are providing the complete Item array, because at some time in the future
3787 * we hopefully will define these values not in the body anymore but in some item fields.
3788 * This function is meant to replace all similar functions in the system.
3790 * @param array $item
3792 * @return array with share information
3794 public static function getShareArray($item)
3796 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3800 $attribute_string = $matches[2];
3801 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3802 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3803 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3804 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3811 * Fetch item information for shared items from the original items and adds it.
3813 * @param array $item
3815 * @return array item array with data from the original item
3817 public static function addShareDataFromOriginal(array $item)
3819 $shared = self::getShareArray($item);
3820 if (empty($shared)) {
3824 // Real reshares always have got a GUID.
3825 if (empty($shared['guid'])) {
3829 $uid = $item['uid'] ?? 0;
3831 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3832 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3833 if (!DBA::isResult($shared_item)) {
3834 if (empty($shared['link'])) {
3838 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3839 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3841 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3845 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
3846 if (!DBA::isResult($shared_item)) {
3849 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3851 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3854 if (!empty($shared_item['title'])) {
3855 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3856 unset($shared_item['title']);
3858 $body = $shared_item['body'];
3861 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3862 unset($shared_item['body']);
3864 return array_merge($item, $shared_item);