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\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Map;
28 use Friendica\Util\Network;
29 use Friendica\Util\Security;
30 use Friendica\Util\Strings;
31 use Friendica\Util\XML;
32 use Friendica\Worker\Delivery;
33 use Text_LanguageDetect;
35 class Item extends BaseObject
37 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
44 const PT_DOCUMENT = 19;
46 const PT_PERSONAL_NOTE = 128;
48 // Field list that is used to display the items
49 const DISPLAY_FIELDLIST = [
50 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
51 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
52 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
53 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
54 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
55 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
56 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
57 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
58 'writable', 'self', 'cid', 'alias',
59 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
60 'event-summary', 'event-desc', 'event-location', 'event-type',
61 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
62 'delivery_queue_count', 'delivery_queue_done'
65 // Field list that is used to deliver items via the protocols
66 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
67 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
68 'private', 'title', 'body', 'location', 'coord', 'app',
69 'attach', 'tag', 'deleted', 'extid', 'post-type',
70 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
71 'author-id', 'author-link', 'owner-link', 'contact-uid',
72 'signed_text', 'signature', 'signer', 'network'];
74 // Field list for "item-content" table that is mixed with the item table
75 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
76 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
77 'object-type', 'object', 'target-type', 'target', 'plink'];
79 // Field list for "item-content" table that is not present in the "item" table
80 const CONTENT_FIELDLIST = ['language'];
82 // All fields in the item table
83 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
84 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
85 'created', 'edited', 'commented', 'received', 'changed', 'verb',
86 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
87 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
88 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
89 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
90 'title', 'content-warning', 'body', 'location', 'coord', 'app',
91 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
92 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
93 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
95 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
96 // The item-activity table only stores the index and needs this array to know the matching activity.
97 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE, ACTIVITY_FOLLOW, ACTIVITY2_ANNOUNCE];
99 private static $legacy_mode = null;
101 public static function isLegacyMode()
103 if (is_null(self::$legacy_mode)) {
104 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
107 return self::$legacy_mode;
111 * @brief returns an activity index from an activity string
113 * @param string $activity activity string
114 * @return integer Activity index
116 public static function activityToIndex($activity)
118 $index = array_search($activity, self::ACTIVITIES);
120 if (is_bool($index)) {
128 * @brief returns an activity string from an activity index
130 * @param integer $index activity index
131 * @return string Activity string
133 private static function indexToActivity($index)
135 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
139 return self::ACTIVITIES[$index];
143 * @brief Fetch a single item row
145 * @param mixed $stmt statement object
146 * @return array current row
148 public static function fetch($stmt)
150 $row = DBA::fetch($stmt);
156 // ---------------------- Transform item structure data ----------------------
158 // We prefer the data from the user's contact over the public one
159 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
160 ($row['author-link'] == $row['contact-link'])) {
161 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
162 $row['author-avatar'] = $row['contact-avatar'];
164 if (isset($row['author-name']) && !empty($row['contact-name'])) {
165 $row['author-name'] = $row['contact-name'];
169 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
170 ($row['owner-link'] == $row['contact-link'])) {
171 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
172 $row['owner-avatar'] = $row['contact-avatar'];
174 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
175 $row['owner-name'] = $row['contact-name'];
179 // We can always comment on posts from these networks
180 if (array_key_exists('writable', $row) &&
181 in_array($row['internal-network'], Protocol::FEDERATED)) {
182 $row['writable'] = true;
185 // ---------------------- Transform item content data ----------------------
187 // Fetch data from the item-content table whenever there is content there
188 if (self::isLegacyMode()) {
189 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
190 foreach ($legacy_fields as $field) {
191 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
192 $row[$field] = $row['internal-item-' . $field];
194 unset($row['internal-item-' . $field]);
198 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
199 $row['verb'] = self::indexToActivity($row['internal-activity']);
200 if (array_key_exists('title', $row)) {
203 if (array_key_exists('body', $row)) {
204 $row['body'] = $row['verb'];
206 if (array_key_exists('object', $row)) {
209 if (array_key_exists('object-type', $row)) {
210 $row['object-type'] = ACTIVITY_OBJ_NOTE;
212 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
213 // Posts don't have an object or target - but having tags or files.
214 // We safe some performance by building tag and file strings only here.
215 // We remove object and target since they aren't used for this type.
216 if (array_key_exists('object', $row)) {
219 if (array_key_exists('target', $row)) {
224 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
225 // Build the tag string out of the term entries
226 if (array_key_exists('tag', $row) && empty($row['tag'])) {
227 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
230 // Build the file string out of the term entries
231 if (array_key_exists('file', $row) && empty($row['file'])) {
232 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
236 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
237 $row['signed_text'] = $row['interaction'];
240 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
241 $row['ignored'] = $row['internal-user-ignored'];
244 // Remove internal fields
245 unset($row['internal-activity']);
246 unset($row['internal-network']);
247 unset($row['internal-iid']);
248 unset($row['internal-iaid']);
249 unset($row['internal-icid']);
250 unset($row['internal-user-ignored']);
251 unset($row['interaction']);
257 * @brief Fills an array with data from an item query
259 * @param object $stmt statement object
260 * @param bool $do_close
261 * @return array Data array
263 public static function inArray($stmt, $do_close = true) {
264 if (is_bool($stmt)) {
269 while ($row = self::fetch($stmt)) {
279 * @brief Check if item data exists
281 * @param array $condition array of fields for condition
283 * @return boolean Are there rows for that condition?
286 public static function exists($condition) {
287 $stmt = self::select(['id'], $condition, ['limit' => 1]);
289 if (is_bool($stmt)) {
292 $retval = (DBA::numRows($stmt) > 0);
301 * Retrieve a single record from the item table for a given user and returns it in an associative array
303 * @brief Retrieve a single record from a table
304 * @param integer $uid User ID
305 * @param array $selected
306 * @param array $condition
307 * @param array $params
312 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
314 $params['uid'] = $uid;
316 if (empty($selected)) {
317 $selected = Item::DISPLAY_FIELDLIST;
320 return self::selectFirst($selected, $condition, $params);
324 * @brief Select rows from the item table for a given user
326 * @param integer $uid User ID
327 * @param array $selected Array of selected fields, empty for all
328 * @param array $condition Array of fields for condition
329 * @param array $params Array of several parameters
331 * @return boolean|object
334 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
336 $params['uid'] = $uid;
338 if (empty($selected)) {
339 $selected = Item::DISPLAY_FIELDLIST;
342 return self::select($selected, $condition, $params);
346 * Retrieve a single record from the item table and returns it in an associative array
348 * @brief Retrieve a single record from a table
349 * @param array $fields
350 * @param array $condition
351 * @param array $params
356 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
358 $params['limit'] = 1;
360 $result = self::select($fields, $condition, $params);
362 if (is_bool($result)) {
365 $row = self::fetch($result);
372 * @brief Select rows from the item table and returns them as an array
374 * @param array $selected Array of selected fields, empty for all
375 * @param array $condition Array of fields for condition
376 * @param array $params Array of several parameters
381 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
383 $result = self::select($fields, $condition, $params);
385 if (is_bool($result)) {
390 while ($row = self::fetch($result)) {
399 * @brief Select rows from the item table
401 * @param array $selected Array of selected fields, empty for all
402 * @param array $condition Array of fields for condition
403 * @param array $params Array of several parameters
405 * @return boolean|object
408 public static function select(array $selected = [], array $condition = [], $params = [])
413 if (isset($params['uid'])) {
414 $uid = $params['uid'];
418 $fields = self::fieldlist($usermode);
420 $select_fields = self::constructSelectFields($fields, $selected);
422 $condition_string = DBA::buildCondition($condition);
424 $condition_string = self::addTablesToFields($condition_string, $fields);
427 $condition_string = $condition_string . ' AND ' . self::condition(false);
430 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
432 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
434 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
436 return DBA::p($sql, $condition);
440 * @brief Select rows from the starting post in the item table
442 * @param integer $uid User ID
443 * @param array $selected
444 * @param array $condition Array of fields for condition
445 * @param array $params Array of several parameters
447 * @return boolean|object
450 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
452 $params['uid'] = $uid;
454 if (empty($selected)) {
455 $selected = Item::DISPLAY_FIELDLIST;
458 return self::selectThread($selected, $condition, $params);
462 * Retrieve a single record from the starting post in the item table and returns it in an associative array
464 * @brief Retrieve a single record from a table
465 * @param integer $uid User ID
466 * @param array $selected
467 * @param array $condition
468 * @param array $params
473 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
475 $params['uid'] = $uid;
477 if (empty($selected)) {
478 $selected = Item::DISPLAY_FIELDLIST;
481 return self::selectFirstThread($selected, $condition, $params);
485 * Retrieve a single record from the starting post in the item table and returns it in an associative array
487 * @brief Retrieve a single record from a table
488 * @param array $fields
489 * @param array $condition
490 * @param array $params
495 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
497 $params['limit'] = 1;
498 $result = self::selectThread($fields, $condition, $params);
500 if (is_bool($result)) {
503 $row = self::fetch($result);
510 * @brief Select rows from the starting post in the item table
512 * @param array $selected Array of selected fields, empty for all
513 * @param array $condition Array of fields for condition
514 * @param array $params Array of several parameters
516 * @return boolean|object
519 public static function selectThread(array $selected = [], array $condition = [], $params = [])
524 if (isset($params['uid'])) {
525 $uid = $params['uid'];
529 $fields = self::fieldlist($usermode);
531 $fields['thread'] = ['mention', 'ignored', 'iid'];
533 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
534 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
535 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
536 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
538 $select_fields = self::constructSelectFields($fields, $selected);
540 $condition_string = DBA::buildCondition($condition);
542 $condition_string = self::addTablesToFields($condition_string, $threadfields);
543 $condition_string = self::addTablesToFields($condition_string, $fields);
546 $condition_string = $condition_string . ' AND ' . self::condition(true);
549 $param_string = DBA::buildParameter($params);
550 $param_string = self::addTablesToFields($param_string, $threadfields);
551 $param_string = self::addTablesToFields($param_string, $fields);
553 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
555 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
557 return DBA::p($sql, $condition);
561 * @brief Returns a list of fields that are associated with the item table
564 * @return array field list
566 private static function fieldlist($usermode)
570 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
571 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
572 'created', 'edited', 'commented', 'received', 'changed', 'psid',
573 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
574 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
575 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
576 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
577 'network' => 'internal-network', 'icid' => 'internal-icid',
578 'iaid' => 'internal-iaid'];
581 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
584 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
586 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
588 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
590 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
592 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
593 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
595 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
596 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
598 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
599 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
600 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
602 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
604 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
606 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
607 'start' => 'event-start','finish' => 'event-finish',
608 'summary' => 'event-summary','desc' => 'event-desc',
609 'location' => 'event-location', 'type' => 'event-type',
610 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
611 'ignore' => 'event-ignore', 'id' => 'event-id'];
613 $fields['sign'] = ['signed_text', 'signature', 'signer'];
615 $fields['diaspora-interaction'] = ['interaction'];
621 * @brief Returns SQL condition for the "select" functions
623 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
625 * @return string SQL condition
627 private static function condition($thread_mode)
630 $master_table = "`thread`";
632 $master_table = "`item`";
634 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
635 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
636 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
637 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
638 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
639 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
640 GRAVITY_PARENT, GRAVITY_PARENT);
644 * @brief Returns all needed "JOIN" commands for the "select" functions
646 * @param integer $uid User ID
647 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
648 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
651 * @return string The SQL joins for the "select" functions
653 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
656 $master_table = "`thread`";
657 $master_table_key = "`thread`.`iid`";
658 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
660 $master_table = "`item`";
661 $master_table_key = "`item`.`id`";
666 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
667 AND NOT `contact`.`blocked`
668 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
669 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
670 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
671 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
672 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
673 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
674 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
675 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
677 if (strpos($sql_commands, "`contact`.") !== false) {
678 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
680 if (strpos($sql_commands, "`author`.") !== false) {
681 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
683 if (strpos($sql_commands, "`owner`.") !== false) {
684 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
688 if (strpos($sql_commands, "`group_member`.") !== false) {
689 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
692 if (strpos($sql_commands, "`user`.") !== false) {
693 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
696 if (strpos($sql_commands, "`event`.") !== false) {
697 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
700 if (strpos($sql_commands, "`sign`.") !== false) {
701 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
704 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
705 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
708 if (strpos($sql_commands, "`item-activity`.") !== false) {
709 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
712 if (strpos($sql_commands, "`item-content`.") !== false) {
713 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
716 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
717 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
720 if (strpos($sql_commands, "`permissionset`.") !== false) {
721 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
724 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
725 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
728 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
729 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
736 * @brief Add the field list for the "select" functions
738 * @param array $fields The field definition array
739 * @param array $selected The array with the selected fields from the "select" functions
741 * @return string The field list
743 private static function constructSelectFields($fields, $selected)
745 if (!empty($selected)) {
746 $selected[] = 'internal-iid';
747 $selected[] = 'internal-iaid';
748 $selected[] = 'internal-icid';
749 $selected[] = 'internal-network';
752 if (in_array('verb', $selected)) {
753 $selected[] = 'internal-activity';
756 if (in_array('ignored', $selected)) {
757 $selected[] = 'internal-user-ignored';
760 if (in_array('signed_text', $selected)) {
761 $selected[] = 'interaction';
764 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
767 foreach ($fields as $table => $table_fields) {
768 foreach ($table_fields as $field => $select) {
769 if (empty($selected) || in_array($select, $selected)) {
770 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
771 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
773 if (is_int($field)) {
774 $selection[] = "`" . $table . "`.`" . $select . "`";
776 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
781 return implode(", ", $selection);
785 * @brief add table definition to fields in an SQL query
787 * @param string $query SQL query
788 * @param array $fields The field definition array
790 * @return string the changed SQL query
792 private static function addTablesToFields($query, $fields)
794 foreach ($fields as $table => $table_fields) {
795 foreach ($table_fields as $alias => $field) {
796 if (is_int($alias)) {
797 $replace_field = $field;
799 $replace_field = $alias;
802 $search = "/([^\.])`" . $field . "`/i";
803 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
804 $query = preg_replace($search, $replace, $query);
811 * @brief Update existing item entries
813 * @param array $fields The fields that are to be changed
814 * @param array $condition The condition for finding the item entries
816 * In the future we may have to change permissions as well.
817 * Then we had to add the user id as third parameter.
819 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
821 * @return integer|boolean number of affected rows - or "false" if there was an error
822 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
824 public static function update(array $fields, array $condition)
826 if (empty($condition) || empty($fields)) {
830 // To ensure the data integrity we do it in an transaction
833 // We cannot simply expand the condition to check for origin entries
834 // The condition needn't to be a simple array but could be a complex condition.
835 // And we have to execute this query before the update to ensure to fetch the same data.
836 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
838 $content_fields = [];
839 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
840 if (isset($fields[$field])) {
841 $content_fields[$field] = $fields[$field];
842 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
843 unset($fields[$field]);
845 $fields[$field] = null;
850 $delivery_data = ItemDeliveryData::extractFields($fields);
852 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
853 foreach ($clear_fields as $field) {
854 if (array_key_exists($field, $fields)) {
855 $fields[$field] = null;
859 if (array_key_exists('tag', $fields)) {
860 $tags = $fields['tag'];
861 $fields['tag'] = null;
866 if (array_key_exists('file', $fields)) {
867 $files = $fields['file'];
868 $fields['file'] = null;
873 if (!empty($fields)) {
874 $success = DBA::update('item', $fields, $condition);
883 // When there is no content for the "old" item table, this will count the fetched items
884 $rows = DBA::affectedRows();
886 while ($item = DBA::fetch($items)) {
887 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
888 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
890 if (empty($item['iaid'])) {
891 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
892 if (DBA::isResult($item_activity)) {
893 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
894 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
895 if (self::isLegacyMode()) {
896 $item_fields[$field] = null;
898 unset($item_fields[$field]);
901 DBA::update('item', $item_fields, ['id' => $item['id']]);
903 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
904 DBA::delete('item-content', ['id' => $item['icid']]);
907 } elseif (!empty($item['icid'])) {
908 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
910 if (!DBA::exists('item', ['icid' => $item['icid']])) {
911 DBA::delete('item-content', ['id' => $item['icid']]);
915 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
917 if (empty($item['icid'])) {
918 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
919 if (DBA::isResult($item_content)) {
920 $item_fields = ['icid' => $item_content['id']];
921 // Clear all fields in the item table that have a content in the item-content table
922 foreach ($item_content as $field => $content) {
923 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
924 if (self::isLegacyMode()) {
925 $item_fields[$field] = null;
927 unset($item_fields[$field]);
931 DBA::update('item', $item_fields, ['id' => $item['id']]);
936 if (!is_null($tags)) {
937 Term::insertFromTagFieldByItemId($item['id'], $tags);
938 if (!empty($item['tag'])) {
939 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
943 if (!is_null($files)) {
944 Term::insertFromFileFieldByItemId($item['id'], $files);
945 if (!empty($item['file'])) {
946 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
950 ItemDeliveryData::update($item['id'], $delivery_data);
952 self::updateThread($item['id']);
954 // We only need to notfiy others when it is an original entry from us.
955 // Only call the notifier when the item has some content relevant change.
956 if ($item['origin'] && in_array('edited', array_keys($fields))) {
957 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $item['id']);
967 * @brief Delete an item and notify others about it - if it was ours
969 * @param array $condition The condition for finding the item entries
970 * @param integer $priority Priority for the notification
971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973 public static function delete($condition, $priority = PRIORITY_HIGH)
975 $items = self::select(['id'], $condition);
976 while ($item = self::fetch($items)) {
977 self::deleteById($item['id'], $priority);
983 * @brief Delete an item for an user and notify others about it - if it was ours
985 * @param array $condition The condition for finding the item entries
986 * @param integer $uid User who wants to delete this item
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 public static function deleteForUser($condition, $uid)
995 $items = self::select(['id', 'uid'], $condition);
996 while ($item = self::fetch($items)) {
997 // "Deleting" global items just means hiding them
998 if ($item['uid'] == 0) {
999 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1000 } elseif ($item['uid'] == $uid) {
1001 self::deleteById($item['id'], PRIORITY_HIGH);
1003 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1010 * @brief Delete an item and notify others about it - if it was ours
1012 * @param integer $item_id Item ID that should be delete
1013 * @param integer $priority Priority for the notification
1015 * @return boolean success
1016 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
1020 // locate item to be deleted
1021 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1022 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1023 'verb', 'object-type', 'object', 'target', 'contact-id',
1024 'icid', 'iaid', 'psid'];
1025 $item = self::selectFirst($fields, ['id' => $item_id]);
1026 if (!DBA::isResult($item)) {
1027 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1031 if ($item['deleted']) {
1032 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1036 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1037 if (!DBA::isResult($parent)) {
1038 $parent = ['origin' => false];
1041 // clean up categories and tags so they don't end up as orphans
1044 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1047 foreach ($matches as $mtch) {
1048 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1054 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1057 foreach ($matches as $mtch) {
1058 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1063 * If item is a link to a photo resource, nuke all the associated photos
1064 * (visitors will not have photo resources)
1065 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1066 * generate a resource-id and therefore aren't intimately linked to the item.
1068 /// @TODO: this should first check if photo is used elsewhere
1069 if (strlen($item['resource-id'])) {
1070 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1073 // If item is a link to an event, delete the event.
1074 if (intval($item['event-id'])) {
1075 Event::delete($item['event-id']);
1078 // If item has attachments, drop them
1079 /// @TODO: this should first check if attachment is used elsewhere
1080 foreach (explode(",", $item['attach']) as $attach) {
1081 preg_match("|attach/(\d+)|", $attach, $matches);
1082 if (is_array($matches) && count($matches) > 1) {
1083 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1087 // Delete tags that had been attached to other items
1088 self::deleteTagsFromItem($item);
1090 // Set the item to "deleted"
1091 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1092 DBA::update('item', $item_fields, ['id' => $item['id']]);
1094 Term::insertFromTagFieldByItemId($item['id'], '');
1095 Term::insertFromFileFieldByItemId($item['id'], '');
1096 self::deleteThread($item['id'], $item['parent-uri']);
1098 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1099 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1102 ItemDeliveryData::delete($item['id']);
1104 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1106 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1107 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1109 // When the permission set will be used in photo and events as well,
1110 // this query here needs to be extended.
1111 // @todo Currently deactivated. We need the permission set in the deletion process.
1112 // This is a reminder to add the removal somewhere else.
1113 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1114 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1117 // If it's the parent of a comment thread, kill all the kids
1118 if ($item['id'] == $item['parent']) {
1119 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1122 // Is it our comment and/or our thread?
1123 if ($item['origin'] || $parent['origin']) {
1125 // When we delete the original post we will delete all existing copies on the server as well
1126 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1128 // send the notification upstream/downstream
1129 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1130 } elseif ($item['uid'] != 0) {
1132 // When we delete just our local user copy of an item, we have to set a marker to hide it
1133 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1134 if (DBA::isResult($global_item)) {
1135 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1139 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1144 private static function deleteTagsFromItem($item)
1146 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1150 $xo = XML::parseString($item["object"], false);
1151 $xt = XML::parseString($item["target"], false);
1153 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1157 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1158 if (!DBA::isResult($i)) {
1162 // For tags, the owner cannot remove the tag on the author's copy of the post.
1163 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1164 $author_copy = $item["origin"];
1166 if (($owner_remove && $author_copy) || !$owner_remove) {
1170 $tags = explode(',', $i["tag"]);
1173 foreach ($tags as $tag) {
1174 if (trim($tag) !== trim($xo->body)) {
1175 $newtags[] = trim($tag);
1179 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1182 private static function guid($item, $notify)
1184 if (!empty($item['guid'])) {
1185 return Strings::escapeTags(trim($item['guid']));
1189 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1190 // We add the hash of our own host because our host is the original creator of the post.
1191 $prefix_host = \get_app()->getHostName();
1195 // We are only storing the post so we create a GUID from the original hostname.
1196 if (!empty($item['author-link'])) {
1197 $parsed = parse_url($item['author-link']);
1198 if (!empty($parsed['host'])) {
1199 $prefix_host = $parsed['host'];
1203 if (empty($prefix_host) && !empty($item['plink'])) {
1204 $parsed = parse_url($item['plink']);
1205 if (!empty($parsed['host'])) {
1206 $prefix_host = $parsed['host'];
1210 if (empty($prefix_host) && !empty($item['uri'])) {
1211 $parsed = parse_url($item['uri']);
1212 if (!empty($parsed['host'])) {
1213 $prefix_host = $parsed['host'];
1217 // Is it in the format data@host.tld? - Used for mail contacts
1218 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1219 $mailparts = explode('@', $item['author-link']);
1220 $prefix_host = array_pop($mailparts);
1224 if (!empty($item['plink'])) {
1225 $guid = self::guidFromUri($item['plink'], $prefix_host);
1226 } elseif (!empty($item['uri'])) {
1227 $guid = self::guidFromUri($item['uri'], $prefix_host);
1229 $guid = System::createUUID(hash('crc32', $prefix_host));
1235 private static function contactId($item)
1237 $contact_id = (int)$item["contact-id"];
1239 if (!empty($contact_id)) {
1242 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1244 * First we are looking for a suitable contact that matches with the author of the post
1245 * This is done only for comments
1247 if ($item['parent-uri'] != $item['uri']) {
1248 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1251 // If not present then maybe the owner was found
1252 if ($contact_id == 0) {
1253 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1256 // Still missing? Then use the "self" contact of the current user
1257 if ($contact_id == 0) {
1258 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1259 if (DBA::isResult($self)) {
1260 $contact_id = $self["id"];
1263 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1268 // This function will finally cover most of the preparation functionality in mod/item.php
1269 public static function prepare(&$item)
1272 * @TODO: Unused code triggering inspection errors
1274 $data = BBCode::getAttachmentData($item['body']);
1275 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1276 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1277 $posttype = Item::PT_PAGE;
1278 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1283 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1287 $priority = PRIORITY_HIGH;
1289 // If it is a posting where users should get notifications, then define it as wall posting
1292 $item['origin'] = 1;
1293 $item['network'] = Protocol::DFRN;
1294 $item['protocol'] = Conversation::PARCEL_DFRN;
1296 if (is_int($notify)) {
1297 $priority = $notify;
1300 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1303 $item['guid'] = self::guid($item, $notify);
1304 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1307 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1309 // Store conversation data
1310 $item = Conversation::insert($item);
1313 * If a Diaspora signature structure was passed in, pull it out of the
1314 * item array and set it aside for later storage.
1318 if (isset($item['dsprsig'])) {
1319 $encoded_signature = $item['dsprsig'];
1320 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1321 unset($item['dsprsig']);
1324 $diaspora_signed_text = '';
1325 if (isset($item['diaspora_signed_text'])) {
1326 $diaspora_signed_text = $item['diaspora_signed_text'];
1327 unset($item['diaspora_signed_text']);
1330 // Converting the plink
1331 /// @TODO Check if this is really still needed
1332 if ($item['network'] == Protocol::OSTATUS) {
1333 if (isset($item['plink'])) {
1334 $item['plink'] = OStatus::convertHref($item['plink']);
1335 } elseif (isset($item['uri'])) {
1336 $item['plink'] = OStatus::convertHref($item['uri']);
1340 if (!empty($item['thr-parent'])) {
1341 $item['parent-uri'] = $item['thr-parent'];
1344 if (isset($item['gravity'])) {
1345 $item['gravity'] = intval($item['gravity']);
1346 } elseif ($item['parent-uri'] === $item['uri']) {
1347 $item['gravity'] = GRAVITY_PARENT;
1348 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1349 $item['gravity'] = GRAVITY_COMMENT;
1350 } elseif (activity_match($item['verb'], ACTIVITY_FOLLOW)) {
1351 $item['gravity'] = GRAVITY_ACTIVITY;
1353 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1354 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1357 $uid = intval($item['uid']);
1359 // check for create date and expire time
1360 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1362 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1363 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1364 $expire_interval = $user['expire'];
1367 if (($expire_interval > 0) && !empty($item['created'])) {
1368 $expire_date = time() - ($expire_interval * 86400);
1369 $created_date = strtotime($item['created']);
1370 if ($created_date < $expire_date) {
1371 Logger::notice('Item created before expiration interval.', [
1372 'created' => date('c', $created_date),
1373 'expired' => date('c', $expire_date),
1381 * Do we already have this item?
1382 * We have to check several networks since Friendica posts could be repeated
1383 * via OStatus (maybe Diasporsa as well)
1385 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1386 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1387 trim($item['uri']), $item['uid'],
1388 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1389 $existing = self::selectFirst(['id', 'network'], $condition);
1390 if (DBA::isResult($existing)) {
1391 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1393 Logger::notice('Item already existed for user', [
1394 'uri' => $item['uri'],
1396 'network' => $item['network'],
1397 'existing_id' => $existing["id"],
1398 'existing_network' => $existing["network"]
1402 return $existing["id"];
1406 $item['wall'] = intval(defaults($item, 'wall', 0));
1407 $item['extid'] = trim(defaults($item, 'extid', ''));
1408 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1409 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1410 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1411 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1412 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1413 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1414 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1415 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1416 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1417 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1418 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1419 $item['title'] = trim(defaults($item, 'title', ''));
1420 $item['location'] = trim(defaults($item, 'location', ''));
1421 $item['coord'] = trim(defaults($item, 'coord', ''));
1422 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1423 $item['deleted'] = 0;
1424 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1425 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1426 $item['verb'] = trim(defaults($item, 'verb', ''));
1427 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1428 $item['object'] = trim(defaults($item, 'object', ''));
1429 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1430 $item['target'] = trim(defaults($item, 'target', ''));
1431 $item['plink'] = trim(defaults($item, 'plink', ''));
1432 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1433 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1434 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1435 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1436 $item['private'] = intval(defaults($item, 'private', 0));
1437 $item['body'] = trim(defaults($item, 'body', ''));
1438 $item['tag'] = trim(defaults($item, 'tag', ''));
1439 $item['attach'] = trim(defaults($item, 'attach', ''));
1440 $item['app'] = trim(defaults($item, 'app', ''));
1441 $item['origin'] = intval(defaults($item, 'origin', 0));
1442 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1443 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1444 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1445 $item['inform'] = trim(defaults($item, 'inform', ''));
1446 $item['file'] = trim(defaults($item, 'file', ''));
1448 // When there is no content then we don't post it
1449 if ($item['body'].$item['title'] == '') {
1450 Logger::notice('No body, no title.');
1454 self::addLanguageToItemArray($item);
1456 // Items cannot be stored before they happen ...
1457 if ($item['created'] > DateTimeFormat::utcNow()) {
1458 $item['created'] = DateTimeFormat::utcNow();
1461 // We haven't invented time travel by now.
1462 if ($item['edited'] > DateTimeFormat::utcNow()) {
1463 $item['edited'] = DateTimeFormat::utcNow();
1466 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1468 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1469 $item["contact-id"] = self::contactId($item);
1471 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1472 'photo' => $item['author-avatar'], 'network' => $item['network']];
1474 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item['author-link'], 0, false, $default));
1476 if (Contact::isBlocked($item['author-id'])) {
1477 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1481 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1482 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1486 if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
1487 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1491 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1492 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1494 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item['owner-link'], 0, false, $default));
1496 if (Contact::isBlocked($item['owner-id'])) {
1497 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1501 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1502 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1506 if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
1507 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1511 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1512 if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
1513 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1517 if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
1518 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1522 // We don't store the causer, we only have it here for the checks above
1523 unset($item['causer-id']);
1524 unset($item['causer-link']);
1526 if ($item['network'] == Protocol::PHANTOM) {
1527 $item['network'] = Protocol::DFRN;
1528 Logger::notice('Missing network, setting to {network}.', [
1529 'uri' => $item["uri"],
1530 'network' => $item['network'],
1531 'callstack' => System::callstack()
1535 // Checking if there is already an item with the same guid
1536 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1537 if (self::exists($condition)) {
1538 Logger::notice('Found already existing item', [
1539 'guid' => $item['guid'],
1540 'uid' => $item['uid'],
1541 'network' => $item['network']
1546 if ($item['verb'] == ACTIVITY_FOLLOW) {
1547 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1548 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1549 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1553 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => $item['uid'],
1554 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1555 if (self::exists($condition)) {
1556 // It happens that we receive multiple follow requests by the same author - we only store one.
1557 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1562 // Check for hashtags in the body and repair or add hashtag links
1563 self::setHashtags($item);
1565 $item['thr-parent'] = $item['parent-uri'];
1567 $notify_type = Delivery::POST;
1573 if ($item['parent-uri'] === $item['uri']) {
1575 $parent_deleted = 0;
1576 $allow_cid = $item['allow_cid'];
1577 $allow_gid = $item['allow_gid'];
1578 $deny_cid = $item['deny_cid'];
1579 $deny_gid = $item['deny_gid'];
1581 // find the parent and snarf the item id and ACLs
1582 // and anything else we need to inherit
1584 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1585 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1586 'wall', 'private', 'forum_mode', 'origin'];
1587 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1588 $params = ['order' => ['id' => false]];
1589 $parent = self::selectFirst($fields, $condition, $params);
1591 if (DBA::isResult($parent)) {
1592 // is the new message multi-level threaded?
1593 // even though we don't support it now, preserve the info
1594 // and re-attach to the conversation parent.
1596 if ($parent['uri'] != $parent['parent-uri']) {
1597 $item['parent-uri'] = $parent['parent-uri'];
1599 $condition = ['uri' => $item['parent-uri'],
1600 'parent-uri' => $item['parent-uri'],
1601 'uid' => $item['uid']];
1602 $params = ['order' => ['id' => false]];
1603 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1605 if (DBA::isResult($toplevel_parent)) {
1606 $parent = $toplevel_parent;
1610 $parent_id = $parent['id'];
1611 $parent_deleted = $parent['deleted'];
1612 $allow_cid = $parent['allow_cid'];
1613 $allow_gid = $parent['allow_gid'];
1614 $deny_cid = $parent['deny_cid'];
1615 $deny_gid = $parent['deny_gid'];
1616 $item['wall'] = $parent['wall'];
1619 * If the parent is private, force privacy for the entire conversation
1620 * This differs from the above settings as it subtly allows comments from
1621 * email correspondents to be private even if the overall thread is not.
1623 if ($parent['private']) {
1624 $item['private'] = $parent['private'];
1628 * Edge case. We host a public forum that was originally posted to privately.
1629 * The original author commented, but as this is a comment, the permissions
1630 * weren't fixed up so it will still show the comment as private unless we fix it here.
1632 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1633 $item['private'] = 0;
1636 // If its a post that originated here then tag the thread as "mention"
1637 if ($item['origin'] && $item['uid']) {
1638 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1639 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1643 * Allow one to see reply tweets from status.net even when
1644 * we don't have or can't see the original post.
1646 if ($force_parent) {
1647 Logger::log('$force_parent=true, reply converted to top-level post.');
1649 $item['parent-uri'] = $item['uri'];
1650 $item['gravity'] = GRAVITY_PARENT;
1652 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1656 $parent_deleted = 0;
1660 if (stristr($item['verb'], ACTIVITY_POKE)) {
1661 $notify_type = Delivery::POKE;
1664 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1665 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1667 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1668 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1669 if (self::exists($condition)) {
1670 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1674 // On Friendica and Diaspora the GUID is unique
1675 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1676 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1677 if (self::exists($condition)) {
1678 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1681 } elseif ($item['network'] == Protocol::OSTATUS) {
1682 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1683 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1684 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1685 if (self::exists($condition)) {
1686 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1691 // Is this item available in the global items (with uid=0)?
1692 if ($item["uid"] == 0) {
1693 $item["global"] = true;
1695 // Set the global flag on all items if this was a global item entry
1696 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1698 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1702 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1705 $private = $item['private'];
1708 $item["allow_cid"] = $allow_cid;
1709 $item["allow_gid"] = $allow_gid;
1710 $item["deny_cid"] = $deny_cid;
1711 $item["deny_gid"] = $deny_gid;
1712 $item["private"] = $private;
1713 $item["deleted"] = $parent_deleted;
1715 // Fill the cache field
1716 self::putInCache($item);
1719 $item['edit'] = false;
1720 $item['parent'] = $parent_id;
1721 Hook::callAll('post_local', $item);
1722 unset($item['edit']);
1723 unset($item['parent']);
1725 Hook::callAll('post_remote', $item);
1728 // This array field is used to trigger some automatic reactions
1729 // It is mainly used in the "post_local" hook.
1730 unset($item['api_source']);
1732 if (!empty($item['cancel'])) {
1733 Logger::log('post cancelled by addon.');
1738 * Check for already added items.
1739 * There is a timing issue here that sometimes creates double postings.
1740 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1742 if ($item["uid"] == 0) {
1743 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1744 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1749 Logger::log('' . print_r($item,true), Logger::DATA);
1751 if (array_key_exists('tag', $item)) {
1752 $tags = $item['tag'];
1753 unset($item['tag']);
1758 if (array_key_exists('file', $item)) {
1759 $files = $item['file'];
1760 unset($item['file']);
1765 // Creates or assigns the permission set
1766 $item['psid'] = PermissionSet::fetchIDForPost($item);
1768 // We are doing this outside of the transaction to avoid timing problems
1769 if (!self::insertActivity($item)) {
1770 self::insertContent($item);
1773 $delivery_data = ItemDeliveryData::extractFields($item);
1775 unset($item['postopts']);
1776 unset($item['inform']);
1778 // These fields aren't stored anymore in the item table, they are fetched upon request
1779 unset($item['author-link']);
1780 unset($item['author-name']);
1781 unset($item['author-avatar']);
1782 unset($item['author-network']);
1784 unset($item['owner-link']);
1785 unset($item['owner-name']);
1786 unset($item['owner-avatar']);
1789 $ret = DBA::insert('item', $item);
1791 // When the item was successfully stored we fetch the ID of the item.
1792 if (DBA::isResult($ret)) {
1793 $current_post = DBA::lastInsertId();
1795 // This can happen - for example - if there are locking timeouts.
1798 // Store the data into a spool file so that we can try again later.
1800 // At first we restore the Diaspora signature that we removed above.
1801 if (isset($encoded_signature)) {
1802 $item['dsprsig'] = $encoded_signature;
1805 // Now we store the data in the spool directory
1806 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1807 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1809 $spoolpath = get_spoolpath();
1810 if ($spoolpath != "") {
1811 $spool = $spoolpath.'/'.$file;
1813 file_put_contents($spool, json_encode($orig_item));
1814 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1819 if ($current_post == 0) {
1820 // This is one of these error messages that never should occur.
1821 Logger::log("couldn't find created item - we better quit now.");
1826 // How much entries have we created?
1827 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1828 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1831 // There are duplicates. We delete our just created entry.
1832 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1834 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1835 DBA::delete('item', ['id' => $current_post]);
1838 } elseif ($entries == 0) {
1839 // This really should never happen since we quit earlier if there were problems.
1840 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1845 Logger::log('created item '.$current_post);
1846 self::updateContact($item);
1848 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1849 $parent_id = $current_post;
1853 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1855 $item['id'] = $current_post;
1856 $item['parent'] = $parent_id;
1858 // update the commented timestamp on the parent
1859 // Only update "commented" if it is really a comment
1860 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1861 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1863 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1868 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1869 * We can check for this condition when we decode and encode the stuff again.
1871 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1872 $dsprsig->signature = base64_decode($dsprsig->signature);
1873 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1876 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1877 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1879 // The other fields are used by very old Friendica servers, so we currently store them differently
1880 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1881 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1885 if (!empty($diaspora_signed_text)) {
1886 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1889 self::tagDeliver($item['uid'], $current_post);
1892 * current post can be deleted if is for a community page and no mention are
1896 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1897 if (DBA::isResult($posted_item)) {
1899 Hook::callAll('post_local_end', $posted_item);
1901 Hook::callAll('post_remote_end', $posted_item);
1904 Logger::log('new item not found in DB, id ' . $current_post);
1908 if ($item['parent-uri'] === $item['uri']) {
1909 self::addThread($current_post);
1911 self::updateThread($parent_id);
1914 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1915 ItemDeliveryData::insert($current_post, $delivery_data);
1921 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1922 * This is not perfect - but a workable solution until we found the reason for the problem.
1924 if (!empty($tags)) {
1925 Term::insertFromTagFieldByItemId($current_post, $tags);
1928 if (!empty($files)) {
1929 Term::insertFromFileFieldByItemId($current_post, $files);
1932 if ($item['parent-uri'] === $item['uri']) {
1933 self::addShadow($current_post);
1935 self::addShadowPost($current_post);
1938 check_user_notification($current_post);
1940 if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
1941 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1944 return $current_post;
1948 * @brief Insert a new item content entry
1950 * @param array $item The item fields that are to be inserted
1952 * @throws \Exception
1954 private static function insertActivity(&$item)
1956 $activity_index = self::activityToIndex($item['verb']);
1958 if ($activity_index < 0) {
1962 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1964 // We just remove everything that is content
1965 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1966 unset($item[$field]);
1969 // To avoid timing problems, we are using locks.
1970 $locked = Lock::acquire('item_insert_activity');
1972 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1975 // Do we already have this content?
1976 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1977 if (DBA::isResult($item_activity)) {
1978 $item['iaid'] = $item_activity['id'];
1979 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1980 } elseif (DBA::insert('item-activity', $fields)) {
1981 $item['iaid'] = DBA::lastInsertId();
1982 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1984 // This shouldn't happen.
1985 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1986 Lock::release('item_insert_activity');
1990 Lock::release('item_insert_activity');
1996 * @brief Insert a new item content entry
1998 * @param array $item The item fields that are to be inserted
1999 * @throws \Exception
2001 private static function insertContent(&$item)
2003 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2005 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2006 if (isset($item[$field])) {
2007 $fields[$field] = $item[$field];
2008 unset($item[$field]);
2012 // To avoid timing problems, we are using locks.
2013 $locked = Lock::acquire('item_insert_content');
2015 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2018 // Do we already have this content?
2019 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2020 if (DBA::isResult($item_content)) {
2021 $item['icid'] = $item_content['id'];
2022 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2023 } elseif (DBA::insert('item-content', $fields)) {
2024 $item['icid'] = DBA::lastInsertId();
2025 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2027 // This shouldn't happen.
2028 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2031 Lock::release('item_insert_content');
2036 * @brief Update existing item content entries
2038 * @param array $item The item fields that are to be changed
2039 * @param array $condition The condition for finding the item content entries
2041 * @throws \Exception
2043 private static function updateActivity($item, $condition)
2045 if (empty($item['verb'])) {
2048 $activity_index = self::activityToIndex($item['verb']);
2050 if ($activity_index < 0) {
2054 $fields = ['activity' => $activity_index];
2056 Logger::log('Update activity for ' . json_encode($condition));
2058 DBA::update('item-activity', $fields, $condition, true);
2064 * @brief Update existing item content entries
2066 * @param array $item The item fields that are to be changed
2067 * @param array $condition The condition for finding the item content entries
2068 * @throws \Exception
2070 private static function updateContent($item, $condition)
2072 // We have to select only the fields from the "item-content" table
2074 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2075 if (isset($item[$field])) {
2076 $fields[$field] = $item[$field];
2080 if (empty($fields)) {
2081 // when there are no fields at all, just use the condition
2082 // This is to ensure that we always store content.
2083 $fields = $condition;
2086 Logger::log('Update content for ' . json_encode($condition));
2088 DBA::update('item-content', $fields, $condition, true);
2092 * @brief Distributes public items to the receivers
2094 * @param integer $itemid Item ID that should be added
2095 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2096 * @throws \Exception
2098 public static function distribute($itemid, $signed_text = '')
2100 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2101 $parent = self::selectFirst(['owner-id'], $condition);
2102 if (!DBA::isResult($parent)) {
2106 // Only distribute public items from native networks
2107 $condition = ['id' => $itemid, 'uid' => 0,
2108 'network' => array_merge(Protocol::FEDERATED ,['']),
2109 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2110 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2111 if (!DBA::isResult($item)) {
2115 $origin = $item['origin'];
2118 unset($item['parent']);
2119 unset($item['mention']);
2120 unset($item['wall']);
2121 unset($item['origin']);
2122 unset($item['starred']);
2126 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2127 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2128 if (!DBA::isResult($owner)) {
2132 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2133 $contacts = DBA::select('contact', ['uid'], $condition);
2134 while ($contact = DBA::fetch($contacts)) {
2135 if ($contact['uid'] == 0) {
2139 $users[$contact['uid']] = $contact['uid'];
2141 DBA::close($contacts);
2143 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2144 $contacts = DBA::select('contact', ['uid'], $condition);
2145 while ($contact = DBA::fetch($contacts)) {
2146 if ($contact['uid'] == 0) {
2150 $users[$contact['uid']] = $contact['uid'];
2152 DBA::close($contacts);
2154 if (!empty($owner['alias'])) {
2155 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2156 $contacts = DBA::select('contact', ['uid'], $condition);
2157 while ($contact = DBA::fetch($contacts)) {
2158 if ($contact['uid'] == 0) {
2162 $users[$contact['uid']] = $contact['uid'];
2164 DBA::close($contacts);
2169 if ($item['uri'] != $item['parent-uri']) {
2170 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2171 while ($parent = self::fetch($parents)) {
2172 $users[$parent['uid']] = $parent['uid'];
2173 if ($parent['origin'] && !$origin) {
2174 $origin_uid = $parent['uid'];
2179 foreach ($users as $uid) {
2180 if ($origin_uid == $uid) {
2181 $item['diaspora_signed_text'] = $signed_text;
2183 self::storeForUser($itemid, $item, $uid);
2188 * @brief Store public items for the receivers
2190 * @param integer $itemid Item ID that should be added
2191 * @param array $item The item entry that will be stored
2192 * @param integer $uid The user that will receive the item entry
2193 * @throws \Exception
2195 private static function storeForUser($itemid, $item, $uid)
2197 $item['uid'] = $uid;
2198 $item['origin'] = 0;
2200 if ($item['uri'] == $item['parent-uri']) {
2201 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2203 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2206 if (empty($item['contact-id'])) {
2207 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2208 if (!DBA::isResult($self)) {
2211 $item['contact-id'] = $self['id'];
2214 /// @todo Handling of "event-id"
2217 if ($item['uri'] == $item['parent-uri']) {
2218 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2219 if (DBA::isResult($contact)) {
2220 $notify = self::isRemoteSelf($contact, $item);
2224 $distributed = self::insert($item, false, $notify, true);
2226 if (!$distributed) {
2227 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2229 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2234 * @brief Add a shadow entry for a given item id that is a thread starter
2236 * We store every public item entry additionally with the user id "0".
2237 * This is used for the community page and for the search.
2238 * It is planned that in the future we will store public item entries only once.
2240 * @param integer $itemid Item ID that should be added
2241 * @throws \Exception
2243 public static function addShadow($itemid)
2245 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2246 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2247 $item = self::selectFirst($fields, $condition);
2249 if (!DBA::isResult($item)) {
2253 // is it already a copy?
2254 if (($itemid == 0) || ($item['uid'] == 0)) {
2258 // Is it a visible public post?
2259 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2263 // is it an entry from a connector? Only add an entry for natively connected networks
2264 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2268 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2272 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2274 if (DBA::isResult($item)) {
2275 // Preparing public shadow (removing user specific data)
2278 unset($item['parent']);
2279 unset($item['wall']);
2280 unset($item['mention']);
2281 unset($item['origin']);
2282 unset($item['starred']);
2283 unset($item['postopts']);
2284 unset($item['inform']);
2285 if ($item['uri'] == $item['parent-uri']) {
2286 $item['contact-id'] = $item['owner-id'];
2288 $item['contact-id'] = $item['author-id'];
2291 $public_shadow = self::insert($item, false, false, true);
2293 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2298 * @brief Add a shadow entry for a given item id that is a comment
2300 * This function does the same like the function above - but for comments
2302 * @param integer $itemid Item ID that should be added
2303 * @throws \Exception
2305 public static function addShadowPost($itemid)
2307 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2308 if (!DBA::isResult($item)) {
2312 // Is it a toplevel post?
2313 if ($item['id'] == $item['parent']) {
2314 self::addShadow($itemid);
2318 // Is this a shadow entry?
2319 if ($item['uid'] == 0) {
2323 // Is there a shadow parent?
2324 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2328 // Is there already a shadow entry?
2329 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2333 // Save "origin" and "parent" state
2334 $origin = $item['origin'];
2335 $parent = $item['parent'];
2337 // Preparing public shadow (removing user specific data)
2340 unset($item['parent']);
2341 unset($item['wall']);
2342 unset($item['mention']);
2343 unset($item['origin']);
2344 unset($item['starred']);
2345 unset($item['postopts']);
2346 unset($item['inform']);
2347 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2349 $public_shadow = self::insert($item, false, false, true);
2351 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2353 // If this was a comment to a Diaspora post we don't get our comment back.
2354 // This means that we have to distribute the comment by ourselves.
2355 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2356 self::distribute($public_shadow);
2361 * Adds a language specification in a "language" element of given $arr.
2362 * Expects "body" element to exist in $arr.
2365 * @throws \Text_LanguageDetect_Exception
2367 private static function addLanguageToItemArray(&$item)
2369 $naked_body = BBCode::toPlaintext($item['body'], false);
2371 $ld = new Text_LanguageDetect();
2372 $ld->setNameMode(2);
2373 $languages = $ld->detect($naked_body, 3);
2375 if (is_array($languages)) {
2376 $item['language'] = json_encode($languages);
2381 * @brief Creates an unique guid out of a given uri
2383 * @param string $uri uri of an item entry
2384 * @param string $host hostname for the GUID prefix
2385 * @return string unique guid
2387 public static function guidFromUri($uri, $host)
2389 // Our regular guid routine is using this kind of prefix as well
2390 // We have to avoid that different routines could accidentally create the same value
2391 $parsed = parse_url($uri);
2393 // We use a hash of the hostname as prefix for the guid
2394 $guid_prefix = hash("crc32", $host);
2396 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2397 unset($parsed["scheme"]);
2399 // Glue it together to be able to make a hash from it
2400 $host_id = implode("/", $parsed);
2402 // We could use any hash algorithm since it isn't a security issue
2403 $host_hash = hash("ripemd128", $host_id);
2405 return $guid_prefix.$host_hash;
2409 * generate an unique URI
2411 * @param integer $uid User id
2412 * @param string $guid An existing GUID (Otherwise it will be generated)
2415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2417 public static function newURI($uid, $guid = "")
2420 $guid = System::createUUID();
2423 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2427 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2429 * This can be used to filter for inactive contacts.
2430 * Only do this for public postings to avoid privacy problems, since poco data is public.
2431 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2433 * @param array $arr Contains the just posted item record
2434 * @throws \Exception
2436 private static function updateContact($arr)
2438 // Unarchive the author
2439 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2440 if (DBA::isResult($contact)) {
2441 Contact::unmarkForArchival($contact);
2444 // Unarchive the contact if it's not our own contact
2445 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2446 if (DBA::isResult($contact)) {
2447 Contact::unmarkForArchival($contact);
2450 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2452 // Is it a forum? Then we don't care about the rules from above
2453 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2454 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2460 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2461 ['id' => $arr['contact-id']]);
2463 // Now do the same for the system wide contacts with uid=0
2464 if (!$arr['private']) {
2465 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2466 ['id' => $arr['owner-id']]);
2468 if ($arr['owner-id'] != $arr['author-id']) {
2469 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2470 ['id' => $arr['author-id']]);
2475 public static function setHashtags(&$item)
2477 $tags = BBCode::getTags($item["body"]);
2480 if (!count($tags)) {
2484 // What happens in [code], stays in [code]!
2485 // escape the # and the [
2486 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2487 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2489 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2491 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2492 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2495 // This sorting is important when there are hashtags that are part of other hashtags
2496 // Otherwise there could be problems with hashtags like #test and #test2
2499 $URLSearchString = "^\[\]";
2501 // All hashtags should point to the home server if "local_tags" is activated
2502 if (Config::get('system', 'local_tags')) {
2503 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2504 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2506 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2507 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2510 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2511 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2513 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2516 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2518 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2521 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2523 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2526 // Repair recursive urls
2527 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2528 "#$2", $item["body"]);
2530 foreach ($tags as $tag) {
2531 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || $tag[1] == '#') {
2535 $basetag = str_replace('_',' ',substr($tag,1));
2536 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2538 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2540 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2541 if (strlen($item["tag"])) {
2542 $item["tag"] = ',' . $item["tag"];
2544 $item["tag"] = $newtag . $item["tag"];
2548 // Convert back the masked hashtags
2549 $item["body"] = str_replace("#", "#", $item["body"]);
2551 // Remember! What happens in [code], stays in [code]
2552 // roleback the # and [
2553 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2555 // we truly unESCape all sharp and leftsquarebracket
2556 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2557 $replace = ['#', '['];
2558 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2563 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2566 * @param int $item_id
2567 * @return void true if item was deleted, else false
2568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2569 * @throws \ImagickException
2571 private static function tagDeliver($uid, $item_id)
2575 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2576 if (!DBA::isResult($user)) {
2580 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2581 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2583 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2584 if (!DBA::isResult($item)) {
2588 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2591 * Diaspora uses their own hardwired link URL in @-tags
2592 * instead of the one we supply with webfinger
2594 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2596 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2598 foreach ($matches as $mtch) {
2599 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2601 Logger::log('mention found: ' . $mtch[2]);
2607 if (($community_page || $prvgroup) &&
2608 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2609 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2611 Logger::log("no-mention top-level post to community or private group. delete.");
2612 DBA::delete('item', ['id' => $item_id]);
2618 $arr = ['item' => $item, 'user' => $user];
2620 Hook::callAll('tagged', $arr);
2622 if (!$community_page && !$prvgroup) {
2627 * tgroup delivery - setup a second delivery chain
2628 * prevent delivery looping - only proceed
2629 * if the message originated elsewhere and is a top-level post
2631 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2635 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2636 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2637 if (!DBA::isResult($self)) {
2641 $owner_id = Contact::getIdForURL($self['url']);
2643 // also reset all the privacy bits to the forum default permissions
2645 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2647 $psid = PermissionSet::fetchIDForPost($user);
2649 $forum_mode = ($prvgroup ? 2 : 1);
2651 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2652 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2653 self::update($fields, ['id' => $item_id]);
2655 self::updateThread($item_id);
2657 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2660 public static function isRemoteSelf($contact, &$datarray)
2664 if (!$contact['remote_self']) {
2668 // Prevent the forwarding of posts that are forwarded
2669 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2670 Logger::log('Already forwarded', Logger::DEBUG);
2674 // Prevent to forward already forwarded posts
2675 if ($datarray["app"] == $a->getHostName()) {
2676 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2680 // Only forward posts
2681 if ($datarray["verb"] != ACTIVITY_POST) {
2682 Logger::log('No post', Logger::DEBUG);
2686 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2687 Logger::log('Not public', Logger::DEBUG);
2691 $datarray2 = $datarray;
2692 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2693 if ($contact['remote_self'] == 2) {
2694 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2695 ['uid' => $contact['uid'], 'self' => true]);
2696 if (DBA::isResult($self)) {
2697 $datarray['contact-id'] = $self["id"];
2699 $datarray['owner-name'] = $self["name"];
2700 $datarray['owner-link'] = $self["url"];
2701 $datarray['owner-avatar'] = $self["thumb"];
2703 $datarray['author-name'] = $datarray['owner-name'];
2704 $datarray['author-link'] = $datarray['owner-link'];
2705 $datarray['author-avatar'] = $datarray['owner-avatar'];
2707 unset($datarray['edited']);
2709 unset($datarray['network']);
2710 unset($datarray['owner-id']);
2711 unset($datarray['author-id']);
2714 if ($contact['network'] != Protocol::FEED) {
2715 $datarray["guid"] = System::createUUID();
2716 unset($datarray["plink"]);
2717 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2718 $datarray["parent-uri"] = $datarray["uri"];
2719 $datarray["thr-parent"] = $datarray["uri"];
2720 $datarray["extid"] = Protocol::DFRN;
2721 $urlpart = parse_url($datarray2['author-link']);
2722 $datarray["app"] = $urlpart["host"];
2724 $datarray['private'] = 0;
2728 if ($contact['network'] != Protocol::FEED) {
2729 // Store the original post
2730 $result = self::insert($datarray2, false, false);
2731 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2733 $datarray["app"] = "Feed";
2737 // Trigger automatic reactions for addons
2738 $datarray['api_source'] = true;
2740 // We have to tell the hooks who we are - this really should be improved
2741 $_SESSION["authenticated"] = true;
2742 $_SESSION["uid"] = $contact['uid'];
2751 * @param array $item
2754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2755 * @throws \ImagickException
2757 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2759 if (Config::get('system', 'disable_embedded')) {
2763 Logger::log('check for photos', Logger::DEBUG);
2764 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2769 $img_start = strpos($orig_body, '[img');
2770 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2771 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2773 while (($img_st_close !== false) && ($img_len !== false)) {
2774 $img_st_close++; // make it point to AFTER the closing bracket
2775 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2777 Logger::log('found photo ' . $image, Logger::DEBUG);
2779 if (stristr($image, $site . '/photo/')) {
2780 // Only embed locally hosted photos
2782 $i = basename($image);
2783 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2784 $x = strpos($i, '-');
2787 $res = substr($i, $x + 1);
2788 $i = substr($i, 0, $x);
2789 $photo = Photo::getPhotoForUser($uid, $i, $res);
2790 if (DBA::isResult($photo)) {
2792 * Check to see if we should replace this photo link with an embedded image
2793 * 1. No need to do so if the photo is public
2794 * 2. If there's a contact-id provided, see if they're in the access list
2795 * for the photo. If so, embed it.
2796 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2797 * permissions, regardless of order but first check to see if they're an exact
2798 * match to save some processing overhead.
2800 if (self::hasPermissions($photo)) {
2802 $recips = self::enumeratePermissions($uid, $photo);
2803 if (in_array($cid, $recips)) {
2807 if (self::samePermissions($uid, $item, $photo)) {
2813 $photo_img = Photo::getImageForPhoto($photo);
2814 // If a custom width and height were specified, apply before embedding
2815 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2816 Logger::log('scaling photo', Logger::DEBUG);
2818 $width = intval($match[1]);
2819 $height = intval($match[2]);
2821 $photo_img->scaleDown(max($width, $height));
2824 $data = $photo_img->asString();
2825 $type = $photo_img->getType();
2827 Logger::log('replacing photo', Logger::DEBUG);
2828 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2829 Logger::log('replaced: ' . $image, Logger::DATA);
2835 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2836 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2837 if ($orig_body === false) {
2841 $img_start = strpos($orig_body, '[img');
2842 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2843 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2846 $new_body = $new_body . $orig_body;
2851 private static function hasPermissions($obj)
2853 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2854 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2857 private static function samePermissions($uid, $obj1, $obj2)
2859 // first part is easy. Check that these are exactly the same.
2860 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2861 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2862 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2863 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2867 // This is harder. Parse all the permissions and compare the resulting set.
2868 $recipients1 = self::enumeratePermissions($uid, $obj1);
2869 $recipients2 = self::enumeratePermissions($uid, $obj2);
2873 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2874 return ($recipients1 == $recipients2);
2877 // returns an array of contact-ids that are allowed to see this object
2878 public static function enumeratePermissions($uid, array $obj)
2880 $allow_people = expand_acl($obj['allow_cid']);
2881 $allow_groups = Group::expand($uid, expand_acl($obj['allow_gid']));
2882 $deny_people = expand_acl($obj['deny_cid']);
2883 $deny_groups = Group::expand($uid, expand_acl($obj['deny_gid']));
2884 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2885 $deny = array_unique(array_merge($deny_people, $deny_groups));
2886 $recipients = array_diff($recipients, $deny);
2890 public static function getFeedTags($item)
2894 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2896 for ($x = 0; $x < $cnt; $x ++) {
2897 if ($matches[1][$x]) {
2898 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2903 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2905 for ($x = 0; $x < $cnt; $x ++) {
2906 if ($matches[1][$x]) {
2907 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2914 public static function expire($uid, $days, $network = "", $force = false)
2916 if (!$uid || ($days < 1)) {
2920 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2921 $uid, GRAVITY_PARENT];
2924 * $expire_network_only = save your own wall posts
2925 * and just expire conversations started by others
2927 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2929 if ($expire_network_only) {
2930 $condition[0] .= " AND NOT `wall`";
2933 if ($network != "") {
2934 $condition[0] .= " AND `network` = ?";
2935 $condition[] = $network;
2938 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2939 $condition[] = $days;
2941 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2943 if (!DBA::isResult($items)) {
2947 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2949 // Forcing expiring of items - but not notes and marked items
2951 $expire_items = true;
2954 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2955 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2956 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2960 while ($item = Item::fetch($items)) {
2961 // don't expire filed items
2963 if (strpos($item['file'], '[') !== false) {
2967 // Only expire posts, not photos and photo comments
2969 if (!$expire_photos && strlen($item['resource-id'])) {
2971 } elseif (!$expire_starred && intval($item['starred'])) {
2973 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2975 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2979 self::deleteById($item['id'], PRIORITY_LOW);
2984 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2987 public static function firstPostDate($uid, $wall = false)
2989 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2990 $params = ['order' => ['received' => false]];
2991 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
2992 if (DBA::isResult($thread)) {
2993 return substr(DateTimeFormat::local($thread['received']), 0, 10);
2999 * @brief add/remove activity to an item
3001 * Toggle activities as like,dislike,attend of an item
3003 * @param string $item_id
3004 * @param string $verb
3005 * Activity verb. One of
3006 * like, unlike, dislike, undislike, attendyes, unattendyes,
3007 * attendno, unattendno, attendmaybe, unattendmaybe
3009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3010 * @throws \ImagickException
3011 * @hook 'post_local_end'
3013 * 'post_id' => ID of posted item
3015 public static function performLike($item_id, $verb)
3017 if (!local_user() && !remote_user()) {
3024 $activity = ACTIVITY_LIKE;
3028 $activity = ACTIVITY_DISLIKE;
3032 $activity = ACTIVITY_ATTEND;
3036 $activity = ACTIVITY_ATTENDNO;
3039 case 'unattendmaybe':
3040 $activity = ACTIVITY_ATTENDMAYBE;
3043 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3047 // Enable activity toggling instead of on/off
3048 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3050 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3052 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3053 if (!DBA::isResult($item)) {
3054 Logger::log('like: unknown item ' . $item_id);
3058 $item_uri = $item['uri'];
3060 $uid = $item['uid'];
3061 if (($uid == 0) && local_user()) {
3062 $uid = local_user();
3065 if (!Security::canWriteToUserWall($uid)) {
3066 Logger::log('like: unable to write on wall ' . $uid);
3070 // Retrieves the local post owner
3071 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3072 if (!DBA::isResult($owner_self_contact)) {
3073 Logger::log('like: unknown owner ' . $uid);
3077 // Retrieve the current logged in user's public contact
3078 $author_id = public_contact();
3080 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3081 if (!DBA::isResult($author_contact)) {
3082 Logger::log('like: unknown author ' . $author_id);
3086 // Contact-id is the uid-dependant author contact
3087 if (local_user() == $uid) {
3088 $item_contact_id = $owner_self_contact['id'];
3090 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3091 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3092 if (!DBA::isResult($item_contact)) {
3093 Logger::log('like: unknown item contact ' . $item_contact_id);
3098 // Look for an existing verb row
3099 // event participation are essentially radio toggles. If you make a subsequent choice,
3100 // we need to eradicate your first choice.
3101 if ($event_verb_flag) {
3102 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3104 // Translate to the index based activity index
3106 foreach ($verbs as $verb) {
3107 $activities[] = self::activityToIndex($verb);
3110 $activities = self::activityToIndex($activity);
3113 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3114 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3116 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3118 // If it exists, mark it as deleted
3119 if (DBA::isResult($like_item)) {
3120 self::deleteById($like_item['id']);
3122 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3127 // Verb is "un-something", just trying to delete existing entries
3128 if (strpos($verb, 'un') === 0) {
3132 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3135 'guid' => System::createUUID(),
3136 'uri' => self::newURI($item['uid']),
3137 'uid' => $item['uid'],
3138 'contact-id' => $item_contact_id,
3139 'wall' => $item['wall'],
3141 'network' => Protocol::DFRN,
3142 'gravity' => GRAVITY_ACTIVITY,
3143 'parent' => $item['id'],
3144 'parent-uri' => $item['uri'],
3145 'thr-parent' => $item['uri'],
3146 'owner-id' => $author_id,
3147 'author-id' => $author_id,
3148 'body' => $activity,
3149 'verb' => $activity,
3150 'object-type' => $objtype,
3151 'allow_cid' => $item['allow_cid'],
3152 'allow_gid' => $item['allow_gid'],
3153 'deny_cid' => $item['deny_cid'],
3154 'deny_gid' => $item['deny_gid'],
3159 $signed = Diaspora::createLikeSignature($uid, $new_item);
3160 if (!empty($signed)) {
3161 $new_item['diaspora_signed_text'] = json_encode($signed);
3164 $new_item_id = self::insert($new_item);
3166 // If the parent item isn't visible then set it to visible
3167 if (!$item['visible']) {
3168 self::update(['visible' => true], ['id' => $item['id']]);
3171 $new_item['id'] = $new_item_id;
3173 Hook::callAll('post_local_end', $new_item);
3178 private static function addThread($itemid, $onlyshadow = false)
3180 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3181 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3182 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3183 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3184 $item = self::selectFirst($fields, $condition);
3186 if (!DBA::isResult($item)) {
3190 $item['iid'] = $itemid;
3193 $result = DBA::insert('thread', $item);
3195 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3199 private static function updateThread($itemid, $setmention = false)
3201 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3202 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3203 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3204 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3206 $item = self::selectFirst($fields, $condition);
3207 if (!DBA::isResult($item)) {
3212 $item["mention"] = 1;
3217 foreach ($item as $field => $data) {
3218 if (!in_array($field, ["guid"])) {
3219 $fields[$field] = $data;
3223 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3225 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3228 private static function deleteThread($itemid, $itemuri = "")
3230 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3231 if (!DBA::isResult($item)) {
3232 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3236 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3238 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3240 if ($itemuri != "") {
3241 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3242 if (!self::exists($condition)) {
3243 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3244 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3249 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3251 $local_user = local_user();
3252 $remote_user = remote_user();
3255 * Construct permissions
3257 * default permissions - anonymous user
3259 $sql = " AND NOT `item`.`private`";
3261 // Profile owner - everything is visible
3262 if ($local_user && ($local_user == $owner_id)) {
3264 } elseif ($remote_user) {
3266 * Authenticated visitor. Unless pre-verified,
3267 * check that the contact belongs to this $owner_id
3268 * and load the groups the visitor belongs to.
3269 * If pre-verified, the caller is expected to have already
3270 * done this and passed the groups into this function.
3272 $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3275 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3280 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3287 * get translated item type
3292 public static function postType($item)
3294 if (!empty($item['event-id'])) {
3295 return L10n::t('event');
3296 } elseif (!empty($item['resource-id'])) {
3297 return L10n::t('photo');
3298 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3299 return L10n::t('activity');
3300 } elseif ($item['id'] != $item['parent']) {
3301 return L10n::t('comment');
3304 return L10n::t('post');
3308 * Sets the "rendered-html" field of the provided item
3310 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3312 * @param array $item
3313 * @param bool $update
3315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3316 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3318 public static function putInCache(&$item, $update = false)
3320 $body = $item["body"];
3322 $rendered_hash = defaults($item, 'rendered-hash', '');
3323 $rendered_html = defaults($item, 'rendered-html', '');
3325 if ($rendered_hash == ''
3326 || $rendered_html == ""
3327 || $rendered_hash != hash("md5", $item["body"])
3328 || Config::get("system", "ignore_cache")
3330 $a = self::getApp();
3331 redir_private_images($a, $item);
3333 $item["rendered-html"] = prepare_text($item["body"]);
3334 $item["rendered-hash"] = hash("md5", $item["body"]);
3336 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3337 Hook::callAll('put_item_in_cache', $hook_data);
3338 $item['rendered-html'] = $hook_data['rendered-html'];
3339 $item['rendered-hash'] = $hook_data['rendered-hash'];
3342 // Force an update if the generated values differ from the existing ones
3343 if ($rendered_hash != $item["rendered-hash"]) {
3347 // Only compare the HTML when we forcefully ignore the cache
3348 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3352 if ($update && !empty($item["id"])) {
3355 'rendered-html' => $item["rendered-html"],
3356 'rendered-hash' => $item["rendered-hash"]
3358 ['id' => $item["id"]]
3363 $item["body"] = $body;
3367 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3368 * If attach is true, also add icons for item attachments.
3370 * @param array $item
3371 * @param boolean $attach
3372 * @param boolean $is_preview
3373 * @return string item body html
3374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3375 * @throws \ImagickException
3376 * @hook prepare_body_init item array before any work
3377 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3378 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3379 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3381 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3383 $a = self::getApp();
3384 Hook::callAll('prepare_body_init', $item);
3386 // In order to provide theme developers more possibilities, event items
3387 // are treated differently.
3388 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3389 $ev = Event::getItemHTML($item);
3393 $tags = Term::populateTagsFromItem($item);
3395 $item['tags'] = $tags['tags'];
3396 $item['hashtags'] = $tags['hashtags'];
3397 $item['mentions'] = $tags['mentions'];
3399 // Compile eventual content filter reasons
3400 $filter_reasons = [];
3401 if (!$is_preview && public_contact() != $item['author-id']) {
3402 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3403 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3408 'filter_reasons' => $filter_reasons
3410 Hook::callAll('prepare_body_content_filter', $hook_data);
3411 $filter_reasons = $hook_data['filter_reasons'];
3415 // Update the cached values if there is no "zrl=..." on the links.
3416 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3418 // Or update it if the current viewer is the intented viewer.
3419 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3423 self::putInCache($item, $update);
3424 $s = $item["rendered-html"];
3429 'preview' => $is_preview,
3430 'filter_reasons' => $filter_reasons
3432 Hook::callAll('prepare_body', $hook_data);
3433 $s = $hook_data['html'];
3437 // Replace the blockquotes with quotes that are used in mails.
3438 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3439 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3446 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3447 foreach ($matches as $mtch) {
3450 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3452 if (strpos($mime, 'video') !== false) {
3455 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3458 $url_parts = explode('/', $the_url);
3459 $id = end($url_parts);
3460 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3463 'title' => L10n::t('View Video'),
3470 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3472 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3473 $filesubtype = str_replace('.', '-', $filesubtype);
3476 $filesubtype = 'unkn';
3479 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3480 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3482 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3483 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3487 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3491 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3492 $x = Map::byCoordinates(trim($item['coord']));
3494 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3499 // Look for spoiler.
3500 $spoilersearch = '<blockquote class="spoiler">';
3502 // Remove line breaks before the spoiler.
3503 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3504 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3506 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3507 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3510 while ((strpos($s, $spoilersearch) !== false)) {
3511 $pos = strpos($s, $spoilersearch);
3512 $rnd = Strings::getRandomHex(8);
3513 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3514 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3515 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3518 // Look for quote with author.
3519 $authorsearch = '<blockquote class="author">';
3521 while ((strpos($s, $authorsearch) !== false)) {
3522 $pos = strpos($s, $authorsearch);
3523 $rnd = Strings::getRandomHex(8);
3524 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3525 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3526 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3529 // Replace friendica image url size with theme preference.
3530 if (!empty($a->theme_info['item_image_size'])) {
3531 $ps = $a->theme_info['item_image_size'];
3532 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3535 $s = HTML::applyContentFilter($s, $filter_reasons);
3537 $hook_data = ['item' => $item, 'html' => $s];
3538 Hook::callAll('prepare_body_final', $hook_data);
3540 return $hook_data['html'];
3544 * get private link for item
3546 * @param array $item
3547 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3548 * @throws \Exception
3550 public static function getPlink($item)
3552 $a = self::getApp();
3554 if ($a->user['nickname'] != "") {
3556 'href' => "display/" . $item['guid'],
3557 'orig' => "display/" . $item['guid'],
3558 'title' => L10n::t('View on separate page'),
3559 'orig_title' => L10n::t('view on separate page'),
3562 if (!empty($item['plink'])) {
3563 $ret["href"] = $a->removeBaseURL($item['plink']);
3564 $ret["title"] = L10n::t('link to source');
3567 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3569 'href' => $item['plink'],
3570 'orig' => $item['plink'],
3571 'title' => L10n::t('link to source'),
3581 * Is the given item array a post that is sent as starting post to a forum?
3583 * @param array $item
3584 * @param array $owner
3586 * @return boolean "true" when it is a forum post
3588 public static function isForumPost(array $item, array $owner = [])
3590 if (empty($owner)) {
3591 $owner = User::getOwnerDataById($item['uid']);
3592 if (empty($owner)) {
3597 if (($item['author-id'] == $item['owner-id']) ||
3598 ($owner['id'] == $item['contact-id']) ||
3599 ($item['uri'] != $item['parent-uri']) ||
3604 return Contact::isForum($item['contact-id']);
3608 * Search item id for given URI or plink
3610 * @param string $uri
3611 * @param integer $uid
3613 * @return integer item id
3615 public static function searchByLink($uri, $uid = 0)
3617 $ssl_uri = str_replace('http://', 'https://', $uri);
3618 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3620 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3621 if (DBA::isResult($item)) {
3625 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3626 if (!DBA::isResult($itemcontent)) {
3630 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3631 if (!DBA::isResult($itemuri)) {
3635 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3636 if (DBA::isResult($item)) {
3644 * Fetches item for given URI or plink
3646 * @param string $uri
3647 * @param integer $uid
3649 * @return integer item id
3651 public static function fetchByLink($uri, $uid = 0)
3653 $item_id = self::searchByLink($uri, $uid);
3654 if (!empty($item_id)) {
3658 if (ActivityPub\Processor::fetchMissingActivity($uri)) {
3659 $item_id = self::searchByLink($uri, $uid);
3661 $item_id = Diaspora::fetchByURL($uri);
3664 if (!empty($item_id)) {