4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Group;
21 use Friendica\Model\Term;
22 use Friendica\Object\Image;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\XML;
27 use Friendica\Util\Lock;
29 use Text_LanguageDetect;
31 require_once 'boot.php';
32 require_once 'include/items.php';
33 require_once 'include/text.php';
35 class Item extends BaseObject
37 // Field list that is used to display the items
38 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
39 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
40 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
41 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
42 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
43 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
44 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
45 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
46 'writable', 'self', 'cid', 'alias',
47 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
48 'event-summary', 'event-desc', 'event-location', 'event-type',
49 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
51 // Field list that is used to deliver items via the protocols
52 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
53 'created', 'edited', 'verb', 'object-type', 'object', 'target',
54 'private', 'title', 'body', 'location', 'coord', 'app',
55 'attach', 'tag', 'bookmark', 'deleted', 'extid',
56 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
57 'author-id', 'author-link', 'owner-link', 'contact-uid',
58 'signed_text', 'signature', 'signer'];
60 // Field list for "item-content" table that is mixed with the item table
61 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
62 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
63 'object-type', 'object', 'target-type', 'target', 'plink'];
65 // Field list for "item-content" table that is not present in the "item" table
66 const CONTENT_FIELDLIST = ['language'];
68 // All fields in the item table
69 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
70 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid',
71 'created', 'edited', 'commented', 'received', 'changed', 'verb',
72 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
73 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
74 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
75 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
76 'title', 'content-warning', 'body', 'location', 'coord', 'app',
77 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
78 'author-id', 'author-link', 'author-name', 'author-avatar',
79 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
81 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
82 // The item-activity table only stores the index and needs this array to know the matching activity.
83 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
86 * @brief returns an activity index from an activity string
88 * @param string $activity activity string
89 * @return integer Activity index
91 private static function activityToIndex($activity)
93 $index = array_search($activity, self::ACTIVITIES);
95 if (is_bool($index)) {
103 * @brief returns an activity string from an activity index
105 * @param integer $index activity index
106 * @return string Activity string
108 private static function indexToActivity($index)
110 if (!isset(self::ACTIVITIES[$index])) {
114 return self::ACTIVITIES[$index];
118 * @brief Fetch a single item row
120 * @param mixed $stmt statement object
121 * @return array current row
123 public static function fetch($stmt)
125 $row = dba::fetch($stmt);
131 // ---------------------- Transform item structure data ----------------------
133 // We prefer the data from the user's contact over the public one
134 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
135 ($row['author-link'] == $row['contact-link'])) {
136 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
137 $row['author-avatar'] = $row['contact-avatar'];
139 if (isset($row['author-name']) && !empty($row['contact-name'])) {
140 $row['author-name'] = $row['contact-name'];
144 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
145 ($row['owner-link'] == $row['contact-link'])) {
146 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
147 $row['owner-avatar'] = $row['contact-avatar'];
149 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
150 $row['owner-name'] = $row['contact-name'];
154 // We can always comment on posts from these networks
155 if (array_key_exists('writable', $row) &&
156 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
157 $row['writable'] = true;
160 // ---------------------- Transform item content data ----------------------
162 // Fetch data from the item-content table whenever there is content there
163 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
164 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
165 $row[$field] = $row['internal-item-' . $field];
167 unset($row['internal-item-' . $field]);
170 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
171 $row['verb'] = self::indexToActivity($row['internal-activity']);
172 if (array_key_exists('title', $row)) {
175 if (array_key_exists('body', $row)) {
176 $row['body'] = $row['verb'];
178 if (array_key_exists('object', $row)) {
181 if (array_key_exists('object-type', $row)) {
182 $row['object-type'] = ACTIVITY_OBJ_NOTE;
184 } elseif (in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
185 // Posts don't have an object or target - but having tags or files.
186 // We safe some performance by building tag and file strings only here.
187 // We remove object and target since they aren't used for this type.
188 if (array_key_exists('object', $row)) {
191 if (array_key_exists('target', $row)) {
194 // Build the tag string out of the term entries
195 if (array_key_exists('tag', $row)) {
196 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
199 // Build the file string out of the term entries
200 if (array_key_exists('file', $row)) {
201 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
205 // Remove internal fields
206 unset($row['internal-activity']);
207 unset($row['internal-network']);
208 unset($row['internal-iid']);
209 unset($row['internal-iaid']);
210 unset($row['internal-icid']);
216 * @brief Fills an array with data from an item query
218 * @param object $stmt statement object
219 * @return array Data array
221 public static function inArray($stmt, $do_close = true) {
222 if (is_bool($stmt)) {
227 while ($row = self::fetch($stmt)) {
237 * @brief Check if item data exists
239 * @param array $condition array of fields for condition
241 * @return boolean Are there rows for that condition?
243 public static function exists($condition) {
244 $stmt = self::select(['id'], $condition, ['limit' => 1]);
246 if (is_bool($stmt)) {
249 $retval = (dba::num_rows($stmt) > 0);
258 * Retrieve a single record from the item table for a given user and returns it in an associative array
260 * @brief Retrieve a single record from a table
261 * @param integer $uid User ID
262 * @param array $fields
263 * @param array $condition
264 * @param array $params
268 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
270 $params['uid'] = $uid;
272 if (empty($selected)) {
273 $selected = Item::DISPLAY_FIELDLIST;
276 return self::selectFirst($selected, $condition, $params);
280 * @brief Select rows from the item table for a given user
282 * @param integer $uid User ID
283 * @param array $selected Array of selected fields, empty for all
284 * @param array $condition Array of fields for condition
285 * @param array $params Array of several parameters
287 * @return boolean|object
289 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
291 $params['uid'] = $uid;
293 if (empty($selected)) {
294 $selected = Item::DISPLAY_FIELDLIST;
297 return self::select($selected, $condition, $params);
301 * Retrieve a single record from the item table and returns it in an associative array
303 * @brief Retrieve a single record from a table
304 * @param array $fields
305 * @param array $condition
306 * @param array $params
310 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
312 $params['limit'] = 1;
314 $result = self::select($fields, $condition, $params);
316 if (is_bool($result)) {
319 $row = self::fetch($result);
326 * @brief Select rows from the item table
328 * @param array $selected Array of selected fields, empty for all
329 * @param array $condition Array of fields for condition
330 * @param array $params Array of several parameters
332 * @return boolean|object
334 public static function select(array $selected = [], array $condition = [], $params = [])
339 if (isset($params['uid'])) {
340 $uid = $params['uid'];
344 $fields = self::fieldlist($selected);
346 $select_fields = self::constructSelectFields($fields, $selected);
348 $condition_string = dba::buildCondition($condition);
350 $condition_string = self::addTablesToFields($condition_string, $fields);
353 $condition_string = $condition_string . ' AND ' . self::condition(false);
356 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
358 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
360 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
362 return dba::p($sql, $condition);
366 * @brief Select rows from the starting post in the item table
368 * @param integer $uid User ID
369 * @param array $fields Array of selected fields, empty for all
370 * @param array $condition Array of fields for condition
371 * @param array $params Array of several parameters
373 * @return boolean|object
375 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
377 $params['uid'] = $uid;
379 if (empty($selected)) {
380 $selected = Item::DISPLAY_FIELDLIST;
383 return self::selectThread($selected, $condition, $params);
387 * Retrieve a single record from the starting post in the item table and returns it in an associative array
389 * @brief Retrieve a single record from a table
390 * @param integer $uid User ID
391 * @param array $selected
392 * @param array $condition
393 * @param array $params
397 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
399 $params['uid'] = $uid;
401 if (empty($selected)) {
402 $selected = Item::DISPLAY_FIELDLIST;
405 return self::selectFirstThread($selected, $condition, $params);
409 * Retrieve a single record from the starting post in the item table and returns it in an associative array
411 * @brief Retrieve a single record from a table
412 * @param array $fields
413 * @param array $condition
414 * @param array $params
418 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
420 $params['limit'] = 1;
421 $result = self::selectThread($fields, $condition, $params);
423 if (is_bool($result)) {
426 $row = self::fetch($result);
433 * @brief Select rows from the starting post in the item table
435 * @param array $selected Array of selected fields, empty for all
436 * @param array $condition Array of fields for condition
437 * @param array $params Array of several parameters
439 * @return boolean|object
441 public static function selectThread(array $selected = [], array $condition = [], $params = [])
446 if (isset($params['uid'])) {
447 $uid = $params['uid'];
451 $fields = self::fieldlist($selected);
453 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
454 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
455 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'bookmark',
456 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
458 $select_fields = self::constructSelectFields($fields, $selected);
460 $condition_string = dba::buildCondition($condition);
462 $condition_string = self::addTablesToFields($condition_string, $threadfields);
463 $condition_string = self::addTablesToFields($condition_string, $fields);
466 $condition_string = $condition_string . ' AND ' . self::condition(true);
469 $param_string = dba::buildParameter($params);
470 $param_string = self::addTablesToFields($param_string, $threadfields);
471 $param_string = self::addTablesToFields($param_string, $fields);
473 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
475 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
477 return dba::p($sql, $condition);
481 * @brief Returns a list of fields that are associated with the item table
483 * @return array field list
485 private static function fieldlist($selected)
489 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
490 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
491 'created', 'edited', 'commented', 'received', 'changed', 'postopts',
492 'resource-id', 'event-id', 'tag', 'attach', 'inform',
493 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
494 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
495 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
496 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
497 'network' => 'internal-network', 'icid' => 'internal-icid',
498 'iaid' => 'internal-iaid'];
500 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
502 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
504 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
505 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
507 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
508 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
510 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
511 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
512 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
514 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
516 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
518 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
519 'start' => 'event-start','finish' => 'event-finish',
520 'summary' => 'event-summary','desc' => 'event-desc',
521 'location' => 'event-location', 'type' => 'event-type',
522 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
523 'ignore' => 'event-ignore', 'id' => 'event-id'];
525 $fields['sign'] = ['signed_text', 'signature', 'signer'];
531 * @brief Returns SQL condition for the "select" functions
533 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
535 * @return string SQL condition
537 private static function condition($thread_mode)
540 $master_table = "`thread`";
542 $master_table = "`item`";
544 return "$master_table.`visible` AND NOT $master_table.`deleted` AND NOT $master_table.`moderated` AND (`user-item`.`hidden` IS NULL OR NOT `user-item`.`hidden`) ";
548 * @brief Returns all needed "JOIN" commands for the "select" functions
550 * @param integer $uid User ID
551 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
552 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
554 * @return string The SQL joins for the "select" functions
556 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
559 $master_table = "`thread`";
560 $master_table_key = "`thread`.`iid`";
561 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
563 $master_table = "`item`";
564 $master_table_key = "`item`.`id`";
569 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
570 AND NOT `contact`.`blocked`
571 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
572 OR `contact`.`self` OR (`item`.`id` != `item`.`parent`) OR `contact`.`uid` = 0)
573 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
574 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
575 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
576 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, intval($uid));
578 if (strpos($sql_commands, "`contact`.") !== false) {
579 $joins .= "STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
581 if (strpos($sql_commands, "`author`.") !== false) {
582 $joins .= " STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
584 if (strpos($sql_commands, "`owner`.") !== false) {
585 $joins .= " STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
589 if (strpos($sql_commands, "`group_member`.") !== false) {
590 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
593 if (strpos($sql_commands, "`user`.") !== false) {
594 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
597 if (strpos($sql_commands, "`event`.") !== false) {
598 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
601 if (strpos($sql_commands, "`sign`.") !== false) {
602 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
605 if (strpos($sql_commands, "`item-activity`.") !== false) {
606 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
609 if (strpos($sql_commands, "`item-content`.") !== false) {
610 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
613 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
614 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
617 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
618 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
625 * @brief Add the field list for the "select" functions
627 * @param array $fields The field definition array
628 * @param array $selected The array with the selected fields from the "select" functions
630 * @return string The field list
632 private static function constructSelectFields($fields, $selected)
634 if (!empty($selected)) {
635 $selected[] = 'internal-iid';
636 $selected[] = 'internal-iaid';
637 $selected[] = 'internal-icid';
638 $selected[] = 'internal-network';
641 if (in_array('verb', $selected)) {
642 $selected[] = 'internal-activity';
646 foreach ($fields as $table => $table_fields) {
647 foreach ($table_fields as $field => $select) {
648 if (empty($selected) || in_array($select, $selected)) {
649 if (in_array($select, self::MIXED_CONTENT_FIELDLIST)) {
650 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
652 if (is_int($field)) {
653 $selection[] = "`" . $table . "`.`" . $select . "`";
655 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
660 return implode(", ", $selection);
664 * @brief add table definition to fields in an SQL query
666 * @param string $query SQL query
667 * @param array $fields The field definition array
669 * @return string the changed SQL query
671 private static function addTablesToFields($query, $fields)
673 foreach ($fields as $table => $table_fields) {
674 foreach ($table_fields as $alias => $field) {
675 if (is_int($alias)) {
676 $replace_field = $field;
678 $replace_field = $alias;
681 $search = "/([^\.])`" . $field . "`/i";
682 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
683 $query = preg_replace($search, $replace, $query);
690 * @brief Update existing item entries
692 * @param array $fields The fields that are to be changed
693 * @param array $condition The condition for finding the item entries
695 * In the future we may have to change permissions as well.
696 * Then we had to add the user id as third parameter.
698 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
700 * @return integer|boolean number of affected rows - or "false" if there was an error
702 public static function update(array $fields, array $condition)
704 if (empty($condition) || empty($fields)) {
708 // To ensure the data integrity we do it in an transaction
711 // We cannot simply expand the condition to check for origin entries
712 // The condition needn't to be a simple array but could be a complex condition.
713 // And we have to execute this query before the update to ensure to fetch the same data.
714 $items = dba::select('item', ['id', 'origin', 'uri', 'plink', 'iaid', 'icid'], $condition);
716 $content_fields = [];
717 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
718 if (isset($fields[$field])) {
719 $content_fields[$field] = $fields[$field];
720 unset($fields[$field]);
724 if (array_key_exists('tag', $fields)) {
725 $tags = $fields['tag'];
726 unset($fields['tag']);
731 if (array_key_exists('file', $fields)) {
732 $files = $fields['file'];
733 unset($fields['file']);
738 if (!empty($fields)) {
739 $success = dba::update('item', $fields, $condition);
748 // When there is no content for the "old" item table, this will count the fetched items
749 $rows = dba::affected_rows();
751 while ($item = dba::fetch($items)) {
752 if (!empty($item['plink'])) {
753 $content_fields['plink'] = $item['plink'];
755 if ((self::activityToIndex($item['verb']) >= 0) || !empty($item['iaid'])) {
756 self::updateActivity($content_fields, ['uri' => $item['uri']]);
758 if (empty($item['iaid'])) {
759 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri' => $item['uri']]);
760 if (DBM::is_result($item_activity)) {
761 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
762 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
763 $item_fields[$field] = '';
765 dba::update('item', $item_fields, ['id' => $item['id']]);
767 if (!empty($item['icid']) && !dba::exists('item', ['icid' => $item['icid']])) {
768 dba::delete('item-content', ['id' => $item['icid']]);
773 self::updateContent($content_fields, ['uri' => $item['uri']]);
775 if (empty($item['icid'])) {
776 $item_content = dba::selectFirst('item-content', [], ['uri' => $item['uri']]);
777 if (DBM::is_result($item_content)) {
778 $item_fields = ['icid' => $item_content['id']];
779 // Clear all fields in the item table that have a content in the item-content table
780 foreach ($item_content as $field => $content) {
781 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
782 $item_fields[$field] = '';
785 dba::update('item', $item_fields, ['id' => $item['id']]);
791 Term::insertFromTagFieldByItemId($item['id'], $tags);
794 if (!empty($files)) {
795 Term::insertFromFileFieldByItemId($item['id'], $files);
798 self::updateThread($item['id']);
800 // We only need to notfiy others when it is an original entry from us.
801 // Only call the notifier when the item has some content relevant change.
802 if ($item['origin'] && in_array('edited', array_keys($fields))) {
803 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
813 * @brief Delete an item and notify others about it - if it was ours
815 * @param array $condition The condition for finding the item entries
816 * @param integer $priority Priority for the notification
818 public static function delete($condition, $priority = PRIORITY_HIGH)
820 $items = dba::select('item', ['id'], $condition);
821 while ($item = dba::fetch($items)) {
822 self::deleteById($item['id'], $priority);
828 * @brief Delete an item for an user and notify others about it - if it was ours
830 * @param array $condition The condition for finding the item entries
831 * @param integer $uid User who wants to delete this item
833 public static function deleteForUser($condition, $uid)
839 $items = dba::select('item', ['id', 'uid'], $condition);
840 while ($item = dba::fetch($items)) {
841 // "Deleting" global items just means hiding them
842 if ($item['uid'] == 0) {
843 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
844 } elseif ($item['uid'] == $uid) {
845 self::deleteById($item['id'], PRIORITY_HIGH);
847 logger('Wrong ownership. Not deleting item ' . $item['id']);
854 * @brief Delete an item and notify others about it - if it was ours
856 * @param integer $item_id Item ID that should be delete
857 * @param integer $priority Priority for the notification
859 * @return boolean success
861 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
863 // locate item to be deleted
864 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
865 'deleted', 'file', 'resource-id', 'event-id', 'attach',
866 'verb', 'object-type', 'object', 'target', 'contact-id'];
867 $item = self::selectFirst($fields, ['id' => $item_id]);
868 if (!DBM::is_result($item)) {
869 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
873 if ($item['deleted']) {
874 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
878 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
879 if (!DBM::is_result($parent)) {
880 $parent = ['origin' => false];
883 // clean up categories and tags so they don't end up as orphans
886 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
888 foreach ($matches as $mtch) {
889 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
895 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
897 foreach ($matches as $mtch) {
898 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
903 * If item is a link to a photo resource, nuke all the associated photos
904 * (visitors will not have photo resources)
905 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
906 * generate a resource-id and therefore aren't intimately linked to the item.
908 if (strlen($item['resource-id'])) {
909 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
912 // If item is a link to an event, delete the event.
913 if (intval($item['event-id'])) {
914 Event::delete($item['event-id']);
917 // If item has attachments, drop them
918 foreach (explode(", ", $item['attach']) as $attach) {
919 preg_match("|attach/(\d+)|", $attach, $matches);
920 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
923 // Delete tags that had been attached to other items
924 self::deleteTagsFromItem($item);
926 // Set the item to "deleted"
927 // This erasing of item content is superfluous for items with a matching item-content.
928 // But for the next time we will still have old content in the item table.
929 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
930 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
931 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
932 dba::update('item', $item_fields, ['id' => $item['id']]);
934 Term::insertFromTagFieldByItemId($item['id'], '');
935 Term::insertFromFileFieldByItemId($item['id'], '');
936 self::deleteThread($item['id'], $item['parent-uri']);
938 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
939 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
942 // If it's the parent of a comment thread, kill all the kids
943 if ($item['id'] == $item['parent']) {
944 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
947 // Is it our comment and/or our thread?
948 if ($item['origin'] || $parent['origin']) {
950 // When we delete the original post we will delete all existing copies on the server as well
951 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
953 // send the notification upstream/downstream
954 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
955 } elseif ($item['uid'] != 0) {
957 // When we delete just our local user copy of an item, we have to set a marker to hide it
958 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
959 if (DBM::is_result($global_item)) {
960 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
964 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
969 private static function deleteTagsFromItem($item)
971 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
975 $xo = XML::parseString($item["object"], false);
976 $xt = XML::parseString($item["target"], false);
978 if ($xt->type != ACTIVITY_OBJ_NOTE) {
982 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
983 if (!DBM::is_result($i)) {
987 // For tags, the owner cannot remove the tag on the author's copy of the post.
988 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
989 $author_copy = $item["origin"];
991 if (($owner_remove && $author_copy) || !$owner_remove) {
995 $tags = explode(',', $i["tag"]);
998 foreach ($tags as $tag) {
999 if (trim($tag) !== trim($xo->body)) {
1000 $newtags[] = trim($tag);
1004 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1007 private static function guid($item, $notify)
1009 $guid = notags(trim($item['guid']));
1011 if (!empty($guid)) {
1016 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1017 // We add the hash of our own host because our host is the original creator of the post.
1018 $prefix_host = get_app()->get_hostname();
1022 // We are only storing the post so we create a GUID from the original hostname.
1023 if (!empty($item['author-link'])) {
1024 $parsed = parse_url($item['author-link']);
1025 if (!empty($parsed['host'])) {
1026 $prefix_host = $parsed['host'];
1030 if (empty($prefix_host) && !empty($item['plink'])) {
1031 $parsed = parse_url($item['plink']);
1032 if (!empty($parsed['host'])) {
1033 $prefix_host = $parsed['host'];
1037 if (empty($prefix_host) && !empty($item['uri'])) {
1038 $parsed = parse_url($item['uri']);
1039 if (!empty($parsed['host'])) {
1040 $prefix_host = $parsed['host'];
1044 // Is it in the format data@host.tld? - Used for mail contacts
1045 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1046 $mailparts = explode('@', $item['author-link']);
1047 $prefix_host = array_pop($mailparts);
1051 if (!empty($item['plink'])) {
1052 $guid = self::guidFromUri($item['plink'], $prefix_host);
1053 } elseif (!empty($item['uri'])) {
1054 $guid = self::guidFromUri($item['uri'], $prefix_host);
1056 $guid = get_guid(32, hash('crc32', $prefix_host));
1062 private static function contactId($item)
1064 $contact_id = (int)$item["contact-id"];
1066 if (!empty($contact_id)) {
1069 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1071 * First we are looking for a suitable contact that matches with the author of the post
1072 * This is done only for comments
1074 if ($item['parent-uri'] != $item['uri']) {
1075 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1078 // If not present then maybe the owner was found
1079 if ($contact_id == 0) {
1080 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1083 // Still missing? Then use the "self" contact of the current user
1084 if ($contact_id == 0) {
1085 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1086 if (DBM::is_result($self)) {
1087 $contact_id = $self["id"];
1090 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1095 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1099 // If it is a posting where users should get notifications, then define it as wall posting
1102 $item['type'] = 'wall';
1103 $item['origin'] = 1;
1104 $item['network'] = NETWORK_DFRN;
1105 $item['protocol'] = PROTOCOL_DFRN;
1107 if (is_int($notify)) {
1108 $priority = $notify;
1110 $priority = PRIORITY_HIGH;
1113 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1116 $item['guid'] = self::guid($item, $notify);
1117 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1119 // Store conversation data
1120 $item = Conversation::insert($item);
1123 * If a Diaspora signature structure was passed in, pull it out of the
1124 * item array and set it aside for later storage.
1128 if (x($item, 'dsprsig')) {
1129 $encoded_signature = $item['dsprsig'];
1130 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1131 unset($item['dsprsig']);
1134 if (!empty($item['diaspora_signed_text'])) {
1135 $diaspora_signed_text = $item['diaspora_signed_text'];
1136 unset($item['diaspora_signed_text']);
1138 $diaspora_signed_text = '';
1141 // Converting the plink
1142 /// @TODO Check if this is really still needed
1143 if ($item['network'] == NETWORK_OSTATUS) {
1144 if (isset($item['plink'])) {
1145 $item['plink'] = OStatus::convertHref($item['plink']);
1146 } elseif (isset($item['uri'])) {
1147 $item['plink'] = OStatus::convertHref($item['uri']);
1151 if (!empty($item['thr-parent'])) {
1152 $item['parent-uri'] = $item['thr-parent'];
1155 $item['type'] = defaults($item, 'type', 'remote');
1157 if (isset($item['gravity'])) {
1158 $item['gravity'] = intval($item['gravity']);
1159 } elseif ($item['parent-uri'] === $item['uri']) {
1160 $item['gravity'] = GRAVITY_PARENT;
1161 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1162 $item['gravity'] = GRAVITY_COMMENT;
1163 } elseif ($item['type'] == 'activity') {
1164 $item['gravity'] = GRAVITY_ACTIVITY;
1166 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1167 logger('Unknown gravity for verb: ' . $item['verb'] . ' - type: ' . $item['type'], LOGGER_DEBUG);
1170 $uid = intval($item['uid']);
1172 // check for create date and expire time
1173 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1175 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1176 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1177 $expire_interval = $user['expire'];
1180 if (($expire_interval > 0) && !empty($item['created'])) {
1181 $expire_date = time() - ($expire_interval * 86400);
1182 $created_date = strtotime($item['created']);
1183 if ($created_date < $expire_date) {
1184 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1190 * Do we already have this item?
1191 * We have to check several networks since Friendica posts could be repeated
1192 * via OStatus (maybe Diasporsa as well)
1194 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1195 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1196 trim($item['uri']), $item['uid'],
1197 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1198 $existing = self::selectFirst(['id', 'network'], $condition);
1199 if (DBM::is_result($existing)) {
1200 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1202 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1205 return $existing["id"];
1209 self::addLanguageToItemArray($item);
1211 $item['wall'] = intval(defaults($item, 'wall', 0));
1212 $item['extid'] = trim(defaults($item, 'extid', ''));
1213 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1214 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1215 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1216 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1217 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1218 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1219 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1220 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1221 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1222 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1223 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1224 $item['title'] = trim(defaults($item, 'title', ''));
1225 $item['location'] = trim(defaults($item, 'location', ''));
1226 $item['coord'] = trim(defaults($item, 'coord', ''));
1227 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1228 $item['deleted'] = 0;
1229 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1230 $item['verb'] = trim(defaults($item, 'verb', ''));
1231 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1232 $item['object'] = trim(defaults($item, 'object', ''));
1233 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1234 $item['target'] = trim(defaults($item, 'target', ''));
1235 $item['plink'] = trim(defaults($item, 'plink', ''));
1236 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1237 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1238 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1239 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1240 $item['private'] = intval(defaults($item, 'private', 0));
1241 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
1242 $item['body'] = trim(defaults($item, 'body', ''));
1243 $item['tag'] = trim(defaults($item, 'tag', ''));
1244 $item['attach'] = trim(defaults($item, 'attach', ''));
1245 $item['app'] = trim(defaults($item, 'app', ''));
1246 $item['origin'] = intval(defaults($item, 'origin', 0));
1247 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1248 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1249 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1250 $item['inform'] = trim(defaults($item, 'inform', ''));
1251 $item['file'] = trim(defaults($item, 'file', ''));
1253 // When there is no content then we don't post it
1254 if ($item['body'].$item['title'] == '') {
1255 logger('No body, no title.');
1259 // Items cannot be stored before they happen ...
1260 if ($item['created'] > DateTimeFormat::utcNow()) {
1261 $item['created'] = DateTimeFormat::utcNow();
1264 // We haven't invented time travel by now.
1265 if ($item['edited'] > DateTimeFormat::utcNow()) {
1266 $item['edited'] = DateTimeFormat::utcNow();
1269 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
1270 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
1273 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1275 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1276 $item["contact-id"] = self::contactId($item);
1278 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1279 'photo' => $item['author-avatar'], 'network' => $item['network']];
1281 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1283 if (Contact::isBlocked($item["author-id"])) {
1284 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1288 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1289 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1291 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1293 if (Contact::isBlocked($item["owner-id"])) {
1294 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1298 // These fields aren't stored anymore in the item table, they are fetched upon request
1299 unset($item['author-link']);
1300 unset($item['author-name']);
1301 unset($item['author-avatar']);
1303 unset($item['owner-link']);
1304 unset($item['owner-name']);
1305 unset($item['owner-avatar']);
1307 if ($item['network'] == NETWORK_PHANTOM) {
1308 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1310 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
1311 if (!empty($contact['network'])) {
1312 $item['network'] = $contact["network"];
1314 $item['network'] = NETWORK_DFRN;
1316 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1319 // Checking if there is already an item with the same guid
1320 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1321 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1322 if (self::exists($condition)) {
1323 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1327 // Check for hashtags in the body and repair or add hashtag links
1328 self::setHashtags($item);
1330 $item['thr-parent'] = $item['parent-uri'];
1338 if ($item['parent-uri'] === $item['uri']) {
1340 $parent_deleted = 0;
1341 $allow_cid = $item['allow_cid'];
1342 $allow_gid = $item['allow_gid'];
1343 $deny_cid = $item['deny_cid'];
1344 $deny_gid = $item['deny_gid'];
1345 $notify_type = 'wall-new';
1347 // find the parent and snarf the item id and ACLs
1348 // and anything else we need to inherit
1350 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1351 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1352 'wall', 'private', 'forum_mode', 'origin'];
1353 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1354 $params = ['order' => ['id' => false]];
1355 $parent = self::selectFirst($fields, $condition, $params);
1357 if (DBM::is_result($parent)) {
1358 // is the new message multi-level threaded?
1359 // even though we don't support it now, preserve the info
1360 // and re-attach to the conversation parent.
1362 if ($parent['uri'] != $parent['parent-uri']) {
1363 $item['parent-uri'] = $parent['parent-uri'];
1365 $condition = ['uri' => $item['parent-uri'],
1366 'parent-uri' => $item['parent-uri'],
1367 'uid' => $item['uid']];
1368 $params = ['order' => ['id' => false]];
1369 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1371 if (DBM::is_result($toplevel_parent)) {
1372 $parent = $toplevel_parent;
1376 $parent_id = $parent['id'];
1377 $parent_deleted = $parent['deleted'];
1378 $allow_cid = $parent['allow_cid'];
1379 $allow_gid = $parent['allow_gid'];
1380 $deny_cid = $parent['deny_cid'];
1381 $deny_gid = $parent['deny_gid'];
1382 $item['wall'] = $parent['wall'];
1383 $notify_type = 'comment-new';
1386 * If the parent is private, force privacy for the entire conversation
1387 * This differs from the above settings as it subtly allows comments from
1388 * email correspondents to be private even if the overall thread is not.
1390 if ($parent['private']) {
1391 $item['private'] = $parent['private'];
1395 * Edge case. We host a public forum that was originally posted to privately.
1396 * The original author commented, but as this is a comment, the permissions
1397 * weren't fixed up so it will still show the comment as private unless we fix it here.
1399 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1400 $item['private'] = 0;
1403 // If its a post from myself then tag the thread as "mention"
1404 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1405 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1406 if (DBM::is_result($user)) {
1407 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1408 $self_id = Contact::getIdForURL($self, 0, true);
1409 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1410 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1411 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1412 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1417 * Allow one to see reply tweets from status.net even when
1418 * we don't have or can't see the original post.
1420 if ($force_parent) {
1421 logger('$force_parent=true, reply converted to top-level post.');
1423 $item['parent-uri'] = $item['uri'];
1424 $item['gravity'] = GRAVITY_PARENT;
1426 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1430 $parent_deleted = 0;
1434 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1435 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1436 if (self::exists($condition)) {
1437 logger('duplicated item with the same uri found. '.print_r($item,true));
1441 // On Friendica and Diaspora the GUID is unique
1442 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1443 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1444 if (self::exists($condition)) {
1445 logger('duplicated item with the same guid found. '.print_r($item,true));
1449 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1450 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1451 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1452 if (self::exists($condition)) {
1453 logger('duplicated item with the same body found. '.print_r($item,true));
1458 // Is this item available in the global items (with uid=0)?
1459 if ($item["uid"] == 0) {
1460 $item["global"] = true;
1462 // Set the global flag on all items if this was a global item entry
1463 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1465 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1469 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1472 $private = $item['private'];
1475 $item["allow_cid"] = $allow_cid;
1476 $item["allow_gid"] = $allow_gid;
1477 $item["deny_cid"] = $deny_cid;
1478 $item["deny_gid"] = $deny_gid;
1479 $item["private"] = $private;
1480 $item["deleted"] = $parent_deleted;
1482 // Fill the cache field
1483 put_item_in_cache($item);
1486 Addon::callHooks('post_local', $item);
1488 Addon::callHooks('post_remote', $item);
1491 // This array field is used to trigger some automatic reactions
1492 // It is mainly used in the "post_local" hook.
1493 unset($item['api_source']);
1495 if (x($item, 'cancel')) {
1496 logger('post cancelled by addon.');
1501 * Check for already added items.
1502 * There is a timing issue here that sometimes creates double postings.
1503 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1505 if ($item["uid"] == 0) {
1506 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1507 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1512 logger('' . print_r($item,true), LOGGER_DATA);
1514 if (array_key_exists('tag', $item)) {
1515 $tags = $item['tag'];
1516 unset($item['tag']);
1521 if (array_key_exists('file', $item)) {
1522 $files = $item['file'];
1523 unset($item['file']);
1528 // We are doing this outside of the transaction to avoid timing problems
1529 if (!self::insertActivity($item)) {
1530 self::insertContent($item);
1534 $ret = dba::insert('item', $item);
1536 // When the item was successfully stored we fetch the ID of the item.
1537 if (DBM::is_result($ret)) {
1538 $current_post = dba::lastInsertId();
1540 // This can happen - for example - if there are locking timeouts.
1543 // Store the data into a spool file so that we can try again later.
1545 // At first we restore the Diaspora signature that we removed above.
1546 if (isset($encoded_signature)) {
1547 $item['dsprsig'] = $encoded_signature;
1550 // Now we store the data in the spool directory
1551 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1552 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1554 $spoolpath = get_spoolpath();
1555 if ($spoolpath != "") {
1556 $spool = $spoolpath.'/'.$file;
1557 file_put_contents($spool, json_encode($item));
1558 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1563 if ($current_post == 0) {
1564 // This is one of these error messages that never should occur.
1565 logger("couldn't find created item - we better quit now.");
1570 // How much entries have we created?
1571 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1572 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1575 // There are duplicates. We delete our just created entry.
1576 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1578 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1579 dba::delete('item', ['id' => $current_post]);
1582 } elseif ($entries == 0) {
1583 // This really should never happen since we quit earlier if there were problems.
1584 logger("Something is terribly wrong. We haven't found our created entry.");
1589 logger('created item '.$current_post);
1590 self::updateContact($item);
1592 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1593 $parent_id = $current_post;
1597 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1599 $item['id'] = $current_post;
1600 $item['parent'] = $parent_id;
1602 // update the commented timestamp on the parent
1603 // Only update "commented" if it is really a comment
1604 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1605 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1607 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1612 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1613 * We can check for this condition when we decode and encode the stuff again.
1615 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1616 $dsprsig->signature = base64_decode($dsprsig->signature);
1617 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1620 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1621 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1624 if (!empty($diaspora_signed_text)) {
1625 // Formerly we stored the signed text, the signature and the author in different fields.
1626 // We now store the raw data so that we are more flexible.
1627 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1630 $deleted = self::tagDeliver($item['uid'], $current_post);
1633 * current post can be deleted if is for a community page and no mention are
1636 if (!$deleted && !$dontcache) {
1637 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1638 if (DBM::is_result($posted_item)) {
1640 Addon::callHooks('post_local_end', $posted_item);
1642 Addon::callHooks('post_remote_end', $posted_item);
1645 logger('new item not found in DB, id ' . $current_post);
1649 if ($item['parent-uri'] === $item['uri']) {
1650 self::addThread($current_post);
1652 self::updateThread($parent_id);
1658 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1659 * This is not perfect - but a workable solution until we found the reason for the problem.
1661 if (!empty($tags)) {
1662 Term::insertFromTagFieldByItemId($current_post, $tags);
1665 if (!empty($files)) {
1666 Term::insertFromFileFieldByItemId($current_post, $files);
1669 if ($item['parent-uri'] === $item['uri']) {
1670 self::addShadow($current_post);
1672 self::addShadowPost($current_post);
1675 check_user_notification($current_post);
1678 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1679 } elseif (!empty($parent) && $parent['origin']) {
1680 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1683 return $current_post;
1687 * @brief Insert a new item content entry
1689 * @param array $item The item fields that are to be inserted
1691 private static function insertActivity(&$item)
1693 $activity_index = self::activityToIndex($item['verb']);
1695 if ($activity_index < 0) {
1699 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1700 'uri-hash' => hash('sha1', $item['uri']) . hash('ripemd160', $item['uri'])];
1702 $saved_item = $item;
1704 // We just remove everything that is content
1705 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1706 unset($item[$field]);
1709 // To avoid timing problems, we are using locks.
1710 $locked = Lock::set('item_insert_activity');
1712 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1715 // Do we already have this content?
1716 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri' => $item['uri']]);
1717 if (DBM::is_result($item_activity)) {
1718 $item['iaid'] = $item_activity['id'];
1719 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1720 } elseif (dba::insert('item-activity', $fields)) {
1721 $item['iaid'] = dba::lastInsertId();
1722 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1724 // This shouldn't happen. But if it does, we simply store it in the item-content table
1725 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1726 $item = $saved_item;
1730 Lock::remove('item_insert_activity');
1736 * @brief Insert a new item content entry
1738 * @param array $item The item fields that are to be inserted
1740 private static function insertContent(&$item)
1742 $fields = ['uri' => $item['uri'], 'plink' => $item['plink'],
1743 'uri-plink-hash' => hash('sha1', $item['plink']).hash('sha1', $item['uri'])];
1745 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1746 if (isset($item[$field])) {
1747 $fields[$field] = $item[$field];
1748 unset($item[$field]);
1752 // To avoid timing problems, we are using locks.
1753 $locked = Lock::set('item_insert_content');
1755 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1758 // Do we already have this content?
1759 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $item['uri']]);
1760 if (DBM::is_result($item_content)) {
1761 $item['icid'] = $item_content['id'];
1762 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1763 } elseif (dba::insert('item-content', $fields)) {
1764 $item['icid'] = dba::lastInsertId();
1765 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1767 // By setting the ICID value through the worker we should avoid timing problems.
1768 // When the locking works, this shouldn't be needed. But better be prepared.
1769 Worker::add(PRIORITY_HIGH, 'SetItemContentID', $item['uri']);
1770 logger('Could not insert content for URI ' . $item['uri'] . ' - trying asynchronously');
1773 Lock::remove('item_insert_content');
1778 * @brief Set the item content id for a given URI
1780 * @param string $uri The item URI
1782 public static function setICIDforURI($uri)
1784 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $uri]);
1785 if (DBM::is_result($item_content)) {
1786 dba::update('item', ['icid' => $item_content['id']], ['icid' => 0, 'uri' => $uri]);
1787 logger('Asynchronously set item content id for URI ' . $uri . ' (' . $item_content['id'] . ') - Affected: '. (int)dba::affected_rows());
1789 logger('No item-content found for URI ' . $uri);
1794 * @brief Update existing item content entries
1796 * @param array $item The item fields that are to be changed
1797 * @param array $condition The condition for finding the item content entries
1799 private static function updateActivity($item, $condition)
1801 if (empty($item['verb'])) {
1804 $activity_index = self::activityToIndex($item['verb']);
1806 if ($activity_index < 0) {
1810 $fields = ['activity' => $activity_index,
1811 'uri-hash' => hash('sha1', $condition['uri']) . hash('ripemd160', $condition['uri'])];
1813 logger('Update activity for URI ' . $condition['uri']);
1815 dba::update('item-activity', $fields, $condition, true);
1821 * @brief Update existing item content entries
1823 * @param array $item The item fields that are to be changed
1824 * @param array $condition The condition for finding the item content entries
1826 private static function updateContent($item, $condition)
1828 // We have to select only the fields from the "item-content" table
1830 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1831 if (isset($item[$field])) {
1832 $fields[$field] = $item[$field];
1836 if (empty($fields)) {
1837 // when there are no fields at all, just use the condition
1838 // This is to ensure that we always store content.
1839 $fields = $condition;
1842 if (!empty($item['plink'])) {
1843 $fields['uri-plink-hash'] = hash('sha1', $item['plink']) . hash('sha1', $condition['uri']);
1845 // Ensure that we don't delete the plink
1846 unset($fields['plink']);
1849 logger('Update content for URI ' . $condition['uri']);
1851 dba::update('item-content', $fields, $condition, true);
1855 * @brief Distributes public items to the receivers
1857 * @param integer $itemid Item ID that should be added
1858 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1860 public static function distribute($itemid, $signed_text = '')
1862 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1863 $parent = self::selectFirst(['owner-id'], $condition);
1864 if (!DBM::is_result($parent)) {
1868 // Only distribute public items from native networks
1869 $condition = ['id' => $itemid, 'uid' => 0,
1870 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1871 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1872 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1873 if (!DBM::is_result($item)) {
1878 unset($item['parent']);
1879 unset($item['mention']);
1880 unset($item['wall']);
1881 unset($item['origin']);
1882 unset($item['starred']);
1886 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1887 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1888 $contacts = dba::select('contact', ['uid'], $condition);
1889 while ($contact = dba::fetch($contacts)) {
1890 $users[$contact['uid']] = $contact['uid'];
1895 if ($item['uri'] != $item['parent-uri']) {
1896 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1897 while ($parent = dba::fetch($parents)) {
1898 $users[$parent['uid']] = $parent['uid'];
1899 if ($parent['origin'] && !$item['origin']) {
1900 $origin_uid = $parent['uid'];
1905 foreach ($users as $uid) {
1906 if ($origin_uid == $uid) {
1907 $item['diaspora_signed_text'] = $signed_text;
1909 self::storeForUser($itemid, $item, $uid);
1914 * @brief Store public items for the receivers
1916 * @param integer $itemid Item ID that should be added
1917 * @param array $item The item entry that will be stored
1918 * @param integer $uid The user that will receive the item entry
1920 private static function storeForUser($itemid, $item, $uid)
1922 $item['uid'] = $uid;
1923 $item['origin'] = 0;
1925 if ($item['uri'] == $item['parent-uri']) {
1926 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1928 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1931 if (empty($item['contact-id'])) {
1932 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1933 if (!DBM::is_result($self)) {
1936 $item['contact-id'] = $self['id'];
1939 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1940 $item['type'] = 'remote-comment';
1941 } elseif ($item['type'] == 'wall') {
1942 $item['type'] = 'remote';
1945 /// @todo Handling of "event-id"
1948 if ($item['uri'] == $item['parent-uri']) {
1949 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1950 if (DBM::is_result($contact)) {
1951 $notify = self::isRemoteSelf($contact, $item);
1955 $distributed = self::insert($item, false, $notify, true);
1957 if (!$distributed) {
1958 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1960 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1965 * @brief Add a shadow entry for a given item id that is a thread starter
1967 * We store every public item entry additionally with the user id "0".
1968 * This is used for the community page and for the search.
1969 * It is planned that in the future we will store public item entries only once.
1971 * @param integer $itemid Item ID that should be added
1973 public static function addShadow($itemid)
1975 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
1976 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1977 $item = self::selectFirst($fields, $condition);
1979 if (!DBM::is_result($item)) {
1983 // is it already a copy?
1984 if (($itemid == 0) || ($item['uid'] == 0)) {
1988 // Is it a visible public post?
1989 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1993 // is it an entry from a connector? Only add an entry for natively connected networks
1994 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
1998 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2002 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2004 if (DBM::is_result($item)) {
2005 // Preparing public shadow (removing user specific data)
2008 unset($item['parent']);
2009 unset($item['wall']);
2010 unset($item['mention']);
2011 unset($item['origin']);
2012 unset($item['starred']);
2013 if ($item['uri'] == $item['parent-uri']) {
2014 $item['contact-id'] = $item['owner-id'];
2016 $item['contact-id'] = $item['author-id'];
2019 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
2020 $item['type'] = 'remote-comment';
2021 } elseif ($item['type'] == 'wall') {
2022 $item['type'] = 'remote';
2025 $public_shadow = self::insert($item, false, false, true);
2027 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2032 * @brief Add a shadow entry for a given item id that is a comment
2034 * This function does the same like the function above - but for comments
2036 * @param integer $itemid Item ID that should be added
2038 public static function addShadowPost($itemid)
2040 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2041 if (!DBM::is_result($item)) {
2045 // Is it a toplevel post?
2046 if ($item['id'] == $item['parent']) {
2047 self::addShadow($itemid);
2051 // Is this a shadow entry?
2052 if ($item['uid'] == 0) {
2056 // Is there a shadow parent?
2057 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2061 // Is there already a shadow entry?
2062 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2066 // Save "origin" and "parent" state
2067 $origin = $item['origin'];
2068 $parent = $item['parent'];
2070 // Preparing public shadow (removing user specific data)
2073 unset($item['parent']);
2074 unset($item['wall']);
2075 unset($item['mention']);
2076 unset($item['origin']);
2077 unset($item['starred']);
2078 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2080 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
2081 $item['type'] = 'remote-comment';
2082 } elseif ($item['type'] == 'wall') {
2083 $item['type'] = 'remote';
2086 $public_shadow = self::insert($item, false, false, true);
2088 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2090 // If this was a comment to a Diaspora post we don't get our comment back.
2091 // This means that we have to distribute the comment by ourselves.
2092 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2093 self::distribute($public_shadow);
2098 * Adds a language specification in a "language" element of given $arr.
2099 * Expects "body" element to exist in $arr.
2101 private static function addLanguageToItemArray(&$item)
2103 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
2105 $ld = new Text_LanguageDetect();
2106 $ld->setNameMode(2);
2107 $languages = $ld->detect($naked_body, 3);
2109 if (is_array($languages)) {
2110 $item['language'] = json_encode($languages);
2115 * @brief Creates an unique guid out of a given uri
2117 * @param string $uri uri of an item entry
2118 * @param string $host hostname for the GUID prefix
2119 * @return string unique guid
2121 public static function guidFromUri($uri, $host)
2123 // Our regular guid routine is using this kind of prefix as well
2124 // We have to avoid that different routines could accidentally create the same value
2125 $parsed = parse_url($uri);
2127 // We use a hash of the hostname as prefix for the guid
2128 $guid_prefix = hash("crc32", $host);
2130 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2131 unset($parsed["scheme"]);
2133 // Glue it together to be able to make a hash from it
2134 $host_id = implode("/", $parsed);
2136 // We could use any hash algorithm since it isn't a security issue
2137 $host_hash = hash("ripemd128", $host_id);
2139 return $guid_prefix.$host_hash;
2143 * generate an unique URI
2145 * @param integer $uid User id
2146 * @param string $guid An existing GUID (Otherwise it will be generated)
2150 public static function newURI($uid, $guid = "")
2153 $guid = get_guid(32);
2156 $hostname = self::getApp()->get_hostname();
2158 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
2160 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2166 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2168 * This can be used to filter for inactive contacts.
2169 * Only do this for public postings to avoid privacy problems, since poco data is public.
2170 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2172 * @param array $arr Contains the just posted item record
2174 private static function updateContact($arr)
2176 // Unarchive the author
2177 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2178 if (DBM::is_result($contact)) {
2179 Contact::unmarkForArchival($contact);
2182 // Unarchive the contact if it's not our own contact
2183 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2184 if (DBM::is_result($contact)) {
2185 Contact::unmarkForArchival($contact);
2188 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
2190 // Is it a forum? Then we don't care about the rules from above
2191 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2192 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2198 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2199 ['id' => $arr['contact-id']]);
2201 // Now do the same for the system wide contacts with uid=0
2202 if (!$arr['private']) {
2203 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2204 ['id' => $arr['owner-id']]);
2206 if ($arr['owner-id'] != $arr['author-id']) {
2207 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2208 ['id' => $arr['author-id']]);
2213 public static function setHashtags(&$item)
2216 $tags = get_tags($item["body"]);
2219 if (!count($tags)) {
2223 // This sorting is important when there are hashtags that are part of other hashtags
2224 // Otherwise there could be problems with hashtags like #test and #test2
2227 $URLSearchString = "^\[\]";
2229 // All hashtags should point to the home server if "local_tags" is activated
2230 if (Config::get('system', 'local_tags')) {
2231 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2232 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2234 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2235 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2238 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2239 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2241 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2244 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2246 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2249 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2251 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2254 // Repair recursive urls
2255 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2256 "#$2", $item["body"]);
2258 foreach ($tags as $tag) {
2259 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2263 $basetag = str_replace('_',' ',substr($tag,1));
2265 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2267 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2269 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2270 if (strlen($item["tag"])) {
2271 $item["tag"] = ','.$item["tag"];
2273 $item["tag"] = $newtag.$item["tag"];
2277 // Convert back the masked hashtags
2278 $item["body"] = str_replace("#", "#", $item["body"]);
2281 public static function getGuidById($id)
2283 $item = self::selectFirst(['guid'], ['id' => $id]);
2284 if (DBM::is_result($item)) {
2285 return $item['guid'];
2291 public static function getIdAndNickByGuid($guid, $uid = 0)
2297 $uid == local_user();
2300 // Does the given user have this item?
2302 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2303 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2304 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2305 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2306 if (DBM::is_result($item)) {
2308 $nick = $item["nickname"];
2312 // Or is it anywhere on the server?
2314 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2315 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2316 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2317 AND NOT `item`.`private` AND `item`.`wall`
2318 AND `item`.`guid` = ?", $guid);
2319 if (DBM::is_result($item)) {
2321 $nick = $item["nickname"];
2324 return ["nick" => $nick, "id" => $id];
2328 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2330 * @param int $item_id
2331 * @return bool true if item was deleted, else false
2333 private static function tagDeliver($uid, $item_id)
2337 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2338 if (!DBM::is_result($user)) {
2342 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2343 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2345 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2346 if (!DBM::is_result($item)) {
2350 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2353 * Diaspora uses their own hardwired link URL in @-tags
2354 * instead of the one we supply with webfinger
2356 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2358 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2360 foreach ($matches as $mtch) {
2361 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2363 logger('mention found: ' . $mtch[2]);
2369 if (($community_page || $prvgroup) &&
2370 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2371 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2373 logger("no-mention top-level post to community or private group. delete.");
2374 dba::delete('item', ['id' => $item_id]);
2380 $arr = ['item' => $item, 'user' => $user];
2382 Addon::callHooks('tagged', $arr);
2384 if (!$community_page && !$prvgroup) {
2389 * tgroup delivery - setup a second delivery chain
2390 * prevent delivery looping - only proceed
2391 * if the message originated elsewhere and is a top-level post
2393 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2397 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2398 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2399 if (!DBM::is_result($self)) {
2403 $owner_id = Contact::getIdForURL($self['url']);
2405 // also reset all the privacy bits to the forum default permissions
2407 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2409 $forum_mode = ($prvgroup ? 2 : 1);
2411 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2412 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2413 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2414 dba::update('item', $fields, ['id' => $item_id]);
2416 self::updateThread($item_id);
2418 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2421 public static function isRemoteSelf($contact, &$datarray)
2425 if (!$contact['remote_self']) {
2429 // Prevent the forwarding of posts that are forwarded
2430 if ($datarray["extid"] == NETWORK_DFRN) {
2431 logger('Already forwarded', LOGGER_DEBUG);
2435 // Prevent to forward already forwarded posts
2436 if ($datarray["app"] == $a->get_hostname()) {
2437 logger('Already forwarded (second test)', LOGGER_DEBUG);
2441 // Only forward posts
2442 if ($datarray["verb"] != ACTIVITY_POST) {
2443 logger('No post', LOGGER_DEBUG);
2447 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2448 logger('Not public', LOGGER_DEBUG);
2452 $datarray2 = $datarray;
2453 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2454 if ($contact['remote_self'] == 2) {
2455 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2456 ['uid' => $contact['uid'], 'self' => true]);
2457 if (DBM::is_result($self)) {
2458 $datarray['contact-id'] = $self["id"];
2460 $datarray['owner-name'] = $self["name"];
2461 $datarray['owner-link'] = $self["url"];
2462 $datarray['owner-avatar'] = $self["thumb"];
2464 $datarray['author-name'] = $datarray['owner-name'];
2465 $datarray['author-link'] = $datarray['owner-link'];
2466 $datarray['author-avatar'] = $datarray['owner-avatar'];
2468 unset($datarray['created']);
2469 unset($datarray['edited']);
2471 unset($datarray['network']);
2472 unset($datarray['owner-id']);
2473 unset($datarray['author-id']);
2476 if ($contact['network'] != NETWORK_FEED) {
2477 $datarray["guid"] = get_guid(32);
2478 unset($datarray["plink"]);
2479 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2480 $datarray["parent-uri"] = $datarray["uri"];
2481 $datarray["thr-parent"] = $datarray["uri"];
2482 $datarray["extid"] = NETWORK_DFRN;
2483 $urlpart = parse_url($datarray2['author-link']);
2484 $datarray["app"] = $urlpart["host"];
2486 $datarray['private'] = 0;
2490 if ($contact['network'] != NETWORK_FEED) {
2491 // Store the original post
2492 $result = self::insert($datarray2, false, false);
2493 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2495 $datarray["app"] = "Feed";
2499 // Trigger automatic reactions for addons
2500 $datarray['api_source'] = true;
2502 // We have to tell the hooks who we are - this really should be improved
2503 $_SESSION["authenticated"] = true;
2504 $_SESSION["uid"] = $contact['uid'];
2513 * @param array $item
2517 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2519 if (Config::get('system', 'disable_embedded')) {
2523 logger('check for photos', LOGGER_DEBUG);
2524 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2529 $img_start = strpos($orig_body, '[img');
2530 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2531 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2533 while (($img_st_close !== false) && ($img_len !== false)) {
2534 $img_st_close++; // make it point to AFTER the closing bracket
2535 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2537 logger('found photo ' . $image, LOGGER_DEBUG);
2539 if (stristr($image, $site . '/photo/')) {
2540 // Only embed locally hosted photos
2542 $i = basename($image);
2543 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2544 $x = strpos($i, '-');
2547 $res = substr($i, $x + 1);
2548 $i = substr($i, 0, $x);
2549 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2550 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2551 if (DBM::is_result($photo)) {
2553 * Check to see if we should replace this photo link with an embedded image
2554 * 1. No need to do so if the photo is public
2555 * 2. If there's a contact-id provided, see if they're in the access list
2556 * for the photo. If so, embed it.
2557 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2558 * permissions, regardless of order but first check to see if they're an exact
2559 * match to save some processing overhead.
2561 if (self::hasPermissions($photo)) {
2563 $recips = self::enumeratePermissions($photo);
2564 if (in_array($cid, $recips)) {
2568 if (self::samePermissions($item, $photo)) {
2574 $data = $photo['data'];
2575 $type = $photo['type'];
2577 // If a custom width and height were specified, apply before embedding
2578 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2579 logger('scaling photo', LOGGER_DEBUG);
2581 $width = intval($match[1]);
2582 $height = intval($match[2]);
2584 $Image = new Image($data, $type);
2585 if ($Image->isValid()) {
2586 $Image->scaleDown(max($width, $height));
2587 $data = $Image->asString();
2588 $type = $Image->getType();
2592 logger('replacing photo', LOGGER_DEBUG);
2593 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2594 logger('replaced: ' . $image, LOGGER_DATA);
2600 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2601 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2602 if ($orig_body === false) {
2606 $img_start = strpos($orig_body, '[img');
2607 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2608 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2611 $new_body = $new_body . $orig_body;
2616 private static function hasPermissions($obj)
2618 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2619 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2622 private static function samePermissions($obj1, $obj2)
2624 // first part is easy. Check that these are exactly the same.
2625 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2626 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2627 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2628 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2632 // This is harder. Parse all the permissions and compare the resulting set.
2633 $recipients1 = self::enumeratePermissions($obj1);
2634 $recipients2 = self::enumeratePermissions($obj2);
2638 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2639 return ($recipients1 == $recipients2);
2642 // returns an array of contact-ids that are allowed to see this object
2643 private static function enumeratePermissions($obj)
2645 $allow_people = expand_acl($obj['allow_cid']);
2646 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2647 $deny_people = expand_acl($obj['deny_cid']);
2648 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2649 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2650 $deny = array_unique(array_merge($deny_people, $deny_groups));
2651 $recipients = array_diff($recipients, $deny);
2655 public static function getFeedTags($item)
2659 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2661 for ($x = 0; $x < $cnt; $x ++) {
2662 if ($matches[1][$x]) {
2663 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2668 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2670 for ($x = 0; $x < $cnt; $x ++) {
2671 if ($matches[1][$x]) {
2672 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2679 public static function expire($uid, $days, $network = "", $force = false)
2681 if (!$uid || ($days < 1)) {
2685 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2686 $uid, GRAVITY_PARENT];
2689 * $expire_network_only = save your own wall posts
2690 * and just expire conversations started by others
2692 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2694 if ($expire_network_only) {
2695 $condition[0] .= " AND NOT `wall`";
2698 if ($network != "") {
2699 $condition[0] .= " AND `network` = ?";
2700 $condition[] = $network;
2703 * There is an index "uid_network_received" but not "uid_network_created"
2704 * This avoids the creation of another index just for one purpose.
2705 * And it doesn't really matter wether to look at "received" or "created"
2707 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2708 $condition[] = $days;
2710 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2711 $condition[] = $days;
2714 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2716 if (!DBM::is_result($items)) {
2720 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2722 // Forcing expiring of items - but not notes and marked items
2724 $expire_items = true;
2727 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2728 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2729 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2733 while ($item = Item::fetch($items)) {
2734 // don't expire filed items
2736 if (strpos($item['file'], '[') !== false) {
2740 // Only expire posts, not photos and photo comments
2742 if (!$expire_photos && strlen($item['resource-id'])) {
2744 } elseif (!$expire_starred && intval($item['starred'])) {
2746 } elseif (!$expire_notes && $item['type'] == 'note') {
2748 } elseif (!$expire_items && $item['type'] != 'note') {
2752 self::deleteById($item['id'], PRIORITY_LOW);
2757 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2760 public static function firstPostDate($uid, $wall = false)
2762 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2763 $params = ['order' => ['created' => false]];
2764 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2765 if (DBM::is_result($thread)) {
2766 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2772 * @brief add/remove activity to an item
2774 * Toggle activities as like,dislike,attend of an item
2776 * @param string $item_id
2777 * @param string $verb
2778 * Activity verb. One of
2779 * like, unlike, dislike, undislike, attendyes, unattendyes,
2780 * attendno, unattendno, attendmaybe, unattendmaybe
2781 * @hook 'post_local_end'
2783 * 'post_id' => ID of posted item
2785 public static function performLike($item_id, $verb)
2787 if (!local_user() && !remote_user()) {
2794 $activity = ACTIVITY_LIKE;
2798 $activity = ACTIVITY_DISLIKE;
2802 $activity = ACTIVITY_ATTEND;
2806 $activity = ACTIVITY_ATTENDNO;
2809 case 'unattendmaybe':
2810 $activity = ACTIVITY_ATTENDMAYBE;
2813 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2817 // Enable activity toggling instead of on/off
2818 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2820 logger('like: verb ' . $verb . ' item ' . $item_id);
2822 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2823 if (!DBM::is_result($item)) {
2824 logger('like: unknown item ' . $item_id);
2828 $item_uri = $item['uri'];
2830 $uid = $item['uid'];
2831 if (($uid == 0) && local_user()) {
2832 $uid = local_user();
2835 if (!can_write_wall($uid)) {
2836 logger('like: unable to write on wall ' . $uid);
2840 // Retrieves the local post owner
2841 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2842 if (!DBM::is_result($owner_self_contact)) {
2843 logger('like: unknown owner ' . $uid);
2847 // Retrieve the current logged in user's public contact
2848 $author_id = public_contact();
2850 $author_contact = dba::selectFirst('contact', ['url'], ['id' => $author_id]);
2851 if (!DBM::is_result($author_contact)) {
2852 logger('like: unknown author ' . $author_id);
2856 // Contact-id is the uid-dependant author contact
2857 if (local_user() == $uid) {
2858 $item_contact_id = $owner_self_contact['id'];
2859 $item_contact = $owner_self_contact;
2861 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2862 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2863 if (!DBM::is_result($item_contact)) {
2864 logger('like: unknown item contact ' . $item_contact_id);
2869 // Look for an existing verb row
2870 // event participation are essentially radio toggles. If you make a subsequent choice,
2871 // we need to eradicate your first choice.
2872 if ($event_verb_flag) {
2873 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2875 // Translate to the index based activity index
2877 foreach ($verbs as $verb) {
2878 $activities[] = self::activityToIndex($verb);
2881 $activities = self::activityToIndex($activity);
2884 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2885 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
2887 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2889 // If it exists, mark it as deleted
2890 if (DBM::is_result($like_item)) {
2891 // Already voted, undo it
2892 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2893 /// @todo Consider using self::update - but before doing so, check the side effects
2894 dba::update('item', $fields, ['id' => $like_item['id']]);
2896 // Clean up the Diaspora signatures for this like
2897 dba::delete('sign', ['iid' => $like_item['id']]);
2899 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
2901 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2906 // Verb is "un-something", just trying to delete existing entries
2907 if (strpos($verb, 'un') === 0) {
2911 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2914 'guid' => get_guid(32),
2915 'uri' => self::newURI($item['uid']),
2916 'uid' => $item['uid'],
2917 'contact-id' => $item_contact_id,
2918 'type' => 'activity',
2919 'wall' => $item['wall'],
2921 'gravity' => GRAVITY_ACTIVITY,
2922 'parent' => $item['id'],
2923 'parent-uri' => $item['uri'],
2924 'thr-parent' => $item['uri'],
2925 'owner-id' => $item['owner-id'],
2926 'author-id' => $author_id,
2927 'body' => $activity,
2928 'verb' => $activity,
2929 'object-type' => $objtype,
2930 'allow_cid' => $item['allow_cid'],
2931 'allow_gid' => $item['allow_gid'],
2932 'deny_cid' => $item['deny_cid'],
2933 'deny_gid' => $item['deny_gid'],
2938 $new_item_id = self::insert($new_item);
2940 // If the parent item isn't visible then set it to visible
2941 if (!$item['visible']) {
2942 self::update(['visible' => true], ['id' => $item['id']]);
2945 // Save the author information for the like in case we need to relay to Diaspora
2946 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2948 $new_item['id'] = $new_item_id;
2950 Addon::callHooks('post_local_end', $new_item);
2952 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2957 private static function addThread($itemid, $onlyshadow = false)
2959 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2960 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2961 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2962 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2963 $item = self::selectFirst($fields, $condition);
2965 if (!DBM::is_result($item)) {
2969 $item['iid'] = $itemid;
2972 $result = dba::insert('thread', $item);
2974 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2978 private static function updateThread($itemid, $setmention = false)
2980 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed',
2981 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2982 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
2983 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2985 $item = self::selectFirst($fields, $condition);
2986 if (!DBM::is_result($item)) {
2991 $item["mention"] = 1;
2998 foreach ($item as $field => $data) {
2999 if (!in_array($field, ["guid"])) {
3000 $fields[$field] = $data;
3004 $result = dba::update('thread', $fields, ['iid' => $itemid]);
3006 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3009 private static function deleteThread($itemid, $itemuri = "")
3011 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3012 if (!DBM::is_result($item)) {
3013 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3017 // Using dba::delete at this time could delete the associated item entries
3018 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3020 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3022 if ($itemuri != "") {
3023 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3024 if (!self::exists($condition)) {
3025 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3026 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);