4 * @file src/Model/Item.php
7 namespace Friendica\Model;
10 use Friendica\BaseObject;
11 use Friendica\Content\Text;
12 use Friendica\Core\Addon;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\PermissionSet;
21 use Friendica\Object\Image;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Util\DateTimeFormat;
25 use Friendica\Util\XML;
26 use Text_LanguageDetect;
28 require_once 'boot.php';
29 require_once 'include/items.php';
30 require_once 'include/text.php';
32 class Item extends BaseObject
34 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
41 const PT_DOCUMENT = 19;
43 const PT_PERSONAL_NOTE = 128;
45 // Field list that is used to display the items
46 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
47 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
48 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
49 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
50 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
51 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
52 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
53 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
54 'writable', 'self', 'cid', 'alias',
55 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
56 'event-summary', 'event-desc', 'event-location', 'event-type',
57 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
59 // Field list that is used to deliver items via the protocols
60 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
61 'created', 'edited', 'verb', 'object-type', 'object', 'target',
62 'private', 'title', 'body', 'location', 'coord', 'app',
63 'attach', 'tag', 'deleted', 'extid', 'post-type',
64 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
65 'author-id', 'author-link', 'owner-link', 'contact-uid',
66 'signed_text', 'signature', 'signer', 'network'];
68 // Field list for "item-content" table that is mixed with the item table
69 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
70 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
71 'object-type', 'object', 'target-type', 'target', 'plink'];
73 // Field list for "item-content" table that is not present in the "item" table
74 const CONTENT_FIELDLIST = ['language'];
76 // All fields in the item table
77 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
78 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
79 'created', 'edited', 'commented', 'received', 'changed', 'verb',
80 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
81 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
82 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
83 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
84 'title', 'content-warning', 'body', 'location', 'coord', 'app',
85 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
86 'author-id', 'author-link', 'author-name', 'author-avatar',
87 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
89 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
90 // The item-activity table only stores the index and needs this array to know the matching activity.
91 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
93 private static $legacy_mode = null;
95 public static function isLegacyMode()
97 if (is_null(self::$legacy_mode)) {
98 self::$legacy_mode = (Config::get("system", "post_update_version") < 1276);
101 return self::$legacy_mode;
105 * @brief returns an activity index from an activity string
107 * @param string $activity activity string
108 * @return integer Activity index
110 private static function activityToIndex($activity)
112 $index = array_search($activity, self::ACTIVITIES);
114 if (is_bool($index)) {
122 * @brief returns an activity string from an activity index
124 * @param integer $index activity index
125 * @return string Activity string
127 private static function indexToActivity($index)
129 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
133 return self::ACTIVITIES[$index];
137 * @brief Fetch a single item row
139 * @param mixed $stmt statement object
140 * @return array current row
142 public static function fetch($stmt)
144 $row = dba::fetch($stmt);
150 // ---------------------- Transform item structure data ----------------------
152 // We prefer the data from the user's contact over the public one
153 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
154 ($row['author-link'] == $row['contact-link'])) {
155 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
156 $row['author-avatar'] = $row['contact-avatar'];
158 if (isset($row['author-name']) && !empty($row['contact-name'])) {
159 $row['author-name'] = $row['contact-name'];
163 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
164 ($row['owner-link'] == $row['contact-link'])) {
165 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
166 $row['owner-avatar'] = $row['contact-avatar'];
168 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
169 $row['owner-name'] = $row['contact-name'];
173 // We can always comment on posts from these networks
174 if (array_key_exists('writable', $row) &&
175 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
176 $row['writable'] = true;
179 // ---------------------- Transform item content data ----------------------
181 // Fetch data from the item-content table whenever there is content there
182 if (self::isLegacyMode()) {
183 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
184 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
185 $row[$field] = $row['internal-item-' . $field];
187 unset($row['internal-item-' . $field]);
191 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
192 $row['verb'] = self::indexToActivity($row['internal-activity']);
193 if (array_key_exists('title', $row)) {
196 if (array_key_exists('body', $row)) {
197 $row['body'] = $row['verb'];
199 if (array_key_exists('object', $row)) {
202 if (array_key_exists('object-type', $row)) {
203 $row['object-type'] = ACTIVITY_OBJ_NOTE;
205 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
206 // Posts don't have an object or target - but having tags or files.
207 // We safe some performance by building tag and file strings only here.
208 // We remove object and target since they aren't used for this type.
209 if (array_key_exists('object', $row)) {
212 if (array_key_exists('target', $row)) {
217 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
218 // Build the tag string out of the term entries
219 if (array_key_exists('tag', $row) && empty($row['tag'])) {
220 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
223 // Build the file string out of the term entries
224 if (array_key_exists('file', $row) && empty($row['file'])) {
225 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
229 // Remove internal fields
230 unset($row['internal-activity']);
231 unset($row['internal-network']);
232 unset($row['internal-iid']);
233 unset($row['internal-iaid']);
234 unset($row['internal-icid']);
240 * @brief Fills an array with data from an item query
242 * @param object $stmt statement object
243 * @return array Data array
245 public static function inArray($stmt, $do_close = true) {
246 if (is_bool($stmt)) {
251 while ($row = self::fetch($stmt)) {
261 * @brief Check if item data exists
263 * @param array $condition array of fields for condition
265 * @return boolean Are there rows for that condition?
267 public static function exists($condition) {
268 $stmt = self::select(['id'], $condition, ['limit' => 1]);
270 if (is_bool($stmt)) {
273 $retval = (dba::num_rows($stmt) > 0);
282 * Retrieve a single record from the item table for a given user and returns it in an associative array
284 * @brief Retrieve a single record from a table
285 * @param integer $uid User ID
286 * @param array $fields
287 * @param array $condition
288 * @param array $params
292 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
294 $params['uid'] = $uid;
296 if (empty($selected)) {
297 $selected = Item::DISPLAY_FIELDLIST;
300 return self::selectFirst($selected, $condition, $params);
304 * @brief Select rows from the item table for a given user
306 * @param integer $uid User ID
307 * @param array $selected Array of selected fields, empty for all
308 * @param array $condition Array of fields for condition
309 * @param array $params Array of several parameters
311 * @return boolean|object
313 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
315 $params['uid'] = $uid;
317 if (empty($selected)) {
318 $selected = Item::DISPLAY_FIELDLIST;
321 return self::select($selected, $condition, $params);
325 * Retrieve a single record from the item table and returns it in an associative array
327 * @brief Retrieve a single record from a table
328 * @param array $fields
329 * @param array $condition
330 * @param array $params
334 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
336 $params['limit'] = 1;
338 $result = self::select($fields, $condition, $params);
340 if (is_bool($result)) {
343 $row = self::fetch($result);
350 * @brief Select rows from the item table
352 * @param array $selected Array of selected fields, empty for all
353 * @param array $condition Array of fields for condition
354 * @param array $params Array of several parameters
356 * @return boolean|object
358 public static function select(array $selected = [], array $condition = [], $params = [])
363 if (isset($params['uid'])) {
364 $uid = $params['uid'];
368 $fields = self::fieldlist($selected);
370 $select_fields = self::constructSelectFields($fields, $selected);
372 $condition_string = dba::buildCondition($condition);
374 $condition_string = self::addTablesToFields($condition_string, $fields);
377 $condition_string = $condition_string . ' AND ' . self::condition(false);
380 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
382 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
384 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
386 return dba::p($sql, $condition);
390 * @brief Select rows from the starting post in the item table
392 * @param integer $uid User ID
393 * @param array $fields Array of selected fields, empty for all
394 * @param array $condition Array of fields for condition
395 * @param array $params Array of several parameters
397 * @return boolean|object
399 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
401 $params['uid'] = $uid;
403 if (empty($selected)) {
404 $selected = Item::DISPLAY_FIELDLIST;
407 return self::selectThread($selected, $condition, $params);
411 * Retrieve a single record from the starting post in the item table and returns it in an associative array
413 * @brief Retrieve a single record from a table
414 * @param integer $uid User ID
415 * @param array $selected
416 * @param array $condition
417 * @param array $params
421 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
423 $params['uid'] = $uid;
425 if (empty($selected)) {
426 $selected = Item::DISPLAY_FIELDLIST;
429 return self::selectFirstThread($selected, $condition, $params);
433 * Retrieve a single record from the starting post in the item table and returns it in an associative array
435 * @brief Retrieve a single record from a table
436 * @param array $fields
437 * @param array $condition
438 * @param array $params
442 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
444 $params['limit'] = 1;
445 $result = self::selectThread($fields, $condition, $params);
447 if (is_bool($result)) {
450 $row = self::fetch($result);
457 * @brief Select rows from the starting post in the item table
459 * @param array $selected Array of selected fields, empty for all
460 * @param array $condition Array of fields for condition
461 * @param array $params Array of several parameters
463 * @return boolean|object
465 public static function selectThread(array $selected = [], array $condition = [], $params = [])
470 if (isset($params['uid'])) {
471 $uid = $params['uid'];
475 $fields = self::fieldlist($selected);
477 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
478 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
479 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
480 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
482 $select_fields = self::constructSelectFields($fields, $selected);
484 $condition_string = dba::buildCondition($condition);
486 $condition_string = self::addTablesToFields($condition_string, $threadfields);
487 $condition_string = self::addTablesToFields($condition_string, $fields);
490 $condition_string = $condition_string . ' AND ' . self::condition(true);
493 $param_string = dba::buildParameter($params);
494 $param_string = self::addTablesToFields($param_string, $threadfields);
495 $param_string = self::addTablesToFields($param_string, $fields);
497 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
499 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
501 return dba::p($sql, $condition);
505 * @brief Returns a list of fields that are associated with the item table
507 * @return array field list
509 private static function fieldlist($selected)
513 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
514 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
515 'created', 'edited', 'commented', 'received', 'changed', 'postopts',
516 'resource-id', 'event-id', 'tag', 'attach', 'inform', 'post-type',
517 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid',
518 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
519 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
520 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
521 'network' => 'internal-network', 'icid' => 'internal-icid',
522 'iaid' => 'internal-iaid'];
524 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
526 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
528 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
529 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
531 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
532 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
534 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
535 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
536 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
538 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
540 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
542 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
543 'start' => 'event-start','finish' => 'event-finish',
544 'summary' => 'event-summary','desc' => 'event-desc',
545 'location' => 'event-location', 'type' => 'event-type',
546 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
547 'ignore' => 'event-ignore', 'id' => 'event-id'];
549 $fields['sign'] = ['signed_text', 'signature', 'signer'];
555 * @brief Returns SQL condition for the "select" functions
557 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
559 * @return string SQL condition
561 private static function condition($thread_mode)
564 $master_table = "`thread`";
566 $master_table = "`item`";
568 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`) ";
572 * @brief Returns all needed "JOIN" commands for the "select" functions
574 * @param integer $uid User ID
575 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
576 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
578 * @return string The SQL joins for the "select" functions
580 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
583 $master_table = "`thread`";
584 $master_table_key = "`thread`.`iid`";
585 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
587 $master_table = "`item`";
588 $master_table_key = "`item`.`id`";
593 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
594 AND NOT `contact`.`blocked`
595 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
596 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
597 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
598 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
599 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
600 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, GRAVITY_PARENT, intval($uid));
602 if (strpos($sql_commands, "`contact`.") !== false) {
603 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
605 if (strpos($sql_commands, "`author`.") !== false) {
606 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
608 if (strpos($sql_commands, "`owner`.") !== false) {
609 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
613 if (strpos($sql_commands, "`group_member`.") !== false) {
614 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
617 if (strpos($sql_commands, "`user`.") !== false) {
618 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
621 if (strpos($sql_commands, "`event`.") !== false) {
622 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
625 if (strpos($sql_commands, "`sign`.") !== false) {
626 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
629 if (strpos($sql_commands, "`item-activity`.") !== false) {
630 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
633 if (strpos($sql_commands, "`item-content`.") !== false) {
634 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
637 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
638 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
641 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
642 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
649 * @brief Add the field list for the "select" functions
651 * @param array $fields The field definition array
652 * @param array $selected The array with the selected fields from the "select" functions
654 * @return string The field list
656 private static function constructSelectFields($fields, $selected)
658 if (!empty($selected)) {
659 $selected[] = 'internal-iid';
660 $selected[] = 'internal-iaid';
661 $selected[] = 'internal-icid';
662 $selected[] = 'internal-network';
665 if (in_array('verb', $selected)) {
666 $selected[] = 'internal-activity';
670 foreach ($fields as $table => $table_fields) {
671 foreach ($table_fields as $field => $select) {
672 if (empty($selected) || in_array($select, $selected)) {
673 if (self::isLegacyMode() && in_array($select, self::MIXED_CONTENT_FIELDLIST)) {
674 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
676 if (is_int($field)) {
677 $selection[] = "`" . $table . "`.`" . $select . "`";
679 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
684 return implode(", ", $selection);
688 * @brief add table definition to fields in an SQL query
690 * @param string $query SQL query
691 * @param array $fields The field definition array
693 * @return string the changed SQL query
695 private static function addTablesToFields($query, $fields)
697 foreach ($fields as $table => $table_fields) {
698 foreach ($table_fields as $alias => $field) {
699 if (is_int($alias)) {
700 $replace_field = $field;
702 $replace_field = $alias;
705 $search = "/([^\.])`" . $field . "`/i";
706 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
707 $query = preg_replace($search, $replace, $query);
714 * @brief Generate a server unique item hash for linking between the item tables
716 * @param string $uri Item URI
717 * @param date $created Item creation date
719 * @return string the item hash
721 private static function itemHash($uri, $created)
723 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
727 * @brief Update existing item entries
729 * @param array $fields The fields that are to be changed
730 * @param array $condition The condition for finding the item entries
732 * In the future we may have to change permissions as well.
733 * Then we had to add the user id as third parameter.
735 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
737 * @return integer|boolean number of affected rows - or "false" if there was an error
739 public static function update(array $fields, array $condition)
741 if (empty($condition) || empty($fields)) {
745 // To ensure the data integrity we do it in an transaction
748 // We cannot simply expand the condition to check for origin entries
749 // The condition needn't to be a simple array but could be a complex condition.
750 // And we have to execute this query before the update to ensure to fetch the same data.
751 $items = dba::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
753 $content_fields = [];
754 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
755 if (isset($fields[$field])) {
756 $content_fields[$field] = $fields[$field];
757 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
758 unset($fields[$field]);
760 $fields[$field] = null;
765 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
766 foreach ($clear_fields as $field) {
767 if (array_key_exists($field, $fields)) {
768 $fields[$field] = null;
772 if (array_key_exists('tag', $fields)) {
773 $tags = $fields['tag'];
774 $fields['tag'] = null;
779 if (array_key_exists('file', $fields)) {
780 $files = $fields['file'];
781 $fields['file'] = null;
786 if (!empty($fields)) {
787 $success = dba::update('item', $fields, $condition);
796 // When there is no content for the "old" item table, this will count the fetched items
797 $rows = dba::affected_rows();
799 while ($item = dba::fetch($items)) {
800 // This part here can safely be removed when the legacy fields in the item had been removed
801 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
803 // Fetch the uri-hash from an existing item entry if there is one
804 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
805 $existing = dba::selectfirst('item', ['uri-hash'], $item_condition);
806 if (DBM::is_result($existing)) {
807 $item['uri-hash'] = $existing['uri-hash'];
809 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
812 dba::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
813 dba::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
814 dba::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
817 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
818 if (!empty($item['iaid'])) {
819 $update_condition = ['id' => $item['iaid']];
821 $update_condition = ['uri-hash' => $item['uri-hash']];
823 self::updateActivity($content_fields, $update_condition);
825 if (empty($item['iaid'])) {
826 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
827 if (DBM::is_result($item_activity)) {
828 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
829 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
830 if (self::isLegacyMode()) {
831 $item_fields[$field] = null;
833 unset($item_fields[$field]);
836 dba::update('item', $item_fields, ['id' => $item['id']]);
838 if (!empty($item['icid']) && !dba::exists('item', ['icid' => $item['icid']])) {
839 dba::delete('item-content', ['id' => $item['icid']]);
842 } elseif (!empty($item['icid'])) {
843 dba::update('item', ['icid' => null], ['id' => $item['id']]);
845 if (!dba::exists('item', ['icid' => $item['icid']])) {
846 dba::delete('item-content', ['id' => $item['icid']]);
850 if (!empty($item['icid'])) {
851 $update_condition = ['id' => $item['icid']];
853 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
855 self::updateContent($content_fields, $update_condition);
857 if (empty($item['icid'])) {
858 $item_content = dba::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
859 if (DBM::is_result($item_content)) {
860 $item_fields = ['icid' => $item_content['id']];
861 // Clear all fields in the item table that have a content in the item-content table
862 foreach ($item_content as $field => $content) {
863 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
864 if (self::isLegacyMode()) {
865 $item_fields[$field] = null;
867 unset($item_fields[$field]);
871 dba::update('item', $item_fields, ['id' => $item['id']]);
877 Term::insertFromTagFieldByItemId($item['id'], $tags);
878 if (!empty($item['tag'])) {
879 dba::update('item', ['tag' => ''], ['id' => $item['id']]);
883 if (!empty($files)) {
884 Term::insertFromFileFieldByItemId($item['id'], $files);
885 if (!empty($item['file'])) {
886 dba::update('item', ['file' => ''], ['id' => $item['id']]);
890 self::updateThread($item['id']);
892 // We only need to notfiy others when it is an original entry from us.
893 // Only call the notifier when the item has some content relevant change.
894 if ($item['origin'] && in_array('edited', array_keys($fields))) {
895 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
905 * @brief Delete an item and notify others about it - if it was ours
907 * @param array $condition The condition for finding the item entries
908 * @param integer $priority Priority for the notification
910 public static function delete($condition, $priority = PRIORITY_HIGH)
912 $items = dba::select('item', ['id'], $condition);
913 while ($item = dba::fetch($items)) {
914 self::deleteById($item['id'], $priority);
920 * @brief Delete an item for an user and notify others about it - if it was ours
922 * @param array $condition The condition for finding the item entries
923 * @param integer $uid User who wants to delete this item
925 public static function deleteForUser($condition, $uid)
931 $items = dba::select('item', ['id', 'uid'], $condition);
932 while ($item = dba::fetch($items)) {
933 // "Deleting" global items just means hiding them
934 if ($item['uid'] == 0) {
935 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
936 } elseif ($item['uid'] == $uid) {
937 self::deleteById($item['id'], PRIORITY_HIGH);
939 logger('Wrong ownership. Not deleting item ' . $item['id']);
946 * @brief Delete an item and notify others about it - if it was ours
948 * @param integer $item_id Item ID that should be delete
949 * @param integer $priority Priority for the notification
951 * @return boolean success
953 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
955 // locate item to be deleted
956 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
957 'deleted', 'file', 'resource-id', 'event-id', 'attach',
958 'verb', 'object-type', 'object', 'target', 'contact-id'];
959 $item = self::selectFirst($fields, ['id' => $item_id]);
960 if (!DBM::is_result($item)) {
961 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
965 if ($item['deleted']) {
966 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
970 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
971 if (!DBM::is_result($parent)) {
972 $parent = ['origin' => false];
975 // clean up categories and tags so they don't end up as orphans
978 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
980 foreach ($matches as $mtch) {
981 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
987 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
989 foreach ($matches as $mtch) {
990 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
995 * If item is a link to a photo resource, nuke all the associated photos
996 * (visitors will not have photo resources)
997 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
998 * generate a resource-id and therefore aren't intimately linked to the item.
1000 if (strlen($item['resource-id'])) {
1001 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1004 // If item is a link to an event, delete the event.
1005 if (intval($item['event-id'])) {
1006 Event::delete($item['event-id']);
1009 // If item has attachments, drop them
1010 foreach (explode(", ", $item['attach']) as $attach) {
1011 preg_match("|attach/(\d+)|", $attach, $matches);
1012 if (is_array($matches) && count($matches) > 1) {
1013 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1017 // Delete tags that had been attached to other items
1018 self::deleteTagsFromItem($item);
1020 // Set the item to "deleted"
1021 // This erasing of item content is superfluous for items with a matching item-content.
1022 // But for the next time we will still have old content in the item table.
1023 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
1024 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
1025 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
1026 dba::update('item', $item_fields, ['id' => $item['id']]);
1028 Term::insertFromTagFieldByItemId($item['id'], '');
1029 Term::insertFromFileFieldByItemId($item['id'], '');
1030 self::deleteThread($item['id'], $item['parent-uri']);
1032 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1033 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1036 // If it's the parent of a comment thread, kill all the kids
1037 if ($item['id'] == $item['parent']) {
1038 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1041 // Is it our comment and/or our thread?
1042 if ($item['origin'] || $parent['origin']) {
1044 // When we delete the original post we will delete all existing copies on the server as well
1045 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1047 // send the notification upstream/downstream
1048 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1049 } elseif ($item['uid'] != 0) {
1051 // When we delete just our local user copy of an item, we have to set a marker to hide it
1052 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1053 if (DBM::is_result($global_item)) {
1054 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1058 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1063 private static function deleteTagsFromItem($item)
1065 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1069 $xo = XML::parseString($item["object"], false);
1070 $xt = XML::parseString($item["target"], false);
1072 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1076 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1077 if (!DBM::is_result($i)) {
1081 // For tags, the owner cannot remove the tag on the author's copy of the post.
1082 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1083 $author_copy = $item["origin"];
1085 if (($owner_remove && $author_copy) || !$owner_remove) {
1089 $tags = explode(',', $i["tag"]);
1092 foreach ($tags as $tag) {
1093 if (trim($tag) !== trim($xo->body)) {
1094 $newtags[] = trim($tag);
1098 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1101 private static function guid($item, $notify)
1103 if (!empty($item['guid'])) {
1104 return notags(trim($item['guid']));
1108 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1109 // We add the hash of our own host because our host is the original creator of the post.
1110 $prefix_host = get_app()->get_hostname();
1114 // We are only storing the post so we create a GUID from the original hostname.
1115 if (!empty($item['author-link'])) {
1116 $parsed = parse_url($item['author-link']);
1117 if (!empty($parsed['host'])) {
1118 $prefix_host = $parsed['host'];
1122 if (empty($prefix_host) && !empty($item['plink'])) {
1123 $parsed = parse_url($item['plink']);
1124 if (!empty($parsed['host'])) {
1125 $prefix_host = $parsed['host'];
1129 if (empty($prefix_host) && !empty($item['uri'])) {
1130 $parsed = parse_url($item['uri']);
1131 if (!empty($parsed['host'])) {
1132 $prefix_host = $parsed['host'];
1136 // Is it in the format data@host.tld? - Used for mail contacts
1137 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1138 $mailparts = explode('@', $item['author-link']);
1139 $prefix_host = array_pop($mailparts);
1143 if (!empty($item['plink'])) {
1144 $guid = self::guidFromUri($item['plink'], $prefix_host);
1145 } elseif (!empty($item['uri'])) {
1146 $guid = self::guidFromUri($item['uri'], $prefix_host);
1148 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1154 private static function contactId($item)
1156 $contact_id = (int)$item["contact-id"];
1158 if (!empty($contact_id)) {
1161 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1163 * First we are looking for a suitable contact that matches with the author of the post
1164 * This is done only for comments
1166 if ($item['parent-uri'] != $item['uri']) {
1167 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1170 // If not present then maybe the owner was found
1171 if ($contact_id == 0) {
1172 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1175 // Still missing? Then use the "self" contact of the current user
1176 if ($contact_id == 0) {
1177 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1178 if (DBM::is_result($self)) {
1179 $contact_id = $self["id"];
1182 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1187 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1191 // If it is a posting where users should get notifications, then define it as wall posting
1194 $item['origin'] = 1;
1195 $item['network'] = NETWORK_DFRN;
1196 $item['protocol'] = PROTOCOL_DFRN;
1198 if (is_int($notify)) {
1199 $priority = $notify;
1201 $priority = PRIORITY_HIGH;
1204 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1207 $item['guid'] = self::guid($item, $notify);
1208 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1210 // Store conversation data
1211 $item = Conversation::insert($item);
1214 * If a Diaspora signature structure was passed in, pull it out of the
1215 * item array and set it aside for later storage.
1219 if (x($item, 'dsprsig')) {
1220 $encoded_signature = $item['dsprsig'];
1221 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1222 unset($item['dsprsig']);
1225 if (!empty($item['diaspora_signed_text'])) {
1226 $diaspora_signed_text = $item['diaspora_signed_text'];
1227 unset($item['diaspora_signed_text']);
1229 $diaspora_signed_text = '';
1232 // Converting the plink
1233 /// @TODO Check if this is really still needed
1234 if ($item['network'] == NETWORK_OSTATUS) {
1235 if (isset($item['plink'])) {
1236 $item['plink'] = OStatus::convertHref($item['plink']);
1237 } elseif (isset($item['uri'])) {
1238 $item['plink'] = OStatus::convertHref($item['uri']);
1242 if (!empty($item['thr-parent'])) {
1243 $item['parent-uri'] = $item['thr-parent'];
1246 if (isset($item['gravity'])) {
1247 $item['gravity'] = intval($item['gravity']);
1248 } elseif ($item['parent-uri'] === $item['uri']) {
1249 $item['gravity'] = GRAVITY_PARENT;
1250 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1251 $item['gravity'] = GRAVITY_COMMENT;
1253 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1254 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1257 $uid = intval($item['uid']);
1259 // check for create date and expire time
1260 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1262 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1263 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1264 $expire_interval = $user['expire'];
1267 if (($expire_interval > 0) && !empty($item['created'])) {
1268 $expire_date = time() - ($expire_interval * 86400);
1269 $created_date = strtotime($item['created']);
1270 if ($created_date < $expire_date) {
1271 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1277 * Do we already have this item?
1278 * We have to check several networks since Friendica posts could be repeated
1279 * via OStatus (maybe Diasporsa as well)
1281 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1282 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1283 trim($item['uri']), $item['uid'],
1284 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1285 $existing = self::selectFirst(['id', 'network'], $condition);
1286 if (DBM::is_result($existing)) {
1287 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1289 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1292 return $existing["id"];
1296 // Ensure to always have the same creation date.
1297 $existing = dba::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1298 if (DBM::is_result($existing)) {
1299 $item['created'] = $existing['created'];
1300 $item['uri-hash'] = $existing['uri-hash'];
1303 self::addLanguageToItemArray($item);
1305 $item['wall'] = intval(defaults($item, 'wall', 0));
1306 $item['extid'] = trim(defaults($item, 'extid', ''));
1307 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1308 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1309 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1310 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1311 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1312 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1313 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1314 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1315 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1316 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1317 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1318 $item['title'] = trim(defaults($item, 'title', ''));
1319 $item['location'] = trim(defaults($item, 'location', ''));
1320 $item['coord'] = trim(defaults($item, 'coord', ''));
1321 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1322 $item['deleted'] = 0;
1323 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1324 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1325 $item['verb'] = trim(defaults($item, 'verb', ''));
1326 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1327 $item['object'] = trim(defaults($item, 'object', ''));
1328 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1329 $item['target'] = trim(defaults($item, 'target', ''));
1330 $item['plink'] = trim(defaults($item, 'plink', ''));
1331 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1332 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1333 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1334 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1335 $item['private'] = intval(defaults($item, 'private', 0));
1336 $item['body'] = trim(defaults($item, 'body', ''));
1337 $item['tag'] = trim(defaults($item, 'tag', ''));
1338 $item['attach'] = trim(defaults($item, 'attach', ''));
1339 $item['app'] = trim(defaults($item, 'app', ''));
1340 $item['origin'] = intval(defaults($item, 'origin', 0));
1341 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1342 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1343 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1344 $item['inform'] = trim(defaults($item, 'inform', ''));
1345 $item['file'] = trim(defaults($item, 'file', ''));
1347 // Unique identifier to be linked against item-activities and item-content
1348 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1350 // When there is no content then we don't post it
1351 if ($item['body'].$item['title'] == '') {
1352 logger('No body, no title.');
1356 // Items cannot be stored before they happen ...
1357 if ($item['created'] > DateTimeFormat::utcNow()) {
1358 $item['created'] = DateTimeFormat::utcNow();
1361 // We haven't invented time travel by now.
1362 if ($item['edited'] > DateTimeFormat::utcNow()) {
1363 $item['edited'] = DateTimeFormat::utcNow();
1366 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1368 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1369 $item["contact-id"] = self::contactId($item);
1371 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1372 'photo' => $item['author-avatar'], 'network' => $item['network']];
1374 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1376 if (Contact::isBlocked($item["author-id"])) {
1377 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1381 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1382 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1384 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1386 if (Contact::isBlocked($item["owner-id"])) {
1387 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1391 // These fields aren't stored anymore in the item table, they are fetched upon request
1392 unset($item['author-link']);
1393 unset($item['author-name']);
1394 unset($item['author-avatar']);
1396 unset($item['owner-link']);
1397 unset($item['owner-name']);
1398 unset($item['owner-avatar']);
1400 if ($item['network'] == NETWORK_PHANTOM) {
1401 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1403 $item['network'] = NETWORK_DFRN;
1404 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1407 // Checking if there is already an item with the same guid
1408 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1409 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1410 if (self::exists($condition)) {
1411 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1415 // Check for hashtags in the body and repair or add hashtag links
1416 self::setHashtags($item);
1418 $item['thr-parent'] = $item['parent-uri'];
1426 if ($item['parent-uri'] === $item['uri']) {
1428 $parent_deleted = 0;
1429 $allow_cid = $item['allow_cid'];
1430 $allow_gid = $item['allow_gid'];
1431 $deny_cid = $item['deny_cid'];
1432 $deny_gid = $item['deny_gid'];
1433 $notify_type = 'wall-new';
1435 // find the parent and snarf the item id and ACLs
1436 // and anything else we need to inherit
1438 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1439 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1440 'wall', 'private', 'forum_mode', 'origin'];
1441 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1442 $params = ['order' => ['id' => false]];
1443 $parent = self::selectFirst($fields, $condition, $params);
1445 if (DBM::is_result($parent)) {
1446 // is the new message multi-level threaded?
1447 // even though we don't support it now, preserve the info
1448 // and re-attach to the conversation parent.
1450 if ($parent['uri'] != $parent['parent-uri']) {
1451 $item['parent-uri'] = $parent['parent-uri'];
1453 $condition = ['uri' => $item['parent-uri'],
1454 'parent-uri' => $item['parent-uri'],
1455 'uid' => $item['uid']];
1456 $params = ['order' => ['id' => false]];
1457 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1459 if (DBM::is_result($toplevel_parent)) {
1460 $parent = $toplevel_parent;
1464 $parent_id = $parent['id'];
1465 $parent_deleted = $parent['deleted'];
1466 $allow_cid = $parent['allow_cid'];
1467 $allow_gid = $parent['allow_gid'];
1468 $deny_cid = $parent['deny_cid'];
1469 $deny_gid = $parent['deny_gid'];
1470 $item['wall'] = $parent['wall'];
1471 $notify_type = 'comment-new';
1474 * If the parent is private, force privacy for the entire conversation
1475 * This differs from the above settings as it subtly allows comments from
1476 * email correspondents to be private even if the overall thread is not.
1478 if ($parent['private']) {
1479 $item['private'] = $parent['private'];
1483 * Edge case. We host a public forum that was originally posted to privately.
1484 * The original author commented, but as this is a comment, the permissions
1485 * weren't fixed up so it will still show the comment as private unless we fix it here.
1487 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1488 $item['private'] = 0;
1491 // If its a post from myself then tag the thread as "mention"
1492 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1493 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1494 if (DBM::is_result($user)) {
1495 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1496 $self_id = Contact::getIdForURL($self, 0, true);
1497 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1498 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1499 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1500 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1505 * Allow one to see reply tweets from status.net even when
1506 * we don't have or can't see the original post.
1508 if ($force_parent) {
1509 logger('$force_parent=true, reply converted to top-level post.');
1511 $item['parent-uri'] = $item['uri'];
1512 $item['gravity'] = GRAVITY_PARENT;
1514 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1518 $parent_deleted = 0;
1522 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1523 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1524 if (self::exists($condition)) {
1525 logger('duplicated item with the same uri found. '.print_r($item,true));
1529 // On Friendica and Diaspora the GUID is unique
1530 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1531 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1532 if (self::exists($condition)) {
1533 logger('duplicated item with the same guid found. '.print_r($item,true));
1537 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1538 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1539 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1540 if (self::exists($condition)) {
1541 logger('duplicated item with the same body found. '.print_r($item,true));
1546 // Is this item available in the global items (with uid=0)?
1547 if ($item["uid"] == 0) {
1548 $item["global"] = true;
1550 // Set the global flag on all items if this was a global item entry
1551 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1553 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1557 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1560 $private = $item['private'];
1563 $item["allow_cid"] = $allow_cid;
1564 $item["allow_gid"] = $allow_gid;
1565 $item["deny_cid"] = $deny_cid;
1566 $item["deny_gid"] = $deny_gid;
1567 $item["private"] = $private;
1568 $item["deleted"] = $parent_deleted;
1570 // Fill the cache field
1571 put_item_in_cache($item);
1574 $item['edit'] = false;
1575 $item['parent'] = $parent_id;
1576 Addon::callHooks('post_local', $item);
1577 unset($item['edit']);
1578 unset($item['parent']);
1580 Addon::callHooks('post_remote', $item);
1583 // This array field is used to trigger some automatic reactions
1584 // It is mainly used in the "post_local" hook.
1585 unset($item['api_source']);
1587 if (x($item, 'cancel')) {
1588 logger('post cancelled by addon.');
1593 * Check for already added items.
1594 * There is a timing issue here that sometimes creates double postings.
1595 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1597 if ($item["uid"] == 0) {
1598 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1599 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1604 logger('' . print_r($item,true), LOGGER_DATA);
1606 if (array_key_exists('tag', $item)) {
1607 $tags = $item['tag'];
1608 unset($item['tag']);
1613 if (array_key_exists('file', $item)) {
1614 $files = $item['file'];
1615 unset($item['file']);
1620 // Creates the permission set
1621 // Currently we only store the data but don't using it
1622 $item['psid'] = PermissionSet::fetchIDForPost($item);
1624 // We are doing this outside of the transaction to avoid timing problems
1625 if (!self::insertActivity($item)) {
1626 self::insertContent($item);
1630 $ret = dba::insert('item', $item);
1632 // When the item was successfully stored we fetch the ID of the item.
1633 if (DBM::is_result($ret)) {
1634 $current_post = dba::lastInsertId();
1636 // This can happen - for example - if there are locking timeouts.
1639 // Store the data into a spool file so that we can try again later.
1641 // At first we restore the Diaspora signature that we removed above.
1642 if (isset($encoded_signature)) {
1643 $item['dsprsig'] = $encoded_signature;
1646 // Now we store the data in the spool directory
1647 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1648 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1650 $spoolpath = get_spoolpath();
1651 if ($spoolpath != "") {
1652 $spool = $spoolpath.'/'.$file;
1653 file_put_contents($spool, json_encode($item));
1654 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1659 if ($current_post == 0) {
1660 // This is one of these error messages that never should occur.
1661 logger("couldn't find created item - we better quit now.");
1666 // How much entries have we created?
1667 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1668 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1671 // There are duplicates. We delete our just created entry.
1672 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1674 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1675 dba::delete('item', ['id' => $current_post]);
1678 } elseif ($entries == 0) {
1679 // This really should never happen since we quit earlier if there were problems.
1680 logger("Something is terribly wrong. We haven't found our created entry.");
1685 logger('created item '.$current_post);
1686 self::updateContact($item);
1688 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1689 $parent_id = $current_post;
1693 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1695 $item['id'] = $current_post;
1696 $item['parent'] = $parent_id;
1698 // update the commented timestamp on the parent
1699 // Only update "commented" if it is really a comment
1700 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1701 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1703 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1708 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1709 * We can check for this condition when we decode and encode the stuff again.
1711 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1712 $dsprsig->signature = base64_decode($dsprsig->signature);
1713 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1716 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1717 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1720 if (!empty($diaspora_signed_text)) {
1721 // Formerly we stored the signed text, the signature and the author in different fields.
1722 // We now store the raw data so that we are more flexible.
1723 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1726 $deleted = self::tagDeliver($item['uid'], $current_post);
1729 * current post can be deleted if is for a community page and no mention are
1732 if (!$deleted && !$dontcache) {
1733 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1734 if (DBM::is_result($posted_item)) {
1736 Addon::callHooks('post_local_end', $posted_item);
1738 Addon::callHooks('post_remote_end', $posted_item);
1741 logger('new item not found in DB, id ' . $current_post);
1745 if ($item['parent-uri'] === $item['uri']) {
1746 self::addThread($current_post);
1748 self::updateThread($parent_id);
1754 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1755 * This is not perfect - but a workable solution until we found the reason for the problem.
1757 if (!empty($tags)) {
1758 Term::insertFromTagFieldByItemId($current_post, $tags);
1761 if (!empty($files)) {
1762 Term::insertFromFileFieldByItemId($current_post, $files);
1765 if ($item['parent-uri'] === $item['uri']) {
1766 self::addShadow($current_post);
1768 self::addShadowPost($current_post);
1771 check_user_notification($current_post);
1774 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1775 } elseif (!empty($parent) && $parent['origin']) {
1776 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1779 return $current_post;
1783 * @brief Insert a new item content entry
1785 * @param array $item The item fields that are to be inserted
1787 private static function insertActivity(&$item)
1789 $activity_index = self::activityToIndex($item['verb']);
1791 if ($activity_index < 0) {
1795 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1796 'uri-hash' => $item['uri-hash']];
1798 // We just remove everything that is content
1799 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1800 unset($item[$field]);
1803 // To avoid timing problems, we are using locks.
1804 $locked = Lock::acquire('item_insert_activity');
1806 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1809 // Do we already have this content?
1810 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1811 if (DBM::is_result($item_activity)) {
1812 $item['iaid'] = $item_activity['id'];
1813 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1814 } elseif (dba::insert('item-activity', $fields)) {
1815 $item['iaid'] = dba::lastInsertId();
1816 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1818 // This shouldn't happen.
1819 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1823 Lock::release('item_insert_activity');
1829 * @brief Insert a new item content entry
1831 * @param array $item The item fields that are to be inserted
1833 private static function insertContent(&$item)
1835 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1837 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1838 if (isset($item[$field])) {
1839 $fields[$field] = $item[$field];
1840 unset($item[$field]);
1844 // To avoid timing problems, we are using locks.
1845 $locked = Lock::acquire('item_insert_content');
1847 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1850 // Do we already have this content?
1851 $item_content = dba::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1852 if (DBM::is_result($item_content)) {
1853 $item['icid'] = $item_content['id'];
1854 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1855 } elseif (dba::insert('item-content', $fields)) {
1856 $item['icid'] = dba::lastInsertId();
1857 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1859 // This shouldn't happen.
1860 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1863 Lock::release('item_insert_content');
1868 * @brief Update existing item content entries
1870 * @param array $item The item fields that are to be changed
1871 * @param array $condition The condition for finding the item content entries
1873 private static function updateActivity($item, $condition)
1875 if (empty($item['verb'])) {
1878 $activity_index = self::activityToIndex($item['verb']);
1880 if ($activity_index < 0) {
1884 $fields = ['activity' => $activity_index];
1886 logger('Update activity for ' . json_encode($condition));
1888 dba::update('item-activity', $fields, $condition, true);
1894 * @brief Update existing item content entries
1896 * @param array $item The item fields that are to be changed
1897 * @param array $condition The condition for finding the item content entries
1899 private static function updateContent($item, $condition)
1901 // We have to select only the fields from the "item-content" table
1903 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1904 if (isset($item[$field])) {
1905 $fields[$field] = $item[$field];
1909 if (empty($fields)) {
1910 // when there are no fields at all, just use the condition
1911 // This is to ensure that we always store content.
1912 $fields = $condition;
1915 logger('Update content for ' . json_encode($condition));
1917 dba::update('item-content', $fields, $condition, true);
1921 * @brief Distributes public items to the receivers
1923 * @param integer $itemid Item ID that should be added
1924 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1926 public static function distribute($itemid, $signed_text = '')
1928 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1929 $parent = self::selectFirst(['owner-id'], $condition);
1930 if (!DBM::is_result($parent)) {
1934 // Only distribute public items from native networks
1935 $condition = ['id' => $itemid, 'uid' => 0,
1936 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
1937 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
1938 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
1939 if (!DBM::is_result($item)) {
1943 $origin = $item['origin'];
1946 unset($item['parent']);
1947 unset($item['mention']);
1948 unset($item['wall']);
1949 unset($item['origin']);
1950 unset($item['starred']);
1954 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
1955 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
1956 $contacts = dba::select('contact', ['uid'], $condition);
1957 while ($contact = dba::fetch($contacts)) {
1958 $users[$contact['uid']] = $contact['uid'];
1963 if ($item['uri'] != $item['parent-uri']) {
1964 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
1965 while ($parent = dba::fetch($parents)) {
1966 $users[$parent['uid']] = $parent['uid'];
1967 if ($parent['origin'] && !$origin) {
1968 $origin_uid = $parent['uid'];
1973 foreach ($users as $uid) {
1974 if ($origin_uid == $uid) {
1975 $item['diaspora_signed_text'] = $signed_text;
1977 self::storeForUser($itemid, $item, $uid);
1982 * @brief Store public items for the receivers
1984 * @param integer $itemid Item ID that should be added
1985 * @param array $item The item entry that will be stored
1986 * @param integer $uid The user that will receive the item entry
1988 private static function storeForUser($itemid, $item, $uid)
1990 $item['uid'] = $uid;
1991 $item['origin'] = 0;
1993 if ($item['uri'] == $item['parent-uri']) {
1994 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
1996 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
1999 if (empty($item['contact-id'])) {
2000 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2001 if (!DBM::is_result($self)) {
2004 $item['contact-id'] = $self['id'];
2007 /// @todo Handling of "event-id"
2010 if ($item['uri'] == $item['parent-uri']) {
2011 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2012 if (DBM::is_result($contact)) {
2013 $notify = self::isRemoteSelf($contact, $item);
2017 $distributed = self::insert($item, false, $notify, true);
2019 if (!$distributed) {
2020 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2022 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2027 * @brief Add a shadow entry for a given item id that is a thread starter
2029 * We store every public item entry additionally with the user id "0".
2030 * This is used for the community page and for the search.
2031 * It is planned that in the future we will store public item entries only once.
2033 * @param integer $itemid Item ID that should be added
2035 public static function addShadow($itemid)
2037 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2038 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2039 $item = self::selectFirst($fields, $condition);
2041 if (!DBM::is_result($item)) {
2045 // is it already a copy?
2046 if (($itemid == 0) || ($item['uid'] == 0)) {
2050 // Is it a visible public post?
2051 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2055 // is it an entry from a connector? Only add an entry for natively connected networks
2056 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2060 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2064 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2066 if (DBM::is_result($item)) {
2067 // Preparing public shadow (removing user specific data)
2070 unset($item['parent']);
2071 unset($item['wall']);
2072 unset($item['mention']);
2073 unset($item['origin']);
2074 unset($item['starred']);
2075 if ($item['uri'] == $item['parent-uri']) {
2076 $item['contact-id'] = $item['owner-id'];
2078 $item['contact-id'] = $item['author-id'];
2081 $public_shadow = self::insert($item, false, false, true);
2083 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2088 * @brief Add a shadow entry for a given item id that is a comment
2090 * This function does the same like the function above - but for comments
2092 * @param integer $itemid Item ID that should be added
2094 public static function addShadowPost($itemid)
2096 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2097 if (!DBM::is_result($item)) {
2101 // Is it a toplevel post?
2102 if ($item['id'] == $item['parent']) {
2103 self::addShadow($itemid);
2107 // Is this a shadow entry?
2108 if ($item['uid'] == 0) {
2112 // Is there a shadow parent?
2113 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2117 // Is there already a shadow entry?
2118 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2122 // Save "origin" and "parent" state
2123 $origin = $item['origin'];
2124 $parent = $item['parent'];
2126 // Preparing public shadow (removing user specific data)
2129 unset($item['parent']);
2130 unset($item['wall']);
2131 unset($item['mention']);
2132 unset($item['origin']);
2133 unset($item['starred']);
2134 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2136 $public_shadow = self::insert($item, false, false, true);
2138 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2140 // If this was a comment to a Diaspora post we don't get our comment back.
2141 // This means that we have to distribute the comment by ourselves.
2142 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2143 self::distribute($public_shadow);
2148 * Adds a language specification in a "language" element of given $arr.
2149 * Expects "body" element to exist in $arr.
2151 private static function addLanguageToItemArray(&$item)
2153 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
2155 $ld = new Text_LanguageDetect();
2156 $ld->setNameMode(2);
2157 $languages = $ld->detect($naked_body, 3);
2159 if (is_array($languages)) {
2160 $item['language'] = json_encode($languages);
2165 * @brief Creates an unique guid out of a given uri
2167 * @param string $uri uri of an item entry
2168 * @param string $host hostname for the GUID prefix
2169 * @return string unique guid
2171 public static function guidFromUri($uri, $host)
2173 // Our regular guid routine is using this kind of prefix as well
2174 // We have to avoid that different routines could accidentally create the same value
2175 $parsed = parse_url($uri);
2177 // We use a hash of the hostname as prefix for the guid
2178 $guid_prefix = hash("crc32", $host);
2180 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2181 unset($parsed["scheme"]);
2183 // Glue it together to be able to make a hash from it
2184 $host_id = implode("/", $parsed);
2186 // We could use any hash algorithm since it isn't a security issue
2187 $host_hash = hash("ripemd128", $host_id);
2189 return $guid_prefix.$host_hash;
2193 * generate an unique URI
2195 * @param integer $uid User id
2196 * @param string $guid An existing GUID (Otherwise it will be generated)
2200 public static function newURI($uid, $guid = "")
2203 $guid = System::createGUID(32);
2206 $hostname = self::getApp()->get_hostname();
2208 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
2210 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2216 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2218 * This can be used to filter for inactive contacts.
2219 * Only do this for public postings to avoid privacy problems, since poco data is public.
2220 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2222 * @param array $arr Contains the just posted item record
2224 private static function updateContact($arr)
2226 // Unarchive the author
2227 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2228 if (DBM::is_result($contact)) {
2229 Contact::unmarkForArchival($contact);
2232 // Unarchive the contact if it's not our own contact
2233 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2234 if (DBM::is_result($contact)) {
2235 Contact::unmarkForArchival($contact);
2238 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2240 // Is it a forum? Then we don't care about the rules from above
2241 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2242 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2248 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2249 ['id' => $arr['contact-id']]);
2251 // Now do the same for the system wide contacts with uid=0
2252 if (!$arr['private']) {
2253 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2254 ['id' => $arr['owner-id']]);
2256 if ($arr['owner-id'] != $arr['author-id']) {
2257 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2258 ['id' => $arr['author-id']]);
2263 public static function setHashtags(&$item)
2266 $tags = get_tags($item["body"]);
2269 if (!count($tags)) {
2273 // This sorting is important when there are hashtags that are part of other hashtags
2274 // Otherwise there could be problems with hashtags like #test and #test2
2277 $URLSearchString = "^\[\]";
2279 // All hashtags should point to the home server if "local_tags" is activated
2280 if (Config::get('system', 'local_tags')) {
2281 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2282 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2284 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2285 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2288 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2289 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2291 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2294 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2296 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2299 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2301 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2304 // Repair recursive urls
2305 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2306 "#$2", $item["body"]);
2308 foreach ($tags as $tag) {
2309 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2313 $basetag = str_replace('_',' ',substr($tag,1));
2315 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2317 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2319 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2320 if (strlen($item["tag"])) {
2321 $item["tag"] = ','.$item["tag"];
2323 $item["tag"] = $newtag.$item["tag"];
2327 // Convert back the masked hashtags
2328 $item["body"] = str_replace("#", "#", $item["body"]);
2331 public static function getGuidById($id)
2333 $item = self::selectFirst(['guid'], ['id' => $id]);
2334 if (DBM::is_result($item)) {
2335 return $item['guid'];
2341 public static function getIdAndNickByGuid($guid, $uid = 0)
2347 $uid == local_user();
2350 // Does the given user have this item?
2352 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2353 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2354 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2355 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2356 if (DBM::is_result($item)) {
2358 $nick = $item["nickname"];
2362 // Or is it anywhere on the server?
2364 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2365 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2366 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2367 AND NOT `item`.`private` AND `item`.`wall`
2368 AND `item`.`guid` = ?", $guid);
2369 if (DBM::is_result($item)) {
2371 $nick = $item["nickname"];
2374 return ["nick" => $nick, "id" => $id];
2378 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2380 * @param int $item_id
2381 * @return bool true if item was deleted, else false
2383 private static function tagDeliver($uid, $item_id)
2387 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2388 if (!DBM::is_result($user)) {
2392 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2393 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2395 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2396 if (!DBM::is_result($item)) {
2400 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2403 * Diaspora uses their own hardwired link URL in @-tags
2404 * instead of the one we supply with webfinger
2406 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2408 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2410 foreach ($matches as $mtch) {
2411 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2413 logger('mention found: ' . $mtch[2]);
2419 if (($community_page || $prvgroup) &&
2420 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2421 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2423 logger("no-mention top-level post to community or private group. delete.");
2424 dba::delete('item', ['id' => $item_id]);
2430 $arr = ['item' => $item, 'user' => $user];
2432 Addon::callHooks('tagged', $arr);
2434 if (!$community_page && !$prvgroup) {
2439 * tgroup delivery - setup a second delivery chain
2440 * prevent delivery looping - only proceed
2441 * if the message originated elsewhere and is a top-level post
2443 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2447 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2448 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2449 if (!DBM::is_result($self)) {
2453 $owner_id = Contact::getIdForURL($self['url']);
2455 // also reset all the privacy bits to the forum default permissions
2457 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2459 $forum_mode = ($prvgroup ? 2 : 1);
2461 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2462 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2463 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2464 dba::update('item', $fields, ['id' => $item_id]);
2466 self::updateThread($item_id);
2468 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2471 public static function isRemoteSelf($contact, &$datarray)
2475 if (!$contact['remote_self']) {
2479 // Prevent the forwarding of posts that are forwarded
2480 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2481 logger('Already forwarded', LOGGER_DEBUG);
2485 // Prevent to forward already forwarded posts
2486 if ($datarray["app"] == $a->get_hostname()) {
2487 logger('Already forwarded (second test)', LOGGER_DEBUG);
2491 // Only forward posts
2492 if ($datarray["verb"] != ACTIVITY_POST) {
2493 logger('No post', LOGGER_DEBUG);
2497 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2498 logger('Not public', LOGGER_DEBUG);
2502 $datarray2 = $datarray;
2503 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2504 if ($contact['remote_self'] == 2) {
2505 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2506 ['uid' => $contact['uid'], 'self' => true]);
2507 if (DBM::is_result($self)) {
2508 $datarray['contact-id'] = $self["id"];
2510 $datarray['owner-name'] = $self["name"];
2511 $datarray['owner-link'] = $self["url"];
2512 $datarray['owner-avatar'] = $self["thumb"];
2514 $datarray['author-name'] = $datarray['owner-name'];
2515 $datarray['author-link'] = $datarray['owner-link'];
2516 $datarray['author-avatar'] = $datarray['owner-avatar'];
2518 unset($datarray['created']);
2519 unset($datarray['edited']);
2521 unset($datarray['network']);
2522 unset($datarray['owner-id']);
2523 unset($datarray['author-id']);
2526 if ($contact['network'] != NETWORK_FEED) {
2527 $datarray["guid"] = System::createGUID(32);
2528 unset($datarray["plink"]);
2529 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2530 $datarray["parent-uri"] = $datarray["uri"];
2531 $datarray["thr-parent"] = $datarray["uri"];
2532 $datarray["extid"] = NETWORK_DFRN;
2533 $urlpart = parse_url($datarray2['author-link']);
2534 $datarray["app"] = $urlpart["host"];
2536 $datarray['private'] = 0;
2540 if ($contact['network'] != NETWORK_FEED) {
2541 // Store the original post
2542 $result = self::insert($datarray2, false, false);
2543 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2545 $datarray["app"] = "Feed";
2549 // Trigger automatic reactions for addons
2550 $datarray['api_source'] = true;
2552 // We have to tell the hooks who we are - this really should be improved
2553 $_SESSION["authenticated"] = true;
2554 $_SESSION["uid"] = $contact['uid'];
2563 * @param array $item
2567 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2569 if (Config::get('system', 'disable_embedded')) {
2573 logger('check for photos', LOGGER_DEBUG);
2574 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2579 $img_start = strpos($orig_body, '[img');
2580 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2581 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2583 while (($img_st_close !== false) && ($img_len !== false)) {
2584 $img_st_close++; // make it point to AFTER the closing bracket
2585 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2587 logger('found photo ' . $image, LOGGER_DEBUG);
2589 if (stristr($image, $site . '/photo/')) {
2590 // Only embed locally hosted photos
2592 $i = basename($image);
2593 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2594 $x = strpos($i, '-');
2597 $res = substr($i, $x + 1);
2598 $i = substr($i, 0, $x);
2599 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2600 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2601 if (DBM::is_result($photo)) {
2603 * Check to see if we should replace this photo link with an embedded image
2604 * 1. No need to do so if the photo is public
2605 * 2. If there's a contact-id provided, see if they're in the access list
2606 * for the photo. If so, embed it.
2607 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2608 * permissions, regardless of order but first check to see if they're an exact
2609 * match to save some processing overhead.
2611 if (self::hasPermissions($photo)) {
2613 $recips = self::enumeratePermissions($photo);
2614 if (in_array($cid, $recips)) {
2618 if (self::samePermissions($item, $photo)) {
2624 $data = $photo['data'];
2625 $type = $photo['type'];
2627 // If a custom width and height were specified, apply before embedding
2628 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2629 logger('scaling photo', LOGGER_DEBUG);
2631 $width = intval($match[1]);
2632 $height = intval($match[2]);
2634 $Image = new Image($data, $type);
2635 if ($Image->isValid()) {
2636 $Image->scaleDown(max($width, $height));
2637 $data = $Image->asString();
2638 $type = $Image->getType();
2642 logger('replacing photo', LOGGER_DEBUG);
2643 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2644 logger('replaced: ' . $image, LOGGER_DATA);
2650 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2651 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2652 if ($orig_body === false) {
2656 $img_start = strpos($orig_body, '[img');
2657 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2658 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2661 $new_body = $new_body . $orig_body;
2666 private static function hasPermissions($obj)
2668 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2669 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2672 private static function samePermissions($obj1, $obj2)
2674 // first part is easy. Check that these are exactly the same.
2675 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2676 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2677 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2678 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2682 // This is harder. Parse all the permissions and compare the resulting set.
2683 $recipients1 = self::enumeratePermissions($obj1);
2684 $recipients2 = self::enumeratePermissions($obj2);
2688 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2689 return ($recipients1 == $recipients2);
2692 // returns an array of contact-ids that are allowed to see this object
2693 private static function enumeratePermissions($obj)
2695 $allow_people = expand_acl($obj['allow_cid']);
2696 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2697 $deny_people = expand_acl($obj['deny_cid']);
2698 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2699 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2700 $deny = array_unique(array_merge($deny_people, $deny_groups));
2701 $recipients = array_diff($recipients, $deny);
2705 public static function getFeedTags($item)
2709 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2711 for ($x = 0; $x < $cnt; $x ++) {
2712 if ($matches[1][$x]) {
2713 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2718 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2720 for ($x = 0; $x < $cnt; $x ++) {
2721 if ($matches[1][$x]) {
2722 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2729 public static function expire($uid, $days, $network = "", $force = false)
2731 if (!$uid || ($days < 1)) {
2735 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2736 $uid, GRAVITY_PARENT];
2739 * $expire_network_only = save your own wall posts
2740 * and just expire conversations started by others
2742 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2744 if ($expire_network_only) {
2745 $condition[0] .= " AND NOT `wall`";
2748 if ($network != "") {
2749 $condition[0] .= " AND `network` = ?";
2750 $condition[] = $network;
2753 * There is an index "uid_network_received" but not "uid_network_created"
2754 * This avoids the creation of another index just for one purpose.
2755 * And it doesn't really matter wether to look at "received" or "created"
2757 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2758 $condition[] = $days;
2760 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2761 $condition[] = $days;
2764 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2766 if (!DBM::is_result($items)) {
2770 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2772 // Forcing expiring of items - but not notes and marked items
2774 $expire_items = true;
2777 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2778 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2779 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2783 while ($item = Item::fetch($items)) {
2784 // don't expire filed items
2786 if (strpos($item['file'], '[') !== false) {
2790 // Only expire posts, not photos and photo comments
2792 if (!$expire_photos && strlen($item['resource-id'])) {
2794 } elseif (!$expire_starred && intval($item['starred'])) {
2796 } elseif (!$expire_notes && $item['type'] == 'note') {
2798 } elseif (!$expire_items && $item['type'] != 'note') {
2802 self::deleteById($item['id'], PRIORITY_LOW);
2807 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2810 public static function firstPostDate($uid, $wall = false)
2812 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2813 $params = ['order' => ['created' => false]];
2814 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2815 if (DBM::is_result($thread)) {
2816 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2822 * @brief add/remove activity to an item
2824 * Toggle activities as like,dislike,attend of an item
2826 * @param string $item_id
2827 * @param string $verb
2828 * Activity verb. One of
2829 * like, unlike, dislike, undislike, attendyes, unattendyes,
2830 * attendno, unattendno, attendmaybe, unattendmaybe
2831 * @hook 'post_local_end'
2833 * 'post_id' => ID of posted item
2835 public static function performLike($item_id, $verb)
2837 if (!local_user() && !remote_user()) {
2844 $activity = ACTIVITY_LIKE;
2848 $activity = ACTIVITY_DISLIKE;
2852 $activity = ACTIVITY_ATTEND;
2856 $activity = ACTIVITY_ATTENDNO;
2859 case 'unattendmaybe':
2860 $activity = ACTIVITY_ATTENDMAYBE;
2863 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2867 // Enable activity toggling instead of on/off
2868 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2870 logger('like: verb ' . $verb . ' item ' . $item_id);
2872 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2873 if (!DBM::is_result($item)) {
2874 logger('like: unknown item ' . $item_id);
2878 $item_uri = $item['uri'];
2880 $uid = $item['uid'];
2881 if (($uid == 0) && local_user()) {
2882 $uid = local_user();
2885 if (!can_write_wall($uid)) {
2886 logger('like: unable to write on wall ' . $uid);
2890 // Retrieves the local post owner
2891 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2892 if (!DBM::is_result($owner_self_contact)) {
2893 logger('like: unknown owner ' . $uid);
2897 // Retrieve the current logged in user's public contact
2898 $author_id = public_contact();
2900 $author_contact = dba::selectFirst('contact', ['url'], ['id' => $author_id]);
2901 if (!DBM::is_result($author_contact)) {
2902 logger('like: unknown author ' . $author_id);
2906 // Contact-id is the uid-dependant author contact
2907 if (local_user() == $uid) {
2908 $item_contact_id = $owner_self_contact['id'];
2909 $item_contact = $owner_self_contact;
2911 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2912 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2913 if (!DBM::is_result($item_contact)) {
2914 logger('like: unknown item contact ' . $item_contact_id);
2919 // Look for an existing verb row
2920 // event participation are essentially radio toggles. If you make a subsequent choice,
2921 // we need to eradicate your first choice.
2922 if ($event_verb_flag) {
2923 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2925 // Translate to the index based activity index
2927 foreach ($verbs as $verb) {
2928 $activities[] = self::activityToIndex($verb);
2931 $activities = self::activityToIndex($activity);
2934 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2935 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
2937 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
2939 // If it exists, mark it as deleted
2940 if (DBM::is_result($like_item)) {
2941 // Already voted, undo it
2942 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
2943 /// @todo Consider using self::update - but before doing so, check the side effects
2944 dba::update('item', $fields, ['id' => $like_item['id']]);
2946 // Clean up the Diaspora signatures for this like
2947 dba::delete('sign', ['iid' => $like_item['id']]);
2949 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
2951 if (!$event_verb_flag || $like_item['verb'] == $activity) {
2956 // Verb is "un-something", just trying to delete existing entries
2957 if (strpos($verb, 'un') === 0) {
2961 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
2964 'guid' => System::createGUID(32),
2965 'uri' => self::newURI($item['uid']),
2966 'uid' => $item['uid'],
2967 'contact-id' => $item_contact_id,
2968 'wall' => $item['wall'],
2970 'network' => NETWORK_DFRN,
2971 'gravity' => GRAVITY_ACTIVITY,
2972 'parent' => $item['id'],
2973 'parent-uri' => $item['uri'],
2974 'thr-parent' => $item['uri'],
2975 'owner-id' => $item['owner-id'],
2976 'author-id' => $author_id,
2977 'body' => $activity,
2978 'verb' => $activity,
2979 'object-type' => $objtype,
2980 'allow_cid' => $item['allow_cid'],
2981 'allow_gid' => $item['allow_gid'],
2982 'deny_cid' => $item['deny_cid'],
2983 'deny_gid' => $item['deny_gid'],
2988 $new_item_id = self::insert($new_item);
2990 // If the parent item isn't visible then set it to visible
2991 if (!$item['visible']) {
2992 self::update(['visible' => true], ['id' => $item['id']]);
2995 // Save the author information for the like in case we need to relay to Diaspora
2996 Diaspora::storeLikeSignature($item_contact, $new_item_id);
2998 $new_item['id'] = $new_item_id;
3000 Addon::callHooks('post_local_end', $new_item);
3002 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3007 private static function addThread($itemid, $onlyshadow = false)
3009 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3010 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3011 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3012 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3013 $item = self::selectFirst($fields, $condition);
3015 if (!DBM::is_result($item)) {
3019 $item['iid'] = $itemid;
3022 $result = dba::insert('thread', $item);
3024 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3028 private static function updateThread($itemid, $setmention = false)
3030 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3031 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3032 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3033 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3035 $item = self::selectFirst($fields, $condition);
3036 if (!DBM::is_result($item)) {
3041 $item["mention"] = 1;
3048 foreach ($item as $field => $data) {
3049 if (!in_array($field, ["guid"])) {
3050 $fields[$field] = $data;
3054 $result = dba::update('thread', $fields, ['iid' => $itemid]);
3056 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3059 private static function deleteThread($itemid, $itemuri = "")
3061 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3062 if (!DBM::is_result($item)) {
3063 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3067 // Using dba::delete at this time could delete the associated item entries
3068 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3070 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3072 if ($itemuri != "") {
3073 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3074 if (!self::exists($condition)) {
3075 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3076 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);