3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Diaspora;
38 use Friendica\Protocol\OStatus;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Map;
41 use Friendica\Util\Network;
42 use Friendica\Util\Security;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use Friendica\Worker\Delivery;
46 use Text_LanguageDetect;
47 use Friendica\Repository\PermissionSet as RepPermissionSet;
51 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
58 const PT_DOCUMENT = 19;
60 const PT_PERSONAL_NOTE = 128;
62 // Field list that is used to display the items
63 const DISPLAY_FIELDLIST = [
64 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network', 'gravity',
65 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
66 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
67 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
68 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
69 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
70 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
71 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
72 'writable', 'self', 'cid', 'alias', 'pinned',
73 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
74 'event-summary', 'event-desc', 'event-location', 'event-type',
75 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
76 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
79 // Field list that is used to deliver items via the protocols
80 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
81 'parent-guid', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
82 'private', 'title', 'body', 'location', 'coord', 'app',
83 'attach', 'tag', 'deleted', 'extid', 'post-type',
84 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
85 'author-id', 'author-link', 'owner-link', 'contact-uid',
86 'signed_text', 'signature', 'signer', 'network'];
88 // Field list for "item-content" table that is mixed with the item table
89 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
90 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
91 'object-type', 'object', 'target-type', 'target', 'plink'];
93 // Field list for "item-content" table that is not present in the "item" table
94 const CONTENT_FIELDLIST = ['language'];
96 // All fields in the item table
97 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
98 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
99 'created', 'edited', 'commented', 'received', 'changed', 'verb',
100 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
101 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
102 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
103 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
104 'title', 'content-warning', 'body', 'location', 'coord', 'app',
105 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
106 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
107 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
109 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
110 // The item-activity table only stores the index and needs this array to know the matching activity.
112 Activity::LIKE, Activity::DISLIKE,
113 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
121 private static $legacy_mode = null;
123 public static function isLegacyMode()
125 if (is_null(self::$legacy_mode)) {
126 self::$legacy_mode = (DI::config()->get("system", "post_update_version") < 1279);
129 return self::$legacy_mode;
133 * Set the pinned state of an item
135 * @param integer $iid Item ID
136 * @param integer $uid User ID
137 * @param boolean $pinned Pinned state
139 public static function setPinned(int $iid, int $uid, bool $pinned)
141 DBA::update('user-item', ['pinned' => $pinned], ['iid' => $iid, 'uid' => $uid], true);
145 * Get the pinned state
147 * @param integer $iid Item ID
148 * @param integer $uid User ID
150 * @return boolean pinned state
152 public static function getPinned(int $iid, int $uid)
154 $useritem = DBA::selectFirst('user-item', ['pinned'], ['iid' => $iid, 'uid' => $uid]);
155 if (!DBA::isResult($useritem)) {
158 return (bool)$useritem['pinned'];
162 * Select pinned rows from the item table for a given user
164 * @param integer $uid User ID
165 * @param array $selected Array of selected fields, empty for all
166 * @param array $condition Array of fields for condition
167 * @param array $params Array of several parameters
169 * @return boolean|object
172 public static function selectPinned(int $uid, array $selected = [], array $condition = [], $params = [])
174 $useritems = DBA::select('user-item', ['iid'], ['uid' => $uid, 'pinned' => true]);
175 if (!DBA::isResult($useritems)) {
180 while ($useritem = self::fetch($useritems)) {
181 $pinned[] = $useritem['iid'];
183 DBA::close($useritems);
185 if (empty($pinned)) {
189 if (empty($condition) || !is_array($condition)) {
190 $condition = ['iid' => $pinned];
193 $first_key = key($condition);
194 if (!is_int($first_key)) {
195 $condition['iid'] = $pinned;
197 $values_string = substr(str_repeat("?, ", count($pinned)), 0, -2);
198 $condition[0] = '(' . $condition[0] . ") AND `iid` IN (" . $values_string . ")";
199 $condition = array_merge($condition, $pinned);
203 return self::selectThreadForUser($uid, $selected, $condition, $params);
207 * returns an activity index from an activity string
209 * @param string $activity activity string
210 * @return integer Activity index
212 public static function activityToIndex($activity)
214 $index = array_search($activity, self::ACTIVITIES);
216 if (is_bool($index)) {
224 * returns an activity string from an activity index
226 * @param integer $index activity index
227 * @return string Activity string
229 private static function indexToActivity($index)
231 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
235 return self::ACTIVITIES[$index];
239 * Fetch a single item row
241 * @param mixed $stmt statement object
242 * @return array current row
244 public static function fetch($stmt)
246 $row = DBA::fetch($stmt);
252 // ---------------------- Transform item structure data ----------------------
254 // We prefer the data from the user's contact over the public one
255 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
256 ($row['author-link'] == $row['contact-link'])) {
257 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
258 $row['author-avatar'] = $row['contact-avatar'];
260 if (isset($row['author-name']) && !empty($row['contact-name'])) {
261 $row['author-name'] = $row['contact-name'];
265 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
266 ($row['owner-link'] == $row['contact-link'])) {
267 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
268 $row['owner-avatar'] = $row['contact-avatar'];
270 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
271 $row['owner-name'] = $row['contact-name'];
275 // We can always comment on posts from these networks
276 if (array_key_exists('writable', $row) &&
277 in_array($row['internal-network'], Protocol::FEDERATED)) {
278 $row['writable'] = true;
281 // ---------------------- Transform item content data ----------------------
283 // Fetch data from the item-content table whenever there is content there
284 if (self::isLegacyMode()) {
285 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
286 foreach ($legacy_fields as $field) {
287 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
288 $row[$field] = $row['internal-item-' . $field];
290 unset($row['internal-item-' . $field]);
294 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
295 $row['verb'] = self::indexToActivity($row['internal-activity']);
296 if (array_key_exists('title', $row)) {
299 if (array_key_exists('body', $row)) {
300 $row['body'] = $row['verb'];
302 if (array_key_exists('object', $row)) {
305 if (array_key_exists('object-type', $row)) {
306 $row['object-type'] = Activity\ObjectType::NOTE;
308 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
309 // Posts don't have a target - but having tags or files.
310 // We safe some performance by building tag and file strings only here.
311 // We remove the target since they aren't used for this type.
312 // In mail posts we do store some mail header data in the object.
313 if (array_key_exists('target', $row)) {
318 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', Activity::POST, Activity::SHARE])) {
319 // Build the tag string out of the term entries
320 if (array_key_exists('tag', $row) && empty($row['tag'])) {
321 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
324 // Build the file string out of the term entries
325 if (array_key_exists('file', $row) && empty($row['file'])) {
326 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
330 if ($row['internal-psid'] == RepPermissionSet::PUBLIC) {
331 if (array_key_exists('allow_cid', $row)) {
332 $row['allow_cid'] = '';
334 if (array_key_exists('allow_gid', $row)) {
335 $row['allow_gid'] = '';
337 if (array_key_exists('deny_cid', $row)) {
338 $row['deny_cid'] = '';
340 if (array_key_exists('deny_gid', $row)) {
341 $row['deny_gid'] = '';
345 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
346 $row['signed_text'] = $row['interaction'];
349 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
350 $row['ignored'] = $row['internal-user-ignored'];
353 // Remove internal fields
354 unset($row['internal-activity']);
355 unset($row['internal-network']);
356 unset($row['internal-iid']);
357 unset($row['internal-psid']);
358 unset($row['internal-iaid']);
359 unset($row['internal-icid']);
360 unset($row['internal-user-ignored']);
361 unset($row['interaction']);
367 * Fills an array with data from an item query
369 * @param object $stmt statement object
370 * @param bool $do_close
371 * @return array Data array
373 public static function inArray($stmt, $do_close = true) {
374 if (is_bool($stmt)) {
379 while ($row = self::fetch($stmt)) {
389 * Check if item data exists
391 * @param array $condition array of fields for condition
393 * @return boolean Are there rows for that condition?
396 public static function exists($condition) {
397 $stmt = self::select(['id'], $condition, ['limit' => 1]);
399 if (is_bool($stmt)) {
402 $retval = (DBA::numRows($stmt) > 0);
411 * Retrieve a single record from the item table for a given user and returns it in an associative array
413 * @param integer $uid User ID
414 * @param array $selected
415 * @param array $condition
416 * @param array $params
421 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
423 $params['uid'] = $uid;
425 if (empty($selected)) {
426 $selected = Item::DISPLAY_FIELDLIST;
429 return self::selectFirst($selected, $condition, $params);
433 * Select rows from the item table for a given user
435 * @param integer $uid User ID
436 * @param array $selected Array of selected fields, empty for all
437 * @param array $condition Array of fields for condition
438 * @param array $params Array of several parameters
440 * @return boolean|object
443 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
445 $params['uid'] = $uid;
447 if (empty($selected)) {
448 $selected = Item::DISPLAY_FIELDLIST;
451 return self::select($selected, $condition, $params);
455 * Retrieve a single record from the item table and returns it in an associative array
457 * @param array $fields
458 * @param array $condition
459 * @param array $params
464 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
466 $params['limit'] = 1;
468 $result = self::select($fields, $condition, $params);
470 if (is_bool($result)) {
473 $row = self::fetch($result);
480 * Select rows from the item table and returns them as an array
482 * @param array $selected Array of selected fields, empty for all
483 * @param array $condition Array of fields for condition
484 * @param array $params Array of several parameters
489 public static function selectToArray(array $fields = [], array $condition = [], $params = [])
491 $result = self::select($fields, $condition, $params);
493 if (is_bool($result)) {
498 while ($row = self::fetch($result)) {
507 * Select rows from the item table
509 * @param array $selected Array of selected fields, empty for all
510 * @param array $condition Array of fields for condition
511 * @param array $params Array of several parameters
513 * @return boolean|object
516 public static function select(array $selected = [], array $condition = [], $params = [])
521 if (isset($params['uid'])) {
522 $uid = $params['uid'];
526 $fields = self::fieldlist($usermode);
528 $select_fields = self::constructSelectFields($fields, $selected);
530 $condition_string = DBA::buildCondition($condition);
532 $condition_string = self::addTablesToFields($condition_string, $fields);
535 $condition_string = $condition_string . ' AND ' . self::condition(false);
538 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
540 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
542 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
544 return DBA::p($sql, $condition);
548 * Select rows from the starting post in the item table
550 * @param integer $uid User ID
551 * @param array $selected
552 * @param array $condition Array of fields for condition
553 * @param array $params Array of several parameters
555 * @return boolean|object
558 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
560 $params['uid'] = $uid;
562 if (empty($selected)) {
563 $selected = Item::DISPLAY_FIELDLIST;
566 return self::selectThread($selected, $condition, $params);
570 * Retrieve a single record from the starting post in the item table and returns it in an associative array
572 * @param integer $uid User ID
573 * @param array $selected
574 * @param array $condition
575 * @param array $params
580 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
582 $params['uid'] = $uid;
584 if (empty($selected)) {
585 $selected = Item::DISPLAY_FIELDLIST;
588 return self::selectFirstThread($selected, $condition, $params);
592 * Retrieve a single record from the starting post in the item table and returns it in an associative array
594 * @param array $fields
595 * @param array $condition
596 * @param array $params
601 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
603 $params['limit'] = 1;
604 $result = self::selectThread($fields, $condition, $params);
606 if (is_bool($result)) {
609 $row = self::fetch($result);
616 * Select rows from the starting post in the item table
618 * @param array $selected Array of selected fields, empty for all
619 * @param array $condition Array of fields for condition
620 * @param array $params Array of several parameters
622 * @return boolean|object
625 public static function selectThread(array $selected = [], array $condition = [], $params = [])
630 if (isset($params['uid'])) {
631 $uid = $params['uid'];
635 $fields = self::fieldlist($usermode);
637 $fields['thread'] = ['mention', 'ignored', 'iid'];
639 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
640 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
641 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
642 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
644 $select_fields = self::constructSelectFields($fields, $selected);
646 $condition_string = DBA::buildCondition($condition);
648 $condition_string = self::addTablesToFields($condition_string, $threadfields);
649 $condition_string = self::addTablesToFields($condition_string, $fields);
652 $condition_string = $condition_string . ' AND ' . self::condition(true);
655 $param_string = DBA::buildParameter($params);
656 $param_string = self::addTablesToFields($param_string, $threadfields);
657 $param_string = self::addTablesToFields($param_string, $fields);
659 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
661 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
663 return DBA::p($sql, $condition);
667 * Returns a list of fields that are associated with the item table
670 * @return array field list
672 private static function fieldlist($usermode)
676 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
677 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
678 'created', 'edited', 'commented', 'received', 'changed', 'psid',
679 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
680 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
681 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
682 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
683 'network' => 'internal-network', 'icid' => 'internal-icid',
684 'iaid' => 'internal-iaid', 'psid' => 'internal-psid'];
687 $fields['user-item'] = ['pinned', 'notification-type', 'ignored' => 'internal-user-ignored'];
690 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
692 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
694 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
696 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
698 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name', 'addr' => 'author-addr',
699 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
701 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name', 'addr' => 'owner-addr',
702 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
704 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
705 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
706 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
708 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
710 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
712 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
713 'start' => 'event-start','finish' => 'event-finish',
714 'summary' => 'event-summary','desc' => 'event-desc',
715 'location' => 'event-location', 'type' => 'event-type',
716 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
717 'ignore' => 'event-ignore', 'id' => 'event-id'];
719 $fields['sign'] = ['signed_text', 'signature', 'signer'];
721 $fields['diaspora-interaction'] = ['interaction'];
727 * Returns SQL condition for the "select" functions
729 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
731 * @return string SQL condition
733 private static function condition($thread_mode)
736 $master_table = "`thread`";
738 $master_table = "`item`";
740 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
741 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
742 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
743 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
744 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
745 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
746 GRAVITY_PARENT, GRAVITY_PARENT);
750 * Returns all needed "JOIN" commands for the "select" functions
752 * @param integer $uid User ID
753 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
754 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
757 * @return string The SQL joins for the "select" functions
759 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
762 $master_table = "`thread`";
763 $master_table_key = "`thread`.`iid`";
764 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
766 $master_table = "`item`";
767 $master_table_key = "`item`.`id`";
772 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
773 AND NOT `contact`.`blocked`
774 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
775 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
776 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
777 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
778 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
779 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
780 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
781 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
783 if (strpos($sql_commands, "`contact`.") !== false) {
784 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
786 if (strpos($sql_commands, "`author`.") !== false) {
787 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
789 if (strpos($sql_commands, "`owner`.") !== false) {
790 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
794 if (strpos($sql_commands, "`group_member`.") !== false) {
795 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
798 if (strpos($sql_commands, "`user`.") !== false) {
799 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
802 if (strpos($sql_commands, "`event`.") !== false) {
803 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
806 if (strpos($sql_commands, "`sign`.") !== false) {
807 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
810 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
811 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
814 if (strpos($sql_commands, "`item-activity`.") !== false) {
815 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
818 if (strpos($sql_commands, "`item-content`.") !== false) {
819 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
822 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
823 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
826 if (strpos($sql_commands, "`permissionset`.") !== false) {
827 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
830 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
831 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
834 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
835 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
842 * Add the field list for the "select" functions
844 * @param array $fields The field definition array
845 * @param array $selected The array with the selected fields from the "select" functions
847 * @return string The field list
849 private static function constructSelectFields($fields, $selected)
851 if (!empty($selected)) {
852 $selected[] = 'internal-iid';
853 $selected[] = 'internal-psid';
854 $selected[] = 'internal-iaid';
855 $selected[] = 'internal-icid';
856 $selected[] = 'internal-network';
859 if (in_array('verb', $selected)) {
860 $selected[] = 'internal-activity';
863 if (in_array('ignored', $selected)) {
864 $selected[] = 'internal-user-ignored';
867 if (in_array('signed_text', $selected)) {
868 $selected[] = 'interaction';
871 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
874 foreach ($fields as $table => $table_fields) {
875 foreach ($table_fields as $field => $select) {
876 if (empty($selected) || in_array($select, $selected)) {
877 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
878 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
880 if (is_int($field)) {
881 $selection[] = "`" . $table . "`.`" . $select . "`";
883 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
888 return implode(", ", $selection);
892 * add table definition to fields in an SQL query
894 * @param string $query SQL query
895 * @param array $fields The field definition array
897 * @return string the changed SQL query
899 private static function addTablesToFields($query, $fields)
901 foreach ($fields as $table => $table_fields) {
902 foreach ($table_fields as $alias => $field) {
903 if (is_int($alias)) {
904 $replace_field = $field;
906 $replace_field = $alias;
909 $search = "/([^\.])`" . $field . "`/i";
910 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
911 $query = preg_replace($search, $replace, $query);
918 * Update existing item entries
920 * @param array $fields The fields that are to be changed
921 * @param array $condition The condition for finding the item entries
923 * In the future we may have to change permissions as well.
924 * Then we had to add the user id as third parameter.
926 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
928 * @return integer|boolean number of affected rows - or "false" if there was an error
929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931 public static function update(array $fields, array $condition)
933 if (empty($condition) || empty($fields)) {
937 // To ensure the data integrity we do it in an transaction
940 // We cannot simply expand the condition to check for origin entries
941 // The condition needn't to be a simple array but could be a complex condition.
942 // And we have to execute this query before the update to ensure to fetch the same data.
943 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
945 $content_fields = [];
946 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
947 if (isset($fields[$field])) {
948 $content_fields[$field] = $fields[$field];
949 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
950 unset($fields[$field]);
952 $fields[$field] = null;
957 $delivery_data = ItemDeliveryData::extractFields($fields);
959 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
960 foreach ($clear_fields as $field) {
961 if (array_key_exists($field, $fields)) {
962 $fields[$field] = null;
966 if (array_key_exists('tag', $fields)) {
967 $tags = $fields['tag'];
968 $fields['tag'] = null;
973 if (array_key_exists('file', $fields)) {
974 $files = $fields['file'];
975 $fields['file'] = null;
980 if (!empty($fields)) {
981 $success = DBA::update('item', $fields, $condition);
990 // When there is no content for the "old" item table, this will count the fetched items
991 $rows = DBA::affectedRows();
995 while ($item = DBA::fetch($items)) {
996 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
997 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
999 if (empty($item['iaid'])) {
1000 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1001 if (DBA::isResult($item_activity)) {
1002 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
1003 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
1004 if (self::isLegacyMode()) {
1005 $item_fields[$field] = null;
1007 unset($item_fields[$field]);
1010 DBA::update('item', $item_fields, ['id' => $item['id']]);
1012 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
1013 DBA::delete('item-content', ['id' => $item['icid']]);
1016 } elseif (!empty($item['icid'])) {
1017 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
1019 if (!DBA::exists('item', ['icid' => $item['icid']])) {
1020 DBA::delete('item-content', ['id' => $item['icid']]);
1024 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
1026 if (empty($item['icid'])) {
1027 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
1028 if (DBA::isResult($item_content)) {
1029 $item_fields = ['icid' => $item_content['id']];
1030 // Clear all fields in the item table that have a content in the item-content table
1031 foreach ($item_content as $field => $content) {
1032 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
1033 if (self::isLegacyMode()) {
1034 $item_fields[$field] = null;
1036 unset($item_fields[$field]);
1040 DBA::update('item', $item_fields, ['id' => $item['id']]);
1045 if (!is_null($tags)) {
1046 Term::insertFromTagFieldByItemId($item['id'], $tags);
1047 if (!empty($item['tag'])) {
1048 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
1052 if (!is_null($files)) {
1053 Term::insertFromFileFieldByItemId($item['id'], $files);
1054 if (!empty($item['file'])) {
1055 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
1059 ItemDeliveryData::update($item['id'], $delivery_data);
1061 self::updateThread($item['id']);
1063 // We only need to notfiy others when it is an original entry from us.
1064 // Only call the notifier when the item has some content relevant change.
1065 if ($item['origin'] && in_array('edited', array_keys($fields))) {
1066 $notify_items[] = $item['id'];
1073 foreach ($notify_items as $notify_item) {
1074 Worker::add(PRIORITY_HIGH, "Notifier", Delivery::POST, $notify_item);
1081 * Delete an item and notify others about it - if it was ours
1083 * @param array $condition The condition for finding the item entries
1084 * @param integer $priority Priority for the notification
1085 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087 public static function markForDeletion($condition, $priority = PRIORITY_HIGH)
1089 $items = self::select(['id'], $condition);
1090 while ($item = self::fetch($items)) {
1091 self::markForDeletionById($item['id'], $priority);
1097 * Delete an item for an user and notify others about it - if it was ours
1099 * @param array $condition The condition for finding the item entries
1100 * @param integer $uid User who wants to delete this item
1101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103 public static function deleteForUser($condition, $uid)
1109 $items = self::select(['id', 'uid'], $condition);
1110 while ($item = self::fetch($items)) {
1111 // "Deleting" global items just means hiding them
1112 if ($item['uid'] == 0) {
1113 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
1115 // Delete notifications
1116 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $uid]);
1117 } elseif ($item['uid'] == $uid) {
1118 self::markForDeletionById($item['id'], PRIORITY_HIGH);
1120 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
1127 * Mark an item for deletion, delete related data and notify others about it - if it was ours
1129 * @param integer $item_id
1130 * @param integer $priority Priority for the notification
1132 * @return boolean success
1133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1135 public static function markForDeletionById($item_id, $priority = PRIORITY_HIGH)
1137 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
1138 // locate item to be deleted
1139 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1140 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1141 'verb', 'object-type', 'object', 'target', 'contact-id',
1142 'icid', 'iaid', 'psid'];
1143 $item = self::selectFirst($fields, ['id' => $item_id]);
1144 if (!DBA::isResult($item)) {
1145 Logger::info('Item not found.', ['id' => $item_id]);
1149 if ($item['deleted']) {
1150 Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
1154 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1155 if (!DBA::isResult($parent)) {
1156 $parent = ['origin' => false];
1159 // clean up categories and tags so they don't end up as orphans
1162 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1165 foreach ($matches as $mtch) {
1166 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1172 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1175 foreach ($matches as $mtch) {
1176 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1181 * If item is a link to a photo resource, nuke all the associated photos
1182 * (visitors will not have photo resources)
1183 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1184 * generate a resource-id and therefore aren't intimately linked to the item.
1186 /// @TODO: this should first check if photo is used elsewhere
1187 if (strlen($item['resource-id'])) {
1188 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1191 // If item is a link to an event, delete the event.
1192 if (intval($item['event-id'])) {
1193 Event::delete($item['event-id']);
1196 // If item has attachments, drop them
1197 /// @TODO: this should first check if attachment is used elsewhere
1198 foreach (explode(",", $item['attach']) as $attach) {
1199 preg_match("|attach/(\d+)|", $attach, $matches);
1200 if (is_array($matches) && count($matches) > 1) {
1201 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1205 // Delete tags that had been attached to other items
1206 self::deleteTagsFromItem($item);
1208 // Delete notifications
1209 DBA::delete('notify', ['iid' => $item['id'], 'uid' => $item['uid']]);
1211 // Set the item to "deleted"
1212 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1213 DBA::update('item', $item_fields, ['id' => $item['id']]);
1215 Term::insertFromTagFieldByItemId($item['id'], '');
1216 Term::insertFromFileFieldByItemId($item['id'], '');
1217 self::deleteThread($item['id'], $item['parent-uri']);
1219 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1220 self::markForDeletion(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1223 ItemDeliveryData::delete($item['id']);
1225 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1227 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1228 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1230 // When the permission set will be used in photo and events as well,
1231 // this query here needs to be extended.
1232 // @todo Currently deactivated. We need the permission set in the deletion process.
1233 // This is a reminder to add the removal somewhere else.
1234 //if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1235 // DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1238 // If it's the parent of a comment thread, kill all the kids
1239 if ($item['id'] == $item['parent']) {
1240 self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
1243 // Is it our comment and/or our thread?
1244 if ($item['origin'] || $parent['origin']) {
1245 // When we delete the original post we will delete all existing copies on the server as well
1246 self::markForDeletion(['uri' => $item['uri'], 'deleted' => false], $priority);
1248 // send the notification upstream/downstream
1249 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", Delivery::DELETION, intval($item['id']));
1250 } elseif ($item['uid'] != 0) {
1252 // When we delete just our local user copy of an item, we have to set a marker to hide it
1253 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1254 if (DBA::isResult($global_item)) {
1255 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1259 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
1264 private static function deleteTagsFromItem($item)
1266 if (($item["verb"] != Activity::TAG) || ($item["object-type"] != Activity\ObjectType::TAGTERM)) {
1270 $xo = XML::parseString($item["object"], false);
1271 $xt = XML::parseString($item["target"], false);
1273 if ($xt->type != Activity\ObjectType::NOTE) {
1277 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1278 if (!DBA::isResult($i)) {
1282 // For tags, the owner cannot remove the tag on the author's copy of the post.
1283 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1284 $author_copy = $item["origin"];
1286 if (($owner_remove && $author_copy) || !$owner_remove) {
1290 $tags = explode(',', $i["tag"]);
1293 foreach ($tags as $tag) {
1294 if (trim($tag) !== trim($xo->body)) {
1295 $newtags[] = trim($tag);
1299 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1302 private static function guid($item, $notify)
1304 if (!empty($item['guid'])) {
1305 return Strings::escapeTags(trim($item['guid']));
1309 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1310 // We add the hash of our own host because our host is the original creator of the post.
1311 $prefix_host = DI::baseUrl()->getHostname();
1315 // We are only storing the post so we create a GUID from the original hostname.
1316 if (!empty($item['author-link'])) {
1317 $parsed = parse_url($item['author-link']);
1318 if (!empty($parsed['host'])) {
1319 $prefix_host = $parsed['host'];
1323 if (empty($prefix_host) && !empty($item['plink'])) {
1324 $parsed = parse_url($item['plink']);
1325 if (!empty($parsed['host'])) {
1326 $prefix_host = $parsed['host'];
1330 if (empty($prefix_host) && !empty($item['uri'])) {
1331 $parsed = parse_url($item['uri']);
1332 if (!empty($parsed['host'])) {
1333 $prefix_host = $parsed['host'];
1337 // Is it in the format data@host.tld? - Used for mail contacts
1338 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1339 $mailparts = explode('@', $item['author-link']);
1340 $prefix_host = array_pop($mailparts);
1344 if (!empty($item['plink'])) {
1345 $guid = self::guidFromUri($item['plink'], $prefix_host);
1346 } elseif (!empty($item['uri'])) {
1347 $guid = self::guidFromUri($item['uri'], $prefix_host);
1349 $guid = System::createUUID(hash('crc32', $prefix_host));
1355 private static function contactId($item)
1357 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
1358 return $item['contact-id'];
1359 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
1360 return $item['contact-id'];
1361 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
1362 return $item['author-id'];
1363 } elseif (!empty($item['contact-id'])) {
1364 return $item['contact-id'];
1366 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1367 if (!empty($contact_id)) {
1371 return $item['author-id'];
1374 // This function will finally cover most of the preparation functionality in mod/item.php
1375 public static function prepare(&$item)
1378 * @TODO: Unused code triggering inspection errors
1380 $data = BBCode::getAttachmentData($item['body']);
1381 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1382 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1383 $posttype = Item::PT_PAGE;
1384 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1390 * Write an item array into a spool file to be inserted later.
1391 * This command is called whenever there are issues storing an item.
1393 * @param array $item The item fields that are to be inserted
1394 * @throws \Exception
1396 private static function spool($orig_item)
1398 // Now we store the data in the spool directory
1399 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1400 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
1402 $spoolpath = get_spoolpath();
1403 if ($spoolpath != "") {
1404 $spool = $spoolpath . '/' . $file;
1406 file_put_contents($spool, json_encode($orig_item));
1407 Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
1411 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1415 $priority = PRIORITY_HIGH;
1417 // If it is a posting where users should get notifications, then define it as wall posting
1420 $item['origin'] = 1;
1421 $item['network'] = Protocol::DFRN;
1422 $item['protocol'] = Conversation::PARCEL_DFRN;
1424 if (is_int($notify)) {
1425 $priority = $notify;
1428 $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
1431 $item['guid'] = self::guid($item, $notify);
1432 $item['uri'] = Strings::escapeTags(trim(($item['uri'] ?? '') ?: self::newURI($item['uid'], $item['guid'])));
1435 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1437 // Store conversation data
1438 $item = Conversation::insert($item);
1441 * If a Diaspora signature structure was passed in, pull it out of the
1442 * item array and set it aside for later storage.
1446 if (isset($item['dsprsig'])) {
1447 $encoded_signature = $item['dsprsig'];
1448 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1449 unset($item['dsprsig']);
1452 $diaspora_signed_text = '';
1453 if (isset($item['diaspora_signed_text'])) {
1454 $diaspora_signed_text = $item['diaspora_signed_text'];
1455 unset($item['diaspora_signed_text']);
1458 // Converting the plink
1459 /// @TODO Check if this is really still needed
1460 if ($item['network'] == Protocol::OSTATUS) {
1461 if (isset($item['plink'])) {
1462 $item['plink'] = OStatus::convertHref($item['plink']);
1463 } elseif (isset($item['uri'])) {
1464 $item['plink'] = OStatus::convertHref($item['uri']);
1468 if (!empty($item['thr-parent'])) {
1469 $item['parent-uri'] = $item['thr-parent'];
1472 $activity = DI::activity();
1474 if (isset($item['gravity'])) {
1475 $item['gravity'] = intval($item['gravity']);
1476 } elseif ($item['parent-uri'] === $item['uri']) {
1477 $item['gravity'] = GRAVITY_PARENT;
1478 } elseif ($activity->match($item['verb'], Activity::POST)) {
1479 $item['gravity'] = GRAVITY_COMMENT;
1480 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
1481 $item['gravity'] = GRAVITY_ACTIVITY;
1483 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1484 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1487 $uid = intval($item['uid']);
1489 // check for create date and expire time
1490 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
1492 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1493 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1494 $expire_interval = $user['expire'];
1497 if (($expire_interval > 0) && !empty($item['created'])) {
1498 $expire_date = time() - ($expire_interval * 86400);
1499 $created_date = strtotime($item['created']);
1500 if ($created_date < $expire_date) {
1501 Logger::notice('Item created before expiration interval.', [
1502 'created' => date('c', $created_date),
1503 'expired' => date('c', $expire_date),
1511 * Do we already have this item?
1512 * We have to check several networks since Friendica posts could be repeated
1513 * via OStatus (maybe Diasporsa as well)
1515 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
1516 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)",
1517 trim($item['uri']), $item['uid'],
1518 Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1519 $existing = self::selectFirst(['id', 'network'], $condition);
1520 if (DBA::isResult($existing)) {
1521 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1523 Logger::notice('Item already existed for user', [
1524 'uri' => $item['uri'],
1526 'network' => $item['network'],
1527 'existing_id' => $existing["id"],
1528 'existing_network' => $existing["network"]
1532 return $existing["id"];
1536 $item['wall'] = intval($item['wall'] ?? 0);
1537 $item['extid'] = trim($item['extid'] ?? '');
1538 $item['author-name'] = trim($item['author-name'] ?? '');
1539 $item['author-link'] = trim($item['author-link'] ?? '');
1540 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
1541 $item['owner-name'] = trim($item['owner-name'] ?? '');
1542 $item['owner-link'] = trim($item['owner-link'] ?? '');
1543 $item['owner-avatar'] = trim($item['owner-avatar'] ?? '');
1544 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1545 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1546 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1547 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1548 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1549 $item['title'] = trim($item['title'] ?? '');
1550 $item['location'] = trim($item['location'] ?? '');
1551 $item['coord'] = trim($item['coord'] ?? '');
1552 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1553 $item['deleted'] = 0;
1554 $item['parent-uri'] = trim(($item['parent-uri'] ?? '') ?: $item['uri']);
1555 $item['post-type'] = ($item['post-type'] ?? '') ?: self::PT_ARTICLE;
1556 $item['verb'] = trim($item['verb'] ?? '');
1557 $item['object-type'] = trim($item['object-type'] ?? '');
1558 $item['object'] = trim($item['object'] ?? '');
1559 $item['target-type'] = trim($item['target-type'] ?? '');
1560 $item['target'] = trim($item['target'] ?? '');
1561 $item['plink'] = trim($item['plink'] ?? '');
1562 $item['allow_cid'] = trim($item['allow_cid'] ?? '');
1563 $item['allow_gid'] = trim($item['allow_gid'] ?? '');
1564 $item['deny_cid'] = trim($item['deny_cid'] ?? '');
1565 $item['deny_gid'] = trim($item['deny_gid'] ?? '');
1566 $item['private'] = intval($item['private'] ?? self::PUBLIC);
1567 $item['body'] = trim($item['body'] ?? '');
1568 $item['tag'] = trim($item['tag'] ?? '');
1569 $item['attach'] = trim($item['attach'] ?? '');
1570 $item['app'] = trim($item['app'] ?? '');
1571 $item['origin'] = intval($item['origin'] ?? 0);
1572 $item['postopts'] = trim($item['postopts'] ?? '');
1573 $item['resource-id'] = trim($item['resource-id'] ?? '');
1574 $item['event-id'] = intval($item['event-id'] ?? 0);
1575 $item['inform'] = trim($item['inform'] ?? '');
1576 $item['file'] = trim($item['file'] ?? '');
1578 // When there is no content then we don't post it
1579 if ($item['body'].$item['title'] == '') {
1580 Logger::notice('No body, no title.');
1584 self::addLanguageToItemArray($item);
1586 // Items cannot be stored before they happen ...
1587 if ($item['created'] > DateTimeFormat::utcNow()) {
1588 $item['created'] = DateTimeFormat::utcNow();
1591 // We haven't invented time travel by now.
1592 if ($item['edited'] > DateTimeFormat::utcNow()) {
1593 $item['edited'] = DateTimeFormat::utcNow();
1596 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
1598 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1599 'photo' => $item['author-avatar'], 'network' => $item['network']];
1601 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, false, $default);
1603 if (Contact::isBlocked($item['author-id'])) {
1604 Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1608 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
1609 Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
1613 if (!empty($uid) && Contact::isBlockedByUser($item['author-id'], $uid)) {
1614 Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1618 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1619 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1621 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, false, $default);
1623 if (Contact::isBlocked($item['owner-id'])) {
1624 Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1628 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
1629 Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
1633 if (!empty($uid) && Contact::isBlockedByUser($item['owner-id'], $uid)) {
1634 Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1638 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
1639 if (!empty($uid) && !empty($item['causer-id']) && Contact::isBlockedByUser($item['causer-id'], $uid)) {
1640 Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1644 if (!empty($uid) && !empty($item['causer-id']) && ($item['parent-uri'] == $item['uri']) && Contact::isIgnoredByUser($item['causer-id'], $uid)) {
1645 Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'], 'uid' => $uid, 'item-uri' => $item['uri']]);
1649 // We don't store the causer, we only have it here for the checks above
1650 unset($item['causer-id']);
1651 unset($item['causer-link']);
1653 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1654 $item["contact-id"] = self::contactId($item);
1656 if ($item['network'] == Protocol::PHANTOM) {
1657 $item['network'] = Protocol::DFRN;
1658 Logger::notice('Missing network, setting to {network}.', [
1659 'uri' => $item["uri"],
1660 'network' => $item['network'],
1661 'callstack' => System::callstack()
1665 // Checking if there is already an item with the same guid
1666 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1667 if (self::exists($condition)) {
1668 Logger::notice('Found already existing item', [
1669 'guid' => $item['guid'],
1670 'uid' => $item['uid'],
1671 'network' => $item['network']
1676 if ($item['verb'] == Activity::FOLLOW) {
1677 if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($uid))) {
1678 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
1679 Logger::log("Follow: Don't store not origin follow request from us for " . $item['parent-uri'], Logger::DEBUG);
1683 $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
1684 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
1685 if (self::exists($condition)) {
1686 // It happens that we receive multiple follow requests by the same author - we only store one.
1687 Logger::log('Follow: Found existing follow request from author ' . $item['author-id'] . ' for ' . $item['parent-uri'], Logger::DEBUG);
1692 // Check for hashtags in the body and repair or add hashtag links
1693 self::setHashtags($item);
1695 $item['thr-parent'] = $item['parent-uri'];
1697 $notify_type = Delivery::POST;
1703 if ($item['parent-uri'] === $item['uri']) {
1705 $parent_deleted = 0;
1706 $allow_cid = $item['allow_cid'];
1707 $allow_gid = $item['allow_gid'];
1708 $deny_cid = $item['deny_cid'];
1709 $deny_gid = $item['deny_gid'];
1711 // find the parent and snarf the item id and ACLs
1712 // and anything else we need to inherit
1714 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1715 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1716 'wall', 'private', 'forum_mode', 'origin', 'author-id'];
1717 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1718 $params = ['order' => ['id' => false]];
1719 $parent = self::selectFirst($fields, $condition, $params);
1721 if (DBA::isResult($parent)) {
1722 // is the new message multi-level threaded?
1723 // even though we don't support it now, preserve the info
1724 // and re-attach to the conversation parent.
1726 if ($parent['uri'] != $parent['parent-uri']) {
1727 $item['parent-uri'] = $parent['parent-uri'];
1729 $condition = ['uri' => $item['parent-uri'],
1730 'parent-uri' => $item['parent-uri'],
1731 'uid' => $item['uid']];
1732 $params = ['order' => ['id' => false]];
1733 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1735 if (DBA::isResult($toplevel_parent)) {
1736 $parent = $toplevel_parent;
1740 $parent_id = $parent['id'];
1741 $parent_deleted = $parent['deleted'];
1742 $allow_cid = $parent['allow_cid'];
1743 $allow_gid = $parent['allow_gid'];
1744 $deny_cid = $parent['deny_cid'];
1745 $deny_gid = $parent['deny_gid'];
1746 $item['wall'] = $parent['wall'];
1749 * If the parent is private, force privacy for the entire conversation
1750 * This differs from the above settings as it subtly allows comments from
1751 * email correspondents to be private even if the overall thread is not.
1753 if ($parent['private']) {
1754 $item['private'] = $parent['private'];
1758 * Edge case. We host a public forum that was originally posted to privately.
1759 * The original author commented, but as this is a comment, the permissions
1760 * weren't fixed up so it will still show the comment as private unless we fix it here.
1762 if ((intval($parent['forum_mode']) == 1) && ($parent['private'] != self::PUBLIC)) {
1763 $item['private'] = self::PUBLIC;
1766 // If its a post that originated here then tag the thread as "mention"
1767 if ($item['origin'] && $item['uid']) {
1768 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1769 Logger::log('tagged thread ' . $parent_id . ' as mention for user ' . $item['uid'], Logger::DEBUG);
1772 // Update the contact relations
1773 if ($item['author-id'] != $parent['author-id']) {
1774 DBA::update('contact-relation', ['last-interaction' => $item['created']], ['cid' => $parent['author-id'], 'relation-cid' => $item['author-id']], true);
1778 * Allow one to see reply tweets from status.net even when
1779 * we don't have or can't see the original post.
1781 if ($force_parent) {
1782 Logger::log('$force_parent=true, reply converted to top-level post.');
1784 $item['parent-uri'] = $item['uri'];
1785 $item['gravity'] = GRAVITY_PARENT;
1787 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1791 $parent_deleted = 0;
1795 if (stristr($item['verb'], Activity::POKE)) {
1796 $notify_type = Delivery::POKE;
1799 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1800 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1802 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1803 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1804 if (self::exists($condition)) {
1805 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1809 // On Friendica and Diaspora the GUID is unique
1810 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1811 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1812 if (self::exists($condition)) {
1813 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1816 } elseif ($item['network'] == Protocol::OSTATUS) {
1817 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1818 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1819 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1820 if (self::exists($condition)) {
1821 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1826 // Is this item available in the global items (with uid=0)?
1827 if ($item["uid"] == 0) {
1828 $item["global"] = true;
1830 // Set the global flag on all items if this was a global item entry
1831 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1833 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1837 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1838 $private = self::PRIVATE;
1840 $private = $item['private'];
1843 $item["allow_cid"] = $allow_cid;
1844 $item["allow_gid"] = $allow_gid;
1845 $item["deny_cid"] = $deny_cid;
1846 $item["deny_gid"] = $deny_gid;
1847 $item["private"] = $private;
1848 $item["deleted"] = $parent_deleted;
1850 // Fill the cache field
1851 self::putInCache($item);
1854 $item['edit'] = false;
1855 $item['parent'] = $parent_id;
1856 Hook::callAll('post_local', $item);
1857 unset($item['edit']);
1858 unset($item['parent']);
1860 Hook::callAll('post_remote', $item);
1863 // This array field is used to trigger some automatic reactions
1864 // It is mainly used in the "post_local" hook.
1865 unset($item['api_source']);
1867 if (!empty($item['cancel'])) {
1868 Logger::log('post cancelled by addon.');
1873 * Check for already added items.
1874 * There is a timing issue here that sometimes creates double postings.
1875 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1877 if ($item["uid"] == 0) {
1878 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1879 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1884 Logger::log('' . print_r($item,true), Logger::DATA);
1886 if (array_key_exists('tag', $item)) {
1887 $tags = $item['tag'];
1888 unset($item['tag']);
1893 if (array_key_exists('file', $item)) {
1894 $files = $item['file'];
1895 unset($item['file']);
1900 // Creates or assigns the permission set
1901 $item['psid'] = PermissionSet::getIdFromACL(
1909 $item['allow_cid'] = null;
1910 $item['allow_gid'] = null;
1911 $item['deny_cid'] = null;
1912 $item['deny_gid'] = null;
1914 // We are doing this outside of the transaction to avoid timing problems
1915 if (!self::insertActivity($item)) {
1916 self::insertContent($item);
1919 $delivery_data = ItemDeliveryData::extractFields($item);
1921 unset($item['postopts']);
1922 unset($item['inform']);
1924 // These fields aren't stored anymore in the item table, they are fetched upon request
1925 unset($item['author-link']);
1926 unset($item['author-name']);
1927 unset($item['author-avatar']);
1928 unset($item['author-network']);
1930 unset($item['owner-link']);
1931 unset($item['owner-name']);
1932 unset($item['owner-avatar']);
1934 $like_no_comment = DI::config()->get('system', 'like_no_comment');
1937 $ret = DBA::insert('item', $item);
1939 // When the item was successfully stored we fetch the ID of the item.
1940 if (DBA::isResult($ret)) {
1941 $current_post = DBA::lastInsertId();
1943 // This can happen - for example - if there are locking timeouts.
1946 // Store the data into a spool file so that we can try again later.
1947 self::spool($orig_item);
1951 if ($current_post == 0) {
1952 // This is one of these error messages that never should occur.
1953 Logger::log("couldn't find created item - we better quit now.");
1958 // How much entries have we created?
1959 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1960 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1963 // There are duplicates. We delete our just created entry.
1964 Logger::info('Delete duplicated item', ['id' => $current_post, 'uri' => $item['uri'], 'uid' => $item['uid'], 'guid' => $item['guid']]);
1966 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1967 DBA::delete('item', ['id' => $current_post]);
1970 } elseif ($entries == 0) {
1971 // This really should never happen since we quit earlier if there were problems.
1972 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1977 Logger::log('created item '.$current_post);
1979 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1980 $parent_id = $current_post;
1984 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1986 $item['id'] = $current_post;
1987 $item['parent'] = $parent_id;
1989 // update the commented timestamp on the parent
1990 // Only update "commented" if it is really a comment
1991 if (($item['gravity'] != GRAVITY_ACTIVITY) || !$like_no_comment) {
1992 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1994 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1999 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
2000 * We can check for this condition when we decode and encode the stuff again.
2002 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
2003 $dsprsig->signature = base64_decode($dsprsig->signature);
2004 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
2007 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
2008 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
2010 // The other fields are used by very old Friendica servers, so we currently store them differently
2011 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
2012 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
2016 if (!empty($diaspora_signed_text)) {
2017 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
2020 if ($item['parent-uri'] === $item['uri']) {
2021 self::addThread($current_post);
2023 self::updateThread($parent_id);
2026 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
2027 ItemDeliveryData::insert($current_post, $delivery_data);
2033 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
2034 * This is not perfect - but a workable solution until we found the reason for the problem.
2036 if (!empty($tags)) {
2037 Term::insertFromTagFieldByItemId($current_post, $tags);
2040 if (!empty($files)) {
2041 Term::insertFromFileFieldByItemId($current_post, $files);
2044 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
2045 if (self::tagDeliver($item['uid'], $current_post)) {
2046 // Get the user information for the logging
2047 $user = User::getById($uid);
2049 Logger::notice('Item had been deleted', ['id' => $current_post, 'user' => $uid, 'account-type' => $user['account-type']]);
2054 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
2055 if (DBA::isResult($posted_item)) {
2057 Hook::callAll('post_local_end', $posted_item);
2059 Hook::callAll('post_remote_end', $posted_item);
2062 Logger::log('new item not found in DB, id ' . $current_post);
2066 if ($item['parent-uri'] === $item['uri']) {
2067 self::addShadow($current_post);
2069 self::addShadowPost($current_post);
2072 self::updateContact($item);
2074 UserItem::setNotification($current_post);
2076 check_user_notification($current_post);
2078 if ($notify || ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin']))) {
2079 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
2082 return $current_post;
2086 * Insert a new item content entry
2088 * @param array $item The item fields that are to be inserted
2090 * @throws \Exception
2092 private static function insertActivity(&$item)
2094 $activity_index = self::activityToIndex($item['verb']);
2096 if ($activity_index < 0) {
2100 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2102 // We just remove everything that is content
2103 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2104 unset($item[$field]);
2107 // To avoid timing problems, we are using locks.
2108 $locked = DI::lock()->acquire('item_insert_activity');
2110 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2113 // Do we already have this content?
2114 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
2115 if (DBA::isResult($item_activity)) {
2116 $item['iaid'] = $item_activity['id'];
2117 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2118 } elseif (DBA::insert('item-activity', $fields)) {
2119 $item['iaid'] = DBA::lastInsertId();
2120 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
2122 // This shouldn't happen.
2123 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
2124 DI::lock()->release('item_insert_activity');
2128 DI::lock()->release('item_insert_activity');
2134 * Insert a new item content entry
2136 * @param array $item The item fields that are to be inserted
2137 * @throws \Exception
2139 private static function insertContent(&$item)
2141 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
2143 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2144 if (isset($item[$field])) {
2145 $fields[$field] = $item[$field];
2146 unset($item[$field]);
2150 // To avoid timing problems, we are using locks.
2151 $locked = DI::lock()->acquire('item_insert_content');
2153 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
2156 // Do we already have this content?
2157 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
2158 if (DBA::isResult($item_content)) {
2159 $item['icid'] = $item_content['id'];
2160 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2161 } elseif (DBA::insert('item-content', $fields)) {
2162 $item['icid'] = DBA::lastInsertId();
2163 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
2165 // This shouldn't happen.
2166 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
2169 DI::lock()->release('item_insert_content');
2174 * Update existing item content entries
2176 * @param array $item The item fields that are to be changed
2177 * @param array $condition The condition for finding the item content entries
2179 * @throws \Exception
2181 private static function updateActivity($item, $condition)
2183 if (empty($item['verb'])) {
2186 $activity_index = self::activityToIndex($item['verb']);
2188 if ($activity_index < 0) {
2192 $fields = ['activity' => $activity_index];
2194 Logger::log('Update activity for ' . json_encode($condition));
2196 DBA::update('item-activity', $fields, $condition, true);
2202 * Update existing item content entries
2204 * @param array $item The item fields that are to be changed
2205 * @param array $condition The condition for finding the item content entries
2206 * @throws \Exception
2208 private static function updateContent($item, $condition)
2210 // We have to select only the fields from the "item-content" table
2212 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
2213 if (isset($item[$field])) {
2214 $fields[$field] = $item[$field];
2218 if (empty($fields)) {
2219 // when there are no fields at all, just use the condition
2220 // This is to ensure that we always store content.
2221 $fields = $condition;
2224 Logger::log('Update content for ' . json_encode($condition));
2226 DBA::update('item-content', $fields, $condition, true);
2230 * Distributes public items to the receivers
2232 * @param integer $itemid Item ID that should be added
2233 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2234 * @throws \Exception
2236 public static function distribute($itemid, $signed_text = '')
2238 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2239 $parent = self::selectFirst(['owner-id'], $condition);
2240 if (!DBA::isResult($parent)) {
2244 // Only distribute public items from native networks
2245 $condition = ['id' => $itemid, 'uid' => 0,
2246 'network' => array_merge(Protocol::FEDERATED ,['']),
2247 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
2248 $item = self::selectFirst(self::ITEM_FIELDLIST, $condition);
2249 if (!DBA::isResult($item)) {
2253 $origin = $item['origin'];
2256 unset($item['parent']);
2257 unset($item['mention']);
2258 unset($item['wall']);
2259 unset($item['origin']);
2260 unset($item['starred']);
2264 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2265 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2266 if (!DBA::isResult($owner)) {
2270 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2271 $contacts = DBA::select('contact', ['uid'], $condition);
2272 while ($contact = DBA::fetch($contacts)) {
2273 if ($contact['uid'] == 0) {
2277 $users[$contact['uid']] = $contact['uid'];
2279 DBA::close($contacts);
2281 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2282 $contacts = DBA::select('contact', ['uid'], $condition);
2283 while ($contact = DBA::fetch($contacts)) {
2284 if ($contact['uid'] == 0) {
2288 $users[$contact['uid']] = $contact['uid'];
2290 DBA::close($contacts);
2292 if (!empty($owner['alias'])) {
2293 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2294 $contacts = DBA::select('contact', ['uid'], $condition);
2295 while ($contact = DBA::fetch($contacts)) {
2296 if ($contact['uid'] == 0) {
2300 $users[$contact['uid']] = $contact['uid'];
2302 DBA::close($contacts);
2307 if ($item['uri'] != $item['parent-uri']) {
2308 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2309 while ($parent = self::fetch($parents)) {
2310 $users[$parent['uid']] = $parent['uid'];
2311 if ($parent['origin'] && !$origin) {
2312 $origin_uid = $parent['uid'];
2317 foreach ($users as $uid) {
2318 if ($origin_uid == $uid) {
2319 $item['diaspora_signed_text'] = $signed_text;
2321 self::storeForUser($itemid, $item, $uid);
2326 * Store public items for the receivers
2328 * @param integer $itemid Item ID that should be added
2329 * @param array $item The item entry that will be stored
2330 * @param integer $uid The user that will receive the item entry
2331 * @throws \Exception
2333 private static function storeForUser($itemid, $item, $uid)
2335 $item['uid'] = $uid;
2336 $item['origin'] = 0;
2338 if ($item['uri'] == $item['parent-uri']) {
2339 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2341 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2344 if (empty($item['contact-id'])) {
2345 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2346 if (!DBA::isResult($self)) {
2349 $item['contact-id'] = $self['id'];
2352 /// @todo Handling of "event-id"
2355 if ($item['uri'] == $item['parent-uri']) {
2356 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2357 if (DBA::isResult($contact)) {
2358 $notify = self::isRemoteSelf($contact, $item);
2362 $distributed = self::insert($item, false, $notify, true);
2364 if (!$distributed) {
2365 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2367 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2372 * Add a shadow entry for a given item id that is a thread starter
2374 * We store every public item entry additionally with the user id "0".
2375 * This is used for the community page and for the search.
2376 * It is planned that in the future we will store public item entries only once.
2378 * @param integer $itemid Item ID that should be added
2379 * @throws \Exception
2381 public static function addShadow($itemid)
2383 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2384 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2385 $item = self::selectFirst($fields, $condition);
2387 if (!DBA::isResult($item)) {
2391 // is it already a copy?
2392 if (($itemid == 0) || ($item['uid'] == 0)) {
2396 // Is it a visible public post?
2397 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || ($item["private"] == Item::PRIVATE)) {
2401 // is it an entry from a connector? Only add an entry for natively connected networks
2402 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
2406 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2410 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2412 if (DBA::isResult($item)) {
2413 // Preparing public shadow (removing user specific data)
2416 unset($item['parent']);
2417 unset($item['wall']);
2418 unset($item['mention']);
2419 unset($item['origin']);
2420 unset($item['starred']);
2421 unset($item['postopts']);
2422 unset($item['inform']);
2423 if ($item['uri'] == $item['parent-uri']) {
2424 $item['contact-id'] = $item['owner-id'];
2426 $item['contact-id'] = $item['author-id'];
2429 $public_shadow = self::insert($item, false, false, true);
2431 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2436 * Add a shadow entry for a given item id that is a comment
2438 * This function does the same like the function above - but for comments
2440 * @param integer $itemid Item ID that should be added
2441 * @throws \Exception
2443 public static function addShadowPost($itemid)
2445 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2446 if (!DBA::isResult($item)) {
2450 // Is it a toplevel post?
2451 if ($item['id'] == $item['parent']) {
2452 self::addShadow($itemid);
2456 // Is this a shadow entry?
2457 if ($item['uid'] == 0) {
2461 // Is there a shadow parent?
2462 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2466 // Is there already a shadow entry?
2467 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2471 // Save "origin" and "parent" state
2472 $origin = $item['origin'];
2473 $parent = $item['parent'];
2475 // Preparing public shadow (removing user specific data)
2478 unset($item['parent']);
2479 unset($item['wall']);
2480 unset($item['mention']);
2481 unset($item['origin']);
2482 unset($item['starred']);
2483 unset($item['postopts']);
2484 unset($item['inform']);
2485 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2487 $public_shadow = self::insert($item, false, false, true);
2489 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2491 // If this was a comment to a Diaspora post we don't get our comment back.
2492 // This means that we have to distribute the comment by ourselves.
2493 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2494 self::distribute($public_shadow);
2499 * Adds a language specification in a "language" element of given $arr.
2500 * Expects "body" element to exist in $arr.
2503 * @throws \Text_LanguageDetect_Exception
2505 private static function addLanguageToItemArray(&$item)
2507 $naked_body = BBCode::toPlaintext($item['body'], false);
2509 $ld = new Text_LanguageDetect();
2510 $ld->setNameMode(2);
2511 $languages = $ld->detect($naked_body, 3);
2513 if (is_array($languages)) {
2514 $item['language'] = json_encode($languages);
2519 * Creates an unique guid out of a given uri
2521 * @param string $uri uri of an item entry
2522 * @param string $host hostname for the GUID prefix
2523 * @return string unique guid
2525 public static function guidFromUri($uri, $host)
2527 // Our regular guid routine is using this kind of prefix as well
2528 // We have to avoid that different routines could accidentally create the same value
2529 $parsed = parse_url($uri);
2531 // We use a hash of the hostname as prefix for the guid
2532 $guid_prefix = hash("crc32", $host);
2534 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2535 unset($parsed["scheme"]);
2537 // Glue it together to be able to make a hash from it
2538 $host_id = implode("/", $parsed);
2540 // We could use any hash algorithm since it isn't a security issue
2541 $host_hash = hash("ripemd128", $host_id);
2543 return $guid_prefix.$host_hash;
2547 * generate an unique URI
2549 * @param integer $uid User id
2550 * @param string $guid An existing GUID (Otherwise it will be generated)
2553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2555 public static function newURI($uid, $guid = "")
2558 $guid = System::createUUID();
2561 return DI::baseUrl()->get() . '/objects/' . $guid;
2565 * Set "success_update" and "last-item" to the date of the last time we heard from this contact
2567 * This can be used to filter for inactive contacts.
2568 * Only do this for public postings to avoid privacy problems, since poco data is public.
2569 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2571 * @param array $arr Contains the just posted item record
2572 * @throws \Exception
2574 private static function updateContact($arr)
2576 // Unarchive the author
2577 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2578 if (DBA::isResult($contact)) {
2579 Contact::unmarkForArchival($contact);
2582 // Unarchive the contact if it's not our own contact
2583 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2584 if (DBA::isResult($contact)) {
2585 Contact::unmarkForArchival($contact);
2588 $update = (($arr['private'] != self::PRIVATE) && ((($arr['author-link'] ?? '') === ($arr['owner-link'] ?? '')) || ($arr["parent-uri"] === $arr["uri"])));
2590 // Is it a forum? Then we don't care about the rules from above
2591 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2592 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2598 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2599 ['id' => $arr['contact-id']]);
2601 // Now do the same for the system wide contacts with uid=0
2602 if ($arr['private'] != self::PRIVATE) {
2603 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2604 ['id' => $arr['owner-id']]);
2606 if ($arr['owner-id'] != $arr['author-id']) {
2607 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2608 ['id' => $arr['author-id']]);
2613 public static function setHashtags(&$item)
2615 $tags = BBCode::getTags($item["body"]);
2618 if (!count($tags)) {
2622 // What happens in [code], stays in [code]!
2623 // escape the # and the [
2624 // hint: we will also get in trouble with #tags, when we want markdown in posts -> ### Headline 3
2625 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2627 // we truly ESCape all # and [ to prevent gettin weird tags in [code] blocks
2629 $replace = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2630 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2633 // This sorting is important when there are hashtags that are part of other hashtags
2634 // Otherwise there could be problems with hashtags like #test and #test2
2637 $URLSearchString = "^\[\]";
2639 // All hashtags should point to the home server if "local_tags" is activated
2640 if (DI::config()->get('system', 'local_tags')) {
2641 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2642 "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2644 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2645 "#[url=".DI::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2648 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2649 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2651 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2654 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2656 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2659 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2661 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2664 // Repair recursive urls
2665 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2666 "#$2", $item["body"]);
2668 foreach ($tags as $tag) {
2669 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2673 $basetag = str_replace('_',' ',substr($tag,1));
2674 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2676 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2678 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2679 if (strlen($item["tag"])) {
2680 $item["tag"] = ',' . $item["tag"];
2682 $item["tag"] = $newtag . $item["tag"];
2686 // Convert back the masked hashtags
2687 $item["body"] = str_replace("#", "#", $item["body"]);
2689 // Remember! What happens in [code], stays in [code]
2690 // roleback the # and [
2691 $item["body"] = preg_replace_callback("/\[code(.*?)\](.*?)\[\/code\]/ism",
2693 // we truly unESCape all sharp and leftsquarebracket
2694 $find = [chr(27).'sharp', chr(27).'leftsquarebracket'];
2695 $replace = ['#', '['];
2696 return ("[code" . $match[1] . "]" . str_replace($find, $replace, $match[2]) . "[/code]");
2701 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2704 * @param int $item_id
2705 * @return boolean true if item was deleted, else false
2706 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2707 * @throws \ImagickException
2709 private static function tagDeliver($uid, $item_id)
2713 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2714 if (!DBA::isResult($user)) {
2718 $community_page = (($user['page-flags'] == User::PAGE_FLAGS_COMMUNITY) ? true : false);
2719 $prvgroup = (($user['page-flags'] == User::PAGE_FLAGS_PRVGROUP) ? true : false);
2721 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2722 if (!DBA::isResult($item)) {
2726 $link = Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']);
2729 * Diaspora uses their own hardwired link URL in @-tags
2730 * instead of the one we supply with webfinger
2732 $dlink = Strings::normaliseLink(DI::baseUrl() . '/u/' . $user['nickname']);
2734 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2736 foreach ($matches as $mtch) {
2737 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2739 Logger::log('mention found: ' . $mtch[2]);
2745 if (($community_page || $prvgroup) &&
2746 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2747 Logger::info('Delete private group/communiy top-level item without mention', ['id' => $item_id, 'guid'=> $item['guid']]);
2748 DBA::delete('item', ['id' => $item_id]);
2754 $arr = ['item' => $item, 'user' => $user];
2756 Hook::callAll('tagged', $arr);
2758 if (!$community_page && !$prvgroup) {
2763 * tgroup delivery - setup a second delivery chain
2764 * prevent delivery looping - only proceed
2765 * if the message originated elsewhere and is a top-level post
2767 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2771 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2772 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2773 if (!DBA::isResult($self)) {
2777 $owner_id = Contact::getIdForURL($self['url']);
2779 // also reset all the privacy bits to the forum default permissions
2781 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? self::PRIVATE : self::PUBLIC;
2783 $psid = PermissionSet::getIdFromACL(
2791 $forum_mode = ($prvgroup ? 2 : 1);
2793 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2794 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2795 self::update($fields, ['id' => $item_id]);
2797 self::updateThread($item_id);
2799 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', Delivery::POST, $item_id);
2804 public static function isRemoteSelf($contact, &$datarray)
2806 if (!$contact['remote_self']) {
2810 // Prevent the forwarding of posts that are forwarded
2811 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2812 Logger::log('Already forwarded', Logger::DEBUG);
2816 // Prevent to forward already forwarded posts
2817 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2818 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2822 // Only forward posts
2823 if ($datarray["verb"] != Activity::POST) {
2824 Logger::log('No post', Logger::DEBUG);
2828 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2829 Logger::log('Not public', Logger::DEBUG);
2833 $datarray2 = $datarray;
2834 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2835 if ($contact['remote_self'] == 2) {
2836 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2837 ['uid' => $contact['uid'], 'self' => true]);
2838 if (DBA::isResult($self)) {
2839 $datarray['contact-id'] = $self["id"];
2841 $datarray['owner-name'] = $self["name"];
2842 $datarray['owner-link'] = $self["url"];
2843 $datarray['owner-avatar'] = $self["thumb"];
2845 $datarray['author-name'] = $datarray['owner-name'];
2846 $datarray['author-link'] = $datarray['owner-link'];
2847 $datarray['author-avatar'] = $datarray['owner-avatar'];
2849 unset($datarray['edited']);
2851 unset($datarray['network']);
2852 unset($datarray['owner-id']);
2853 unset($datarray['author-id']);
2856 if ($contact['network'] != Protocol::FEED) {
2857 $datarray["guid"] = System::createUUID();
2858 unset($datarray["plink"]);
2859 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2860 $datarray["parent-uri"] = $datarray["uri"];
2861 $datarray["thr-parent"] = $datarray["uri"];
2862 $datarray["extid"] = Protocol::DFRN;
2863 $urlpart = parse_url($datarray2['author-link']);
2864 $datarray["app"] = $urlpart["host"];
2866 $datarray['private'] = self::PUBLIC;
2870 if ($contact['network'] != Protocol::FEED) {
2871 // Store the original post
2872 $result = self::insert($datarray2, false, false);
2873 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2875 $datarray["app"] = "Feed";
2879 // Trigger automatic reactions for addons
2880 $datarray['api_source'] = true;
2882 // We have to tell the hooks who we are - this really should be improved
2883 $_SESSION["authenticated"] = true;
2884 $_SESSION["uid"] = $contact['uid'];
2893 * @param array $item
2896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2897 * @throws \ImagickException
2899 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2901 if (DI::config()->get('system', 'disable_embedded')) {
2905 Logger::log('check for photos', Logger::DEBUG);
2906 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2911 $img_start = strpos($orig_body, '[img');
2912 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2913 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2915 while (($img_st_close !== false) && ($img_len !== false)) {
2916 $img_st_close++; // make it point to AFTER the closing bracket
2917 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2919 Logger::log('found photo ' . $image, Logger::DEBUG);
2921 if (stristr($image, $site . '/photo/')) {
2922 // Only embed locally hosted photos
2924 $i = basename($image);
2925 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2926 $x = strpos($i, '-');
2929 $res = substr($i, $x + 1);
2930 $i = substr($i, 0, $x);
2931 $photo = Photo::getPhotoForUser($uid, $i, $res);
2932 if (DBA::isResult($photo)) {
2934 * Check to see if we should replace this photo link with an embedded image
2935 * 1. No need to do so if the photo is public
2936 * 2. If there's a contact-id provided, see if they're in the access list
2937 * for the photo. If so, embed it.
2938 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2939 * permissions, regardless of order but first check to see if they're an exact
2940 * match to save some processing overhead.
2942 if (self::hasPermissions($photo)) {
2944 $recips = self::enumeratePermissions($photo);
2945 if (in_array($cid, $recips)) {
2949 if (self::samePermissions($uid, $item, $photo)) {
2955 $photo_img = Photo::getImageForPhoto($photo);
2956 // If a custom width and height were specified, apply before embedding
2957 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2958 Logger::log('scaling photo', Logger::DEBUG);
2960 $width = intval($match[1]);
2961 $height = intval($match[2]);
2963 $photo_img->scaleDown(max($width, $height));
2966 $data = $photo_img->asString();
2967 $type = $photo_img->getType();
2969 Logger::log('replacing photo', Logger::DEBUG);
2970 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2971 Logger::log('replaced: ' . $image, Logger::DATA);
2977 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2978 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2979 if ($orig_body === false) {
2983 $img_start = strpos($orig_body, '[img');
2984 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2985 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2988 $new_body = $new_body . $orig_body;
2993 private static function hasPermissions($obj)
2995 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2996 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2999 private static function samePermissions($uid, $obj1, $obj2)
3001 // first part is easy. Check that these are exactly the same.
3002 if (($obj1['allow_cid'] == $obj2['allow_cid'])
3003 && ($obj1['allow_gid'] == $obj2['allow_gid'])
3004 && ($obj1['deny_cid'] == $obj2['deny_cid'])
3005 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
3009 // This is harder. Parse all the permissions and compare the resulting set.
3010 $recipients1 = self::enumeratePermissions($obj1);
3011 $recipients2 = self::enumeratePermissions($obj2);
3015 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
3016 return ($recipients1 == $recipients2);
3020 * Returns an array of contact-ids that are allowed to see this object
3022 * @param array $obj Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
3023 * @param bool $check_dead Prunes unavailable contacts from the result
3025 * @throws \Exception
3027 public static function enumeratePermissions(array $obj, bool $check_dead = false)
3029 $aclFormater = DI::aclFormatter();
3031 $allow_people = $aclFormater->expand($obj['allow_cid']);
3032 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
3033 $deny_people = $aclFormater->expand($obj['deny_cid']);
3034 $deny_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
3035 $recipients = array_unique(array_merge($allow_people, $allow_groups));
3036 $deny = array_unique(array_merge($deny_people, $deny_groups));
3037 $recipients = array_diff($recipients, $deny);
3041 public static function getFeedTags($item)
3045 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
3047 for ($x = 0; $x < $cnt; $x ++) {
3048 if ($matches[1][$x]) {
3049 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
3054 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
3056 for ($x = 0; $x < $cnt; $x ++) {
3057 if ($matches[1][$x]) {
3058 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
3065 public static function expire($uid, $days, $network = "", $force = false)
3067 if (!$uid || ($days < 1)) {
3071 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
3072 $uid, GRAVITY_PARENT];
3075 * $expire_network_only = save your own wall posts
3076 * and just expire conversations started by others
3078 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
3080 if ($expire_network_only) {
3081 $condition[0] .= " AND NOT `wall`";
3084 if ($network != "") {
3085 $condition[0] .= " AND `network` = ?";
3086 $condition[] = $network;
3089 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
3090 $condition[] = $days;
3092 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
3094 if (!DBA::isResult($items)) {
3098 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
3100 // Forcing expiring of items - but not notes and marked items
3102 $expire_items = true;
3105 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
3106 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
3107 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
3111 while ($item = Item::fetch($items)) {
3112 // don't expire filed items
3114 if (strpos($item['file'], '[') !== false) {
3118 // Only expire posts, not photos and photo comments
3120 if (!$expire_photos && strlen($item['resource-id'])) {
3122 } elseif (!$expire_starred && intval($item['starred'])) {
3124 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
3126 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
3130 self::markForDeletionById($item['id'], PRIORITY_LOW);
3135 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
3138 public static function firstPostDate($uid, $wall = false)
3140 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
3141 $params = ['order' => ['received' => false]];
3142 $thread = DBA::selectFirst('thread', ['received'], $condition, $params);
3143 if (DBA::isResult($thread)) {
3144 return substr(DateTimeFormat::local($thread['received']), 0, 10);
3150 * add/remove activity to an item
3152 * Toggle activities as like,dislike,attend of an item
3154 * @param string $item_id
3155 * @param string $verb
3156 * Activity verb. One of
3157 * like, unlike, dislike, undislike, attendyes, unattendyes,
3158 * attendno, unattendno, attendmaybe, unattendmaybe
3160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3161 * @throws \ImagickException
3162 * @hook 'post_local_end'
3164 * 'post_id' => ID of posted item
3166 public static function performActivity($item_id, $verb)
3168 if (!Session::isAuthenticated()) {
3175 $activity = Activity::LIKE;
3179 $activity = Activity::DISLIKE;
3183 $activity = Activity::ATTEND;
3187 $activity = Activity::ATTENDNO;
3190 case 'unattendmaybe':
3191 $activity = Activity::ATTENDMAYBE;
3195 $activity = Activity::FOLLOW;
3198 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3202 // Enable activity toggling instead of on/off
3203 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
3205 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3207 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3208 if (!DBA::isResult($item)) {
3209 Logger::log('like: unknown item ' . $item_id);
3213 $item_uri = $item['uri'];
3215 $uid = $item['uid'];
3216 if (($uid == 0) && local_user()) {
3217 $uid = local_user();
3220 if (!Security::canWriteToUserWall($uid)) {
3221 Logger::log('like: unable to write on wall ' . $uid);
3225 // Retrieves the local post owner
3226 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3227 if (!DBA::isResult($owner_self_contact)) {
3228 Logger::log('like: unknown owner ' . $uid);
3232 // Retrieve the current logged in user's public contact
3233 $author_id = public_contact();
3235 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3236 if (!DBA::isResult($author_contact)) {
3237 Logger::log('like: unknown author ' . $author_id);
3241 // Contact-id is the uid-dependant author contact
3242 if (local_user() == $uid) {
3243 $item_contact_id = $owner_self_contact['id'];
3245 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3246 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3247 if (!DBA::isResult($item_contact)) {
3248 Logger::log('like: unknown item contact ' . $item_contact_id);
3253 // Look for an existing verb row
3254 // event participation are essentially radio toggles. If you make a subsequent choice,
3255 // we need to eradicate your first choice.
3256 if ($event_verb_flag) {
3257 $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
3259 // Translate to the index based activity index
3261 foreach ($verbs as $verb) {
3262 $activities[] = self::activityToIndex($verb);
3265 $activities = self::activityToIndex($activity);
3268 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3269 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3271 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3273 // If it exists, mark it as deleted
3274 if (DBA::isResult($like_item)) {
3275 self::markForDeletionById($like_item['id']);
3277 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3282 // Verb is "un-something", just trying to delete existing entries
3283 if (strpos($verb, 'un') === 0) {
3287 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
3290 'guid' => System::createUUID(),
3291 'uri' => self::newURI($item['uid']),
3292 'uid' => $item['uid'],
3293 'contact-id' => $item_contact_id,
3294 'wall' => $item['wall'],
3296 'network' => Protocol::DFRN,
3297 'gravity' => GRAVITY_ACTIVITY,
3298 'parent' => $item['id'],
3299 'parent-uri' => $item['uri'],
3300 'thr-parent' => $item['uri'],
3301 'owner-id' => $author_id,
3302 'author-id' => $author_id,
3303 'body' => $activity,
3304 'verb' => $activity,
3305 'object-type' => $objtype,
3306 'allow_cid' => $item['allow_cid'],
3307 'allow_gid' => $item['allow_gid'],
3308 'deny_cid' => $item['deny_cid'],
3309 'deny_gid' => $item['deny_gid'],
3314 $signed = Diaspora::createLikeSignature($uid, $new_item);
3315 if (!empty($signed)) {
3316 $new_item['diaspora_signed_text'] = json_encode($signed);
3319 $new_item_id = self::insert($new_item);
3321 // If the parent item isn't visible then set it to visible
3322 if (!$item['visible']) {
3323 self::update(['visible' => true], ['id' => $item['id']]);
3326 $new_item['id'] = $new_item_id;
3328 Hook::callAll('post_local_end', $new_item);
3333 private static function addThread($itemid, $onlyshadow = false)
3335 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3336 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3337 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3338 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3339 $item = self::selectFirst($fields, $condition);
3341 if (!DBA::isResult($item)) {
3345 $item['iid'] = $itemid;
3348 $result = DBA::insert('thread', $item);
3350 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3354 private static function updateThread($itemid, $setmention = false)
3356 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3357 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3358 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3359 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3361 $item = self::selectFirst($fields, $condition);
3362 if (!DBA::isResult($item)) {
3367 $item["mention"] = 1;
3372 foreach ($item as $field => $data) {
3373 if (!in_array($field, ["guid"])) {
3374 $fields[$field] = $data;
3378 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3380 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3383 private static function deleteThread($itemid, $itemuri = "")
3385 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3386 if (!DBA::isResult($item)) {
3387 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3391 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3393 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3395 if ($itemuri != "") {
3396 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3397 if (!self::exists($condition)) {
3398 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3399 Logger::debug('Deleted shadow item', ['id' => $itemid, 'uri' => $itemuri]);
3404 public static function getPermissionsSQLByUserId($owner_id)
3406 $local_user = local_user();
3407 $remote_user = Session::getRemoteContactID($owner_id);
3410 * Construct permissions
3412 * default permissions - anonymous user
3414 $sql = sprintf(" AND `item`.`private` != %d", self::PRIVATE);
3416 // Profile owner - everything is visible
3417 if ($local_user && ($local_user == $owner_id)) {
3419 } elseif ($remote_user) {
3421 * Authenticated visitor. Unless pre-verified,
3422 * check that the contact belongs to this $owner_id
3423 * and load the groups the visitor belongs to.
3424 * If pre-verified, the caller is expected to have already
3425 * done this and passed the groups into this function.
3427 $set = PermissionSet::get($owner_id, $remote_user);
3430 $sql_set = sprintf(" OR (`item`.`private` = %d AND `item`.`wall` AND `item`.`psid` IN (", self::PRIVATE) . implode(',', $set) . "))";
3435 $sql = sprintf(" AND (`item`.`private` != %d", self::PRIVATE) . $sql_set . ")";
3442 * get translated item type
3447 public static function postType($item)
3449 if (!empty($item['event-id'])) {
3450 return DI::l10n()->t('event');
3451 } elseif (!empty($item['resource-id'])) {
3452 return DI::l10n()->t('photo');
3453 } elseif (!empty($item['verb']) && $item['verb'] !== Activity::POST) {
3454 return DI::l10n()->t('activity');
3455 } elseif ($item['id'] != $item['parent']) {
3456 return DI::l10n()->t('comment');
3459 return DI::l10n()->t('post');
3463 * Sets the "rendered-html" field of the provided item
3465 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3467 * @param array $item
3468 * @param bool $update
3470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3471 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3473 public static function putInCache(&$item, $update = false)
3475 $body = $item["body"];
3477 $rendered_hash = $item['rendered-hash'] ?? '';
3478 $rendered_html = $item['rendered-html'] ?? '';
3480 if ($rendered_hash == ''
3481 || $rendered_html == ""
3482 || $rendered_hash != hash("md5", $item["body"])
3483 || DI::config()->get("system", "ignore_cache")
3485 self::addRedirToImageTags($item);
3487 $item["rendered-html"] = BBCode::convert($item["body"]);
3488 $item["rendered-hash"] = hash("md5", $item["body"]);
3490 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3491 Hook::callAll('put_item_in_cache', $hook_data);
3492 $item['rendered-html'] = $hook_data['rendered-html'];
3493 $item['rendered-hash'] = $hook_data['rendered-hash'];
3496 // Force an update if the generated values differ from the existing ones
3497 if ($rendered_hash != $item["rendered-hash"]) {
3501 // Only compare the HTML when we forcefully ignore the cache
3502 if (DI::config()->get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3506 if ($update && !empty($item["id"])) {
3509 'rendered-html' => $item["rendered-html"],
3510 'rendered-hash' => $item["rendered-hash"]
3512 ['id' => $item["id"]]
3517 $item["body"] = $body;
3521 * Find any non-embedded images in private items and add redir links to them
3523 * @param array &$item The field array of an item row
3525 private static function addRedirToImageTags(array &$item)
3530 $cnt = preg_match_all('|\[img\](http[^\[]*?/photo/[a-fA-F0-9]+?(-[0-9]\.[\w]+?)?)\[\/img\]|', $item['body'], $matches, PREG_SET_ORDER);
3532 foreach ($matches as $mtch) {
3533 if (strpos($mtch[1], '/redir') !== false) {
3537 if ((local_user() == $item['uid']) && ($item['private'] == self::PRIVATE) && ($item['contact-id'] != $app->contact['id']) && ($item['network'] == Protocol::DFRN)) {
3538 $img_url = 'redir/' . $item['contact-id'] . '?url=' . urlencode($mtch[1]);
3539 $item['body'] = str_replace($mtch[0], '[img]' . $img_url . '[/img]', $item['body']);
3546 * Given an item array, convert the body element from bbcode to html and add smilie icons.
3547 * If attach is true, also add icons for item attachments.
3549 * @param array $item
3550 * @param boolean $attach
3551 * @param boolean $is_preview
3552 * @return string item body html
3553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3554 * @throws \ImagickException
3555 * @hook prepare_body_init item array before any work
3556 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3557 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3558 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3560 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3563 Hook::callAll('prepare_body_init', $item);
3565 // In order to provide theme developers more possibilities, event items
3566 // are treated differently.
3567 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
3568 $ev = Event::getItemHTML($item);
3572 $tags = Term::populateTagsFromItem($item);
3574 $item['tags'] = $tags['tags'];
3575 $item['hashtags'] = $tags['hashtags'];
3576 $item['mentions'] = $tags['mentions'];
3578 // Compile eventual content filter reasons
3579 $filter_reasons = [];
3580 if (!$is_preview && public_contact() != $item['author-id']) {
3581 if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
3582 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
3587 'filter_reasons' => $filter_reasons
3589 Hook::callAll('prepare_body_content_filter', $hook_data);
3590 $filter_reasons = $hook_data['filter_reasons'];
3594 // Update the cached values if there is no "zrl=..." on the links.
3595 $update = (!Session::isAuthenticated() && ($item["uid"] == 0));
3597 // Or update it if the current viewer is the intented viewer.
3598 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3602 self::putInCache($item, $update);
3603 $s = $item["rendered-html"];
3608 'preview' => $is_preview,
3609 'filter_reasons' => $filter_reasons
3611 Hook::callAll('prepare_body', $hook_data);
3612 $s = $hook_data['html'];
3616 // Replace the blockquotes with quotes that are used in mails.
3617 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3618 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3625 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3626 foreach ($matches as $mtch) {
3629 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3631 if (strpos($mime, 'video') !== false) {
3634 DI::page()['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'));
3637 $url_parts = explode('/', $the_url);
3638 $id = end($url_parts);
3639 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3642 'title' => DI::l10n()->t('View Video'),
3649 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3651 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3652 $filesubtype = str_replace('.', '-', $filesubtype);
3655 $filesubtype = 'unkn';
3658 $title = Strings::escapeHtml(trim(($mtch[4] ?? '') ?: $mtch[1]));
3659 $title .= ' ' . $mtch[2] . ' ' . DI::l10n()->t('bytes');
3661 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3662 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3666 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3670 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3671 $x = Map::byCoordinates(trim($item['coord']));
3673 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3677 // Replace friendica image url size with theme preference.
3678 if (!empty($a->theme_info['item_image_size'])) {
3679 $ps = $a->theme_info['item_image_size'];
3680 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3683 $s = HTML::applyContentFilter($s, $filter_reasons);
3685 $hook_data = ['item' => $item, 'html' => $s];
3686 Hook::callAll('prepare_body_final', $hook_data);
3688 return $hook_data['html'];
3692 * get private link for item
3694 * @param array $item
3695 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3696 * @throws \Exception
3698 public static function getPlink($item)
3702 if ($a->user['nickname'] != "") {
3704 'href' => "display/" . $item['guid'],
3705 'orig' => "display/" . $item['guid'],
3706 'title' => DI::l10n()->t('View on separate page'),
3707 'orig_title' => DI::l10n()->t('view on separate page'),
3710 if (!empty($item['plink'])) {
3711 $ret["href"] = DI::baseUrl()->remove($item['plink']);
3712 $ret["title"] = DI::l10n()->t('link to source');
3715 } elseif (!empty($item['plink']) && ($item['private'] != self::PRIVATE)) {
3717 'href' => $item['plink'],
3718 'orig' => $item['plink'],
3719 'title' => DI::l10n()->t('link to source'),
3729 * Is the given item array a post that is sent as starting post to a forum?
3731 * @param array $item
3732 * @param array $owner
3734 * @return boolean "true" when it is a forum post
3736 public static function isForumPost(array $item, array $owner = [])
3738 if (empty($owner)) {
3739 $owner = User::getOwnerDataById($item['uid']);
3740 if (empty($owner)) {
3745 if (($item['author-id'] == $item['owner-id']) ||
3746 ($owner['id'] == $item['contact-id']) ||
3747 ($item['uri'] != $item['parent-uri']) ||
3752 return Contact::isForum($item['contact-id']);
3756 * Search item id for given URI or plink
3758 * @param string $uri
3759 * @param integer $uid
3761 * @return integer item id
3763 public static function searchByLink($uri, $uid = 0)
3765 $ssl_uri = str_replace('http://', 'https://', $uri);
3766 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3768 $item = DBA::selectFirst('item', ['id'], ['uri' => $uris, 'uid' => $uid]);
3769 if (DBA::isResult($item)) {
3773 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3774 if (!DBA::isResult($itemcontent)) {
3778 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3779 if (!DBA::isResult($itemuri)) {
3783 $item = DBA::selectFirst('item', ['id'], ['uri' => $itemuri['uri'], 'uid' => $uid]);
3784 if (DBA::isResult($item)) {
3792 * Return the URI for a link to the post
3794 * @param string $uri URI or link to post
3796 * @return string URI
3798 public static function getURIByLink(string $uri)
3800 $ssl_uri = str_replace('http://', 'https://', $uri);
3801 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3803 $item = DBA::selectFirst('item', ['uri'], ['uri' => $uris]);
3804 if (DBA::isResult($item)) {
3805 return $item['uri'];
3808 $itemcontent = DBA::selectFirst('item-content', ['uri-id'], ['plink' => $uris]);
3809 if (!DBA::isResult($itemcontent)) {
3813 $itemuri = DBA::selectFirst('item-uri', ['uri'], ['id' => $itemcontent['uri-id']]);
3814 if (DBA::isResult($itemuri)) {
3815 return $itemuri['uri'];
3822 * Fetches item for given URI or plink
3824 * @param string $uri
3825 * @param integer $uid
3827 * @return integer item id
3829 public static function fetchByLink($uri, $uid = 0)
3831 $item_id = self::searchByLink($uri, $uid);
3832 if (!empty($item_id)) {
3836 if ($fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri)) {
3837 $item_id = self::searchByLink($fetched_uri, $uid);
3839 $item_id = Diaspora::fetchByURL($uri);
3842 if (!empty($item_id)) {
3850 * Return share data from an item array (if the item is shared item)
3851 * We are providing the complete Item array, because at some time in the future
3852 * we hopefully will define these values not in the body anymore but in some item fields.
3853 * This function is meant to replace all similar functions in the system.
3855 * @param array $item
3857 * @return array with share information
3859 public static function getShareArray($item)
3861 if (!preg_match("/(.*?)\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", $item['body'], $matches)) {
3865 $attribute_string = $matches[2];
3866 $attributes = ['comment' => trim($matches[1]), 'shared' => trim($matches[3])];
3867 foreach (['author', 'profile', 'avatar', 'guid', 'posted', 'link'] as $field) {
3868 if (preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches)) {
3869 $attributes[$field] = trim(html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'));
3876 * Fetch item information for shared items from the original items and adds it.
3878 * @param array $item
3880 * @return array item array with data from the original item
3882 public static function addShareDataFromOriginal($item)
3884 $shared = self::getShareArray($item);
3885 if (empty($shared)) {
3889 // Real reshares always have got a GUID.
3890 if (empty($shared['guid'])) {
3894 $uid = $item['uid'] ?? 0;
3896 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3897 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3898 if (!DBA::isResult($shared_item)) {
3899 if (empty($shared['link'])) {
3903 // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3904 $id = self::fetchByLink($shared['link'], $uid);
3906 Logger::info('Original item not found', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3910 $shared_item = self::selectFirst(['title', 'body', 'attach'], ['id' => $id]);
3911 if (!DBA::isResult($shared_item)) {
3914 Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3916 Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3919 if (!empty($shared_item['title'])) {
3920 $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3921 unset($shared_item['title']);
3923 $body = $shared_item['body'];
3926 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . $body . '[/share]', $item['body']);
3927 unset($shared_item['body']);
3929 return array_merge($item, $shared_item);