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_PERSONAL_NOTE = 128;
67 // Field list that is used to display the items
68 const DISPLAY_FIELDLIST = [
69 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
70 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
71 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
72 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
73 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
74 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
75 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
76 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
77 'writable', 'self', 'cid', 'alias', 'pinned',
78 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
79 'event-summary', 'event-desc', 'event-location', 'event-type',
80 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
81 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
84 // Field list that is used to deliver items via the protocols
85 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
86 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
87 'private', 'title', 'body', 'location', 'coord', 'app',
88 'attach', 'deleted', 'extid', 'post-type', 'gravity',
89 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
90 'author-id', 'author-link', 'owner-link', 'contact-uid',
91 'signed_text', 'signature', 'signer', 'network'];
93 // Field list for "item-content" table that is mixed with the item table
94 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
95 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
96 'object-type', 'object', 'target-type', 'target', 'plink'];
98 // Field list for "item-content" table that is not present in the "item" table
99 const CONTENT_FIELDLIST = ['language'];
101 // All fields in the item table
102 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
103 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
104 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
105 'created', 'edited', 'commented', 'received', 'changed', 'verb',
106 'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform',
107 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
108 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
109 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
110 'title', 'content-warning', 'body', 'location', 'coord', 'app',
111 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
112 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
113 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
115 // List of all verbs that don't need additional content data.
116 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
118 Activity::LIKE, Activity::DISLIKE,
119 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
127 const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction'];
129 private static $legacy_mode = null;
131 private static function getItemFields()
133 $definition = DBStructure::definition('', false);
136 foreach (self::TABLES as $table) {
137 $postfields[$table] = array_keys($definition[$table]['fields']);
143 public static function isLegacyMode()
145 if (is_null(self::$legacy_mode)) {
146 self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
149 return self::$legacy_mode;
153 * Set the pinned state of an item
155 * @param integer $iid Item ID
156 * @param integer $uid User ID
157 * @param boolean $pinned Pinned state
159 public static function setPinned(int $iid, int $uid, bool $pinned)
161 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
165 * Get the pinned state
167 * @param integer $iid Item ID
168 * @param integer $uid User ID
170 * @return boolean pinned state
172 public static function getPinned(int $iid, int $uid)
174 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
175 if (!DBA::isResult($useritem)) {
178 return (bool)$useritem['pinned'];
182 * Select pinned rows from the item table for a given user
184 * @param integer $uid User ID
185 * @param array $selected Array of selected fields, empty for all
186 * @param array $condition Array of fields for condition
187 * @param array $params Array of several parameters
189 * @return boolean|object
192 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
194 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
195 if (!DBA::isResult($useritems)) {
200 while ($useritem = DBA::fetch($useritems)) {
201 $pinned[] = $useritem['iid'];
203 DBA::close($useritems);
205 if (empty($pinned)) {
209 $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
211 return self::selectThreadForUser($uid, $selected, $condition, $params);
215 * Fetch a single item row
217 * @param mixed $stmt statement object
218 * @return array current row
220 public static function fetch($stmt)
222 $row = DBA::fetch($stmt);
228 // ---------------------- Transform item structure data ----------------------
230 // We prefer the data from the user's contact over the public one
231 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
232 ($row['author-link'] == $row['contact-link'])) {
233 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
234 $row['author-avatar'] = $row['contact-avatar'];
236 if (isset($row['author-name']) && !empty($row['contact-name'])) {
237 $row['author-name'] = $row['contact-name'];
241 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
242 ($row['owner-link'] == $row['contact-link'])) {
243 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
244 $row['owner-avatar'] = $row['contact-avatar'];
246 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
247 $row['owner-name'] = $row['contact-name'];
251 // We can always comment on posts from these networks
252 if (array_key_exists('writable', $row) &&
253 in_array($row['internal-network'], Protocol::FEDERATED)) {
254 $row['writable'] = true;
257 // ---------------------- Transform item content data ----------------------
259 // Fetch data from the item-content table whenever there is content there
260 if (self::isLegacyMode()) {
261 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
262 foreach ($legacy_fields as $field) {
263 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
264 $row[$field] = $row['internal-item-' . $field];
266 unset($row['internal-item-' . $field]);
270 if (array_key_exists('verb', $row)) {
271 if (!is_null($row['internal-verb'])) {
272 $row['verb'] = $row['internal-verb'];
275 if (in_array($row['verb'], self::ACTIVITIES)) {
276 if (array_key_exists('title', $row)) {
279 if (array_key_exists('body', $row)) {
280 $row['body'] = $row['verb'];
282 if (array_key_exists('object', $row)) {
285 if (array_key_exists('object-type', $row)) {
286 $row['object-type'] = Activity\ObjectType::NOTE;
288 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
289 // Posts don't have a target - but having tags or files.
290 if (array_key_exists('target', $row)) {
296 if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
297 $row['vid'] = Verb::getID($row['verb']);
300 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
301 // Build the file string out of the term entries
302 if (array_key_exists('file', $row) && empty($row['file'])) {
303 $row['file'] = Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
307 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
308 if (array_key_exists('allow_cid', $row)) {
309 $row['allow_cid'] = '';
311 if (array_key_exists('allow_gid', $row)) {
312 $row['allow_gid'] = '';
314 if (array_key_exists('deny_cid', $row)) {
315 $row['deny_cid'] = '';
317 if (array_key_exists('deny_gid', $row)) {
318 $row['deny_gid'] = '';
322 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
323 $row['ignored'] = $row['internal-user-ignored'];
326 // Remove internal fields
327 unset($row['internal-network']);
328 unset($row['internal-uri-id']);
329 unset($row['internal-uid']);
330 unset($row['internal-psid']);
331 unset($row['internal-verb']);
332 unset($row['internal-user-ignored']);
333 unset($row['interaction']);
339 * Fills an array with data from an item query
341 * @param object $stmt statement object
342 * @param bool $do_close
343 * @return array Data array
345 public static function inArray($stmt, $do_close = true) {
346 if (is_bool($stmt)) {
351 while ($row = self::fetch($stmt)) {
361 * Check if item data exists
363 * @param array $condition array of fields for condition
365 * @return boolean Are there rows for that condition?
368 public static function exists($condition) {
369 $stmt = self::select(['id'], $condition, ['limit' => 1]);
371 if (is_bool($stmt)) {
374 $retval = (DBA::numRows($stmt) > 0);
383 * Retrieve a single record from the item table for a given user and returns it in an associative array
385 * @param integer $uid User ID
386 * @param array $selected
387 * @param array $condition
388 * @param array $params
393 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
395 $params['uid'] = $uid;
397 if (empty($selected)) {
398 $selected = Item::DISPLAY_FIELDLIST;
401 return self::selectFirst($selected, $condition, $params);
405 * Select rows from the item table for a given user
407 * @param integer $uid User ID
408 * @param array $selected Array of selected fields, empty for all
409 * @param array $condition Array of fields for condition
410 * @param array $params Array of several parameters
412 * @return boolean|object
415 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
417 $params['uid'] = $uid;
419 if (empty($selected)) {
420 $selected = Item::DISPLAY_FIELDLIST;
423 return self::select($selected, $condition, $params);
427 * Retrieve a single record from the item table and returns it in an associative array
429 * @param array $fields
430 * @param array $condition
431 * @param array $params
436 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
438 $params['limit'] = 1;
440 $result = self::select($fields, $condition, $params);
442 if (is_bool($result)) {
445 $row = self::fetch($result);
452 * Select rows from the item table and returns them as an array
454 * @param array $selected Array of selected fields, empty for all
455 * @param array $condition Array of fields for condition
456 * @param array $params Array of several parameters
461 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
463 $result = self::select($fields, $condition, $params);
465 if (is_bool($result)) {
470 while ($row = self::fetch($result)) {
479 * Select rows from the item table
481 * @param array $selected Array of selected fields, empty for all
482 * @param array $condition Array of fields for condition
483 * @param array $params Array of several parameters
485 * @return boolean|object
488 public static function select(array $selected = [], array $condition = [], $params = [])
493 if (isset($params['uid'])) {
494 $uid = $params['uid'];
498 $fields = self::fieldlist($usermode);
500 $select_fields = self::constructSelectFields($fields, $selected);
502 $condition_string = DBA::buildCondition($condition);
504 $condition_string = self::addTablesToFields($condition_string, $fields);
507 $condition_string = $condition_string . ' AND ' . self::condition(false);
510 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
512 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
514 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
516 return DBA::p($sql, $condition);
520 * Select rows from the starting post in the item table
522 * @param integer $uid User ID
523 * @param array $selected
524 * @param array $condition Array of fields for condition
525 * @param array $params Array of several parameters
527 * @return boolean|object
530 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
532 $params['uid'] = $uid;
534 if (empty($selected)) {
535 $selected = Item::DISPLAY_FIELDLIST;
538 return self::selectThread($selected, $condition, $params);
542 * Retrieve a single record from the starting post in the item table and returns it in an associative array
544 * @param integer $uid User ID
545 * @param array $selected
546 * @param array $condition
547 * @param array $params
552 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
554 $params['uid'] = $uid;
556 if (empty($selected)) {
557 $selected = Item::DISPLAY_FIELDLIST;
560 return self::selectFirstThread($selected, $condition, $params);
564 * Retrieve a single record from the starting post in the item table and returns it in an associative array
566 * @param array $fields
567 * @param array $condition
568 * @param array $params
573 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
575 $params['limit'] = 1;
576 $result = self::selectThread($fields, $condition, $params);
578 if (is_bool($result)) {
581 $row = self::fetch($result);
588 * Select rows from the starting post in the item table
590 * @param array $selected Array of selected fields, empty for all
591 * @param array $condition Array of fields for condition
592 * @param array $params Array of several parameters
594 * @return boolean|object
597 public static function selectThread(array $selected = [], array $condition = [], $params = [])
602 if (isset($params['uid'])) {
603 $uid = $params['uid'];
607 $fields = self::fieldlist($usermode);
609 $fields['thread'] = ['mention', 'ignored', 'iid'];
611 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
612 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
613 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
614 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
616 $select_fields = self::constructSelectFields($fields, $selected);
618 $condition_string = DBA::buildCondition($condition);
620 $condition_string = self::addTablesToFields($condition_string, $threadfields);
621 $condition_string = self::addTablesToFields($condition_string, $fields);
624 $condition_string = $condition_string . ' AND ' . self::condition(true);
627 $param_string = DBA::buildParameter($params);
628 $param_string = self::addTablesToFields($param_string, $threadfields);
629 $param_string = self::addTablesToFields($param_string, $fields);
631 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
633 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
635 return DBA::p($sql, $condition);
639 * Returns a list of fields that are associated with the item table
642 * @return array field list
644 private static function fieldlist($usermode)
648 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
649 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
650 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
651 'created', 'edited', 'commented', 'received', 'changed', 'psid',
652 'resource-id', 'event-id', 'attach', 'post-type', 'file',
653 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
654 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
655 'id' => 'item_id', 'network', 'icid',
656 'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
657 'network' => 'internal-network', 'psid' => 'internal-psid'];
660 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
663 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
665 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
667 $fields['verb'] = ['name' => 'internal-verb'];
669 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
671 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
672 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
674 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
675 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
677 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
678 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
679 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
681 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
683 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
684 'network' => 'parent-author-network'];
686 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
687 'start' => 'event-start','finish' => 'event-finish',
688 'summary' => 'event-summary','desc' => 'event-desc',
689 'location' => 'event-location', 'type' => 'event-type',
690 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
691 'ignore' => 'event-ignore', 'id' => 'event-id'];
693 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
699 * Returns SQL condition for the "select" functions
701 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
703 * @return string SQL condition
705 private static function condition($thread_mode)
708 $master_table = "`thread`";
710 $master_table = "`item`";
712 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
713 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
714 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
715 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
716 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
717 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
718 GRAVITY_PARENT, GRAVITY_PARENT);
722 * Returns all needed "JOIN" commands for the "select" functions
724 * @param integer $uid User ID
725 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
726 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
729 * @return string The SQL joins for the "select" functions
731 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
734 $master_table = "`thread`";
735 $master_table_key = "`thread`.`iid`";
736 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
738 $master_table = "`item`";
739 $master_table_key = "`item`.`id`";
744 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
745 AND NOT `contact`.`blocked`
746 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
747 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
748 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
749 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
750 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
751 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
752 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
753 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
755 if (strpos($sql_commands, "`contact`.") !== false) {
756 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
758 if (strpos($sql_commands, "`author`.") !== false) {
759 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
761 if (strpos($sql_commands, "`owner`.") !== false) {
762 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
766 if (strpos($sql_commands, "`group_member`.") !== false) {
767 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
770 if (strpos($sql_commands, "`user`.") !== false) {
771 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
774 if (strpos($sql_commands, "`event`.") !== false) {
775 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
778 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
779 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
782 if (strpos($sql_commands, "`item-content`.") !== false) {
783 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
786 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
787 $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
790 if (strpos($sql_commands, "`verb`.") !== false) {
791 $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
794 if (strpos($sql_commands, "`permissionset`.") !== false) {
795 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
798 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
799 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
801 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
802 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
810 * Add the field list for the "select" functions
812 * @param array $fields The field definition array
813 * @param array $selected The array with the selected fields from the "select" functions
815 * @return string The field list
817 private static function constructSelectFields(array $fields, array $selected)
819 if (!empty($selected)) {
820 $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
823 if (in_array('verb', $selected)) {
824 $selected = array_merge($selected, ['internal-verb']);
827 if (in_array('ignored', $selected)) {
828 $selected[] = 'internal-user-ignored';
831 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
834 foreach ($fields as $table => $table_fields) {
835 foreach ($table_fields as $field => $select) {
836 if (empty($selected) || in_array($select, $selected)) {
837 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
838 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
840 if (is_int($field)) {
841 $selection[] = "`" . $table . "`.`" . $select . "`";
843 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
848 return implode(", ", $selection);
852 * add table definition to fields in an SQL query
854 * @param string $query SQL query
855 * @param array $fields The field definition array
857 * @return string the changed SQL query
859 private static function addTablesToFields($query, $fields)
861 foreach ($fields as $table => $table_fields) {
862 foreach ($table_fields as $alias => $field) {
863 if (is_int($alias)) {
864 $replace_field = $field;
866 $replace_field = $alias;
869 $search = "/([^\.])`" . $field . "`/i";
870 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
871 $query = preg_replace($search, $replace, $query);
878 * Update existing item entries
880 * @param array $fields The fields that are to be changed
881 * @param array $condition The condition for finding the item entries
883 * In the future we may have to change permissions as well.
884 * Then we had to add the user id as third parameter.
886 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
888 * @return integer|boolean number of affected rows - or "false" if there was an error
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891 public static function update(array $fields, array $condition)
893 if (empty($condition) || empty($fields)) {
897 // To ensure the data integrity we do it in an transaction
900 // We cannot simply expand the condition to check for origin entries
901 // The condition needn't to be a simple array but could be a complex condition.
902 // And we have to execute this query before the update to ensure to fetch the same data.
903 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
905 $content_fields = [];
906 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
907 if (isset($fields[$field])) {
908 $content_fields[$field] = $fields[$field];
909 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
910 unset($fields[$field]);
912 $fields[$field] = null;
917 $delivery_data = Post\DeliveryData::extractFields($fields);
919 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
920 foreach ($clear_fields as $field) {
921 if (array_key_exists($field, $fields)) {
922 $fields[$field] = null;
926 if (array_key_exists('file', $fields)) {
927 $files = $fields['file'];
928 $fields['file'] = null;
933 if (!empty($content_fields['verb'])) {
934 $fields['vid'] = Verb::getID($content_fields['verb']);
937 if (!empty($fields)) {
938 $success = DBA::update('item', $fields, $condition);
947 // When there is no content for the "old" item table, this will count the fetched items
948 $rows = DBA::affectedRows();
952 while ($item = DBA::fetch($items)) {
953 if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
954 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
956 if (empty($item['icid'])) {
957 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
958 if (DBA::isResult($item_content)) {
959 $item_fields = ['icid' => $item_content['id']];
960 // Clear all fields in the item table that have a content in the item-content table
961 if (self::isLegacyMode()) {
962 foreach ($item_content as $field => $content) {
963 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($content)) {
964 $item_fields[$field] = null;
968 DBA::update('item', $item_fields, ['id' => $item['id']]);
973 if (!is_null($files)) {
974 Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
975 if (!empty($item['file'])) {
976 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
980 Post\DeliveryData::update($item['uri-id'], $delivery_data);
982 self::updateThread($item['id']);
984 // We only need to notfiy others when it is an original entry from us.
985 // Only call the notifier when the item has some content relevant change.
986 if ($item['origin'] && in_array('edited', array_keys($fields))) {
987 $notify_items[] = $item['id'];
994 foreach ($notify_items as $notify_item) {
995 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1002 * Delete an item and notify others about it - if it was ours
1004 * @param array $condition The condition for finding the item entries
1005 * @param integer $priority Priority for the notification
1006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1008 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
1010 $items = self::select(['id'], $condition);
1011 while ($item = self::fetch($items)) {
1012 self::markForDeletionById($item['id'], $priority);
1018 * Delete an item for an user and notify others about it - if it was ours
1020 * @param array $condition The condition for finding the item entries
1021 * @param integer $uid User who wants to delete this item
1022 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1024 public static function deleteForUser($condition, $uid)
1030 $items = self::select(['id', 'uid'], $condition);
1031 while ($item = self::fetch($items)) {
1032 // "Deleting" global items just means hiding them
1033 if ($item['uid'] == 0) {
1034 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1036 // Delete notifications
1037 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
1038 } elseif ($item['uid'] == $uid) {
1039 self::markForDeletionById($item['id'], PRIORITY_HIGH);
1041 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1048 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1050 * @param integer $item_id
1051 * @param integer $priority Priority for the notification
1053 * @return boolean success
1054 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1056 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1058 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1059 // locate item to be deleted
1060 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1061 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1062 'verb', 'object-type', 'object', 'target', 'contact-id',
1063 'icid', 'psid', 'gravity'];
1064 $item = self::selectFirst($fields, ['id' => $item_id]);
1065 if (!DBA::isResult($item)) {
1066 Logger::info('Item not found.', ['id' => $item_id]);
1070 if ($item['deleted']) {
1071 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1075 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1076 if (!DBA::isResult($parent)) {
1077 $parent = ['origin' => false];
1080 // clean up categories and tags so they don't end up as orphans
1083 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1086 foreach ($matches as $mtch) {
1087 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1093 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1096 foreach ($matches as $mtch) {
1097 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1102 * If item is a link to a photo resource, nuke all the associated photos
1103 * (visitors will not have photo resources)
1104 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1105 * generate a resource-id and therefore aren't intimately linked to the item.
1107 /// @TODO: this should first check if photo is used elsewhere
1108 if (strlen($item['resource-id'])) {
1109 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1112 // If item is a link to an event, delete the event.
1113 if (intval($item['event-id'])) {
1114 Event::delete($item['event-id']);
1117 // If item has attachments, drop them
1118 /// @TODO: this should first check if attachment is used elsewhere
1119 foreach (explode(",", $item['attach']) as $attach) {
1120 preg_match("|attach/(\d+)|", $attach, $matches);
1121 if (is_array($matches) && count($matches) > 1) {
1122 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1126 // Delete notifications
1127 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
1129 // Set the item to "deleted"
1130 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1131 DBA::update('item', $item_fields, ['id' => $item['id']]);
1133 Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
1134 self::deleteThread($item['id'], $item['parent-uri']);
1136 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1137 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1140 Post\DeliveryData::delete($item['uri-id']);
1142 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1143 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1145 // When the permission set will be used in photo and events as well,
1146 // this query here needs to be extended.
1147 // @todo Currently deactivated. We need the permission set in the deletion process.
1148 // This is a reminder to add the removal somewhere else.
1149 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1150 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1153 // If it's the parent of a comment thread, kill all the kids
1154 if ($item['gravity'] == GRAVITY_PARENT) {
1155 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1158 // Is it our comment and/or our thread?
1159 if ($item['origin'] || $parent['origin']) {
1160 // When we delete the original post we will delete all existing copies on the server as well
1161 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1163 // send the notification upstream/downstream
1164 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1165 } elseif ($item['uid'] != 0) {
1167 // When we delete just our local user copy of an item, we have to set a marker to hide it
1168 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1169 if (DBA::isResult($global_item)) {
1170 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1174 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1180 private static function guid($item, $notify)
1182 if (!empty($item['guid'])) {
1183 return Strings::escapeTags(trim($item['guid']));
1187 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1188 // We add the hash of our own host because our host is the original creator of the post.
1189 $prefix_host = DI::baseUrl()->getHostname();
1193 // We are only storing the post so we create a GUID from the original hostname.
1194 if (!empty($item['author-link'])) {
1195 $parsed = parse_url($item['author-link']);
1196 if (!empty($parsed['host'])) {
1197 $prefix_host = $parsed['host'];
1201 if (empty($prefix_host) && !empty($item['plink'])) {
1202 $parsed = parse_url($item['plink']);
1203 if (!empty($parsed['host'])) {
1204 $prefix_host = $parsed['host'];
1208 if (empty($prefix_host) && !empty($item['uri'])) {
1209 $parsed = parse_url($item['uri']);
1210 if (!empty($parsed['host'])) {
1211 $prefix_host = $parsed['host'];
1215 // Is it in the format data@host.tld? - Used for mail contacts
1216 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1217 $mailparts = explode('@', $item['author-link']);
1218 $prefix_host = array_pop($mailparts);
1222 if (!empty($item['plink'])) {
1223 $guid = self::guidFromUri($item['plink'], $prefix_host);
1224 } elseif (!empty($item['uri'])) {
1225 $guid = self::guidFromUri($item['uri'], $prefix_host);
1227 $guid = System::createUUID(hash('crc32', $prefix_host));
1233 private static function contactId($item)
1235 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1236 return $item['contact-id'];
1237 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1238 return $item['contact-id'];
1239 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1240 return $item['author-id'];
1241 } elseif (!empty($item['contact-id'])) {
1242 return $item['contact-id'];
1244 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1245 if (!empty($contact_id)) {
1249 return $item['author-id'];
1252 // This function will finally cover most of the preparation functionality in mod/item.php
1253 public static function prepare(&$item)
1256 * @TODO: Unused code triggering inspection errors
1258 $data = BBCode::getAttachmentData($item['body']);
1259 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1260 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1261 $posttype = Item::PT_PAGE;
1262 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1268 * Write an item array into a spool file to be inserted later.
1269 * This command is called whenever there are issues storing an item.
1271 * @param array $item The item fields that are to be inserted
1272 * @throws \Exception
1274 private static function spool($orig_item)
1276 // Now we store the data in the spool directory
1277 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1278 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1280 $spoolpath = get_spoolpath();
1281 if ($spoolpath != "") {
1282 $spool = $spoolpath . '/' . $file;
1284 file_put_contents($spool, json_encode($orig_item));
1285 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1290 * Check if the item array is a duplicate
1292 * @param array $item
1293 * @return boolean is it a duplicate?
1295 private static function isDuplicate(array $item)
1297 // Checking if there is already an item with the same guid
1298 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1299 if (self::exists($condition)) {
1300 Logger::notice('Found already existing item', [
1301 'guid' => $item['guid'],
1302 'uid' => $item['uid'],
1303 'network' => $item['network']
1308 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1309 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1310 if (self::exists($condition)) {
1311 Logger::notice('duplicated item with the same uri found.', $item);
1315 // On Friendica and Diaspora the GUID is unique
1316 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1317 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1318 if (self::exists($condition)) {
1319 Logger::notice('duplicated item with the same guid found.', $item);
1322 } elseif ($item['network'] == Protocol::OSTATUS) {
1323 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1324 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1325 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1326 if (self::exists($condition)) {
1327 Logger::notice('duplicated item with the same body found.', $item);
1333 * Check for already added items.
1334 * There is a timing issue here that sometimes creates double postings.
1335 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1337 if (($item['uid'] == 0) && self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1338 Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
1346 * Check if the item array is valid
1348 * @param array $item
1349 * @return boolean item is valid
1351 public static function isValid(array $item)
1353 // When there is no content then we don't post it
1354 if ($item['body'].$item['title'] == '') {
1355 Logger::notice('No body, no title.');
1359 // check for create date and expire time
1360 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1362 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
1363 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1364 $expire_interval = $user['expire'];
1367 if (($expire_interval > 0) && !empty($item['created'])) {
1368 $expire_date = time() - ($expire_interval * 86400);
1369 $created_date = strtotime($item['created']);
1370 if ($created_date < $expire_date) {
1371 Logger::notice('Item created before expiration interval.', [
1372 'created' => date('c', $created_date),
1373 'expired' => date('c', $expire_date),
1380 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
1381 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1385 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1386 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1390 if (!empty($item['uid']) && !empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $item['uid'])) {
1391 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1395 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
1396 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1400 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1401 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1405 if (!empty($item['uid']) && !empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $item['uid'])) {
1406 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1410 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1411 if (!empty($item['uid']) && !empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $item['uid'])) {
1412 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1416 if (!empty($item['uid']) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact\User::isIgnored($item['causer-id'], $item['uid'])) {
1417 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $item['uid'], 'item-uri' => $item['uri']]);
1421 if ($item['verb'] == Activity::FOLLOW) {
1422 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
1423 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1424 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
1428 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1429 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1430 if (self::exists($condition)) {
1431 // It happens that we receive multiple follow requests by the same author - we only store one.
1432 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
1441 * Return the id of the given item array if it has been stored before
1443 * @param array $item
1444 * @return integer item id
1446 private static function getDuplicateID(array $item)
1448 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1449 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1450 trim($item['uri']), $item['uid'],
1451 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1452 $existing = self::selectFirst(['id', 'network'], $condition);
1453 if (DBA::isResult($existing)) {
1454 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1455 if ($item['uid'] != 0) {
1456 Logger::notice('Item already existed for user', [
1457 'uri' => $item['uri'],
1458 'uid' => $item['uid'],
1459 'network' => $item['network'],
1460 'existing_id' => $existing["id"],
1461 'existing_network' => $existing["network"]
1465 return $existing["id"];
1472 * Fetch parent data for the given item array
1474 * @param array $item
1475 * @return array item array with parent data
1477 private static function getParentData(array $item)
1479 // find the parent and snarf the item id and ACLs
1480 // and anything else we need to inherit
1482 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1483 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1484 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1485 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1486 $params = ['order' => ['id' => false]];
1487 $parent = self::selectFirst($fields, $condition, $params);
1489 if (!DBA::isResult($parent)) {
1490 Logger::info('item parent was not found - ignoring item', ['parent-uri' => $item['parent-uri'], 'uid' => $item['uid']]);
1493 // is the new message multi-level threaded?
1494 // even though we don't support it now, preserve the info
1495 // and re-attach to the conversation parent.
1496 if ($parent['uri'] != $parent['parent-uri']) {
1497 $item['parent-uri'] = $parent['parent-uri'];
1499 $condition = ['uri' => $item['parent-uri'],
1500 'parent-uri' => $item['parent-uri'],
1501 'uid' => $item['uid']];
1502 $params = ['order' => ['id' => false]];
1503 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1505 if (DBA::isResult($toplevel_parent)) {
1506 $parent = $toplevel_parent;
1510 $item['parent'] = $parent['id'];
1511 $item["deleted"] = $parent['deleted'];
1512 $item["allow_cid"] = $parent['allow_cid'];
1513 $item['allow_gid'] = $parent['allow_gid'];
1514 $item['deny_cid'] = $parent['deny_cid'];
1515 $item['deny_gid'] = $parent['deny_gid'];
1516 $item['parent_origin'] = $parent['origin'];
1518 // Don't federate received participation messages
1519 if ($item['verb'] != Activity::FOLLOW) {
1520 $item['wall'] = $parent['wall'];
1522 $item['wall'] = false;
1526 * If the parent is private, force privacy for the entire conversation
1527 * This differs from the above settings as it subtly allows comments from
1528 * email correspondents to be private even if the overall thread is not.
1530 if ($parent['private']) {
1531 $item['private'] = $parent['private'];
1535 * Edge case. We host a public forum that was originally posted to privately.
1536 * The original author commented, but as this is a comment, the permissions
1537 * weren't fixed up so it will still show the comment as private unless we fix it here.
1539 if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
1540 $item['private'] = self::PUBLIC;
1543 // If its a post that originated here then tag the thread as "mention"
1544 if ($item['origin'] && $item['uid']) {
1545 DBA::update('thread', ['mention' => true], ['iid' => $item['parent']]);
1546 Logger::info('tagged thread as mention', ['parent' => $item['parent'], 'uid' => $item['uid']]);
1549 // Update the contact relations
1550 Contact\Relation::store($parent['author-id'], $item['author-id'], $item['created']);
1557 * Get the gravity for the given item array
1559 * @param array $item
1560 * @return integer gravity
1562 private static function getGravity(array $item)
1564 $activity = DI::activity();
1566 if (isset($item['gravity'])) {
1567 return intval($item['gravity']);
1568 } elseif ($item['parent-uri'] === $item['uri']) {
1569 return GRAVITY_PARENT;
1570 } elseif ($activity->match($item['verb'], Activity::POST)) {
1571 return GRAVITY_COMMENT;
1572 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1573 return GRAVITY_ACTIVITY;
1574 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
1575 return GRAVITY_ACTIVITY;
1577 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
1578 return GRAVITY_UNKNOWN; // Should not happen
1581 public static function insert($item, $notify = false, $dontcache = false)
1583 $structure = self::getItemFields();
1587 $priority = PRIORITY_HIGH;
1589 // If it is a posting where users should get notifications, then define it as wall posting
1592 $item['origin'] = 1;
1593 $item['network'] = Protocol::DFRN;
1594 $item['protocol'] = Conversation::PARCEL_DFRN;
1596 if (is_int($notify)) {
1597 $priority = $notify;
1600 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1603 $uid = intval($item['uid']);
1605 $item['guid'] = self::guid($item, $notify);
1606 $item['uri'] = substr(Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']))), 0, 255);
1609 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1611 // Store conversation data
1612 $item = Conversation::insert($item);
1614 if (!empty($item['thr-parent'])) {
1615 $item['parent-uri'] = $item['thr-parent'];
1619 * Do we already have this item?
1620 * We have to check several networks since Friendica posts could be repeated
1621 * via OStatus (maybe Diasporsa as well)
1623 $duplicate = self::getDuplicateID($item);
1628 // Additional duplicate checks
1629 /// @todo Check why the first duplication check returns the item number and the second a 0
1630 if (self::isDuplicate($item)) {
1634 $item['wall'] = intval($item['wall'] ?? 0);
1635 $item['extid'] = trim($item['extid'] ?? '');
1636 $item['author-name'] = trim($item['author-name'] ?? '');
1637 $item['author-link'] = trim($item['author-link'] ?? '');
1638 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1639 $item['owner-name'] = trim($item['owner-name'] ?? '');
1640 $item['owner-link'] = trim($item['owner-link'] ?? '');
1641 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1642 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1643 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1644 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1645 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1646 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1647 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
1648 $item['location'] = trim($item['location'] ?? '');
1649 $item['coord'] = trim($item['coord'] ?? '');
1650 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1651 $item['deleted'] = 0;
1652 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1653 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1654 $item['verb'] = trim($item['verb'] ?? '');
1655 $item['object-type'] = trim($item['object-type'] ?? '');
1656 $item['object'] = trim($item['object'] ?? '');
1657 $item['target-type'] = trim($item['target-type'] ?? '');
1658 $item['target'] = trim($item['target'] ?? '');
1659 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
1660 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1661 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1662 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1663 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1664 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1665 $item['body'] = trim($item['body'] ?? '');
1666 $item['attach'] = trim($item['attach'] ?? '');
1667 $item['app'] = trim($item['app'] ?? '');
1668 $item['origin'] = intval($item['origin'] ?? 0);
1669 $item['postopts'] = trim($item['postopts'] ?? '');
1670 $item['resource-id'] = trim($item['resource-id'] ?? '');
1671 $item['event-id'] = intval($item['event-id'] ?? 0);
1672 $item['inform'] = trim($item['inform'] ?? '');
1673 $item['file'] = trim($item['file'] ?? '');
1675 // Items cannot be stored before they happen ...
1676 if ($item['created'] > DateTimeFormat::utcNow()) {
1677 $item['created'] = DateTimeFormat::utcNow();
1680 // We haven't invented time travel by now.
1681 if ($item['edited'] > DateTimeFormat::utcNow()) {
1682 $item['edited'] = DateTimeFormat::utcNow();
1685 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1687 $item['language'] = self::getLanguage($item);
1689 $item['gravity'] = self::getGravity($item);
1691 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1692 'photo' => $item['author-avatar'], 'network' => $item['network']];
1693 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1695 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1696 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1697 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1699 // Ensure that there is an avatar cache
1700 Contact::checkAvatarCache($item['author-id']);
1701 Contact::checkAvatarCache($item['owner-id']);
1703 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1704 $item["contact-id"] = self::contactId($item);
1706 if (!self::isValid($item)) {
1710 // We don't store the causer, we only have it here for the checks in the function above
1711 unset($item['causer-id']);
1712 unset($item['causer-link']);
1714 // We don't store these fields anymore in the item table
1715 unset($item['author-link']);
1716 unset($item['author-name']);
1717 unset($item['author-avatar']);
1718 unset($item['author-network']);
1720 unset($item['owner-link']);
1721 unset($item['owner-name']);
1722 unset($item['owner-avatar']);
1724 $item['thr-parent'] = $item['parent-uri'];
1726 if ($item['parent-uri'] != $item['uri']) {
1727 $item = self::getParentData($item);
1732 $parent_id = $item['parent'];
1733 unset($item['parent']);
1734 $parent_origin = $item['parent_origin'];
1735 unset($item['parent_origin']);
1738 $parent_origin = $item['origin'];
1741 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1742 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1744 // Is this item available in the global items (with uid=0)?
1745 if ($item["uid"] == 0) {
1746 $item["global"] = true;
1748 // Set the global flag on all items if this was a global item entry
1749 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1751 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1755 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
1756 $item["private"] = self::PRIVATE;
1760 $item['edit'] = false;
1761 $item['parent'] = $parent_id;
1762 Hook::callAll('post_local', $item);
1763 unset($item['edit']);
1764 unset($item['parent']);
1766 Hook::callAll('post_remote', $item);
1769 if (!empty($item['cancel'])) {
1770 Logger::log('post cancelled by addon.');
1774 if (empty($item['vid']) && !empty($item['verb'])) {
1775 $item['vid'] = Verb::getID($item['verb']);
1778 // Creates or assigns the permission set
1779 $item['psid'] = PermissionSet::getIdFromACL(
1787 unset($item['allow_cid']);
1788 unset($item['allow_gid']);
1789 unset($item['deny_cid']);
1790 unset($item['deny_gid']);
1792 // This array field is used to trigger some automatic reactions
1793 // It is mainly used in the "post_local" hook.
1794 unset($item['api_source']);
1796 if ($item['verb'] == Activity::ANNOUNCE) {
1797 self::setOwnerforResharedItem($item);
1800 // Check for hashtags in the body and repair or add hashtag links
1801 $item['body'] = self::setHashtags($item['body']);
1803 // Fill the cache field
1804 self::putInCache($item);
1806 if (stristr($item['verb'], Activity::POKE)) {
1807 $notify_type = Delivery::POKE;
1809 $notify_type = Delivery::POST;
1812 $like_no_comment = DI::config()->get('system', 'like_no_comment');
1816 if (!in_array($item['verb'], self::ACTIVITIES)) {
1817 $item['icid'] = self::insertContent($item);
1820 $body = $item['body'];
1822 // We just remove everything that is content
1823 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1824 unset($item[$field]);
1827 unset($item['activity']);
1829 // Filling item related side tables
1831 // Diaspora signature
1832 if (!empty($item['diaspora_signed_text'])) {
1833 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']], true);
1836 unset($item['diaspora_signed_text']);
1838 // Attached file links
1839 if (!empty($item['file'])) {
1840 Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1843 unset($item['file']);
1845 // Delivery relevant data
1846 $delivery_data = Post\DeliveryData::extractFields($item);
1847 unset($item['postopts']);
1848 unset($item['inform']);
1850 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1851 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1854 // Store tags from the body if this hadn't been handled previously in the protocol classes
1855 if (!Tag::existsForPost($item['uri-id'])) {
1856 Tag::storeFromBody($item['uri-id'], $body);
1859 // Remove all fields that aren't part of the item table
1860 foreach ($item as $field => $value) {
1861 if (!in_array($field, $structure['item'])) {
1862 unset($item[$field]);
1866 $ret = DBA::insert('item', $item);
1868 // When the item was successfully stored we fetch the ID of the item.
1869 if (DBA::isResult($ret)) {
1870 $current_post = DBA::lastInsertId();
1872 // This can happen - for example - if there are locking timeouts.
1875 // Store the data into a spool file so that we can try again later.
1876 self::spool($orig_item);
1880 if ($current_post == 0) {
1881 // This is one of these error messages that never should occur.
1882 Logger::log("couldn't find created item - we better quit now.");
1887 // How much entries have we created?
1888 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1889 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1892 // There are duplicates. We delete our just created entry.
1893 Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
1895 // Yes, we could do a rollback here - but we possibly are still having users with MyISAM.
1896 DBA::delete('item', ['id' => $current_post]);
1899 } elseif ($entries == 0) {
1900 // This really should never happen since we quit earlier if there were problems.
1901 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1906 Logger::log('created item '.$current_post);
1908 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1909 $parent_id = $current_post;
1913 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1915 $item['id'] = $current_post;
1916 $item['parent'] = $parent_id;
1918 // update the commented timestamp on the parent
1919 // Only update "commented" if it is really a comment
1920 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1921 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1923 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1926 if ($item['parent-uri'] === $item['uri']) {
1927 self::addThread($current_post);
1929 self::updateThread($parent_id);
1933 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1934 if (self::tagDeliver($item['uid'], $current_post)) {
1935 // Get the user information for the logging
1936 $user = User::getById($uid);
1938 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1943 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1944 if (DBA::isResult($posted_item)) {
1946 Hook::callAll('post_local_end', $posted_item);
1948 Hook::callAll('post_remote_end', $posted_item);
1951 Logger::log('new item not found in DB, id ' . $current_post);
1955 if ($item['parent-uri'] === $item['uri']) {
1956 self::addShadow($current_post);
1958 self::addShadowPost($current_post);
1961 self::updateContact($item);
1963 UserItem::setNotification($current_post);
1965 check_user_notification($current_post);
1967 // Distribute items to users who subscribed to their tags
1968 self::distributeByTags($item);
1970 $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
1973 $transmit_item = Item::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
1974 // Don't relay participation messages
1975 if (($transmit_item['verb'] == Activity::FOLLOW) &&
1976 (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1977 Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
1983 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1986 return $current_post;
1990 * Change the owner of a parent item if it had been shared by a forum
1992 * (public) forum posts in the new format consist of the regular post by the author
1993 * followed by an announce message sent from the forum account.
1994 * Changing the owner helps in grouping forum posts.
1996 * @param array $item
1999 private static function setOwnerforResharedItem(array $item)
2001 $parent = self::selectFirst(['id', 'owner-id', 'author-id', 'author-link', 'origin'],
2002 ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
2003 if (!DBA::isResult($parent)) {
2004 Logger::error('Parent not found', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
2008 $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
2009 if (!DBA::isResult($author)) {
2010 Logger::error('Author not found', ['id' => $item['author-id']]);
2014 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
2015 logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2019 $cid = Contact::getIdForURL($author['url'], $item['uid']);
2020 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
2021 logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
2025 Item::update(['owner-id' => $item['author-id'], 'contact-id' => $cid], ['id' => $parent['id']]);
2026 Logger::info('Change owner of the parent', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'owner-id' => $item['author-id'], 'contact-id' => $cid]);
2030 * Distribute the given item to users who subscribed to their tags
2032 * @param array $item Processed item
2034 private static function distributeByTags(array $item)
2036 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
2040 $uids = Tag::getUIDListByURIId($item['uri-id']);
2041 foreach ($uids as $uid) {
2042 if (Contact::isSharing($item['author-id'], $uid)) {
2045 $fields = ['post-type' => self::PT_TAG];
2048 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
2049 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
2054 * Insert a new item content entry
2056 * @param array $item The item fields that are to be inserted
2057 * @throws \Exception
2059 private static function insertContent(array $item)
2061 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2063 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2064 if (isset($item[$field])) {
2065 $fields[$field] = $item[$field];
2069 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2070 if (DBA::isResult($item_content)) {
2071 $icid = $item_content['id'];
2072 Logger::info('Content found', ['icid' => $icid, 'uri' => $item['uri']]);
2076 DBA::insert('item-content', $fields, true);
2077 $icid = DBA::lastInsertId();
2079 Logger::info('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
2083 // Possibly there can be timing issues. Then the same content could be inserted multiple times.
2084 // Due to the indexes this doesn't happen, but "lastInsertId" will be empty in these situations.
2085 // So we have to fetch the id manually. This is no bug and there is no data loss.
2086 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2087 if (DBA::isResult($item_content)) {
2088 $icid = $item_content['id'];
2089 Logger::notice('Content inserted with empty lastInsertId', ['icid' => $icid, 'uri' => $item['uri']]);
2093 // This shouldn't happen.
2094 Logger::error("Content wasn't inserted", $item);
2099 * Update existing item content entries
2101 * @param array $item The item fields that are to be changed
2102 * @param array $condition The condition for finding the item content entries
2103 * @throws \Exception
2105 private static function updateContent($item, $condition)
2107 // We have to select only the fields from the "item-content" table
2109 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2110 if (isset($item[$field])) {
2111 $fields[$field] = $item[$field];
2115 if (empty($fields)) {
2119 DBA::update('item-content', $fields, $condition, true);
2120 Logger::info('Updated content', ['condition' => $condition]);
2124 * Distributes public items to the receivers
2126 * @param integer $itemid Item ID that should be added
2127 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2128 * @throws \Exception
2130 public static function distribute($itemid, $signed_text = '')
2132 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2133 $parent = self::selectFirst(['owner-id'], $condition);
2134 if (!DBA::isResult($parent)) {
2138 // Only distribute public items from native networks
2139 $condition = ['id' => $itemid, 'uid' => 0,
2140 'network' => array_merge(Protocol::FEDERATED ,['']),
2141 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2142 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2143 if (!DBA::isResult($item)) {
2147 $origin = $item['origin'];
2151 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2152 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2153 if (!DBA::isResult($owner)) {
2157 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2158 $contacts = DBA::select('contact', ['uid'], $condition);
2159 while ($contact = DBA::fetch($contacts)) {
2160 if ($contact['uid'] == 0) {
2164 $users[$contact['uid']] = $contact['uid'];
2166 DBA::close($contacts);
2168 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2169 $contacts = DBA::select('contact', ['uid'], $condition);
2170 while ($contact = DBA::fetch($contacts)) {
2171 if ($contact['uid'] == 0) {
2175 $users[$contact['uid']] = $contact['uid'];
2177 DBA::close($contacts);
2179 if (!empty($owner['alias'])) {
2180 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
2181 $contacts = DBA::select('contact', ['uid'], $condition);
2182 while ($contact = DBA::fetch($contacts)) {
2183 if ($contact['uid'] == 0) {
2187 $users[$contact['uid']] = $contact['uid'];
2189 DBA::close($contacts);
2194 if ($item['uri'] != $item['parent-uri']) {
2195 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2196 while ($parent = self::fetch($parents)) {
2197 $users[$parent['uid']] = $parent['uid'];
2198 if ($parent['origin'] && !$origin) {
2199 $origin_uid = $parent['uid'];
2204 foreach ($users as $uid) {
2205 if ($origin_uid == $uid) {
2206 $item['diaspora_signed_text'] = $signed_text;
2208 self::storeForUser($item, $uid);
2213 * Store a public item defined by their URI-ID for the given users
2215 * @param integer $uri_id URI-ID of the given item
2216 * @param integer $uid The user that will receive the item entry
2217 * @param array $fields Additional fields to be stored
2218 * @return integer stored item id
2220 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
2222 $item = self::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
2223 if (!DBA::isResult($item)) {
2227 if (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED)) {
2228 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']]);
2232 $item = array_merge($item, $fields);
2234 $stored = self::storeForUser($item, $uid);
2235 Logger::info('Public item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
2240 * Store a public item array for the given users
2242 * @param array $item The item entry that will be stored
2243 * @param integer $uid The user that will receive the item entry
2244 * @return integer stored item id
2245 * @throws \Exception
2247 private static function storeForUser(array $item, int $uid)
2249 if (self::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
2250 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
2255 unset($item['parent']);
2256 unset($item['mention']);
2257 unset($item['starred']);
2258 unset($item['unseen']);
2259 unset($item['psid']);
2261 $item['uid'] = $uid;
2262 $item['origin'] = 0;
2265 if ($item['gravity'] == GRAVITY_PARENT) {
2266 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
2268 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
2271 if (!empty($contact['id'])) {
2272 $item['contact-id'] = $contact['id'];
2274 // Shouldn't happen at all
2275 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
2276 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2277 if (!DBA::isResult($self)) {
2278 // Shouldn't happen even less
2279 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
2282 $item['contact-id'] = $self['id'];
2285 /// @todo Handling of "event-id"
2288 if ($item['gravity'] == GRAVITY_PARENT) {
2289 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2290 if (DBA::isResult($contact)) {
2291 $notify = self::isRemoteSelf($contact, $item);
2295 $distributed = self::insert($item, $notify, true);
2297 if (!$distributed) {
2298 Logger::info("Distributed public item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
2300 Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
2302 return $distributed;
2306 * Add a shadow entry for a given item id that is a thread starter
2308 * We store every public item entry additionally with the user id "0".
2309 * This is used for the community page and for the search.
2310 * It is planned that in the future we will store public item entries only once.
2312 * @param integer $itemid Item ID that should be added
2313 * @throws \Exception
2315 public static function addShadow($itemid)
2317 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2318 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2319 $item = self::selectFirst($fields, $condition);
2321 if (!DBA::isResult($item)) {
2325 // is it already a copy?
2326 if (($itemid == 0) || ($item['uid'] == 0)) {
2330 // Is it a visible public post?
2331 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
2335 // is it an entry from a connector? Only add an entry for natively connected networks
2336 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2340 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2344 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2346 if (DBA::isResult($item)) {
2347 // Preparing public shadow (removing user specific data)
2350 unset($item['parent']);
2351 unset($item['wall']);
2352 unset($item['mention']);
2353 unset($item['origin']);
2354 unset($item['starred']);
2355 unset($item['postopts']);
2356 unset($item['inform']);
2357 if ($item['uri'] == $item['parent-uri']) {
2358 $item['contact-id'] = $item['owner-id'];
2360 $item['contact-id'] = $item['author-id'];
2363 $public_shadow = self::insert($item, false, true);
2365 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
2370 * Add a shadow entry for a given item id that is a comment
2372 * This function does the same like the function above - but for comments
2374 * @param integer $itemid Item ID that should be added
2375 * @throws \Exception
2377 public static function addShadowPost($itemid)
2379 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2380 if (!DBA::isResult($item)) {
2384 // Is it a toplevel post?
2385 if ($item['gravity'] == GRAVITY_PARENT) {
2386 self::addShadow($itemid);
2390 // Is this a shadow entry?
2391 if ($item['uid'] == 0) {
2395 // Is there a shadow parent?
2396 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2400 // Is there already a shadow entry?
2401 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2405 // Save "origin" and "parent" state
2406 $origin = $item['origin'];
2407 $parent = $item['parent'];
2409 // Preparing public shadow (removing user specific data)
2412 unset($item['parent']);
2413 unset($item['wall']);
2414 unset($item['mention']);
2415 unset($item['origin']);
2416 unset($item['starred']);
2417 unset($item['postopts']);
2418 unset($item['inform']);
2419 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2421 $public_shadow = self::insert($item, false, true);
2423 Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
2425 // If this was a comment to a Diaspora post we don't get our comment back.
2426 // This means that we have to distribute the comment by ourselves.
2427 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2428 self::distribute($public_shadow);
2433 * Adds a language specification in a "language" element of given $arr.
2434 * Expects "body" element to exist in $arr.
2436 * @param array $item
2437 * @return string detected language
2438 * @throws \Text_LanguageDetect_Exception
2440 private static function getLanguage(array $item)
2442 $naked_body = BBCode::toPlaintext($item['body'], false);
2444 $ld = new Text_LanguageDetect();
2445 $ld->setNameMode(2);
2446 $languages = $ld->detect($naked_body, 3);
2447 if (is_array($languages)) {
2448 return json_encode($languages);
2455 * Creates an unique guid out of a given uri
2457 * @param string $uri uri of an item entry
2458 * @param string $host hostname for the GUID prefix
2459 * @return string unique guid
2461 public static function guidFromUri($uri, $host)
2463 // Our regular guid routine is using this kind of prefix as well
2464 // We have to avoid that different routines could accidentally create the same value
2465 $parsed = parse_url($uri);
2467 // We use a hash of the hostname as prefix for the guid
2468 $guid_prefix = hash("crc32", $host);
2470 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2471 unset($parsed["scheme"]);
2473 // Glue it together to be able to make a hash from it
2474 $host_id = implode("/", $parsed);
2476 // We could use any hash algorithm since it isn't a security issue
2477 $host_hash = hash("ripemd128", $host_id);
2479 return $guid_prefix.$host_hash;
2483 * generate an unique URI
2485 * @param integer $uid User id
2486 * @param string $guid An existing GUID (Otherwise it will be generated)
2489 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2491 public static function newURI($uid, $guid = "")
2494 $guid = System::createUUID();
2497 return DI::baseUrl()->get() . '/objects/' . $guid;
2501 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2503 * This can be used to filter for inactive contacts.
2504 * Only do this for public postings to avoid privacy problems, since poco data is public.
2505 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2507 * @param array $arr Contains the just posted item record
2508 * @throws \Exception
2510 private static function updateContact($arr)
2512 // Unarchive the author
2513 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2514 if (DBA::isResult($contact)) {
2515 Contact::unmarkForArchival($contact);
2518 // Unarchive the contact if it's not our own contact
2519 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2520 if (DBA::isResult($contact)) {
2521 Contact::unmarkForArchival($contact);
2524 /// @todo On private posts we could obfuscate the date
2525 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2527 // Is it a forum? Then we don't care about the rules from above
2528 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2529 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2535 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2536 // So we have to ensure to only update the last item when it had been our own post,
2537 // or it had been done by a "regular" contact.
2538 if (!empty($arr['wall'])) {
2539 $condition = ['id' => $arr['contact-id']];
2541 $condition = ['id' => $arr['contact-id'], 'self' => false];
2543 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2545 // Now do the same for the system wide contacts with uid=0
2546 if ($arr['private'] != self::PRIVATE) {
2547 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2548 ['id' => $arr['owner-id']]);
2550 if ($arr['owner-id'] != $arr['author-id']) {
2551 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2552 ['id' => $arr['author-id']]);
2557 public static function setHashtags($body)
2559 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
2560 $tags = BBCode::getTags($body);
2563 if (!count($tags)) {
2567 // This sorting is important when there are hashtags that are part of other hashtags
2568 // Otherwise there could be problems with hashtags like #test and #test2
2569 // Because of this we are sorting from the longest to the shortest tag.
2570 usort($tags, function ($a, $b) {
2571 return strlen($b) <=> strlen($a);
2574 $URLSearchString = "^\[\]";
2576 // All hashtags should point to the home server if "local_tags" is activated
2577 if (DI::config()->get('system', 'local_tags')) {
2578 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2579 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2582 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2583 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2585 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2588 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2590 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2593 $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2595 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2598 // Repair recursive urls
2599 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2602 foreach ($tags as $tag) {
2603 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2607 $basetag = str_replace('_', ' ', substr($tag, 1));
2608 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2610 $body = str_replace($tag, $newtag, $body);
2613 // Convert back the masked hashtags
2614 $body = str_replace("#", "#", $body);
2623 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2626 * @param int $item_id
2627 * @return boolean true if item was deleted, else false
2628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2629 * @throws \ImagickException
2631 private static function tagDeliver($uid, $item_id)
2635 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2636 if (!DBA::isResult($user)) {
2640 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2641 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2643 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2644 if (!DBA::isResult($item)) {
2648 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2651 * Diaspora uses their own hardwired link URL in @-tags
2652 * instead of the one we supply with webfinger
2654 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2656 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2658 foreach ($matches as $mtch) {
2659 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2661 Logger::log('mention found: ' . $mtch[2]);
2667 if (($community_page || $prvgroup) &&
2668 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
2669 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2670 DBA::delete('item', ['id' => $item_id]);
2676 $arr = ['item' => $item, 'user' => $user];
2678 Hook::callAll('tagged', $arr);
2680 if (!$community_page && !$prvgroup) {
2685 * tgroup delivery - setup a second delivery chain
2686 * prevent delivery looping - only proceed
2687 * if the message originated elsewhere and is a top-level post
2689 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2693 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2694 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2695 if (!DBA::isResult($self)) {
2699 $owner_id = Contact::getIdForURL($self['url']);
2701 // also reset all the privacy bits to the forum default permissions
2703 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2705 $psid = PermissionSet::getIdFromACL(
2713 $forum_mode = ($prvgroup ? 2 : 1);
2715 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2716 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2717 self::update($fields, ['id' => $item_id]);
2719 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2721 Item::performActivity($item_id, 'announce', $uid);
2726 public static function isRemoteSelf($contact, &$datarray)
2728 if (!$contact['remote_self']) {
2732 // Prevent the forwarding of posts that are forwarded
2733 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2734 Logger::info('Already forwarded');
2738 // Prevent to forward already forwarded posts
2739 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2740 Logger::info('Already forwarded (second test)');
2744 // Only forward posts
2745 if ($datarray["verb"] != Activity::POST) {
2746 Logger::info('No post');
2750 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2751 Logger::info('Not public');
2755 $datarray2 = $datarray;
2756 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2757 if ($contact['remote_self'] == 2) {
2758 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2759 ['uid' => $contact['uid'], 'self' => true]);
2760 if (DBA::isResult($self)) {
2761 $datarray['contact-id'] = $self["id"];
2763 $datarray['owner-name'] = $self["name"];
2764 $datarray['owner-link'] = $self["url"];
2765 $datarray['owner-avatar'] = $self["thumb"];
2767 $datarray['author-name'] = $datarray['owner-name'];
2768 $datarray['author-link'] = $datarray['owner-link'];
2769 $datarray['author-avatar'] = $datarray['owner-avatar'];
2771 unset($datarray['edited']);
2773 unset($datarray['network']);
2774 unset($datarray['owner-id']);
2775 unset($datarray['author-id']);
2778 if ($contact['network'] != Protocol::FEED) {
2779 $datarray["guid"] = System::createUUID();
2780 unset($datarray["plink"]);
2781 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2782 $datarray["parent-uri"] = $datarray["uri"];
2783 $datarray["thr-parent"] = $datarray["uri"];
2784 $datarray["extid"] = Protocol::DFRN;
2785 $urlpart = parse_url($datarray2['author-link']);
2786 $datarray["app"] = $urlpart["host"];
2788 $datarray['private'] = self::PUBLIC;
2792 if ($contact['network'] != Protocol::FEED) {
2793 // Store the original post
2794 $result = self::insert($datarray2);
2795 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2797 $datarray["app"] = "Feed";
2801 // Trigger automatic reactions for addons
2802 $datarray['api_source'] = true;
2804 // We have to tell the hooks who we are - this really should be improved
2805 $_SESSION["authenticated"] = true;
2806 $_SESSION["uid"] = $contact['uid'];
2815 * @param array $item
2818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2819 * @throws \ImagickException
2821 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2823 if (DI::config()->get('system', 'disable_embedded')) {
2827 Logger::info('check for photos');
2828 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2833 $img_start = strpos($orig_body, '[img');
2834 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2835 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2837 while (($img_st_close !== false) && ($img_len !== false)) {
2838 $img_st_close++; // make it point to AFTER the closing bracket
2839 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2841 Logger::info('found photo', ['image' => $image]);
2843 if (stristr($image, $site . '/photo/')) {
2844 // Only embed locally hosted photos
2846 $i = basename($image);
2847 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2848 $x = strpos($i, '-');
2851 $res = substr($i, $x + 1);
2852 $i = substr($i, 0, $x);
2853 $photo = Photo::getPhotoForUser($uid, $i, $res);
2854 if (DBA::isResult($photo)) {
2856 * Check to see if we should replace this photo link with an embedded image
2857 * 1. No need to do so if the photo is public
2858 * 2. If there's a contact-id provided, see if they're in the access list
2859 * for the photo. If so, embed it.
2860 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2861 * permissions, regardless of order but first check to see if they're an exact
2862 * match to save some processing overhead.
2864 if (self::hasPermissions($photo)) {
2866 $recips = self::enumeratePermissions($photo);
2867 if (in_array($cid, $recips)) {
2871 if (self::samePermissions($uid, $item, $photo)) {
2877 $photo_img = Photo::getImageForPhoto($photo);
2878 // If a custom width and height were specified, apply before embedding
2879 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2880 Logger::info('scaling photo');
2882 $width = intval($match[1]);
2883 $height = intval($match[2]);
2885 $photo_img->scaleDown(max($width, $height));
2888 $data = $photo_img->asString();
2889 $type = $photo_img->getType();
2891 Logger::info('replacing photo');
2892 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2893 Logger::debug('replaced', ['image' => $image]);
2899 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2900 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2901 if ($orig_body === false) {
2905 $img_start = strpos($orig_body, '[img');
2906 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2907 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2910 $new_body = $new_body . $orig_body;
2915 private static function hasPermissions($obj)
2917 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2918 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2921 private static function samePermissions($uid, $obj1, $obj2)
2923 // first part is easy. Check that these are exactly the same.
2924 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2925 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2926 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2927 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2931 // This is harder. Parse all the permissions and compare the resulting set.
2932 $recipients1 = self::enumeratePermissions($obj1);
2933 $recipients2 = self::enumeratePermissions($obj2);
2937 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2938 return ($recipients1 == $recipients2);
2942 * Returns an array of contact-ids that are allowed to see this object
2944 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2945 * @param bool $check_dead Prunes unavailable contacts from the result
2947 * @throws \Exception
2949 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2951 $aclFormater = DI::aclFormatter();
2953 $allow_people = $aclFormater->expand($obj['allow_cid']);
2954 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2955 $deny_people = $aclFormater->expand($obj['deny_cid']);
2956 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2957 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2958 $deny = array_unique(array_merge($deny_people, $deny_groups));
2959 $recipients = array_diff($recipients, $deny);
2963 public static function expire($uid, $days, $network = "", $force = false)
2965 if (!$uid || ($days < 1)) {
2969 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2970 $uid, GRAVITY_PARENT];
2973 * $expire_network_only = save your own wall posts
2974 * and just expire conversations started by others
2976 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2978 if ($expire_network_only) {
2979 $condition[0] .= " AND NOT `wall`";
2982 if ($network != "") {
2983 $condition[0] .= " AND `network` = ?";
2984 $condition[] = $network;
2987 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2988 $condition[] = $days;
2990 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2992 if (!DBA::isResult($items)) {
2996 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2998 // Forcing expiring of items - but not notes and marked items
3000 $expire_items = true;
3003 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3004 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3005 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3009 while ($item = Item::fetch($items)) {
3010 // don't expire filed items
3012 if (strpos($item['file'], '[') !== false) {
3016 // Only expire posts, not photos and photo comments
3018 if (!$expire_photos && strlen($item['resource-id'])) {
3020 } elseif (!$expire_starred && intval($item['starred'])) {
3022 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3024 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3028 self::markForDeletionById($item['id'], PRIORITY_LOW);
3033 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3036 public static function firstPostDate($uid, $wall = false)
3038 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3039 $params = ['order' => ['received' => false]];
3040 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3041 if (DBA::isResult($thread)) {
3042 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3048 * add/remove activity to an item
3050 * Toggle activities as like,dislike,attend of an item
3052 * @param int $item_id
3053 * @param string $verb
3054 * Activity verb. One of
3055 * like, unlike, dislike, undislike, attendyes, unattendyes,
3056 * attendno, unattendno, attendmaybe, unattendmaybe,
3057 * announce, unannouce
3059 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3060 * @throws \ImagickException
3061 * @hook 'post_local_end'
3063 * 'post_id' => ID of posted item
3065 public static function performActivity(int $item_id, string $verb, int $uid)
3071 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
3073 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
3074 if (!DBA::isResult($item)) {
3075 Logger::log('like: unknown item ' . $item_id);
3079 $item_uri = $item['uri'];
3081 if (!in_array($item['uid'], [0, $uid])) {
3085 if (!Item::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
3086 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
3087 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
3088 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
3089 if (!DBA::isResult($item)) {
3090 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
3096 // Retrieves the local post owner
3097 $owner = User::getOwnerDataById($uid);
3098 if (empty($owner)) {
3099 Logger::info('Empty owner for user', ['uid' => $uid]);
3103 // Retrieve the current logged in user's public contact
3104 $author_id = Contact::getIdForURL($owner['url']);
3105 if (empty($author_id)) {
3106 Logger::info('Empty public contact');
3114 $activity = Activity::LIKE;
3118 $activity = Activity::DISLIKE;
3122 $activity = Activity::ATTEND;
3126 $activity = Activity::ATTENDNO;
3129 case 'unattendmaybe':
3130 $activity = Activity::ATTENDMAYBE;
3134 $activity = Activity::FOLLOW;
3138 $activity = Activity::ANNOUNCE;
3141 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3145 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3147 // Enable activity toggling instead of on/off
3148 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3150 // Look for an existing verb row
3151 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3152 if ($event_verb_flag) {
3153 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3155 // Translate to the index based activity index
3157 foreach ($verbs as $verb) {
3158 $vids[] = Verb::getID($verb);
3161 $vids = Verb::getID($activity);
3164 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3165 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3166 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3168 if (DBA::isResult($like_item)) {
3170 * Truth table for existing activities
3172 * | Inputs || Outputs |
3173 * |----------------------------||-------------------|
3174 * | Mode | Event | Same verb || Delete? | Return? |
3175 * |--------|-------|-----------||---------|---------|
3176 * | create | Yes | Yes || No | Yes |
3177 * | create | Yes | No || Yes | No |
3178 * | create | No | Yes || No | Yes |
3179 * | create | No | No || N/A†|
3180 * | delete | Yes | Yes || Yes | N/A‡ |
3181 * | delete | Yes | No || No | N/A‡ |
3182 * | delete | No | Yes || Yes | N/A‡ |
3183 * | delete | No | No || N/A†|
3184 * |--------|-------|-----------||---------|---------|
3185 * | A | B | C || A xor C | !B or C |
3187 * †Can't happen: It's impossible to find an existing non-event activity without
3188 * the same verb because we are only looking for this single verb.
3190 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
3192 if ($mode == 'create' xor $like_item['verb'] == $activity) {
3193 self::markForDeletionById($like_item['id']);
3196 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3201 // No need to go further if we aren't creating anything
3202 if ($mode == 'delete') {
3206 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3209 'guid' => System::createUUID(),
3210 'uri' => self::newURI($item['uid']),
3211 'uid' => $item['uid'],
3212 'contact-id' => $owner['id'],
3213 'wall' => $item['wall'],
3215 'network' => Protocol::DFRN,
3216 'gravity' => GRAVITY_ACTIVITY,
3217 'parent' => $item['id'],
3218 'parent-uri' => $item['uri'],
3219 'thr-parent' => $item['uri'],
3220 'owner-id' => $author_id,
3221 'author-id' => $author_id,
3222 'body' => $activity,
3223 'verb' => $activity,
3224 'object-type' => $objtype,
3225 'allow_cid' => $item['allow_cid'],
3226 'allow_gid' => $item['allow_gid'],
3227 'deny_cid' => $item['deny_cid'],
3228 'deny_gid' => $item['deny_gid'],
3233 $signed = Diaspora::createLikeSignature($uid, $new_item);
3234 if (!empty($signed)) {
3235 $new_item['diaspora_signed_text'] = json_encode($signed);
3238 $new_item_id = self::insert($new_item);
3240 // If the parent item isn't visible then set it to visible
3241 if (!$item['visible']) {
3242 self::update(['visible' => true], ['id' => $item['id']]);
3245 $new_item['id'] = $new_item_id;
3247 Hook::callAll('post_local_end', $new_item);
3252 private static function addThread($itemid, $onlyshadow = false)
3254 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3255 'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
3256 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3257 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3258 $item = self::selectFirst($fields, $condition);
3260 if (!DBA::isResult($item)) {
3264 $item['iid'] = $itemid;
3267 $result = DBA::insert('thread', $item);
3269 Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
3273 private static function updateThread($itemid, $setmention = false)
3275 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3276 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
3277 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3279 $item = self::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
3280 if (!DBA::isResult($item)) {
3285 $item["mention"] = 1;
3290 foreach ($item as $field => $data) {
3291 if (!in_array($field, ["guid"])) {
3292 $fields[$field] = $data;
3296 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3298 Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
3301 private static function deleteThread($itemid, $itemuri = "")
3303 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3304 if (!DBA::isResult($item)) {
3305 Logger::info('No thread found', ['id' => $itemid]);
3309 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3311 Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
3313 if ($itemuri != "") {
3314 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3315 if (!self::exists($condition)) {
3316 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3317 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3322 public static function getPermissionsSQLByUserId($owner_id)
3324 $local_user = local_user();
3325 $remote_user = Session::getRemoteContactID($owner_id);
3328 * Construct permissions
3330 * default permissions - anonymous user
3332 $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
3334 // Profile owner - everything is visible
3335 if ($local_user && ($local_user == $owner_id)) {
3337 } elseif ($remote_user) {
3339 * Authenticated visitor. Unless pre-verified,
3340 * check that the contact belongs to this $owner_id
3341 * and load the groups the visitor belongs to.
3342 * If pre-verified, the caller is expected to have already
3343 * done this and passed the groups into this function.
3345 $set = PermissionSet::get($owner_id, $remote_user);
3348 $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3353 $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
3360 * get translated item type
3365 public static function postType($item)
3367 if (!empty($item['event-id'])) {
3368 return DI::l10n()->t('event');
3369 } elseif (!empty($item['resource-id'])) {
3370 return DI::l10n()->t('photo');
3371 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
3372 return DI::l10n()->t('activity');
3373 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
3374 return DI::l10n()->t('comment');
3377 return DI::l10n()->t('post');
3381 * Sets the "rendered-html" field of the provided item
3383 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3385 * @param array $item
3386 * @param bool $update
3388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3389 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3391 public static function putInCache(&$item, $update = false)
3393 $body = $item["body"];
3395 $rendered_hash = $item['rendered-hash'] ?? '';
3396 $rendered_html = $item['rendered-html'] ?? '';
3398 if ($rendered_hash == ''
3399 || $rendered_html == ""
3400 || $rendered_hash != hash("md5", $item["body"])
3401 || DI::config()->get("system", "ignore_cache")
3403 self::addRedirToImageTags($item);
3405 $item["rendered-html"] = BBCode::convert($item["body"]);
3406 $item["rendered-hash"] = hash("md5", $item["body"]);
3408 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3409 Hook::callAll('put_item_in_cache', $hook_data);
3410 $item['rendered-html'] = $hook_data['rendered-html'];
3411 $item['rendered-hash'] = $hook_data['rendered-hash'];
3414 // Force an update if the generated values differ from the existing ones
3415 if ($rendered_hash != $item["rendered-hash"]) {
3419 // Only compare the HTML when we forcefully ignore the cache
3420 if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3424 if ($update && !empty($item["id"])) {
3427 'rendered-html' => $item["rendered-html"],
3428 'rendered-hash' => $item["rendered-hash"]
3430 ['id' => $item["id"]]
3435 $item["body"] = $body;
3439 * Find any non-embedded images in private items and add redir links to them
3441 * @param array &$item The field array of an item row
3443 private static function addRedirToImageTags(array &$item)
3448 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3450 foreach ($matches as $mtch) {
3451 if (strpos($mtch[1], '/redir') !== false) {
3455 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3456 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3457 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3464 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3465 * If attach is true, also add icons for item attachments.
3467 * @param array $item
3468 * @param boolean $attach
3469 * @param boolean $is_preview
3470 * @return string item body html
3471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3472 * @throws \ImagickException
3473 * @hook prepare_body_init item array before any work
3474 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3475 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3476 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3478 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3481 Hook::callAll('prepare_body_init', $item);
3483 // In order to provide theme developers more possibilities, event items
3484 // are treated differently.
3485 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3486 $ev = Event::getItemHTML($item);
3490 $tags = Tag::populateFromItem($item);
3492 $item['tags'] = $tags['tags'];
3493 $item['hashtags'] = $tags['hashtags'];
3494 $item['mentions'] = $tags['mentions'];
3496 // Compile eventual content filter reasons
3497 $filter_reasons = [];
3498 if (!$is_preview && public_contact() != $item['author-id']) {
3499 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3500 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3505 'filter_reasons' => $filter_reasons
3507 Hook::callAll('prepare_body_content_filter', $hook_data);
3508 $filter_reasons = $hook_data['filter_reasons'];
3512 // Update the cached values if there is no "zrl=..." on the links.
3513 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3515 // Or update it if the current viewer is the intented viewer.
3516 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3520 self::putInCache($item, $update);
3521 $s = $item["rendered-html"];
3526 'preview' => $is_preview,
3527 'filter_reasons' => $filter_reasons
3529 Hook::callAll('prepare_body', $hook_data);
3530 $s = $hook_data['html'];
3534 // Replace the blockquotes with quotes that are used in mails.
3535 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3536 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3543 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3544 foreach ($matches as $mtch) {
3547 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3549 if (strpos($mime, 'video') !== false) {
3552 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3555 $url_parts = explode('/', $the_url);
3556 $id = end($url_parts);
3557 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3560 'title' => DI::l10n()->t('View Video'),
3567 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3569 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3570 $filesubtype = str_replace('.', '-', $filesubtype);
3573 $filesubtype = 'unkn';
3576 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3577 $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
3579 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3580 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3584 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3588 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3589 $x = Map::byCoordinates(trim($item['coord']));
3591 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3595 // Replace friendica image url size with theme preference.
3596 if (!empty($a->theme_info['item_image_size'])) {
3597 $ps = $a->theme_info['item_image_size'];
3598 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3601 $s = HTML::applyContentFilter($s, $filter_reasons);
3603 $hook_data = ['item' => $item, 'html' => $s];
3604 Hook::callAll('prepare_body_final', $hook_data);
3606 return $hook_data['html'];
3610 * get private link for item
3612 * @param array $item
3613 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3614 * @throws \Exception
3616 public static function getPlink($item)
3620 'href' => "display/" . $item['guid'],
3621 'orig' => "display/" . $item['guid'],
3622 'title' => DI::l10n()->t('View on separate page'),
3623 'orig_title' => DI::l10n()->t('view on separate page'),
3626 if (!empty($item['plink'])) {
3627 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3628 $ret["title"] = DI::l10n()->t('link to source');
3630 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3632 'href' => $item['plink'],
3633 'orig' => $item['plink'],
3634 'title' => DI::l10n()->t('link to source'),
3644 * Is the given item array a post that is sent as starting post to a forum?
3646 * @param array $item
3647 * @param array $owner
3649 * @return boolean "true" when it is a forum post
3651 public static function isForumPost(array $item, array $owner = [])
3653 if (empty($owner)) {
3654 $owner = User::getOwnerDataById($item['uid']);
3655 if (empty($owner)) {
3660 if (($item['author-id'] == $item['owner-id']) ||
3661 ($owner['id'] == $item['contact-id']) ||
3662 ($item['uri'] != $item['parent-uri']) ||
3667 return Contact::isForum($item['contact-id']);
3671 * Search item id for given URI or plink
3673 * @param string $uri
3674 * @param integer $uid
3676 * @return integer item id
3678 public static function searchByLink($uri, $uid = 0)
3680 $ssl_uri = str_replace('http://', 'https://', $uri);
3681 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3683 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3684 if (DBA::isResult($item)) {
3688 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3689 if (!DBA::isResult($itemcontent)) {
3693 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3694 if (!DBA::isResult($itemuri)) {
3698 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3699 if (DBA::isResult($item)) {
3707 * Return the URI for a link to the post
3709 * @param string $uri URI or link to post
3711 * @return string URI
3713 public static function getURIByLink(string $uri)
3715 $ssl_uri = str_replace('http://', 'https://', $uri);
3716 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3718 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3719 if (DBA::isResult($item)) {
3720 return $item['uri'];
3723 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3724 if (!DBA::isResult($itemcontent)) {
3728 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3729 if (DBA::isResult($itemuri)) {
3730 return $itemuri['uri'];
3737 * Fetches item for given URI or plink
3739 * @param string $uri
3740 * @param integer $uid
3742 * @return integer item id
3744 public static function fetchByLink(string $uri, int $uid = 0)
3746 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3747 $item_id = self::searchByLink($uri, $uid);
3748 if (!empty($item_id)) {
3749 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3753 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3754 $item_id = self::searchByLink($fetched_uri, $uid);
3756 $item_id = Diaspora::fetchByURL($uri);
3759 if (!empty($item_id)) {
3760 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3764 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3769 * Return share data from an item array (if the item is shared item)
3770 * We are providing the complete Item array, because at some time in the future
3771 * we hopefully will define these values not in the body anymore but in some item fields.
3772 * This function is meant to replace all similar functions in the system.
3774 * @param array $item
3776 * @return array with share information
3778 public static function getShareArray($item)
3780 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3784 $attribute_string = $matches[2];
3785 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3786 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3787 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3788 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3795 * Fetch item information for shared items from the original items and adds it.
3797 * @param array $item
3799 * @return array item array with data from the original item
3801 public static function addShareDataFromOriginal(array $item)
3803 $shared = self::getShareArray($item);
3804 if (empty($shared)) {
3808 // Real reshares always have got a GUID.
3809 if (empty($shared['guid'])) {
3813 $uid = $item['uid'] ?? 0;
3815 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3816 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3817 if (!DBA::isResult($shared_item)) {
3818 if (empty($shared['link'])) {
3822 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3823 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3825 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3829 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
3830 if (!DBA::isResult($shared_item)) {
3833 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3835 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3838 if (!empty($shared_item['title'])) {
3839 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3840 unset($shared_item['title']);
3842 $body = $shared_item['body'];
3845 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3846 unset($shared_item['body']);
3848 return array_merge($item, $shared_item);