4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Lock;
15 use Friendica\Core\Logger;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Protocol;
19 use Friendica\Core\Renderer;
20 use Friendica\Core\System;
21 use Friendica\Core\Worker;
22 use Friendica\Database\DBA;
23 use Friendica\Model\Contact;
24 use Friendica\Model\Event;
25 use Friendica\Model\FileTag;
26 use Friendica\Model\PermissionSet;
27 use Friendica\Model\Term;
28 use Friendica\Model\ItemURI;
29 use Friendica\Model\Photo;
30 use Friendica\Model\Attach;
31 use Friendica\Object\Image;
32 use Friendica\Protocol\Diaspora;
33 use Friendica\Protocol\OStatus;
34 use Friendica\Util\DateTimeFormat;
35 use Friendica\Util\Map;
36 use Friendica\Util\XML;
37 use Friendica\Util\Security;
38 use Friendica\Util\Strings;
39 use Text_LanguageDetect;
41 class Item extends BaseObject
43 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
50 const PT_DOCUMENT = 19;
52 const PT_PERSONAL_NOTE = 128;
54 // Field list that is used to display the items
55 const DISPLAY_FIELDLIST = [
56 'uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
57 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
58 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
59 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
60 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
61 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
62 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
63 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
64 'writable', 'self', 'cid', 'alias',
65 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
66 'event-summary', 'event-desc', 'event-location', 'event-type',
67 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id',
68 'delivery_queue_count', 'delivery_queue_done'
71 // Field list that is used to deliver items via the protocols
72 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
73 'created', 'edited', 'verb', 'object-type', 'object', 'target',
74 'private', 'title', 'body', 'location', 'coord', 'app',
75 'attach', 'tag', 'deleted', 'extid', 'post-type',
76 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
77 'author-id', 'author-link', 'owner-link', 'contact-uid',
78 'signed_text', 'signature', 'signer', 'network'];
80 // Field list for "item-content" table that is mixed with the item table
81 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
82 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
83 'object-type', 'object', 'target-type', 'target', 'plink'];
85 // Field list for "item-content" table that is not present in the "item" table
86 const CONTENT_FIELDLIST = ['language'];
88 // All fields in the item table
89 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
90 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
91 'created', 'edited', 'commented', 'received', 'changed', 'verb',
92 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
93 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
94 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
95 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
96 'title', 'content-warning', 'body', 'location', 'coord', 'app',
97 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
98 'author-id', 'author-link', 'author-name', 'author-avatar',
99 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
101 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
102 // The item-activity table only stores the index and needs this array to know the matching activity.
103 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
105 private static $legacy_mode = null;
107 public static function isLegacyMode()
109 if (is_null(self::$legacy_mode)) {
110 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
113 return self::$legacy_mode;
117 * @brief returns an activity index from an activity string
119 * @param string $activity activity string
120 * @return integer Activity index
122 public static function activityToIndex($activity)
124 $index = array_search($activity, self::ACTIVITIES);
126 if (is_bool($index)) {
134 * @brief returns an activity string from an activity index
136 * @param integer $index activity index
137 * @return string Activity string
139 private static function indexToActivity($index)
141 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
145 return self::ACTIVITIES[$index];
149 * @brief Fetch a single item row
151 * @param mixed $stmt statement object
152 * @return array current row
154 public static function fetch($stmt)
156 $row = DBA::fetch($stmt);
162 // ---------------------- Transform item structure data ----------------------
164 // We prefer the data from the user's contact over the public one
165 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
166 ($row['author-link'] == $row['contact-link'])) {
167 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
168 $row['author-avatar'] = $row['contact-avatar'];
170 if (isset($row['author-name']) && !empty($row['contact-name'])) {
171 $row['author-name'] = $row['contact-name'];
175 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
176 ($row['owner-link'] == $row['contact-link'])) {
177 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
178 $row['owner-avatar'] = $row['contact-avatar'];
180 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
181 $row['owner-name'] = $row['contact-name'];
185 // We can always comment on posts from these networks
186 if (array_key_exists('writable', $row) &&
187 in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
188 $row['writable'] = true;
191 // ---------------------- Transform item content data ----------------------
193 // Fetch data from the item-content table whenever there is content there
194 if (self::isLegacyMode()) {
195 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
196 foreach ($legacy_fields as $field) {
197 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
198 $row[$field] = $row['internal-item-' . $field];
200 unset($row['internal-item-' . $field]);
204 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
205 $row['verb'] = self::indexToActivity($row['internal-activity']);
206 if (array_key_exists('title', $row)) {
209 if (array_key_exists('body', $row)) {
210 $row['body'] = $row['verb'];
212 if (array_key_exists('object', $row)) {
215 if (array_key_exists('object-type', $row)) {
216 $row['object-type'] = ACTIVITY_OBJ_NOTE;
218 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
219 // Posts don't have an object or target - but having tags or files.
220 // We safe some performance by building tag and file strings only here.
221 // We remove object and target since they aren't used for this type.
222 if (array_key_exists('object', $row)) {
225 if (array_key_exists('target', $row)) {
230 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
231 // Build the tag string out of the term entries
232 if (array_key_exists('tag', $row) && empty($row['tag'])) {
233 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
236 // Build the file string out of the term entries
237 if (array_key_exists('file', $row) && empty($row['file'])) {
238 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
242 if (array_key_exists('signed_text', $row) && array_key_exists('interaction', $row) && !is_null($row['interaction'])) {
243 $row['signed_text'] = $row['interaction'];
246 if (array_key_exists('ignored', $row) && array_key_exists('internal-user-ignored', $row) && !is_null($row['internal-user-ignored'])) {
247 $row['ignored'] = $row['internal-user-ignored'];
250 // Remove internal fields
251 unset($row['internal-activity']);
252 unset($row['internal-network']);
253 unset($row['internal-iid']);
254 unset($row['internal-iaid']);
255 unset($row['internal-icid']);
256 unset($row['internal-user-ignored']);
257 unset($row['interaction']);
263 * @brief Fills an array with data from an item query
265 * @param object $stmt statement object
266 * @param bool $do_close
267 * @return array Data array
269 public static function inArray($stmt, $do_close = true) {
270 if (is_bool($stmt)) {
275 while ($row = self::fetch($stmt)) {
285 * @brief Check if item data exists
287 * @param array $condition array of fields for condition
289 * @return boolean Are there rows for that condition?
292 public static function exists($condition) {
293 $stmt = self::select(['id'], $condition, ['limit' => 1]);
295 if (is_bool($stmt)) {
298 $retval = (DBA::numRows($stmt) > 0);
307 * Retrieve a single record from the item table for a given user and returns it in an associative array
309 * @brief Retrieve a single record from a table
310 * @param integer $uid User ID
311 * @param array $selected
312 * @param array $condition
313 * @param array $params
318 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
320 $params['uid'] = $uid;
322 if (empty($selected)) {
323 $selected = Item::DISPLAY_FIELDLIST;
326 return self::selectFirst($selected, $condition, $params);
330 * @brief Select rows from the item table for a given user
332 * @param integer $uid User ID
333 * @param array $selected Array of selected fields, empty for all
334 * @param array $condition Array of fields for condition
335 * @param array $params Array of several parameters
337 * @return boolean|object
340 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
342 $params['uid'] = $uid;
344 if (empty($selected)) {
345 $selected = Item::DISPLAY_FIELDLIST;
348 return self::select($selected, $condition, $params);
352 * Retrieve a single record from the item table and returns it in an associative array
354 * @brief Retrieve a single record from a table
355 * @param array $fields
356 * @param array $condition
357 * @param array $params
362 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
364 $params['limit'] = 1;
366 $result = self::select($fields, $condition, $params);
368 if (is_bool($result)) {
371 $row = self::fetch($result);
378 * @brief Select rows from the item table
380 * @param array $selected Array of selected fields, empty for all
381 * @param array $condition Array of fields for condition
382 * @param array $params Array of several parameters
384 * @return boolean|object
387 public static function select(array $selected = [], array $condition = [], $params = [])
392 if (isset($params['uid'])) {
393 $uid = $params['uid'];
397 $fields = self::fieldlist($usermode);
399 $select_fields = self::constructSelectFields($fields, $selected);
401 $condition_string = DBA::buildCondition($condition);
403 $condition_string = self::addTablesToFields($condition_string, $fields);
406 $condition_string = $condition_string . ' AND ' . self::condition(false);
409 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
411 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
413 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
415 return DBA::p($sql, $condition);
419 * @brief Select rows from the starting post in the item table
421 * @param integer $uid User ID
422 * @param array $selected
423 * @param array $condition Array of fields for condition
424 * @param array $params Array of several parameters
426 * @return boolean|object
429 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
431 $params['uid'] = $uid;
433 if (empty($selected)) {
434 $selected = Item::DISPLAY_FIELDLIST;
437 return self::selectThread($selected, $condition, $params);
441 * Retrieve a single record from the starting post in the item table and returns it in an associative array
443 * @brief Retrieve a single record from a table
444 * @param integer $uid User ID
445 * @param array $selected
446 * @param array $condition
447 * @param array $params
452 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
454 $params['uid'] = $uid;
456 if (empty($selected)) {
457 $selected = Item::DISPLAY_FIELDLIST;
460 return self::selectFirstThread($selected, $condition, $params);
464 * Retrieve a single record from the starting post in the item table and returns it in an associative array
466 * @brief Retrieve a single record from a table
467 * @param array $fields
468 * @param array $condition
469 * @param array $params
474 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
476 $params['limit'] = 1;
477 $result = self::selectThread($fields, $condition, $params);
479 if (is_bool($result)) {
482 $row = self::fetch($result);
489 * @brief Select rows from the starting post in the item table
491 * @param array $selected Array of selected fields, empty for all
492 * @param array $condition Array of fields for condition
493 * @param array $params Array of several parameters
495 * @return boolean|object
498 public static function selectThread(array $selected = [], array $condition = [], $params = [])
503 if (isset($params['uid'])) {
504 $uid = $params['uid'];
508 $fields = self::fieldlist($usermode);
510 $fields['thread'] = ['mention', 'ignored', 'iid'];
512 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
513 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
514 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
515 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
517 $select_fields = self::constructSelectFields($fields, $selected);
519 $condition_string = DBA::buildCondition($condition);
521 $condition_string = self::addTablesToFields($condition_string, $threadfields);
522 $condition_string = self::addTablesToFields($condition_string, $fields);
525 $condition_string = $condition_string . ' AND ' . self::condition(true);
528 $param_string = DBA::buildParameter($params);
529 $param_string = self::addTablesToFields($param_string, $threadfields);
530 $param_string = self::addTablesToFields($param_string, $fields);
532 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
534 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
536 return DBA::p($sql, $condition);
540 * @brief Returns a list of fields that are associated with the item table
543 * @return array field list
545 private static function fieldlist($usermode)
549 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
550 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
551 'created', 'edited', 'commented', 'received', 'changed', 'psid',
552 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
553 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
554 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
555 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
556 'network' => 'internal-network', 'icid' => 'internal-icid',
557 'iaid' => 'internal-iaid'];
560 $fields['user-item'] = ['ignored' => 'internal-user-ignored'];
563 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
565 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
567 $fields['item-delivery-data'] = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, ItemDeliveryData::FIELD_LIST);
569 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
571 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
572 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
574 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
575 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
577 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
578 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
579 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
581 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
583 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
585 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
586 'start' => 'event-start','finish' => 'event-finish',
587 'summary' => 'event-summary','desc' => 'event-desc',
588 'location' => 'event-location', 'type' => 'event-type',
589 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
590 'ignore' => 'event-ignore', 'id' => 'event-id'];
592 $fields['sign'] = ['signed_text', 'signature', 'signer'];
594 $fields['diaspora-interaction'] = ['interaction'];
600 * @brief Returns SQL condition for the "select" functions
602 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
604 * @return string SQL condition
606 private static function condition($thread_mode)
609 $master_table = "`thread`";
611 $master_table = "`item`";
613 return sprintf("$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated`
614 AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`)
615 AND (`user-author`.`blocked` IS NULL OR NOT `user-author`.`blocked`)
616 AND (`user-author`.`ignored` IS NULL OR NOT `user-author`.`ignored` OR `item`.`gravity` != %d)
617 AND (`user-owner`.`blocked` IS NULL OR NOT `user-owner`.`blocked`)
618 AND (`user-owner`.`ignored` IS NULL OR NOT `user-owner`.`ignored` OR `item`.`gravity` != %d) ",
619 GRAVITY_PARENT, GRAVITY_PARENT);
623 * @brief Returns all needed "JOIN" commands for the "select" functions
625 * @param integer $uid User ID
626 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
627 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
630 * @return string The SQL joins for the "select" functions
632 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
635 $master_table = "`thread`";
636 $master_table_key = "`thread`.`iid`";
637 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
639 $master_table = "`item`";
640 $master_table_key = "`item`.`id`";
645 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
646 AND NOT `contact`.`blocked`
647 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
648 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
649 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
650 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
651 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d
652 LEFT JOIN `user-contact` AS `user-author` ON `user-author`.`cid` = $master_table.`author-id` AND `user-author`.`uid` = %d
653 LEFT JOIN `user-contact` AS `user-owner` ON `user-owner`.`cid` = $master_table.`owner-id` AND `user-owner`.`uid` = %d",
654 Contact::SHARING, Contact::FRIEND, GRAVITY_PARENT, intval($uid), intval($uid), intval($uid));
656 if (strpos($sql_commands, "`contact`.") !== false) {
657 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
659 if (strpos($sql_commands, "`author`.") !== false) {
660 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
662 if (strpos($sql_commands, "`owner`.") !== false) {
663 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
667 if (strpos($sql_commands, "`group_member`.") !== false) {
668 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
671 if (strpos($sql_commands, "`user`.") !== false) {
672 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
675 if (strpos($sql_commands, "`event`.") !== false) {
676 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
679 if (strpos($sql_commands, "`sign`.") !== false) {
680 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
683 if (strpos($sql_commands, "`diaspora-interaction`.") !== false) {
684 $joins .= " LEFT JOIN `diaspora-interaction` ON `diaspora-interaction`.`uri-id` = `item`.`uri-id`";
687 if (strpos($sql_commands, "`item-activity`.") !== false) {
688 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`uri-id` = `item`.`uri-id`";
691 if (strpos($sql_commands, "`item-content`.") !== false) {
692 $joins .= " LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`";
695 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
696 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
699 if (strpos($sql_commands, "`permissionset`.") !== false) {
700 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
703 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
704 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
707 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
708 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
715 * @brief Add the field list for the "select" functions
717 * @param array $fields The field definition array
718 * @param array $selected The array with the selected fields from the "select" functions
720 * @return string The field list
722 private static function constructSelectFields($fields, $selected)
724 if (!empty($selected)) {
725 $selected[] = 'internal-iid';
726 $selected[] = 'internal-iaid';
727 $selected[] = 'internal-icid';
728 $selected[] = 'internal-network';
731 if (in_array('verb', $selected)) {
732 $selected[] = 'internal-activity';
735 if (in_array('ignored', $selected)) {
736 $selected[] = 'internal-user-ignored';
739 if (in_array('signed_text', $selected)) {
740 $selected[] = 'interaction';
743 $legacy_fields = array_merge(ItemDeliveryData::LEGACY_FIELD_LIST, self::MIXED_CONTENT_FIELDLIST);
746 foreach ($fields as $table => $table_fields) {
747 foreach ($table_fields as $field => $select) {
748 if (empty($selected) || in_array($select, $selected)) {
749 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
750 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
752 if (is_int($field)) {
753 $selection[] = "`" . $table . "`.`" . $select . "`";
755 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
760 return implode(", ", $selection);
764 * @brief add table definition to fields in an SQL query
766 * @param string $query SQL query
767 * @param array $fields The field definition array
769 * @return string the changed SQL query
771 private static function addTablesToFields($query, $fields)
773 foreach ($fields as $table => $table_fields) {
774 foreach ($table_fields as $alias => $field) {
775 if (is_int($alias)) {
776 $replace_field = $field;
778 $replace_field = $alias;
781 $search = "/([^\.])`" . $field . "`/i";
782 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
783 $query = preg_replace($search, $replace, $query);
790 * @brief Update existing item entries
792 * @param array $fields The fields that are to be changed
793 * @param array $condition The condition for finding the item entries
795 * In the future we may have to change permissions as well.
796 * Then we had to add the user id as third parameter.
798 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
800 * @return integer|boolean number of affected rows - or "false" if there was an error
801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 public static function update(array $fields, array $condition)
805 if (empty($condition) || empty($fields)) {
809 // To ensure the data integrity we do it in an transaction
812 // We cannot simply expand the condition to check for origin entries
813 // The condition needn't to be a simple array but could be a complex condition.
814 // And we have to execute this query before the update to ensure to fetch the same data.
815 $items = DBA::select('item', ['id', 'origin', 'uri', 'uri-id', 'iaid', 'icid', 'tag', 'file'], $condition);
817 $content_fields = [];
818 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
819 if (isset($fields[$field])) {
820 $content_fields[$field] = $fields[$field];
821 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
822 unset($fields[$field]);
824 $fields[$field] = null;
829 $delivery_data = ItemDeliveryData::extractFields($fields);
831 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'postopts', 'inform'];
832 foreach ($clear_fields as $field) {
833 if (array_key_exists($field, $fields)) {
834 $fields[$field] = null;
838 if (array_key_exists('tag', $fields)) {
839 $tags = $fields['tag'];
840 $fields['tag'] = null;
845 if (array_key_exists('file', $fields)) {
846 $files = $fields['file'];
847 $fields['file'] = null;
852 if (!empty($fields)) {
853 $success = DBA::update('item', $fields, $condition);
862 // When there is no content for the "old" item table, this will count the fetched items
863 $rows = DBA::affectedRows();
865 while ($item = DBA::fetch($items)) {
866 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
867 self::updateActivity($content_fields, ['uri-id' => $item['uri-id']]);
869 if (empty($item['iaid'])) {
870 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
871 if (DBA::isResult($item_activity)) {
872 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
873 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
874 if (self::isLegacyMode()) {
875 $item_fields[$field] = null;
877 unset($item_fields[$field]);
880 DBA::update('item', $item_fields, ['id' => $item['id']]);
882 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
883 DBA::delete('item-content', ['id' => $item['icid']]);
886 } elseif (!empty($item['icid'])) {
887 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
889 if (!DBA::exists('item', ['icid' => $item['icid']])) {
890 DBA::delete('item-content', ['id' => $item['icid']]);
894 self::updateContent($content_fields, ['uri-id' => $item['uri-id']]);
896 if (empty($item['icid'])) {
897 $item_content = DBA::selectFirst('item-content', [], ['uri-id' => $item['uri-id']]);
898 if (DBA::isResult($item_content)) {
899 $item_fields = ['icid' => $item_content['id']];
900 // Clear all fields in the item table that have a content in the item-content table
901 foreach ($item_content as $field => $content) {
902 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
903 if (self::isLegacyMode()) {
904 $item_fields[$field] = null;
906 unset($item_fields[$field]);
910 DBA::update('item', $item_fields, ['id' => $item['id']]);
915 if (!is_null($tags)) {
916 Term::insertFromTagFieldByItemId($item['id'], $tags);
917 if (!empty($item['tag'])) {
918 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
922 if (!is_null($files)) {
923 Term::insertFromFileFieldByItemId($item['id'], $files);
924 if (!empty($item['file'])) {
925 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
929 ItemDeliveryData::update($item['id'], $delivery_data);
931 self::updateThread($item['id']);
933 // We only need to notfiy others when it is an original entry from us.
934 // Only call the notifier when the item has some content relevant change.
935 if ($item['origin'] && in_array('edited', array_keys($fields))) {
936 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
946 * @brief Delete an item and notify others about it - if it was ours
948 * @param array $condition The condition for finding the item entries
949 * @param integer $priority Priority for the notification
950 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
952 public static function delete($condition, $priority = PRIORITY_HIGH)
954 $items = self::select(['id'], $condition);
955 while ($item = self::fetch($items)) {
956 self::deleteById($item['id'], $priority);
962 * @brief Delete an item for an user and notify others about it - if it was ours
964 * @param array $condition The condition for finding the item entries
965 * @param integer $uid User who wants to delete this item
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 public static function deleteForUser($condition, $uid)
974 $items = self::select(['id', 'uid'], $condition);
975 while ($item = self::fetch($items)) {
976 // "Deleting" global items just means hiding them
977 if ($item['uid'] == 0) {
978 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
979 } elseif ($item['uid'] == $uid) {
980 self::deleteById($item['id'], PRIORITY_HIGH);
982 Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
989 * @brief Delete an item and notify others about it - if it was ours
991 * @param integer $item_id Item ID that should be delete
992 * @param integer $priority Priority for the notification
994 * @return boolean success
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
997 public static function deleteById($item_id, $priority = PRIORITY_HIGH)
999 // locate item to be deleted
1000 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
1001 'deleted', 'file', 'resource-id', 'event-id', 'attach',
1002 'verb', 'object-type', 'object', 'target', 'contact-id',
1003 'icid', 'iaid', 'psid'];
1004 $item = self::selectFirst($fields, ['id' => $item_id]);
1005 if (!DBA::isResult($item)) {
1006 Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
1010 if ($item['deleted']) {
1011 Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
1015 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
1016 if (!DBA::isResult($parent)) {
1017 $parent = ['origin' => false];
1020 // clean up categories and tags so they don't end up as orphans
1023 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1026 foreach ($matches as $mtch) {
1027 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],true);
1033 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1036 foreach ($matches as $mtch) {
1037 FileTag::unsaveFile($item['uid'], $item['id'], $mtch[1],false);
1042 * If item is a link to a photo resource, nuke all the associated photos
1043 * (visitors will not have photo resources)
1044 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1045 * generate a resource-id and therefore aren't intimately linked to the item.
1047 /// @TODO: this should first check if photo is used elsewhere
1048 if (strlen($item['resource-id'])) {
1049 Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1052 // If item is a link to an event, delete the event.
1053 if (intval($item['event-id'])) {
1054 Event::delete($item['event-id']);
1057 // If item has attachments, drop them
1058 /// @TODO: this should first check if attachment is used elsewhere
1059 foreach (explode(",", $item['attach']) as $attach) {
1060 preg_match("|attach/(\d+)|", $attach, $matches);
1061 if (is_array($matches) && count($matches) > 1) {
1062 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
1066 // Delete tags that had been attached to other items
1067 self::deleteTagsFromItem($item);
1069 // Set the item to "deleted"
1070 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1071 DBA::update('item', $item_fields, ['id' => $item['id']]);
1073 Term::insertFromTagFieldByItemId($item['id'], '');
1074 Term::insertFromFileFieldByItemId($item['id'], '');
1075 self::deleteThread($item['id'], $item['parent-uri']);
1077 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1078 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1081 ItemDeliveryData::delete($item['id']);
1083 // We don't delete the item-activity here, since we need some of the data for ActivityPub
1085 if (!empty($item['icid']) && !self::exists(['icid' => $item['icid'], 'deleted' => false])) {
1086 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1088 // When the permission set will be used in photo and events as well,
1089 // this query here needs to be extended.
1090 if (!empty($item['psid']) && !self::exists(['psid' => $item['psid'], 'deleted' => false])) {
1091 DBA::delete('permissionset', ['id' => $item['psid']], ['cascade' => false]);
1094 // If it's the parent of a comment thread, kill all the kids
1095 if ($item['id'] == $item['parent']) {
1096 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1099 // Is it our comment and/or our thread?
1100 if ($item['origin'] || $parent['origin']) {
1102 // When we delete the original post we will delete all existing copies on the server as well
1103 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1105 // send the notification upstream/downstream
1106 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1107 } elseif ($item['uid'] != 0) {
1109 // When we delete just our local user copy of an item, we have to set a marker to hide it
1110 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1111 if (DBA::isResult($global_item)) {
1112 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1116 Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
1121 private static function deleteTagsFromItem($item)
1123 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1127 $xo = XML::parseString($item["object"], false);
1128 $xt = XML::parseString($item["target"], false);
1130 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1134 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1135 if (!DBA::isResult($i)) {
1139 // For tags, the owner cannot remove the tag on the author's copy of the post.
1140 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1141 $author_copy = $item["origin"];
1143 if (($owner_remove && $author_copy) || !$owner_remove) {
1147 $tags = explode(',', $i["tag"]);
1150 foreach ($tags as $tag) {
1151 if (trim($tag) !== trim($xo->body)) {
1152 $newtags[] = trim($tag);
1156 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1159 private static function guid($item, $notify)
1161 if (!empty($item['guid'])) {
1162 return Strings::escapeTags(trim($item['guid']));
1166 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1167 // We add the hash of our own host because our host is the original creator of the post.
1168 $prefix_host = \get_app()->getHostName();
1172 // We are only storing the post so we create a GUID from the original hostname.
1173 if (!empty($item['author-link'])) {
1174 $parsed = parse_url($item['author-link']);
1175 if (!empty($parsed['host'])) {
1176 $prefix_host = $parsed['host'];
1180 if (empty($prefix_host) && !empty($item['plink'])) {
1181 $parsed = parse_url($item['plink']);
1182 if (!empty($parsed['host'])) {
1183 $prefix_host = $parsed['host'];
1187 if (empty($prefix_host) && !empty($item['uri'])) {
1188 $parsed = parse_url($item['uri']);
1189 if (!empty($parsed['host'])) {
1190 $prefix_host = $parsed['host'];
1194 // Is it in the format data@host.tld? - Used for mail contacts
1195 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1196 $mailparts = explode('@', $item['author-link']);
1197 $prefix_host = array_pop($mailparts);
1201 if (!empty($item['plink'])) {
1202 $guid = self::guidFromUri($item['plink'], $prefix_host);
1203 } elseif (!empty($item['uri'])) {
1204 $guid = self::guidFromUri($item['uri'], $prefix_host);
1206 $guid = System::createUUID(hash('crc32', $prefix_host));
1212 private static function contactId($item)
1214 $contact_id = (int)$item["contact-id"];
1216 if (!empty($contact_id)) {
1219 Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
1221 * First we are looking for a suitable contact that matches with the author of the post
1222 * This is done only for comments
1224 if ($item['parent-uri'] != $item['uri']) {
1225 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1228 // If not present then maybe the owner was found
1229 if ($contact_id == 0) {
1230 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1233 // Still missing? Then use the "self" contact of the current user
1234 if ($contact_id == 0) {
1235 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1236 if (DBA::isResult($self)) {
1237 $contact_id = $self["id"];
1240 Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
1245 // This function will finally cover most of the preparation functionality in mod/item.php
1246 public static function prepare(&$item)
1248 $data = BBCode::getAttachmentData($item['body']);
1249 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1250 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1251 $posttype = Item::PT_PAGE;
1252 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1256 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1260 // If it is a posting where users should get notifications, then define it as wall posting
1263 $item['origin'] = 1;
1264 $item['network'] = Protocol::DFRN;
1265 $item['protocol'] = Conversation::PARCEL_DFRN;
1267 if (is_int($notify)) {
1268 $priority = $notify;
1270 $priority = PRIORITY_HIGH;
1273 $item['network'] = trim(defaults($item, 'network', Protocol::PHANTOM));
1276 $item['guid'] = self::guid($item, $notify);
1277 $item['uri'] = Strings::escapeTags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1280 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1282 // Store conversation data
1283 $item = Conversation::insert($item);
1286 * If a Diaspora signature structure was passed in, pull it out of the
1287 * item array and set it aside for later storage.
1291 if (isset($item['dsprsig'])) {
1292 $encoded_signature = $item['dsprsig'];
1293 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1294 unset($item['dsprsig']);
1297 $diaspora_signed_text = '';
1298 if (isset($item['diaspora_signed_text'])) {
1299 $diaspora_signed_text = $item['diaspora_signed_text'];
1300 unset($item['diaspora_signed_text']);
1303 // Converting the plink
1304 /// @TODO Check if this is really still needed
1305 if ($item['network'] == Protocol::OSTATUS) {
1306 if (isset($item['plink'])) {
1307 $item['plink'] = OStatus::convertHref($item['plink']);
1308 } elseif (isset($item['uri'])) {
1309 $item['plink'] = OStatus::convertHref($item['uri']);
1313 if (!empty($item['thr-parent'])) {
1314 $item['parent-uri'] = $item['thr-parent'];
1317 if (isset($item['gravity'])) {
1318 $item['gravity'] = intval($item['gravity']);
1319 } elseif ($item['parent-uri'] === $item['uri']) {
1320 $item['gravity'] = GRAVITY_PARENT;
1321 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1322 $item['gravity'] = GRAVITY_COMMENT;
1324 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1325 Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
1328 $uid = intval($item['uid']);
1330 // check for create date and expire time
1331 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1333 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1334 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1335 $expire_interval = $user['expire'];
1338 if (($expire_interval > 0) && !empty($item['created'])) {
1339 $expire_date = time() - ($expire_interval * 86400);
1340 $created_date = strtotime($item['created']);
1341 if ($created_date < $expire_date) {
1342 Logger::log('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), Logger::DEBUG);
1348 * Do we already have this item?
1349 * We have to check several networks since Friendica posts could be repeated
1350 * via OStatus (maybe Diasporsa as well)
1352 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
1353 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1354 trim($item['uri']), $item['uid'],
1355 Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
1356 $existing = self::selectFirst(['id', 'network'], $condition);
1357 if (DBA::isResult($existing)) {
1358 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1360 Logger::log("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1363 return $existing["id"];
1367 $item['wall'] = intval(defaults($item, 'wall', 0));
1368 $item['extid'] = trim(defaults($item, 'extid', ''));
1369 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1370 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1371 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1372 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1373 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1374 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1375 $item['received'] = (isset($item['received']) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1376 $item['created'] = (isset($item['created']) ? DateTimeFormat::utc($item['created']) : $item['received']);
1377 $item['edited'] = (isset($item['edited']) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1378 $item['changed'] = (isset($item['changed']) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1379 $item['commented'] = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1380 $item['title'] = trim(defaults($item, 'title', ''));
1381 $item['location'] = trim(defaults($item, 'location', ''));
1382 $item['coord'] = trim(defaults($item, 'coord', ''));
1383 $item['visible'] = (isset($item['visible']) ? intval($item['visible']) : 1);
1384 $item['deleted'] = 0;
1385 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1386 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1387 $item['verb'] = trim(defaults($item, 'verb', ''));
1388 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1389 $item['object'] = trim(defaults($item, 'object', ''));
1390 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1391 $item['target'] = trim(defaults($item, 'target', ''));
1392 $item['plink'] = trim(defaults($item, 'plink', ''));
1393 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1394 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1395 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1396 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1397 $item['private'] = intval(defaults($item, 'private', 0));
1398 $item['body'] = trim(defaults($item, 'body', ''));
1399 $item['tag'] = trim(defaults($item, 'tag', ''));
1400 $item['attach'] = trim(defaults($item, 'attach', ''));
1401 $item['app'] = trim(defaults($item, 'app', ''));
1402 $item['origin'] = intval(defaults($item, 'origin', 0));
1403 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1404 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1405 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1406 $item['inform'] = trim(defaults($item, 'inform', ''));
1407 $item['file'] = trim(defaults($item, 'file', ''));
1409 // When there is no content then we don't post it
1410 if ($item['body'].$item['title'] == '') {
1411 Logger::log('No body, no title.');
1415 self::addLanguageToItemArray($item);
1417 // Items cannot be stored before they happen ...
1418 if ($item['created'] > DateTimeFormat::utcNow()) {
1419 $item['created'] = DateTimeFormat::utcNow();
1422 // We haven't invented time travel by now.
1423 if ($item['edited'] > DateTimeFormat::utcNow()) {
1424 $item['edited'] = DateTimeFormat::utcNow();
1427 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1429 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1430 $item["contact-id"] = self::contactId($item);
1432 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1433 'photo' => $item['author-avatar'], 'network' => $item['network']];
1435 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1437 if (Contact::isBlocked($item["author-id"])) {
1438 Logger::log('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1442 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1443 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1445 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1447 if (Contact::isBlocked($item["owner-id"])) {
1448 Logger::log('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1452 if ($item['network'] == Protocol::PHANTOM) {
1453 Logger::log('Missing network. Called by: '.System::callstack(), Logger::DEBUG);
1455 $item['network'] = Protocol::DFRN;
1456 Logger::log("Set network to " . $item["network"] . " for " . $item["uri"], Logger::DEBUG);
1459 // Checking if there is already an item with the same guid
1460 Logger::log('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], Logger::DEBUG);
1461 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1462 if (self::exists($condition)) {
1463 Logger::log('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], Logger::DEBUG);
1467 // Check for hashtags in the body and repair or add hashtag links
1468 self::setHashtags($item);
1470 $item['thr-parent'] = $item['parent-uri'];
1478 if ($item['parent-uri'] === $item['uri']) {
1480 $parent_deleted = 0;
1481 $allow_cid = $item['allow_cid'];
1482 $allow_gid = $item['allow_gid'];
1483 $deny_cid = $item['deny_cid'];
1484 $deny_gid = $item['deny_gid'];
1485 $notify_type = 'wall-new';
1487 // find the parent and snarf the item id and ACLs
1488 // and anything else we need to inherit
1490 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1491 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1492 'wall', 'private', 'forum_mode', 'origin'];
1493 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1494 $params = ['order' => ['id' => false]];
1495 $parent = self::selectFirst($fields, $condition, $params);
1497 if (DBA::isResult($parent)) {
1498 // is the new message multi-level threaded?
1499 // even though we don't support it now, preserve the info
1500 // and re-attach to the conversation parent.
1502 if ($parent['uri'] != $parent['parent-uri']) {
1503 $item['parent-uri'] = $parent['parent-uri'];
1505 $condition = ['uri' => $item['parent-uri'],
1506 'parent-uri' => $item['parent-uri'],
1507 'uid' => $item['uid']];
1508 $params = ['order' => ['id' => false]];
1509 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1511 if (DBA::isResult($toplevel_parent)) {
1512 $parent = $toplevel_parent;
1516 $parent_id = $parent['id'];
1517 $parent_deleted = $parent['deleted'];
1518 $allow_cid = $parent['allow_cid'];
1519 $allow_gid = $parent['allow_gid'];
1520 $deny_cid = $parent['deny_cid'];
1521 $deny_gid = $parent['deny_gid'];
1522 $item['wall'] = $parent['wall'];
1523 $notify_type = 'comment-new';
1526 * If the parent is private, force privacy for the entire conversation
1527 * This differs from the above settings as it subtly allows comments from
1528 * email correspondents to be private even if the overall thread is not.
1530 if ($parent['private']) {
1531 $item['private'] = $parent['private'];
1535 * Edge case. We host a public forum that was originally posted to privately.
1536 * The original author commented, but as this is a comment, the permissions
1537 * weren't fixed up so it will still show the comment as private unless we fix it here.
1539 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1540 $item['private'] = 0;
1543 // If its a post from myself then tag the thread as "mention"
1544 Logger::log("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], Logger::DEBUG);
1545 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1546 if (DBA::isResult($user)) {
1547 $self = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
1548 $self_id = Contact::getIdForURL($self, 0, true);
1549 Logger::log("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], Logger::DEBUG);
1550 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1551 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1552 Logger::log("tagged thread ".$parent_id." as mention for user ".$self, Logger::DEBUG);
1557 * Allow one to see reply tweets from status.net even when
1558 * we don't have or can't see the original post.
1560 if ($force_parent) {
1561 Logger::log('$force_parent=true, reply converted to top-level post.');
1563 $item['parent-uri'] = $item['uri'];
1564 $item['gravity'] = GRAVITY_PARENT;
1566 Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1570 $parent_deleted = 0;
1574 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1575 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1577 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1578 $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
1579 if (self::exists($condition)) {
1580 Logger::log('duplicated item with the same uri found. '.print_r($item,true));
1584 // On Friendica and Diaspora the GUID is unique
1585 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
1586 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1587 if (self::exists($condition)) {
1588 Logger::log('duplicated item with the same guid found. '.print_r($item,true));
1592 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1593 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1594 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1595 if (self::exists($condition)) {
1596 Logger::log('duplicated item with the same body found. '.print_r($item,true));
1601 // Is this item available in the global items (with uid=0)?
1602 if ($item["uid"] == 0) {
1603 $item["global"] = true;
1605 // Set the global flag on all items if this was a global item entry
1606 self::update(['global' => true], ['uri' => $item["uri"]]);
1608 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1612 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1615 $private = $item['private'];
1618 $item["allow_cid"] = $allow_cid;
1619 $item["allow_gid"] = $allow_gid;
1620 $item["deny_cid"] = $deny_cid;
1621 $item["deny_gid"] = $deny_gid;
1622 $item["private"] = $private;
1623 $item["deleted"] = $parent_deleted;
1625 // Fill the cache field
1626 self::putInCache($item);
1629 $item['edit'] = false;
1630 $item['parent'] = $parent_id;
1631 Hook::callAll('post_local', $item);
1632 unset($item['edit']);
1633 unset($item['parent']);
1635 Hook::callAll('post_remote', $item);
1638 // This array field is used to trigger some automatic reactions
1639 // It is mainly used in the "post_local" hook.
1640 unset($item['api_source']);
1642 if (!empty($item['cancel'])) {
1643 Logger::log('post cancelled by addon.');
1648 * Check for already added items.
1649 * There is a timing issue here that sometimes creates double postings.
1650 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1652 if ($item["uid"] == 0) {
1653 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1654 Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
1659 Logger::log('' . print_r($item,true), Logger::DATA);
1661 if (array_key_exists('tag', $item)) {
1662 $tags = $item['tag'];
1663 unset($item['tag']);
1668 if (array_key_exists('file', $item)) {
1669 $files = $item['file'];
1670 unset($item['file']);
1675 // Creates or assigns the permission set
1676 $item['psid'] = PermissionSet::fetchIDForPost($item);
1678 // We are doing this outside of the transaction to avoid timing problems
1679 if (!self::insertActivity($item)) {
1680 self::insertContent($item);
1683 $delivery_data = ItemDeliveryData::extractFields($item);
1685 unset($item['postopts']);
1686 unset($item['inform']);
1688 // These fields aren't stored anymore in the item table, they are fetched upon request
1689 unset($item['author-link']);
1690 unset($item['author-name']);
1691 unset($item['author-avatar']);
1693 unset($item['owner-link']);
1694 unset($item['owner-name']);
1695 unset($item['owner-avatar']);
1698 $ret = DBA::insert('item', $item);
1700 // When the item was successfully stored we fetch the ID of the item.
1701 if (DBA::isResult($ret)) {
1702 $current_post = DBA::lastInsertId();
1704 // This can happen - for example - if there are locking timeouts.
1707 // Store the data into a spool file so that we can try again later.
1709 // At first we restore the Diaspora signature that we removed above.
1710 if (isset($encoded_signature)) {
1711 $item['dsprsig'] = $encoded_signature;
1714 // Now we store the data in the spool directory
1715 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1716 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1718 $spoolpath = get_spoolpath();
1719 if ($spoolpath != "") {
1720 $spool = $spoolpath.'/'.$file;
1722 file_put_contents($spool, json_encode($orig_item));
1723 Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
1728 if ($current_post == 0) {
1729 // This is one of these error messages that never should occur.
1730 Logger::log("couldn't find created item - we better quit now.");
1735 // How much entries have we created?
1736 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1737 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1740 // There are duplicates. We delete our just created entry.
1741 Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1743 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1744 DBA::delete('item', ['id' => $current_post]);
1747 } elseif ($entries == 0) {
1748 // This really should never happen since we quit earlier if there were problems.
1749 Logger::log("Something is terribly wrong. We haven't found our created entry.");
1754 Logger::log('created item '.$current_post);
1755 self::updateContact($item);
1757 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1758 $parent_id = $current_post;
1762 self::update(['parent' => $parent_id], ['id' => $current_post]);
1764 $item['id'] = $current_post;
1765 $item['parent'] = $parent_id;
1767 // update the commented timestamp on the parent
1768 // Only update "commented" if it is really a comment
1769 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1770 self::update(['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1772 self::update(['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1777 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1778 * We can check for this condition when we decode and encode the stuff again.
1780 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1781 $dsprsig->signature = base64_decode($dsprsig->signature);
1782 Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
1785 if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
1786 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $dsprsig->signed_text], true);
1788 // The other fields are used by very old Friendica servers, so we currently store them differently
1789 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1790 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1794 if (!empty($diaspora_signed_text)) {
1795 DBA::insert('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $diaspora_signed_text], true);
1798 $deleted = self::tagDeliver($item['uid'], $current_post);
1801 * current post can be deleted if is for a community page and no mention are
1804 if (!$deleted && !$dontcache) {
1805 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1806 if (DBA::isResult($posted_item)) {
1808 Hook::callAll('post_local_end', $posted_item);
1810 Hook::callAll('post_remote_end', $posted_item);
1813 Logger::log('new item not found in DB, id ' . $current_post);
1817 if ($item['parent-uri'] === $item['uri']) {
1818 self::addThread($current_post);
1820 self::updateThread($parent_id);
1823 ItemDeliveryData::insert($current_post, $delivery_data);
1828 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1829 * This is not perfect - but a workable solution until we found the reason for the problem.
1831 if (!empty($tags)) {
1832 Term::insertFromTagFieldByItemId($current_post, $tags);
1835 if (!empty($files)) {
1836 Term::insertFromFileFieldByItemId($current_post, $files);
1839 if ($item['parent-uri'] === $item['uri']) {
1840 self::addShadow($current_post);
1842 self::addShadowPost($current_post);
1845 check_user_notification($current_post);
1848 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, $current_post);
1849 } elseif ($item['visible'] && ((!empty($parent) && $parent['origin']) || $item['origin'])) {
1850 if ($item['gravity'] == GRAVITY_ACTIVITY) {
1851 $cmd = $item['origin'] ? 'activity-new' : 'activity-import';
1852 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
1853 $cmd = $item['origin'] ? 'comment-new' : 'comment-import';
1858 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', $cmd, $current_post);
1861 return $current_post;
1865 * @brief Insert a new item content entry
1867 * @param array $item The item fields that are to be inserted
1869 * @throws \Exception
1871 private static function insertActivity(&$item)
1873 $activity_index = self::activityToIndex($item['verb']);
1875 if ($activity_index < 0) {
1879 $fields = ['activity' => $activity_index, 'uri-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1881 // We just remove everything that is content
1882 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1883 unset($item[$field]);
1886 // To avoid timing problems, we are using locks.
1887 $locked = Lock::acquire('item_insert_activity');
1889 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1892 // Do we already have this content?
1893 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
1894 if (DBA::isResult($item_activity)) {
1895 $item['iaid'] = $item_activity['id'];
1896 Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1897 } elseif (DBA::insert('item-activity', $fields)) {
1898 $item['iaid'] = DBA::lastInsertId();
1899 Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1901 // This shouldn't happen.
1902 Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1903 Lock::release('item_insert_activity');
1907 Lock::release('item_insert_activity');
1913 * @brief Insert a new item content entry
1915 * @param array $item The item fields that are to be inserted
1916 * @throws \Exception
1918 private static function insertContent(&$item)
1920 $fields = ['uri-plink-hash' => (string)$item['uri-id'], 'uri-id' => $item['uri-id']];
1922 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1923 if (isset($item[$field])) {
1924 $fields[$field] = $item[$field];
1925 unset($item[$field]);
1929 // To avoid timing problems, we are using locks.
1930 $locked = Lock::acquire('item_insert_content');
1932 Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1935 // Do we already have this content?
1936 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
1937 if (DBA::isResult($item_content)) {
1938 $item['icid'] = $item_content['id'];
1939 Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1940 } elseif (DBA::insert('item-content', $fields)) {
1941 $item['icid'] = DBA::lastInsertId();
1942 Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1944 // This shouldn't happen.
1945 Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1948 Lock::release('item_insert_content');
1953 * @brief Update existing item content entries
1955 * @param array $item The item fields that are to be changed
1956 * @param array $condition The condition for finding the item content entries
1958 * @throws \Exception
1960 private static function updateActivity($item, $condition)
1962 if (empty($item['verb'])) {
1965 $activity_index = self::activityToIndex($item['verb']);
1967 if ($activity_index < 0) {
1971 $fields = ['activity' => $activity_index];
1973 Logger::log('Update activity for ' . json_encode($condition));
1975 DBA::update('item-activity', $fields, $condition, true);
1981 * @brief Update existing item content entries
1983 * @param array $item The item fields that are to be changed
1984 * @param array $condition The condition for finding the item content entries
1985 * @throws \Exception
1987 private static function updateContent($item, $condition)
1989 // We have to select only the fields from the "item-content" table
1991 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1992 if (isset($item[$field])) {
1993 $fields[$field] = $item[$field];
1997 if (empty($fields)) {
1998 // when there are no fields at all, just use the condition
1999 // This is to ensure that we always store content.
2000 $fields = $condition;
2003 Logger::log('Update content for ' . json_encode($condition));
2005 DBA::update('item-content', $fields, $condition, true);
2009 * @brief Distributes public items to the receivers
2011 * @param integer $itemid Item ID that should be added
2012 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2013 * @throws \Exception
2015 public static function distribute($itemid, $signed_text = '')
2017 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2018 $parent = self::selectFirst(['owner-id'], $condition);
2019 if (!DBA::isResult($parent)) {
2023 // Only distribute public items from native networks
2024 $condition = ['id' => $itemid, 'uid' => 0,
2025 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
2026 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2027 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2028 if (!DBA::isResult($item)) {
2032 $origin = $item['origin'];
2035 unset($item['parent']);
2036 unset($item['mention']);
2037 unset($item['wall']);
2038 unset($item['origin']);
2039 unset($item['starred']);
2043 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
2044 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
2045 if (!DBA::isResult($owner)) {
2049 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2050 $contacts = DBA::select('contact', ['uid'], $condition);
2051 while ($contact = DBA::fetch($contacts)) {
2052 if ($contact['uid'] == 0) {
2056 $users[$contact['uid']] = $contact['uid'];
2058 DBA::close($contacts);
2060 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2061 $contacts = DBA::select('contact', ['uid'], $condition);
2062 while ($contact = DBA::fetch($contacts)) {
2063 if ($contact['uid'] == 0) {
2067 $users[$contact['uid']] = $contact['uid'];
2069 DBA::close($contacts);
2071 if (!empty($owner['alias'])) {
2072 $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
2073 $contacts = DBA::select('contact', ['uid'], $condition);
2074 while ($contact = DBA::fetch($contacts)) {
2075 if ($contact['uid'] == 0) {
2079 $users[$contact['uid']] = $contact['uid'];
2081 DBA::close($contacts);
2086 if ($item['uri'] != $item['parent-uri']) {
2087 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2088 while ($parent = self::fetch($parents)) {
2089 $users[$parent['uid']] = $parent['uid'];
2090 if ($parent['origin'] && !$origin) {
2091 $origin_uid = $parent['uid'];
2096 foreach ($users as $uid) {
2097 if ($origin_uid == $uid) {
2098 $item['diaspora_signed_text'] = $signed_text;
2100 self::storeForUser($itemid, $item, $uid);
2105 * @brief Store public items for the receivers
2107 * @param integer $itemid Item ID that should be added
2108 * @param array $item The item entry that will be stored
2109 * @param integer $uid The user that will receive the item entry
2110 * @throws \Exception
2112 private static function storeForUser($itemid, $item, $uid)
2114 $item['uid'] = $uid;
2115 $item['origin'] = 0;
2117 if ($item['uri'] == $item['parent-uri']) {
2118 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2120 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2123 if (empty($item['contact-id'])) {
2124 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2125 if (!DBA::isResult($self)) {
2128 $item['contact-id'] = $self['id'];
2131 /// @todo Handling of "event-id"
2134 if ($item['uri'] == $item['parent-uri']) {
2135 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2136 if (DBA::isResult($contact)) {
2137 $notify = self::isRemoteSelf($contact, $item);
2141 $distributed = self::insert($item, false, $notify, true);
2143 if (!$distributed) {
2144 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
2146 Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
2151 * @brief Add a shadow entry for a given item id that is a thread starter
2153 * We store every public item entry additionally with the user id "0".
2154 * This is used for the community page and for the search.
2155 * It is planned that in the future we will store public item entries only once.
2157 * @param integer $itemid Item ID that should be added
2158 * @throws \Exception
2160 public static function addShadow($itemid)
2162 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2163 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2164 $item = self::selectFirst($fields, $condition);
2166 if (!DBA::isResult($item)) {
2170 // is it already a copy?
2171 if (($itemid == 0) || ($item['uid'] == 0)) {
2175 // Is it a visible public post?
2176 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2180 // is it an entry from a connector? Only add an entry for natively connected networks
2181 if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
2185 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2189 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2191 if (DBA::isResult($item)) {
2192 // Preparing public shadow (removing user specific data)
2195 unset($item['parent']);
2196 unset($item['wall']);
2197 unset($item['mention']);
2198 unset($item['origin']);
2199 unset($item['starred']);
2200 unset($item['postopts']);
2201 unset($item['inform']);
2202 if ($item['uri'] == $item['parent-uri']) {
2203 $item['contact-id'] = $item['owner-id'];
2205 $item['contact-id'] = $item['author-id'];
2208 $public_shadow = self::insert($item, false, false, true);
2210 Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
2215 * @brief Add a shadow entry for a given item id that is a comment
2217 * This function does the same like the function above - but for comments
2219 * @param integer $itemid Item ID that should be added
2220 * @throws \Exception
2222 public static function addShadowPost($itemid)
2224 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2225 if (!DBA::isResult($item)) {
2229 // Is it a toplevel post?
2230 if ($item['id'] == $item['parent']) {
2231 self::addShadow($itemid);
2235 // Is this a shadow entry?
2236 if ($item['uid'] == 0) {
2240 // Is there a shadow parent?
2241 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2245 // Is there already a shadow entry?
2246 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2250 // Save "origin" and "parent" state
2251 $origin = $item['origin'];
2252 $parent = $item['parent'];
2254 // Preparing public shadow (removing user specific data)
2257 unset($item['parent']);
2258 unset($item['wall']);
2259 unset($item['mention']);
2260 unset($item['origin']);
2261 unset($item['starred']);
2262 unset($item['postopts']);
2263 unset($item['inform']);
2264 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2266 $public_shadow = self::insert($item, false, false, true);
2268 Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
2270 // If this was a comment to a Diaspora post we don't get our comment back.
2271 // This means that we have to distribute the comment by ourselves.
2272 if ($origin && self::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
2273 self::distribute($public_shadow);
2278 * Adds a language specification in a "language" element of given $arr.
2279 * Expects "body" element to exist in $arr.
2282 * @throws \Text_LanguageDetect_Exception
2284 private static function addLanguageToItemArray(&$item)
2286 $naked_body = BBCode::toPlaintext($item['body'], false);
2288 $ld = new Text_LanguageDetect();
2289 $ld->setNameMode(2);
2290 $languages = $ld->detect($naked_body, 3);
2292 if (is_array($languages)) {
2293 $item['language'] = json_encode($languages);
2298 * @brief Creates an unique guid out of a given uri
2300 * @param string $uri uri of an item entry
2301 * @param string $host hostname for the GUID prefix
2302 * @return string unique guid
2304 public static function guidFromUri($uri, $host)
2306 // Our regular guid routine is using this kind of prefix as well
2307 // We have to avoid that different routines could accidentally create the same value
2308 $parsed = parse_url($uri);
2310 // We use a hash of the hostname as prefix for the guid
2311 $guid_prefix = hash("crc32", $host);
2313 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2314 unset($parsed["scheme"]);
2316 // Glue it together to be able to make a hash from it
2317 $host_id = implode("/", $parsed);
2319 // We could use any hash algorithm since it isn't a security issue
2320 $host_hash = hash("ripemd128", $host_id);
2322 return $guid_prefix.$host_hash;
2326 * generate an unique URI
2328 * @param integer $uid User id
2329 * @param string $guid An existing GUID (Otherwise it will be generated)
2332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2334 public static function newURI($uid, $guid = "")
2337 $guid = System::createUUID();
2340 return self::getApp()->getBaseURL() . '/objects/' . $guid;
2344 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2346 * This can be used to filter for inactive contacts.
2347 * Only do this for public postings to avoid privacy problems, since poco data is public.
2348 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2350 * @param array $arr Contains the just posted item record
2351 * @throws \Exception
2353 private static function updateContact($arr)
2355 // Unarchive the author
2356 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2357 if (DBA::isResult($contact)) {
2358 Contact::unmarkForArchival($contact);
2361 // Unarchive the contact if it's not our own contact
2362 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2363 if (DBA::isResult($contact)) {
2364 Contact::unmarkForArchival($contact);
2367 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2369 // Is it a forum? Then we don't care about the rules from above
2370 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri"] === $arr["uri"])) {
2371 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2377 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2378 ['id' => $arr['contact-id']]);
2380 // Now do the same for the system wide contacts with uid=0
2381 if (!$arr['private']) {
2382 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2383 ['id' => $arr['owner-id']]);
2385 if ($arr['owner-id'] != $arr['author-id']) {
2386 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2387 ['id' => $arr['author-id']]);
2392 public static function setHashtags(&$item)
2395 $tags = BBCode::getTags($item["body"]);
2398 if (!count($tags)) {
2402 // This sorting is important when there are hashtags that are part of other hashtags
2403 // Otherwise there could be problems with hashtags like #test and #test2
2406 $URLSearchString = "^\[\]";
2408 // All hashtags should point to the home server if "local_tags" is activated
2409 if (Config::get('system', 'local_tags')) {
2410 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2411 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2413 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2414 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2417 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2418 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2420 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2423 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2425 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2428 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2430 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2433 // Repair recursive urls
2434 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2435 "#$2", $item["body"]);
2437 foreach ($tags as $tag) {
2438 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2442 $basetag = str_replace('_',' ',substr($tag,1));
2444 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2446 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2448 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2449 if (strlen($item["tag"])) {
2450 $item["tag"] = ',' . $item["tag"];
2452 $item["tag"] = $newtag . $item["tag"];
2456 // Convert back the masked hashtags
2457 $item["body"] = str_replace("#", "#", $item["body"]);
2460 public static function getGuidById($id)
2462 $item = self::selectFirst(['guid'], ['id' => $id]);
2463 if (DBA::isResult($item)) {
2464 return $item['guid'];
2471 * This function is only used for the old Friendica app on Android that doesn't like paths with guid
2473 * @param string $guid item guid
2474 * @param int $uid user id
2475 * @return array with id and nick of the item with the given guid
2476 * @throws \Exception
2478 public static function getIdAndNickByGuid($guid, $uid = 0)
2484 $uid == local_user();
2487 // Does the given user have this item?
2489 $item = self::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]);
2490 if (DBA::isResult($item)) {
2491 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2492 if (!DBA::isResult($user)) {
2496 $nick = $user['nickname'];
2500 // Or is it anywhere on the server?
2502 $condition = ["`guid` = ? AND `uid` != 0", $guid];
2503 $item = self::selectFirst(['id', 'uid'], $condition);
2504 if (DBA::isResult($item)) {
2505 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
2506 if (!DBA::isResult($user)) {
2510 $nick = $user['nickname'];
2513 return ["nick" => $nick, "id" => $id];
2517 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2520 * @param int $item_id
2521 * @return void true if item was deleted, else false
2522 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2523 * @throws \ImagickException
2525 private static function tagDeliver($uid, $item_id)
2529 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2530 if (!DBA::isResult($user)) {
2534 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2535 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2537 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2538 if (!DBA::isResult($item)) {
2542 $link = Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']);
2545 * Diaspora uses their own hardwired link URL in @-tags
2546 * instead of the one we supply with webfinger
2548 $dlink = Strings::normaliseLink(System::baseUrl() . '/u/' . $user['nickname']);
2550 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2552 foreach ($matches as $mtch) {
2553 if (Strings::compareLink($link, $mtch[1]) || Strings::compareLink($dlink, $mtch[1])) {
2555 Logger::log('mention found: ' . $mtch[2]);
2561 if (($community_page || $prvgroup) &&
2562 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2563 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2565 Logger::log("no-mention top-level post to community or private group. delete.");
2566 DBA::delete('item', ['id' => $item_id]);
2572 $arr = ['item' => $item, 'user' => $user];
2574 Hook::callAll('tagged', $arr);
2576 if (!$community_page && !$prvgroup) {
2581 * tgroup delivery - setup a second delivery chain
2582 * prevent delivery looping - only proceed
2583 * if the message originated elsewhere and is a top-level post
2585 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2589 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2590 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2591 if (!DBA::isResult($self)) {
2595 $owner_id = Contact::getIdForURL($self['url']);
2597 // also reset all the privacy bits to the forum default permissions
2599 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2601 $psid = PermissionSet::fetchIDForPost($user);
2603 $forum_mode = ($prvgroup ? 2 : 1);
2605 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2606 'owner-id' => $owner_id, 'private' => $private, 'psid' => $psid];
2607 self::update($fields, ['id' => $item_id]);
2609 self::updateThread($item_id);
2611 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2614 public static function isRemoteSelf($contact, &$datarray)
2618 if (!$contact['remote_self']) {
2622 // Prevent the forwarding of posts that are forwarded
2623 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2624 Logger::log('Already forwarded', Logger::DEBUG);
2628 // Prevent to forward already forwarded posts
2629 if ($datarray["app"] == $a->getHostName()) {
2630 Logger::log('Already forwarded (second test)', Logger::DEBUG);
2634 // Only forward posts
2635 if ($datarray["verb"] != ACTIVITY_POST) {
2636 Logger::log('No post', Logger::DEBUG);
2640 if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
2641 Logger::log('Not public', Logger::DEBUG);
2645 $datarray2 = $datarray;
2646 Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
2647 if ($contact['remote_self'] == 2) {
2648 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2649 ['uid' => $contact['uid'], 'self' => true]);
2650 if (DBA::isResult($self)) {
2651 $datarray['contact-id'] = $self["id"];
2653 $datarray['owner-name'] = $self["name"];
2654 $datarray['owner-link'] = $self["url"];
2655 $datarray['owner-avatar'] = $self["thumb"];
2657 $datarray['author-name'] = $datarray['owner-name'];
2658 $datarray['author-link'] = $datarray['owner-link'];
2659 $datarray['author-avatar'] = $datarray['owner-avatar'];
2661 unset($datarray['created']);
2662 unset($datarray['edited']);
2664 unset($datarray['network']);
2665 unset($datarray['owner-id']);
2666 unset($datarray['author-id']);
2669 if ($contact['network'] != Protocol::FEED) {
2670 $datarray["guid"] = System::createUUID();
2671 unset($datarray["plink"]);
2672 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2673 $datarray["parent-uri"] = $datarray["uri"];
2674 $datarray["thr-parent"] = $datarray["uri"];
2675 $datarray["extid"] = Protocol::DFRN;
2676 $urlpart = parse_url($datarray2['author-link']);
2677 $datarray["app"] = $urlpart["host"];
2679 $datarray['private'] = 0;
2683 if ($contact['network'] != Protocol::FEED) {
2684 // Store the original post
2685 $result = self::insert($datarray2, false, false);
2686 Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
2688 $datarray["app"] = "Feed";
2692 // Trigger automatic reactions for addons
2693 $datarray['api_source'] = true;
2695 // We have to tell the hooks who we are - this really should be improved
2696 $_SESSION["authenticated"] = true;
2697 $_SESSION["uid"] = $contact['uid'];
2706 * @param array $item
2709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2710 * @throws \ImagickException
2712 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2714 if (Config::get('system', 'disable_embedded')) {
2718 Logger::log('check for photos', Logger::DEBUG);
2719 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2724 $img_start = strpos($orig_body, '[img');
2725 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2726 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2728 while (($img_st_close !== false) && ($img_len !== false)) {
2729 $img_st_close++; // make it point to AFTER the closing bracket
2730 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2732 Logger::log('found photo ' . $image, Logger::DEBUG);
2734 if (stristr($image, $site . '/photo/')) {
2735 // Only embed locally hosted photos
2737 $i = basename($image);
2738 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2739 $x = strpos($i, '-');
2742 $res = substr($i, $x + 1);
2743 $i = substr($i, 0, $x);
2744 $photo = Photo::getPhotoForUser($uid, $i, $res);
2745 if (DBA::isResult($photo)) {
2747 * Check to see if we should replace this photo link with an embedded image
2748 * 1. No need to do so if the photo is public
2749 * 2. If there's a contact-id provided, see if they're in the access list
2750 * for the photo. If so, embed it.
2751 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2752 * permissions, regardless of order but first check to see if they're an exact
2753 * match to save some processing overhead.
2755 if (self::hasPermissions($photo)) {
2757 $recips = self::enumeratePermissions($photo);
2758 if (in_array($cid, $recips)) {
2762 if (self::samePermissions($item, $photo)) {
2768 $photo_img = Photo::getImageForPhoto($photo);
2769 // If a custom width and height were specified, apply before embedding
2770 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2771 Logger::log('scaling photo', Logger::DEBUG);
2773 $width = intval($match[1]);
2774 $height = intval($match[2]);
2776 $photo_img->scaleDown(max($width, $height));
2779 $data = $photo_img->asString();
2780 $type = $photo_img->getType();
2782 Logger::log('replacing photo', Logger::DEBUG);
2783 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2784 Logger::log('replaced: ' . $image, Logger::DATA);
2790 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2791 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2792 if ($orig_body === false) {
2796 $img_start = strpos($orig_body, '[img');
2797 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2798 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2801 $new_body = $new_body . $orig_body;
2806 private static function hasPermissions($obj)
2808 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2809 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2812 private static function samePermissions($obj1, $obj2)
2814 // first part is easy. Check that these are exactly the same.
2815 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2816 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2817 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2818 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2822 // This is harder. Parse all the permissions and compare the resulting set.
2823 $recipients1 = self::enumeratePermissions($obj1);
2824 $recipients2 = self::enumeratePermissions($obj2);
2828 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2829 return ($recipients1 == $recipients2);
2832 // returns an array of contact-ids that are allowed to see this object
2833 public static function enumeratePermissions($obj)
2835 $allow_people = expand_acl($obj['allow_cid']);
2836 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2837 $deny_people = expand_acl($obj['deny_cid']);
2838 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2839 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2840 $deny = array_unique(array_merge($deny_people, $deny_groups));
2841 $recipients = array_diff($recipients, $deny);
2845 public static function getFeedTags($item)
2849 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2851 for ($x = 0; $x < $cnt; $x ++) {
2852 if ($matches[1][$x]) {
2853 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2858 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2860 for ($x = 0; $x < $cnt; $x ++) {
2861 if ($matches[1][$x]) {
2862 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2869 public static function expire($uid, $days, $network = "", $force = false)
2871 if (!$uid || ($days < 1)) {
2875 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2876 $uid, GRAVITY_PARENT];
2879 * $expire_network_only = save your own wall posts
2880 * and just expire conversations started by others
2882 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2884 if ($expire_network_only) {
2885 $condition[0] .= " AND NOT `wall`";
2888 if ($network != "") {
2889 $condition[0] .= " AND `network` = ?";
2890 $condition[] = $network;
2893 * There is an index "uid_network_received" but not "uid_network_created"
2894 * This avoids the creation of another index just for one purpose.
2895 * And it doesn't really matter wether to look at "received" or "created"
2897 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2898 $condition[] = $days;
2900 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2901 $condition[] = $days;
2904 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2906 if (!DBA::isResult($items)) {
2910 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2912 // Forcing expiring of items - but not notes and marked items
2914 $expire_items = true;
2917 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2918 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2919 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2923 while ($item = Item::fetch($items)) {
2924 // don't expire filed items
2926 if (strpos($item['file'], '[') !== false) {
2930 // Only expire posts, not photos and photo comments
2932 if (!$expire_photos && strlen($item['resource-id'])) {
2934 } elseif (!$expire_starred && intval($item['starred'])) {
2936 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2938 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2942 self::deleteById($item['id'], PRIORITY_LOW);
2947 Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2950 public static function firstPostDate($uid, $wall = false)
2952 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2953 $params = ['order' => ['created' => false]];
2954 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2955 if (DBA::isResult($thread)) {
2956 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2962 * @brief add/remove activity to an item
2964 * Toggle activities as like,dislike,attend of an item
2966 * @param string $item_id
2967 * @param string $verb
2968 * Activity verb. One of
2969 * like, unlike, dislike, undislike, attendyes, unattendyes,
2970 * attendno, unattendno, attendmaybe, unattendmaybe
2972 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2973 * @throws \ImagickException
2974 * @hook 'post_local_end'
2976 * 'post_id' => ID of posted item
2978 public static function performLike($item_id, $verb)
2980 if (!local_user() && !remote_user()) {
2987 $activity = ACTIVITY_LIKE;
2991 $activity = ACTIVITY_DISLIKE;
2995 $activity = ACTIVITY_ATTEND;
2999 $activity = ACTIVITY_ATTENDNO;
3002 case 'unattendmaybe':
3003 $activity = ACTIVITY_ATTENDMAYBE;
3006 Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
3010 // Enable activity toggling instead of on/off
3011 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
3013 Logger::log('like: verb ' . $verb . ' item ' . $item_id);
3015 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
3016 if (!DBA::isResult($item)) {
3017 Logger::log('like: unknown item ' . $item_id);
3021 $item_uri = $item['uri'];
3023 $uid = $item['uid'];
3024 if (($uid == 0) && local_user()) {
3025 $uid = local_user();
3028 if (!Security::canWriteToUserWall($uid)) {
3029 Logger::log('like: unable to write on wall ' . $uid);
3033 // Retrieves the local post owner
3034 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
3035 if (!DBA::isResult($owner_self_contact)) {
3036 Logger::log('like: unknown owner ' . $uid);
3040 // Retrieve the current logged in user's public contact
3041 $author_id = public_contact();
3043 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
3044 if (!DBA::isResult($author_contact)) {
3045 Logger::log('like: unknown author ' . $author_id);
3049 // Contact-id is the uid-dependant author contact
3050 if (local_user() == $uid) {
3051 $item_contact_id = $owner_self_contact['id'];
3052 $item_contact = $owner_self_contact;
3054 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3055 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3056 if (!DBA::isResult($item_contact)) {
3057 Logger::log('like: unknown item contact ' . $item_contact_id);
3062 // Look for an existing verb row
3063 // event participation are essentially radio toggles. If you make a subsequent choice,
3064 // we need to eradicate your first choice.
3065 if ($event_verb_flag) {
3066 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3068 // Translate to the index based activity index
3070 foreach ($verbs as $verb) {
3071 $activities[] = self::activityToIndex($verb);
3074 $activities = self::activityToIndex($activity);
3077 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3078 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3080 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3082 // If it exists, mark it as deleted
3083 if (DBA::isResult($like_item)) {
3084 self::deleteById($like_item['id']);
3086 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3091 // Verb is "un-something", just trying to delete existing entries
3092 if (strpos($verb, 'un') === 0) {
3096 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE;
3099 'guid' => System::createUUID(),
3100 'uri' => self::newURI($item['uid']),
3101 'uid' => $item['uid'],
3102 'contact-id' => $item_contact_id,
3103 'wall' => $item['wall'],
3105 'network' => Protocol::DFRN,
3106 'gravity' => GRAVITY_ACTIVITY,
3107 'parent' => $item['id'],
3108 'parent-uri' => $item['uri'],
3109 'thr-parent' => $item['uri'],
3110 'owner-id' => $author_id,
3111 'author-id' => $author_id,
3112 'body' => $activity,
3113 'verb' => $activity,
3114 'object-type' => $objtype,
3115 'allow_cid' => $item['allow_cid'],
3116 'allow_gid' => $item['allow_gid'],
3117 'deny_cid' => $item['deny_cid'],
3118 'deny_gid' => $item['deny_gid'],
3123 $signed = Diaspora::createLikeSignature($uid, $new_item);
3124 if (!empty($signed)) {
3125 $new_item['diaspora_signed_text'] = json_encode($signed);
3128 $new_item_id = self::insert($new_item);
3130 // If the parent item isn't visible then set it to visible
3131 if (!$item['visible']) {
3132 self::update(['visible' => true], ['id' => $item['id']]);
3135 $new_item['id'] = $new_item_id;
3137 Hook::callAll('post_local_end', $new_item);
3142 private static function addThread($itemid, $onlyshadow = false)
3144 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3145 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3146 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3147 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3148 $item = self::selectFirst($fields, $condition);
3150 if (!DBA::isResult($item)) {
3154 $item['iid'] = $itemid;
3157 $result = DBA::insert('thread', $item);
3159 Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3163 private static function updateThread($itemid, $setmention = false)
3165 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3166 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3167 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3168 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3170 $item = self::selectFirst($fields, $condition);
3171 if (!DBA::isResult($item)) {
3176 $item["mention"] = 1;
3183 foreach ($item as $field => $data) {
3184 if (!in_array($field, ["guid"])) {
3185 $fields[$field] = $data;
3189 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3191 Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
3194 private static function deleteThread($itemid, $itemuri = "")
3196 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3197 if (!DBA::isResult($item)) {
3198 Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
3202 $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
3204 Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
3206 if ($itemuri != "") {
3207 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3208 if (!self::exists($condition)) {
3209 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3210 Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
3215 public static function getPermissionsSQLByUserId($owner_id, $remote_verified = false, $groups = null, $remote_cid = null)
3217 $local_user = local_user();
3218 $remote_user = remote_user();
3221 * Construct permissions
3223 * default permissions - anonymous user
3225 $sql = " AND NOT `item`.`private`";
3227 // Profile owner - everything is visible
3228 if ($local_user && ($local_user == $owner_id)) {
3230 } elseif ($remote_user) {
3232 * Authenticated visitor. Unless pre-verified,
3233 * check that the contact belongs to this $owner_id
3234 * and load the groups the visitor belongs to.
3235 * If pre-verified, the caller is expected to have already
3236 * done this and passed the groups into this function.
3238 $set = PermissionSet::get($owner_id, $remote_cid, $groups);
3241 $sql_set = " OR (`item`.`private` IN (1,2) AND `item`.`wall` AND `item`.`psid` IN (" . implode(',', $set) . "))";
3246 $sql = " AND (NOT `item`.`private`" . $sql_set . ")";
3253 * get translated item type
3258 public static function postType($item)
3260 if (!empty($item['event-id'])) {
3261 return L10n::t('event');
3262 } elseif (!empty($item['resource-id'])) {
3263 return L10n::t('photo');
3264 } elseif (!empty($item['verb']) && $item['verb'] !== ACTIVITY_POST) {
3265 return L10n::t('activity');
3266 } elseif ($item['id'] != $item['parent']) {
3267 return L10n::t('comment');
3270 return L10n::t('post');
3274 * Sets the "rendered-html" field of the provided item
3276 * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
3278 * @param array $item
3279 * @param bool $update
3281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3282 * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
3284 public static function putInCache(&$item, $update = false)
3286 $body = $item["body"];
3288 $rendered_hash = defaults($item, 'rendered-hash', '');
3289 $rendered_html = defaults($item, 'rendered-html', '');
3291 if ($rendered_hash == ''
3292 || $rendered_html == ""
3293 || $rendered_hash != hash("md5", $item["body"])
3294 || Config::get("system", "ignore_cache")
3296 $a = self::getApp();
3297 redir_private_images($a, $item);
3299 $item["rendered-html"] = prepare_text($item["body"]);
3300 $item["rendered-hash"] = hash("md5", $item["body"]);
3302 $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
3303 Hook::callAll('put_item_in_cache', $hook_data);
3304 $item['rendered-html'] = $hook_data['rendered-html'];
3305 $item['rendered-hash'] = $hook_data['rendered-hash'];
3308 // Force an update if the generated values differ from the existing ones
3309 if ($rendered_hash != $item["rendered-hash"]) {
3313 // Only compare the HTML when we forcefully ignore the cache
3314 if (Config::get("system", "ignore_cache") && ($rendered_html != $item["rendered-html"])) {
3318 if ($update && !empty($item["id"])) {
3321 'rendered-html' => $item["rendered-html"],
3322 'rendered-hash' => $item["rendered-hash"]
3324 ['id' => $item["id"]]
3329 $item["body"] = $body;
3333 * @brief Given an item array, convert the body element from bbcode to html and add smilie icons.
3334 * If attach is true, also add icons for item attachments.
3336 * @param array $item
3337 * @param boolean $attach
3338 * @param boolean $is_preview
3339 * @return string item body html
3340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3341 * @throws \ImagickException
3342 * @hook prepare_body_init item array before any work
3343 * @hook prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
3344 * @hook prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
3345 * @hook prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
3347 public static function prepareBody(array &$item, $attach = false, $is_preview = false)
3349 $a = self::getApp();
3350 Hook::callAll('prepare_body_init', $item);
3352 // In order to provide theme developers more possibilities, event items
3353 // are treated differently.
3354 if ($item['object-type'] === ACTIVITY_OBJ_EVENT && isset($item['event-id'])) {
3355 $ev = Event::getItemHTML($item);
3359 $tags = Term::populateTagsFromItem($item);
3361 $item['tags'] = $tags['tags'];
3362 $item['hashtags'] = $tags['hashtags'];
3363 $item['mentions'] = $tags['mentions'];
3365 // Compile eventual content filter reasons
3366 $filter_reasons = [];
3367 if (!$is_preview && public_contact() != $item['author-id']) {
3368 if (!empty($item['content-warning']) && (!local_user() || !PConfig::get(local_user(), 'system', 'disable_cw', false))) {
3369 $filter_reasons[] = L10n::t('Content warning: %s', $item['content-warning']);
3374 'filter_reasons' => $filter_reasons
3376 Hook::callAll('prepare_body_content_filter', $hook_data);
3377 $filter_reasons = $hook_data['filter_reasons'];
3381 // Update the cached values if there is no "zrl=..." on the links.
3382 $update = (!local_user() && !remote_user() && ($item["uid"] == 0));
3384 // Or update it if the current viewer is the intented viewer.
3385 if (($item["uid"] == local_user()) && ($item["uid"] != 0)) {
3389 self::putInCache($item, $update);
3390 $s = $item["rendered-html"];
3395 'preview' => $is_preview,
3396 'filter_reasons' => $filter_reasons
3398 Hook::callAll('prepare_body', $hook_data);
3399 $s = $hook_data['html'];
3403 // Replace the blockquotes with quotes that are used in mails.
3404 $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
3405 $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
3412 preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $item['attach'], $matches, PREG_SET_ORDER);
3413 foreach ($matches as $mtch) {
3416 $the_url = Contact::magicLinkById($item['author-id'], $mtch[1]);
3418 if (strpos($mime, 'video') !== false) {
3421 $a->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('videos_head.tpl'), [
3422 '$baseurl' => System::baseUrl(),
3426 $url_parts = explode('/', $the_url);
3427 $id = end($url_parts);
3428 $as .= Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3431 'title' => L10n::t('View Video'),
3438 $filetype = strtolower(substr($mime, 0, strpos($mime, '/')));
3440 $filesubtype = strtolower(substr($mime, strpos($mime, '/') + 1));
3441 $filesubtype = str_replace('.', '-', $filesubtype);
3444 $filesubtype = 'unkn';
3447 $title = Strings::escapeHtml(trim(defaults($mtch, 4, $mtch[1])));
3448 $title .= ' ' . $mtch[2] . ' ' . L10n::t('bytes');
3450 $icon = '<div class="attachtype icon s22 type-' . $filetype . ' subtype-' . $filesubtype . '"></div>';
3451 $as .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" >' . $icon . '</a>';
3455 $s .= '<div class="body-attach">'.$as.'<div class="clear"></div></div>';
3459 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
3460 $x = Map::byCoordinates(trim($item['coord']));
3462 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
3467 // Look for spoiler.
3468 $spoilersearch = '<blockquote class="spoiler">';
3470 // Remove line breaks before the spoiler.
3471 while ((strpos($s, "\n" . $spoilersearch) !== false)) {
3472 $s = str_replace("\n" . $spoilersearch, $spoilersearch, $s);
3474 while ((strpos($s, "<br />" . $spoilersearch) !== false)) {
3475 $s = str_replace("<br />" . $spoilersearch, $spoilersearch, $s);
3478 while ((strpos($s, $spoilersearch) !== false)) {
3479 $pos = strpos($s, $spoilersearch);
3480 $rnd = Strings::getRandomHex(8);
3481 $spoilerreplace = '<br /> <span id="spoiler-wrap-' . $rnd . '" class="spoiler-wrap fakelink" onclick="openClose(\'spoiler-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3482 '<blockquote class="spoiler" id="spoiler-' . $rnd . '" style="display: none;">';
3483 $s = substr($s, 0, $pos) . $spoilerreplace . substr($s, $pos + strlen($spoilersearch));
3486 // Look for quote with author.
3487 $authorsearch = '<blockquote class="author">';
3489 while ((strpos($s, $authorsearch) !== false)) {
3490 $pos = strpos($s, $authorsearch);
3491 $rnd = Strings::getRandomHex(8);
3492 $authorreplace = '<br /> <span id="author-wrap-' . $rnd . '" class="author-wrap fakelink" onclick="openClose(\'author-' . $rnd . '\');">' . L10n::t('Click to open/close') . '</span>'.
3493 '<blockquote class="author" id="author-' . $rnd . '" style="display: block;">';
3494 $s = substr($s, 0, $pos) . $authorreplace . substr($s, $pos + strlen($authorsearch));
3497 // Replace friendica image url size with theme preference.
3498 if (!empty($a->theme_info['item_image_size'])) {
3499 $ps = $a->theme_info['item_image_size'];
3500 $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
3503 $s = HTML::applyContentFilter($s, $filter_reasons);
3505 $hook_data = ['item' => $item, 'html' => $s];
3506 Hook::callAll('prepare_body_final', $hook_data);
3508 return $hook_data['html'];
3512 * get private link for item
3514 * @param array $item
3515 * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3516 * @throws \Exception
3518 public static function getPlink($item)
3520 $a = self::getApp();
3522 if ($a->user['nickname'] != "") {
3524 'href' => "display/" . $item['guid'],
3525 'orig' => "display/" . $item['guid'],
3526 'title' => L10n::t('View on separate page'),
3527 'orig_title' => L10n::t('view on separate page'),
3530 if (!empty($item['plink'])) {
3531 $ret["href"] = $a->removeBaseURL($item['plink']);
3532 $ret["title"] = L10n::t('link to source');
3535 } elseif (!empty($item['plink']) && ($item['private'] != 1)) {
3537 'href' => $item['plink'],
3538 'orig' => $item['plink'],
3539 'title' => L10n::t('link to source'),