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 // Field list for additional delivery data
77 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
79 // All fields in the item table
80 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
81 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
82 'created', 'edited', 'commented', 'received', 'changed', 'verb',
83 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
84 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
85 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
86 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
87 'title', 'content-warning', 'body', 'location', 'coord', 'app',
88 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
89 'author-id', 'author-link', 'author-name', 'author-avatar',
90 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
92 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
93 // The item-activity table only stores the index and needs this array to know the matching activity.
94 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
96 private static $legacy_mode = null;
98 public static function isLegacyMode()
100 if (is_null(self::$legacy_mode)) {
101 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
104 return self::$legacy_mode;
108 * @brief returns an activity index from an activity string
110 * @param string $activity activity string
111 * @return integer Activity index
113 private static function activityToIndex($activity)
115 $index = array_search($activity, self::ACTIVITIES);
117 if (is_bool($index)) {
125 * @brief returns an activity string from an activity index
127 * @param integer $index activity index
128 * @return string Activity string
130 private static function indexToActivity($index)
132 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
136 return self::ACTIVITIES[$index];
140 * @brief Fetch a single item row
142 * @param mixed $stmt statement object
143 * @return array current row
145 public static function fetch($stmt)
147 $row = dba::fetch($stmt);
153 // ---------------------- Transform item structure data ----------------------
155 // We prefer the data from the user's contact over the public one
156 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
157 ($row['author-link'] == $row['contact-link'])) {
158 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
159 $row['author-avatar'] = $row['contact-avatar'];
161 if (isset($row['author-name']) && !empty($row['contact-name'])) {
162 $row['author-name'] = $row['contact-name'];
166 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
167 ($row['owner-link'] == $row['contact-link'])) {
168 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
169 $row['owner-avatar'] = $row['contact-avatar'];
171 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
172 $row['owner-name'] = $row['contact-name'];
176 // We can always comment on posts from these networks
177 if (array_key_exists('writable', $row) &&
178 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
179 $row['writable'] = true;
182 // ---------------------- Transform item content data ----------------------
184 // Fetch data from the item-content table whenever there is content there
185 if (self::isLegacyMode()) {
186 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
187 foreach ($legacy_fields as $field) {
188 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
189 $row[$field] = $row['internal-item-' . $field];
191 unset($row['internal-item-' . $field]);
195 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
196 $row['verb'] = self::indexToActivity($row['internal-activity']);
197 if (array_key_exists('title', $row)) {
200 if (array_key_exists('body', $row)) {
201 $row['body'] = $row['verb'];
203 if (array_key_exists('object', $row)) {
206 if (array_key_exists('object-type', $row)) {
207 $row['object-type'] = ACTIVITY_OBJ_NOTE;
209 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
210 // Posts don't have an object or target - but having tags or files.
211 // We safe some performance by building tag and file strings only here.
212 // We remove object and target since they aren't used for this type.
213 if (array_key_exists('object', $row)) {
216 if (array_key_exists('target', $row)) {
221 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
222 // Build the tag string out of the term entries
223 if (array_key_exists('tag', $row) && empty($row['tag'])) {
224 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
227 // Build the file string out of the term entries
228 if (array_key_exists('file', $row) && empty($row['file'])) {
229 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
233 // Remove internal fields
234 unset($row['internal-activity']);
235 unset($row['internal-network']);
236 unset($row['internal-iid']);
237 unset($row['internal-iaid']);
238 unset($row['internal-icid']);
244 * @brief Fills an array with data from an item query
246 * @param object $stmt statement object
247 * @return array Data array
249 public static function inArray($stmt, $do_close = true) {
250 if (is_bool($stmt)) {
255 while ($row = self::fetch($stmt)) {
265 * @brief Check if item data exists
267 * @param array $condition array of fields for condition
269 * @return boolean Are there rows for that condition?
271 public static function exists($condition) {
272 $stmt = self::select(['id'], $condition, ['limit' => 1]);
274 if (is_bool($stmt)) {
277 $retval = (dba::num_rows($stmt) > 0);
286 * Retrieve a single record from the item table for a given user and returns it in an associative array
288 * @brief Retrieve a single record from a table
289 * @param integer $uid User ID
290 * @param array $fields
291 * @param array $condition
292 * @param array $params
296 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
298 $params['uid'] = $uid;
300 if (empty($selected)) {
301 $selected = Item::DISPLAY_FIELDLIST;
304 return self::selectFirst($selected, $condition, $params);
308 * @brief Select rows from the item table for a given user
310 * @param integer $uid User ID
311 * @param array $selected Array of selected fields, empty for all
312 * @param array $condition Array of fields for condition
313 * @param array $params Array of several parameters
315 * @return boolean|object
317 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
319 $params['uid'] = $uid;
321 if (empty($selected)) {
322 $selected = Item::DISPLAY_FIELDLIST;
325 return self::select($selected, $condition, $params);
329 * Retrieve a single record from the item table and returns it in an associative array
331 * @brief Retrieve a single record from a table
332 * @param array $fields
333 * @param array $condition
334 * @param array $params
338 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
340 $params['limit'] = 1;
342 $result = self::select($fields, $condition, $params);
344 if (is_bool($result)) {
347 $row = self::fetch($result);
354 * @brief Select rows from the item table
356 * @param array $selected Array of selected fields, empty for all
357 * @param array $condition Array of fields for condition
358 * @param array $params Array of several parameters
360 * @return boolean|object
362 public static function select(array $selected = [], array $condition = [], $params = [])
367 if (isset($params['uid'])) {
368 $uid = $params['uid'];
372 $fields = self::fieldlist($selected);
374 $select_fields = self::constructSelectFields($fields, $selected);
376 $condition_string = dba::buildCondition($condition);
378 $condition_string = self::addTablesToFields($condition_string, $fields);
381 $condition_string = $condition_string . ' AND ' . self::condition(false);
384 $param_string = self::addTablesToFields(dba::buildParameter($params), $fields);
386 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
388 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
390 return dba::p($sql, $condition);
394 * @brief Select rows from the starting post in the item table
396 * @param integer $uid User ID
397 * @param array $fields Array of selected fields, empty for all
398 * @param array $condition Array of fields for condition
399 * @param array $params Array of several parameters
401 * @return boolean|object
403 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
405 $params['uid'] = $uid;
407 if (empty($selected)) {
408 $selected = Item::DISPLAY_FIELDLIST;
411 return self::selectThread($selected, $condition, $params);
415 * Retrieve a single record from the starting post in the item table and returns it in an associative array
417 * @brief Retrieve a single record from a table
418 * @param integer $uid User ID
419 * @param array $selected
420 * @param array $condition
421 * @param array $params
425 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
427 $params['uid'] = $uid;
429 if (empty($selected)) {
430 $selected = Item::DISPLAY_FIELDLIST;
433 return self::selectFirstThread($selected, $condition, $params);
437 * Retrieve a single record from the starting post in the item table and returns it in an associative array
439 * @brief Retrieve a single record from a table
440 * @param array $fields
441 * @param array $condition
442 * @param array $params
446 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
448 $params['limit'] = 1;
449 $result = self::selectThread($fields, $condition, $params);
451 if (is_bool($result)) {
454 $row = self::fetch($result);
461 * @brief Select rows from the starting post in the item table
463 * @param array $selected Array of selected fields, empty for all
464 * @param array $condition Array of fields for condition
465 * @param array $params Array of several parameters
467 * @return boolean|object
469 public static function selectThread(array $selected = [], array $condition = [], $params = [])
474 if (isset($params['uid'])) {
475 $uid = $params['uid'];
479 $fields = self::fieldlist($selected);
481 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
482 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
483 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
484 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
486 $select_fields = self::constructSelectFields($fields, $selected);
488 $condition_string = dba::buildCondition($condition);
490 $condition_string = self::addTablesToFields($condition_string, $threadfields);
491 $condition_string = self::addTablesToFields($condition_string, $fields);
494 $condition_string = $condition_string . ' AND ' . self::condition(true);
497 $param_string = dba::buildParameter($params);
498 $param_string = self::addTablesToFields($param_string, $threadfields);
499 $param_string = self::addTablesToFields($param_string, $fields);
501 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
503 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
505 return dba::p($sql, $condition);
509 * @brief Returns a list of fields that are associated with the item table
511 * @return array field list
513 private static function fieldlist($selected)
517 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
518 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
519 'created', 'edited', 'commented', 'received', 'changed',
520 'resource-id', 'event-id', 'tag', 'attach', 'post-type',
521 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'psid',
522 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
523 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
524 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
525 'network' => 'internal-network', 'icid' => 'internal-icid',
526 'iaid' => 'internal-iaid'];
528 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
530 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
532 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
534 $fields['author'] = ['url' => 'author-link', 'name' => 'author-name',
535 'thumb' => 'author-avatar', 'nick' => 'author-nick', 'network' => 'author-network'];
537 $fields['owner'] = ['url' => 'owner-link', 'name' => 'owner-name',
538 'thumb' => 'owner-avatar', 'nick' => 'owner-nick', 'network' => 'owner-network'];
540 $fields['contact'] = ['url' => 'contact-link', 'name' => 'contact-name', 'thumb' => 'contact-avatar',
541 'writable', 'self', 'id' => 'cid', 'alias', 'uid' => 'contact-uid',
542 'photo', 'name-date', 'uri-date', 'avatar-date', 'thumb', 'dfrn-id'];
544 $fields['parent-item'] = ['guid' => 'parent-guid', 'network' => 'parent-network'];
546 $fields['parent-item-author'] = ['url' => 'parent-author-link', 'name' => 'parent-author-name'];
548 $fields['event'] = ['created' => 'event-created', 'edited' => 'event-edited',
549 'start' => 'event-start','finish' => 'event-finish',
550 'summary' => 'event-summary','desc' => 'event-desc',
551 'location' => 'event-location', 'type' => 'event-type',
552 'nofinish' => 'event-nofinish','adjust' => 'event-adjust',
553 'ignore' => 'event-ignore', 'id' => 'event-id'];
555 $fields['sign'] = ['signed_text', 'signature', 'signer'];
561 * @brief Returns SQL condition for the "select" functions
563 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
565 * @return string SQL condition
567 private static function condition($thread_mode)
570 $master_table = "`thread`";
572 $master_table = "`item`";
574 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`) ";
578 * @brief Returns all needed "JOIN" commands for the "select" functions
580 * @param integer $uid User ID
581 * @param string $sql_commands The parts of the built SQL commands in the "select" functions
582 * @param boolean $thread_mode Called for the items (false) or for the threads (true)
584 * @return string The SQL joins for the "select" functions
586 private static function constructJoins($uid, $sql_commands, $thread_mode, $user_mode)
589 $master_table = "`thread`";
590 $master_table_key = "`thread`.`iid`";
591 $joins = "STRAIGHT_JOIN `item` ON `item`.`id` = `thread`.`iid` ";
593 $master_table = "`item`";
594 $master_table_key = "`item`.`id`";
599 $joins .= sprintf("STRAIGHT_JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`
600 AND NOT `contact`.`blocked`
601 AND ((NOT `contact`.`readonly` AND NOT `contact`.`pending` AND (`contact`.`rel` IN (%s, %s)))
602 OR `contact`.`self` OR `item`.`gravity` != %d OR `contact`.`uid` = 0)
603 STRAIGHT_JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id` AND NOT `author`.`blocked`
604 STRAIGHT_JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id` AND NOT `owner`.`blocked`
605 LEFT JOIN `user-item` ON `user-item`.`iid` = $master_table_key AND `user-item`.`uid` = %d",
606 CONTACT_IS_SHARING, CONTACT_IS_FRIEND, GRAVITY_PARENT, intval($uid));
608 if (strpos($sql_commands, "`contact`.") !== false) {
609 $joins .= "LEFT JOIN `contact` ON `contact`.`id` = $master_table.`contact-id`";
611 if (strpos($sql_commands, "`author`.") !== false) {
612 $joins .= " LEFT JOIN `contact` AS `author` ON `author`.`id` = $master_table.`author-id`";
614 if (strpos($sql_commands, "`owner`.") !== false) {
615 $joins .= " LEFT JOIN `contact` AS `owner` ON `owner`.`id` = $master_table.`owner-id`";
619 if (strpos($sql_commands, "`group_member`.") !== false) {
620 $joins .= " STRAIGHT_JOIN `group_member` ON `group_member`.`contact-id` = $master_table.`contact-id`";
623 if (strpos($sql_commands, "`user`.") !== false) {
624 $joins .= " STRAIGHT_JOIN `user` ON `user`.`uid` = $master_table.`uid`";
627 if (strpos($sql_commands, "`event`.") !== false) {
628 $joins .= " LEFT JOIN `event` ON `event-id` = `event`.`id`";
631 if (strpos($sql_commands, "`sign`.") !== false) {
632 $joins .= " LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`";
635 if (strpos($sql_commands, "`item-activity`.") !== false) {
636 $joins .= " LEFT JOIN `item-activity` ON `item-activity`.`id` = `item`.`iaid`";
639 if (strpos($sql_commands, "`item-content`.") !== false) {
640 $joins .= " LEFT JOIN `item-content` ON `item-content`.`id` = `item`.`icid`";
643 if (strpos($sql_commands, "`item-delivery-data`.") !== false) {
644 $joins .= " LEFT JOIN `item-delivery-data` ON `item-delivery-data`.`iid` = `item`.`id`";
647 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
648 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
651 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
652 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
659 * @brief Add the field list for the "select" functions
661 * @param array $fields The field definition array
662 * @param array $selected The array with the selected fields from the "select" functions
664 * @return string The field list
666 private static function constructSelectFields($fields, $selected)
668 if (!empty($selected)) {
669 $selected[] = 'internal-iid';
670 $selected[] = 'internal-iaid';
671 $selected[] = 'internal-icid';
672 $selected[] = 'internal-network';
675 if (in_array('verb', $selected)) {
676 $selected[] = 'internal-activity';
680 foreach ($fields as $table => $table_fields) {
681 foreach ($table_fields as $field => $select) {
682 if (empty($selected) || in_array($select, $selected)) {
683 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
684 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
685 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
687 if (is_int($field)) {
688 $selection[] = "`" . $table . "`.`" . $select . "`";
690 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
695 return implode(", ", $selection);
699 * @brief add table definition to fields in an SQL query
701 * @param string $query SQL query
702 * @param array $fields The field definition array
704 * @return string the changed SQL query
706 private static function addTablesToFields($query, $fields)
708 foreach ($fields as $table => $table_fields) {
709 foreach ($table_fields as $alias => $field) {
710 if (is_int($alias)) {
711 $replace_field = $field;
713 $replace_field = $alias;
716 $search = "/([^\.])`" . $field . "`/i";
717 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
718 $query = preg_replace($search, $replace, $query);
725 * @brief Generate a server unique item hash for linking between the item tables
727 * @param string $uri Item URI
728 * @param date $created Item creation date
730 * @return string the item hash
732 private static function itemHash($uri, $created)
734 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
738 * @brief Update existing item entries
740 * @param array $fields The fields that are to be changed
741 * @param array $condition The condition for finding the item entries
743 * In the future we may have to change permissions as well.
744 * Then we had to add the user id as third parameter.
746 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
748 * @return integer|boolean number of affected rows - or "false" if there was an error
750 public static function update(array $fields, array $condition)
752 if (empty($condition) || empty($fields)) {
756 // To ensure the data integrity we do it in an transaction
759 // We cannot simply expand the condition to check for origin entries
760 // The condition needn't to be a simple array but could be a complex condition.
761 // And we have to execute this query before the update to ensure to fetch the same data.
762 $items = dba::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
764 $content_fields = [];
765 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
766 if (isset($fields[$field])) {
767 $content_fields[$field] = $fields[$field];
768 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
769 unset($fields[$field]);
771 $fields[$field] = null;
776 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
777 foreach ($clear_fields as $field) {
778 if (array_key_exists($field, $fields)) {
779 $fields[$field] = null;
783 if (array_key_exists('tag', $fields)) {
784 $tags = $fields['tag'];
785 $fields['tag'] = null;
790 if (array_key_exists('file', $fields)) {
791 $files = $fields['file'];
792 $fields['file'] = null;
797 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
798 'inform' => defaults($fields, 'inform', '')];
800 $fields['postopts'] = null;
801 $fields['inform'] = null;
803 if (!empty($fields)) {
804 $success = dba::update('item', $fields, $condition);
813 // When there is no content for the "old" item table, this will count the fetched items
814 $rows = dba::affected_rows();
816 while ($item = dba::fetch($items)) {
818 // This part here can safely be removed when the legacy fields in the item had been removed
819 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
821 // Fetch the uri-hash from an existing item entry if there is one
822 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
823 $existing = dba::selectfirst('item', ['uri-hash'], $item_condition);
824 if (DBM::is_result($existing)) {
825 $item['uri-hash'] = $existing['uri-hash'];
827 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
830 dba::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
831 dba::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
832 dba::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
835 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
836 if (!empty($item['iaid'])) {
837 $update_condition = ['id' => $item['iaid']];
839 $update_condition = ['uri-hash' => $item['uri-hash']];
841 self::updateActivity($content_fields, $update_condition);
843 if (empty($item['iaid'])) {
844 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
845 if (DBM::is_result($item_activity)) {
846 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
847 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
848 if (self::isLegacyMode()) {
849 $item_fields[$field] = null;
851 unset($item_fields[$field]);
854 dba::update('item', $item_fields, ['id' => $item['id']]);
856 if (!empty($item['icid']) && !dba::exists('item', ['icid' => $item['icid']])) {
857 dba::delete('item-content', ['id' => $item['icid']]);
860 } elseif (!empty($item['icid'])) {
861 dba::update('item', ['icid' => null], ['id' => $item['id']]);
863 if (!dba::exists('item', ['icid' => $item['icid']])) {
864 dba::delete('item-content', ['id' => $item['icid']]);
868 if (!empty($item['icid'])) {
869 $update_condition = ['id' => $item['icid']];
871 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
873 self::updateContent($content_fields, $update_condition);
875 if (empty($item['icid'])) {
876 $item_content = dba::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
877 if (DBM::is_result($item_content)) {
878 $item_fields = ['icid' => $item_content['id']];
879 // Clear all fields in the item table that have a content in the item-content table
880 foreach ($item_content as $field => $content) {
881 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
882 if (self::isLegacyMode()) {
883 $item_fields[$field] = null;
885 unset($item_fields[$field]);
889 dba::update('item', $item_fields, ['id' => $item['id']]);
895 Term::insertFromTagFieldByItemId($item['id'], $tags);
896 if (!empty($item['tag'])) {
897 dba::update('item', ['tag' => ''], ['id' => $item['id']]);
901 if (!empty($files)) {
902 Term::insertFromFileFieldByItemId($item['id'], $files);
903 if (!empty($item['file'])) {
904 dba::update('item', ['file' => ''], ['id' => $item['id']]);
908 self::updateDeliveryData($item['id'], $delivery_data);
910 self::updateThread($item['id']);
912 // We only need to notfiy others when it is an original entry from us.
913 // Only call the notifier when the item has some content relevant change.
914 if ($item['origin'] && in_array('edited', array_keys($fields))) {
915 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
925 * @brief Delete an item and notify others about it - if it was ours
927 * @param array $condition The condition for finding the item entries
928 * @param integer $priority Priority for the notification
930 public static function delete($condition, $priority = PRIORITY_HIGH)
932 $items = dba::select('item', ['id'], $condition);
933 while ($item = dba::fetch($items)) {
934 self::deleteById($item['id'], $priority);
940 * @brief Delete an item for an user and notify others about it - if it was ours
942 * @param array $condition The condition for finding the item entries
943 * @param integer $uid User who wants to delete this item
945 public static function deleteForUser($condition, $uid)
951 $items = dba::select('item', ['id', 'uid'], $condition);
952 while ($item = dba::fetch($items)) {
953 // "Deleting" global items just means hiding them
954 if ($item['uid'] == 0) {
955 dba::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
956 } elseif ($item['uid'] == $uid) {
957 self::deleteById($item['id'], PRIORITY_HIGH);
959 logger('Wrong ownership. Not deleting item ' . $item['id']);
966 * @brief Delete an item and notify others about it - if it was ours
968 * @param integer $item_id Item ID that should be delete
969 * @param integer $priority Priority for the notification
971 * @return boolean success
973 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
975 // locate item to be deleted
976 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
977 'deleted', 'file', 'resource-id', 'event-id', 'attach',
978 'verb', 'object-type', 'object', 'target', 'contact-id'];
979 $item = self::selectFirst($fields, ['id' => $item_id]);
980 if (!DBM::is_result($item)) {
981 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
985 if ($item['deleted']) {
986 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
990 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
991 if (!DBM::is_result($parent)) {
992 $parent = ['origin' => false];
995 // clean up categories and tags so they don't end up as orphans
998 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1000 foreach ($matches as $mtch) {
1001 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1007 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1009 foreach ($matches as $mtch) {
1010 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1015 * If item is a link to a photo resource, nuke all the associated photos
1016 * (visitors will not have photo resources)
1017 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1018 * generate a resource-id and therefore aren't intimately linked to the item.
1020 if (strlen($item['resource-id'])) {
1021 dba::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1024 // If item is a link to an event, delete the event.
1025 if (intval($item['event-id'])) {
1026 Event::delete($item['event-id']);
1029 // If item has attachments, drop them
1030 foreach (explode(", ", $item['attach']) as $attach) {
1031 preg_match("|attach/(\d+)|", $attach, $matches);
1032 if (is_array($matches) && count($matches) > 1) {
1033 dba::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1037 // Delete tags that had been attached to other items
1038 self::deleteTagsFromItem($item);
1040 // Set the item to "deleted"
1041 // This erasing of item content is superfluous for items with a matching item-content.
1042 // But for the next time we will still have old content in the item table.
1043 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
1044 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
1045 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
1046 dba::update('item', $item_fields, ['id' => $item['id']]);
1048 Term::insertFromTagFieldByItemId($item['id'], '');
1049 Term::insertFromFileFieldByItemId($item['id'], '');
1050 self::deleteThread($item['id'], $item['parent-uri']);
1052 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1053 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1056 dba::delete('item-delivery-data', ['iid' => $item['id']]);
1058 // If it's the parent of a comment thread, kill all the kids
1059 if ($item['id'] == $item['parent']) {
1060 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1063 // Is it our comment and/or our thread?
1064 if ($item['origin'] || $parent['origin']) {
1066 // When we delete the original post we will delete all existing copies on the server as well
1067 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1069 // send the notification upstream/downstream
1070 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1071 } elseif ($item['uid'] != 0) {
1073 // When we delete just our local user copy of an item, we have to set a marker to hide it
1074 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1075 if (DBM::is_result($global_item)) {
1076 dba::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1080 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1085 private static function deleteTagsFromItem($item)
1087 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1091 $xo = XML::parseString($item["object"], false);
1092 $xt = XML::parseString($item["target"], false);
1094 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1098 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1099 if (!DBM::is_result($i)) {
1103 // For tags, the owner cannot remove the tag on the author's copy of the post.
1104 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1105 $author_copy = $item["origin"];
1107 if (($owner_remove && $author_copy) || !$owner_remove) {
1111 $tags = explode(',', $i["tag"]);
1114 foreach ($tags as $tag) {
1115 if (trim($tag) !== trim($xo->body)) {
1116 $newtags[] = trim($tag);
1120 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1123 private static function guid($item, $notify)
1125 if (!empty($item['guid'])) {
1126 return notags(trim($item['guid']));
1130 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1131 // We add the hash of our own host because our host is the original creator of the post.
1132 $prefix_host = get_app()->get_hostname();
1136 // We are only storing the post so we create a GUID from the original hostname.
1137 if (!empty($item['author-link'])) {
1138 $parsed = parse_url($item['author-link']);
1139 if (!empty($parsed['host'])) {
1140 $prefix_host = $parsed['host'];
1144 if (empty($prefix_host) && !empty($item['plink'])) {
1145 $parsed = parse_url($item['plink']);
1146 if (!empty($parsed['host'])) {
1147 $prefix_host = $parsed['host'];
1151 if (empty($prefix_host) && !empty($item['uri'])) {
1152 $parsed = parse_url($item['uri']);
1153 if (!empty($parsed['host'])) {
1154 $prefix_host = $parsed['host'];
1158 // Is it in the format data@host.tld? - Used for mail contacts
1159 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1160 $mailparts = explode('@', $item['author-link']);
1161 $prefix_host = array_pop($mailparts);
1165 if (!empty($item['plink'])) {
1166 $guid = self::guidFromUri($item['plink'], $prefix_host);
1167 } elseif (!empty($item['uri'])) {
1168 $guid = self::guidFromUri($item['uri'], $prefix_host);
1170 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1176 private static function contactId($item)
1178 $contact_id = (int)$item["contact-id"];
1180 if (!empty($contact_id)) {
1183 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1185 * First we are looking for a suitable contact that matches with the author of the post
1186 * This is done only for comments
1188 if ($item['parent-uri'] != $item['uri']) {
1189 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1192 // If not present then maybe the owner was found
1193 if ($contact_id == 0) {
1194 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1197 // Still missing? Then use the "self" contact of the current user
1198 if ($contact_id == 0) {
1199 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1200 if (DBM::is_result($self)) {
1201 $contact_id = $self["id"];
1204 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1209 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1213 // If it is a posting where users should get notifications, then define it as wall posting
1216 $item['origin'] = 1;
1217 $item['network'] = NETWORK_DFRN;
1218 $item['protocol'] = PROTOCOL_DFRN;
1220 if (is_int($notify)) {
1221 $priority = $notify;
1223 $priority = PRIORITY_HIGH;
1226 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1229 $item['guid'] = self::guid($item, $notify);
1230 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1232 // Store conversation data
1233 $item = Conversation::insert($item);
1236 * If a Diaspora signature structure was passed in, pull it out of the
1237 * item array and set it aside for later storage.
1241 if (x($item, 'dsprsig')) {
1242 $encoded_signature = $item['dsprsig'];
1243 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1244 unset($item['dsprsig']);
1247 if (!empty($item['diaspora_signed_text'])) {
1248 $diaspora_signed_text = $item['diaspora_signed_text'];
1249 unset($item['diaspora_signed_text']);
1251 $diaspora_signed_text = '';
1254 // Converting the plink
1255 /// @TODO Check if this is really still needed
1256 if ($item['network'] == NETWORK_OSTATUS) {
1257 if (isset($item['plink'])) {
1258 $item['plink'] = OStatus::convertHref($item['plink']);
1259 } elseif (isset($item['uri'])) {
1260 $item['plink'] = OStatus::convertHref($item['uri']);
1264 if (!empty($item['thr-parent'])) {
1265 $item['parent-uri'] = $item['thr-parent'];
1268 if (isset($item['gravity'])) {
1269 $item['gravity'] = intval($item['gravity']);
1270 } elseif ($item['parent-uri'] === $item['uri']) {
1271 $item['gravity'] = GRAVITY_PARENT;
1272 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1273 $item['gravity'] = GRAVITY_COMMENT;
1275 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1276 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1279 $uid = intval($item['uid']);
1281 // check for create date and expire time
1282 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1284 $user = dba::selectFirst('user', ['expire'], ['uid' => $uid]);
1285 if (DBM::is_result($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1286 $expire_interval = $user['expire'];
1289 if (($expire_interval > 0) && !empty($item['created'])) {
1290 $expire_date = time() - ($expire_interval * 86400);
1291 $created_date = strtotime($item['created']);
1292 if ($created_date < $expire_date) {
1293 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1299 * Do we already have this item?
1300 * We have to check several networks since Friendica posts could be repeated
1301 * via OStatus (maybe Diasporsa as well)
1303 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1304 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1305 trim($item['uri']), $item['uid'],
1306 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1307 $existing = self::selectFirst(['id', 'network'], $condition);
1308 if (DBM::is_result($existing)) {
1309 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1311 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1314 return $existing["id"];
1318 // Ensure to always have the same creation date.
1319 $existing = dba::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1320 if (DBM::is_result($existing)) {
1321 $item['created'] = $existing['created'];
1322 $item['uri-hash'] = $existing['uri-hash'];
1325 self::addLanguageToItemArray($item);
1327 $item['wall'] = intval(defaults($item, 'wall', 0));
1328 $item['extid'] = trim(defaults($item, 'extid', ''));
1329 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1330 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1331 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1332 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1333 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1334 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1335 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1336 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1337 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1338 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1339 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1340 $item['title'] = trim(defaults($item, 'title', ''));
1341 $item['location'] = trim(defaults($item, 'location', ''));
1342 $item['coord'] = trim(defaults($item, 'coord', ''));
1343 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1344 $item['deleted'] = 0;
1345 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1346 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1347 $item['verb'] = trim(defaults($item, 'verb', ''));
1348 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1349 $item['object'] = trim(defaults($item, 'object', ''));
1350 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1351 $item['target'] = trim(defaults($item, 'target', ''));
1352 $item['plink'] = trim(defaults($item, 'plink', ''));
1353 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1354 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1355 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1356 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1357 $item['private'] = intval(defaults($item, 'private', 0));
1358 $item['body'] = trim(defaults($item, 'body', ''));
1359 $item['tag'] = trim(defaults($item, 'tag', ''));
1360 $item['attach'] = trim(defaults($item, 'attach', ''));
1361 $item['app'] = trim(defaults($item, 'app', ''));
1362 $item['origin'] = intval(defaults($item, 'origin', 0));
1363 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1364 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1365 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1366 $item['inform'] = trim(defaults($item, 'inform', ''));
1367 $item['file'] = trim(defaults($item, 'file', ''));
1369 // Unique identifier to be linked against item-activities and item-content
1370 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1372 // When there is no content then we don't post it
1373 if ($item['body'].$item['title'] == '') {
1374 logger('No body, no title.');
1378 // Items cannot be stored before they happen ...
1379 if ($item['created'] > DateTimeFormat::utcNow()) {
1380 $item['created'] = DateTimeFormat::utcNow();
1383 // We haven't invented time travel by now.
1384 if ($item['edited'] > DateTimeFormat::utcNow()) {
1385 $item['edited'] = DateTimeFormat::utcNow();
1388 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1390 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1391 $item["contact-id"] = self::contactId($item);
1393 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1394 'photo' => $item['author-avatar'], 'network' => $item['network']];
1396 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1398 if (Contact::isBlocked($item["author-id"])) {
1399 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1403 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1404 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1406 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1408 if (Contact::isBlocked($item["owner-id"])) {
1409 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1413 // These fields aren't stored anymore in the item table, they are fetched upon request
1414 unset($item['author-link']);
1415 unset($item['author-name']);
1416 unset($item['author-avatar']);
1418 unset($item['owner-link']);
1419 unset($item['owner-name']);
1420 unset($item['owner-avatar']);
1422 if ($item['network'] == NETWORK_PHANTOM) {
1423 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1425 $item['network'] = NETWORK_DFRN;
1426 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1429 // Checking if there is already an item with the same guid
1430 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1431 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1432 if (self::exists($condition)) {
1433 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1437 // Check for hashtags in the body and repair or add hashtag links
1438 self::setHashtags($item);
1440 $item['thr-parent'] = $item['parent-uri'];
1448 if ($item['parent-uri'] === $item['uri']) {
1450 $parent_deleted = 0;
1451 $allow_cid = $item['allow_cid'];
1452 $allow_gid = $item['allow_gid'];
1453 $deny_cid = $item['deny_cid'];
1454 $deny_gid = $item['deny_gid'];
1455 $notify_type = 'wall-new';
1457 // find the parent and snarf the item id and ACLs
1458 // and anything else we need to inherit
1460 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1461 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1462 'wall', 'private', 'forum_mode', 'origin'];
1463 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1464 $params = ['order' => ['id' => false]];
1465 $parent = self::selectFirst($fields, $condition, $params);
1467 if (DBM::is_result($parent)) {
1468 // is the new message multi-level threaded?
1469 // even though we don't support it now, preserve the info
1470 // and re-attach to the conversation parent.
1472 if ($parent['uri'] != $parent['parent-uri']) {
1473 $item['parent-uri'] = $parent['parent-uri'];
1475 $condition = ['uri' => $item['parent-uri'],
1476 'parent-uri' => $item['parent-uri'],
1477 'uid' => $item['uid']];
1478 $params = ['order' => ['id' => false]];
1479 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1481 if (DBM::is_result($toplevel_parent)) {
1482 $parent = $toplevel_parent;
1486 $parent_id = $parent['id'];
1487 $parent_deleted = $parent['deleted'];
1488 $allow_cid = $parent['allow_cid'];
1489 $allow_gid = $parent['allow_gid'];
1490 $deny_cid = $parent['deny_cid'];
1491 $deny_gid = $parent['deny_gid'];
1492 $item['wall'] = $parent['wall'];
1493 $notify_type = 'comment-new';
1496 * If the parent is private, force privacy for the entire conversation
1497 * This differs from the above settings as it subtly allows comments from
1498 * email correspondents to be private even if the overall thread is not.
1500 if ($parent['private']) {
1501 $item['private'] = $parent['private'];
1505 * Edge case. We host a public forum that was originally posted to privately.
1506 * The original author commented, but as this is a comment, the permissions
1507 * weren't fixed up so it will still show the comment as private unless we fix it here.
1509 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1510 $item['private'] = 0;
1513 // If its a post from myself then tag the thread as "mention"
1514 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1515 $user = dba::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1516 if (DBM::is_result($user)) {
1517 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1518 $self_id = Contact::getIdForURL($self, 0, true);
1519 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1520 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1521 dba::update('thread', ['mention' => true], ['iid' => $parent_id]);
1522 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1527 * Allow one to see reply tweets from status.net even when
1528 * we don't have or can't see the original post.
1530 if ($force_parent) {
1531 logger('$force_parent=true, reply converted to top-level post.');
1533 $item['parent-uri'] = $item['uri'];
1534 $item['gravity'] = GRAVITY_PARENT;
1536 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1540 $parent_deleted = 0;
1544 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1545 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1546 if (self::exists($condition)) {
1547 logger('duplicated item with the same uri found. '.print_r($item,true));
1551 // On Friendica and Diaspora the GUID is unique
1552 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1553 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1554 if (self::exists($condition)) {
1555 logger('duplicated item with the same guid found. '.print_r($item,true));
1559 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1560 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1561 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1562 if (self::exists($condition)) {
1563 logger('duplicated item with the same body found. '.print_r($item,true));
1568 // Is this item available in the global items (with uid=0)?
1569 if ($item["uid"] == 0) {
1570 $item["global"] = true;
1572 // Set the global flag on all items if this was a global item entry
1573 dba::update('item', ['global' => true], ['uri' => $item["uri"]]);
1575 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1579 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1582 $private = $item['private'];
1585 $item["allow_cid"] = $allow_cid;
1586 $item["allow_gid"] = $allow_gid;
1587 $item["deny_cid"] = $deny_cid;
1588 $item["deny_gid"] = $deny_gid;
1589 $item["private"] = $private;
1590 $item["deleted"] = $parent_deleted;
1592 // Fill the cache field
1593 put_item_in_cache($item);
1596 $item['edit'] = false;
1597 $item['parent'] = $parent_id;
1598 Addon::callHooks('post_local', $item);
1599 unset($item['edit']);
1600 unset($item['parent']);
1602 Addon::callHooks('post_remote', $item);
1605 // This array field is used to trigger some automatic reactions
1606 // It is mainly used in the "post_local" hook.
1607 unset($item['api_source']);
1609 if (x($item, 'cancel')) {
1610 logger('post cancelled by addon.');
1615 * Check for already added items.
1616 * There is a timing issue here that sometimes creates double postings.
1617 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1619 if ($item["uid"] == 0) {
1620 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1621 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1626 logger('' . print_r($item,true), LOGGER_DATA);
1628 if (array_key_exists('tag', $item)) {
1629 $tags = $item['tag'];
1630 unset($item['tag']);
1635 if (array_key_exists('file', $item)) {
1636 $files = $item['file'];
1637 unset($item['file']);
1642 // Creates the permission set
1643 // Currently we only store the data but don't using it
1644 $item['psid'] = PermissionSet::fetchIDForPost($item);
1646 // We are doing this outside of the transaction to avoid timing problems
1647 if (!self::insertActivity($item)) {
1648 self::insertContent($item);
1651 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1652 'inform' => defaults($item, 'inform', '')];
1654 unset($item['postopts']);
1655 unset($item['inform']);
1658 $ret = dba::insert('item', $item);
1660 // When the item was successfully stored we fetch the ID of the item.
1661 if (DBM::is_result($ret)) {
1662 $current_post = dba::lastInsertId();
1664 // This can happen - for example - if there are locking timeouts.
1667 // Store the data into a spool file so that we can try again later.
1669 // At first we restore the Diaspora signature that we removed above.
1670 if (isset($encoded_signature)) {
1671 $item['dsprsig'] = $encoded_signature;
1674 // Now we store the data in the spool directory
1675 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1676 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1678 $spoolpath = get_spoolpath();
1679 if ($spoolpath != "") {
1680 $spool = $spoolpath.'/'.$file;
1682 // Ensure to have the removed data from above again in the item array
1683 $item = array_merge($item, $delivery_data);
1685 file_put_contents($spool, json_encode($item));
1686 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1691 if ($current_post == 0) {
1692 // This is one of these error messages that never should occur.
1693 logger("couldn't find created item - we better quit now.");
1698 // How much entries have we created?
1699 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1700 $entries = dba::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1703 // There are duplicates. We delete our just created entry.
1704 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1706 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1707 dba::delete('item', ['id' => $current_post]);
1710 } elseif ($entries == 0) {
1711 // This really should never happen since we quit earlier if there were problems.
1712 logger("Something is terribly wrong. We haven't found our created entry.");
1717 logger('created item '.$current_post);
1718 self::updateContact($item);
1720 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1721 $parent_id = $current_post;
1725 dba::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1727 $item['id'] = $current_post;
1728 $item['parent'] = $parent_id;
1730 // update the commented timestamp on the parent
1731 // Only update "commented" if it is really a comment
1732 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1733 dba::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1735 dba::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1740 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1741 * We can check for this condition when we decode and encode the stuff again.
1743 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1744 $dsprsig->signature = base64_decode($dsprsig->signature);
1745 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1748 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1749 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1752 if (!empty($diaspora_signed_text)) {
1753 // Formerly we stored the signed text, the signature and the author in different fields.
1754 // We now store the raw data so that we are more flexible.
1755 dba::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1758 $deleted = self::tagDeliver($item['uid'], $current_post);
1761 * current post can be deleted if is for a community page and no mention are
1764 if (!$deleted && !$dontcache) {
1765 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1766 if (DBM::is_result($posted_item)) {
1768 Addon::callHooks('post_local_end', $posted_item);
1770 Addon::callHooks('post_remote_end', $posted_item);
1773 logger('new item not found in DB, id ' . $current_post);
1777 if ($item['parent-uri'] === $item['uri']) {
1778 self::addThread($current_post);
1780 self::updateThread($parent_id);
1783 $delivery_data['iid'] = $current_post;
1785 self::insertDeliveryData($delivery_data);
1790 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1791 * This is not perfect - but a workable solution until we found the reason for the problem.
1793 if (!empty($tags)) {
1794 Term::insertFromTagFieldByItemId($current_post, $tags);
1797 if (!empty($files)) {
1798 Term::insertFromFileFieldByItemId($current_post, $files);
1801 if ($item['parent-uri'] === $item['uri']) {
1802 self::addShadow($current_post);
1804 self::addShadowPost($current_post);
1807 check_user_notification($current_post);
1810 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1811 } elseif (!empty($parent) && $parent['origin']) {
1812 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1815 return $current_post;
1819 * @brief Insert a new item delivery data entry
1821 * @param array $item The item fields that are to be inserted
1823 private static function insertDeliveryData($delivery_data)
1825 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1829 dba::insert('item-delivery-data', $delivery_data);
1833 * @brief Update an existing item delivery data entry
1835 * @param integer $id The item id that is to be updated
1836 * @param array $item The item fields that are to be inserted
1838 private static function updateDeliveryData($id, $delivery_data)
1840 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1844 dba::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1848 * @brief Insert a new item content entry
1850 * @param array $item The item fields that are to be inserted
1852 private static function insertActivity(&$item)
1854 $activity_index = self::activityToIndex($item['verb']);
1856 if ($activity_index < 0) {
1860 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1861 'uri-hash' => $item['uri-hash']];
1863 // We just remove everything that is content
1864 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1865 unset($item[$field]);
1868 // To avoid timing problems, we are using locks.
1869 $locked = Lock::acquire('item_insert_activity');
1871 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1874 // Do we already have this content?
1875 $item_activity = dba::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1876 if (DBM::is_result($item_activity)) {
1877 $item['iaid'] = $item_activity['id'];
1878 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1879 } elseif (dba::insert('item-activity', $fields)) {
1880 $item['iaid'] = dba::lastInsertId();
1881 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1883 // This shouldn't happen.
1884 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1888 Lock::release('item_insert_activity');
1894 * @brief Insert a new item content entry
1896 * @param array $item The item fields that are to be inserted
1898 private static function insertContent(&$item)
1900 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1902 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1903 if (isset($item[$field])) {
1904 $fields[$field] = $item[$field];
1905 unset($item[$field]);
1909 // To avoid timing problems, we are using locks.
1910 $locked = Lock::acquire('item_insert_content');
1912 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1915 // Do we already have this content?
1916 $item_content = dba::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1917 if (DBM::is_result($item_content)) {
1918 $item['icid'] = $item_content['id'];
1919 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1920 } elseif (dba::insert('item-content', $fields)) {
1921 $item['icid'] = dba::lastInsertId();
1922 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1924 // This shouldn't happen.
1925 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1928 Lock::release('item_insert_content');
1933 * @brief Update existing item content entries
1935 * @param array $item The item fields that are to be changed
1936 * @param array $condition The condition for finding the item content entries
1938 private static function updateActivity($item, $condition)
1940 if (empty($item['verb'])) {
1943 $activity_index = self::activityToIndex($item['verb']);
1945 if ($activity_index < 0) {
1949 $fields = ['activity' => $activity_index];
1951 logger('Update activity for ' . json_encode($condition));
1953 dba::update('item-activity', $fields, $condition, true);
1959 * @brief Update existing item content entries
1961 * @param array $item The item fields that are to be changed
1962 * @param array $condition The condition for finding the item content entries
1964 private static function updateContent($item, $condition)
1966 // We have to select only the fields from the "item-content" table
1968 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1969 if (isset($item[$field])) {
1970 $fields[$field] = $item[$field];
1974 if (empty($fields)) {
1975 // when there are no fields at all, just use the condition
1976 // This is to ensure that we always store content.
1977 $fields = $condition;
1980 logger('Update content for ' . json_encode($condition));
1982 dba::update('item-content', $fields, $condition, true);
1986 * @brief Distributes public items to the receivers
1988 * @param integer $itemid Item ID that should be added
1989 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
1991 public static function distribute($itemid, $signed_text = '')
1993 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
1994 $parent = self::selectFirst(['owner-id'], $condition);
1995 if (!DBM::is_result($parent)) {
1999 // Only distribute public items from native networks
2000 $condition = ['id' => $itemid, 'uid' => 0,
2001 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2002 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2003 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2004 if (!DBM::is_result($item)) {
2008 $origin = $item['origin'];
2011 unset($item['parent']);
2012 unset($item['mention']);
2013 unset($item['wall']);
2014 unset($item['origin']);
2015 unset($item['starred']);
2019 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2020 $parent['owner-id'], CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
2021 $contacts = dba::select('contact', ['uid'], $condition);
2022 while ($contact = dba::fetch($contacts)) {
2023 $users[$contact['uid']] = $contact['uid'];
2028 if ($item['uri'] != $item['parent-uri']) {
2029 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2030 while ($parent = dba::fetch($parents)) {
2031 $users[$parent['uid']] = $parent['uid'];
2032 if ($parent['origin'] && !$origin) {
2033 $origin_uid = $parent['uid'];
2038 foreach ($users as $uid) {
2039 if ($origin_uid == $uid) {
2040 $item['diaspora_signed_text'] = $signed_text;
2042 self::storeForUser($itemid, $item, $uid);
2047 * @brief Store public items for the receivers
2049 * @param integer $itemid Item ID that should be added
2050 * @param array $item The item entry that will be stored
2051 * @param integer $uid The user that will receive the item entry
2053 private static function storeForUser($itemid, $item, $uid)
2055 $item['uid'] = $uid;
2056 $item['origin'] = 0;
2058 if ($item['uri'] == $item['parent-uri']) {
2059 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2061 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2064 if (empty($item['contact-id'])) {
2065 $self = dba::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2066 if (!DBM::is_result($self)) {
2069 $item['contact-id'] = $self['id'];
2072 /// @todo Handling of "event-id"
2075 if ($item['uri'] == $item['parent-uri']) {
2076 $contact = dba::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2077 if (DBM::is_result($contact)) {
2078 $notify = self::isRemoteSelf($contact, $item);
2082 $distributed = self::insert($item, false, $notify, true);
2084 if (!$distributed) {
2085 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2087 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2092 * @brief Add a shadow entry for a given item id that is a thread starter
2094 * We store every public item entry additionally with the user id "0".
2095 * This is used for the community page and for the search.
2096 * It is planned that in the future we will store public item entries only once.
2098 * @param integer $itemid Item ID that should be added
2100 public static function addShadow($itemid)
2102 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2103 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2104 $item = self::selectFirst($fields, $condition);
2106 if (!DBM::is_result($item)) {
2110 // is it already a copy?
2111 if (($itemid == 0) || ($item['uid'] == 0)) {
2115 // Is it a visible public post?
2116 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2120 // is it an entry from a connector? Only add an entry for natively connected networks
2121 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2125 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2129 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2131 if (DBM::is_result($item)) {
2132 // Preparing public shadow (removing user specific data)
2135 unset($item['parent']);
2136 unset($item['wall']);
2137 unset($item['mention']);
2138 unset($item['origin']);
2139 unset($item['starred']);
2140 unset($item['postopts']);
2141 unset($item['inform']);
2142 if ($item['uri'] == $item['parent-uri']) {
2143 $item['contact-id'] = $item['owner-id'];
2145 $item['contact-id'] = $item['author-id'];
2148 $public_shadow = self::insert($item, false, false, true);
2150 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2155 * @brief Add a shadow entry for a given item id that is a comment
2157 * This function does the same like the function above - but for comments
2159 * @param integer $itemid Item ID that should be added
2161 public static function addShadowPost($itemid)
2163 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2164 if (!DBM::is_result($item)) {
2168 // Is it a toplevel post?
2169 if ($item['id'] == $item['parent']) {
2170 self::addShadow($itemid);
2174 // Is this a shadow entry?
2175 if ($item['uid'] == 0) {
2179 // Is there a shadow parent?
2180 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2184 // Is there already a shadow entry?
2185 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2189 // Save "origin" and "parent" state
2190 $origin = $item['origin'];
2191 $parent = $item['parent'];
2193 // Preparing public shadow (removing user specific data)
2196 unset($item['parent']);
2197 unset($item['wall']);
2198 unset($item['mention']);
2199 unset($item['origin']);
2200 unset($item['starred']);
2201 unset($item['postopts']);
2202 unset($item['inform']);
2203 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2205 $public_shadow = self::insert($item, false, false, true);
2207 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2209 // If this was a comment to a Diaspora post we don't get our comment back.
2210 // This means that we have to distribute the comment by ourselves.
2211 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2212 self::distribute($public_shadow);
2217 * Adds a language specification in a "language" element of given $arr.
2218 * Expects "body" element to exist in $arr.
2220 private static function addLanguageToItemArray(&$item)
2222 $naked_body = Text\BBCode::toPlaintext($item['body'], false);
2224 $ld = new Text_LanguageDetect();
2225 $ld->setNameMode(2);
2226 $languages = $ld->detect($naked_body, 3);
2228 if (is_array($languages)) {
2229 $item['language'] = json_encode($languages);
2234 * @brief Creates an unique guid out of a given uri
2236 * @param string $uri uri of an item entry
2237 * @param string $host hostname for the GUID prefix
2238 * @return string unique guid
2240 public static function guidFromUri($uri, $host)
2242 // Our regular guid routine is using this kind of prefix as well
2243 // We have to avoid that different routines could accidentally create the same value
2244 $parsed = parse_url($uri);
2246 // We use a hash of the hostname as prefix for the guid
2247 $guid_prefix = hash("crc32", $host);
2249 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2250 unset($parsed["scheme"]);
2252 // Glue it together to be able to make a hash from it
2253 $host_id = implode("/", $parsed);
2255 // We could use any hash algorithm since it isn't a security issue
2256 $host_hash = hash("ripemd128", $host_id);
2258 return $guid_prefix.$host_hash;
2262 * generate an unique URI
2264 * @param integer $uid User id
2265 * @param string $guid An existing GUID (Otherwise it will be generated)
2269 public static function newURI($uid, $guid = "")
2272 $guid = System::createGUID(32);
2275 $hostname = self::getApp()->get_hostname();
2277 $user = dba::selectFirst('user', ['nickname'], ['uid' => $uid]);
2279 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2285 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2287 * This can be used to filter for inactive contacts.
2288 * Only do this for public postings to avoid privacy problems, since poco data is public.
2289 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2291 * @param array $arr Contains the just posted item record
2293 private static function updateContact($arr)
2295 // Unarchive the author
2296 $contact = dba::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2297 if (DBM::is_result($contact)) {
2298 Contact::unmarkForArchival($contact);
2301 // Unarchive the contact if it's not our own contact
2302 $contact = dba::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2303 if (DBM::is_result($contact)) {
2304 Contact::unmarkForArchival($contact);
2307 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2309 // Is it a forum? Then we don't care about the rules from above
2310 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2311 if (dba::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2317 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2318 ['id' => $arr['contact-id']]);
2320 // Now do the same for the system wide contacts with uid=0
2321 if (!$arr['private']) {
2322 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2323 ['id' => $arr['owner-id']]);
2325 if ($arr['owner-id'] != $arr['author-id']) {
2326 dba::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2327 ['id' => $arr['author-id']]);
2332 public static function setHashtags(&$item)
2335 $tags = get_tags($item["body"]);
2338 if (!count($tags)) {
2342 // This sorting is important when there are hashtags that are part of other hashtags
2343 // Otherwise there could be problems with hashtags like #test and #test2
2346 $URLSearchString = "^\[\]";
2348 // All hashtags should point to the home server if "local_tags" is activated
2349 if (Config::get('system', 'local_tags')) {
2350 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2351 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2353 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2354 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2357 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2358 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2360 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2363 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2365 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2368 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2370 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2373 // Repair recursive urls
2374 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2375 "#$2", $item["body"]);
2377 foreach ($tags as $tag) {
2378 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2382 $basetag = str_replace('_',' ',substr($tag,1));
2384 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2386 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2388 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2389 if (strlen($item["tag"])) {
2390 $item["tag"] = ','.$item["tag"];
2392 $item["tag"] = $newtag.$item["tag"];
2396 // Convert back the masked hashtags
2397 $item["body"] = str_replace("#", "#", $item["body"]);
2400 public static function getGuidById($id)
2402 $item = self::selectFirst(['guid'], ['id' => $id]);
2403 if (DBM::is_result($item)) {
2404 return $item['guid'];
2410 public static function getIdAndNickByGuid($guid, $uid = 0)
2416 $uid == local_user();
2419 // Does the given user have this item?
2421 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2422 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2423 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2424 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2425 if (DBM::is_result($item)) {
2427 $nick = $item["nickname"];
2431 // Or is it anywhere on the server?
2433 $item = dba::fetch_first("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2434 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2435 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2436 AND NOT `item`.`private` AND `item`.`wall`
2437 AND `item`.`guid` = ?", $guid);
2438 if (DBM::is_result($item)) {
2440 $nick = $item["nickname"];
2443 return ["nick" => $nick, "id" => $id];
2447 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2449 * @param int $item_id
2450 * @return bool true if item was deleted, else false
2452 private static function tagDeliver($uid, $item_id)
2456 $user = dba::selectFirst('user', [], ['uid' => $uid]);
2457 if (!DBM::is_result($user)) {
2461 $community_page = (($user['page-flags'] == PAGE_COMMUNITY) ? true : false);
2462 $prvgroup = (($user['page-flags'] == PAGE_PRVGROUP) ? true : false);
2464 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2465 if (!DBM::is_result($item)) {
2469 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2472 * Diaspora uses their own hardwired link URL in @-tags
2473 * instead of the one we supply with webfinger
2475 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2477 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2479 foreach ($matches as $mtch) {
2480 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2482 logger('mention found: ' . $mtch[2]);
2488 if (($community_page || $prvgroup) &&
2489 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2490 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2492 logger("no-mention top-level post to community or private group. delete.");
2493 dba::delete('item', ['id' => $item_id]);
2499 $arr = ['item' => $item, 'user' => $user];
2501 Addon::callHooks('tagged', $arr);
2503 if (!$community_page && !$prvgroup) {
2508 * tgroup delivery - setup a second delivery chain
2509 * prevent delivery looping - only proceed
2510 * if the message originated elsewhere and is a top-level post
2512 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2516 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2517 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2518 if (!DBM::is_result($self)) {
2522 $owner_id = Contact::getIdForURL($self['url']);
2524 // also reset all the privacy bits to the forum default permissions
2526 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2528 $forum_mode = ($prvgroup ? 2 : 1);
2530 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2531 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2532 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2533 dba::update('item', $fields, ['id' => $item_id]);
2535 self::updateThread($item_id);
2537 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2540 public static function isRemoteSelf($contact, &$datarray)
2544 if (!$contact['remote_self']) {
2548 // Prevent the forwarding of posts that are forwarded
2549 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2550 logger('Already forwarded', LOGGER_DEBUG);
2554 // Prevent to forward already forwarded posts
2555 if ($datarray["app"] == $a->get_hostname()) {
2556 logger('Already forwarded (second test)', LOGGER_DEBUG);
2560 // Only forward posts
2561 if ($datarray["verb"] != ACTIVITY_POST) {
2562 logger('No post', LOGGER_DEBUG);
2566 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2567 logger('Not public', LOGGER_DEBUG);
2571 $datarray2 = $datarray;
2572 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2573 if ($contact['remote_self'] == 2) {
2574 $self = dba::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2575 ['uid' => $contact['uid'], 'self' => true]);
2576 if (DBM::is_result($self)) {
2577 $datarray['contact-id'] = $self["id"];
2579 $datarray['owner-name'] = $self["name"];
2580 $datarray['owner-link'] = $self["url"];
2581 $datarray['owner-avatar'] = $self["thumb"];
2583 $datarray['author-name'] = $datarray['owner-name'];
2584 $datarray['author-link'] = $datarray['owner-link'];
2585 $datarray['author-avatar'] = $datarray['owner-avatar'];
2587 unset($datarray['created']);
2588 unset($datarray['edited']);
2590 unset($datarray['network']);
2591 unset($datarray['owner-id']);
2592 unset($datarray['author-id']);
2595 if ($contact['network'] != NETWORK_FEED) {
2596 $datarray["guid"] = System::createGUID(32);
2597 unset($datarray["plink"]);
2598 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2599 $datarray["parent-uri"] = $datarray["uri"];
2600 $datarray["thr-parent"] = $datarray["uri"];
2601 $datarray["extid"] = NETWORK_DFRN;
2602 $urlpart = parse_url($datarray2['author-link']);
2603 $datarray["app"] = $urlpart["host"];
2605 $datarray['private'] = 0;
2609 if ($contact['network'] != NETWORK_FEED) {
2610 // Store the original post
2611 $result = self::insert($datarray2, false, false);
2612 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2614 $datarray["app"] = "Feed";
2618 // Trigger automatic reactions for addons
2619 $datarray['api_source'] = true;
2621 // We have to tell the hooks who we are - this really should be improved
2622 $_SESSION["authenticated"] = true;
2623 $_SESSION["uid"] = $contact['uid'];
2632 * @param array $item
2636 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2638 if (Config::get('system', 'disable_embedded')) {
2642 logger('check for photos', LOGGER_DEBUG);
2643 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2648 $img_start = strpos($orig_body, '[img');
2649 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2650 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2652 while (($img_st_close !== false) && ($img_len !== false)) {
2653 $img_st_close++; // make it point to AFTER the closing bracket
2654 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2656 logger('found photo ' . $image, LOGGER_DEBUG);
2658 if (stristr($image, $site . '/photo/')) {
2659 // Only embed locally hosted photos
2661 $i = basename($image);
2662 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2663 $x = strpos($i, '-');
2666 $res = substr($i, $x + 1);
2667 $i = substr($i, 0, $x);
2668 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2669 $photo = dba::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2670 if (DBM::is_result($photo)) {
2672 * Check to see if we should replace this photo link with an embedded image
2673 * 1. No need to do so if the photo is public
2674 * 2. If there's a contact-id provided, see if they're in the access list
2675 * for the photo. If so, embed it.
2676 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2677 * permissions, regardless of order but first check to see if they're an exact
2678 * match to save some processing overhead.
2680 if (self::hasPermissions($photo)) {
2682 $recips = self::enumeratePermissions($photo);
2683 if (in_array($cid, $recips)) {
2687 if (self::samePermissions($item, $photo)) {
2693 $data = $photo['data'];
2694 $type = $photo['type'];
2696 // If a custom width and height were specified, apply before embedding
2697 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2698 logger('scaling photo', LOGGER_DEBUG);
2700 $width = intval($match[1]);
2701 $height = intval($match[2]);
2703 $Image = new Image($data, $type);
2704 if ($Image->isValid()) {
2705 $Image->scaleDown(max($width, $height));
2706 $data = $Image->asString();
2707 $type = $Image->getType();
2711 logger('replacing photo', LOGGER_DEBUG);
2712 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2713 logger('replaced: ' . $image, LOGGER_DATA);
2719 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2720 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2721 if ($orig_body === false) {
2725 $img_start = strpos($orig_body, '[img');
2726 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2727 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2730 $new_body = $new_body . $orig_body;
2735 private static function hasPermissions($obj)
2737 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2738 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2741 private static function samePermissions($obj1, $obj2)
2743 // first part is easy. Check that these are exactly the same.
2744 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2745 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2746 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2747 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2751 // This is harder. Parse all the permissions and compare the resulting set.
2752 $recipients1 = self::enumeratePermissions($obj1);
2753 $recipients2 = self::enumeratePermissions($obj2);
2757 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2758 return ($recipients1 == $recipients2);
2761 // returns an array of contact-ids that are allowed to see this object
2762 private static function enumeratePermissions($obj)
2764 $allow_people = expand_acl($obj['allow_cid']);
2765 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2766 $deny_people = expand_acl($obj['deny_cid']);
2767 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2768 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2769 $deny = array_unique(array_merge($deny_people, $deny_groups));
2770 $recipients = array_diff($recipients, $deny);
2774 public static function getFeedTags($item)
2778 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2780 for ($x = 0; $x < $cnt; $x ++) {
2781 if ($matches[1][$x]) {
2782 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2787 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2789 for ($x = 0; $x < $cnt; $x ++) {
2790 if ($matches[1][$x]) {
2791 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2798 public static function expire($uid, $days, $network = "", $force = false)
2800 if (!$uid || ($days < 1)) {
2804 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2805 $uid, GRAVITY_PARENT];
2808 * $expire_network_only = save your own wall posts
2809 * and just expire conversations started by others
2811 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2813 if ($expire_network_only) {
2814 $condition[0] .= " AND NOT `wall`";
2817 if ($network != "") {
2818 $condition[0] .= " AND `network` = ?";
2819 $condition[] = $network;
2822 * There is an index "uid_network_received" but not "uid_network_created"
2823 * This avoids the creation of another index just for one purpose.
2824 * And it doesn't really matter wether to look at "received" or "created"
2826 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2827 $condition[] = $days;
2829 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2830 $condition[] = $days;
2833 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2835 if (!DBM::is_result($items)) {
2839 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2841 // Forcing expiring of items - but not notes and marked items
2843 $expire_items = true;
2846 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2847 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2848 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2852 while ($item = Item::fetch($items)) {
2853 // don't expire filed items
2855 if (strpos($item['file'], '[') !== false) {
2859 // Only expire posts, not photos and photo comments
2861 if (!$expire_photos && strlen($item['resource-id'])) {
2863 } elseif (!$expire_starred && intval($item['starred'])) {
2865 } elseif (!$expire_notes && $item['type'] == 'note') {
2867 } elseif (!$expire_items && $item['type'] != 'note') {
2871 self::deleteById($item['id'], PRIORITY_LOW);
2876 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2879 public static function firstPostDate($uid, $wall = false)
2881 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2882 $params = ['order' => ['created' => false]];
2883 $thread = dba::selectFirst('thread', ['created'], $condition, $params);
2884 if (DBM::is_result($thread)) {
2885 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2891 * @brief add/remove activity to an item
2893 * Toggle activities as like,dislike,attend of an item
2895 * @param string $item_id
2896 * @param string $verb
2897 * Activity verb. One of
2898 * like, unlike, dislike, undislike, attendyes, unattendyes,
2899 * attendno, unattendno, attendmaybe, unattendmaybe
2900 * @hook 'post_local_end'
2902 * 'post_id' => ID of posted item
2904 public static function performLike($item_id, $verb)
2906 if (!local_user() && !remote_user()) {
2913 $activity = ACTIVITY_LIKE;
2917 $activity = ACTIVITY_DISLIKE;
2921 $activity = ACTIVITY_ATTEND;
2925 $activity = ACTIVITY_ATTENDNO;
2928 case 'unattendmaybe':
2929 $activity = ACTIVITY_ATTENDMAYBE;
2932 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2936 // Enable activity toggling instead of on/off
2937 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2939 logger('like: verb ' . $verb . ' item ' . $item_id);
2941 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2942 if (!DBM::is_result($item)) {
2943 logger('like: unknown item ' . $item_id);
2947 $item_uri = $item['uri'];
2949 $uid = $item['uid'];
2950 if (($uid == 0) && local_user()) {
2951 $uid = local_user();
2954 if (!can_write_wall($uid)) {
2955 logger('like: unable to write on wall ' . $uid);
2959 // Retrieves the local post owner
2960 $owner_self_contact = dba::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2961 if (!DBM::is_result($owner_self_contact)) {
2962 logger('like: unknown owner ' . $uid);
2966 // Retrieve the current logged in user's public contact
2967 $author_id = public_contact();
2969 $author_contact = dba::selectFirst('contact', ['url'], ['id' => $author_id]);
2970 if (!DBM::is_result($author_contact)) {
2971 logger('like: unknown author ' . $author_id);
2975 // Contact-id is the uid-dependant author contact
2976 if (local_user() == $uid) {
2977 $item_contact_id = $owner_self_contact['id'];
2978 $item_contact = $owner_self_contact;
2980 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2981 $item_contact = dba::selectFirst('contact', [], ['id' => $item_contact_id]);
2982 if (!DBM::is_result($item_contact)) {
2983 logger('like: unknown item contact ' . $item_contact_id);
2988 // Look for an existing verb row
2989 // event participation are essentially radio toggles. If you make a subsequent choice,
2990 // we need to eradicate your first choice.
2991 if ($event_verb_flag) {
2992 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
2994 // Translate to the index based activity index
2996 foreach ($verbs as $verb) {
2997 $activities[] = self::activityToIndex($verb);
3000 $activities = self::activityToIndex($activity);
3003 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3004 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3006 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3008 // If it exists, mark it as deleted
3009 if (DBM::is_result($like_item)) {
3010 // Already voted, undo it
3011 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
3012 /// @todo Consider using self::update - but before doing so, check the side effects
3013 dba::update('item', $fields, ['id' => $like_item['id']]);
3015 // Clean up the Diaspora signatures for this like
3016 dba::delete('sign', ['iid' => $like_item['id']]);
3018 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
3020 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3025 // Verb is "un-something", just trying to delete existing entries
3026 if (strpos($verb, 'un') === 0) {
3030 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3033 'guid' => System::createGUID(32),
3034 'uri' => self::newURI($item['uid']),
3035 'uid' => $item['uid'],
3036 'contact-id' => $item_contact_id,
3037 'wall' => $item['wall'],
3039 'network' => NETWORK_DFRN,
3040 'gravity' => GRAVITY_ACTIVITY,
3041 'parent' => $item['id'],
3042 'parent-uri' => $item['uri'],
3043 'thr-parent' => $item['uri'],
3044 'owner-id' => $item['owner-id'],
3045 'author-id' => $author_id,
3046 'body' => $activity,
3047 'verb' => $activity,
3048 'object-type' => $objtype,
3049 'allow_cid' => $item['allow_cid'],
3050 'allow_gid' => $item['allow_gid'],
3051 'deny_cid' => $item['deny_cid'],
3052 'deny_gid' => $item['deny_gid'],
3057 $new_item_id = self::insert($new_item);
3059 // If the parent item isn't visible then set it to visible
3060 if (!$item['visible']) {
3061 self::update(['visible' => true], ['id' => $item['id']]);
3064 // Save the author information for the like in case we need to relay to Diaspora
3065 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3067 $new_item['id'] = $new_item_id;
3069 Addon::callHooks('post_local_end', $new_item);
3071 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3076 private static function addThread($itemid, $onlyshadow = false)
3078 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3079 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3080 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3081 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3082 $item = self::selectFirst($fields, $condition);
3084 if (!DBM::is_result($item)) {
3088 $item['iid'] = $itemid;
3091 $result = dba::insert('thread', $item);
3093 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3097 private static function updateThread($itemid, $setmention = false)
3099 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3100 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3101 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3102 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3104 $item = self::selectFirst($fields, $condition);
3105 if (!DBM::is_result($item)) {
3110 $item["mention"] = 1;
3117 foreach ($item as $field => $data) {
3118 if (!in_array($field, ["guid"])) {
3119 $fields[$field] = $data;
3123 $result = dba::update('thread', $fields, ['iid' => $itemid]);
3125 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3128 private static function deleteThread($itemid, $itemuri = "")
3130 $item = dba::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3131 if (!DBM::is_result($item)) {
3132 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3136 // Using dba::delete at this time could delete the associated item entries
3137 $result = dba::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3139 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3141 if ($itemuri != "") {
3142 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3143 if (!self::exists($condition)) {
3144 dba::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3145 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);