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 (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
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']]);
771 } elseif (!empty($item['icid'])) {
772 dba::update('item', ['icid' => null], ['id' => $item['id']]);
774 if (!dba::exists('item', ['icid' => $item['icid']])) {
775 dba::delete('item-content', ['id' => $item['icid']]);
779 self::updateContent($content_fields, ['uri' => $item['uri']]);
781 if (empty($item['icid'])) {
782 $item_content = dba::selectFirst('item-content', [], ['uri' => $item['uri']]);
783 if (DBM::is_result($item_content)) {
784 $item_fields = ['icid' => $item_content['id']];
785 // Clear all fields in the item table that have a content in the item-content table
786 foreach ($item_content as $field => $content) {
787 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
788 $item_fields[$field] = '';
791 dba::update('item', $item_fields, ['id' => $item['id']]);
797 Term::insertFromTagFieldByItemId($item['id'], $tags);
800 if (!empty($files)) {
801 Term::insertFromFileFieldByItemId($item['id'], $files);
804 self::updateThread($item['id']);
806 // We only need to notfiy others when it is an original entry from us.
807 // Only call the notifier when the item has some content relevant change.
808 if ($item['origin'] && in_array('edited', array_keys($fields))) {
809 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
819 * @brief Delete an item and notify others about it - if it was ours
821 * @param array $condition The condition for finding the item entries
822 * @param integer $priority Priority for the notification
824 public static function delete($condition, $priority = PRIORITY_HIGH)
826 $items = dba::select('item', ['id'], $condition);
827 while ($item = dba::fetch($items)) {
828 self::deleteById($item['id'], $priority);
834 * @brief Delete an item for an user and notify others about it - if it was ours
836 * @param array $condition The condition for finding the item entries
837 * @param integer $uid User who wants to delete this item
839 public static function deleteForUser($condition, $uid)
845 $items = dba::select('item', ['id', 'uid'], $condition);
846 while ($item = dba::fetch($items)) {
847 // "Deleting" global items just means hiding them
848 if ($item['uid'] == 0) {
849 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
850 } elseif ($item['uid'] == $uid) {
851 self::deleteById($item['id'], PRIORITY_HIGH);
853 logger('Wrong ownership. Not deleting item ' . $item['id']);
860 * @brief Delete an item and notify others about it - if it was ours
862 * @param integer $item_id Item ID that should be delete
863 * @param integer $priority Priority for the notification
865 * @return boolean success
867 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
869 // locate item to be deleted
870 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
871 'deleted', 'file', 'resource-id', 'event-id', 'attach',
872 'verb', 'object-type', 'object', 'target', 'contact-id'];
873 $item = self::selectFirst($fields, ['id' => $item_id]);
874 if (!DBM::is_result($item)) {
875 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
879 if ($item['deleted']) {
880 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
884 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
885 if (!DBM::is_result($parent)) {
886 $parent = ['origin' => false];
889 // clean up categories and tags so they don't end up as orphans
892 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
894 foreach ($matches as $mtch) {
895 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
901 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
903 foreach ($matches as $mtch) {
904 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
909 * If item is a link to a photo resource, nuke all the associated photos
910 * (visitors will not have photo resources)
911 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
912 * generate a resource-id and therefore aren't intimately linked to the item.
914 if (strlen($item['resource-id'])) {
915 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
918 // If item is a link to an event, delete the event.
919 if (intval($item['event-id'])) {
920 Event::delete($item['event-id']);
923 // If item has attachments, drop them
924 foreach (explode(", ", $item['attach']) as $attach) {
925 preg_match("|attach/(\d+)|", $attach, $matches);
926 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
929 // Delete tags that had been attached to other items
930 self::deleteTagsFromItem($item);
932 // Set the item to "deleted"
933 // This erasing of item content is superfluous for items with a matching item-content.
934 // But for the next time we will still have old content in the item table.
935 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
936 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
937 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
938 dba::update('item', $item_fields, ['id' => $item['id']]);
940 Term::insertFromTagFieldByItemId($item['id'], '');
941 Term::insertFromFileFieldByItemId($item['id'], '');
942 self::deleteThread($item['id'], $item['parent-uri']);
944 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
945 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
948 // If it's the parent of a comment thread, kill all the kids
949 if ($item['id'] == $item['parent']) {
950 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
953 // Is it our comment and/or our thread?
954 if ($item['origin'] || $parent['origin']) {
956 // When we delete the original post we will delete all existing copies on the server as well
957 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
959 // send the notification upstream/downstream
960 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
961 } elseif ($item['uid'] != 0) {
963 // When we delete just our local user copy of an item, we have to set a marker to hide it
964 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
965 if (DBM::is_result($global_item)) {
966 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
970 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
975 private static function deleteTagsFromItem($item)
977 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
981 $xo = XML::parseString($item["object"], false);
982 $xt = XML::parseString($item["target"], false);
984 if ($xt->type != ACTIVITY_OBJ_NOTE) {
988 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
989 if (!DBM::is_result($i)) {
993 // For tags, the owner cannot remove the tag on the author's copy of the post.
994 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
995 $author_copy = $item["origin"];
997 if (($owner_remove && $author_copy) || !$owner_remove) {
1001 $tags = explode(',', $i["tag"]);
1004 foreach ($tags as $tag) {
1005 if (trim($tag) !== trim($xo->body)) {
1006 $newtags[] = trim($tag);
1010 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1013 private static function guid($item, $notify)
1015 $guid = notags(trim($item['guid']));
1017 if (!empty($guid)) {
1022 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1023 // We add the hash of our own host because our host is the original creator of the post.
1024 $prefix_host = get_app()->get_hostname();
1028 // We are only storing the post so we create a GUID from the original hostname.
1029 if (!empty($item['author-link'])) {
1030 $parsed = parse_url($item['author-link']);
1031 if (!empty($parsed['host'])) {
1032 $prefix_host = $parsed['host'];
1036 if (empty($prefix_host) && !empty($item['plink'])) {
1037 $parsed = parse_url($item['plink']);
1038 if (!empty($parsed['host'])) {
1039 $prefix_host = $parsed['host'];
1043 if (empty($prefix_host) && !empty($item['uri'])) {
1044 $parsed = parse_url($item['uri']);
1045 if (!empty($parsed['host'])) {
1046 $prefix_host = $parsed['host'];
1050 // Is it in the format data@host.tld? - Used for mail contacts
1051 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1052 $mailparts = explode('@', $item['author-link']);
1053 $prefix_host = array_pop($mailparts);
1057 if (!empty($item['plink'])) {
1058 $guid = self::guidFromUri($item['plink'], $prefix_host);
1059 } elseif (!empty($item['uri'])) {
1060 $guid = self::guidFromUri($item['uri'], $prefix_host);
1062 $guid = get_guid(32, hash('crc32', $prefix_host));
1068 private static function contactId($item)
1070 $contact_id = (int)$item["contact-id"];
1072 if (!empty($contact_id)) {
1075 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1077 * First we are looking for a suitable contact that matches with the author of the post
1078 * This is done only for comments
1080 if ($item['parent-uri'] != $item['uri']) {
1081 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1084 // If not present then maybe the owner was found
1085 if ($contact_id == 0) {
1086 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1089 // Still missing? Then use the "self" contact of the current user
1090 if ($contact_id == 0) {
1091 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1092 if (DBM::is_result($self)) {
1093 $contact_id = $self["id"];
1096 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1101 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1105 // If it is a posting where users should get notifications, then define it as wall posting
1108 $item['type'] = 'wall';
1109 $item['origin'] = 1;
1110 $item['network'] = NETWORK_DFRN;
1111 $item['protocol'] = PROTOCOL_DFRN;
1113 if (is_int($notify)) {
1114 $priority = $notify;
1116 $priority = PRIORITY_HIGH;
1119 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1122 $item['guid'] = self::guid($item, $notify);
1123 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1125 // Store conversation data
1126 $item = Conversation::insert($item);
1129 * If a Diaspora signature structure was passed in, pull it out of the
1130 * item array and set it aside for later storage.
1134 if (x($item, 'dsprsig')) {
1135 $encoded_signature = $item['dsprsig'];
1136 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1137 unset($item['dsprsig']);
1140 if (!empty($item['diaspora_signed_text'])) {
1141 $diaspora_signed_text = $item['diaspora_signed_text'];
1142 unset($item['diaspora_signed_text']);
1144 $diaspora_signed_text = '';
1147 // Converting the plink
1148 /// @TODO Check if this is really still needed
1149 if ($item['network'] == NETWORK_OSTATUS) {
1150 if (isset($item['plink'])) {
1151 $item['plink'] = OStatus::convertHref($item['plink']);
1152 } elseif (isset($item['uri'])) {
1153 $item['plink'] = OStatus::convertHref($item['uri']);
1157 if (!empty($item['thr-parent'])) {
1158 $item['parent-uri'] = $item['thr-parent'];
1161 $item['type'] = defaults($item, 'type', 'remote');
1163 if (isset($item['gravity'])) {
1164 $item['gravity'] = intval($item['gravity']);
1165 } elseif ($item['parent-uri'] === $item['uri']) {
1166 $item['gravity'] = GRAVITY_PARENT;
1167 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1168 $item['gravity'] = GRAVITY_COMMENT;
1169 } elseif ($item['type'] == 'activity') {
1170 $item['gravity'] = GRAVITY_ACTIVITY;
1172 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1173 logger('Unknown gravity for verb: ' . $item['verb'] . ' - type: ' . $item['type'], LOGGER_DEBUG);
1176 $uid = intval($item['uid']);
1178 // check for create date and expire time
1179 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1181 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1182 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1183 $expire_interval = $user['expire'];
1186 if (($expire_interval > 0) && !empty($item['created'])) {
1187 $expire_date = time() - ($expire_interval * 86400);
1188 $created_date = strtotime($item['created']);
1189 if ($created_date < $expire_date) {
1190 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1196 * Do we already have this item?
1197 * We have to check several networks since Friendica posts could be repeated
1198 * via OStatus (maybe Diasporsa as well)
1200 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1201 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1202 trim($item['uri']), $item['uid'],
1203 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1204 $existing = self::selectFirst(['id', 'network'], $condition);
1205 if (DBM::is_result($existing)) {
1206 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1208 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1211 return $existing["id"];
1215 self::addLanguageToItemArray($item);
1217 $item['wall'] = intval(defaults($item, 'wall', 0));
1218 $item['extid'] = trim(defaults($item, 'extid', ''));
1219 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1220 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1221 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1222 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1223 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1224 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1225 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1226 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1227 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1228 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1229 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1230 $item['title'] = trim(defaults($item, 'title', ''));
1231 $item['location'] = trim(defaults($item, 'location', ''));
1232 $item['coord'] = trim(defaults($item, 'coord', ''));
1233 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1234 $item['deleted'] = 0;
1235 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1236 $item['verb'] = trim(defaults($item, 'verb', ''));
1237 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1238 $item['object'] = trim(defaults($item, 'object', ''));
1239 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1240 $item['target'] = trim(defaults($item, 'target', ''));
1241 $item['plink'] = trim(defaults($item, 'plink', ''));
1242 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1243 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1244 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1245 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1246 $item['private'] = intval(defaults($item, 'private', 0));
1247 $item['bookmark'] = intval(defaults($item, 'bookmark', 0));
1248 $item['body'] = trim(defaults($item, 'body', ''));
1249 $item['tag'] = trim(defaults($item, 'tag', ''));
1250 $item['attach'] = trim(defaults($item, 'attach', ''));
1251 $item['app'] = trim(defaults($item, 'app', ''));
1252 $item['origin'] = intval(defaults($item, 'origin', 0));
1253 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1254 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1255 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1256 $item['inform'] = trim(defaults($item, 'inform', ''));
1257 $item['file'] = trim(defaults($item, 'file', ''));
1259 // When there is no content then we don't post it
1260 if ($item['body'].$item['title'] == '') {
1261 logger('No body, no title.');
1265 // Items cannot be stored before they happen ...
1266 if ($item['created'] > DateTimeFormat::utcNow()) {
1267 $item['created'] = DateTimeFormat::utcNow();
1270 // We haven't invented time travel by now.
1271 if ($item['edited'] > DateTimeFormat::utcNow()) {
1272 $item['edited'] = DateTimeFormat::utcNow();
1275 if (($item['author-link'] == "") && ($item['owner-link'] == "")) {
1276 logger("Both author-link and owner-link are empty. Called by: " . System::callstack(), LOGGER_DEBUG);
1279 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1281 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1282 $item["contact-id"] = self::contactId($item);
1284 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1285 'photo' => $item['author-avatar'], 'network' => $item['network']];
1287 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1289 if (Contact::isBlocked($item["author-id"])) {
1290 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1294 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1295 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1297 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1299 if (Contact::isBlocked($item["owner-id"])) {
1300 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1304 // These fields aren't stored anymore in the item table, they are fetched upon request
1305 unset($item['author-link']);
1306 unset($item['author-name']);
1307 unset($item['author-avatar']);
1309 unset($item['owner-link']);
1310 unset($item['owner-name']);
1311 unset($item['owner-avatar']);
1313 if ($item['network'] == NETWORK_PHANTOM) {
1314 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1316 $contact = Contact::getDetailsByURL($item['author-link'], $item['uid']);
1317 if (!empty($contact['network'])) {
1318 $item['network'] = $contact["network"];
1320 $item['network'] = NETWORK_DFRN;
1322 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1325 // Checking if there is already an item with the same guid
1326 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1327 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1328 if (self::exists($condition)) {
1329 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1333 // Check for hashtags in the body and repair or add hashtag links
1334 self::setHashtags($item);
1336 $item['thr-parent'] = $item['parent-uri'];
1344 if ($item['parent-uri'] === $item['uri']) {
1346 $parent_deleted = 0;
1347 $allow_cid = $item['allow_cid'];
1348 $allow_gid = $item['allow_gid'];
1349 $deny_cid = $item['deny_cid'];
1350 $deny_gid = $item['deny_gid'];
1351 $notify_type = 'wall-new';
1353 // find the parent and snarf the item id and ACLs
1354 // and anything else we need to inherit
1356 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1357 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1358 'wall', 'private', 'forum_mode', 'origin'];
1359 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1360 $params = ['order' => ['id' => false]];
1361 $parent = self::selectFirst($fields, $condition, $params);
1363 if (DBM::is_result($parent)) {
1364 // is the new message multi-level threaded?
1365 // even though we don't support it now, preserve the info
1366 // and re-attach to the conversation parent.
1368 if ($parent['uri'] != $parent['parent-uri']) {
1369 $item['parent-uri'] = $parent['parent-uri'];
1371 $condition = ['uri' => $item['parent-uri'],
1372 'parent-uri' => $item['parent-uri'],
1373 'uid' => $item['uid']];
1374 $params = ['order' => ['id' => false]];
1375 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1377 if (DBM::is_result($toplevel_parent)) {
1378 $parent = $toplevel_parent;
1382 $parent_id = $parent['id'];
1383 $parent_deleted = $parent['deleted'];
1384 $allow_cid = $parent['allow_cid'];
1385 $allow_gid = $parent['allow_gid'];
1386 $deny_cid = $parent['deny_cid'];
1387 $deny_gid = $parent['deny_gid'];
1388 $item['wall'] = $parent['wall'];
1389 $notify_type = 'comment-new';
1392 * If the parent is private, force privacy for the entire conversation
1393 * This differs from the above settings as it subtly allows comments from
1394 * email correspondents to be private even if the overall thread is not.
1396 if ($parent['private']) {
1397 $item['private'] = $parent['private'];
1401 * Edge case. We host a public forum that was originally posted to privately.
1402 * The original author commented, but as this is a comment, the permissions
1403 * weren't fixed up so it will still show the comment as private unless we fix it here.
1405 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1406 $item['private'] = 0;
1409 // If its a post from myself then tag the thread as "mention"
1410 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1411 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1412 if (DBM::is_result($user)) {
1413 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1414 $self_id = Contact::getIdForURL($self, 0, true);
1415 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1416 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1417 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1418 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1423 * Allow one to see reply tweets from status.net even when
1424 * we don't have or can't see the original post.
1426 if ($force_parent) {
1427 logger('$force_parent=true, reply converted to top-level post.');
1429 $item['parent-uri'] = $item['uri'];
1430 $item['gravity'] = GRAVITY_PARENT;
1432 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1436 $parent_deleted = 0;
1440 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1441 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1442 if (self::exists($condition)) {
1443 logger('duplicated item with the same uri found. '.print_r($item,true));
1447 // On Friendica and Diaspora the GUID is unique
1448 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1449 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1450 if (self::exists($condition)) {
1451 logger('duplicated item with the same guid found. '.print_r($item,true));
1455 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1456 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1457 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1458 if (self::exists($condition)) {
1459 logger('duplicated item with the same body found. '.print_r($item,true));
1464 // Is this item available in the global items (with uid=0)?
1465 if ($item["uid"] == 0) {
1466 $item["global"] = true;
1468 // Set the global flag on all items if this was a global item entry
1469 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1471 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1475 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1478 $private = $item['private'];
1481 $item["allow_cid"] = $allow_cid;
1482 $item["allow_gid"] = $allow_gid;
1483 $item["deny_cid"] = $deny_cid;
1484 $item["deny_gid"] = $deny_gid;
1485 $item["private"] = $private;
1486 $item["deleted"] = $parent_deleted;
1488 // Fill the cache field
1489 put_item_in_cache($item);
1492 Addon::callHooks('post_local', $item);
1494 Addon::callHooks('post_remote', $item);
1497 // This array field is used to trigger some automatic reactions
1498 // It is mainly used in the "post_local" hook.
1499 unset($item['api_source']);
1501 if (x($item, 'cancel')) {
1502 logger('post cancelled by addon.');
1507 * Check for already added items.
1508 * There is a timing issue here that sometimes creates double postings.
1509 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1511 if ($item["uid"] == 0) {
1512 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1513 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1518 logger('' . print_r($item,true), LOGGER_DATA);
1520 if (array_key_exists('tag', $item)) {
1521 $tags = $item['tag'];
1522 unset($item['tag']);
1527 if (array_key_exists('file', $item)) {
1528 $files = $item['file'];
1529 unset($item['file']);
1534 // We are doing this outside of the transaction to avoid timing problems
1535 if (!self::insertActivity($item)) {
1536 self::insertContent($item);
1540 $ret = dba::insert('item', $item);
1542 // When the item was successfully stored we fetch the ID of the item.
1543 if (DBM::is_result($ret)) {
1544 $current_post = dba::lastInsertId();
1546 // This can happen - for example - if there are locking timeouts.
1549 // Store the data into a spool file so that we can try again later.
1551 // At first we restore the Diaspora signature that we removed above.
1552 if (isset($encoded_signature)) {
1553 $item['dsprsig'] = $encoded_signature;
1556 // Now we store the data in the spool directory
1557 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1558 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1560 $spoolpath = get_spoolpath();
1561 if ($spoolpath != "") {
1562 $spool = $spoolpath.'/'.$file;
1563 file_put_contents($spool, json_encode($item));
1564 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1569 if ($current_post == 0) {
1570 // This is one of these error messages that never should occur.
1571 logger("couldn't find created item - we better quit now.");
1576 // How much entries have we created?
1577 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1578 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1581 // There are duplicates. We delete our just created entry.
1582 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1584 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1585 dba::delete('item', ['id' => $current_post]);
1588 } elseif ($entries == 0) {
1589 // This really should never happen since we quit earlier if there were problems.
1590 logger("Something is terribly wrong. We haven't found our created entry.");
1595 logger('created item '.$current_post);
1596 self::updateContact($item);
1598 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1599 $parent_id = $current_post;
1603 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1605 $item['id'] = $current_post;
1606 $item['parent'] = $parent_id;
1608 // update the commented timestamp on the parent
1609 // Only update "commented" if it is really a comment
1610 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1611 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1613 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1618 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1619 * We can check for this condition when we decode and encode the stuff again.
1621 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1622 $dsprsig->signature = base64_decode($dsprsig->signature);
1623 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1626 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1627 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1630 if (!empty($diaspora_signed_text)) {
1631 // Formerly we stored the signed text, the signature and the author in different fields.
1632 // We now store the raw data so that we are more flexible.
1633 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1636 $deleted = self::tagDeliver($item['uid'], $current_post);
1639 * current post can be deleted if is for a community page and no mention are
1642 if (!$deleted && !$dontcache) {
1643 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1644 if (DBM::is_result($posted_item)) {
1646 Addon::callHooks('post_local_end', $posted_item);
1648 Addon::callHooks('post_remote_end', $posted_item);
1651 logger('new item not found in DB, id ' . $current_post);
1655 if ($item['parent-uri'] === $item['uri']) {
1656 self::addThread($current_post);
1658 self::updateThread($parent_id);
1664 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1665 * This is not perfect - but a workable solution until we found the reason for the problem.
1667 if (!empty($tags)) {
1668 Term::insertFromTagFieldByItemId($current_post, $tags);
1671 if (!empty($files)) {
1672 Term::insertFromFileFieldByItemId($current_post, $files);
1675 if ($item['parent-uri'] === $item['uri']) {
1676 self::addShadow($current_post);
1678 self::addShadowPost($current_post);
1681 check_user_notification($current_post);
1684 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1685 } elseif (!empty($parent) && $parent['origin']) {
1686 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1689 return $current_post;
1693 * @brief Insert a new item content entry
1695 * @param array $item The item fields that are to be inserted
1697 private static function insertActivity(&$item)
1699 $activity_index = self::activityToIndex($item['verb']);
1701 if ($activity_index < 0) {
1705 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1706 'uri-hash' => hash('sha1', $item['uri']) . hash('ripemd160', $item['uri'])];
1708 $saved_item = $item;
1710 // We just remove everything that is content
1711 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1712 unset($item[$field]);
1715 // To avoid timing problems, we are using locks.
1716 $locked = Lock::set('item_insert_activity');
1718 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1721 // Do we already have this content?
1722 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri' => $item['uri']]);
1723 if (DBM::is_result($item_activity)) {
1724 $item['iaid'] = $item_activity['id'];
1725 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1726 } elseif (dba::insert('item-activity', $fields)) {
1727 $item['iaid'] = dba::lastInsertId();
1728 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1730 // This shouldn't happen. But if it does, we simply store it in the item-content table
1731 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1732 $item = $saved_item;
1736 Lock::remove('item_insert_activity');
1742 * @brief Insert a new item content entry
1744 * @param array $item The item fields that are to be inserted
1746 private static function insertContent(&$item)
1748 $fields = ['uri' => $item['uri'], 'plink' => $item['plink'],
1749 'uri-plink-hash' => hash('sha1', $item['plink']).hash('sha1', $item['uri'])];
1751 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1752 if (isset($item[$field])) {
1753 $fields[$field] = $item[$field];
1754 unset($item[$field]);
1758 // To avoid timing problems, we are using locks.
1759 $locked = Lock::set('item_insert_content');
1761 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1764 // Do we already have this content?
1765 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $item['uri']]);
1766 if (DBM::is_result($item_content)) {
1767 $item['icid'] = $item_content['id'];
1768 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1769 } elseif (dba::insert('item-content', $fields)) {
1770 $item['icid'] = dba::lastInsertId();
1771 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1773 // By setting the ICID value through the worker we should avoid timing problems.
1774 // When the locking works, this shouldn't be needed. But better be prepared.
1775 Worker::add(PRIORITY_HIGH, 'SetItemContentID', $item['uri']);
1776 logger('Could not insert content for URI ' . $item['uri'] . ' - trying asynchronously');
1779 Lock::remove('item_insert_content');
1784 * @brief Set the item content id for a given URI
1786 * @param string $uri The item URI
1788 public static function setICIDforURI($uri)
1790 $item_content = dba::selectFirst('item-content', ['id'], ['uri' => $uri]);
1791 if (DBM::is_result($item_content)) {
1792 dba::update('item', ['icid' => $item_content['id']], ['icid' => 0, 'uri' => $uri]);
1793 logger('Asynchronously set item content id for URI ' . $uri . ' (' . $item_content['id'] . ') - Affected: '. (int)dba::affected_rows());
1795 logger('No item-content found for URI ' . $uri);
1800 * @brief Update existing item content entries
1802 * @param array $item The item fields that are to be changed
1803 * @param array $condition The condition for finding the item content entries
1805 private static function updateActivity($item, $condition)
1807 if (empty($item['verb'])) {
1810 $activity_index = self::activityToIndex($item['verb']);
1812 if ($activity_index < 0) {
1816 $fields = ['activity' => $activity_index,
1817 'uri-hash' => hash('sha1', $condition['uri']) . hash('ripemd160', $condition['uri'])];
1819 logger('Update activity for URI ' . $condition['uri']);
1821 dba::update('item-activity', $fields, $condition, true);
1827 * @brief Update existing item content entries
1829 * @param array $item The item fields that are to be changed
1830 * @param array $condition The condition for finding the item content entries
1832 private static function updateContent($item, $condition)
1834 // We have to select only the fields from the "item-content" table
1836 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1837 if (isset($item[$field])) {
1838 $fields[$field] = $item[$field];
1842 if (empty($fields)) {
1843 // when there are no fields at all, just use the condition
1844 // This is to ensure that we always store content.
1845 $fields = $condition;
1848 if (!empty($item['plink'])) {
1849 $fields['uri-plink-hash'] = hash('sha1', $item['plink']) . hash('sha1', $condition['uri']);
1851 // Ensure that we don't delete the plink
1852 unset($fields['plink']);
1855 logger('Update content for URI ' . $condition['uri']);
1857 dba::update('item-content', $fields, $condition, true);
1861 * @brief Distributes public items to the receivers
1863 * @param integer $itemid Item ID that should be added
1864 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1866 public static function distribute($itemid, $signed_text = '')
1868 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1869 $parent = self::selectFirst(['owner-id'], $condition);
1870 if (!DBM::is_result($parent)) {
1874 // Only distribute public items from native networks
1875 $condition = ['id' => $itemid, 'uid' => 0,
1876 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1877 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1878 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1879 if (!DBM::is_result($item)) {
1884 unset($item['parent']);
1885 unset($item['mention']);
1886 unset($item['wall']);
1887 unset($item['origin']);
1888 unset($item['starred']);
1892 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1893 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1894 $contacts = dba::select('contact', ['uid'], $condition);
1895 while ($contact = dba::fetch($contacts)) {
1896 $users[$contact['uid']] = $contact['uid'];
1901 if ($item['uri'] != $item['parent-uri']) {
1902 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1903 while ($parent = dba::fetch($parents)) {
1904 $users[$parent['uid']] = $parent['uid'];
1905 if ($parent['origin'] && !$item['origin']) {
1906 $origin_uid = $parent['uid'];
1911 foreach ($users as $uid) {
1912 if ($origin_uid == $uid) {
1913 $item['diaspora_signed_text'] = $signed_text;
1915 self::storeForUser($itemid, $item, $uid);
1920 * @brief Store public items for the receivers
1922 * @param integer $itemid Item ID that should be added
1923 * @param array $item The item entry that will be stored
1924 * @param integer $uid The user that will receive the item entry
1926 private static function storeForUser($itemid, $item, $uid)
1928 $item['uid'] = $uid;
1929 $item['origin'] = 0;
1931 if ($item['uri'] == $item['parent-uri']) {
1932 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1934 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1937 if (empty($item['contact-id'])) {
1938 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1939 if (!DBM::is_result($self)) {
1942 $item['contact-id'] = $self['id'];
1945 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
1946 $item['type'] = 'remote-comment';
1947 } elseif ($item['type'] == 'wall') {
1948 $item['type'] = 'remote';
1951 /// @todo Handling of "event-id"
1954 if ($item['uri'] == $item['parent-uri']) {
1955 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1956 if (DBM::is_result($contact)) {
1957 $notify = self::isRemoteSelf($contact, $item);
1961 $distributed = self::insert($item, false, $notify, true);
1963 if (!$distributed) {
1964 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
1966 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
1971 * @brief Add a shadow entry for a given item id that is a thread starter
1973 * We store every public item entry additionally with the user id "0".
1974 * This is used for the community page and for the search.
1975 * It is planned that in the future we will store public item entries only once.
1977 * @param integer $itemid Item ID that should be added
1979 public static function addShadow($itemid)
1981 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
1982 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
1983 $item = self::selectFirst($fields, $condition);
1985 if (!DBM::is_result($item)) {
1989 // is it already a copy?
1990 if (($itemid == 0) || ($item['uid'] == 0)) {
1994 // Is it a visible public post?
1995 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
1999 // is it an entry from a connector? Only add an entry for natively connected networks
2000 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2004 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2008 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2010 if (DBM::is_result($item)) {
2011 // Preparing public shadow (removing user specific data)
2014 unset($item['parent']);
2015 unset($item['wall']);
2016 unset($item['mention']);
2017 unset($item['origin']);
2018 unset($item['starred']);
2019 if ($item['uri'] == $item['parent-uri']) {
2020 $item['contact-id'] = $item['owner-id'];
2022 $item['contact-id'] = $item['author-id'];
2025 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
2026 $item['type'] = 'remote-comment';
2027 } elseif ($item['type'] == 'wall') {
2028 $item['type'] = 'remote';
2031 $public_shadow = self::insert($item, false, false, true);
2033 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2038 * @brief Add a shadow entry for a given item id that is a comment
2040 * This function does the same like the function above - but for comments
2042 * @param integer $itemid Item ID that should be added
2044 public static function addShadowPost($itemid)
2046 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2047 if (!DBM::is_result($item)) {
2051 // Is it a toplevel post?
2052 if ($item['id'] == $item['parent']) {
2053 self::addShadow($itemid);
2057 // Is this a shadow entry?
2058 if ($item['uid'] == 0) {
2062 // Is there a shadow parent?
2063 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2067 // Is there already a shadow entry?
2068 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2072 // Save "origin" and "parent" state
2073 $origin = $item['origin'];
2074 $parent = $item['parent'];
2076 // Preparing public shadow (removing user specific data)
2079 unset($item['parent']);
2080 unset($item['wall']);
2081 unset($item['mention']);
2082 unset($item['origin']);
2083 unset($item['starred']);
2084 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2086 if (in_array($item['type'], ["net-comment", "wall-comment"])) {
2087 $item['type'] = 'remote-comment';
2088 } elseif ($item['type'] == 'wall') {
2089 $item['type'] = 'remote';
2092 $public_shadow = self::insert($item, false, false, true);
2094 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2096 // If this was a comment to a Diaspora post we don't get our comment back.
2097 // This means that we have to distribute the comment by ourselves.
2098 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2099 self::distribute($public_shadow);
2104 * Adds a language specification in a "language" element of given $arr.
2105 * Expects "body" element to exist in $arr.
2107 private static function addLanguageToItemArray(&$item)
2109 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
2111 $ld = new Text_LanguageDetect();
2112 $ld->setNameMode(2);
2113 $languages = $ld->detect($naked_body, 3);
2115 if (is_array($languages)) {
2116 $item['language'] = json_encode($languages);
2121 * @brief Creates an unique guid out of a given uri
2123 * @param string $uri uri of an item entry
2124 * @param string $host hostname for the GUID prefix
2125 * @return string unique guid
2127 public static function guidFromUri($uri, $host)
2129 // Our regular guid routine is using this kind of prefix as well
2130 // We have to avoid that different routines could accidentally create the same value
2131 $parsed = parse_url($uri);
2133 // We use a hash of the hostname as prefix for the guid
2134 $guid_prefix = hash("crc32", $host);
2136 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2137 unset($parsed["scheme"]);
2139 // Glue it together to be able to make a hash from it
2140 $host_id = implode("/", $parsed);
2142 // We could use any hash algorithm since it isn't a security issue
2143 $host_hash = hash("ripemd128", $host_id);
2145 return $guid_prefix.$host_hash;
2149 * generate an unique URI
2151 * @param integer $uid User id
2152 * @param string $guid An existing GUID (Otherwise it will be generated)
2156 public static function newURI($uid, $guid = "")
2159 $guid = get_guid(32);
2162 $hostname = self::getApp()->get_hostname();
2164 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
2166 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2172 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2174 * This can be used to filter for inactive contacts.
2175 * Only do this for public postings to avoid privacy problems, since poco data is public.
2176 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2178 * @param array $arr Contains the just posted item record
2180 private static function updateContact($arr)
2182 // Unarchive the author
2183 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2184 if (DBM::is_result($contact)) {
2185 Contact::unmarkForArchival($contact);
2188 // Unarchive the contact if it's not our own contact
2189 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2190 if (DBM::is_result($contact)) {
2191 Contact::unmarkForArchival($contact);
2194 $update = (!$arr['private'] && (($arr["author-link"] === $arr["owner-link"]) || ($arr["parent-uri"] === $arr["uri"])));
2196 // Is it a forum? Then we don't care about the rules from above
2197 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2198 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2204 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2205 ['id' => $arr['contact-id']]);
2207 // Now do the same for the system wide contacts with uid=0
2208 if (!$arr['private']) {
2209 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2210 ['id' => $arr['owner-id']]);
2212 if ($arr['owner-id'] != $arr['author-id']) {
2213 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2214 ['id' => $arr['author-id']]);
2219 public static function setHashtags(&$item)
2222 $tags = get_tags($item["body"]);
2225 if (!count($tags)) {
2229 // This sorting is important when there are hashtags that are part of other hashtags
2230 // Otherwise there could be problems with hashtags like #test and #test2
2233 $URLSearchString = "^\[\]";
2235 // All hashtags should point to the home server if "local_tags" is activated
2236 if (Config::get('system', 'local_tags')) {
2237 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2238 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2240 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2241 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2244 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2245 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2247 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2250 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2252 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2255 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2257 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2260 // Repair recursive urls
2261 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2262 "#$2", $item["body"]);
2264 foreach ($tags as $tag) {
2265 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2269 $basetag = str_replace('_',' ',substr($tag,1));
2271 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2273 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2275 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2276 if (strlen($item["tag"])) {
2277 $item["tag"] = ','.$item["tag"];
2279 $item["tag"] = $newtag.$item["tag"];
2283 // Convert back the masked hashtags
2284 $item["body"] = str_replace("#", "#", $item["body"]);
2287 public static function getGuidById($id)
2289 $item = self::selectFirst(['guid'], ['id' => $id]);
2290 if (DBM::is_result($item)) {
2291 return $item['guid'];
2297 public static function getIdAndNickByGuid($guid, $uid = 0)
2303 $uid == local_user();
2306 // Does the given user have this item?
2308 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2309 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2310 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2311 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2312 if (DBM::is_result($item)) {
2314 $nick = $item["nickname"];
2318 // Or is it anywhere on the server?
2320 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2321 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2322 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2323 AND NOT `item`.`private` AND `item`.`wall`
2324 AND `item`.`guid` = ?", $guid);
2325 if (DBM::is_result($item)) {
2327 $nick = $item["nickname"];
2330 return ["nick" => $nick, "id" => $id];
2334 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2336 * @param int $item_id
2337 * @return bool true if item was deleted, else false
2339 private static function tagDeliver($uid, $item_id)
2343 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2344 if (!DBM::is_result($user)) {
2348 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2349 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2351 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2352 if (!DBM::is_result($item)) {
2356 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2359 * Diaspora uses their own hardwired link URL in @-tags
2360 * instead of the one we supply with webfinger
2362 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2364 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2366 foreach ($matches as $mtch) {
2367 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2369 logger('mention found: ' . $mtch[2]);
2375 if (($community_page || $prvgroup) &&
2376 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2377 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2379 logger("no-mention top-level post to community or private group. delete.");
2380 dba::delete('item', ['id' => $item_id]);
2386 $arr = ['item' => $item, 'user' => $user];
2388 Addon::callHooks('tagged', $arr);
2390 if (!$community_page && !$prvgroup) {
2395 * tgroup delivery - setup a second delivery chain
2396 * prevent delivery looping - only proceed
2397 * if the message originated elsewhere and is a top-level post
2399 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2403 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2404 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2405 if (!DBM::is_result($self)) {
2409 $owner_id = Contact::getIdForURL($self['url']);
2411 // also reset all the privacy bits to the forum default permissions
2413 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2415 $forum_mode = ($prvgroup ? 2 : 1);
2417 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2418 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2419 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2420 dba::update('item', $fields, ['id' => $item_id]);
2422 self::updateThread($item_id);
2424 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2427 public static function isRemoteSelf($contact, &$datarray)
2431 if (!$contact['remote_self']) {
2435 // Prevent the forwarding of posts that are forwarded
2436 if ($datarray["extid"] == NETWORK_DFRN) {
2437 logger('Already forwarded', LOGGER_DEBUG);
2441 // Prevent to forward already forwarded posts
2442 if ($datarray["app"] == $a->get_hostname()) {
2443 logger('Already forwarded (second test)', LOGGER_DEBUG);
2447 // Only forward posts
2448 if ($datarray["verb"] != ACTIVITY_POST) {
2449 logger('No post', LOGGER_DEBUG);
2453 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2454 logger('Not public', LOGGER_DEBUG);
2458 $datarray2 = $datarray;
2459 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2460 if ($contact['remote_self'] == 2) {
2461 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2462 ['uid' => $contact['uid'], 'self' => true]);
2463 if (DBM::is_result($self)) {
2464 $datarray['contact-id'] = $self["id"];
2466 $datarray['owner-name'] = $self["name"];
2467 $datarray['owner-link'] = $self["url"];
2468 $datarray['owner-avatar'] = $self["thumb"];
2470 $datarray['author-name'] = $datarray['owner-name'];
2471 $datarray['author-link'] = $datarray['owner-link'];
2472 $datarray['author-avatar'] = $datarray['owner-avatar'];
2474 unset($datarray['created']);
2475 unset($datarray['edited']);
2477 unset($datarray['network']);
2478 unset($datarray['owner-id']);
2479 unset($datarray['author-id']);
2482 if ($contact['network'] != NETWORK_FEED) {
2483 $datarray["guid"] = get_guid(32);
2484 unset($datarray["plink"]);
2485 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2486 $datarray["parent-uri"] = $datarray["uri"];
2487 $datarray["thr-parent"] = $datarray["uri"];
2488 $datarray["extid"] = NETWORK_DFRN;
2489 $urlpart = parse_url($datarray2['author-link']);
2490 $datarray["app"] = $urlpart["host"];
2492 $datarray['private'] = 0;
2496 if ($contact['network'] != NETWORK_FEED) {
2497 // Store the original post
2498 $result = self::insert($datarray2, false, false);
2499 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2501 $datarray["app"] = "Feed";
2505 // Trigger automatic reactions for addons
2506 $datarray['api_source'] = true;
2508 // We have to tell the hooks who we are - this really should be improved
2509 $_SESSION["authenticated"] = true;
2510 $_SESSION["uid"] = $contact['uid'];
2519 * @param array $item
2523 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2525 if (Config::get('system', 'disable_embedded')) {
2529 logger('check for photos', LOGGER_DEBUG);
2530 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2535 $img_start = strpos($orig_body, '[img');
2536 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2537 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2539 while (($img_st_close !== false) && ($img_len !== false)) {
2540 $img_st_close++; // make it point to AFTER the closing bracket
2541 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2543 logger('found photo ' . $image, LOGGER_DEBUG);
2545 if (stristr($image, $site . '/photo/')) {
2546 // Only embed locally hosted photos
2548 $i = basename($image);
2549 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2550 $x = strpos($i, '-');
2553 $res = substr($i, $x + 1);
2554 $i = substr($i, 0, $x);
2555 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2556 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2557 if (DBM::is_result($photo)) {
2559 * Check to see if we should replace this photo link with an embedded image
2560 * 1. No need to do so if the photo is public
2561 * 2. If there's a contact-id provided, see if they're in the access list
2562 * for the photo. If so, embed it.
2563 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2564 * permissions, regardless of order but first check to see if they're an exact
2565 * match to save some processing overhead.
2567 if (self::hasPermissions($photo)) {
2569 $recips = self::enumeratePermissions($photo);
2570 if (in_array($cid, $recips)) {
2574 if (self::samePermissions($item, $photo)) {
2580 $data = $photo['data'];
2581 $type = $photo['type'];
2583 // If a custom width and height were specified, apply before embedding
2584 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2585 logger('scaling photo', LOGGER_DEBUG);
2587 $width = intval($match[1]);
2588 $height = intval($match[2]);
2590 $Image = new Image($data, $type);
2591 if ($Image->isValid()) {
2592 $Image->scaleDown(max($width, $height));
2593 $data = $Image->asString();
2594 $type = $Image->getType();
2598 logger('replacing photo', LOGGER_DEBUG);
2599 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2600 logger('replaced: ' . $image, LOGGER_DATA);
2606 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2607 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2608 if ($orig_body === false) {
2612 $img_start = strpos($orig_body, '[img');
2613 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2614 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2617 $new_body = $new_body . $orig_body;
2622 private static function hasPermissions($obj)
2624 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2625 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2628 private static function samePermissions($obj1, $obj2)
2630 // first part is easy. Check that these are exactly the same.
2631 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2632 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2633 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2634 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2638 // This is harder. Parse all the permissions and compare the resulting set.
2639 $recipients1 = self::enumeratePermissions($obj1);
2640 $recipients2 = self::enumeratePermissions($obj2);
2644 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2645 return ($recipients1 == $recipients2);
2648 // returns an array of contact-ids that are allowed to see this object
2649 private static function enumeratePermissions($obj)
2651 $allow_people = expand_acl($obj['allow_cid']);
2652 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2653 $deny_people = expand_acl($obj['deny_cid']);
2654 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2655 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2656 $deny = array_unique(array_merge($deny_people, $deny_groups));
2657 $recipients = array_diff($recipients, $deny);
2661 public static function getFeedTags($item)
2665 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2667 for ($x = 0; $x < $cnt; $x ++) {
2668 if ($matches[1][$x]) {
2669 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2674 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2676 for ($x = 0; $x < $cnt; $x ++) {
2677 if ($matches[1][$x]) {
2678 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2685 public static function expire($uid, $days, $network = "", $force = false)
2687 if (!$uid || ($days < 1)) {
2691 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2692 $uid, GRAVITY_PARENT];
2695 * $expire_network_only = save your own wall posts
2696 * and just expire conversations started by others
2698 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2700 if ($expire_network_only) {
2701 $condition[0] .= " AND NOT `wall`";
2704 if ($network != "") {
2705 $condition[0] .= " AND `network` = ?";
2706 $condition[] = $network;
2709 * There is an index "uid_network_received" but not "uid_network_created"
2710 * This avoids the creation of another index just for one purpose.
2711 * And it doesn't really matter wether to look at "received" or "created"
2713 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2714 $condition[] = $days;
2716 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2717 $condition[] = $days;
2720 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2722 if (!DBM::is_result($items)) {
2726 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2728 // Forcing expiring of items - but not notes and marked items
2730 $expire_items = true;
2733 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2734 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2735 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2739 while ($item = Item::fetch($items)) {
2740 // don't expire filed items
2742 if (strpos($item['file'], '[') !== false) {
2746 // Only expire posts, not photos and photo comments
2748 if (!$expire_photos && strlen($item['resource-id'])) {
2750 } elseif (!$expire_starred && intval($item['starred'])) {
2752 } elseif (!$expire_notes && $item['type'] == 'note') {
2754 } elseif (!$expire_items && $item['type'] != 'note') {
2758 self::deleteById($item['id'], PRIORITY_LOW);
2763 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2766 public static function firstPostDate($uid, $wall = false)
2768 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2769 $params = ['order' => ['created' => false]];
2770 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2771 if (DBM::is_result($thread)) {
2772 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2778 * @brief add/remove activity to an item
2780 * Toggle activities as like,dislike,attend of an item
2782 * @param string $item_id
2783 * @param string $verb
2784 * Activity verb. One of
2785 * like, unlike, dislike, undislike, attendyes, unattendyes,
2786 * attendno, unattendno, attendmaybe, unattendmaybe
2787 * @hook 'post_local_end'
2789 * 'post_id' => ID of posted item
2791 public static function performLike($item_id, $verb)
2793 if (!local_user() && !remote_user()) {
2800 $activity = ACTIVITY_LIKE;
2804 $activity = ACTIVITY_DISLIKE;
2808 $activity = ACTIVITY_ATTEND;
2812 $activity = ACTIVITY_ATTENDNO;
2815 case 'unattendmaybe':
2816 $activity = ACTIVITY_ATTENDMAYBE;
2819 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2823 // Enable activity toggling instead of on/off
2824 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2826 logger('like: verb ' . $verb . ' item ' . $item_id);
2828 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2829 if (!DBM::is_result($item)) {
2830 logger('like: unknown item ' . $item_id);
2834 $item_uri = $item['uri'];
2836 $uid = $item['uid'];
2837 if (($uid == 0) && local_user()) {
2838 $uid = local_user();
2841 if (!can_write_wall($uid)) {
2842 logger('like: unable to write on wall ' . $uid);
2846 // Retrieves the local post owner
2847 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2848 if (!DBM::is_result($owner_self_contact)) {
2849 logger('like: unknown owner ' . $uid);
2853 // Retrieve the current logged in user's public contact
2854 $author_id = public_contact();
2856 $author_contact = dba::selectFirst('contact', ['url'], ['id' => $author_id]);
2857 if (!DBM::is_result($author_contact)) {
2858 logger('like: unknown author ' . $author_id);
2862 // Contact-id is the uid-dependant author contact
2863 if (local_user() == $uid) {
2864 $item_contact_id = $owner_self_contact['id'];
2865 $item_contact = $owner_self_contact;
2867 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2868 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2869 if (!DBM::is_result($item_contact)) {
2870 logger('like: unknown item contact ' . $item_contact_id);
2875 // Look for an existing verb row
2876 // event participation are essentially radio toggles. If you make a subsequent choice,
2877 // we need to eradicate your first choice.
2878 if ($event_verb_flag) {
2879 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2881 // Translate to the index based activity index
2883 foreach ($verbs as $verb) {
2884 $activities[] = self::activityToIndex($verb);
2887 $activities = self::activityToIndex($activity);
2890 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2891 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
2893 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2895 // If it exists, mark it as deleted
2896 if (DBM::is_result($like_item)) {
2897 // Already voted, undo it
2898 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2899 /// @todo Consider using self::update - but before doing so, check the side effects
2900 dba::update('item', $fields, ['id' => $like_item['id']]);
2902 // Clean up the Diaspora signatures for this like
2903 dba::delete('sign', ['iid' => $like_item['id']]);
2905 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
2907 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2912 // Verb is "un-something", just trying to delete existing entries
2913 if (strpos($verb, 'un') === 0) {
2917 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2920 'guid' => get_guid(32),
2921 'uri' => self::newURI($item['uid']),
2922 'uid' => $item['uid'],
2923 'contact-id' => $item_contact_id,
2924 'type' => 'activity',
2925 'wall' => $item['wall'],
2927 'gravity' => GRAVITY_ACTIVITY,
2928 'parent' => $item['id'],
2929 'parent-uri' => $item['uri'],
2930 'thr-parent' => $item['uri'],
2931 'owner-id' => $item['owner-id'],
2932 'author-id' => $author_id,
2933 'body' => $activity,
2934 'verb' => $activity,
2935 'object-type' => $objtype,
2936 'allow_cid' => $item['allow_cid'],
2937 'allow_gid' => $item['allow_gid'],
2938 'deny_cid' => $item['deny_cid'],
2939 'deny_gid' => $item['deny_gid'],
2944 $new_item_id = self::insert($new_item);
2946 // If the parent item isn't visible then set it to visible
2947 if (!$item['visible']) {
2948 self::update(['visible' => true], ['id' => $item['id']]);
2951 // Save the author information for the like in case we need to relay to Diaspora
2952 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2954 $new_item['id'] = $new_item_id;
2956 Addon::callHooks('post_local_end', $new_item);
2958 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
2963 private static function addThread($itemid, $onlyshadow = false)
2965 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
2966 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2967 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
2968 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2969 $item = self::selectFirst($fields, $condition);
2971 if (!DBM::is_result($item)) {
2975 $item['iid'] = $itemid;
2978 $result = dba::insert('thread', $item);
2980 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
2984 private static function updateThread($itemid, $setmention = false)
2986 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed',
2987 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark', 'contact-id',
2988 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
2989 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
2991 $item = self::selectFirst($fields, $condition);
2992 if (!DBM::is_result($item)) {
2997 $item["mention"] = 1;
3004 foreach ($item as $field => $data) {
3005 if (!in_array($field, ["guid"])) {
3006 $fields[$field] = $data;
3010 $result = dba::update('thread', $fields, ['iid' => $itemid]);
3012 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3015 private static function deleteThread($itemid, $itemuri = "")
3017 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3018 if (!DBM::is_result($item)) {
3019 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3023 // Using dba::delete at this time could delete the associated item entries
3024 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3026 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3028 if ($itemuri != "") {
3029 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3030 if (!self::exists($condition)) {
3031 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3032 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);