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\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
35 use Friendica\Database\DBStructure;
37 use Friendica\Model\Post;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Map;
43 use Friendica\Util\Network;
44 use Friendica\Util\Strings;
45 use Friendica\Worker\Delivery;
46 use Friendica\Repository\PermissionSet as RepPermissionSet;
47 use LanguageDetection\Language;
51 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
58 const PT_DOCUMENT = 19;
65 const PT_FOLLOWER = 69;
66 const PT_ANNOUNCEMENT = 70;
67 const PT_COMMENT = 71;
71 const PT_FETCHED = 75;
72 const PT_PERSONAL_NOTE = 128;
74 // Field list that is used to display the items
75 const DISPLAY_FIELDLIST = [
76 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
77 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
78 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'language',
79 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
80 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
81 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
82 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
83 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type',
84 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
85 'writable', 'self', 'cid', 'alias',
86 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
87 'event-summary', 'event-desc', 'event-location', 'event-type',
88 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
89 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
92 // Field list that is used to deliver items via the protocols
93 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
94 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
95 'private', 'title', 'body', 'location', 'coord', 'app',
96 'deleted', 'extid', 'post-type', 'gravity',
97 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
98 'author-id', 'author-link', 'owner-link', 'contact-uid',
99 'signed_text', 'network'];
101 // Field list for "item-content" table that is mixed with the item table
102 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
103 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
104 'object-type', 'object', 'target-type', 'target', 'plink'];
106 // Field list for "item-content" table that is not present in the "item" table
107 const CONTENT_FIELDLIST = ['language', 'raw-body'];
109 // All fields in the item table
110 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
111 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid',
112 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'psid',
113 'created', 'edited', 'commented', 'received', 'changed', 'verb',
114 'postopts', 'plink', 'resource-id', 'event-id', 'inform',
115 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
116 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
117 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
118 'title', 'content-warning', 'body', 'location', 'coord', 'app',
119 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
120 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
121 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
123 // List of all verbs that don't need additional content data.
124 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
126 Activity::LIKE, Activity::DISLIKE,
127 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
135 const TABLES = ['item', 'user-item', 'item-content', 'post-delivery-data', 'diaspora-interaction'];
137 private static $legacy_mode = null;
139 private static function getItemFields()
141 $definition = DBStructure::definition('', false);
144 foreach (self::TABLES as $table) {
145 $postfields[$table] = array_keys($definition[$table]['fields']);
152 * Set the pinned state of an item
154 * @param integer $iid Item ID
155 * @param integer $uid User ID
156 * @param boolean $pinned Pinned state
158 public static function setPinned(int $iid, int $uid, bool $pinned)
160 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
164 * Get the pinned state
166 * @param integer $iid Item ID
167 * @param integer $uid User ID
169 * @return boolean pinned state
171 public static function getPinned(int $iid, int $uid)
173 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
174 if (!DBA::isResult($useritem)) {
177 return (bool)$useritem['pinned'];
181 * Select pinned rows from the item table for a given user
183 * @param integer $uid User ID
184 * @param array $selected Array of selected fields, empty for all
185 * @param array $condition Array of fields for condition
186 * @param array $params Array of several parameters
188 * @return boolean|object
191 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
193 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
194 if (!DBA::isResult($useritems)) {
199 while ($useritem = DBA::fetch($useritems)) {
200 $pinned[] = $useritem['iid'];
202 DBA::close($useritems);
204 if (empty($pinned)) {
208 $condition = DBA::mergeConditions(['iid' => $pinned], $condition);
210 return self::selectThreadForUser($uid, $selected, $condition, $params);
214 * Fetch a single item row
216 * @param mixed $stmt statement object
217 * @return array|false current row or false
220 private static function fetch($stmt)
222 $row = DBA::fetch($stmt);
224 if (!is_array($row)) {
228 $row = DBA::castFields('item', $row);
230 // ---------------------- Transform item structure data ----------------------
232 // We prefer the data from the user's contact over the public one
233 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
234 ($row['author-link'] == $row['contact-link'])) {
235 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
236 $row['author-avatar'] = $row['contact-avatar'];
238 if (isset($row['author-name']) && !empty($row['contact-name'])) {
239 $row['author-name'] = $row['contact-name'];
243 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
244 ($row['owner-link'] == $row['contact-link'])) {
245 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
246 $row['owner-avatar'] = $row['contact-avatar'];
248 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
249 $row['owner-name'] = $row['contact-name'];
253 // We can always comment on posts from these networks
254 if (array_key_exists('writable', $row) &&
255 in_array($row['internal-network'], Protocol::FEDERATED)) {
256 $row['writable'] = 1;
259 // ---------------------- Transform item content data ----------------------
261 if (array_key_exists('verb', $row)) {
262 if (!is_null($row['internal-verb'])) {
263 $row['verb'] = $row['internal-verb'];
266 if (in_array($row['verb'], self::ACTIVITIES)) {
267 if (array_key_exists('title', $row)) {
270 if (array_key_exists('body', $row)) {
271 $row['body'] = $row['verb'];
273 if (array_key_exists('object', $row)) {
276 if (array_key_exists('object-type', $row)) {
277 $row['object-type'] = Activity\ObjectType::NOTE;
279 } elseif (in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
280 // Posts don't have a target - but having tags or files.
281 if (array_key_exists('target', $row)) {
287 if (array_key_exists('vid', $row) && is_null($row['vid']) && !empty($row['verb'])) {
288 $row['vid'] = Verb::getID($row['verb']);
291 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
292 // Build the file string out of the term entries
293 if (array_key_exists('file', $row) && empty($row['file'])) {
294 $row['file'] = Post\Category::getTextByURIId($row['internal-uri-id'], $row['internal-uid']);
298 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
299 if (array_key_exists('allow_cid', $row)) {
300 $row['allow_cid'] = '';
302 if (array_key_exists('allow_gid', $row)) {
303 $row['allow_gid'] = '';
305 if (array_key_exists('deny_cid', $row)) {
306 $row['deny_cid'] = '';
308 if (array_key_exists('deny_gid', $row)) {
309 $row['deny_gid'] = '';
313 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
314 $row['ignored'] = $row['internal-user-ignored'];
317 // Remove internal fields
318 unset($row['internal-network']);
319 unset($row['internal-uri-id']);
320 unset($row['internal-uid']);
321 unset($row['internal-psid']);
322 unset($row['internal-verb']);
323 unset($row['internal-user-ignored']);
324 unset($row['interaction']);
330 * Fills an array with data from an item query
332 * @param object $stmt statement object
333 * @param bool $do_close
334 * @return array Data array
336 public static function toArray($stmt, $do_close = true) {
337 if (is_bool($stmt)) {
342 while ($row = self::fetch($stmt)) {
352 * Check if item data exists
354 * @param array $condition array of fields for condition
356 * @return boolean Are there rows for that condition?
359 public static function exists($condition) {
360 $stmt = self::select(['id'], $condition, ['limit' => 1]);
362 if (is_bool($stmt)) {
365 $retval = (DBA::numRows($stmt) > 0);
374 * Retrieve a single record from the item table and returns it in an associative array
376 * @param array $fields
377 * @param array $condition
378 * @param array $params
383 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
385 $params['limit'] = 1;
387 $result = self::select($fields, $condition, $params);
389 if (is_bool($result)) {
392 $row = self::fetch($result);
399 * Select rows from the item table and returns them as an array
401 * @param array $selected Array of selected fields, empty for all
402 * @param array $condition Array of fields for condition
403 * @param array $params Array of several parameters
408 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
410 $result = self::select($fields, $condition, $params);
412 if (is_bool($result)) {
417 while ($row = self::fetch($result)) {
426 * Select rows from the item table
428 * @param array $selected Array of selected fields, empty for all
429 * @param array $condition Array of fields for condition
430 * @param array $params Array of several parameters
432 * @return boolean|object
435 public static function select(array $selected = [], array $condition = [], $params = [])
440 if (isset($params['uid'])) {
441 $uid = $params['uid'];
445 $fields = self::fieldlist($usermode);
447 $select_fields = self::constructSelectFields($fields, $selected);
449 $condition_string = DBA::buildCondition($condition);
451 $condition_string = self::addTablesToFields($condition_string, $fields);
454 $condition_string = $condition_string . ' AND ' . self::condition(false);
457 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
459 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
461 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
463 return DBA::p($sql, $condition);
467 * Select rows from the starting post in the item table
469 * @param integer $uid User ID
470 * @param array $selected
471 * @param array $condition Array of fields for condition
472 * @param array $params Array of several parameters
474 * @return boolean|object
477 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
479 $params['uid'] = $uid;
481 if (empty($selected)) {
482 $selected = self::DISPLAY_FIELDLIST;
485 return self::selectThread($selected, $condition, $params);
489 * Retrieve a single record from the starting post in the item table and returns it in an associative array
491 * @param integer $uid User ID
492 * @param array $selected
493 * @param array $condition
494 * @param array $params
499 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
501 $params['uid'] = $uid;
503 if (empty($selected)) {
504 $selected = self::DISPLAY_FIELDLIST;
507 return self::selectFirstThread($selected, $condition, $params);
511 * Retrieve a single record from the starting post in the item table and returns it in an associative array
513 * @param array $fields
514 * @param array $condition
515 * @param array $params
520 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
522 $params['limit'] = 1;
523 $result = self::selectThread($fields, $condition, $params);
525 if (is_bool($result)) {
528 $row = self::fetch($result);
535 * Select rows from the starting post in the item table
537 * @param array $selected Array of selected fields, empty for all
538 * @param array $condition Array of fields for condition
539 * @param array $params Array of several parameters
541 * @return boolean|object
544 public static function selectThread(array $selected = [], array $condition = [], $params = [])
549 if (isset($params['uid'])) {
550 $uid = $params['uid'];
554 $fields = self::fieldlist($usermode);
556 $fields['thread'] = ['mention', 'ignored', 'iid'];
558 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
559 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
560 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
561 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
563 $select_fields = self::constructSelectFields($fields, $selected);
565 $condition_string = DBA::buildCondition($condition);
567 $condition_string = self::addTablesToFields($condition_string, $threadfields);
568 $condition_string = self::addTablesToFields($condition_string, $fields);
571 $condition_string = $condition_string . ' AND ' . self::condition(true);
574 $param_string = DBA::buildParameter($params);
575 $param_string = self::addTablesToFields($param_string, $threadfields);
576 $param_string = self::addTablesToFields($param_string, $fields);
578 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
580 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
582 return DBA::p($sql, $condition);
586 * Returns a list of fields that are associated with the item table
589 * @return array field list
591 private static function fieldlist($usermode)
595 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
596 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'vid', 'causer-id',
597 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
598 'created', 'edited', 'commented', 'received', 'changed', 'psid',
599 'resource-id', 'event-id', 'post-type', 'file',
600 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
601 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
602 'id' => 'item_id', 'network', 'icid', 'event-id',
603 'uri-id' => 'internal-uri-id', 'uid' => 'internal-uid',
604 'network' => 'internal-network', 'psid' => 'internal-psid'];
607 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
610 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
612 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
614 $fields['verb'] = ['name' => 'internal-verb'];
616 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
618 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
619 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
621 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
622 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
624 $fields['causer'] = ['url' => 'causer-link', 'name' => 'causer-name', 'addr' => 'causer-addr',
625 'thumb' => 'causer-avatar', 'nick' => 'causer-nick', 'network' => 'causer-network',
626 'contact-type' => 'causer-contact-type'];
628 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
629 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
630 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
632 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network', 'author-id' => 'parent-author-id'];
634 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name',
635 'network' => 'parent-author-network'];
637 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
638 'start' => 'event-start','finish' => 'event-finish',
639 'summary' => 'event-summary','desc' => 'event-desc',
640 'location' => 'event-location', 'type' => 'event-type',
641 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
642 'ignore' => 'event-ignore'];
644 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
650 * Returns SQL condition for the "select" functions
652 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
654 * @return string SQL condition
656 private static function condition($thread_mode)
659 $master_table = "`thread`";
661 $master_table = "`item`";
663 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
664 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
665 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
666 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
667 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
668 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
669 GRAVITY_PARENT, GRAVITY_PARENT);
673 * Returns all needed "JOIN" commands for the "select" functions
675 * @param integer $uid User ID
676 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
677 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
680 * @return string The SQL joins for the "select" functions
682 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
685 $master_table = "`thread`";
686 $master_table_key = "`thread`.`iid`";
687 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
689 $master_table = "`item`";
690 $master_table_key = "`item`.`id`";
695 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
696 AND NOT `contact`.`blocked`
697 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
698 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
699 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
700 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
701 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
702 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
703 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
704 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
706 if (strpos($sql_commands, "`contact`.") !== false) {
707 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
709 if (strpos($sql_commands, "`author`.") !== false) {
710 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
712 if (strpos($sql_commands, "`owner`.") !== false) {
713 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
716 if (strpos($sql_commands, "`causer`.") !== false) {
717 $joins .= " LEFT JOIN `contact` AS `causer` ON `causer`.`id` = `item`.`causer-id`";
720 if (strpos($sql_commands, "`group_member`.") !== false) {
721 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
724 if (strpos($sql_commands, "`user`.") !== false) {
725 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
728 if (strpos($sql_commands, "`event`.") !== false) {
729 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
732 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
733 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
736 if (strpos($sql_commands, "`item-content`.") !== false) {
737 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
740 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
741 $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
744 if (strpos($sql_commands, "`verb`.") !== false) {
745 $joins .= " LEFT JOIN `verb` ON `verb`.`id` = `item`.`vid`";
748 if (strpos($sql_commands, "`permissionset`.") !== false) {
749 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
752 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-item-author`.") !== false)) {
753 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
755 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
756 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
764 * Add the field list for the "select" functions
766 * @param array $fields The field definition array
767 * @param array $selected The array with the selected fields from the "select" functions
769 * @return string The field list
771 private static function constructSelectFields(array $fields, array $selected)
773 if (!empty($selected)) {
774 $selected = array_merge($selected, ['internal-uri-id', 'internal-uid', 'internal-psid', 'internal-network']);
777 if (in_array('verb', $selected)) {
778 $selected = array_merge($selected, ['internal-verb']);
781 if (in_array('ignored', $selected)) {
782 $selected[] = 'internal-user-ignored';
785 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
788 foreach ($fields as $table => $table_fields) {
789 foreach ($table_fields as $field => $select) {
790 if (empty($selected) || in_array($select, $selected)) {
791 if (is_int($field)) {
792 $selection[] = "`" . $table . "`.`" . $select . "`";
794 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
799 return implode(", ", $selection);
803 * add table definition to fields in an SQL query
805 * @param string $query SQL query
806 * @param array $fields The field definition array
808 * @return string the changed SQL query
810 private static function addTablesToFields($query, $fields)
812 foreach ($fields as $table => $table_fields) {
813 foreach ($table_fields as $alias => $field) {
814 if (is_int($alias)) {
815 $replace_field = $field;
817 $replace_field = $alias;
820 $search = "/([^\.])`" . $field . "`/i";
821 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
822 $query = preg_replace($search, $replace, $query);
829 * Update existing item entries
831 * @param array $fields The fields that are to be changed
832 * @param array $condition The condition for finding the item entries
834 * In the future we may have to change permissions as well.
835 * Then we had to add the user id as third parameter.
837 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
839 * @return integer|boolean number of affected rows - or "false" if there was an error
840 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
842 public static function update(array $fields, array $condition)
844 if (empty($condition) || empty($fields)) {
848 $data_fields = $fields;
850 // To ensure the data integrity we do it in an transaction
853 // We cannot simply expand the condition to check for origin entries
854 // The condition needn't to be a simple array but could be a complex condition.
855 // And we have to execute this query before the update to ensure to fetch the same data.
856 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'icid', 'uid', 'file'], $condition);
858 $content_fields = [];
859 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
860 if (isset($fields[$field])) {
861 $content_fields[$field] = $fields[$field];
862 if (in_array($field, self::CONTENT_FIELDLIST)) {
863 unset($fields[$field]);
865 $fields[$field] = null;
870 $delivery_data = Post\DeliveryData::extractFields($fields);
872 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
873 foreach ($clear_fields as $field) {
874 if (array_key_exists($field, $fields)) {
875 $fields[$field] = null;
879 if (array_key_exists('file', $fields)) {
880 $files = $fields['file'];
881 $fields['file'] = null;
886 if (!empty($content_fields['verb'])) {
887 $fields['vid'] = Verb::getID($content_fields['verb']);
890 if (!empty($fields)) {
891 $success = DBA::update('item', $fields, $condition);
900 // When there is no content for the "old" item table, this will count the fetched items
901 $rows = DBA::affectedRows();
905 while ($item = DBA::fetch($items)) {
906 Post\User::update($item['uri-id'], $item['uid'], $data_fields);
908 if (empty($content_fields['verb']) || !in_array($content_fields['verb'], self::ACTIVITIES)) {
909 if (!empty($content_fields['body'])) {
910 $content_fields['raw-body'] = trim($content_fields['raw-body'] ?? $content_fields['body']);
912 // Remove all media attachments from the body and store them in the post-media table
913 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
914 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
917 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
919 if (empty($item['icid'])) {
920 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
921 if (DBA::isResult($item_content)) {
922 $item_fields = ['icid' => $item_content['id']];
923 DBA::update('item', $item_fields, ['id' => $item['id']]);
928 if (!is_null($files)) {
929 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $files);
930 if (!empty($item['file'])) {
931 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
935 if (!empty($fields['attach'])) {
936 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
939 Post\DeliveryData::update($item['uri-id'], $delivery_data);
941 self::updateThread($item['id']);
943 // We only need to notfiy others when it is an original entry from us.
944 // Only call the notifier when the item has some content relevant change.
945 if ($item['origin'] && in_array('edited', array_keys($fields))) {
946 $notify_items[] = $item['id'];
953 foreach ($notify_items as $notify_item) {
954 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
961 * Delete an item and notify others about it - if it was ours
963 * @param array $condition The condition for finding the item entries
964 * @param integer $priority Priority for the notification
965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
969 $items = Post::select(['id'], $condition);
970 while ($item = Post::fetch($items)) {
971 self::markForDeletionById($item['id'], $priority);
977 * Delete an item for an user and notify others about it - if it was ours
979 * @param array $condition The condition for finding the item entries
980 * @param integer $uid User who wants to delete this item
981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983 public static function deleteForUser($condition, $uid)
989 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
990 while ($item = Post::fetch($items)) {
991 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
993 // "Deleting" global items just means hiding them
994 if ($item['uid'] == 0) {
995 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
996 } elseif ($item['uid'] == $uid) {
997 self::markForDeletionById($item['id'], PRIORITY_HIGH);
999 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1006 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1008 * @param integer $item_id
1009 * @param integer $priority Priority for the notification
1011 * @return boolean success
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1014 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1016 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1017 // locate item to be deleted
1018 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1019 'deleted', 'file', 'resource-id', 'event-id',
1020 'verb', 'object-type', 'object', 'target', 'contact-id',
1021 'icid', 'psid', 'gravity'];
1022 $item = Post::selectFirst($fields, ['id' => $item_id]);
1023 if (!DBA::isResult($item)) {
1024 Logger::info('Item not found.', ['id' => $item_id]);
1028 if ($item['deleted']) {
1029 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1033 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
1034 if (!DBA::isResult($parent)) {
1035 $parent = ['origin' => false];
1038 // clean up categories and tags so they don't end up as orphans
1041 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1044 foreach ($matches as $mtch) {
1045 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1051 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1054 foreach ($matches as $mtch) {
1055 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1060 * If item is a link to a photo resource, nuke all the associated photos
1061 * (visitors will not have photo resources)
1062 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1063 * generate a resource-id and therefore aren't intimately linked to the item.
1065 /// @TODO: this should first check if photo is used elsewhere
1066 if (strlen($item['resource-id'])) {
1067 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1070 // If item is a link to an event, delete the event.
1071 if (intval($item['event-id'])) {
1072 Event::delete($item['event-id']);
1075 // If item has attachments, drop them
1076 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
1077 foreach($attachments as $attachment) {
1078 if (preg_match("|attach/(\d+)|", $attachment['url'], $matches)) {
1079 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1083 // Set the item to "deleted"
1084 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1085 DBA::update('item', $item_fields, ['id' => $item['id']]);
1087 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
1088 self::deleteThread($item['id'], $item['parent-uri']);
1090 if (!Post::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1091 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1094 Post\DeliveryData::delete($item['uri-id']);
1096 // When the permission set will be used in photo and events as well,
1097 // this query here needs to be extended.
1098 // @todo Currently deactivated. We need the permission set in the deletion process.
1099 // This is a reminder to add the removal somewhere else.
1100 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1101 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1104 // If it's the parent of a comment thread, kill all the kids
1105 if ($item['gravity'] == GRAVITY_PARENT) {
1106 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1109 // Is it our comment and/or our thread?
1110 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
1111 // When we delete the original post we will delete all existing copies on the server as well
1112 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1114 // send the notification upstream/downstream
1116 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1118 } elseif ($item['uid'] != 0) {
1119 Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
1121 // When we delete just our local user copy of an item, we have to set a marker to hide it
1122 $global_item = Post::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1123 if (DBA::isResult($global_item)) {
1124 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1128 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1134 private static function guid($item, $notify)
1136 if (!empty($item['guid'])) {
1137 return Strings::escapeTags(trim($item['guid']));
1141 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1142 // We add the hash of our own host because our host is the original creator of the post.
1143 $prefix_host = DI::baseUrl()->getHostname();
1147 // We are only storing the post so we create a GUID from the original hostname.
1148 if (!empty($item['author-link'])) {
1149 $parsed = parse_url($item['author-link']);
1150 if (!empty($parsed['host'])) {
1151 $prefix_host = $parsed['host'];
1155 if (empty($prefix_host) && !empty($item['plink'])) {
1156 $parsed = parse_url($item['plink']);
1157 if (!empty($parsed['host'])) {
1158 $prefix_host = $parsed['host'];
1162 if (empty($prefix_host) && !empty($item['uri'])) {
1163 $parsed = parse_url($item['uri']);
1164 if (!empty($parsed['host'])) {
1165 $prefix_host = $parsed['host'];
1169 // Is it in the format data@host.tld? - Used for mail contacts
1170 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1171 $mailparts = explode('@', $item['author-link']);
1172 $prefix_host = array_pop($mailparts);
1176 if (!empty($item['plink'])) {
1177 $guid = self::guidFromUri($item['plink'], $prefix_host);
1178 } elseif (!empty($item['uri'])) {
1179 $guid = self::guidFromUri($item['uri'], $prefix_host);
1181 $guid = System::createUUID(hash('crc32', $prefix_host));
1187 private static function contactId($item)
1189 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1190 return $item['contact-id'];
1191 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1192 return $item['contact-id'];
1193 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1194 return $item['author-id'];
1195 } elseif (!empty($item['contact-id'])) {
1196 return $item['contact-id'];
1198 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1199 if (!empty($contact_id)) {
1203 return $item['author-id'];
1206 // This function will finally cover most of the preparation functionality in mod/item.php
1207 public static function prepare(&$item)
1210 * @TODO: Unused code triggering inspection errors
1212 $data = BBCode::getAttachmentData($item['body']);
1213 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1214 && ($posttype != self::PT_PERSONAL_NOTE)) {
1215 $posttype = self::PT_PAGE;
1216 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1222 * Write an item array into a spool file to be inserted later.
1223 * This command is called whenever there are issues storing an item.
1225 * @param array $item The item fields that are to be inserted
1226 * @throws \Exception
1228 private static function spool($orig_item)
1230 // Now we store the data in the spool directory
1231 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1232 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1234 $spoolpath = get_spoolpath();
1235 if ($spoolpath != "") {
1236 $spool = $spoolpath . '/' . $file;
1238 file_put_contents($spool, json_encode($orig_item));
1239 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1244 * Check if the item array is a duplicate
1246 * @param array $item
1247 * @return boolean is it a duplicate?
1249 private static function isDuplicate(array $item)
1251 // Checking if there is already an item with the same guid
1252 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1253 if (Post::exists($condition)) {
1254 Logger::notice('Found already existing item', [
1255 'guid' => $item['guid'],
1256 'uid' => $item['uid'],
1257 'network' => $item['network']
1262 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1263 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1264 if (Post::exists($condition)) {
1265 Logger::notice('duplicated item with the same uri found.', $item);
1269 // On Friendica and Diaspora the GUID is unique
1270 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1271 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1272 if (Post::exists($condition)) {
1273 Logger::notice('duplicated item with the same guid found.', $item);
1276 } elseif ($item['network'] == Protocol::OSTATUS) {
1277 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1278 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1279 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1280 if (Post::exists($condition)) {
1281 Logger::notice('duplicated item with the same body found.', $item);
1287 * Check for already added items.
1288 * There is a timing issue here that sometimes creates double postings.
1289 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1291 if (($item['uid'] == 0) && Post::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1292 Logger::notice('Global item already stored.', ['uri' => $item['uri'], 'network' => $item['network']]);
1300 * Check if the item array is valid
1302 * @param array $item
1303 * @return boolean item is valid
1305 public static function isValid(array $item)
1307 // When there is no content then we don't post it
1308 if ($item['body'] . $item['title'] == '') {
1309 Logger::notice('No body, no title.');
1313 if (!empty($item['uid'])) {
1314 $owner = User::getOwnerDataById($item['uid'], false);
1316 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
1320 if ($owner['account_expired'] || $owner['account_removed']) {
1321 Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
1326 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
1327 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1331 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1332 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1336 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
1337 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1341 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1342 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1346 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
1350 if ($item['verb'] == Activity::FOLLOW) {
1351 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
1352 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1353 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
1357 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1358 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1359 if (Post::exists($condition)) {
1360 // It happens that we receive multiple follow requests by the same author - we only store one.
1361 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
1370 * Check if the item array is too old
1372 * @param array $item
1373 * @return boolean item is too old
1375 public static function isTooOld(array $item)
1377 // check for create date and expire time
1378 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1380 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
1381 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1382 $expire_interval = $user['expire'];
1385 if (($expire_interval > 0) && !empty($item['created'])) {
1386 $expire_date = time() - ($expire_interval * 86400);
1387 $created_date = strtotime($item['created']);
1388 if ($created_date < $expire_date) {
1389 Logger::notice('Item created before expiration interval.', [
1390 'created' => date('c', $created_date),
1391 'expired' => date('c', $expire_date),
1402 * Return the id of the given item array if it has been stored before
1404 * @param array $item
1405 * @return integer item id
1407 private static function getDuplicateID(array $item)
1409 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1410 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1411 trim($item['uri']), $item['uid'],
1412 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1413 $existing = Post::selectFirst(['id', 'network'], $condition);
1414 if (DBA::isResult($existing)) {
1415 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1416 if ($item['uid'] != 0) {
1417 Logger::notice('Item already existed for user', [
1418 'uri' => $item['uri'],
1419 'uid' => $item['uid'],
1420 'network' => $item['network'],
1421 'existing_id' => $existing["id"],
1422 'existing_network' => $existing["network"]
1426 return $existing["id"];
1433 * Fetch top-level parent data for the given item array
1435 * @param array $item
1436 * @return array item array with parent data
1437 * @throws \Exception
1439 private static function getTopLevelParent(array $item)
1441 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
1442 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1443 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1444 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid']];
1445 $params = ['order' => ['id' => false]];
1446 $parent = Post::selectFirst($fields, $condition, $params);
1448 if (!DBA::isResult($parent)) {
1449 Logger::notice('item parent was not found - ignoring item', ['thr-parent' => $item['thr-parent'], 'uid' => $item['uid']]);
1453 if ($parent['uri'] == $parent['parent-uri']) {
1457 $condition = ['uri' => $parent['parent-uri'],
1458 'parent-uri' => $parent['parent-uri'],
1459 'uid' => $parent['uid']];
1460 $params = ['order' => ['id' => false]];
1461 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
1462 if (!DBA::isResult($toplevel_parent)) {
1463 Logger::notice('item top level parent was not found - ignoring item', ['parent-uri' => $parent['parent-uri'], 'uid' => $parent['uid']]);
1467 return $toplevel_parent;
1471 * Get the gravity for the given item array
1473 * @param array $item
1474 * @return integer gravity
1476 private static function getGravity(array $item)
1478 $activity = DI::activity();
1480 if (isset($item['gravity'])) {
1481 return intval($item['gravity']);
1482 } elseif ($item['parent-uri'] === $item['uri']) {
1483 return GRAVITY_PARENT;
1484 } elseif ($activity->match($item['verb'], Activity::POST)) {
1485 return GRAVITY_COMMENT;
1486 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1487 return GRAVITY_ACTIVITY;
1488 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
1489 return GRAVITY_ACTIVITY;
1491 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
1492 return GRAVITY_UNKNOWN; // Should not happen
1495 public static function insert($item, $notify = false, $dontcache = false)
1497 $structure = self::getItemFields();
1501 $priority = PRIORITY_HIGH;
1503 // If it is a posting where users should get notifications, then define it as wall posting
1506 $item['origin'] = 1;
1507 $item['network'] = Protocol::DFRN;
1508 $item['protocol'] = Conversation::PARCEL_DIRECT;
1509 $item['direction'] = Conversation::PUSH;
1511 if (in_array($notify, PRIORITIES)) {
1512 $priority = $notify;
1515 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1518 $uid = intval($item['uid']);
1520 $item['guid'] = self::guid($item, $notify);
1521 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']), 0, 255);
1524 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1526 // Backward compatibility: parent-uri used to be the direct parent uri.
1527 // If it is provided without a thr-parent, it probably is the old behavior.
1528 $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
1529 $item['parent-uri'] = $item['thr-parent'];
1531 // Store conversation data
1532 $item = Conversation::insert($item);
1535 * Do we already have this item?
1536 * We have to check several networks since Friendica posts could be repeated
1537 * via OStatus (maybe Diasporsa as well)
1539 $duplicate = self::getDuplicateID($item);
1544 // Additional duplicate checks
1545 /// @todo Check why the first duplication check returns the item number and the second a 0
1546 if (self::isDuplicate($item)) {
1550 $item['wall'] = intval($item['wall'] ?? 0);
1551 $item['extid'] = trim($item['extid'] ?? '');
1552 $item['author-name'] = trim($item['author-name'] ?? '');
1553 $item['author-link'] = trim($item['author-link'] ?? '');
1554 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1555 $item['owner-name'] = trim($item['owner-name'] ?? '');
1556 $item['owner-link'] = trim($item['owner-link'] ?? '');
1557 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1558 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1559 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1560 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1561 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1562 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1563 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
1564 $item['location'] = trim($item['location'] ?? '');
1565 $item['coord'] = trim($item['coord'] ?? '');
1566 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1567 $item['deleted'] = 0;
1568 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1569 $item['verb'] = trim($item['verb'] ?? '');
1570 $item['object-type'] = trim($item['object-type'] ?? '');
1571 $item['object'] = trim($item['object'] ?? '');
1572 $item['target-type'] = trim($item['target-type'] ?? '');
1573 $item['target'] = trim($item['target'] ?? '');
1574 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
1575 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1576 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1577 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1578 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1579 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1580 $item['body'] = trim($item['body'] ?? '');
1581 $item['raw-body'] = trim($item['raw-body'] ?? $item['body']);
1582 $item['app'] = trim($item['app'] ?? '');
1583 $item['origin'] = intval($item['origin'] ?? 0);
1584 $item['postopts'] = trim($item['postopts'] ?? '');
1585 $item['resource-id'] = trim($item['resource-id'] ?? '');
1586 $item['event-id'] = intval($item['event-id'] ?? 0);
1587 $item['inform'] = trim($item['inform'] ?? '');
1588 $item['file'] = trim($item['file'] ?? '');
1590 // Items cannot be stored before they happen ...
1591 if ($item['created'] > DateTimeFormat::utcNow()) {
1592 $item['created'] = DateTimeFormat::utcNow();
1595 // We haven't invented time travel by now.
1596 if ($item['edited'] > DateTimeFormat::utcNow()) {
1597 $item['edited'] = DateTimeFormat::utcNow();
1600 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1602 $item['gravity'] = self::getGravity($item);
1604 $item['language'] = self::getLanguage($item);
1606 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1607 'photo' => $item['author-avatar'], 'network' => $item['network']];
1608 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
1610 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1611 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1612 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
1614 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
1615 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
1616 $item['post-type'] = self::PT_FOLLOWER;
1619 // Ensure that there is an avatar cache
1620 Contact::checkAvatarCache($item['author-id']);
1621 Contact::checkAvatarCache($item['owner-id']);
1623 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1624 $item["contact-id"] = self::contactId($item);
1626 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
1627 self::isTooOld($item)) {
1628 Logger::info('Item is too old', ['item' => $item]);
1632 if (!self::isValid($item)) {
1636 if ($item['gravity'] !== GRAVITY_PARENT) {
1637 $toplevel_parent = self::getTopLevelParent($item);
1638 if (empty($toplevel_parent)) {
1642 // If the thread originated from this node, we check the permission against the thread starter
1643 $condition = ['uri' => $toplevel_parent['uri'], 'wall' => true];
1644 $localTopLevelParent = Post::selectFirst(['uid'], $condition);
1645 if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
1649 $parent_id = $toplevel_parent['id'];
1650 $item['parent-uri'] = $toplevel_parent['uri'];
1651 $item['deleted'] = $toplevel_parent['deleted'];
1652 $item['allow_cid'] = $toplevel_parent['allow_cid'];
1653 $item['allow_gid'] = $toplevel_parent['allow_gid'];
1654 $item['deny_cid'] = $toplevel_parent['deny_cid'];
1655 $item['deny_gid'] = $toplevel_parent['deny_gid'];
1656 $parent_origin = $toplevel_parent['origin'];
1658 // Don't federate received participation messages
1659 if ($item['verb'] != Activity::FOLLOW) {
1660 $item['wall'] = $toplevel_parent['wall'];
1662 $item['wall'] = false;
1666 * If the parent is private, force privacy for the entire conversation
1667 * This differs from the above settings as it subtly allows comments from
1668 * email correspondents to be private even if the overall thread is not.
1670 if ($toplevel_parent['private']) {
1671 $item['private'] = $toplevel_parent['private'];
1675 * Edge case. We host a public forum that was originally posted to privately.
1676 * The original author commented, but as this is a comment, the permissions
1677 * weren't fixed up so it will still show the comment as private unless we fix it here.
1679 if ((intval($toplevel_parent['forum_mode']) == 1) && ($toplevel_parent['private'] != self::PUBLIC)) {
1680 $item['private'] = self::PUBLIC;
1683 // If its a post that originated here then tag the thread as "mention"
1684 if ($item['origin'] && $item['uid']) {
1685 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1686 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'uid' => $item['uid']]);
1689 // Update the contact relations
1690 Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
1692 unset($item['parent_origin']);
1695 $parent_origin = $item['origin'];
1698 // We don't store the causer link, only the id
1699 unset($item['causer-link']);
1701 // We don't store these fields anymore in the item table
1702 unset($item['author-link']);
1703 unset($item['author-name']);
1704 unset($item['author-avatar']);
1705 unset($item['author-network']);
1707 unset($item['owner-link']);
1708 unset($item['owner-name']);
1709 unset($item['owner-avatar']);
1711 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1712 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1714 // Is this item available in the global items (with uid=0)?
1715 if ($item["uid"] == 0) {
1716 $item["global"] = true;
1718 // Set the global flag on all items if this was a global item entry
1719 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1721 $item["global"] = Post::exists(['uid' => 0, 'uri' => $item["uri"]]);
1725 if (!empty($item["allow_cid"] . $item["allow_gid"] . $item["deny_cid"] . $item["deny_gid"])) {
1726 $item["private"] = self::PRIVATE;
1730 $item['edit'] = false;
1731 $item['parent'] = $parent_id;
1732 Hook::callAll('post_local', $item);
1733 unset($item['edit']);
1735 Hook::callAll('post_remote', $item);
1738 // Set after the insert because top-level posts are self-referencing
1739 unset($item['parent']);
1741 if (!empty($item['cancel'])) {
1742 Logger::log('post cancelled by addon.');
1746 if (empty($item['vid']) && !empty($item['verb'])) {
1747 $item['vid'] = Verb::getID($item['verb']);
1750 // Creates or assigns the permission set
1751 $item['psid'] = PermissionSet::getIdFromACL(
1759 unset($item['allow_cid']);
1760 unset($item['allow_gid']);
1761 unset($item['deny_cid']);
1762 unset($item['deny_gid']);
1764 // This array field is used to trigger some automatic reactions
1765 // It is mainly used in the "post_local" hook.
1766 unset($item['api_source']);
1768 if ($item['verb'] == Activity::ANNOUNCE) {
1769 self::setOwnerforResharedItem($item);
1772 // Remove all media attachments from the body and store them in the post-media table
1773 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1774 $item['raw-body'] = self::setHashtags($item['raw-body']);
1776 // Check for hashtags in the body and repair or add hashtag links
1777 $item['body'] = self::setHashtags($item['body']);
1779 if (!empty($item['attach'])) {
1780 Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1783 // Fill the cache field
1784 self::putInCache($item);
1786 if (stristr($item['verb'], Activity::POKE)) {
1787 $notify_type = Delivery::POKE;
1789 $notify_type = Delivery::POST;
1792 if (!in_array($item['verb'], self::ACTIVITIES)) {
1793 $item['icid'] = self::insertContent($item);
1794 if (empty($item['icid'])) {
1795 // This shouldn't happen
1796 Logger::warning('No content stored, quitting', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'causer-id' => ($item['causer-id'] ?? 0), 'post-type' => $item['post-type'], 'network' => $item['network']]);
1801 $body = $item['body'];
1802 $verb = $item['verb'];
1804 // We just remove everything that is content
1805 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1806 unset($item[$field]);
1809 unset($item['activity']);
1811 // Filling item related side tables
1813 // Diaspora signature
1814 if (!empty($item['diaspora_signed_text'])) {
1815 DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1818 unset($item['diaspora_signed_text']);
1820 // Attached file links
1821 if (!empty($item['file'])) {
1822 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1825 unset($item['file']);
1827 // Delivery relevant data
1828 $delivery_data = Post\DeliveryData::extractFields($item);
1829 unset($item['postopts']);
1830 unset($item['inform']);
1832 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1833 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1836 // Store tags from the body if this hadn't been handled previously in the protocol classes
1837 if (!Tag::existsForPost($item['uri-id'])) {
1838 Tag::storeFromBody($item['uri-id'], $body);
1841 if (Post\User::insert($item['uri-id'], $item['uid'], $item)) {
1842 // Remove all fields that aren't part of the item table
1843 foreach ($item as $field => $value) {
1844 if (!in_array($field, $structure['item'])) {
1845 unset($item[$field]);
1849 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network']];
1850 if (DBA::exists('item', $condition)) {
1851 Logger::notice('Item is already inserted - aborting', $condition);
1855 $result = DBA::insert('item', $item);
1857 // When the item was successfully stored we fetch the ID of the item.
1858 $current_post = DBA::lastInsertId();
1860 Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1864 if (empty($current_post) || !DBA::isResult($result)) {
1865 // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1866 Logger::warning('Could not store item. it will be spooled', ['result' => $result, 'id' => $current_post]);
1867 self::spool($orig_item);
1871 Logger::notice('created item', ['id' => $current_post, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1873 if (!$parent_id || ($item['gravity'] === GRAVITY_PARENT)) {
1874 $parent_id = $current_post;
1878 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1880 $item['id'] = $current_post;
1881 $item['parent'] = $parent_id;
1883 // update the commented timestamp on the parent
1884 if (DI::config()->get('system', 'like_no_comment')) {
1885 // Update when it is a comment
1886 $update_commented = in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1888 // Update when it isn't a follow or tag verb
1889 $update_commented = !in_array($verb, [Activity::FOLLOW, Activity::TAG]);
1892 if ($update_commented) {
1893 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1895 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1898 if ($item['gravity'] === GRAVITY_PARENT) {
1899 self::addThread($current_post);
1901 self::updateThread($parent_id);
1904 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1905 if (self::tagDeliver($item['uid'], $current_post)) {
1906 // Get the user information for the logging
1907 $user = User::getById($uid);
1909 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1914 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1915 if (DBA::isResult($posted_item)) {
1917 Hook::callAll('post_local_end', $posted_item);
1919 Hook::callAll('post_remote_end', $posted_item);
1922 Logger::log('new item not found in DB, id ' . $current_post);
1926 if ($item['gravity'] === GRAVITY_PARENT) {
1927 self::addShadow($current_post);
1929 self::addShadowPost($current_post);
1932 self::updateContact($item);
1934 UserItem::setNotification($current_post);
1936 check_user_notification($current_post);
1938 // Distribute items to users who subscribed to their tags
1939 self::distributeByTags($item);
1941 // Automatically reshare the item if the "remote_self" option is selected
1942 self::autoReshare($item);
1944 $transmit = $notify || ($item['visible'] && ($parent_origin || $item['origin']));
1947 $transmit_item = Post::selectFirst(['verb', 'origin'], ['id' => $item['id']]);
1948 // Don't relay participation messages
1949 if (($transmit_item['verb'] == Activity::FOLLOW) &&
1950 (!$transmit_item['origin'] || ($item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1951 Logger::info('Participation messages will not be relayed', ['item' => $item['id'], 'uri' => $item['uri'], 'verb' => $transmit_item['verb']]);
1957 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1960 return $current_post;
1964 * Change the owner of a parent item if it had been shared by a forum
1966 * (public) forum posts in the new format consist of the regular post by the author
1967 * followed by an announce message sent from the forum account.
1968 * Changing the owner helps in grouping forum posts.
1970 * @param array $item
1973 private static function setOwnerforResharedItem(array $item)
1975 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-type'],
1976 ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1977 if (!DBA::isResult($parent)) {
1978 Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1982 $author = Contact::selectFirst(['url', 'contact-type'], ['id' => $item['author-id']]);
1983 if (!DBA::isResult($author)) {
1984 Logger::error('Author not found', ['id' => $item['author-id']]);
1988 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1989 if (empty($cid) || !Contact::isSharing($cid, $item['uid'])) {
1990 Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid']]);
1994 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1995 if ($parent['post-type'] == self::PT_ANNOUNCEMENT) {
1996 Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2000 if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
2001 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
2004 self::update(['post-type' => self::PT_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
2005 Logger::info('Set announcement post-type', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
2009 self::update(['owner-id' => $item['author-id'], 'contact-id' => $cid], ['id' => $parent['id']]);
2010 Logger::info('Change owner of the parent', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'owner-id' => $item['author-id'], 'contact-id' => $cid]);
2014 * Distribute the given item to users who subscribed to their tags
2016 * @param array $item Processed item
2018 private static function distributeByTags(array $item)
2020 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
2024 $uids = Tag::getUIDListByURIId($item['uri-id']);
2025 foreach ($uids as $uid) {
2026 if (Contact::isSharing($item['author-id'], $uid)) {
2029 $fields = ['post-type' => self::PT_TAG];
2032 $stored = self::storeForUserByUriId($item['uri-id'], $uid, $fields);
2033 Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'fields' => $fields, 'stored' => $stored]);
2038 * Insert a new item content entry
2040 * @param array $item The item fields that are to be inserted
2041 * @throws \Exception
2043 private static function insertContent(array $item)
2045 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2047 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2048 if (isset($item[$field])) {
2049 $fields[$field] = $item[$field];
2053 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2054 if (DBA::isResult($item_content)) {
2055 $icid = $item_content['id'];
2056 Logger::info('Existing content found', ['icid' => $icid, 'uri' => $item['uri']]);
2060 DBA::replace('item-content', $fields);
2062 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2063 if (DBA::isResult($item_content)) {
2064 $icid = $item_content['id'];
2065 Logger::notice('Content inserted', ['icid' => $icid, 'uri' => $item['uri']]);
2069 // This shouldn't happen.
2070 Logger::error("Content wasn't inserted", $item);
2075 * Update existing item content entries
2077 * @param array $item The item fields that are to be changed
2078 * @param array $condition The condition for finding the item content entries
2079 * @throws \Exception
2081 private static function updateContent($item, $condition)
2083 // We have to select only the fields from the "item-content" table
2085 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2086 if (isset($item[$field])) {
2087 $fields[$field] = $item[$field];
2091 if (empty($fields)) {
2095 DBA::update('item-content', $fields, $condition, true);
2096 Logger::info('Updated content', ['condition' => $condition]);
2100 * Distributes public items to the receivers
2102 * @param integer $itemid Item ID that should be added
2103 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2104 * @throws \Exception
2106 public static function distribute($itemid, $signed_text = '')
2108 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2109 $parent = Post::selectFirst(['owner-id'], $condition);
2110 if (!DBA::isResult($parent)) {
2114 // Only distribute public items from native networks
2115 $condition = ['id' => $itemid, 'uid' => 0,
2116 'network' => array_merge(Protocol::FEDERATED ,['']),
2117 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2118 $item = Post::selectFirst(self::ITEM_FIELDLIST, $condition);
2119 if (!DBA::isResult($item)) {
2123 $origin = $item['origin'];
2127 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2128 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2129 if (!DBA::isResult($owner)) {
2133 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2134 $contacts = DBA::select('contact', ['uid'], $condition);
2135 while ($contact = DBA::fetch($contacts)) {
2136 if ($contact['uid'] == 0) {
2140 $users[$contact['uid']] = $contact['uid'];
2142 DBA::close($contacts);
2144 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2145 $contacts = DBA::select('contact', ['uid'], $condition);
2146 while ($contact = DBA::fetch($contacts)) {
2147 if ($contact['uid'] == 0) {
2151 $users[$contact['uid']] = $contact['uid'];
2153 DBA::close($contacts);
2155 if (!empty($owner['alias'])) {
2156 $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
2157 $contacts = DBA::select('contact', ['uid'], $condition);
2158 while ($contact = DBA::fetch($contacts)) {
2159 if ($contact['uid'] == 0) {
2163 $users[$contact['uid']] = $contact['uid'];
2165 DBA::close($contacts);
2170 if ($item['uri'] != $item['parent-uri']) {
2171 $parents = Post::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2172 while ($parent = Post::fetch($parents)) {
2173 $users[$parent['uid']] = $parent['uid'];
2174 if ($parent['origin'] && !$origin) {
2175 $origin_uid = $parent['uid'];
2178 DBA::close($parents);
2181 foreach ($users as $uid) {
2182 if ($origin_uid == $uid) {
2183 $item['diaspora_signed_text'] = $signed_text;
2185 self::storeForUser($item, $uid);
2190 * Store a public item defined by their URI-ID for the given users
2192 * @param integer $uri_id URI-ID of the given item
2193 * @param integer $uid The user that will receive the item entry
2194 * @param array $fields Additional fields to be stored
2195 * @return integer stored item id
2197 public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [])
2199 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['uri-id' => $uri_id, 'uid' => 0]);
2200 if (!DBA::isResult($item)) {
2204 if (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED)) {
2205 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']]);
2209 $item['post-type'] = self::PT_STORED;
2211 $item = array_merge($item, $fields);
2213 $stored = self::storeForUser($item, $uid);
2214 Logger::info('Public item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
2219 * Store a public item array for the given users
2221 * @param array $item The item entry that will be stored
2222 * @param integer $uid The user that will receive the item entry
2223 * @return integer stored item id
2224 * @throws \Exception
2226 private static function storeForUser(array $item, int $uid)
2228 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
2229 Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
2234 unset($item['parent']);
2235 unset($item['mention']);
2236 unset($item['starred']);
2237 unset($item['unseen']);
2238 unset($item['psid']);
2240 $item['uid'] = $uid;
2241 $item['origin'] = 0;
2244 if ($item['gravity'] == GRAVITY_PARENT) {
2245 $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
2247 $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
2250 if (!empty($contact['id'])) {
2251 $item['contact-id'] = $contact['id'];
2253 // Shouldn't happen at all
2254 Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
2255 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2256 if (!DBA::isResult($self)) {
2257 // Shouldn't happen even less
2258 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
2261 $item['contact-id'] = $self['id'];
2264 /// @todo Handling of "event-id"
2267 if ($item['gravity'] == GRAVITY_PARENT) {
2268 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2269 if (DBA::isResult($contact)) {
2270 $notify = self::isRemoteSelf($contact, $item);
2274 $distributed = self::insert($item, $notify, true);
2276 if (!$distributed) {
2277 Logger::info("Distributed public item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
2279 Logger::info('Distributed public item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
2281 return $distributed;
2285 * Add a shadow entry for a given item id that is a thread starter
2287 * We store every public item entry additionally with the user id "0".
2288 * This is used for the community page and for the search.
2289 * It is planned that in the future we will store public item entries only once.
2291 * @param integer $itemid Item ID that should be added
2292 * @throws \Exception
2294 private static function addShadow($itemid)
2296 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2297 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2298 $item = Post::selectFirst($fields, $condition);
2300 if (!DBA::isResult($item)) {
2304 // is it already a copy?
2305 if (($itemid == 0) || ($item['uid'] == 0)) {
2309 // Is it a visible public post?
2310 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == self::PRIVATE)) {
2314 // is it an entry from a connector? Only add an entry for natively connected networks
2315 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2319 if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
2323 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2325 if (DBA::isResult($item)) {
2326 // Preparing public shadow (removing user specific data)
2329 unset($item['parent']);
2330 unset($item['wall']);
2331 unset($item['mention']);
2332 unset($item['origin']);
2333 unset($item['starred']);
2334 unset($item['postopts']);
2335 unset($item['inform']);
2336 unset($item['post-type']);
2337 if ($item['uri'] == $item['parent-uri']) {
2338 $item['contact-id'] = $item['owner-id'];
2340 $item['contact-id'] = $item['author-id'];
2343 $public_shadow = self::insert($item, false, true);
2345 Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
2350 * Add a shadow entry for a given item id that is a comment
2352 * This function does the same like the function above - but for comments
2354 * @param integer $itemid Item ID that should be added
2355 * @throws \Exception
2357 private static function addShadowPost($itemid)
2359 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2360 if (!DBA::isResult($item)) {
2364 // Is it a toplevel post?
2365 if ($item['gravity'] == GRAVITY_PARENT) {
2366 self::addShadow($itemid);
2370 // Is this a shadow entry?
2371 if ($item['uid'] == 0) {
2375 // Is there a shadow parent?
2376 if (!Post::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2380 // Is there already a shadow entry?
2381 if (Post::exists(['uri' => $item['uri'], 'uid' => 0])) {
2385 // Save "origin" and "parent" state
2386 $origin = $item['origin'];
2387 $parent = $item['parent'];
2389 // Preparing public shadow (removing user specific data)
2392 unset($item['parent']);
2393 unset($item['wall']);
2394 unset($item['mention']);
2395 unset($item['origin']);
2396 unset($item['starred']);
2397 unset($item['postopts']);
2398 unset($item['inform']);
2399 unset($item['post-type']);
2400 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2402 $public_shadow = self::insert($item, false, true);
2404 Logger::info('Stored public shadow', ['uri' => $item['uri'], 'id' => $public_shadow]);
2406 // If this was a comment to a Diaspora post we don't get our comment back.
2407 // This means that we have to distribute the comment by ourselves.
2408 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2409 self::distribute($public_shadow);
2414 * Adds a language specification in a "language" element of given $arr.
2415 * Expects "body" element to exist in $arr.
2417 * @param array $item
2418 * @return string detected language
2419 * @throws \Text_LanguageDetect_Exception
2421 private static function getLanguage(array $item)
2423 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
2427 // Convert attachments to links
2428 $naked_body = BBCode::removeAttachment($item['body']);
2429 if (empty($naked_body)) {
2433 // Remove links and pictures
2434 $naked_body = BBCode::removeLinks($naked_body);
2436 // Convert the title and the body to plain text
2437 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
2439 // Remove possibly remaining links
2440 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
2442 if (empty($naked_body)) {
2446 $ld = new Language(DI::l10n()->getAvailableLanguages());
2447 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
2448 if (is_array($languages)) {
2449 return json_encode($languages);
2455 public static function getLanguageMessage(array $item)
2457 $iso639 = new \Matriphe\ISO639\ISO639;
2459 $used_languages = '';
2460 foreach (json_decode($item['language'], true) as $language => $reliability) {
2461 $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
2463 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
2464 return $used_languages;
2468 * Creates an unique guid out of a given uri
2470 * @param string $uri uri of an item entry
2471 * @param string $host hostname for the GUID prefix
2472 * @return string unique guid
2474 public static function guidFromUri($uri, $host)
2476 // Our regular guid routine is using this kind of prefix as well
2477 // We have to avoid that different routines could accidentally create the same value
2478 $parsed = parse_url($uri);
2480 // We use a hash of the hostname as prefix for the guid
2481 $guid_prefix = hash("crc32", $host);
2483 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2484 unset($parsed["scheme"]);
2486 // Glue it together to be able to make a hash from it
2487 $host_id = implode("/", $parsed);
2489 // We could use any hash algorithm since it isn't a security issue
2490 $host_hash = hash("ripemd128", $host_id);
2492 return $guid_prefix.$host_hash;
2496 * generate an unique URI
2498 * @param integer $uid User id
2499 * @param string $guid An existing GUID (Otherwise it will be generated)
2502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2504 public static function newURI($uid, $guid = "")
2507 $guid = System::createUUID();
2510 return DI::baseUrl()->get() . '/objects/' . $guid;
2514 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2516 * This can be used to filter for inactive contacts.
2517 * Only do this for public postings to avoid privacy problems, since poco data is public.
2518 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2520 * @param array $arr Contains the just posted item record
2521 * @throws \Exception
2523 private static function updateContact($arr)
2525 // Unarchive the author
2526 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2527 if (DBA::isResult($contact)) {
2528 Contact::unmarkForArchival($contact);
2531 // Unarchive the contact if it's not our own contact
2532 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2533 if (DBA::isResult($contact)) {
2534 Contact::unmarkForArchival($contact);
2537 /// @todo On private posts we could obfuscate the date
2538 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
2540 // Is it a forum? Then we don't care about the rules from above
2541 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2542 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2548 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2549 // So we have to ensure to only update the last item when it had been our own post,
2550 // or it had been done by a "regular" contact.
2551 if (!empty($arr['wall'])) {
2552 $condition = ['id' => $arr['contact-id']];
2554 $condition = ['id' => $arr['contact-id'], 'self' => false];
2556 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2558 // Now do the same for the system wide contacts with uid=0
2559 if ($arr['private'] != self::PRIVATE) {
2560 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2561 ['id' => $arr['owner-id']]);
2563 if ($arr['owner-id'] != $arr['author-id']) {
2564 DBA::update('contact', ['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
2565 ['id' => $arr['author-id']]);
2570 public static function setHashtags($body)
2572 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code'], function ($body) {
2573 $tags = BBCode::getTags($body);
2576 if (!count($tags)) {
2580 // This sorting is important when there are hashtags that are part of other hashtags
2581 // Otherwise there could be problems with hashtags like #test and #test2
2582 // Because of this we are sorting from the longest to the shortest tag.
2583 usort($tags, function ($a, $b) {
2584 return strlen($b) <=> strlen($a);
2587 $URLSearchString = "^\[\]";
2589 // All hashtags should point to the home server if "local_tags" is activated
2590 if (DI::config()->get('system', 'local_tags')) {
2591 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2592 "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
2595 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2596 $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2598 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2601 $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2603 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2606 $body = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2608 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2611 // Repair recursive urls
2612 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2615 foreach ($tags as $tag) {
2616 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2620 $basetag = str_replace('_', ' ', substr($tag, 1));
2621 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2623 $body = str_replace($tag, $newtag, $body);
2626 // Convert back the masked hashtags
2627 $body = str_replace("#", "#", $body);
2636 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2639 * @param int $item_id
2640 * @return boolean true if item was deleted, else false
2641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2642 * @throws \ImagickException
2644 private static function tagDeliver($uid, $item_id)
2648 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2649 if (!DBA::isResult($user)) {
2653 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2654 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2656 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2657 if (!DBA::isResult($item)) {
2661 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2664 * Diaspora uses their own hardwired link URL in @-tags
2665 * instead of the one we supply with webfinger
2667 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2669 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2671 foreach ($matches as $mtch) {
2672 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2674 Logger::log('mention found: ' . $mtch[2]);
2680 $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2681 foreach ($tags as $tag) {
2682 if (Strings::compareLink($link, $tag['url']) || Strings::compareLink($dlink, $tag['url'])) {
2684 DI::logger()->info('mention found in tag.', ['url' => $tag['url']]);
2690 if (($community_page || $prvgroup) &&
2691 !$item['wall'] && !$item['origin'] && ($item['gravity'] == GRAVITY_PARENT)) {
2692 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2693 DBA::delete('item', ['id' => $item_id]);
2699 $arr = ['item' => $item, 'user' => $user];
2701 Hook::callAll('tagged', $arr);
2703 if (!$community_page && !$prvgroup) {
2708 * tgroup delivery - setup a second delivery chain
2709 * prevent delivery looping - only proceed
2710 * if the message originated elsewhere and is a top-level post
2712 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2716 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2717 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2718 if (!DBA::isResult($self)) {
2722 $owner_id = Contact::getIdForURL($self['url']);
2724 // also reset all the privacy bits to the forum default permissions
2726 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2728 $psid = PermissionSet::getIdFromACL(
2736 $forum_mode = ($prvgroup ? 2 : 1);
2738 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2739 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2740 self::update($fields, ['id' => $item_id]);
2742 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2744 self::performActivity($item_id, 'announce', $uid);
2750 * Automatically reshare the item if the "remote_self" option is selected
2752 * @param array $item
2755 private static function autoReshare(array $item)
2757 if ($item['gravity'] != GRAVITY_PARENT) {
2761 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2765 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2769 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2771 self::performActivity($item['id'], 'announce', $item['uid']);
2774 public static function isRemoteSelf($contact, &$datarray)
2776 if (!$contact['remote_self']) {
2780 // Prevent the forwarding of posts that are forwarded
2781 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2782 Logger::info('Already forwarded');
2786 // Prevent to forward already forwarded posts
2787 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2788 Logger::info('Already forwarded (second test)');
2792 // Only forward posts
2793 if ($datarray["verb"] != Activity::POST) {
2794 Logger::info('No post');
2798 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2799 Logger::info('Not public');
2803 $datarray2 = $datarray;
2804 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2805 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2806 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2807 ['uid' => $contact['uid'], 'self' => true]);
2808 if (DBA::isResult($self)) {
2809 $datarray['contact-id'] = $self["id"];
2811 $datarray['owner-name'] = $self["name"];
2812 $datarray['owner-link'] = $self["url"];
2813 $datarray['owner-avatar'] = $self["thumb"];
2815 $datarray['author-name'] = $datarray['owner-name'];
2816 $datarray['author-link'] = $datarray['owner-link'];
2817 $datarray['author-avatar'] = $datarray['owner-avatar'];
2819 unset($datarray['edited']);
2821 unset($datarray['network']);
2822 unset($datarray['owner-id']);
2823 unset($datarray['author-id']);
2826 if ($contact['network'] != Protocol::FEED) {
2827 $old_uri_id = $datarray["uri-id"] ?? 0;
2828 $datarray["guid"] = System::createUUID();
2829 unset($datarray["plink"]);
2830 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2831 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2832 $datarray["extid"] = Protocol::DFRN;
2833 $urlpart = parse_url($datarray2['author-link']);
2834 $datarray["app"] = $urlpart["host"];
2835 if (!empty($old_uri_id)) {
2836 Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2839 unset($datarray["parent-uri"]);
2840 unset($datarray["thr-parent"]);
2842 $datarray['private'] = self::PUBLIC;
2846 if ($contact['network'] != Protocol::FEED) {
2847 // Store the original post
2848 $result = self::insert($datarray2);
2849 Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2851 $datarray["app"] = "Feed";
2855 // Trigger automatic reactions for addons
2856 $datarray['api_source'] = true;
2858 // We have to tell the hooks who we are - this really should be improved
2859 $_SESSION['authenticated'] = true;
2860 $_SESSION['uid'] = $contact['uid'];
2862 return (bool)$result;
2869 * @param array $item
2872 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2873 * @throws \ImagickException
2875 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2877 if (DI::config()->get('system', 'disable_embedded')) {
2881 Logger::info('check for photos');
2882 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2887 $img_start = strpos($orig_body, '[img');
2888 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2889 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2891 while (($img_st_close !== false) && ($img_len !== false)) {
2892 $img_st_close++; // make it point to AFTER the closing bracket
2893 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2895 Logger::info('found photo', ['image' => $image]);
2897 if (stristr($image, $site . '/photo/')) {
2898 // Only embed locally hosted photos
2900 $i = basename($image);
2901 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2902 $x = strpos($i, '-');
2905 $res = substr($i, $x + 1);
2906 $i = substr($i, 0, $x);
2907 $photo = Photo::getPhotoForUser($uid, $i, $res);
2908 if (DBA::isResult($photo)) {
2910 * Check to see if we should replace this photo link with an embedded image
2911 * 1. No need to do so if the photo is public
2912 * 2. If there's a contact-id provided, see if they're in the access list
2913 * for the photo. If so, embed it.
2914 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2915 * permissions, regardless of order but first check to see if they're an exact
2916 * match to save some processing overhead.
2918 if (self::hasPermissions($photo)) {
2920 $recips = self::enumeratePermissions($photo);
2921 if (in_array($cid, $recips)) {
2925 if (self::samePermissions($uid, $item, $photo)) {
2931 $photo_img = Photo::getImageForPhoto($photo);
2932 // If a custom width and height were specified, apply before embedding
2933 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2934 Logger::info('scaling photo');
2936 $width = intval($match[1]);
2937 $height = intval($match[2]);
2939 $photo_img->scaleDown(max($width, $height));
2942 $data = $photo_img->asString();
2943 $type = $photo_img->getType();
2945 Logger::info('replacing photo');
2946 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2947 Logger::debug('replaced', ['image' => $image]);
2953 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2954 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2955 if ($orig_body === false) {
2959 $img_start = strpos($orig_body, '[img');
2960 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2961 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2964 $new_body = $new_body . $orig_body;
2969 private static function hasPermissions($obj)
2971 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2972 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2975 private static function samePermissions($uid, $obj1, $obj2)
2977 // first part is easy. Check that these are exactly the same.
2978 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2979 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2980 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2981 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2985 // This is harder. Parse all the permissions and compare the resulting set.
2986 $recipients1 = self::enumeratePermissions($obj1);
2987 $recipients2 = self::enumeratePermissions($obj2);
2991 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2992 return ($recipients1 == $recipients2);
2996 * Returns an array of contact-ids that are allowed to see this object
2998 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2999 * @param bool $check_dead Prunes unavailable contacts from the result
3001 * @throws \Exception
3003 public static function enumeratePermissions(array $obj, bool $check_dead = false)
3005 $aclFormater = DI::aclFormatter();
3007 $allow_people = $aclFormater->expand($obj['allow_cid']);
3008 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
3009 $deny_people = $aclFormater->expand($obj['deny_cid']);
3010 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
3011 $recipients = array_unique(array_merge($allow_people, $allow_groups));
3012 $deny = array_unique(array_merge($deny_people, $deny_groups));
3013 $recipients = array_diff($recipients, $deny);
3017 public static function expire(int $uid, int $days, string $network = "", bool $force = false)
3019 if (!$uid || ($days < 1)) {
3023 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
3024 $uid, GRAVITY_PARENT];
3027 * $expire_network_only = save your own wall posts
3028 * and just expire conversations started by others
3030 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
3032 if ($expire_network_only) {
3033 $condition[0] .= " AND NOT `wall`";
3036 if ($network != "") {
3037 $condition[0] .= " AND `network` = ?";
3038 $condition[] = $network;
3041 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3042 $condition[] = $days;
3044 $items = Post::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3046 if (!DBA::isResult($items)) {
3050 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
3052 // Forcing expiring of items - but not notes and marked items
3054 $expire_items = true;
3057 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3058 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3059 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3063 $priority = DI::config()->get('system', 'expire-notify-priority');
3065 while ($item = Post::fetch($items)) {
3066 // don't expire filed items
3068 if (strpos($item['file'], '[') !== false) {
3072 // Only expire posts, not photos and photo comments
3074 if (!$expire_photos && strlen($item['resource-id'])) {
3076 } elseif (!$expire_starred && intval($item['starred'])) {
3078 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == self::PT_PERSONAL_NOTE))) {
3080 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
3084 self::markForDeletionById($item['id'], $priority);
3089 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3092 public static function firstPostDate($uid, $wall = false)
3094 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3095 $params = ['order' => ['received' => false]];
3096 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3097 if (DBA::isResult($thread)) {
3098 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3104 * add/remove activity to an item
3106 * Toggle activities as like,dislike,attend of an item
3108 * @param int $item_id
3109 * @param string $verb
3110 * Activity verb. One of
3111 * like, unlike, dislike, undislike, attendyes, unattendyes,
3112 * attendno, unattendno, attendmaybe, unattendmaybe,
3113 * announce, unannouce
3115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3116 * @throws \ImagickException
3117 * @hook 'post_local_end'
3119 * 'post_id' => ID of posted item
3121 public static function performActivity(int $item_id, string $verb, int $uid)
3127 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
3129 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
3130 if (!DBA::isResult($item)) {
3131 Logger::log('like: unknown item ' . $item_id);
3135 $item_uri = $item['uri'];
3137 if (!in_array($item['uid'], [0, $uid])) {
3141 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
3142 $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid);
3143 if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
3144 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
3145 if (!DBA::isResult($item)) {
3146 Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'item-uri' => $item_uri]);
3152 // Retrieves the local post owner
3153 $owner = User::getOwnerDataById($uid);
3154 if (empty($owner)) {
3155 Logger::info('Empty owner for user', ['uid' => $uid]);
3159 // Retrieve the current logged in user's public contact
3160 $author_id = Contact::getIdForURL($owner['url']);
3161 if (empty($author_id)) {
3162 Logger::info('Empty public contact');
3170 $activity = Activity::LIKE;
3174 $activity = Activity::DISLIKE;
3178 $activity = Activity::ATTEND;
3182 $activity = Activity::ATTENDNO;
3185 case 'unattendmaybe':
3186 $activity = Activity::ATTENDMAYBE;
3190 $activity = Activity::FOLLOW;
3194 $activity = Activity::ANNOUNCE;
3197 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
3201 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
3203 // Enable activity toggling instead of on/off
3204 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3206 // Look for an existing verb row
3207 // Event participation activities are mutually exclusive, only one of them can exist at all times.
3208 if ($event_verb_flag) {
3209 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3211 // Translate to the index based activity index
3213 foreach ($verbs as $verb) {
3214 $vids[] = Verb::getID($verb);
3217 $vids = Verb::getID($activity);
3220 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3221 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3222 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
3224 if (DBA::isResult($like_item)) {
3226 * Truth table for existing activities
3228 * | Inputs || Outputs |
3229 * |----------------------------||-------------------|
3230 * | Mode | Event | Same verb || Delete? | Return? |
3231 * |--------|-------|-----------||---------|---------|
3232 * | create | Yes | Yes || No | Yes |
3233 * | create | Yes | No || Yes | No |
3234 * | create | No | Yes || No | Yes |
3235 * | create | No | No || N/A†|
3236 * | delete | Yes | Yes || Yes | N/A‡ |
3237 * | delete | Yes | No || No | N/A‡ |
3238 * | delete | No | Yes || Yes | N/A‡ |
3239 * | delete | No | No || N/A†|
3240 * |--------|-------|-----------||---------|---------|
3241 * | A | B | C || A xor C | !B or C |
3243 * †Can't happen: It's impossible to find an existing non-event activity without
3244 * the same verb because we are only looking for this single verb.
3246 * ‡ The "mode = delete" is returning early whether an existing activity was found or not.
3248 if ($mode == 'create' xor $like_item['verb'] == $activity) {
3249 self::markForDeletionById($like_item['id']);
3252 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3257 // No need to go further if we aren't creating anything
3258 if ($mode == 'delete') {
3262 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3265 'guid' => System::createUUID(),
3266 'uri' => self::newURI($item['uid']),
3267 'uid' => $item['uid'],
3268 'contact-id' => $owner['id'],
3269 'wall' => $item['wall'],
3271 'network' => Protocol::DFRN,
3272 'protocol' => Conversation::PARCEL_DIRECT,
3273 'direction' => Conversation::PUSH,
3274 'gravity' => GRAVITY_ACTIVITY,
3275 'parent' => $item['id'],
3276 'thr-parent' => $item['uri'],
3277 'owner-id' => $author_id,
3278 'author-id' => $author_id,
3279 'body' => $activity,
3280 'verb' => $activity,
3281 'object-type' => $objtype,
3282 'allow_cid' => $item['allow_cid'],
3283 'allow_gid' => $item['allow_gid'],
3284 'deny_cid' => $item['deny_cid'],
3285 'deny_gid' => $item['deny_gid'],
3290 $signed = Diaspora::createLikeSignature($uid, $new_item);
3291 if (!empty($signed)) {
3292 $new_item['diaspora_signed_text'] = json_encode($signed);
3295 $new_item_id = self::insert($new_item);
3297 // If the parent item isn't visible then set it to visible
3298 if (!$item['visible']) {
3299 self::update(['visible' => true], ['id' => $item['id']]);
3302 $new_item['id'] = $new_item_id;
3304 Hook::callAll('post_local_end', $new_item);
3309 private static function addThread($itemid, $onlyshadow = false)
3311 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3312 'moderated', 'visible', 'starred', 'contact-id', 'post-type', 'uri-id',
3313 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3314 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3315 $item = Post::selectFirst($fields, $condition);
3317 if (!DBA::isResult($item)) {
3321 $item['iid'] = $itemid;
3324 $result = DBA::replace('thread', $item);
3326 Logger::info('Add thread', ['item' => $itemid, 'result' => $result]);
3330 private static function updateThread($itemid, $setmention = false)
3332 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3333 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id', 'uri-id',
3334 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3336 $item = Post::selectFirst($fields, ['id' => $itemid, 'gravity' => GRAVITY_PARENT]);
3337 if (!DBA::isResult($item)) {
3342 $item["mention"] = 1;
3347 foreach ($item as $field => $data) {
3348 if (!in_array($field, ["guid"])) {
3349 $fields[$field] = $data;
3353 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3355 Logger::info('Update thread', ['item' => $itemid, 'guid' => $item["guid"], 'result' => $result]);
3358 private static function deleteThread($itemid, $itemuri = "")
3360 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3361 if (!DBA::isResult($item)) {
3362 Logger::info('No thread found', ['id' => $itemid]);
3366 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3368 Logger::info('Deleted thread', ['item' => $itemid, 'result' => $result]);
3370 if ($itemuri != "") {
3371 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3372 if (!Post::exists($condition)) {
3373 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3374 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3380 * Fetch the SQL condition for the given user id
3382 * @param integer $owner_id User ID for which the permissions should be fetched
3383 * @return array condition
3385 public static function getPermissionsConditionArrayByUserId(int $owner_id)
3387 $local_user = local_user();
3388 $remote_user = Session::getRemoteContactID($owner_id);
3390 // default permissions - anonymous user
3391 $condition = ["`private` != ?", self::PRIVATE];
3393 if ($local_user && ($local_user == $owner_id)) {
3394 // Profile owner - everything is visible
3396 } elseif ($remote_user) {
3397 // Authenticated visitor - fetch the matching permissionsets
3398 $set = PermissionSet::get($owner_id, $remote_user);
3400 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
3401 AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
3402 self::PRIVATE, self::PRIVATE];
3403 $condition = array_merge($condition, $set);
3410 public static function getPermissionsSQLByUserId($owner_id)
3412 $local_user = local_user();
3413 $remote_user = Session::getRemoteContactID($owner_id);
3416 * Construct permissions
3418 * default permissions - anonymous user
3420 $sql = sprintf(" AND `private` != %d", self::PRIVATE);
3422 // Profile owner - everything is visible
3423 if ($local_user && ($local_user == $owner_id)) {
3425 } elseif ($remote_user) {
3427 * Authenticated visitor. Unless pre-verified,
3428 * check that the contact belongs to this $owner_id
3429 * and load the groups the visitor belongs to.
3430 * If pre-verified, the caller is expected to have already
3431 * done this and passed the groups into this function.
3433 $set = PermissionSet::get($owner_id, $remote_user);
3436 $sql_set = sprintf(" OR (`private` = %d AND `wall` AND `psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3441 $sql = sprintf(" AND (`private` != %d", self::PRIVATE) . $sql_set . ")";
3448 * get translated item type
3453 public static function postType($item)
3455 if (!empty($item['event-id'])) {
3456 return DI::l10n()->t('event');
3457 } elseif (!empty($item['resource-id'])) {
3458 return DI::l10n()->t('photo');
3459 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
3460 return DI::l10n()->t('activity');
3461 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
3462 return DI::l10n()->t('comment');
3465 return DI::l10n()->t('post');
3469 * Sets the "rendered-html" field of the provided item
3471 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3473 * @param array $item
3474 * @param bool $update
3476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3477 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3479 public static function putInCache(&$item, $update = false)
3481 // Save original body to prevent addons to modify it
3482 $body = $item['body'];
3484 $rendered_hash = $item['rendered-hash'] ?? '';
3485 $rendered_html = $item['rendered-html'] ?? '';
3487 if ($rendered_hash == ''
3488 || $rendered_html == ''
3489 || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
3490 || DI::config()->get('system', 'ignore_cache')
3492 self::addRedirToImageTags($item);
3494 $item['rendered-html'] = BBCode::convert($item['body']);
3495 $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
3497 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3498 Hook::callAll('put_item_in_cache', $hook_data);
3499 $item['rendered-html'] = $hook_data['rendered-html'];
3500 $item['rendered-hash'] = $hook_data['rendered-hash'];
3503 // Force an update if the generated values differ from the existing ones
3504 if ($rendered_hash != $item['rendered-hash']) {
3508 // Only compare the HTML when we forcefully ignore the cache
3509 if (DI::config()->get('system', 'ignore_cache') && ($rendered_html != $item['rendered-html'])) {
3513 if ($update && !empty($item['id'])) {
3516 'rendered-html' => $item['rendered-html'],
3517 'rendered-hash' => $item['rendered-hash']
3519 ['id' => $item['id']]
3524 $item['body'] = $body;
3528 * Find any non-embedded images in private items and add redir links to them
3530 * @param array &$item The field array of an item row
3532 private static function addRedirToImageTags(array &$item)
3537 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3539 foreach ($matches as $mtch) {
3540 if (strpos($mtch[1], '/redir') !== false) {
3544 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3545 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3546 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3553 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3554 * If attach is true, also add icons for item attachments.
3556 * @param array $item
3557 * @param boolean $attach
3558 * @param boolean $is_preview
3559 * @return string item body html
3560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3561 * @throws \ImagickException
3562 * @hook prepare_body_init item array before any work
3563 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3564 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3565 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3567 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3570 Hook::callAll('prepare_body_init', $item);
3572 // In order to provide theme developers more possibilities, event items
3573 // are treated differently.
3574 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3575 $ev = Event::getItemHTML($item);
3579 $tags = Tag::populateFromItem($item);
3581 $item['tags'] = $tags['tags'];
3582 $item['hashtags'] = $tags['hashtags'];
3583 $item['mentions'] = $tags['mentions'];
3585 // Compile eventual content filter reasons
3586 $filter_reasons = [];
3587 if (!$is_preview && public_contact() != $item['author-id']) {
3588 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3589 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3594 'filter_reasons' => $filter_reasons
3596 Hook::callAll('prepare_body_content_filter', $hook_data);
3597 $filter_reasons = $hook_data['filter_reasons'];
3601 // Update the cached values if there is no "zrl=..." on the links.
3602 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3604 // Or update it if the current viewer is the intented viewer.
3605 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3609 self::putInCache($item, $update);
3610 $s = $item["rendered-html"];
3615 'preview' => $is_preview,
3616 'filter_reasons' => $filter_reasons
3618 Hook::callAll('prepare_body', $hook_data);
3619 $s = $hook_data['html'];
3623 // Replace the blockquotes with quotes that are used in mails.
3624 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3625 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3631 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
3632 $mime = $attachment['mimetype'];
3634 $the_url = Contact::magicLinkById($item['author-id'], $attachment['url']);
3636 if (strpos($mime, 'video') !== false) {
3639 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3642 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3644 'id' => $item['author-id'],
3645 'title' => DI::l10n()->t('View Video'),
3652 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3654 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3655 $filesubtype = str_replace('.', '-', $filesubtype);
3658 $filesubtype = 'unkn';
3661 $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3662 $title .= ' ' . ($attachment['size'] ?? 0) . ' ' . DI::l10n()->t('bytes');
3664 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3665 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3669 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3673 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3674 $x = Map::byCoordinates(trim($item['coord']));
3676 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3680 // Replace friendica image url size with theme preference.
3681 if (!empty($a->theme_info['item_image_size'])) {
3682 $ps = $a->theme_info['item_image_size'];
3683 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3686 $s = HTML::applyContentFilter($s, $filter_reasons);
3688 $hook_data = ['item' => $item, 'html' => $s];
3689 Hook::callAll('prepare_body_final', $hook_data);
3691 return $hook_data['html'];
3695 * get private link for item
3697 * @param array $item
3698 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3699 * @throws \Exception
3701 public static function getPlink($item)
3705 'href' => "display/" . $item['guid'],
3706 'orig' => "display/" . $item['guid'],
3707 'title' => DI::l10n()->t('View on separate page'),
3708 'orig_title' => DI::l10n()->t('view on separate page'),
3711 if (!empty($item['plink'])) {
3712 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3713 $ret["title"] = DI::l10n()->t('link to source');
3715 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3717 'href' => $item['plink'],
3718 'orig' => $item['plink'],
3719 'title' => DI::l10n()->t('link to source'),
3729 * Is the given item array a post that is sent as starting post to a forum?
3731 * @param array $item
3732 * @param array $owner
3734 * @return boolean "true" when it is a forum post
3736 public static function isForumPost(array $item, array $owner = [])
3738 if (empty($owner)) {
3739 $owner = User::getOwnerDataById($item['uid']);
3740 if (empty($owner)) {
3745 if (($item['author-id'] == $item['owner-id']) ||
3746 ($owner['id'] == $item['contact-id']) ||
3747 ($item['uri'] != $item['parent-uri']) ||
3752 return Contact::isForum($item['contact-id']);
3756 * Search item id for given URI or plink
3758 * @param string $uri
3759 * @param integer $uid
3761 * @return integer item id
3763 public static function searchByLink($uri, $uid = 0)
3765 $ssl_uri = str_replace('http://', 'https://', $uri);
3766 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3768 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3769 if (DBA::isResult($item)) {
3773 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3774 if (!DBA::isResult($itemcontent)) {
3778 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3779 if (!DBA::isResult($itemuri)) {
3783 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3784 if (DBA::isResult($item)) {
3792 * Return the URI for a link to the post
3794 * @param string $uri URI or link to post
3796 * @return string URI
3798 public static function getURIByLink(string $uri)
3800 $ssl_uri = str_replace('http://', 'https://', $uri);
3801 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3803 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3804 if (DBA::isResult($item)) {
3805 return $item['uri'];
3808 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3809 if (!DBA::isResult($itemcontent)) {
3813 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3814 if (DBA::isResult($itemuri)) {
3815 return $itemuri['uri'];
3822 * Fetches item for given URI or plink
3824 * @param string $uri
3825 * @param integer $uid
3827 * @return integer item id
3829 public static function fetchByLink(string $uri, int $uid = 0)
3831 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3832 $item_id = self::searchByLink($uri, $uid);
3833 if (!empty($item_id)) {
3834 Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3838 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3839 $item_id = self::searchByLink($fetched_uri, $uid);
3841 $item_id = Diaspora::fetchByURL($uri);
3844 if (!empty($item_id)) {
3845 Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3849 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3854 * Return share data from an item array (if the item is shared item)
3855 * We are providing the complete Item array, because at some time in the future
3856 * we hopefully will define these values not in the body anymore but in some item fields.
3857 * This function is meant to replace all similar functions in the system.
3859 * @param array $item
3861 * @return array with share information
3863 public static function getShareArray($item)
3865 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3869 $attribute_string = $matches[2];
3870 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3871 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3872 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3873 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3880 * Fetch item information for shared items from the original items and adds it.
3882 * @param array $item
3884 * @return array item array with data from the original item
3886 public static function addShareDataFromOriginal(array $item)
3888 $shared = self::getShareArray($item);
3889 if (empty($shared)) {
3893 // Real reshares always have got a GUID.
3894 if (empty($shared['guid'])) {
3898 $uid = $item['uid'] ?? 0;
3900 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3901 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3902 if (!DBA::isResult($shared_item)) {
3903 if (empty($shared['link'])) {
3907 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3908 $id = self::fetchByLink($shared['link'] ?? '', $uid);
3910 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3914 $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3915 if (!DBA::isResult($shared_item)) {
3918 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3920 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3923 if (!empty($shared_item['title'])) {
3924 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3925 unset($shared_item['title']);
3927 $body = $shared_item['body'];
3930 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3931 unset($shared_item['body']);
3933 return array_merge($item, $shared_item);
3937 * Check a prospective item array against user-level permissions
3939 * @param array $item Expected keys: uri, gravity, and
3940 * author-link if is author-id is set,
3941 * owner-link if is owner-id is set,
3942 * causer-link if is causer-id is set.
3943 * @param int $user_id Local user ID
3945 * @throws \Exception
3947 protected static function isAllowedByUser(array $item, int $user_id)
3949 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3950 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3954 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3955 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3959 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3960 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3961 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3965 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3966 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);