4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\Logger;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\Session;
21 use Friendica\Core\System;
22 use Friendica\Core\Worker;
23 use Friendica\Database\DBA;
24 use Friendica\Protocol\Activity;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Protocol\OStatus;
28 use Friendica\Util\ACLFormatter;
29 use Friendica\Util\DateTimeFormat;
30 use Friendica\Util\Map;
31 use Friendica\Util\Network;
32 use Friendica\Util\Security;
33 use Friendica\Util\Strings;
34 use Friendica\Util\XML;
35 use Friendica\Worker\Delivery;
36 use Text_LanguageDetect;
38 class Item extends BaseObject
40 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
47 const PT_DOCUMENT = 19;
49 const PT_PERSONAL_NOTE = 128;
51 // Field list that is used to display the items
52 const DISPLAY_FIELDLIST = [
53 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
54 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
55 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
56 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
57 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
58 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
59 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
60 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
61 'writable', 'self', 'cid', 'alias', 'pinned',
62 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
63 'event-summary', 'event-desc', 'event-location', 'event-type',
64 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
65 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
68 // Field list that is used to deliver items via the protocols
69 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
70 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
71 'private', 'title', 'body', 'location', 'coord', 'app',
72 'attach', 'tag', 'deleted', 'extid', 'post-type',
73 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
74 'author-id', 'author-link', 'owner-link', 'contact-uid',
75 'signed_text', 'signature', 'signer', 'network'];
77 // Field list for "item-content" table that is mixed with the item table
78 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
79 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
80 'object-type', 'object', 'target-type', 'target', 'plink'];
82 // Field list for "item-content" table that is not present in the "item" table
83 const CONTENT_FIELDLIST = ['language'];
85 // All fields in the item table
86 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
87 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
88 'created', 'edited', 'commented', 'received', 'changed', 'verb',
89 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
90 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
91 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
92 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
93 'title', 'content-warning', 'body', 'location', 'coord', 'app',
94 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
95 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
96 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
98 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
99 // The item-activity table only stores the index and needs this array to know the matching activity.
101 Activity::LIKE, Activity::DISLIKE,
102 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
106 private static $legacy_mode = null;
108 public static function isLegacyMode()
110 if (is_null(self::$legacy_mode)) {
111 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
114 return self::$legacy_mode;
118 * Set the pinned state of an item
120 * @param integer $iid Item ID
121 * @param integer $uid User ID
122 * @param boolean $pinned Pinned state
124 public static function setPinned(int $iid, int $uid, bool $pinned)
126 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
130 * Get the pinned state
132 * @param integer $iid Item ID
133 * @param integer $uid User ID
135 * @return boolean pinned state
137 public static function getPinned(int $iid, int $uid)
139 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
140 if (!DBA::isResult($useritem)) {
143 return (bool)$useritem['pinned'];
147 * @brief Select pinned rows from the item table for a given user
149 * @param integer $uid User ID
150 * @param array $selected Array of selected fields, empty for all
152 * @return boolean|object
155 public static function selectPinned(int $uid, array $selected = [])
157 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
158 if (!DBA::isResult($useritems)) {
163 while ($useritem = self::fetch($useritems)) {
164 $pinned[] = $useritem['iid'];
166 DBA::close($useritems);
168 return self::selectThreadForUser($uid, $selected, ['iid' => $pinned]);
172 * @brief returns an activity index from an activity string
174 * @param string $activity activity string
175 * @return integer Activity index
177 public static function activityToIndex($activity)
179 $index = array_search($activity, self::ACTIVITIES);
181 if (is_bool($index)) {
189 * @brief returns an activity string from an activity index
191 * @param integer $index activity index
192 * @return string Activity string
194 private static function indexToActivity($index)
196 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
200 return self::ACTIVITIES[$index];
204 * @brief Fetch a single item row
206 * @param mixed $stmt statement object
207 * @return array current row
209 public static function fetch($stmt)
211 $row = DBA::fetch($stmt);
217 // ---------------------- Transform item structure data ----------------------
219 // We prefer the data from the user's contact over the public one
220 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
221 ($row['author-link'] == $row['contact-link'])) {
222 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
223 $row['author-avatar'] = $row['contact-avatar'];
225 if (isset($row['author-name']) && !empty($row['contact-name'])) {
226 $row['author-name'] = $row['contact-name'];
230 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
231 ($row['owner-link'] == $row['contact-link'])) {
232 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
233 $row['owner-avatar'] = $row['contact-avatar'];
235 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
236 $row['owner-name'] = $row['contact-name'];
240 // We can always comment on posts from these networks
241 if (array_key_exists('writable', $row) &&
242 in_array($row['internal-network'], Protocol::FEDERATED)) {
243 $row['writable'] = true;
246 // ---------------------- Transform item content data ----------------------
248 // Fetch data from the item-content table whenever there is content there
249 if (self::isLegacyMode()) {
250 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
251 foreach ($legacy_fields as $field) {
252 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
253 $row[$field] = $row['internal-item-' . $field];
255 unset($row['internal-item-' . $field]);
259 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
260 $row['verb'] = self::indexToActivity($row['internal-activity']);
261 if (array_key_exists('title', $row)) {
264 if (array_key_exists('body', $row)) {
265 $row['body'] = $row['verb'];
267 if (array_key_exists('object', $row)) {
270 if (array_key_exists('object-type', $row)) {
271 $row['object-type'] = Activity\ObjectType::NOTE;
273 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
274 // Posts don't have an object or target - but having tags or files.
275 // We safe some performance by building tag and file strings only here.
276 // We remove object and target since they aren't used for this type.
277 if (array_key_exists('object', $row)) {
280 if (array_key_exists('target', $row)) {
285 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
286 // Build the tag string out of the term entries
287 if (array_key_exists('tag', $row) && empty($row['tag'])) {
288 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
291 // Build the file string out of the term entries
292 if (array_key_exists('file', $row) && empty($row['file'])) {
293 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
297 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
298 $row['signed_text'] = $row['interaction'];
301 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
302 $row['ignored'] = $row['internal-user-ignored'];
305 // Remove internal fields
306 unset($row['internal-activity']);
307 unset($row['internal-network']);
308 unset($row['internal-iid']);
309 unset($row['internal-iaid']);
310 unset($row['internal-icid']);
311 unset($row['internal-user-ignored']);
312 unset($row['interaction']);
318 * @brief Fills an array with data from an item query
320 * @param object $stmt statement object
321 * @param bool $do_close
322 * @return array Data array
324 public static function inArray($stmt, $do_close = true) {
325 if (is_bool($stmt)) {
330 while ($row = self::fetch($stmt)) {
340 * @brief Check if item data exists
342 * @param array $condition array of fields for condition
344 * @return boolean Are there rows for that condition?
347 public static function exists($condition) {
348 $stmt = self::select(['id'], $condition, ['limit' => 1]);
350 if (is_bool($stmt)) {
353 $retval = (DBA::numRows($stmt) > 0);
362 * Retrieve a single record from the item table for a given user and returns it in an associative array
364 * @brief Retrieve a single record from a table
365 * @param integer $uid User ID
366 * @param array $selected
367 * @param array $condition
368 * @param array $params
373 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
375 $params['uid'] = $uid;
377 if (empty($selected)) {
378 $selected = Item::DISPLAY_FIELDLIST;
381 return self::selectFirst($selected, $condition, $params);
385 * @brief Select rows from the item table for a given user
387 * @param integer $uid User ID
388 * @param array $selected Array of selected fields, empty for all
389 * @param array $condition Array of fields for condition
390 * @param array $params Array of several parameters
392 * @return boolean|object
395 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
397 $params['uid'] = $uid;
399 if (empty($selected)) {
400 $selected = Item::DISPLAY_FIELDLIST;
403 return self::select($selected, $condition, $params);
407 * Retrieve a single record from the item table and returns it in an associative array
409 * @brief Retrieve a single record from a table
410 * @param array $fields
411 * @param array $condition
412 * @param array $params
417 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
419 $params['limit'] = 1;
421 $result = self::select($fields, $condition, $params);
423 if (is_bool($result)) {
426 $row = self::fetch($result);
433 * @brief Select rows from the item table and returns them as an array
435 * @param array $selected Array of selected fields, empty for all
436 * @param array $condition Array of fields for condition
437 * @param array $params Array of several parameters
442 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
444 $result = self::select($fields, $condition, $params);
446 if (is_bool($result)) {
451 while ($row = self::fetch($result)) {
460 * @brief Select rows from the item table
462 * @param array $selected Array of selected fields, empty for all
463 * @param array $condition Array of fields for condition
464 * @param array $params Array of several parameters
466 * @return boolean|object
469 public static function select(array $selected = [], array $condition = [], $params = [])
474 if (isset($params['uid'])) {
475 $uid = $params['uid'];
479 $fields = self::fieldlist($usermode);
481 $select_fields = self::constructSelectFields($fields, $selected);
483 $condition_string = DBA::buildCondition($condition);
485 $condition_string = self::addTablesToFields($condition_string, $fields);
488 $condition_string = $condition_string . ' AND ' . self::condition(false);
491 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
493 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
495 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
497 return DBA::p($sql, $condition);
501 * @brief Select rows from the starting post in the item table
503 * @param integer $uid User ID
504 * @param array $selected
505 * @param array $condition Array of fields for condition
506 * @param array $params Array of several parameters
508 * @return boolean|object
511 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
513 $params['uid'] = $uid;
515 if (empty($selected)) {
516 $selected = Item::DISPLAY_FIELDLIST;
519 return self::selectThread($selected, $condition, $params);
523 * Retrieve a single record from the starting post in the item table and returns it in an associative array
525 * @brief Retrieve a single record from a table
526 * @param integer $uid User ID
527 * @param array $selected
528 * @param array $condition
529 * @param array $params
534 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
536 $params['uid'] = $uid;
538 if (empty($selected)) {
539 $selected = Item::DISPLAY_FIELDLIST;
542 return self::selectFirstThread($selected, $condition, $params);
546 * Retrieve a single record from the starting post in the item table and returns it in an associative array
548 * @brief Retrieve a single record from a table
549 * @param array $fields
550 * @param array $condition
551 * @param array $params
556 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
558 $params['limit'] = 1;
559 $result = self::selectThread($fields, $condition, $params);
561 if (is_bool($result)) {
564 $row = self::fetch($result);
571 * @brief Select rows from the starting post in the item table
573 * @param array $selected Array of selected fields, empty for all
574 * @param array $condition Array of fields for condition
575 * @param array $params Array of several parameters
577 * @return boolean|object
580 public static function selectThread(array $selected = [], array $condition = [], $params = [])
585 if (isset($params['uid'])) {
586 $uid = $params['uid'];
590 $fields = self::fieldlist($usermode);
592 $fields['thread'] = ['mention', 'ignored', 'iid'];
594 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
595 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
596 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
597 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
599 $select_fields = self::constructSelectFields($fields, $selected);
601 $condition_string = DBA::buildCondition($condition);
603 $condition_string = self::addTablesToFields($condition_string, $threadfields);
604 $condition_string = self::addTablesToFields($condition_string, $fields);
607 $condition_string = $condition_string . ' AND ' . self::condition(true);
610 $param_string = DBA::buildParameter($params);
611 $param_string = self::addTablesToFields($param_string, $threadfields);
612 $param_string = self::addTablesToFields($param_string, $fields);
614 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
616 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
618 return DBA::p($sql, $condition);
622 * @brief Returns a list of fields that are associated with the item table
625 * @return array field list
627 private static function fieldlist($usermode)
631 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
632 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
633 'created', 'edited', 'commented', 'received', 'changed', 'psid',
634 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
635 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
636 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
637 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
638 'network' => 'internal-network', 'icid' => 'internal-icid',
639 'iaid' => 'internal-iaid'];
642 $fields['user-item'] = ['pinned', 'ignored' => 'internal-user-ignored'];
645 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
647 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
649 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
651 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
653 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
654 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
656 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
657 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
659 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
660 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
661 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
663 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
665 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
667 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
668 'start' => 'event-start','finish' => 'event-finish',
669 'summary' => 'event-summary','desc' => 'event-desc',
670 'location' => 'event-location', 'type' => 'event-type',
671 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
672 'ignore' => 'event-ignore', 'id' => 'event-id'];
674 $fields['sign'] = ['signed_text', 'signature', 'signer'];
676 $fields['diaspora-interaction'] = ['interaction'];
682 * @brief Returns SQL condition for the "select" functions
684 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
686 * @return string SQL condition
688 private static function condition($thread_mode)
691 $master_table = "`thread`";
693 $master_table = "`item`";
695 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
696 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
697 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
698 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
699 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
700 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
701 GRAVITY_PARENT, GRAVITY_PARENT);
705 * @brief Returns all needed "JOIN" commands for the "select" functions
707 * @param integer $uid User ID
708 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
709 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
712 * @return string The SQL joins for the "select" functions
714 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
717 $master_table = "`thread`";
718 $master_table_key = "`thread`.`iid`";
719 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
721 $master_table = "`item`";
722 $master_table_key = "`item`.`id`";
727 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
728 AND NOT `contact`.`blocked`
729 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
730 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
731 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
732 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
733 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
734 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
735 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
736 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
738 if (strpos($sql_commands, "`contact`.") !== false) {
739 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
741 if (strpos($sql_commands, "`author`.") !== false) {
742 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
744 if (strpos($sql_commands, "`owner`.") !== false) {
745 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
749 if (strpos($sql_commands, "`group_member`.") !== false) {
750 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
753 if (strpos($sql_commands, "`user`.") !== false) {
754 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
757 if (strpos($sql_commands, "`event`.") !== false) {
758 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
761 if (strpos($sql_commands, "`sign`.") !== false) {
762 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
765 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
766 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
769 if (strpos($sql_commands, "`item-activity`.") !== false) {
770 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
773 if (strpos($sql_commands, "`item-content`.") !== false) {
774 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
777 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
778 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
781 if (strpos($sql_commands, "`permissionset`.") !== false) {
782 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
785 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
786 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
789 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
790 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
797 * @brief Add the field list for the "select" functions
799 * @param array $fields The field definition array
800 * @param array $selected The array with the selected fields from the "select" functions
802 * @return string The field list
804 private static function constructSelectFields($fields, $selected)
806 if (!empty($selected)) {
807 $selected[] = 'internal-iid';
808 $selected[] = 'internal-iaid';
809 $selected[] = 'internal-icid';
810 $selected[] = 'internal-network';
813 if (in_array('verb', $selected)) {
814 $selected[] = 'internal-activity';
817 if (in_array('ignored', $selected)) {
818 $selected[] = 'internal-user-ignored';
821 if (in_array('signed_text', $selected)) {
822 $selected[] = 'interaction';
825 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
828 foreach ($fields as $table => $table_fields) {
829 foreach ($table_fields as $field => $select) {
830 if (empty($selected) || in_array($select, $selected)) {
831 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
832 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
834 if (is_int($field)) {
835 $selection[] = "`" . $table . "`.`" . $select . "`";
837 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
842 return implode(", ", $selection);
846 * @brief add table definition to fields in an SQL query
848 * @param string $query SQL query
849 * @param array $fields The field definition array
851 * @return string the changed SQL query
853 private static function addTablesToFields($query, $fields)
855 foreach ($fields as $table => $table_fields) {
856 foreach ($table_fields as $alias => $field) {
857 if (is_int($alias)) {
858 $replace_field = $field;
860 $replace_field = $alias;
863 $search = "/([^\.])`" . $field . "`/i";
864 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
865 $query = preg_replace($search, $replace, $query);
872 * @brief Update existing item entries
874 * @param array $fields The fields that are to be changed
875 * @param array $condition The condition for finding the item entries
877 * In the future we may have to change permissions as well.
878 * Then we had to add the user id as third parameter.
880 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
882 * @return integer|boolean number of affected rows - or "false" if there was an error
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
885 public static function update(array $fields, array $condition)
887 if (empty($condition) || empty($fields)) {
891 // To ensure the data integrity we do it in an transaction
894 // We cannot simply expand the condition to check for origin entries
895 // The condition needn't to be a simple array but could be a complex condition.
896 // And we have to execute this query before the update to ensure to fetch the same data.
897 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
899 $content_fields = [];
900 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
901 if (isset($fields[$field])) {
902 $content_fields[$field] = $fields[$field];
903 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
904 unset($fields[$field]);
906 $fields[$field] = null;
911 $delivery_data = ItemDeliveryData::extractFields($fields);
913 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
914 foreach ($clear_fields as $field) {
915 if (array_key_exists($field, $fields)) {
916 $fields[$field] = null;
920 if (array_key_exists('tag', $fields)) {
921 $tags = $fields['tag'];
922 $fields['tag'] = null;
927 if (array_key_exists('file', $fields)) {
928 $files = $fields['file'];
929 $fields['file'] = null;
934 if (!empty($fields)) {
935 $success = DBA::update('item', $fields, $condition);
944 // When there is no content for the "old" item table, this will count the fetched items
945 $rows = DBA::affectedRows();
949 while ($item = DBA::fetch($items)) {
950 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
951 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
953 if (empty($item['iaid'])) {
954 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
955 if (DBA::isResult($item_activity)) {
956 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
957 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
958 if (self::isLegacyMode()) {
959 $item_fields[$field] = null;
961 unset($item_fields[$field]);
964 DBA::update('item', $item_fields, ['id' => $item['id']]);
966 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
967 DBA::delete('item-content', ['id' => $item['icid']]);
970 } elseif (!empty($item['icid'])) {
971 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
973 if (!DBA::exists('item', ['icid' => $item['icid']])) {
974 DBA::delete('item-content', ['id' => $item['icid']]);
978 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
980 if (empty($item['icid'])) {
981 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
982 if (DBA::isResult($item_content)) {
983 $item_fields = ['icid' => $item_content['id']];
984 // Clear all fields in the item table that have a content in the item-content table
985 foreach ($item_content as $field => $content) {
986 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
987 if (self::isLegacyMode()) {
988 $item_fields[$field] = null;
990 unset($item_fields[$field]);
994 DBA::update('item', $item_fields, ['id' => $item['id']]);
999 if (!is_null($tags)) {
1000 Term::insertFromTagFieldByItemId($item['id'], $tags);
1001 if (!empty($item['tag'])) {
1002 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
1006 if (!is_null($files)) {
1007 Term::insertFromFileFieldByItemId($item['id'], $files);
1008 if (!empty($item['file'])) {
1009 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
1013 ItemDeliveryData::update($item['id'], $delivery_data);
1015 self::updateThread($item['id']);
1017 // We only need to notfiy others when it is an original entry from us.
1018 // Only call the notifier when the item has some content relevant change.
1019 if ($item['origin'] && in_array('edited', array_keys($fields))) {
1020 $notify_items[] = $item['id'];
1027 foreach ($notify_items as $notify_item) {
1028 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1035 * @brief Delete an item and notify others about it - if it was ours
1037 * @param array $condition The condition for finding the item entries
1038 * @param integer $priority Priority for the notification
1039 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1041 public static function delete($condition, $priority = PRIORITY_HIGH)
1043 $items = self::select(['id'], $condition);
1044 while ($item = self::fetch($items)) {
1045 self::deleteById($item['id'], $priority);
1051 * @brief Delete an item for an user and notify others about it - if it was ours
1053 * @param array $condition The condition for finding the item entries
1054 * @param integer $uid User who wants to delete this item
1055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1057 public static function deleteForUser($condition, $uid)
1063 $items = self::select(['id', 'uid'], $condition);
1064 while ($item = self::fetch($items)) {
1065 // "Deleting" global items just means hiding them
1066 if ($item['uid'] == 0) {
1067 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1068 } elseif ($item['uid'] == $uid) {
1069 self::deleteById($item['id'], PRIORITY_HIGH);
1071 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1078 * @brief Delete an item and notify others about it - if it was ours
1080 * @param integer $item_id Item ID that should be delete
1081 * @param integer $priority Priority for the notification
1083 * @return boolean success
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
1088 // locate item to be deleted
1089 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1090 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1091 'verb', 'object-type', 'object', 'target', 'contact-id',
1092 'icid', 'iaid', 'psid'];
1093 $item = self::selectFirst($fields, ['id' => $item_id]);
1094 if (!DBA::isResult($item)) {
1095 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1099 if ($item['deleted']) {
1100 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1104 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1105 if (!DBA::isResult($parent)) {
1106 $parent = ['origin' => false];
1109 // clean up categories and tags so they don't end up as orphans
1112 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1115 foreach ($matches as $mtch) {
1116 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1122 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1125 foreach ($matches as $mtch) {
1126 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1131 * If item is a link to a photo resource, nuke all the associated photos
1132 * (visitors will not have photo resources)
1133 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1134 * generate a resource-id and therefore aren't intimately linked to the item.
1136 /// @TODO: this should first check if photo is used elsewhere
1137 if (strlen($item['resource-id'])) {
1138 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1141 // If item is a link to an event, delete the event.
1142 if (intval($item['event-id'])) {
1143 Event::delete($item['event-id']);
1146 // If item has attachments, drop them
1147 /// @TODO: this should first check if attachment is used elsewhere
1148 foreach (explode(",", $item['attach']) as $attach) {
1149 preg_match("|attach/(\d+)|", $attach, $matches);
1150 if (is_array($matches) && count($matches) > 1) {
1151 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1155 // Delete tags that had been attached to other items
1156 self::deleteTagsFromItem($item);
1158 // Set the item to "deleted"
1159 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1160 DBA::update('item', $item_fields, ['id' => $item['id']]);
1162 Term::insertFromTagFieldByItemId($item['id'], '');
1163 Term::insertFromFileFieldByItemId($item['id'], '');
1164 self::deleteThread($item['id'], $item['parent-uri']);
1166 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1167 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1170 ItemDeliveryData::delete($item['id']);
1172 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1174 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1175 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1177 // When the permission set will be used in photo and events as well,
1178 // this query here needs to be extended.
1179 // @todo Currently deactivated. We need the permission set in the deletion process.
1180 // This is a reminder to add the removal somewhere else.
1181 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1182 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1185 // If it's the parent of a comment thread, kill all the kids
1186 if ($item['id'] == $item['parent']) {
1187 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1190 // Is it our comment and/or our thread?
1191 if ($item['origin'] || $parent['origin']) {
1193 // When we delete the original post we will delete all existing copies on the server as well
1194 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1196 // send the notification upstream/downstream
1197 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1198 } elseif ($item['uid'] != 0) {
1200 // When we delete just our local user copy of an item, we have to set a marker to hide it
1201 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1202 if (DBA::isResult($global_item)) {
1203 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1207 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1212 private static function deleteTagsFromItem($item)
1214 if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity\ObjectType::TAGTERM)) {
1218 $xo = XML::parseString($item["object"], false);
1219 $xt = XML::parseString($item["target"], false);
1221 if ($xt->type != Activity\ObjectType::NOTE) {
1225 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1226 if (!DBA::isResult($i)) {
1230 // For tags, the owner cannot remove the tag on the author's copy of the post.
1231 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1232 $author_copy = $item["origin"];
1234 if (($owner_remove && $author_copy) || !$owner_remove) {
1238 $tags = explode(',', $i["tag"]);
1241 foreach ($tags as $tag) {
1242 if (trim($tag) !== trim($xo->body)) {
1243 $newtags[] = trim($tag);
1247 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1250 private static function guid($item, $notify)
1252 if (!empty($item['guid'])) {
1253 return Strings::escapeTags(trim($item['guid']));
1257 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1258 // We add the hash of our own host because our host is the original creator of the post.
1259 $prefix_host = \get_app()->getHostName();
1263 // We are only storing the post so we create a GUID from the original hostname.
1264 if (!empty($item['author-link'])) {
1265 $parsed = parse_url($item['author-link']);
1266 if (!empty($parsed['host'])) {
1267 $prefix_host = $parsed['host'];
1271 if (empty($prefix_host) && !empty($item['plink'])) {
1272 $parsed = parse_url($item['plink']);
1273 if (!empty($parsed['host'])) {
1274 $prefix_host = $parsed['host'];
1278 if (empty($prefix_host) && !empty($item['uri'])) {
1279 $parsed = parse_url($item['uri']);
1280 if (!empty($parsed['host'])) {
1281 $prefix_host = $parsed['host'];
1285 // Is it in the format data@host.tld? - Used for mail contacts
1286 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1287 $mailparts = explode('@', $item['author-link']);
1288 $prefix_host = array_pop($mailparts);
1292 if (!empty($item['plink'])) {
1293 $guid = self::guidFromUri($item['plink'], $prefix_host);
1294 } elseif (!empty($item['uri'])) {
1295 $guid = self::guidFromUri($item['uri'], $prefix_host);
1297 $guid = System::createUUID(hash('crc32', $prefix_host));
1303 private static function contactId($item)
1305 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1306 return $item['contact-id'];
1307 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1308 return $item['contact-id'];
1309 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1310 return $item['author-id'];
1311 } elseif (!empty($item['contact-id'])) {
1312 return $item['contact-id'];
1314 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1315 if (!empty($contact_id)) {
1319 return $item['author-id'];
1322 // This function will finally cover most of the preparation functionality in mod/item.php
1323 public static function prepare(&$item)
1326 * @TODO: Unused code triggering inspection errors
1328 $data = BBCode::getAttachmentData($item['body']);
1329 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1330 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1331 $posttype = Item::PT_PAGE;
1332 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1338 * Write an item array into a spool file to be inserted later.
1339 * This command is called whenever there are issues storing an item.
1341 * @param array $item The item fields that are to be inserted
1342 * @throws \Exception
1344 private static function spool($orig_item)
1346 // Now we store the data in the spool directory
1347 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1348 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1350 $spoolpath = get_spoolpath();
1351 if ($spoolpath != "") {
1352 $spool = $spoolpath . '/' . $file;
1354 file_put_contents($spool, json_encode($orig_item));
1355 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1359 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1363 $priority = PRIORITY_HIGH;
1365 // If it is a posting where users should get notifications, then define it as wall posting
1368 $item['origin'] = 1;
1369 $item['network'] = Protocol::DFRN;
1370 $item['protocol'] = Conversation::PARCEL_DFRN;
1372 if (is_int($notify)) {
1373 $priority = $notify;
1376 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1379 $item['guid'] = self::guid($item, $notify);
1380 $item['uri'] = Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid'])));
1383 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1385 // Store conversation data
1386 $item = Conversation::insert($item);
1389 * If a Diaspora signature structure was passed in, pull it out of the
1390 * item array and set it aside for later storage.
1394 if (isset($item['dsprsig'])) {
1395 $encoded_signature = $item['dsprsig'];
1396 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1397 unset($item['dsprsig']);
1400 $diaspora_signed_text = '';
1401 if (isset($item['diaspora_signed_text'])) {
1402 $diaspora_signed_text = $item['diaspora_signed_text'];
1403 unset($item['diaspora_signed_text']);
1406 // Converting the plink
1407 /// @TODO Check if this is really still needed
1408 if ($item['network'] == Protocol::OSTATUS) {
1409 if (isset($item['plink'])) {
1410 $item['plink'] = OStatus::convertHref($item['plink']);
1411 } elseif (isset($item['uri'])) {
1412 $item['plink'] = OStatus::convertHref($item['uri']);
1416 if (!empty($item['thr-parent'])) {
1417 $item['parent-uri'] = $item['thr-parent'];
1420 /** @var Activity $activity */
1421 $activity = self::getClass(Activity::class);
1423 if (isset($item['gravity'])) {
1424 $item['gravity'] = intval($item['gravity']);
1425 } elseif ($item['parent-uri'] === $item['uri']) {
1426 $item['gravity'] = GRAVITY_PARENT;
1427 } elseif ($activity->match($item['verb'], Activity::POST)) {
1428 $item['gravity'] = GRAVITY_COMMENT;
1429 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1430 $item['gravity'] = GRAVITY_ACTIVITY;
1432 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1433 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1436 $uid = intval($item['uid']);
1438 // check for create date and expire time
1439 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1441 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1442 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1443 $expire_interval = $user['expire'];
1446 if (($expire_interval > 0) && !empty($item['created'])) {
1447 $expire_date = time() - ($expire_interval * 86400);
1448 $created_date = strtotime($item['created']);
1449 if ($created_date < $expire_date) {
1450 Logger::notice('Item created before expiration interval.', [
1451 'created' => date('c', $created_date),
1452 'expired' => date('c', $expire_date),
1460 * Do we already have this item?
1461 * We have to check several networks since Friendica posts could be repeated
1462 * via OStatus (maybe Diasporsa as well)
1464 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1465 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1466 trim($item['uri']), $item['uid'],
1467 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1468 $existing = self::selectFirst(['id', 'network'], $condition);
1469 if (DBA::isResult($existing)) {
1470 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1472 Logger::notice('Item already existed for user', [
1473 'uri' => $item['uri'],
1475 'network' => $item['network'],
1476 'existing_id' => $existing["id"],
1477 'existing_network' => $existing["network"]
1481 return $existing["id"];
1485 $item['wall'] = intval($item['wall'] ?? 0);
1486 $item['extid'] = trim($item['extid'] ?? '');
1487 $item['author-name'] = trim($item['author-name'] ?? '');
1488 $item['author-link'] = trim($item['author-link'] ?? '');
1489 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1490 $item['owner-name'] = trim($item['owner-name'] ?? '');
1491 $item['owner-link'] = trim($item['owner-link'] ?? '');
1492 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1493 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1494 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1495 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1496 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1497 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1498 $item['title'] = trim($item['title'] ?? '');
1499 $item['location'] = trim($item['location'] ?? '');
1500 $item['coord'] = trim($item['coord'] ?? '');
1501 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1502 $item['deleted'] = 0;
1503 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1504 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1505 $item['verb'] = trim($item['verb'] ?? '');
1506 $item['object-type'] = trim($item['object-type'] ?? '');
1507 $item['object'] = trim($item['object'] ?? '');
1508 $item['target-type'] = trim($item['target-type'] ?? '');
1509 $item['target'] = trim($item['target'] ?? '');
1510 $item['plink'] = trim($item['plink'] ?? '');
1511 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1512 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1513 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1514 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1515 $item['private'] = intval($item['private'] ?? 0);
1516 $item['body'] = trim($item['body'] ?? '');
1517 $item['tag'] = trim($item['tag'] ?? '');
1518 $item['attach'] = trim($item['attach'] ?? '');
1519 $item['app'] = trim($item['app'] ?? '');
1520 $item['origin'] = intval($item['origin'] ?? 0);
1521 $item['postopts'] = trim($item['postopts'] ?? '');
1522 $item['resource-id'] = trim($item['resource-id'] ?? '');
1523 $item['event-id'] = intval($item['event-id'] ?? 0);
1524 $item['inform'] = trim($item['inform'] ?? '');
1525 $item['file'] = trim($item['file'] ?? '');
1527 // When there is no content then we don't post it
1528 if ($item['body'].$item['title'] == '') {
1529 Logger::notice('No body, no title.');
1533 self::addLanguageToItemArray($item);
1535 // Items cannot be stored before they happen ...
1536 if ($item['created'] > DateTimeFormat::utcNow()) {
1537 $item['created'] = DateTimeFormat::utcNow();
1540 // We haven't invented time travel by now.
1541 if ($item['edited'] > DateTimeFormat::utcNow()) {
1542 $item['edited'] = DateTimeFormat::utcNow();
1545 $item['plink'] = ($item['plink'] ?? '') ?: System::baseUrl() . '/display/' . urlencode($item['guid']);
1547 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1548 'photo' => $item['author-avatar'], 'network' => $item['network']];
1550 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, false, $default);
1552 if (Contact::isBlocked($item['author-id'])) {
1553 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1557 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1558 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1562 if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
1563 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1567 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1568 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1570 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, false, $default);
1572 if (Contact::isBlocked($item['owner-id'])) {
1573 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1577 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1578 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1582 if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
1583 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1587 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1588 if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
1589 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1593 if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
1594 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1598 // We don't store the causer, we only have it here for the checks above
1599 unset($item['causer-id']);
1600 unset($item['causer-link']);
1602 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1603 $item["contact-id"] = self::contactId($item);
1605 if ($item['network'] == Protocol::PHANTOM) {
1606 $item['network'] = Protocol::DFRN;
1607 Logger::notice('Missing network, setting to {network}.', [
1608 'uri' => $item["uri"],
1609 'network' => $item['network'],
1610 'callstack' => System::callstack()
1614 // Checking if there is already an item with the same guid
1615 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1616 if (self::exists($condition)) {
1617 Logger::notice('Found already existing item', [
1618 'guid' => $item['guid'],
1619 'uid' => $item['uid'],
1620 'network' => $item['network']
1625 if ($item['verb'] == Activity::FOLLOW) {
1626 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1627 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1628 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1632 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1633 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1634 if (self::exists($condition)) {
1635 // It happens that we receive multiple follow requests by the same author - we only store one.
1636 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1641 // Check for hashtags in the body and repair or add hashtag links
1642 self::setHashtags($item);
1644 $item['thr-parent'] = $item['parent-uri'];
1646 $notify_type = Delivery::POST;
1652 if ($item['parent-uri'] === $item['uri']) {
1654 $parent_deleted = 0;
1655 $allow_cid = $item['allow_cid'];
1656 $allow_gid = $item['allow_gid'];
1657 $deny_cid = $item['deny_cid'];
1658 $deny_gid = $item['deny_gid'];
1660 // find the parent and snarf the item id and ACLs
1661 // and anything else we need to inherit
1663 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1664 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1665 'wall', 'private', 'forum_mode', 'origin'];
1666 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1667 $params = ['order' => ['id' => false]];
1668 $parent = self::selectFirst($fields, $condition, $params);
1670 if (DBA::isResult($parent)) {
1671 // is the new message multi-level threaded?
1672 // even though we don't support it now, preserve the info
1673 // and re-attach to the conversation parent.
1675 if ($parent['uri'] != $parent['parent-uri']) {
1676 $item['parent-uri'] = $parent['parent-uri'];
1678 $condition = ['uri' => $item['parent-uri'],
1679 'parent-uri' => $item['parent-uri'],
1680 'uid' => $item['uid']];
1681 $params = ['order' => ['id' => false]];
1682 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1684 if (DBA::isResult($toplevel_parent)) {
1685 $parent = $toplevel_parent;
1689 $parent_id = $parent['id'];
1690 $parent_deleted = $parent['deleted'];
1691 $allow_cid = $parent['allow_cid'];
1692 $allow_gid = $parent['allow_gid'];
1693 $deny_cid = $parent['deny_cid'];
1694 $deny_gid = $parent['deny_gid'];
1695 $item['wall'] = $parent['wall'];
1698 * If the parent is private, force privacy for the entire conversation
1699 * This differs from the above settings as it subtly allows comments from
1700 * email correspondents to be private even if the overall thread is not.
1702 if ($parent['private']) {
1703 $item['private'] = $parent['private'];
1707 * Edge case. We host a public forum that was originally posted to privately.
1708 * The original author commented, but as this is a comment, the permissions
1709 * weren't fixed up so it will still show the comment as private unless we fix it here.
1711 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1712 $item['private'] = 0;
1715 // If its a post that originated here then tag the thread as "mention"
1716 if ($item['origin'] && $item['uid']) {
1717 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1718 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1722 * Allow one to see reply tweets from status.net even when
1723 * we don't have or can't see the original post.
1725 if ($force_parent) {
1726 Logger::log('$force_parent=true, reply converted to top-level post.');
1728 $item['parent-uri'] = $item['uri'];
1729 $item['gravity'] = GRAVITY_PARENT;
1731 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1735 $parent_deleted = 0;
1739 if (stristr($item['verb'], Activity::POKE)) {
1740 $notify_type = Delivery::POKE;
1743 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1744 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1746 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1747 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1748 if (self::exists($condition)) {
1749 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1753 // On Friendica and Diaspora the GUID is unique
1754 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1755 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1756 if (self::exists($condition)) {
1757 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1760 } elseif ($item['network'] == Protocol::OSTATUS) {
1761 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1762 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1763 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1764 if (self::exists($condition)) {
1765 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1770 // Is this item available in the global items (with uid=0)?
1771 if ($item["uid"] == 0) {
1772 $item["global"] = true;
1774 // Set the global flag on all items if this was a global item entry
1775 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1777 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1781 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1784 $private = $item['private'];
1787 $item["allow_cid"] = $allow_cid;
1788 $item["allow_gid"] = $allow_gid;
1789 $item["deny_cid"] = $deny_cid;
1790 $item["deny_gid"] = $deny_gid;
1791 $item["private"] = $private;
1792 $item["deleted"] = $parent_deleted;
1794 // Fill the cache field
1795 self::putInCache($item);
1798 $item['edit'] = false;
1799 $item['parent'] = $parent_id;
1800 Hook::callAll('post_local', $item);
1801 unset($item['edit']);
1802 unset($item['parent']);
1804 Hook::callAll('post_remote', $item);
1807 // This array field is used to trigger some automatic reactions
1808 // It is mainly used in the "post_local" hook.
1809 unset($item['api_source']);
1811 if (!empty($item['cancel'])) {
1812 Logger::log('post cancelled by addon.');
1817 * Check for already added items.
1818 * There is a timing issue here that sometimes creates double postings.
1819 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1821 if ($item["uid"] == 0) {
1822 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1823 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1828 Logger::log('' . print_r($item,true), Logger::DATA);
1830 if (array_key_exists('tag', $item)) {
1831 $tags = $item['tag'];
1832 unset($item['tag']);
1837 if (array_key_exists('file', $item)) {
1838 $files = $item['file'];
1839 unset($item['file']);
1844 // Creates or assigns the permission set
1845 $item['psid'] = PermissionSet::fetchIDForPost($item);
1847 // We are doing this outside of the transaction to avoid timing problems
1848 if (!self::insertActivity($item)) {
1849 self::insertContent($item);
1852 $delivery_data = ItemDeliveryData::extractFields($item);
1854 unset($item['postopts']);
1855 unset($item['inform']);
1857 // These fields aren't stored anymore in the item table, they are fetched upon request
1858 unset($item['author-link']);
1859 unset($item['author-name']);
1860 unset($item['author-avatar']);
1861 unset($item['author-network']);
1863 unset($item['owner-link']);
1864 unset($item['owner-name']);
1865 unset($item['owner-avatar']);
1867 $like_no_comment = Config::get('system', 'like_no_comment');
1870 $ret = DBA::insert('item', $item);
1872 // When the item was successfully stored we fetch the ID of the item.
1873 if (DBA::isResult($ret)) {
1874 $current_post = DBA::lastInsertId();
1876 // This can happen - for example - if there are locking timeouts.
1879 // Store the data into a spool file so that we can try again later.
1880 self::spool($orig_item);
1884 if ($current_post == 0) {
1885 // This is one of these error messages that never should occur.
1886 Logger::log("couldn't find created item - we better quit now.");
1891 // How much entries have we created?
1892 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1893 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1896 // There are duplicates. We delete our just created entry.
1897 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1899 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1900 DBA::delete('item', ['id' => $current_post]);
1903 } elseif ($entries == 0) {
1904 // This really should never happen since we quit earlier if there were problems.
1905 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1910 Logger::log('created item '.$current_post);
1912 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1913 $parent_id = $current_post;
1917 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1919 $item['id'] = $current_post;
1920 $item['parent'] = $parent_id;
1922 // update the commented timestamp on the parent
1923 // Only update "commented" if it is really a comment
1924 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1925 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1927 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1932 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1933 * We can check for this condition when we decode and encode the stuff again.
1935 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1936 $dsprsig->signature = base64_decode($dsprsig->signature);
1937 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1940 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1941 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1943 // The other fields are used by very old Friendica servers, so we currently store them differently
1944 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1945 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1949 if (!empty($diaspora_signed_text)) {
1950 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1953 if ($item['parent-uri'] === $item['uri']) {
1954 self::addThread($current_post);
1956 self::updateThread($parent_id);
1959 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1960 ItemDeliveryData::insert($current_post, $delivery_data);
1966 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1967 * This is not perfect - but a workable solution until we found the reason for the problem.
1969 if (!empty($tags)) {
1970 Term::insertFromTagFieldByItemId($current_post, $tags);
1973 if (!empty($files)) {
1974 Term::insertFromFileFieldByItemId($current_post, $files);
1977 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1978 if (self::tagDeliver($item['uid'], $current_post)) {
1979 // Get the user information for the logging
1980 $user = User::getById($uid);
1982 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
1987 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1988 if (DBA::isResult($posted_item)) {
1990 Hook::callAll('post_local_end', $posted_item);
1992 Hook::callAll('post_remote_end', $posted_item);
1995 Logger::log('new item not found in DB, id ' . $current_post);
1999 if ($item['parent-uri'] === $item['uri']) {
2000 self::addShadow($current_post);
2002 self::addShadowPost($current_post);
2005 self::updateContact($item);
2007 check_user_notification($current_post);
2009 if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
2010 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
2013 return $current_post;
2017 * @brief Insert a new item content entry
2019 * @param array $item The item fields that are to be inserted
2021 * @throws \Exception
2023 private static function insertActivity(&$item)
2025 $activity_index = self::activityToIndex($item['verb']);
2027 if ($activity_index < 0) {
2031 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2033 // We just remove everything that is content
2034 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2035 unset($item[$field]);
2038 // To avoid timing problems, we are using locks.
2039 $locked = Lock::acquire('item_insert_activity');
2041 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2044 // Do we already have this content?
2045 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
2046 if (DBA::isResult($item_activity)) {
2047 $item['iaid'] = $item_activity['id'];
2048 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2049 } elseif (DBA::insert('item-activity', $fields)) {
2050 $item['iaid'] = DBA::lastInsertId();
2051 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2053 // This shouldn't happen.
2054 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
2055 Lock::release('item_insert_activity');
2059 Lock::release('item_insert_activity');
2065 * @brief Insert a new item content entry
2067 * @param array $item The item fields that are to be inserted
2068 * @throws \Exception
2070 private static function insertContent(&$item)
2072 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2074 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2075 if (isset($item[$field])) {
2076 $fields[$field] = $item[$field];
2077 unset($item[$field]);
2081 // To avoid timing problems, we are using locks.
2082 $locked = Lock::acquire('item_insert_content');
2084 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2087 // Do we already have this content?
2088 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2089 if (DBA::isResult($item_content)) {
2090 $item['icid'] = $item_content['id'];
2091 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2092 } elseif (DBA::insert('item-content', $fields)) {
2093 $item['icid'] = DBA::lastInsertId();
2094 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2096 // This shouldn't happen.
2097 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2100 Lock::release('item_insert_content');
2105 * @brief Update existing item content entries
2107 * @param array $item The item fields that are to be changed
2108 * @param array $condition The condition for finding the item content entries
2110 * @throws \Exception
2112 private static function updateActivity($item, $condition)
2114 if (empty($item['verb'])) {
2117 $activity_index = self::activityToIndex($item['verb']);
2119 if ($activity_index < 0) {
2123 $fields = ['activity' => $activity_index];
2125 Logger::log('Update activity for ' . json_encode($condition));
2127 DBA::update('item-activity', $fields, $condition, true);
2133 * @brief Update existing item content entries
2135 * @param array $item The item fields that are to be changed
2136 * @param array $condition The condition for finding the item content entries
2137 * @throws \Exception
2139 private static function updateContent($item, $condition)
2141 // We have to select only the fields from the "item-content" table
2143 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2144 if (isset($item[$field])) {
2145 $fields[$field] = $item[$field];
2149 if (empty($fields)) {
2150 // when there are no fields at all, just use the condition
2151 // This is to ensure that we always store content.
2152 $fields = $condition;
2155 Logger::log('Update content for ' . json_encode($condition));
2157 DBA::update('item-content', $fields, $condition, true);
2161 * @brief Distributes public items to the receivers
2163 * @param integer $itemid Item ID that should be added
2164 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2165 * @throws \Exception
2167 public static function distribute($itemid, $signed_text = '')
2169 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2170 $parent = self::selectFirst(['owner-id'], $condition);
2171 if (!DBA::isResult($parent)) {
2175 // Only distribute public items from native networks
2176 $condition = ['id' => $itemid, 'uid' => 0,
2177 'network' => array_merge(Protocol::FEDERATED ,['']),
2178 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2179 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2180 if (!DBA::isResult($item)) {
2184 $origin = $item['origin'];
2187 unset($item['parent']);
2188 unset($item['mention']);
2189 unset($item['wall']);
2190 unset($item['origin']);
2191 unset($item['starred']);
2195 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2196 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2197 if (!DBA::isResult($owner)) {
2201 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2202 $contacts = DBA::select('contact', ['uid'], $condition);
2203 while ($contact = DBA::fetch($contacts)) {
2204 if ($contact['uid'] == 0) {
2208 $users[$contact['uid']] = $contact['uid'];
2210 DBA::close($contacts);
2212 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2213 $contacts = DBA::select('contact', ['uid'], $condition);
2214 while ($contact = DBA::fetch($contacts)) {
2215 if ($contact['uid'] == 0) {
2219 $users[$contact['uid']] = $contact['uid'];
2221 DBA::close($contacts);
2223 if (!empty($owner['alias'])) {
2224 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2225 $contacts = DBA::select('contact', ['uid'], $condition);
2226 while ($contact = DBA::fetch($contacts)) {
2227 if ($contact['uid'] == 0) {
2231 $users[$contact['uid']] = $contact['uid'];
2233 DBA::close($contacts);
2238 if ($item['uri'] != $item['parent-uri']) {
2239 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2240 while ($parent = self::fetch($parents)) {
2241 $users[$parent['uid']] = $parent['uid'];
2242 if ($parent['origin'] && !$origin) {
2243 $origin_uid = $parent['uid'];
2248 foreach ($users as $uid) {
2249 if ($origin_uid == $uid) {
2250 $item['diaspora_signed_text'] = $signed_text;
2252 self::storeForUser($itemid, $item, $uid);
2257 * @brief Store public items for the receivers
2259 * @param integer $itemid Item ID that should be added
2260 * @param array $item The item entry that will be stored
2261 * @param integer $uid The user that will receive the item entry
2262 * @throws \Exception
2264 private static function storeForUser($itemid, $item, $uid)
2266 $item['uid'] = $uid;
2267 $item['origin'] = 0;
2269 if ($item['uri'] == $item['parent-uri']) {
2270 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2272 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2275 if (empty($item['contact-id'])) {
2276 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2277 if (!DBA::isResult($self)) {
2280 $item['contact-id'] = $self['id'];
2283 /// @todo Handling of "event-id"
2286 if ($item['uri'] == $item['parent-uri']) {
2287 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2288 if (DBA::isResult($contact)) {
2289 $notify = self::isRemoteSelf($contact, $item);
2293 $distributed = self::insert($item, false, $notify, true);
2295 if (!$distributed) {
2296 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2298 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2303 * @brief Add a shadow entry for a given item id that is a thread starter
2305 * We store every public item entry additionally with the user id "0".
2306 * This is used for the community page and for the search.
2307 * It is planned that in the future we will store public item entries only once.
2309 * @param integer $itemid Item ID that should be added
2310 * @throws \Exception
2312 public static function addShadow($itemid)
2314 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2315 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2316 $item = self::selectFirst($fields, $condition);
2318 if (!DBA::isResult($item)) {
2322 // is it already a copy?
2323 if (($itemid == 0) || ($item['uid'] == 0)) {
2327 // Is it a visible public post?
2328 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2332 // is it an entry from a connector? Only add an entry for natively connected networks
2333 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2337 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2341 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2343 if (DBA::isResult($item)) {
2344 // Preparing public shadow (removing user specific data)
2347 unset($item['parent']);
2348 unset($item['wall']);
2349 unset($item['mention']);
2350 unset($item['origin']);
2351 unset($item['starred']);
2352 unset($item['postopts']);
2353 unset($item['inform']);
2354 if ($item['uri'] == $item['parent-uri']) {
2355 $item['contact-id'] = $item['owner-id'];
2357 $item['contact-id'] = $item['author-id'];
2360 $public_shadow = self::insert($item, false, false, true);
2362 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2367 * @brief Add a shadow entry for a given item id that is a comment
2369 * This function does the same like the function above - but for comments
2371 * @param integer $itemid Item ID that should be added
2372 * @throws \Exception
2374 public static function addShadowPost($itemid)
2376 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2377 if (!DBA::isResult($item)) {
2381 // Is it a toplevel post?
2382 if ($item['id'] == $item['parent']) {
2383 self::addShadow($itemid);
2387 // Is this a shadow entry?
2388 if ($item['uid'] == 0) {
2392 // Is there a shadow parent?
2393 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2397 // Is there already a shadow entry?
2398 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2402 // Save "origin" and "parent" state
2403 $origin = $item['origin'];
2404 $parent = $item['parent'];
2406 // Preparing public shadow (removing user specific data)
2409 unset($item['parent']);
2410 unset($item['wall']);
2411 unset($item['mention']);
2412 unset($item['origin']);
2413 unset($item['starred']);
2414 unset($item['postopts']);
2415 unset($item['inform']);
2416 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2418 $public_shadow = self::insert($item, false, false, true);
2420 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2422 // If this was a comment to a Diaspora post we don't get our comment back.
2423 // This means that we have to distribute the comment by ourselves.
2424 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2425 self::distribute($public_shadow);
2430 * Adds a language specification in a "language" element of given $arr.
2431 * Expects "body" element to exist in $arr.
2434 * @throws \Text_LanguageDetect_Exception
2436 private static function addLanguageToItemArray(&$item)
2438 $naked_body = BBCode::toPlaintext($item['body'], false);
2440 $ld = new Text_LanguageDetect();
2441 $ld->setNameMode(2);
2442 $languages = $ld->detect($naked_body, 3);
2444 if (is_array($languages)) {
2445 $item['language'] = json_encode($languages);
2450 * @brief Creates an unique guid out of a given uri
2452 * @param string $uri uri of an item entry
2453 * @param string $host hostname for the GUID prefix
2454 * @return string unique guid
2456 public static function guidFromUri($uri, $host)
2458 // Our regular guid routine is using this kind of prefix as well
2459 // We have to avoid that different routines could accidentally create the same value
2460 $parsed = parse_url($uri);
2462 // We use a hash of the hostname as prefix for the guid
2463 $guid_prefix = hash("crc32", $host);
2465 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2466 unset($parsed["scheme"]);
2468 // Glue it together to be able to make a hash from it
2469 $host_id = implode("/", $parsed);
2471 // We could use any hash algorithm since it isn't a security issue
2472 $host_hash = hash("ripemd128", $host_id);
2474 return $guid_prefix.$host_hash;
2478 * generate an unique URI
2480 * @param integer $uid User id
2481 * @param string $guid An existing GUID (Otherwise it will be generated)
2484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2486 public static function newURI($uid, $guid = "")
2489 $guid = System::createUUID();
2492 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2496 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2498 * This can be used to filter for inactive contacts.
2499 * Only do this for public postings to avoid privacy problems, since poco data is public.
2500 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2502 * @param array $arr Contains the just posted item record
2503 * @throws \Exception
2505 private static function updateContact($arr)
2507 // Unarchive the author
2508 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2509 if (DBA::isResult($contact)) {
2510 Contact::unmarkForArchival($contact);
2513 // Unarchive the contact if it's not our own contact
2514 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2515 if (DBA::isResult($contact)) {
2516 Contact::unmarkForArchival($contact);
2519 $update = (!$arr['private'] && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"])));
2521 // Is it a forum? Then we don't care about the rules from above
2522 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2523 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2529 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2530 ['id' => $arr['contact-id']]);
2532 // Now do the same for the system wide contacts with uid=0
2533 if (!$arr['private']) {
2534 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2535 ['id' => $arr['owner-id']]);
2537 if ($arr['owner-id'] != $arr['author-id']) {
2538 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2539 ['id' => $arr['author-id']]);
2544 public static function setHashtags(&$item)
2546 $tags = BBCode::getTags($item["body"]);
2549 if (!count($tags)) {
2553 // What happens in [code], stays in [code]!
2554 // escape the # and the [
2555 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2556 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2558 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2560 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2561 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2564 // This sorting is important when there are hashtags that are part of other hashtags
2565 // Otherwise there could be problems with hashtags like #test and #test2
2568 $URLSearchString = "^\[\]";
2570 // All hashtags should point to the home server if "local_tags" is activated
2571 if (Config::get('system', 'local_tags')) {
2572 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2573 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2575 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2576 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2579 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2580 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2582 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2585 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2587 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2590 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2592 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2595 // Repair recursive urls
2596 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2597 "#$2", $item["body"]);
2599 foreach ($tags as $tag) {
2600 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
2604 $basetag = str_replace('_',' ',substr($tag,1));
2605 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2607 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2609 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2610 if (strlen($item["tag"])) {
2611 $item["tag"] = ',' . $item["tag"];
2613 $item["tag"] = $newtag . $item["tag"];
2617 // Convert back the masked hashtags
2618 $item["body"] = str_replace("#", "#", $item["body"]);
2620 // Remember! What happens in [code], stays in [code]
2621 // roleback the # and [
2622 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2624 // we truly unESCape all sharp and leftsquarebracket
2625 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2626 $replace = ['#', '['];
2627 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2632 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2635 * @param int $item_id
2636 * @return boolean true if item was deleted, else false
2637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2638 * @throws \ImagickException
2640 private static function tagDeliver($uid, $item_id)
2644 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2645 if (!DBA::isResult($user)) {
2649 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2650 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2652 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2653 if (!DBA::isResult($item)) {
2657 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2660 * Diaspora uses their own hardwired link URL in @-tags
2661 * instead of the one we supply with webfinger
2663 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2665 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2667 foreach ($matches as $mtch) {
2668 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2670 Logger::log('mention found: ' . $mtch[2]);
2676 if (($community_page || $prvgroup) &&
2677 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2678 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2680 Logger::log("no-mention top-level post to community or private group. delete.");
2681 DBA::delete('item', ['id' => $item_id]);
2687 $arr = ['item' => $item, 'user' => $user];
2689 Hook::callAll('tagged', $arr);
2691 if (!$community_page && !$prvgroup) {
2696 * tgroup delivery - setup a second delivery chain
2697 * prevent delivery looping - only proceed
2698 * if the message originated elsewhere and is a top-level post
2700 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2704 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2705 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2706 if (!DBA::isResult($self)) {
2710 $owner_id = Contact::getIdForURL($self['url']);
2712 // also reset all the privacy bits to the forum default permissions
2714 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2716 $psid = PermissionSet::fetchIDForPost($user);
2718 $forum_mode = ($prvgroup ? 2 : 1);
2720 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2721 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2722 self::update($fields, ['id' => $item_id]);
2724 self::updateThread($item_id);
2726 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2731 public static function isRemoteSelf($contact, &$datarray)
2735 if (!$contact['remote_self']) {
2739 // Prevent the forwarding of posts that are forwarded
2740 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2741 Logger::log('Already forwarded', Logger::DEBUG);
2745 // Prevent to forward already forwarded posts
2746 if ($datarray["app"] == $a->getHostName()) {
2747 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2751 // Only forward posts
2752 if ($datarray["verb"] != Activity::POST) {
2753 Logger::log('No post', Logger::DEBUG);
2757 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2758 Logger::log('Not public', Logger::DEBUG);
2762 $datarray2 = $datarray;
2763 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2764 if ($contact['remote_self'] == 2) {
2765 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2766 ['uid' => $contact['uid'], 'self' => true]);
2767 if (DBA::isResult($self)) {
2768 $datarray['contact-id'] = $self["id"];
2770 $datarray['owner-name'] = $self["name"];
2771 $datarray['owner-link'] = $self["url"];
2772 $datarray['owner-avatar'] = $self["thumb"];
2774 $datarray['author-name'] = $datarray['owner-name'];
2775 $datarray['author-link'] = $datarray['owner-link'];
2776 $datarray['author-avatar'] = $datarray['owner-avatar'];
2778 unset($datarray['edited']);
2780 unset($datarray['network']);
2781 unset($datarray['owner-id']);
2782 unset($datarray['author-id']);
2785 if ($contact['network'] != Protocol::FEED) {
2786 $datarray["guid"] = System::createUUID();
2787 unset($datarray["plink"]);
2788 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2789 $datarray["parent-uri"] = $datarray["uri"];
2790 $datarray["thr-parent"] = $datarray["uri"];
2791 $datarray["extid"] = Protocol::DFRN;
2792 $urlpart = parse_url($datarray2['author-link']);
2793 $datarray["app"] = $urlpart["host"];
2795 $datarray['private'] = 0;
2799 if ($contact['network'] != Protocol::FEED) {
2800 // Store the original post
2801 $result = self::insert($datarray2, false, false);
2802 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2804 $datarray["app"] = "Feed";
2808 // Trigger automatic reactions for addons
2809 $datarray['api_source'] = true;
2811 // We have to tell the hooks who we are - this really should be improved
2812 $_SESSION["authenticated"] = true;
2813 $_SESSION["uid"] = $contact['uid'];
2822 * @param array $item
2825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2826 * @throws \ImagickException
2828 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2830 if (Config::get('system', 'disable_embedded')) {
2834 Logger::log('check for photos', Logger::DEBUG);
2835 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2840 $img_start = strpos($orig_body, '[img');
2841 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2842 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2844 while (($img_st_close !== false) && ($img_len !== false)) {
2845 $img_st_close++; // make it point to AFTER the closing bracket
2846 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2848 Logger::log('found photo ' . $image, Logger::DEBUG);
2850 if (stristr($image, $site . '/photo/')) {
2851 // Only embed locally hosted photos
2853 $i = basename($image);
2854 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2855 $x = strpos($i, '-');
2858 $res = substr($i, $x + 1);
2859 $i = substr($i, 0, $x);
2860 $photo = Photo::getPhotoForUser($uid, $i, $res);
2861 if (DBA::isResult($photo)) {
2863 * Check to see if we should replace this photo link with an embedded image
2864 * 1. No need to do so if the photo is public
2865 * 2. If there's a contact-id provided, see if they're in the access list
2866 * for the photo. If so, embed it.
2867 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2868 * permissions, regardless of order but first check to see if they're an exact
2869 * match to save some processing overhead.
2871 if (self::hasPermissions($photo)) {
2873 $recips = self::enumeratePermissions($photo);
2874 if (in_array($cid, $recips)) {
2878 if (self::samePermissions($uid, $item, $photo)) {
2884 $photo_img = Photo::getImageForPhoto($photo);
2885 // If a custom width and height were specified, apply before embedding
2886 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2887 Logger::log('scaling photo', Logger::DEBUG);
2889 $width = intval($match[1]);
2890 $height = intval($match[2]);
2892 $photo_img->scaleDown(max($width, $height));
2895 $data = $photo_img->asString();
2896 $type = $photo_img->getType();
2898 Logger::log('replacing photo', Logger::DEBUG);
2899 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2900 Logger::log('replaced: ' . $image, Logger::DATA);
2906 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2907 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2908 if ($orig_body === false) {
2912 $img_start = strpos($orig_body, '[img');
2913 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2914 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2917 $new_body = $new_body . $orig_body;
2922 private static function hasPermissions($obj)
2924 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2925 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2928 private static function samePermissions($uid, $obj1, $obj2)
2930 // first part is easy. Check that these are exactly the same.
2931 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2932 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2933 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2934 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2938 // This is harder. Parse all the permissions and compare the resulting set.
2939 $recipients1 = self::enumeratePermissions($obj1);
2940 $recipients2 = self::enumeratePermissions($obj2);
2944 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2945 return ($recipients1 == $recipients2);
2949 * Returns an array of contact-ids that are allowed to see this object
2951 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2952 * @param bool $check_dead Prunes unavailable contacts from the result
2954 * @throws \Exception
2956 public static function enumeratePermissions(array $obj, bool $check_dead = false)
2958 /** @var ACLFormatter $aclFormater */
2959 $aclFormater = self::getClass(ACLFormatter::class);
2961 $allow_people = $aclFormater->expand($obj['allow_cid']);
2962 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2963 $deny_people = $aclFormater->expand($obj['deny_cid']);
2964 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2965 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2966 $deny = array_unique(array_merge($deny_people, $deny_groups));
2967 $recipients = array_diff($recipients, $deny);
2971 public static function getFeedTags($item)
2975 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2977 for ($x = 0; $x < $cnt; $x ++) {
2978 if ($matches[1][$x]) {
2979 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2984 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2986 for ($x = 0; $x < $cnt; $x ++) {
2987 if ($matches[1][$x]) {
2988 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2995 public static function expire($uid, $days, $network = "", $force = false)
2997 if (!$uid || ($days < 1)) {
3001 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
3002 $uid, GRAVITY_PARENT];
3005 * $expire_network_only = save your own wall posts
3006 * and just expire conversations started by others
3008 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
3010 if ($expire_network_only) {
3011 $condition[0] .= " AND NOT `wall`";
3014 if ($network != "") {
3015 $condition[0] .= " AND `network` = ?";
3016 $condition[] = $network;
3019 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3020 $condition[] = $days;
3022 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3024 if (!DBA::isResult($items)) {
3028 $expire_items = PConfig::get($uid, 'expire', 'items', true);
3030 // Forcing expiring of items - but not notes and marked items
3032 $expire_items = true;
3035 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
3036 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
3037 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
3041 while ($item = Item::fetch($items)) {
3042 // don't expire filed items
3044 if (strpos($item['file'], '[') !== false) {
3048 // Only expire posts, not photos and photo comments
3050 if (!$expire_photos && strlen($item['resource-id'])) {
3052 } elseif (!$expire_starred && intval($item['starred'])) {
3054 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3056 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3060 self::deleteById($item['id'], PRIORITY_LOW);
3065 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3068 public static function firstPostDate($uid, $wall = false)
3070 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3071 $params = ['order' => ['received' => false]];
3072 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3073 if (DBA::isResult($thread)) {
3074 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3080 * @brief add/remove activity to an item
3082 * Toggle activities as like,dislike,attend of an item
3084 * @param string $item_id
3085 * @param string $verb
3086 * Activity verb. One of
3087 * like, unlike, dislike, undislike, attendyes, unattendyes,
3088 * attendno, unattendno, attendmaybe, unattendmaybe
3090 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3091 * @throws \ImagickException
3092 * @hook 'post_local_end'
3094 * 'post_id' => ID of posted item
3096 public static function performLike($item_id, $verb)
3098 if (!Session::isAuthenticated()) {
3105 $activity = Activity::LIKE;
3109 $activity = Activity::DISLIKE;
3113 $activity = Activity::ATTEND;
3117 $activity = Activity::ATTENDNO;
3120 case 'unattendmaybe':
3121 $activity = Activity::ATTENDMAYBE;
3124 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3128 // Enable activity toggling instead of on/off
3129 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3131 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3133 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3134 if (!DBA::isResult($item)) {
3135 Logger::log('like: unknown item ' . $item_id);
3139 $item_uri = $item['uri'];
3141 $uid = $item['uid'];
3142 if (($uid == 0) && local_user()) {
3143 $uid = local_user();
3146 if (!Security::canWriteToUserWall($uid)) {
3147 Logger::log('like: unable to write on wall ' . $uid);
3151 // Retrieves the local post owner
3152 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3153 if (!DBA::isResult($owner_self_contact)) {
3154 Logger::log('like: unknown owner ' . $uid);
3158 // Retrieve the current logged in user's public contact
3159 $author_id = public_contact();
3161 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3162 if (!DBA::isResult($author_contact)) {
3163 Logger::log('like: unknown author ' . $author_id);
3167 // Contact-id is the uid-dependant author contact
3168 if (local_user() == $uid) {
3169 $item_contact_id = $owner_self_contact['id'];
3171 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3172 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3173 if (!DBA::isResult($item_contact)) {
3174 Logger::log('like: unknown item contact ' . $item_contact_id);
3179 // Look for an existing verb row
3180 // event participation are essentially radio toggles. If you make a subsequent choice,
3181 // we need to eradicate your first choice.
3182 if ($event_verb_flag) {
3183 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3185 // Translate to the index based activity index
3187 foreach ($verbs as $verb) {
3188 $activities[] = self::activityToIndex($verb);
3191 $activities = self::activityToIndex($activity);
3194 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3195 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3197 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3199 // If it exists, mark it as deleted
3200 if (DBA::isResult($like_item)) {
3201 self::deleteById($like_item['id']);
3203 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3208 // Verb is "un-something", just trying to delete existing entries
3209 if (strpos($verb, 'un') === 0) {
3213 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3216 'guid' => System::createUUID(),
3217 'uri' => self::newURI($item['uid']),
3218 'uid' => $item['uid'],
3219 'contact-id' => $item_contact_id,
3220 'wall' => $item['wall'],
3222 'network' => Protocol::DFRN,
3223 'gravity' => GRAVITY_ACTIVITY,
3224 'parent' => $item['id'],
3225 'parent-uri' => $item['uri'],
3226 'thr-parent' => $item['uri'],
3227 'owner-id' => $author_id,
3228 'author-id' => $author_id,
3229 'body' => $activity,
3230 'verb' => $activity,
3231 'object-type' => $objtype,
3232 'allow_cid' => $item['allow_cid'],
3233 'allow_gid' => $item['allow_gid'],
3234 'deny_cid' => $item['deny_cid'],
3235 'deny_gid' => $item['deny_gid'],
3240 $signed = Diaspora::createLikeSignature($uid, $new_item);
3241 if (!empty($signed)) {
3242 $new_item['diaspora_signed_text'] = json_encode($signed);
3245 $new_item_id = self::insert($new_item);
3247 // If the parent item isn't visible then set it to visible
3248 if (!$item['visible']) {
3249 self::update(['visible' => true], ['id' => $item['id']]);
3252 $new_item['id'] = $new_item_id;
3254 Hook::callAll('post_local_end', $new_item);
3259 private static function addThread($itemid, $onlyshadow = false)
3261 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3262 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3263 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3264 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3265 $item = self::selectFirst($fields, $condition);
3267 if (!DBA::isResult($item)) {
3271 $item['iid'] = $itemid;
3274 $result = DBA::insert('thread', $item);
3276 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3280 private static function updateThread($itemid, $setmention = false)
3282 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3283 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3284 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3285 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3287 $item = self::selectFirst($fields, $condition);
3288 if (!DBA::isResult($item)) {
3293 $item["mention"] = 1;
3298 foreach ($item as $field => $data) {
3299 if (!in_array($field, ["guid"])) {
3300 $fields[$field] = $data;
3304 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3306 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3309 private static function deleteThread($itemid, $itemuri = "")
3311 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3312 if (!DBA::isResult($item)) {
3313 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3317 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3319 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3321 if ($itemuri != "") {
3322 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3323 if (!self::exists($condition)) {
3324 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3325 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3330 public static function getPermissionsSQLByUserId($owner_id)
3332 $local_user = local_user();
3333 $remote_user = Session::getRemoteContactID($owner_id);
3336 * Construct permissions
3338 * default permissions - anonymous user
3340 $sql = " AND NOT `item`.`private`";
3342 // Profile owner - everything is visible
3343 if ($local_user && ($local_user == $owner_id)) {
3345 } elseif ($remote_user) {
3347 * Authenticated visitor. Unless pre-verified,
3348 * check that the contact belongs to this $owner_id
3349 * and load the groups the visitor belongs to.
3350 * If pre-verified, the caller is expected to have already
3351 * done this and passed the groups into this function.
3353 $set = PermissionSet::get($owner_id, $remote_user);
3356 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3361 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3368 * get translated item type
3373 public static function postType($item)
3375 if (!empty($item['event-id'])) {
3376 return L10n::t('event');
3377 } elseif (!empty($item['resource-id'])) {
3378 return L10n::t('photo');
3379 } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) {
3380 return L10n::t('activity');
3381 } elseif ($item['id'] != $item['parent']) {
3382 return L10n::t('comment');
3385 return L10n::t('post');
3389 * Sets the "rendered-html" field of the provided item
3391 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3393 * @param array $item
3394 * @param bool $update
3396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3397 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3399 public static function putInCache(&$item, $update = false)
3401 $body = $item["body"];
3403 $rendered_hash = $item['rendered-hash'] ?? '';
3404 $rendered_html = $item['rendered-html'] ?? '';
3406 if ($rendered_hash == ''
3407 || $rendered_html == ""
3408 || $rendered_hash != hash("md5", $item["body"])
3409 || Config::get("system", "ignore_cache")
3411 self::addRedirToImageTags($item);
3413 $item["rendered-html"] = BBCode::convert($item["body"]);
3414 $item["rendered-hash"] = hash("md5", $item["body"]);
3416 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3417 Hook::callAll('put_item_in_cache', $hook_data);
3418 $item['rendered-html'] = $hook_data['rendered-html'];
3419 $item['rendered-hash'] = $hook_data['rendered-hash'];
3422 // Force an update if the generated values differ from the existing ones
3423 if ($rendered_hash != $item["rendered-hash"]) {
3427 // Only compare the HTML when we forcefully ignore the cache
3428 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3432 if ($update && !empty($item["id"])) {
3435 'rendered-html' => $item["rendered-html"],
3436 'rendered-hash' => $item["rendered-hash"]
3438 ['id' => $item["id"]]
3443 $item["body"] = $body;
3447 * @brief Find any non-embedded images in private items and add redir links to them
3449 * @param array &$item The field array of an item row
3451 private static function addRedirToImageTags(array &$item)
3453 $app = self::getApp();
3456 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3458 foreach ($matches as $mtch) {
3459 if (strpos($mtch[1], '/redir') !== false) {
3463 if ((local_user() == $item['uid']) && ($item['private'] == 1) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3464 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3465 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3472 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3473 * If attach is true, also add icons for item attachments.
3475 * @param array $item
3476 * @param boolean $attach
3477 * @param boolean $is_preview
3478 * @return string item body html
3479 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3480 * @throws \ImagickException
3481 * @hook prepare_body_init item array before any work
3482 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3483 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3484 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3486 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3488 $a = self::getApp();
3489 Hook::callAll('prepare_body_init', $item);
3491 // In order to provide theme developers more possibilities, event items
3492 // are treated differently.
3493 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3494 $ev = Event::getItemHTML($item);
3498 $tags = Term::populateTagsFromItem($item);
3500 $item['tags'] = $tags['tags'];
3501 $item['hashtags'] = $tags['hashtags'];
3502 $item['mentions'] = $tags['mentions'];
3504 // Compile eventual content filter reasons
3505 $filter_reasons = [];
3506 if (!$is_preview && public_contact() != $item['author-id']) {
3507 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3508 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3513 'filter_reasons' => $filter_reasons
3515 Hook::callAll('prepare_body_content_filter', $hook_data);
3516 $filter_reasons = $hook_data['filter_reasons'];
3520 // Update the cached values if there is no "zrl=..." on the links.
3521 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3523 // Or update it if the current viewer is the intented viewer.
3524 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3528 self::putInCache($item, $update);
3529 $s = $item["rendered-html"];
3534 'preview' => $is_preview,
3535 'filter_reasons' => $filter_reasons
3537 Hook::callAll('prepare_body', $hook_data);
3538 $s = $hook_data['html'];
3542 // Replace the blockquotes with quotes that are used in mails.
3543 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3544 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3551 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3552 foreach ($matches as $mtch) {
3555 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3557 if (strpos($mime, 'video') !== false) {
3560 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3563 $url_parts = explode('/', $the_url);
3564 $id = end($url_parts);
3565 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3568 'title' => L10n::t('View Video'),
3575 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3577 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3578 $filesubtype = str_replace('.', '-', $filesubtype);
3581 $filesubtype = 'unkn';
3584 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3585 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3587 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3588 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3592 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3596 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3597 $x = Map::byCoordinates(trim($item['coord']));
3599 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3603 // Replace friendica image url size with theme preference.
3604 if (!empty($a->theme_info['item_image_size'])) {
3605 $ps = $a->theme_info['item_image_size'];
3606 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3609 $s = HTML::applyContentFilter($s, $filter_reasons);
3611 $hook_data = ['item' => $item, 'html' => $s];
3612 Hook::callAll('prepare_body_final', $hook_data);
3614 return $hook_data['html'];
3618 * get private link for item
3620 * @param array $item
3621 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3622 * @throws \Exception
3624 public static function getPlink($item)
3626 $a = self::getApp();
3628 if ($a->user['nickname'] != "") {
3630 'href' => "display/" . $item['guid'],
3631 'orig' => "display/" . $item['guid'],
3632 'title' => L10n::t('View on separate page'),
3633 'orig_title' => L10n::t('view on separate page'),
3636 if (!empty($item['plink'])) {
3637 $ret["href"] = $a->removeBaseURL($item['plink']);
3638 $ret["title"] = L10n::t('link to source');
3641 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3643 'href' => $item['plink'],
3644 'orig' => $item['plink'],
3645 'title' => L10n::t('link to source'),
3655 * Is the given item array a post that is sent as starting post to a forum?
3657 * @param array $item
3658 * @param array $owner
3660 * @return boolean "true" when it is a forum post
3662 public static function isForumPost(array $item, array $owner = [])
3664 if (empty($owner)) {
3665 $owner = User::getOwnerDataById($item['uid']);
3666 if (empty($owner)) {
3671 if (($item['author-id'] == $item['owner-id']) ||
3672 ($owner['id'] == $item['contact-id']) ||
3673 ($item['uri'] != $item['parent-uri']) ||
3678 return Contact::isForum($item['contact-id']);
3682 * Search item id for given URI or plink
3684 * @param string $uri
3685 * @param integer $uid
3687 * @return integer item id
3689 public static function searchByLink($uri, $uid = 0)
3691 $ssl_uri = str_replace('http://', 'https://', $uri);
3692 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3694 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3695 if (DBA::isResult($item)) {
3699 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3700 if (!DBA::isResult($itemcontent)) {
3704 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3705 if (!DBA::isResult($itemuri)) {
3709 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3710 if (DBA::isResult($item)) {
3718 * Fetches item for given URI or plink
3720 * @param string $uri
3721 * @param integer $uid
3723 * @return integer item id
3725 public static function fetchByLink($uri, $uid = 0)
3727 $item_id = self::searchByLink($uri, $uid);
3728 if (!empty($item_id)) {
3732 if (ActivityPub\Processor::fetchMissingActivity($uri)) {
3733 $item_id = self::searchByLink($uri, $uid);
3735 $item_id = Diaspora::fetchByURL($uri);
3738 if (!empty($item_id)) {