3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Protocol\OStatus;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Security;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use Friendica\Worker\Delivery;
46 use Text_LanguageDetect;
47 use Friendica\Repository\PermissionSet as RepPermissionSet;
51 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
58 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Field list that is used to display the items
63 const DISPLAY_FIELDLIST = [
64 'uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
65 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
66 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
67 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
68 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
69 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
70 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
71 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
72 'writable', 'self', 'cid', 'alias', 'pinned',
73 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
74 'event-summary', 'event-desc', 'event-location', 'event-type',
75 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
76 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
79 // Field list that is used to deliver items via the protocols
80 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
81 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
82 'private', 'title', 'body', 'location', 'coord', 'app',
83 'attach', 'deleted', 'extid', 'post-type',
84 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
85 'author-id', 'author-link', 'owner-link', 'contact-uid',
86 'signed_text', 'signature', 'signer', 'network'];
88 // Field list for "item-content" table that is mixed with the item table
89 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
90 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
91 'object-type', 'object', 'target-type', 'target', 'plink'];
93 // Field list for "item-content" table that is not present in the "item" table
94 const CONTENT_FIELDLIST = ['language'];
96 // All fields in the item table
97 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
98 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id',
99 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
100 'created', 'edited', 'commented', 'received', 'changed', 'verb',
101 'postopts', 'plink', 'resource-id', 'event-id', 'attach', 'inform',
102 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
103 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
104 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
105 'title', 'content-warning', 'body', 'location', 'coord', 'app',
106 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
107 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
108 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
110 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
111 // The item-activity table only stores the index and needs this array to know the matching activity.
113 Activity::LIKE, Activity::DISLIKE,
114 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
122 private static $legacy_mode = null;
124 public static function isLegacyMode()
126 if (is_null(self::$legacy_mode)) {
127 self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
130 return self::$legacy_mode;
134 * Set the pinned state of an item
136 * @param integer $iid Item ID
137 * @param integer $uid User ID
138 * @param boolean $pinned Pinned state
140 public static function setPinned(int $iid, int $uid, bool $pinned)
142 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
146 * Get the pinned state
148 * @param integer $iid Item ID
149 * @param integer $uid User ID
151 * @return boolean pinned state
153 public static function getPinned(int $iid, int $uid)
155 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
156 if (!DBA::isResult($useritem)) {
159 return (bool)$useritem['pinned'];
163 * Select pinned rows from the item table for a given user
165 * @param integer $uid User ID
166 * @param array $selected Array of selected fields, empty for all
167 * @param array $condition Array of fields for condition
168 * @param array $params Array of several parameters
170 * @return boolean|object
173 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
175 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
176 if (!DBA::isResult($useritems)) {
181 while ($useritem = DBA::fetch($useritems)) {
182 $pinned[] = $useritem['iid'];
184 DBA::close($useritems);
186 if (empty($pinned)) {
190 if (empty($condition) || !is_array($condition)) {
191 $condition = ['iid' => $pinned];
194 $first_key = key($condition);
195 if (!is_int($first_key)) {
196 $condition['iid'] = $pinned;
198 $values_string = substr(str_repeat("?, ", count($pinned)), 0, -2);
199 $condition[0] = '(' . $condition[0] . ") AND `iid` IN (" . $values_string . ")";
200 $condition = array_merge($condition, $pinned);
204 return self::selectThreadForUser($uid, $selected, $condition, $params);
208 * returns an activity index from an activity string
210 * @param string $activity activity string
211 * @return integer Activity index
213 public static function activityToIndex($activity)
215 $index = array_search($activity, self::ACTIVITIES);
217 if (is_bool($index)) {
225 * returns an activity string from an activity index
227 * @param integer $index activity index
228 * @return string Activity string
230 private static function indexToActivity($index)
232 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
236 return self::ACTIVITIES[$index];
240 * Fetch a single item row
242 * @param mixed $stmt statement object
243 * @return array current row
245 public static function fetch($stmt)
247 $row = DBA::fetch($stmt);
253 // ---------------------- Transform item structure data ----------------------
255 // We prefer the data from the user's contact over the public one
256 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
257 ($row['author-link'] == $row['contact-link'])) {
258 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
259 $row['author-avatar'] = $row['contact-avatar'];
261 if (isset($row['author-name']) && !empty($row['contact-name'])) {
262 $row['author-name'] = $row['contact-name'];
266 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
267 ($row['owner-link'] == $row['contact-link'])) {
268 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
269 $row['owner-avatar'] = $row['contact-avatar'];
271 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
272 $row['owner-name'] = $row['contact-name'];
276 // We can always comment on posts from these networks
277 if (array_key_exists('writable', $row) &&
278 in_array($row['internal-network'], Protocol::FEDERATED)) {
279 $row['writable'] = true;
282 // ---------------------- Transform item content data ----------------------
284 // Fetch data from the item-content table whenever there is content there
285 if (self::isLegacyMode()) {
286 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
287 foreach ($legacy_fields as $field) {
288 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
289 $row[$field] = $row['internal-item-' . $field];
291 unset($row['internal-item-' . $field]);
295 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
296 $row['verb'] = self::indexToActivity($row['internal-activity']);
297 if (array_key_exists('title', $row)) {
300 if (array_key_exists('body', $row)) {
301 $row['body'] = $row['verb'];
303 if (array_key_exists('object', $row)) {
306 if (array_key_exists('object-type', $row)) {
307 $row['object-type'] = Activity\ObjectType::NOTE;
309 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
310 // Posts don't have a target - but having tags or files.
311 // We safe some performance by building tag and file strings only here.
312 // We remove the target since they aren't used for this type.
313 // In mail posts we do store some mail header data in the object.
314 if (array_key_exists('target', $row)) {
319 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
320 // Build the file string out of the term entries
321 if (array_key_exists('file', $row) && empty($row['file'])) {
322 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
326 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
327 if (array_key_exists('allow_cid', $row)) {
328 $row['allow_cid'] = '';
330 if (array_key_exists('allow_gid', $row)) {
331 $row['allow_gid'] = '';
333 if (array_key_exists('deny_cid', $row)) {
334 $row['deny_cid'] = '';
336 if (array_key_exists('deny_gid', $row)) {
337 $row['deny_gid'] = '';
341 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
342 $row['ignored'] = $row['internal-user-ignored'];
345 // Remove internal fields
346 unset($row['internal-activity']);
347 unset($row['internal-network']);
348 unset($row['internal-iid']);
349 unset($row['internal-psid']);
350 unset($row['internal-iaid']);
351 unset($row['internal-user-ignored']);
352 unset($row['interaction']);
358 * Fills an array with data from an item query
360 * @param object $stmt statement object
361 * @param bool $do_close
362 * @return array Data array
364 public static function inArray($stmt, $do_close = true) {
365 if (is_bool($stmt)) {
370 while ($row = self::fetch($stmt)) {
380 * Check if item data exists
382 * @param array $condition array of fields for condition
384 * @return boolean Are there rows for that condition?
387 public static function exists($condition) {
388 $stmt = self::select(['id'], $condition, ['limit' => 1]);
390 if (is_bool($stmt)) {
393 $retval = (DBA::numRows($stmt) > 0);
402 * Retrieve a single record from the item table for a given user and returns it in an associative array
404 * @param integer $uid User ID
405 * @param array $selected
406 * @param array $condition
407 * @param array $params
412 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
414 $params['uid'] = $uid;
416 if (empty($selected)) {
417 $selected = Item::DISPLAY_FIELDLIST;
420 return self::selectFirst($selected, $condition, $params);
424 * Select rows from the item table for a given user
426 * @param integer $uid User ID
427 * @param array $selected Array of selected fields, empty for all
428 * @param array $condition Array of fields for condition
429 * @param array $params Array of several parameters
431 * @return boolean|object
434 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
436 $params['uid'] = $uid;
438 if (empty($selected)) {
439 $selected = Item::DISPLAY_FIELDLIST;
442 return self::select($selected, $condition, $params);
446 * Retrieve a single record from the item table and returns it in an associative array
448 * @param array $fields
449 * @param array $condition
450 * @param array $params
455 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
457 $params['limit'] = 1;
459 $result = self::select($fields, $condition, $params);
461 if (is_bool($result)) {
464 $row = self::fetch($result);
471 * Select rows from the item table and returns them as an array
473 * @param array $selected Array of selected fields, empty for all
474 * @param array $condition Array of fields for condition
475 * @param array $params Array of several parameters
480 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
482 $result = self::select($fields, $condition, $params);
484 if (is_bool($result)) {
489 while ($row = self::fetch($result)) {
498 * Select rows from the item table
500 * @param array $selected Array of selected fields, empty for all
501 * @param array $condition Array of fields for condition
502 * @param array $params Array of several parameters
504 * @return boolean|object
507 public static function select(array $selected = [], array $condition = [], $params = [])
512 if (isset($params['uid'])) {
513 $uid = $params['uid'];
517 $fields = self::fieldlist($usermode);
519 $select_fields = self::constructSelectFields($fields, $selected);
521 $condition_string = DBA::buildCondition($condition);
523 $condition_string = self::addTablesToFields($condition_string, $fields);
526 $condition_string = $condition_string . ' AND ' . self::condition(false);
529 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
531 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
533 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
535 return DBA::p($sql, $condition);
539 * Select rows from the starting post in the item table
541 * @param integer $uid User ID
542 * @param array $selected
543 * @param array $condition Array of fields for condition
544 * @param array $params Array of several parameters
546 * @return boolean|object
549 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
551 $params['uid'] = $uid;
553 if (empty($selected)) {
554 $selected = Item::DISPLAY_FIELDLIST;
557 return self::selectThread($selected, $condition, $params);
561 * Retrieve a single record from the starting post in the item table and returns it in an associative array
563 * @param integer $uid User ID
564 * @param array $selected
565 * @param array $condition
566 * @param array $params
571 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
573 $params['uid'] = $uid;
575 if (empty($selected)) {
576 $selected = Item::DISPLAY_FIELDLIST;
579 return self::selectFirstThread($selected, $condition, $params);
583 * Retrieve a single record from the starting post in the item table and returns it in an associative array
585 * @param array $fields
586 * @param array $condition
587 * @param array $params
592 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
594 $params['limit'] = 1;
595 $result = self::selectThread($fields, $condition, $params);
597 if (is_bool($result)) {
600 $row = self::fetch($result);
607 * Select rows from the starting post in the item table
609 * @param array $selected Array of selected fields, empty for all
610 * @param array $condition Array of fields for condition
611 * @param array $params Array of several parameters
613 * @return boolean|object
616 public static function selectThread(array $selected = [], array $condition = [], $params = [])
621 if (isset($params['uid'])) {
622 $uid = $params['uid'];
626 $fields = self::fieldlist($usermode);
628 $fields['thread'] = ['mention', 'ignored', 'iid'];
630 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
631 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
632 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
633 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
635 $select_fields = self::constructSelectFields($fields, $selected);
637 $condition_string = DBA::buildCondition($condition);
639 $condition_string = self::addTablesToFields($condition_string, $threadfields);
640 $condition_string = self::addTablesToFields($condition_string, $fields);
643 $condition_string = $condition_string . ' AND ' . self::condition(true);
646 $param_string = DBA::buildParameter($params);
647 $param_string = self::addTablesToFields($param_string, $threadfields);
648 $param_string = self::addTablesToFields($param_string, $fields);
650 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
652 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
654 return DBA::p($sql, $condition);
658 * Returns a list of fields that are associated with the item table
661 * @return array field list
663 private static function fieldlist($usermode)
667 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
668 'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id',
669 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
670 'created', 'edited', 'commented', 'received', 'changed', 'psid',
671 'resource-id', 'event-id', 'attach', 'post-type', 'file',
672 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
673 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
674 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
675 'network' => 'internal-network', 'iaid' => 'internal-iaid', 'psid' => 'internal-psid'];
678 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
681 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
683 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
685 $fields['post-delivery-data'] = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, Post\DeliveryData::FIELD_LIST);
687 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
689 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
690 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
692 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
693 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
695 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
696 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
697 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
699 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
701 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
703 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
704 'start' => 'event-start','finish' => 'event-finish',
705 'summary' => 'event-summary','desc' => 'event-desc',
706 'location' => 'event-location', 'type' => 'event-type',
707 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
708 'ignore' => 'event-ignore', 'id' => 'event-id'];
710 $fields['diaspora-interaction'] = ['interaction', 'interaction' => 'signed_text'];
716 * Returns SQL condition for the "select" functions
718 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
720 * @return string SQL condition
722 private static function condition($thread_mode)
725 $master_table = "`thread`";
727 $master_table = "`item`";
729 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
730 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
731 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
732 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
733 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
734 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
735 GRAVITY_PARENT, GRAVITY_PARENT);
739 * Returns all needed "JOIN" commands for the "select" functions
741 * @param integer $uid User ID
742 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
743 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
746 * @return string The SQL joins for the "select" functions
748 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
751 $master_table = "`thread`";
752 $master_table_key = "`thread`.`iid`";
753 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
755 $master_table = "`item`";
756 $master_table_key = "`item`.`id`";
761 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
762 AND NOT `contact`.`blocked`
763 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
764 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
765 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
766 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
767 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
768 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
769 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
770 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
772 if (strpos($sql_commands, "`contact`.") !== false) {
773 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
775 if (strpos($sql_commands, "`author`.") !== false) {
776 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
778 if (strpos($sql_commands, "`owner`.") !== false) {
779 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
783 if (strpos($sql_commands, "`group_member`.") !== false) {
784 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
787 if (strpos($sql_commands, "`user`.") !== false) {
788 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
791 if (strpos($sql_commands, "`event`.") !== false) {
792 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
795 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
796 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
799 if (strpos($sql_commands, "`item-activity`.") !== false) {
800 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
803 if (strpos($sql_commands, "`item-content`.") !== false) {
804 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
807 if (strpos($sql_commands, "`post-delivery-data`.") !== false) {
808 $joins .= " LEFT JOIN `post-delivery-data` ON `post-delivery-data`.`uri-id` = `item`.`uri-id` AND `item`.`origin`";
811 if (strpos($sql_commands, "`permissionset`.") !== false) {
812 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
815 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
816 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
819 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
820 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
827 * Add the field list for the "select" functions
829 * @param array $fields The field definition array
830 * @param array $selected The array with the selected fields from the "select" functions
832 * @return string The field list
834 private static function constructSelectFields(array $fields, array $selected)
836 if (!empty($selected)) {
837 $selected = array_merge($selected, ['internal-iid', 'internal-psid', 'internal-iaid', 'internal-network']);
840 if (in_array('verb', $selected)) {
841 $selected[] = 'internal-activity';
844 if (in_array('ignored', $selected)) {
845 $selected[] = 'internal-user-ignored';
848 $legacy_fields = array_merge(Post\DeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
851 foreach ($fields as $table => $table_fields) {
852 foreach ($table_fields as $field => $select) {
853 if (empty($selected) || in_array($select, $selected)) {
854 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
855 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
857 if (is_int($field)) {
858 $selection[] = "`" . $table . "`.`" . $select . "`";
860 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
865 return implode(", ", $selection);
869 * add table definition to fields in an SQL query
871 * @param string $query SQL query
872 * @param array $fields The field definition array
874 * @return string the changed SQL query
876 private static function addTablesToFields($query, $fields)
878 foreach ($fields as $table => $table_fields) {
879 foreach ($table_fields as $alias => $field) {
880 if (is_int($alias)) {
881 $replace_field = $field;
883 $replace_field = $alias;
886 $search = "/([^\.])`" . $field . "`/i";
887 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
888 $query = preg_replace($search, $replace, $query);
895 * Update existing item entries
897 * @param array $fields The fields that are to be changed
898 * @param array $condition The condition for finding the item entries
900 * In the future we may have to change permissions as well.
901 * Then we had to add the user id as third parameter.
903 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
905 * @return integer|boolean number of affected rows - or "false" if there was an error
906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 public static function update(array $fields, array $condition)
910 if (empty($condition) || empty($fields)) {
914 // To ensure the data integrity we do it in an transaction
917 // We cannot simply expand the condition to check for origin entries
918 // The condition needn't to be a simple array but could be a complex condition.
919 // And we have to execute this query before the update to ensure to fetch the same data.
920 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'file'], $condition);
922 $content_fields = [];
923 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
924 if (isset($fields[$field])) {
925 $content_fields[$field] = $fields[$field];
926 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
927 unset($fields[$field]);
929 $fields[$field] = null;
934 $delivery_data = Post\DeliveryData::extractFields($fields);
936 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
937 foreach ($clear_fields as $field) {
938 if (array_key_exists($field, $fields)) {
939 $fields[$field] = null;
943 if (array_key_exists('file', $fields)) {
944 $files = $fields['file'];
945 $fields['file'] = null;
950 if (!empty($fields)) {
951 $success = DBA::update('item', $fields, $condition);
960 // When there is no content for the "old" item table, this will count the fetched items
961 $rows = DBA::affectedRows();
965 while ($item = DBA::fetch($items)) {
966 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
967 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
969 if (empty($item['iaid'])) {
970 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
971 if (DBA::isResult($item_activity)) {
972 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
973 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
974 if (self::isLegacyMode()) {
975 $item_fields[$field] = null;
977 unset($item_fields[$field]);
980 DBA::update('item', $item_fields, ['id' => $item['id']]);
982 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
983 DBA::delete('item-content', ['id' => $item['icid']]);
986 } elseif (!empty($item['icid'])) {
987 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
989 if (!DBA::exists('item', ['icid' => $item['icid']])) {
990 DBA::delete('item-content', ['id' => $item['icid']]);
994 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
996 if (empty($item['icid'])) {
997 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
998 if (DBA::isResult($item_content)) {
999 $item_fields = ['icid' => $item_content['id']];
1000 // Clear all fields in the item table that have a content in the item-content table
1001 foreach ($item_content as $field => $content) {
1002 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
1003 if (self::isLegacyMode()) {
1004 $item_fields[$field] = null;
1006 unset($item_fields[$field]);
1010 DBA::update('item', $item_fields, ['id' => $item['id']]);
1015 if (!is_null($files)) {
1016 Term::insertFromFileFieldByItemId($item['id'], $files);
1017 if (!empty($item['file'])) {
1018 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
1022 Post\DeliveryData::update($item['uri-id'], $delivery_data);
1024 self::updateThread($item['id']);
1026 // We only need to notfiy others when it is an original entry from us.
1027 // Only call the notifier when the item has some content relevant change.
1028 if ($item['origin'] && in_array('edited', array_keys($fields))) {
1029 $notify_items[] = $item['id'];
1036 foreach ($notify_items as $notify_item) {
1037 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1044 * Delete an item and notify others about it - if it was ours
1046 * @param array $condition The condition for finding the item entries
1047 * @param integer $priority Priority for the notification
1048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1050 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
1052 $items = self::select(['id'], $condition);
1053 while ($item = self::fetch($items)) {
1054 self::markForDeletionById($item['id'], $priority);
1060 * Delete an item for an user and notify others about it - if it was ours
1062 * @param array $condition The condition for finding the item entries
1063 * @param integer $uid User who wants to delete this item
1064 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1066 public static function deleteForUser($condition, $uid)
1072 $items = self::select(['id', 'uid'], $condition);
1073 while ($item = self::fetch($items)) {
1074 // "Deleting" global items just means hiding them
1075 if ($item['uid'] == 0) {
1076 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1078 // Delete notifications
1079 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
1080 } elseif ($item['uid'] == $uid) {
1081 self::markForDeletionById($item['id'], PRIORITY_HIGH);
1083 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1090 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1092 * @param integer $item_id
1093 * @param integer $priority Priority for the notification
1095 * @return boolean success
1096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1100 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1101 // locate item to be deleted
1102 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri', 'origin',
1103 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1104 'verb', 'object-type', 'object', 'target', 'contact-id',
1105 'icid', 'iaid', 'psid'];
1106 $item = self::selectFirst($fields, ['id' => $item_id]);
1107 if (!DBA::isResult($item)) {
1108 Logger::info('Item not found.', ['id' => $item_id]);
1112 if ($item['deleted']) {
1113 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1117 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1118 if (!DBA::isResult($parent)) {
1119 $parent = ['origin' => false];
1122 // clean up categories and tags so they don't end up as orphans
1125 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1128 foreach ($matches as $mtch) {
1129 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1135 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1138 foreach ($matches as $mtch) {
1139 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1144 * If item is a link to a photo resource, nuke all the associated photos
1145 * (visitors will not have photo resources)
1146 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1147 * generate a resource-id and therefore aren't intimately linked to the item.
1149 /// @TODO: this should first check if photo is used elsewhere
1150 if (strlen($item['resource-id'])) {
1151 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1154 // If item is a link to an event, delete the event.
1155 if (intval($item['event-id'])) {
1156 Event::delete($item['event-id']);
1159 // If item has attachments, drop them
1160 /// @TODO: this should first check if attachment is used elsewhere
1161 foreach (explode(",", $item['attach']) as $attach) {
1162 preg_match("|attach/(\d+)|", $attach, $matches);
1163 if (is_array($matches) && count($matches) > 1) {
1164 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1168 // Delete notifications
1169 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
1171 // Set the item to "deleted"
1172 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1173 DBA::update('item', $item_fields, ['id' => $item['id']]);
1175 Term::insertFromFileFieldByItemId($item['id'], '');
1176 self::deleteThread($item['id'], $item['parent-uri']);
1178 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1179 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1182 Post\DeliveryData::delete($item['uri-id']);
1184 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1186 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1187 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1189 // When the permission set will be used in photo and events as well,
1190 // this query here needs to be extended.
1191 // @todo Currently deactivated. We need the permission set in the deletion process.
1192 // This is a reminder to add the removal somewhere else.
1193 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1194 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1197 // If it's the parent of a comment thread, kill all the kids
1198 if ($item['id'] == $item['parent']) {
1199 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1202 // Is it our comment and/or our thread?
1203 if ($item['origin'] || $parent['origin']) {
1204 // When we delete the original post we will delete all existing copies on the server as well
1205 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1207 // send the notification upstream/downstream
1208 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1209 } elseif ($item['uid'] != 0) {
1211 // When we delete just our local user copy of an item, we have to set a marker to hide it
1212 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1213 if (DBA::isResult($global_item)) {
1214 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1218 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1224 private static function guid($item, $notify)
1226 if (!empty($item['guid'])) {
1227 return Strings::escapeTags(trim($item['guid']));
1231 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1232 // We add the hash of our own host because our host is the original creator of the post.
1233 $prefix_host = DI::baseUrl()->getHostname();
1237 // We are only storing the post so we create a GUID from the original hostname.
1238 if (!empty($item['author-link'])) {
1239 $parsed = parse_url($item['author-link']);
1240 if (!empty($parsed['host'])) {
1241 $prefix_host = $parsed['host'];
1245 if (empty($prefix_host) && !empty($item['plink'])) {
1246 $parsed = parse_url($item['plink']);
1247 if (!empty($parsed['host'])) {
1248 $prefix_host = $parsed['host'];
1252 if (empty($prefix_host) && !empty($item['uri'])) {
1253 $parsed = parse_url($item['uri']);
1254 if (!empty($parsed['host'])) {
1255 $prefix_host = $parsed['host'];
1259 // Is it in the format data@host.tld? - Used for mail contacts
1260 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1261 $mailparts = explode('@', $item['author-link']);
1262 $prefix_host = array_pop($mailparts);
1266 if (!empty($item['plink'])) {
1267 $guid = self::guidFromUri($item['plink'], $prefix_host);
1268 } elseif (!empty($item['uri'])) {
1269 $guid = self::guidFromUri($item['uri'], $prefix_host);
1271 $guid = System::createUUID(hash('crc32', $prefix_host));
1277 private static function contactId($item)
1279 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1280 return $item['contact-id'];
1281 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1282 return $item['contact-id'];
1283 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1284 return $item['author-id'];
1285 } elseif (!empty($item['contact-id'])) {
1286 return $item['contact-id'];
1288 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1289 if (!empty($contact_id)) {
1293 return $item['author-id'];
1296 // This function will finally cover most of the preparation functionality in mod/item.php
1297 public static function prepare(&$item)
1300 * @TODO: Unused code triggering inspection errors
1302 $data = BBCode::getAttachmentData($item['body']);
1303 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1304 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1305 $posttype = Item::PT_PAGE;
1306 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1312 * Write an item array into a spool file to be inserted later.
1313 * This command is called whenever there are issues storing an item.
1315 * @param array $item The item fields that are to be inserted
1316 * @throws \Exception
1318 private static function spool($orig_item)
1320 // Now we store the data in the spool directory
1321 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1322 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1324 $spoolpath = get_spoolpath();
1325 if ($spoolpath != "") {
1326 $spool = $spoolpath . '/' . $file;
1328 file_put_contents($spool, json_encode($orig_item));
1329 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1333 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1337 $priority = PRIORITY_HIGH;
1339 // If it is a posting where users should get notifications, then define it as wall posting
1342 $item['origin'] = 1;
1343 $item['network'] = Protocol::DFRN;
1344 $item['protocol'] = Conversation::PARCEL_DFRN;
1346 if (is_int($notify)) {
1347 $priority = $notify;
1350 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1353 $item['guid'] = self::guid($item, $notify);
1354 $item['uri'] = substr(Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid']))), 0, 255);
1357 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1359 // Store conversation data
1360 $item = Conversation::insert($item);
1363 * If a Diaspora signature structure was passed in, pull it out of the
1364 * item array and set it aside for later storage.
1368 if (isset($item['dsprsig'])) {
1369 $encoded_signature = $item['dsprsig'];
1370 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1371 unset($item['dsprsig']);
1374 $diaspora_signed_text = '';
1375 if (isset($item['diaspora_signed_text'])) {
1376 $diaspora_signed_text = $item['diaspora_signed_text'];
1377 unset($item['diaspora_signed_text']);
1380 // Converting the plink
1381 /// @TODO Check if this is really still needed
1382 if ($item['network'] == Protocol::OSTATUS) {
1383 if (isset($item['plink'])) {
1384 $item['plink'] = OStatus::convertHref($item['plink']);
1385 } elseif (isset($item['uri'])) {
1386 $item['plink'] = OStatus::convertHref($item['uri']);
1390 if (!empty($item['thr-parent'])) {
1391 $item['parent-uri'] = $item['thr-parent'];
1394 $activity = DI::activity();
1396 if (isset($item['gravity'])) {
1397 $item['gravity'] = intval($item['gravity']);
1398 } elseif ($item['parent-uri'] === $item['uri']) {
1399 $item['gravity'] = GRAVITY_PARENT;
1400 } elseif ($activity->match($item['verb'], Activity::POST)) {
1401 $item['gravity'] = GRAVITY_COMMENT;
1402 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1403 $item['gravity'] = GRAVITY_ACTIVITY;
1405 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1406 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1409 $uid = intval($item['uid']);
1411 // check for create date and expire time
1412 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1414 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1415 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1416 $expire_interval = $user['expire'];
1419 if (($expire_interval > 0) && !empty($item['created'])) {
1420 $expire_date = time() - ($expire_interval * 86400);
1421 $created_date = strtotime($item['created']);
1422 if ($created_date < $expire_date) {
1423 Logger::notice('Item created before expiration interval.', [
1424 'created' => date('c', $created_date),
1425 'expired' => date('c', $expire_date),
1433 * Do we already have this item?
1434 * We have to check several networks since Friendica posts could be repeated
1435 * via OStatus (maybe Diasporsa as well)
1437 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1438 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1439 trim($item['uri']), $item['uid'],
1440 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1441 $existing = self::selectFirst(['id', 'network'], $condition);
1442 if (DBA::isResult($existing)) {
1443 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1445 Logger::notice('Item already existed for user', [
1446 'uri' => $item['uri'],
1448 'network' => $item['network'],
1449 'existing_id' => $existing["id"],
1450 'existing_network' => $existing["network"]
1454 return $existing["id"];
1458 $item['wall'] = intval($item['wall'] ?? 0);
1459 $item['extid'] = trim($item['extid'] ?? '');
1460 $item['author-name'] = trim($item['author-name'] ?? '');
1461 $item['author-link'] = trim($item['author-link'] ?? '');
1462 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1463 $item['owner-name'] = trim($item['owner-name'] ?? '');
1464 $item['owner-link'] = trim($item['owner-link'] ?? '');
1465 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1466 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1467 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1468 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1469 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1470 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1471 $item['title'] = substr(trim($item['title'] ?? ''), 0, 255);
1472 $item['location'] = trim($item['location'] ?? '');
1473 $item['coord'] = trim($item['coord'] ?? '');
1474 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1475 $item['deleted'] = 0;
1476 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1477 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1478 $item['verb'] = trim($item['verb'] ?? '');
1479 $item['object-type'] = trim($item['object-type'] ?? '');
1480 $item['object'] = trim($item['object'] ?? '');
1481 $item['target-type'] = trim($item['target-type'] ?? '');
1482 $item['target'] = trim($item['target'] ?? '');
1483 $item['plink'] = substr(trim($item['plink'] ?? ''), 0, 255);
1484 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1485 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1486 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1487 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1488 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1489 $item['body'] = trim($item['body'] ?? '');
1490 $item['attach'] = trim($item['attach'] ?? '');
1491 $item['app'] = trim($item['app'] ?? '');
1492 $item['origin'] = intval($item['origin'] ?? 0);
1493 $item['postopts'] = trim($item['postopts'] ?? '');
1494 $item['resource-id'] = trim($item['resource-id'] ?? '');
1495 $item['event-id'] = intval($item['event-id'] ?? 0);
1496 $item['inform'] = trim($item['inform'] ?? '');
1497 $item['file'] = trim($item['file'] ?? '');
1499 // When there is no content then we don't post it
1500 if ($item['body'].$item['title'] == '') {
1501 Logger::notice('No body, no title.');
1505 self::addLanguageToItemArray($item);
1507 // Items cannot be stored before they happen ...
1508 if ($item['created'] > DateTimeFormat::utcNow()) {
1509 $item['created'] = DateTimeFormat::utcNow();
1512 // We haven't invented time travel by now.
1513 if ($item['edited'] > DateTimeFormat::utcNow()) {
1514 $item['edited'] = DateTimeFormat::utcNow();
1517 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1519 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1520 'photo' => $item['author-avatar'], 'network' => $item['network']];
1522 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, false, $default);
1524 if (Contact::isBlocked($item['author-id'])) {
1525 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1529 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1530 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1534 if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
1535 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1539 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1540 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1542 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, false, $default);
1544 if (Contact::isBlocked($item['owner-id'])) {
1545 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1549 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1550 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1554 if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
1555 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1559 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1560 if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
1561 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1565 if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
1566 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1570 // We don't store the causer, we only have it here for the checks above
1571 unset($item['causer-id']);
1572 unset($item['causer-link']);
1574 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1575 $item["contact-id"] = self::contactId($item);
1577 if ($item['network'] == Protocol::PHANTOM) {
1578 $item['network'] = Protocol::DFRN;
1579 Logger::notice('Missing network, setting to {network}.', [
1580 'uri' => $item["uri"],
1581 'network' => $item['network'],
1582 'callstack' => System::callstack()
1586 // Checking if there is already an item with the same guid
1587 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1588 if (self::exists($condition)) {
1589 Logger::notice('Found already existing item', [
1590 'guid' => $item['guid'],
1591 'uid' => $item['uid'],
1592 'network' => $item['network']
1597 if ($item['verb'] == Activity::FOLLOW) {
1598 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1599 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1600 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1604 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1605 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1606 if (self::exists($condition)) {
1607 // It happens that we receive multiple follow requests by the same author - we only store one.
1608 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1613 // Check for hashtags in the body and repair or add hashtag links
1614 self::setHashtags($item);
1616 // Store tags from the body if this hadn't been handled previously in the protocol classes
1617 if (!Tag::existsForPost($item['uri-id'])) {
1618 Tag::storeFromBody($item['uri-id'], $item['body']);
1621 $item['thr-parent'] = $item['parent-uri'];
1623 $notify_type = Delivery::POST;
1629 if ($item['parent-uri'] === $item['uri']) {
1631 $parent_deleted = 0;
1632 $allow_cid = $item['allow_cid'];
1633 $allow_gid = $item['allow_gid'];
1634 $deny_cid = $item['deny_cid'];
1635 $deny_gid = $item['deny_gid'];
1637 // find the parent and snarf the item id and ACLs
1638 // and anything else we need to inherit
1640 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1641 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1642 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1643 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1644 $params = ['order' => ['id' => false]];
1645 $parent = self::selectFirst($fields, $condition, $params);
1647 if (DBA::isResult($parent)) {
1648 // is the new message multi-level threaded?
1649 // even though we don't support it now, preserve the info
1650 // and re-attach to the conversation parent.
1652 if ($parent['uri'] != $parent['parent-uri']) {
1653 $item['parent-uri'] = $parent['parent-uri'];
1655 $condition = ['uri' => $item['parent-uri'],
1656 'parent-uri' => $item['parent-uri'],
1657 'uid' => $item['uid']];
1658 $params = ['order' => ['id' => false]];
1659 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1661 if (DBA::isResult($toplevel_parent)) {
1662 $parent = $toplevel_parent;
1666 $parent_id = $parent['id'];
1667 $parent_deleted = $parent['deleted'];
1668 $allow_cid = $parent['allow_cid'];
1669 $allow_gid = $parent['allow_gid'];
1670 $deny_cid = $parent['deny_cid'];
1671 $deny_gid = $parent['deny_gid'];
1672 $item['wall'] = $parent['wall'];
1675 * If the parent is private, force privacy for the entire conversation
1676 * This differs from the above settings as it subtly allows comments from
1677 * email correspondents to be private even if the overall thread is not.
1679 if ($parent['private']) {
1680 $item['private'] = $parent['private'];
1684 * Edge case. We host a public forum that was originally posted to privately.
1685 * The original author commented, but as this is a comment, the permissions
1686 * weren't fixed up so it will still show the comment as private unless we fix it here.
1688 if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
1689 $item['private'] = self::PUBLIC;
1692 // If its a post that originated here then tag the thread as "mention"
1693 if ($item['origin'] && $item['uid']) {
1694 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1695 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1698 // Update the contact relations
1699 if ($item['author-id'] != $parent['author-id']) {
1700 DBA::update('contact-relation', ['last-interaction' => $item['created']], ['cid' => $parent['author-id'], 'relation-cid' => $item['author-id']], true);
1704 * Allow one to see reply tweets from status.net even when
1705 * we don't have or can't see the original post.
1707 if ($force_parent) {
1708 Logger::log('$force_parent=true, reply converted to top-level post.');
1710 $item['parent-uri'] = $item['uri'];
1711 $item['gravity'] = GRAVITY_PARENT;
1713 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1717 $parent_deleted = 0;
1721 if (stristr($item['verb'], Activity::POKE)) {
1722 $notify_type = Delivery::POKE;
1725 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1726 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1728 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1729 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1730 if (self::exists($condition)) {
1731 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1735 // On Friendica and Diaspora the GUID is unique
1736 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1737 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1738 if (self::exists($condition)) {
1739 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1742 } elseif ($item['network'] == Protocol::OSTATUS) {
1743 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1744 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1745 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1746 if (self::exists($condition)) {
1747 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1752 // Is this item available in the global items (with uid=0)?
1753 if ($item["uid"] == 0) {
1754 $item["global"] = true;
1756 // Set the global flag on all items if this was a global item entry
1757 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1759 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1763 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1764 $private = self::PRIVATE;
1766 $private = $item['private'];
1769 $item["allow_cid"] = $allow_cid;
1770 $item["allow_gid"] = $allow_gid;
1771 $item["deny_cid"] = $deny_cid;
1772 $item["deny_gid"] = $deny_gid;
1773 $item["private"] = $private;
1774 $item["deleted"] = $parent_deleted;
1776 // Fill the cache field
1777 self::putInCache($item);
1780 $item['edit'] = false;
1781 $item['parent'] = $parent_id;
1782 Hook::callAll('post_local', $item);
1783 unset($item['edit']);
1784 unset($item['parent']);
1786 Hook::callAll('post_remote', $item);
1789 // This array field is used to trigger some automatic reactions
1790 // It is mainly used in the "post_local" hook.
1791 unset($item['api_source']);
1793 if (!empty($item['cancel'])) {
1794 Logger::log('post cancelled by addon.');
1799 * Check for already added items.
1800 * There is a timing issue here that sometimes creates double postings.
1801 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1803 if ($item["uid"] == 0) {
1804 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1805 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1810 Logger::log('' . print_r($item,true), Logger::DATA);
1812 if (array_key_exists('file', $item)) {
1813 $files = $item['file'];
1814 unset($item['file']);
1819 // Creates or assigns the permission set
1820 $item['psid'] = PermissionSet::getIdFromACL(
1828 $item['allow_cid'] = null;
1829 $item['allow_gid'] = null;
1830 $item['deny_cid'] = null;
1831 $item['deny_gid'] = null;
1833 // We are doing this outside of the transaction to avoid timing problems
1834 if (!self::insertActivity($item)) {
1835 self::insertContent($item);
1838 $delivery_data = Post\DeliveryData::extractFields($item);
1840 unset($item['postopts']);
1841 unset($item['inform']);
1843 // These fields aren't stored anymore in the item table, they are fetched upon request
1844 unset($item['author-link']);
1845 unset($item['author-name']);
1846 unset($item['author-avatar']);
1847 unset($item['author-network']);
1849 unset($item['owner-link']);
1850 unset($item['owner-name']);
1851 unset($item['owner-avatar']);
1853 $like_no_comment = DI::config()->get('system', 'like_no_comment');
1856 $ret = DBA::insert('item', $item);
1858 // When the item was successfully stored we fetch the ID of the item.
1859 if (DBA::isResult($ret)) {
1860 $current_post = DBA::lastInsertId();
1862 // This can happen - for example - if there are locking timeouts.
1865 // Store the data into a spool file so that we can try again later.
1866 self::spool($orig_item);
1870 if ($current_post == 0) {
1871 // This is one of these error messages that never should occur.
1872 Logger::log("couldn't find created item - we better quit now.");
1877 // How much entries have we created?
1878 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1879 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1882 // There are duplicates. We delete our just created entry.
1883 Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
1885 // Yes, we could do a rollback here - but we possibly are still having users with MyISAM.
1886 DBA::delete('item', ['id' => $current_post]);
1889 } elseif ($entries == 0) {
1890 // This really should never happen since we quit earlier if there were problems.
1891 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1896 Logger::log('created item '.$current_post);
1898 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1899 $parent_id = $current_post;
1903 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1905 $item['id'] = $current_post;
1906 $item['parent'] = $parent_id;
1908 // update the commented timestamp on the parent
1909 // Only update "commented" if it is really a comment
1910 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1911 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1913 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1918 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1919 * We can check for this condition when we decode and encode the stuff again.
1921 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1922 $dsprsig->signature = base64_decode($dsprsig->signature);
1923 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1926 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1927 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1931 if (!empty($diaspora_signed_text)) {
1932 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1935 if ($item['parent-uri'] === $item['uri']) {
1936 self::addThread($current_post);
1938 self::updateThread($parent_id);
1941 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1942 Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1948 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1949 * This is not perfect - but a workable solution until we found the reason for the problem.
1951 if (!empty($files)) {
1952 Term::insertFromFileFieldByItemId($current_post, $files);
1955 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1956 if (self::tagDeliver($item['uid'], $current_post)) {
1957 // Get the user information for the logging
1958 $user = User::getById($uid);
1960 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1965 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1966 if (DBA::isResult($posted_item)) {
1968 Hook::callAll('post_local_end', $posted_item);
1970 Hook::callAll('post_remote_end', $posted_item);
1973 Logger::log('new item not found in DB, id ' . $current_post);
1977 if ($item['parent-uri'] === $item['uri']) {
1978 self::addShadow($current_post);
1980 self::addShadowPost($current_post);
1983 self::updateContact($item);
1985 UserItem::setNotification($current_post);
1987 check_user_notification($current_post);
1989 if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
1990 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1993 return $current_post;
1997 * Insert a new item content entry
1999 * @param array $item The item fields that are to be inserted
2001 * @throws \Exception
2003 private static function insertActivity(&$item)
2005 $activity_index = self::activityToIndex($item['verb']);
2007 if ($activity_index < 0) {
2011 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2013 // We just remove everything that is content
2014 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2015 unset($item[$field]);
2018 // To avoid timing problems, we are using locks.
2019 $locked = DI::lock()->acquire('item_insert_activity');
2021 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2024 // Do we already have this content?
2025 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
2026 if (DBA::isResult($item_activity)) {
2027 $item['iaid'] = $item_activity['id'];
2028 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2029 } elseif (DBA::insert('item-activity', $fields)) {
2030 $item['iaid'] = DBA::lastInsertId();
2031 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2033 // This shouldn't happen.
2034 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
2035 DI::lock()->release('item_insert_activity');
2039 DI::lock()->release('item_insert_activity');
2045 * Insert a new item content entry
2047 * @param array $item The item fields that are to be inserted
2048 * @throws \Exception
2050 private static function insertContent(&$item)
2052 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2054 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2055 if (isset($item[$field])) {
2056 $fields[$field] = $item[$field];
2057 unset($item[$field]);
2061 // To avoid timing problems, we are using locks.
2062 $locked = DI::lock()->acquire('item_insert_content');
2064 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2067 // Do we already have this content?
2068 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2069 if (DBA::isResult($item_content)) {
2070 $item['icid'] = $item_content['id'];
2071 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2072 } elseif (DBA::insert('item-content', $fields)) {
2073 $item['icid'] = DBA::lastInsertId();
2074 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2076 // This shouldn't happen.
2077 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2080 DI::lock()->release('item_insert_content');
2085 * Update existing item content entries
2087 * @param array $item The item fields that are to be changed
2088 * @param array $condition The condition for finding the item content entries
2090 * @throws \Exception
2092 private static function updateActivity($item, $condition)
2094 if (empty($item['verb'])) {
2097 $activity_index = self::activityToIndex($item['verb']);
2099 if ($activity_index < 0) {
2103 $fields = ['activity' => $activity_index];
2105 Logger::log('Update activity for ' . json_encode($condition));
2107 DBA::update('item-activity', $fields, $condition, true);
2113 * Update existing item content entries
2115 * @param array $item The item fields that are to be changed
2116 * @param array $condition The condition for finding the item content entries
2117 * @throws \Exception
2119 private static function updateContent($item, $condition)
2121 // We have to select only the fields from the "item-content" table
2123 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2124 if (isset($item[$field])) {
2125 $fields[$field] = $item[$field];
2129 if (empty($fields)) {
2130 // when there are no fields at all, just use the condition
2131 // This is to ensure that we always store content.
2132 $fields = $condition;
2135 Logger::log('Update content for ' . json_encode($condition));
2137 DBA::update('item-content', $fields, $condition, true);
2141 * Distributes public items to the receivers
2143 * @param integer $itemid Item ID that should be added
2144 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2145 * @throws \Exception
2147 public static function distribute($itemid, $signed_text = '')
2149 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2150 $parent = self::selectFirst(['owner-id'], $condition);
2151 if (!DBA::isResult($parent)) {
2155 // Only distribute public items from native networks
2156 $condition = ['id' => $itemid, 'uid' => 0,
2157 'network' => array_merge(Protocol::FEDERATED ,['']),
2158 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2159 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2160 if (!DBA::isResult($item)) {
2164 $origin = $item['origin'];
2167 unset($item['parent']);
2168 unset($item['mention']);
2169 unset($item['wall']);
2170 unset($item['origin']);
2171 unset($item['starred']);
2175 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2176 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2177 if (!DBA::isResult($owner)) {
2181 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2182 $contacts = DBA::select('contact', ['uid'], $condition);
2183 while ($contact = DBA::fetch($contacts)) {
2184 if ($contact['uid'] == 0) {
2188 $users[$contact['uid']] = $contact['uid'];
2190 DBA::close($contacts);
2192 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2193 $contacts = DBA::select('contact', ['uid'], $condition);
2194 while ($contact = DBA::fetch($contacts)) {
2195 if ($contact['uid'] == 0) {
2199 $users[$contact['uid']] = $contact['uid'];
2201 DBA::close($contacts);
2203 if (!empty($owner['alias'])) {
2204 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2205 $contacts = DBA::select('contact', ['uid'], $condition);
2206 while ($contact = DBA::fetch($contacts)) {
2207 if ($contact['uid'] == 0) {
2211 $users[$contact['uid']] = $contact['uid'];
2213 DBA::close($contacts);
2218 if ($item['uri'] != $item['parent-uri']) {
2219 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2220 while ($parent = self::fetch($parents)) {
2221 $users[$parent['uid']] = $parent['uid'];
2222 if ($parent['origin'] && !$origin) {
2223 $origin_uid = $parent['uid'];
2228 foreach ($users as $uid) {
2229 if ($origin_uid == $uid) {
2230 $item['diaspora_signed_text'] = $signed_text;
2232 self::storeForUser($itemid, $item, $uid);
2237 * Store public items for the receivers
2239 * @param integer $itemid Item ID that should be added
2240 * @param array $item The item entry that will be stored
2241 * @param integer $uid The user that will receive the item entry
2242 * @throws \Exception
2244 private static function storeForUser($itemid, $item, $uid)
2246 $item['uid'] = $uid;
2247 $item['origin'] = 0;
2249 if ($item['uri'] == $item['parent-uri']) {
2250 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2252 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2255 if (empty($item['contact-id'])) {
2256 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2257 if (!DBA::isResult($self)) {
2260 $item['contact-id'] = $self['id'];
2263 /// @todo Handling of "event-id"
2266 if ($item['uri'] == $item['parent-uri']) {
2267 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2268 if (DBA::isResult($contact)) {
2269 $notify = self::isRemoteSelf($contact, $item);
2273 $distributed = self::insert($item, false, $notify, true);
2275 if (!$distributed) {
2276 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2278 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2283 * Add a shadow entry for a given item id that is a thread starter
2285 * We store every public item entry additionally with the user id "0".
2286 * This is used for the community page and for the search.
2287 * It is planned that in the future we will store public item entries only once.
2289 * @param integer $itemid Item ID that should be added
2290 * @throws \Exception
2292 public static function addShadow($itemid)
2294 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2295 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2296 $item = self::selectFirst($fields, $condition);
2298 if (!DBA::isResult($item)) {
2302 // is it already a copy?
2303 if (($itemid == 0) || ($item['uid'] == 0)) {
2307 // Is it a visible public post?
2308 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
2312 // is it an entry from a connector? Only add an entry for natively connected networks
2313 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2317 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2321 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2323 if (DBA::isResult($item)) {
2324 // Preparing public shadow (removing user specific data)
2327 unset($item['parent']);
2328 unset($item['wall']);
2329 unset($item['mention']);
2330 unset($item['origin']);
2331 unset($item['starred']);
2332 unset($item['postopts']);
2333 unset($item['inform']);
2334 if ($item['uri'] == $item['parent-uri']) {
2335 $item['contact-id'] = $item['owner-id'];
2337 $item['contact-id'] = $item['author-id'];
2340 $public_shadow = self::insert($item, false, false, true);
2342 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2347 * Add a shadow entry for a given item id that is a comment
2349 * This function does the same like the function above - but for comments
2351 * @param integer $itemid Item ID that should be added
2352 * @throws \Exception
2354 public static function addShadowPost($itemid)
2356 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2357 if (!DBA::isResult($item)) {
2361 // Is it a toplevel post?
2362 if ($item['id'] == $item['parent']) {
2363 self::addShadow($itemid);
2367 // Is this a shadow entry?
2368 if ($item['uid'] == 0) {
2372 // Is there a shadow parent?
2373 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2377 // Is there already a shadow entry?
2378 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2382 // Save "origin" and "parent" state
2383 $origin = $item['origin'];
2384 $parent = $item['parent'];
2386 // Preparing public shadow (removing user specific data)
2389 unset($item['parent']);
2390 unset($item['wall']);
2391 unset($item['mention']);
2392 unset($item['origin']);
2393 unset($item['starred']);
2394 unset($item['postopts']);
2395 unset($item['inform']);
2396 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2398 $public_shadow = self::insert($item, false, false, true);
2400 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2402 // If this was a comment to a Diaspora post we don't get our comment back.
2403 // This means that we have to distribute the comment by ourselves.
2404 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2405 self::distribute($public_shadow);
2410 * Adds a language specification in a "language" element of given $arr.
2411 * Expects "body" element to exist in $arr.
2414 * @throws \Text_LanguageDetect_Exception
2416 private static function addLanguageToItemArray(&$item)
2418 $naked_body = BBCode::toPlaintext($item['body'], false);
2420 $ld = new Text_LanguageDetect();
2421 $ld->setNameMode(2);
2422 $languages = $ld->detect($naked_body, 3);
2424 if (is_array($languages)) {
2425 $item['language'] = json_encode($languages);
2430 * Creates an unique guid out of a given uri
2432 * @param string $uri uri of an item entry
2433 * @param string $host hostname for the GUID prefix
2434 * @return string unique guid
2436 public static function guidFromUri($uri, $host)
2438 // Our regular guid routine is using this kind of prefix as well
2439 // We have to avoid that different routines could accidentally create the same value
2440 $parsed = parse_url($uri);
2442 // We use a hash of the hostname as prefix for the guid
2443 $guid_prefix = hash("crc32", $host);
2445 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2446 unset($parsed["scheme"]);
2448 // Glue it together to be able to make a hash from it
2449 $host_id = implode("/", $parsed);
2451 // We could use any hash algorithm since it isn't a security issue
2452 $host_hash = hash("ripemd128", $host_id);
2454 return $guid_prefix.$host_hash;
2458 * generate an unique URI
2460 * @param integer $uid User id
2461 * @param string $guid An existing GUID (Otherwise it will be generated)
2464 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2466 public static function newURI($uid, $guid = "")
2469 $guid = System::createUUID();
2472 return DI::baseUrl()->get() . '/objects/' . $guid;
2476 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2478 * This can be used to filter for inactive contacts.
2479 * Only do this for public postings to avoid privacy problems, since poco data is public.
2480 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2482 * @param array $arr Contains the just posted item record
2483 * @throws \Exception
2485 private static function updateContact($arr)
2487 // Unarchive the author
2488 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2489 if (DBA::isResult($contact)) {
2490 Contact::unmarkForArchival($contact);
2493 // Unarchive the contact if it's not our own contact
2494 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2495 if (DBA::isResult($contact)) {
2496 Contact::unmarkForArchival($contact);
2499 /// @todo On private posts we could obfuscate the date
2500 $update = ($arr['private'] != self::PRIVATE);
2502 // Is it a forum? Then we don't care about the rules from above
2503 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2504 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2510 // The "self" contact id is used (for example in the connectors) when the contact is unknown
2511 // So we have to ensure to only update the last item when it had been our own post,
2512 // or it had been done by a "regular" contact.
2513 if (!empty($arr['wall'])) {
2514 $condition = ['id' => $arr['contact-id']];
2516 $condition = ['id' => $arr['contact-id'], 'self' => false];
2518 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
2520 // Now do the same for the system wide contacts with uid=0
2521 if ($arr['private'] != self::PRIVATE) {
2522 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2523 ['id' => $arr['owner-id']]);
2525 if ($arr['owner-id'] != $arr['author-id']) {
2526 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2527 ['id' => $arr['author-id']]);
2532 public static function setHashtags(&$item)
2534 $tags = BBCode::getTags($item["body"]);
2537 if (!count($tags)) {
2541 // What happens in [code], stays in [code]!
2542 // escape the # and the [
2543 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2544 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2546 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2548 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2549 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2552 // This sorting is important when there are hashtags that are part of other hashtags
2553 // Otherwise there could be problems with hashtags like #test and #test2
2554 // Because of this we are sorting from the longest to the shortest tag.
2555 usort($tags, function($a, $b) {
2556 return strlen($b) <=> strlen($a);
2559 $URLSearchString = "^\[\]";
2561 // All hashtags should point to the home server if "local_tags" is activated
2562 if (DI::config()->get('system', 'local_tags')) {
2563 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2564 "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2567 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2568 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2570 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2573 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2575 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2578 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2580 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2583 // Repair recursive urls
2584 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2585 "#$2", $item["body"]);
2587 foreach ($tags as $tag) {
2588 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2592 $basetag = str_replace('_',' ',substr($tag,1));
2593 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2595 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2598 // Convert back the masked hashtags
2599 $item["body"] = str_replace("#", "#", $item["body"]);
2601 // Remember! What happens in [code], stays in [code]
2602 // roleback the # and [
2603 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2605 // we truly unESCape all sharp and leftsquarebracket
2606 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2607 $replace = ['#', '['];
2608 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2613 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2616 * @param int $item_id
2617 * @return boolean true if item was deleted, else false
2618 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2619 * @throws \ImagickException
2621 private static function tagDeliver($uid, $item_id)
2625 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2626 if (!DBA::isResult($user)) {
2630 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2631 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2633 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2634 if (!DBA::isResult($item)) {
2638 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2641 * Diaspora uses their own hardwired link URL in @-tags
2642 * instead of the one we supply with webfinger
2644 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2646 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2648 foreach ($matches as $mtch) {
2649 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2651 Logger::log('mention found: ' . $mtch[2]);
2657 if (($community_page || $prvgroup) &&
2658 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2659 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2660 DBA::delete('item', ['id' => $item_id]);
2666 $arr = ['item' => $item, 'user' => $user];
2668 Hook::callAll('tagged', $arr);
2670 if (!$community_page && !$prvgroup) {
2675 * tgroup delivery - setup a second delivery chain
2676 * prevent delivery looping - only proceed
2677 * if the message originated elsewhere and is a top-level post
2679 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2683 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2684 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2685 if (!DBA::isResult($self)) {
2689 $owner_id = Contact::getIdForURL($self['url']);
2691 // also reset all the privacy bits to the forum default permissions
2693 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2695 $psid = PermissionSet::getIdFromACL(
2703 $forum_mode = ($prvgroup ? 2 : 1);
2705 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2706 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2707 self::update($fields, ['id' => $item_id]);
2709 self::updateThread($item_id);
2711 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2716 public static function isRemoteSelf($contact, &$datarray)
2718 if (!$contact['remote_self']) {
2722 // Prevent the forwarding of posts that are forwarded
2723 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2724 Logger::log('Already forwarded', Logger::DEBUG);
2728 // Prevent to forward already forwarded posts
2729 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2730 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2734 // Only forward posts
2735 if ($datarray["verb"] != Activity::POST) {
2736 Logger::log('No post', Logger::DEBUG);
2740 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2741 Logger::log('Not public', Logger::DEBUG);
2745 $datarray2 = $datarray;
2746 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2747 if ($contact['remote_self'] == 2) {
2748 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2749 ['uid' => $contact['uid'], 'self' => true]);
2750 if (DBA::isResult($self)) {
2751 $datarray['contact-id'] = $self["id"];
2753 $datarray['owner-name'] = $self["name"];
2754 $datarray['owner-link'] = $self["url"];
2755 $datarray['owner-avatar'] = $self["thumb"];
2757 $datarray['author-name'] = $datarray['owner-name'];
2758 $datarray['author-link'] = $datarray['owner-link'];
2759 $datarray['author-avatar'] = $datarray['owner-avatar'];
2761 unset($datarray['edited']);
2763 unset($datarray['network']);
2764 unset($datarray['owner-id']);
2765 unset($datarray['author-id']);
2768 if ($contact['network'] != Protocol::FEED) {
2769 $datarray["guid"] = System::createUUID();
2770 unset($datarray["plink"]);
2771 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2772 $datarray["parent-uri"] = $datarray["uri"];
2773 $datarray["thr-parent"] = $datarray["uri"];
2774 $datarray["extid"] = Protocol::DFRN;
2775 $urlpart = parse_url($datarray2['author-link']);
2776 $datarray["app"] = $urlpart["host"];
2778 $datarray['private'] = self::PUBLIC;
2782 if ($contact['network'] != Protocol::FEED) {
2783 // Store the original post
2784 $result = self::insert($datarray2, false, false);
2785 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2787 $datarray["app"] = "Feed";
2791 // Trigger automatic reactions for addons
2792 $datarray['api_source'] = true;
2794 // We have to tell the hooks who we are - this really should be improved
2795 $_SESSION["authenticated"] = true;
2796 $_SESSION["uid"] = $contact['uid'];
2805 * @param array $item
2808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2809 * @throws \ImagickException
2811 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2813 if (DI::config()->get('system', 'disable_embedded')) {
2817 Logger::log('check for photos', Logger::DEBUG);
2818 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2823 $img_start = strpos($orig_body, '[img');
2824 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2825 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2827 while (($img_st_close !== false) && ($img_len !== false)) {
2828 $img_st_close++; // make it point to AFTER the closing bracket
2829 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2831 Logger::log('found photo ' . $image, Logger::DEBUG);
2833 if (stristr($image, $site . '/photo/')) {
2834 // Only embed locally hosted photos
2836 $i = basename($image);
2837 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2838 $x = strpos($i, '-');
2841 $res = substr($i, $x + 1);
2842 $i = substr($i, 0, $x);
2843 $photo = Photo::getPhotoForUser($uid, $i, $res);
2844 if (DBA::isResult($photo)) {
2846 * Check to see if we should replace this photo link with an embedded image
2847 * 1. No need to do so if the photo is public
2848 * 2. If there's a contact-id provided, see if they're in the access list
2849 * for the photo. If so, embed it.
2850 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2851 * permissions, regardless of order but first check to see if they're an exact
2852 * match to save some processing overhead.
2854 if (self::hasPermissions($photo)) {
2856 $recips = self::enumeratePermissions($photo);
2857 if (in_array($cid, $recips)) {
2861 if (self::samePermissions($uid, $item, $photo)) {
2867 $photo_img = Photo::getImageForPhoto($photo);
2868 // If a custom width and height were specified, apply before embedding
2869 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2870 Logger::log('scaling photo', Logger::DEBUG);
2872 $width = intval($match[1]);
2873 $height = intval($match[2]);
2875 $photo_img->scaleDown(max($width, $height));
2878 $data = $photo_img->asString();
2879 $type = $photo_img->getType();
2881 Logger::log('replacing photo', Logger::DEBUG);
2882 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2883 Logger::log('replaced: ' . $image, Logger::DATA);
2889 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2890 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2891 if ($orig_body === false) {
2895 $img_start = strpos($orig_body, '[img');
2896 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2897 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2900 $new_body = $new_body . $orig_body;
2905 private static function hasPermissions($obj)
2907 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2908 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2911 private static function samePermissions($uid, $obj1, $obj2)
2913 // first part is easy. Check that these are exactly the same.
2914 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2915 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2916 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2917 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2921 // This is harder. Parse all the permissions and compare the resulting set.
2922 $recipients1 = self::enumeratePermissions($obj1);
2923 $recipients2 = self::enumeratePermissions($obj2);
2927 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2928 return ($recipients1 == $recipients2);
2932 * Returns an array of contact-ids that are allowed to see this object
2934 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2935 * @param bool $check_dead Prunes unavailable contacts from the result
2937 * @throws \Exception
2939 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2941 $aclFormater = DI::aclFormatter();
2943 $allow_people = $aclFormater->expand($obj['allow_cid']);
2944 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2945 $deny_people = $aclFormater->expand($obj['deny_cid']);
2946 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2947 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2948 $deny = array_unique(array_merge($deny_people, $deny_groups));
2949 $recipients = array_diff($recipients, $deny);
2953 public static function expire($uid, $days, $network = "", $force = false)
2955 if (!$uid || ($days < 1)) {
2959 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2960 $uid, GRAVITY_PARENT];
2963 * $expire_network_only = save your own wall posts
2964 * and just expire conversations started by others
2966 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2968 if ($expire_network_only) {
2969 $condition[0] .= " AND NOT `wall`";
2972 if ($network != "") {
2973 $condition[0] .= " AND `network` = ?";
2974 $condition[] = $network;
2977 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2978 $condition[] = $days;
2980 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2982 if (!DBA::isResult($items)) {
2986 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2988 // Forcing expiring of items - but not notes and marked items
2990 $expire_items = true;
2993 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2994 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2995 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2999 while ($item = Item::fetch($items)) {
3000 // don't expire filed items
3002 if (strpos($item['file'], '[') !== false) {
3006 // Only expire posts, not photos and photo comments
3008 if (!$expire_photos && strlen($item['resource-id'])) {
3010 } elseif (!$expire_starred && intval($item['starred'])) {
3012 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3014 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3018 self::markForDeletionById($item['id'], PRIORITY_LOW);
3023 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3026 public static function firstPostDate($uid, $wall = false)
3028 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3029 $params = ['order' => ['received' => false]];
3030 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3031 if (DBA::isResult($thread)) {
3032 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3038 * add/remove activity to an item
3040 * Toggle activities as like,dislike,attend of an item
3042 * @param string $item_id
3043 * @param string $verb
3044 * Activity verb. One of
3045 * like, unlike, dislike, undislike, attendyes, unattendyes,
3046 * attendno, unattendno, attendmaybe, unattendmaybe
3048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3049 * @throws \ImagickException
3050 * @hook 'post_local_end'
3052 * 'post_id' => ID of posted item
3054 public static function performActivity($item_id, $verb)
3056 if (!Session::isAuthenticated()) {
3063 $activity = Activity::LIKE;
3067 $activity = Activity::DISLIKE;
3071 $activity = Activity::ATTEND;
3075 $activity = Activity::ATTENDNO;
3078 case 'unattendmaybe':
3079 $activity = Activity::ATTENDMAYBE;
3083 $activity = Activity::FOLLOW;
3086 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3090 // Enable activity toggling instead of on/off
3091 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3093 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3095 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3096 if (!DBA::isResult($item)) {
3097 Logger::log('like: unknown item ' . $item_id);
3101 $item_uri = $item['uri'];
3103 $uid = $item['uid'];
3104 if (($uid == 0) && local_user()) {
3105 $uid = local_user();
3108 if (!Security::canWriteToUserWall($uid)) {
3109 Logger::log('like: unable to write on wall ' . $uid);
3113 // Retrieves the local post owner
3114 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3115 if (!DBA::isResult($owner_self_contact)) {
3116 Logger::log('like: unknown owner ' . $uid);
3120 // Retrieve the current logged in user's public contact
3121 $author_id = public_contact();
3123 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3124 if (!DBA::isResult($author_contact)) {
3125 Logger::log('like: unknown author ' . $author_id);
3129 // Contact-id is the uid-dependant author contact
3130 if (local_user() == $uid) {
3131 $item_contact_id = $owner_self_contact['id'];
3133 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3134 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3135 if (!DBA::isResult($item_contact)) {
3136 Logger::log('like: unknown item contact ' . $item_contact_id);
3141 // Look for an existing verb row
3142 // event participation are essentially radio toggles. If you make a subsequent choice,
3143 // we need to eradicate your first choice.
3144 if ($event_verb_flag) {
3145 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3147 // Translate to the index based activity index
3149 foreach ($verbs as $verb) {
3150 $activities[] = self::activityToIndex($verb);
3153 $activities = self::activityToIndex($activity);
3156 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3157 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3159 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3161 // If it exists, mark it as deleted
3162 if (DBA::isResult($like_item)) {
3163 self::markForDeletionById($like_item['id']);
3165 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3170 // Verb is "un-something", just trying to delete existing entries
3171 if (strpos($verb, 'un') === 0) {
3175 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3178 'guid' => System::createUUID(),
3179 'uri' => self::newURI($item['uid']),
3180 'uid' => $item['uid'],
3181 'contact-id' => $item_contact_id,
3182 'wall' => $item['wall'],
3184 'network' => Protocol::DFRN,
3185 'gravity' => GRAVITY_ACTIVITY,
3186 'parent' => $item['id'],
3187 'parent-uri' => $item['uri'],
3188 'thr-parent' => $item['uri'],
3189 'owner-id' => $author_id,
3190 'author-id' => $author_id,
3191 'body' => $activity,
3192 'verb' => $activity,
3193 'object-type' => $objtype,
3194 'allow_cid' => $item['allow_cid'],
3195 'allow_gid' => $item['allow_gid'],
3196 'deny_cid' => $item['deny_cid'],
3197 'deny_gid' => $item['deny_gid'],
3202 $signed = Diaspora::createLikeSignature($uid, $new_item);
3203 if (!empty($signed)) {
3204 $new_item['diaspora_signed_text'] = json_encode($signed);
3207 $new_item_id = self::insert($new_item);
3209 // If the parent item isn't visible then set it to visible
3210 if (!$item['visible']) {
3211 self::update(['visible' => true], ['id' => $item['id']]);
3214 $new_item['id'] = $new_item_id;
3216 Hook::callAll('post_local_end', $new_item);
3221 private static function addThread($itemid, $onlyshadow = false)
3223 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3224 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3225 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3226 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3227 $item = self::selectFirst($fields, $condition);
3229 if (!DBA::isResult($item)) {
3233 $item['iid'] = $itemid;
3236 $result = DBA::insert('thread', $item);
3238 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3242 private static function updateThread($itemid, $setmention = false)
3244 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3245 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3246 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3247 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3249 $item = self::selectFirst($fields, $condition);
3250 if (!DBA::isResult($item)) {
3255 $item["mention"] = 1;
3260 foreach ($item as $field => $data) {
3261 if (!in_array($field, ["guid"])) {
3262 $fields[$field] = $data;
3266 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3268 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3271 private static function deleteThread($itemid, $itemuri = "")
3273 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3274 if (!DBA::isResult($item)) {
3275 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3279 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3281 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3283 if ($itemuri != "") {
3284 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3285 if (!self::exists($condition)) {
3286 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3287 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3292 public static function getPermissionsSQLByUserId($owner_id)
3294 $local_user = local_user();
3295 $remote_user = Session::getRemoteContactID($owner_id);
3298 * Construct permissions
3300 * default permissions - anonymous user
3302 $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
3304 // Profile owner - everything is visible
3305 if ($local_user && ($local_user == $owner_id)) {
3307 } elseif ($remote_user) {
3309 * Authenticated visitor. Unless pre-verified,
3310 * check that the contact belongs to this $owner_id
3311 * and load the groups the visitor belongs to.
3312 * If pre-verified, the caller is expected to have already
3313 * done this and passed the groups into this function.
3315 $set = PermissionSet::get($owner_id, $remote_user);
3318 $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3323 $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
3330 * get translated item type
3335 public static function postType($item)
3337 if (!empty($item['event-id'])) {
3338 return DI::l10n()->t('event');
3339 } elseif (!empty($item['resource-id'])) {
3340 return DI::l10n()->t('photo');
3341 } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) {
3342 return DI::l10n()->t('activity');
3343 } elseif ($item['id'] != $item['parent']) {
3344 return DI::l10n()->t('comment');
3347 return DI::l10n()->t('post');
3351 * Sets the "rendered-html" field of the provided item
3353 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3355 * @param array $item
3356 * @param bool $update
3358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3359 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3361 public static function putInCache(&$item, $update = false)
3363 $body = $item["body"];
3365 $rendered_hash = $item['rendered-hash'] ?? '';
3366 $rendered_html = $item['rendered-html'] ?? '';
3368 if ($rendered_hash == ''
3369 || $rendered_html == ""
3370 || $rendered_hash != hash("md5", $item["body"])
3371 || DI::config()->get("system", "ignore_cache")
3373 self::addRedirToImageTags($item);
3375 $item["rendered-html"] = BBCode::convert($item["body"]);
3376 $item["rendered-hash"] = hash("md5", $item["body"]);
3378 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3379 Hook::callAll('put_item_in_cache', $hook_data);
3380 $item['rendered-html'] = $hook_data['rendered-html'];
3381 $item['rendered-hash'] = $hook_data['rendered-hash'];
3384 // Force an update if the generated values differ from the existing ones
3385 if ($rendered_hash != $item["rendered-hash"]) {
3389 // Only compare the HTML when we forcefully ignore the cache
3390 if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3394 if ($update && !empty($item["id"])) {
3397 'rendered-html' => $item["rendered-html"],
3398 'rendered-hash' => $item["rendered-hash"]
3400 ['id' => $item["id"]]
3405 $item["body"] = $body;
3409 * Find any non-embedded images in private items and add redir links to them
3411 * @param array &$item The field array of an item row
3413 private static function addRedirToImageTags(array &$item)
3418 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3420 foreach ($matches as $mtch) {
3421 if (strpos($mtch[1], '/redir') !== false) {
3425 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3426 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3427 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3434 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3435 * If attach is true, also add icons for item attachments.
3437 * @param array $item
3438 * @param boolean $attach
3439 * @param boolean $is_preview
3440 * @return string item body html
3441 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3442 * @throws \ImagickException
3443 * @hook prepare_body_init item array before any work
3444 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3445 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3446 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3448 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3451 Hook::callAll('prepare_body_init', $item);
3453 // In order to provide theme developers more possibilities, event items
3454 // are treated differently.
3455 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3456 $ev = Event::getItemHTML($item);
3460 $tags = Tag::populateFromItem($item);
3462 $item['tags'] = $tags['tags'];
3463 $item['hashtags'] = $tags['hashtags'];
3464 $item['mentions'] = $tags['mentions'];
3466 // Compile eventual content filter reasons
3467 $filter_reasons = [];
3468 if (!$is_preview && public_contact() != $item['author-id']) {
3469 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3470 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3475 'filter_reasons' => $filter_reasons
3477 Hook::callAll('prepare_body_content_filter', $hook_data);
3478 $filter_reasons = $hook_data['filter_reasons'];
3482 // Update the cached values if there is no "zrl=..." on the links.
3483 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3485 // Or update it if the current viewer is the intented viewer.
3486 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3490 self::putInCache($item, $update);
3491 $s = $item["rendered-html"];
3496 'preview' => $is_preview,
3497 'filter_reasons' => $filter_reasons
3499 Hook::callAll('prepare_body', $hook_data);
3500 $s = $hook_data['html'];
3504 // Replace the blockquotes with quotes that are used in mails.
3505 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3506 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3513 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3514 foreach ($matches as $mtch) {
3517 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3519 if (strpos($mime, 'video') !== false) {
3522 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3525 $url_parts = explode('/', $the_url);
3526 $id = end($url_parts);
3527 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3530 'title' => DI::l10n()->t('View Video'),
3537 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3539 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3540 $filesubtype = str_replace('.', '-', $filesubtype);
3543 $filesubtype = 'unkn';
3546 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3547 $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
3549 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3550 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3554 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3558 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3559 $x = Map::byCoordinates(trim($item['coord']));
3561 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3565 // Replace friendica image url size with theme preference.
3566 if (!empty($a->theme_info['item_image_size'])) {
3567 $ps = $a->theme_info['item_image_size'];
3568 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3571 $s = HTML::applyContentFilter($s, $filter_reasons);
3573 $hook_data = ['item' => $item, 'html' => $s];
3574 Hook::callAll('prepare_body_final', $hook_data);
3576 return $hook_data['html'];
3580 * get private link for item
3582 * @param array $item
3583 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3584 * @throws \Exception
3586 public static function getPlink($item)
3590 if ($a->user['nickname'] != "") {
3592 'href' => "display/" . $item['guid'],
3593 'orig' => "display/" . $item['guid'],
3594 'title' => DI::l10n()->t('View on separate page'),
3595 'orig_title' => DI::l10n()->t('view on separate page'),
3598 if (!empty($item['plink'])) {
3599 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3600 $ret["title"] = DI::l10n()->t('link to source');
3603 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3605 'href' => $item['plink'],
3606 'orig' => $item['plink'],
3607 'title' => DI::l10n()->t('link to source'),
3617 * Is the given item array a post that is sent as starting post to a forum?
3619 * @param array $item
3620 * @param array $owner
3622 * @return boolean "true" when it is a forum post
3624 public static function isForumPost(array $item, array $owner = [])
3626 if (empty($owner)) {
3627 $owner = User::getOwnerDataById($item['uid']);
3628 if (empty($owner)) {
3633 if (($item['author-id'] == $item['owner-id']) ||
3634 ($owner['id'] == $item['contact-id']) ||
3635 ($item['uri'] != $item['parent-uri']) ||
3640 return Contact::isForum($item['contact-id']);
3644 * Search item id for given URI or plink
3646 * @param string $uri
3647 * @param integer $uid
3649 * @return integer item id
3651 public static function searchByLink($uri, $uid = 0)
3653 $ssl_uri = str_replace('http://', 'https://', $uri);
3654 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3656 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3657 if (DBA::isResult($item)) {
3661 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3662 if (!DBA::isResult($itemcontent)) {
3666 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3667 if (!DBA::isResult($itemuri)) {
3671 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3672 if (DBA::isResult($item)) {
3680 * Return the URI for a link to the post
3682 * @param string $uri URI or link to post
3684 * @return string URI
3686 public static function getURIByLink(string $uri)
3688 $ssl_uri = str_replace('http://', 'https://', $uri);
3689 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3691 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3692 if (DBA::isResult($item)) {
3693 return $item['uri'];
3696 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3697 if (!DBA::isResult($itemcontent)) {
3701 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3702 if (DBA::isResult($itemuri)) {
3703 return $itemuri['uri'];
3710 * Fetches item for given URI or plink
3712 * @param string $uri
3713 * @param integer $uid
3715 * @return integer item id
3717 public static function fetchByLink($uri, $uid = 0)
3719 $item_id = self::searchByLink($uri, $uid);
3720 if (!empty($item_id)) {
3724 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3725 $item_id = self::searchByLink($fetched_uri, $uid);
3727 $item_id = Diaspora::fetchByURL($uri);
3730 if (!empty($item_id)) {
3738 * Return share data from an item array (if the item is shared item)
3739 * We are providing the complete Item array, because at some time in the future
3740 * we hopefully will define these values not in the body anymore but in some item fields.
3741 * This function is meant to replace all similar functions in the system.
3743 * @param array $item
3745 * @return array with share information
3747 public static function getShareArray($item)
3749 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3753 $attribute_string = $matches[2];
3754 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3755 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3756 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3757 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3764 * Fetch item information for shared items from the original items and adds it.
3766 * @param array $item
3768 * @return array item array with data from the original item
3770 public static function addShareDataFromOriginal($item)
3772 $shared = self::getShareArray($item);
3773 if (empty($shared)) {
3777 // Real reshares always have got a GUID.
3778 if (empty($shared['guid'])) {
3782 $uid = $item['uid'] ?? 0;
3784 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3785 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3786 if (!DBA::isResult($shared_item)) {
3787 if (empty($shared['link'])) {
3791 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3792 $id = self::fetchByLink($shared['link'], $uid);
3794 Logger::info('Original item not found', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3798 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
3799 if (!DBA::isResult($shared_item)) {
3802 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3804 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3807 if (!empty($shared_item['title'])) {
3808 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3809 unset($shared_item['title']);
3811 $body = $shared_item['body'];
3814 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3815 unset($shared_item['body']);
3817 return array_merge($item, $shared_item);