4 * @file src/Model/Item.php
7 namespace Friendica\Model;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Config;
13 use Friendica\Core\Lock;
14 use Friendica\Core\PConfig;
15 use Friendica\Core\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Contact;
19 use Friendica\Model\PermissionSet;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\XML;
25 use Text_LanguageDetect;
27 require_once 'boot.php';
28 require_once 'include/items.php';
29 require_once 'include/text.php';
31 class Item extends BaseObject
33 // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
40 const PT_DOCUMENT = 19;
42 const PT_PERSONAL_NOTE = 128;
44 // Field list that is used to display the items
45 const DISPLAY_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid', 'network',
46 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
47 'wall', 'private', 'starred', 'origin', 'title', 'body', 'file', 'attach', 'language',
48 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
49 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'item_id',
50 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
51 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network',
52 'contact-id', 'contact-link', 'contact-name', 'contact-avatar',
53 'writable', 'self', 'cid', 'alias',
54 'event-id', 'event-created', 'event-edited', 'event-start', 'event-finish',
55 'event-summary', 'event-desc', 'event-location', 'event-type',
56 'event-nofinish', 'event-adjust', 'event-ignore', 'event-id'];
58 // Field list that is used to deliver items via the protocols
59 const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri', 'thr-parent', 'parent-uri', 'guid',
60 'created', 'edited', 'verb', 'object-type', 'object', 'target',
61 'private', 'title', 'body', 'location', 'coord', 'app',
62 'attach', 'tag', 'deleted', 'extid', 'post-type',
63 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
64 'author-id', 'author-link', 'owner-link', 'contact-uid',
65 'signed_text', 'signature', 'signer', 'network'];
67 // Field list for "item-content" table that is mixed with the item table
68 const MIXED_CONTENT_FIELDLIST = ['title', 'content-warning', 'body', 'location',
69 'coord', 'app', 'rendered-hash', 'rendered-html', 'verb',
70 'object-type', 'object', 'target-type', 'target', 'plink'];
72 // Field list for "item-content" table that is not present in the "item" table
73 const CONTENT_FIELDLIST = ['language'];
75 // Field list for additional delivery data
76 const DELIVERY_DATA_FIELDLIST = ['postopts', 'inform'];
78 // All fields in the item table
79 const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
80 'contact-id', 'type', 'wall', 'gravity', 'extid', 'icid', 'iaid', 'psid',
81 'created', 'edited', 'commented', 'received', 'changed', 'verb',
82 'postopts', 'plink', 'resource-id', 'event-id', 'tag', 'attach', 'inform',
83 'file', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type',
84 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
85 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global', 'network',
86 'title', 'content-warning', 'body', 'location', 'coord', 'app',
87 'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
88 'author-id', 'author-link', 'author-name', 'author-avatar',
89 'owner-id', 'owner-link', 'owner-name', 'owner-avatar'];
91 // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
92 // The item-activity table only stores the index and needs this array to know the matching activity.
93 const ACTIVITIES = [ACTIVITY_LIKE, ACTIVITY_DISLIKE, ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
95 private static $legacy_mode = null;
97 public static function isLegacyMode()
99 if (is_null(self::$legacy_mode)) {
100 self::$legacy_mode = (Config::get("system", "post_update_version") < 1279);
103 return self::$legacy_mode;
107 * @brief returns an activity index from an activity string
109 * @param string $activity activity string
110 * @return integer Activity index
112 private static function activityToIndex($activity)
114 $index = array_search($activity, self::ACTIVITIES);
116 if (is_bool($index)) {
124 * @brief returns an activity string from an activity index
126 * @param integer $index activity index
127 * @return string Activity string
129 private static function indexToActivity($index)
131 if (is_null($index) || !array_key_exists($index, self::ACTIVITIES)) {
135 return self::ACTIVITIES[$index];
139 * @brief Fetch a single item row
141 * @param mixed $stmt statement object
142 * @return array current row
144 public static function fetch($stmt)
146 $row = DBA::fetch($stmt);
152 // ---------------------- Transform item structure data ----------------------
154 // We prefer the data from the user's contact over the public one
155 if (!empty($row['author-link']) && !empty($row['contact-link']) &&
156 ($row['author-link'] == $row['contact-link'])) {
157 if (isset($row['author-avatar']) && !empty($row['contact-avatar'])) {
158 $row['author-avatar'] = $row['contact-avatar'];
160 if (isset($row['author-name']) && !empty($row['contact-name'])) {
161 $row['author-name'] = $row['contact-name'];
165 if (!empty($row['owner-link']) && !empty($row['contact-link']) &&
166 ($row['owner-link'] == $row['contact-link'])) {
167 if (isset($row['owner-avatar']) && !empty($row['contact-avatar'])) {
168 $row['owner-avatar'] = $row['contact-avatar'];
170 if (isset($row['owner-name']) && !empty($row['contact-name'])) {
171 $row['owner-name'] = $row['contact-name'];
175 // We can always comment on posts from these networks
176 if (array_key_exists('writable', $row) &&
177 in_array($row['internal-network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])) {
178 $row['writable'] = true;
181 // ---------------------- Transform item content data ----------------------
183 // Fetch data from the item-content table whenever there is content there
184 if (self::isLegacyMode()) {
185 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
186 foreach ($legacy_fields as $field) {
187 if (empty($row[$field]) && !empty($row['internal-item-' . $field])) {
188 $row[$field] = $row['internal-item-' . $field];
190 unset($row['internal-item-' . $field]);
194 if (!empty($row['internal-iaid']) && array_key_exists('verb', $row)) {
195 $row['verb'] = self::indexToActivity($row['internal-activity']);
196 if (array_key_exists('title', $row)) {
199 if (array_key_exists('body', $row)) {
200 $row['body'] = $row['verb'];
202 if (array_key_exists('object', $row)) {
205 if (array_key_exists('object-type', $row)) {
206 $row['object-type'] = ACTIVITY_OBJ_NOTE;
208 } elseif (array_key_exists('verb', $row) && in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
209 // Posts don't have an object or target - but having tags or files.
210 // We safe some performance by building tag and file strings only here.
211 // We remove object and target since they aren't used for this type.
212 if (array_key_exists('object', $row)) {
215 if (array_key_exists('target', $row)) {
220 if (!array_key_exists('verb', $row) || in_array($row['verb'], ['', ACTIVITY_POST, ACTIVITY_SHARE])) {
221 // Build the tag string out of the term entries
222 if (array_key_exists('tag', $row) && empty($row['tag'])) {
223 $row['tag'] = Term::tagTextFromItemId($row['internal-iid']);
226 // Build the file string out of the term entries
227 if (array_key_exists('file', $row) && empty($row['file'])) {
228 $row['file'] = Term::fileTextFromItemId($row['internal-iid']);
232 // Remove internal fields
233 unset($row['internal-activity']);
234 unset($row['internal-network']);
235 unset($row['internal-iid']);
236 unset($row['internal-iaid']);
237 unset($row['internal-icid']);
243 * @brief Fills an array with data from an item query
245 * @param object $stmt statement object
246 * @return array Data array
248 public static function inArray($stmt, $do_close = true) {
249 if (is_bool($stmt)) {
254 while ($row = self::fetch($stmt)) {
264 * @brief Check if item data exists
266 * @param array $condition array of fields for condition
268 * @return boolean Are there rows for that condition?
270 public static function exists($condition) {
271 $stmt = self::select(['id'], $condition, ['limit' => 1]);
273 if (is_bool($stmt)) {
276 $retval = (DBA::numRows($stmt) > 0);
285 * Retrieve a single record from the item table for a given user and returns it in an associative array
287 * @brief Retrieve a single record from a table
288 * @param integer $uid User ID
289 * @param array $fields
290 * @param array $condition
291 * @param array $params
295 public static function selectFirstForUser($uid, array $selected = [], array $condition = [], $params = [])
297 $params['uid'] = $uid;
299 if (empty($selected)) {
300 $selected = Item::DISPLAY_FIELDLIST;
303 return self::selectFirst($selected, $condition, $params);
307 * @brief Select rows from the item table for a given user
309 * @param integer $uid User ID
310 * @param array $selected Array of selected fields, empty for all
311 * @param array $condition Array of fields for condition
312 * @param array $params Array of several parameters
314 * @return boolean|object
316 public static function selectForUser($uid, array $selected = [], array $condition = [], $params = [])
318 $params['uid'] = $uid;
320 if (empty($selected)) {
321 $selected = Item::DISPLAY_FIELDLIST;
324 return self::select($selected, $condition, $params);
328 * Retrieve a single record from the item table and returns it in an associative array
330 * @brief Retrieve a single record from a table
331 * @param array $fields
332 * @param array $condition
333 * @param array $params
337 public static function selectFirst(array $fields = [], array $condition = [], $params = [])
339 $params['limit'] = 1;
341 $result = self::select($fields, $condition, $params);
343 if (is_bool($result)) {
346 $row = self::fetch($result);
353 * @brief Select rows from the item table
355 * @param array $selected Array of selected fields, empty for all
356 * @param array $condition Array of fields for condition
357 * @param array $params Array of several parameters
359 * @return boolean|object
361 public static function select(array $selected = [], array $condition = [], $params = [])
366 if (isset($params['uid'])) {
367 $uid = $params['uid'];
371 $fields = self::fieldlist($selected);
373 $select_fields = self::constructSelectFields($fields, $selected);
375 $condition_string = DBA::buildCondition($condition);
377 $condition_string = self::addTablesToFields($condition_string, $fields);
380 $condition_string = $condition_string . ' AND ' . self::condition(false);
383 $param_string = self::addTablesToFields(DBA::buildParameter($params), $fields);
385 $table = "`item` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, false, $usermode);
387 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
389 return DBA::p($sql, $condition);
393 * @brief Select rows from the starting post in the item table
395 * @param integer $uid User ID
396 * @param array $fields Array of selected fields, empty for all
397 * @param array $condition Array of fields for condition
398 * @param array $params Array of several parameters
400 * @return boolean|object
402 public static function selectThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
404 $params['uid'] = $uid;
406 if (empty($selected)) {
407 $selected = Item::DISPLAY_FIELDLIST;
410 return self::selectThread($selected, $condition, $params);
414 * Retrieve a single record from the starting post in the item table and returns it in an associative array
416 * @brief Retrieve a single record from a table
417 * @param integer $uid User ID
418 * @param array $selected
419 * @param array $condition
420 * @param array $params
424 public static function selectFirstThreadForUser($uid, array $selected = [], array $condition = [], $params = [])
426 $params['uid'] = $uid;
428 if (empty($selected)) {
429 $selected = Item::DISPLAY_FIELDLIST;
432 return self::selectFirstThread($selected, $condition, $params);
436 * Retrieve a single record from the starting post in the item table and returns it in an associative array
438 * @brief Retrieve a single record from a table
439 * @param array $fields
440 * @param array $condition
441 * @param array $params
445 public static function selectFirstThread(array $fields = [], array $condition = [], $params = [])
447 $params['limit'] = 1;
448 $result = self::selectThread($fields, $condition, $params);
450 if (is_bool($result)) {
453 $row = self::fetch($result);
460 * @brief Select rows from the starting post in the item table
462 * @param array $selected Array of selected fields, empty for all
463 * @param array $condition Array of fields for condition
464 * @param array $params Array of several parameters
466 * @return boolean|object
468 public static function selectThread(array $selected = [], array $condition = [], $params = [])
473 if (isset($params['uid'])) {
474 $uid = $params['uid'];
478 $fields = self::fieldlist($selected);
480 $threadfields = ['thread' => ['iid', 'uid', 'contact-id', 'owner-id', 'author-id',
481 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private',
482 'pubmail', 'moderated', 'visible', 'starred', 'ignored', 'post-type',
483 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'network']];
485 $select_fields = self::constructSelectFields($fields, $selected);
487 $condition_string = DBA::buildCondition($condition);
489 $condition_string = self::addTablesToFields($condition_string, $threadfields);
490 $condition_string = self::addTablesToFields($condition_string, $fields);
493 $condition_string = $condition_string . ' AND ' . self::condition(true);
496 $param_string = DBA::buildParameter($params);
497 $param_string = self::addTablesToFields($param_string, $threadfields);
498 $param_string = self::addTablesToFields($param_string, $fields);
500 $table = "`thread` " . self::constructJoins($uid, $select_fields . $condition_string . $param_string, true, $usermode);
502 $sql = "SELECT " . $select_fields . " FROM " . $table . $condition_string . $param_string;
504 return DBA::p($sql, $condition);
508 * @brief Returns a list of fields that are associated with the item table
510 * @return array field list
512 private static function fieldlist($selected)
516 $fields['item'] = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent', 'guid',
517 'contact-id', 'owner-id', 'author-id', 'type', 'wall', 'gravity', 'extid',
518 'created', 'edited', 'commented', 'received', 'changed', 'psid',
519 'resource-id', 'event-id', 'tag', 'attach', 'post-type', 'file',
520 'private', 'pubmail', 'moderated', 'visible', 'starred', 'bookmark',
521 'unseen', 'deleted', 'origin', 'forum_mode', 'mention', 'global',
522 'id' => 'item_id', 'network', 'icid', 'iaid', 'id' => 'internal-iid',
523 'network' => 'internal-network', 'icid' => 'internal-icid',
524 'iaid' => 'internal-iaid'];
526 $fields['item-activity'] = ['activity', 'activity' => 'internal-activity'];
528 $fields['item-content'] = array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
530 $fields['item-delivery-data'] = self::DELIVERY_DATA_FIELDLIST;
532 $fields['permissionset'] = ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
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::SHARING, Contact::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, "`permissionset`.") !== false) {
648 $joins .= " LEFT JOIN `permissionset` ON `permissionset`.`id` = `item`.`psid`";
651 if ((strpos($sql_commands, "`parent-item`.") !== false) || (strpos($sql_commands, "`parent-author`.") !== false)) {
652 $joins .= " STRAIGHT_JOIN `item` AS `parent-item` ON `parent-item`.`id` = `item`.`parent`";
655 if (strpos($sql_commands, "`parent-item-author`.") !== false) {
656 $joins .= " STRAIGHT_JOIN `contact` AS `parent-item-author` ON `parent-item-author`.`id` = `parent-item`.`author-id`";
663 * @brief Add the field list for the "select" functions
665 * @param array $fields The field definition array
666 * @param array $selected The array with the selected fields from the "select" functions
668 * @return string The field list
670 private static function constructSelectFields($fields, $selected)
672 if (!empty($selected)) {
673 $selected[] = 'internal-iid';
674 $selected[] = 'internal-iaid';
675 $selected[] = 'internal-icid';
676 $selected[] = 'internal-network';
679 if (in_array('verb', $selected)) {
680 $selected[] = 'internal-activity';
684 foreach ($fields as $table => $table_fields) {
685 foreach ($table_fields as $field => $select) {
686 if (empty($selected) || in_array($select, $selected)) {
687 $legacy_fields = array_merge(self::DELIVERY_DATA_FIELDLIST, self::MIXED_CONTENT_FIELDLIST);
688 if (self::isLegacyMode() && in_array($select, $legacy_fields)) {
689 $selection[] = "`item`.`".$select."` AS `internal-item-" . $select . "`";
691 if (is_int($field)) {
692 $selection[] = "`" . $table . "`.`" . $select . "`";
694 $selection[] = "`" . $table . "`.`" . $field . "` AS `" . $select . "`";
699 return implode(", ", $selection);
703 * @brief add table definition to fields in an SQL query
705 * @param string $query SQL query
706 * @param array $fields The field definition array
708 * @return string the changed SQL query
710 private static function addTablesToFields($query, $fields)
712 foreach ($fields as $table => $table_fields) {
713 foreach ($table_fields as $alias => $field) {
714 if (is_int($alias)) {
715 $replace_field = $field;
717 $replace_field = $alias;
720 $search = "/([^\.])`" . $field . "`/i";
721 $replace = "$1`" . $table . "`.`" . $replace_field . "`";
722 $query = preg_replace($search, $replace, $query);
729 * @brief Generate a server unique item hash for linking between the item tables
731 * @param string $uri Item URI
732 * @param date $created Item creation date
734 * @return string the item hash
736 private static function itemHash($uri, $created)
738 return round(strtotime($created) / 100) . hash('ripemd128', $uri);
742 * @brief Update existing item entries
744 * @param array $fields The fields that are to be changed
745 * @param array $condition The condition for finding the item entries
747 * In the future we may have to change permissions as well.
748 * Then we had to add the user id as third parameter.
750 * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
752 * @return integer|boolean number of affected rows - or "false" if there was an error
754 public static function update(array $fields, array $condition)
756 if (empty($condition) || empty($fields)) {
760 // To ensure the data integrity we do it in an transaction
763 // We cannot simply expand the condition to check for origin entries
764 // The condition needn't to be a simple array but could be a complex condition.
765 // And we have to execute this query before the update to ensure to fetch the same data.
766 $items = DBA::select('item', ['id', 'origin', 'uri', 'created', 'uri-hash', 'iaid', 'icid', 'tag', 'file'], $condition);
768 $content_fields = [];
769 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
770 if (isset($fields[$field])) {
771 $content_fields[$field] = $fields[$field];
772 if (in_array($field, self::CONTENT_FIELDLIST) || !self::isLegacyMode()) {
773 unset($fields[$field]);
775 $fields[$field] = null;
780 $clear_fields = ['bookmark', 'type', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link'];
781 foreach ($clear_fields as $field) {
782 if (array_key_exists($field, $fields)) {
783 $fields[$field] = null;
787 if (array_key_exists('tag', $fields)) {
788 $tags = $fields['tag'];
789 $fields['tag'] = null;
794 if (array_key_exists('file', $fields)) {
795 $files = $fields['file'];
796 $fields['file'] = null;
801 $delivery_data = ['postopts' => defaults($fields, 'postopts', ''),
802 'inform' => defaults($fields, 'inform', '')];
804 $fields['postopts'] = null;
805 $fields['inform'] = null;
807 if (!empty($fields)) {
808 $success = DBA::update('item', $fields, $condition);
817 // When there is no content for the "old" item table, this will count the fetched items
818 $rows = DBA::affectedRows();
820 while ($item = DBA::fetch($items)) {
822 // This part here can safely be removed when the legacy fields in the item had been removed
823 if (empty($item['uri-hash']) && !empty($item['uri']) && !empty($item['created'])) {
825 // Fetch the uri-hash from an existing item entry if there is one
826 $item_condition = ["`uri` = ? AND `uri-hash` != ''", $item['uri']];
827 $existing = DBA::selectfirst('item', ['uri-hash'], $item_condition);
828 if (DBA::isResult($existing)) {
829 $item['uri-hash'] = $existing['uri-hash'];
831 $item['uri-hash'] = self::itemHash($item['uri'], $item['created']);
834 DBA::update('item', ['uri-hash' => $item['uri-hash']], ['id' => $item['id']]);
835 DBA::update('item-activity', ['uri-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-hash` = ''", $item['uri']]);
836 DBA::update('item-content', ['uri-plink-hash' => $item['uri-hash']], ["`uri` = ? AND `uri-plink-hash` = ''", $item['uri']]);
839 if (!empty($item['iaid']) || (!empty($content_fields['verb']) && (self::activityToIndex($content_fields['verb']) >= 0))) {
840 if (!empty($item['iaid'])) {
841 $update_condition = ['id' => $item['iaid']];
843 $update_condition = ['uri-hash' => $item['uri-hash']];
845 self::updateActivity($content_fields, $update_condition);
847 if (empty($item['iaid'])) {
848 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
849 if (DBA::isResult($item_activity)) {
850 $item_fields = ['iaid' => $item_activity['id'], 'icid' => null];
851 foreach (self::MIXED_CONTENT_FIELDLIST as $field) {
852 if (self::isLegacyMode()) {
853 $item_fields[$field] = null;
855 unset($item_fields[$field]);
858 DBA::update('item', $item_fields, ['id' => $item['id']]);
860 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid']])) {
861 DBA::delete('item-content', ['id' => $item['icid']]);
864 } elseif (!empty($item['icid'])) {
865 DBA::update('item', ['icid' => null], ['id' => $item['id']]);
867 if (!DBA::exists('item', ['icid' => $item['icid']])) {
868 DBA::delete('item-content', ['id' => $item['icid']]);
872 if (!empty($item['icid'])) {
873 $update_condition = ['id' => $item['icid']];
875 $update_condition = ['uri-plink-hash' => $item['uri-hash']];
877 self::updateContent($content_fields, $update_condition);
879 if (empty($item['icid'])) {
880 $item_content = DBA::selectFirst('item-content', [], ['uri-plink-hash' => $item['uri-hash']]);
881 if (DBA::isResult($item_content)) {
882 $item_fields = ['icid' => $item_content['id']];
883 // Clear all fields in the item table that have a content in the item-content table
884 foreach ($item_content as $field => $content) {
885 if (in_array($field, self::MIXED_CONTENT_FIELDLIST) && !empty($item_content[$field])) {
886 if (self::isLegacyMode()) {
887 $item_fields[$field] = null;
889 unset($item_fields[$field]);
893 DBA::update('item', $item_fields, ['id' => $item['id']]);
899 Term::insertFromTagFieldByItemId($item['id'], $tags);
900 if (!empty($item['tag'])) {
901 DBA::update('item', ['tag' => ''], ['id' => $item['id']]);
905 if (!empty($files)) {
906 Term::insertFromFileFieldByItemId($item['id'], $files);
907 if (!empty($item['file'])) {
908 DBA::update('item', ['file' => ''], ['id' => $item['id']]);
912 self::updateDeliveryData($item['id'], $delivery_data);
914 self::updateThread($item['id']);
916 // We only need to notfiy others when it is an original entry from us.
917 // Only call the notifier when the item has some content relevant change.
918 if ($item['origin'] && in_array('edited', array_keys($fields))) {
919 Worker::add(PRIORITY_HIGH, "Notifier", 'edit_post', $item['id']);
929 * @brief Delete an item and notify others about it - if it was ours
931 * @param array $condition The condition for finding the item entries
932 * @param integer $priority Priority for the notification
934 public static function delete($condition, $priority = PRIORITY_HIGH)
936 $items = DBA::select('item', ['id'], $condition);
937 while ($item = DBA::fetch($items)) {
938 self::deleteById($item['id'], $priority);
944 * @brief Delete an item for an user and notify others about it - if it was ours
946 * @param array $condition The condition for finding the item entries
947 * @param integer $uid User who wants to delete this item
949 public static function deleteForUser($condition, $uid)
955 $items = DBA::select('item', ['id', 'uid'], $condition);
956 while ($item = DBA::fetch($items)) {
957 // "Deleting" global items just means hiding them
958 if ($item['uid'] == 0) {
959 DBA::update('user-item', ['hidden' => true], ['iid' => $item['id'], 'uid' => $uid], true);
960 } elseif ($item['uid'] == $uid) {
961 self::deleteById($item['id'], PRIORITY_HIGH);
963 logger('Wrong ownership. Not deleting item ' . $item['id']);
970 * @brief Delete an item and notify others about it - if it was ours
972 * @param integer $item_id Item ID that should be delete
973 * @param integer $priority Priority for the notification
975 * @return boolean success
977 private static function deleteById($item_id, $priority = PRIORITY_HIGH)
979 // locate item to be deleted
980 $fields = ['id', 'uri', 'uid', 'parent', 'parent-uri', 'origin',
981 'deleted', 'file', 'resource-id', 'event-id', 'attach',
982 'verb', 'object-type', 'object', 'target', 'contact-id'];
983 $item = self::selectFirst($fields, ['id' => $item_id]);
984 if (!DBA::isResult($item)) {
985 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
989 if ($item['deleted']) {
990 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
994 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
995 if (!DBA::isResult($parent)) {
996 $parent = ['origin' => false];
999 // clean up categories and tags so they don't end up as orphans
1002 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1004 foreach ($matches as $mtch) {
1005 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1011 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1013 foreach ($matches as $mtch) {
1014 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1019 * If item is a link to a photo resource, nuke all the associated photos
1020 * (visitors will not have photo resources)
1021 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1022 * generate a resource-id and therefore aren't intimately linked to the item.
1024 if (strlen($item['resource-id'])) {
1025 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1028 // If item is a link to an event, delete the event.
1029 if (intval($item['event-id'])) {
1030 Event::delete($item['event-id']);
1033 // If item has attachments, drop them
1034 foreach (explode(", ", $item['attach']) as $attach) {
1035 preg_match("|attach/(\d+)|", $attach, $matches);
1036 if (is_array($matches) && count($matches) > 1) {
1037 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1041 // Delete tags that had been attached to other items
1042 self::deleteTagsFromItem($item);
1044 // Set the item to "deleted"
1045 // This erasing of item content is superfluous for items with a matching item-content.
1046 // But for the next time we will still have old content in the item table.
1047 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow(),
1048 'body' => '', 'title' => '', 'content-warning' => '', 'rendered-hash' => '', 'rendered-html' => '',
1049 'object' => '', 'target' => '', 'tag' => '', 'postopts' => '', 'attach' => '', 'file' => ''];
1050 DBA::update('item', $item_fields, ['id' => $item['id']]);
1052 Term::insertFromTagFieldByItemId($item['id'], '');
1053 Term::insertFromFileFieldByItemId($item['id'], '');
1054 self::deleteThread($item['id'], $item['parent-uri']);
1056 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1057 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1060 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1062 // If it's the parent of a comment thread, kill all the kids
1063 if ($item['id'] == $item['parent']) {
1064 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1067 // Is it our comment and/or our thread?
1068 if ($item['origin'] || $parent['origin']) {
1070 // When we delete the original post we will delete all existing copies on the server as well
1071 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1073 // send the notification upstream/downstream
1074 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1075 } elseif ($item['uid'] != 0) {
1077 // When we delete just our local user copy of an item, we have to set a marker to hide it
1078 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1079 if (DBA::isResult($global_item)) {
1080 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1084 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1089 private static function deleteTagsFromItem($item)
1091 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1095 $xo = XML::parseString($item["object"], false);
1096 $xt = XML::parseString($item["target"], false);
1098 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1102 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1103 if (!DBA::isResult($i)) {
1107 // For tags, the owner cannot remove the tag on the author's copy of the post.
1108 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1109 $author_copy = $item["origin"];
1111 if (($owner_remove && $author_copy) || !$owner_remove) {
1115 $tags = explode(',', $i["tag"]);
1118 foreach ($tags as $tag) {
1119 if (trim($tag) !== trim($xo->body)) {
1120 $newtags[] = trim($tag);
1124 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1127 private static function guid($item, $notify)
1129 if (!empty($item['guid'])) {
1130 return notags(trim($item['guid']));
1134 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1135 // We add the hash of our own host because our host is the original creator of the post.
1136 $prefix_host = get_app()->get_hostname();
1140 // We are only storing the post so we create a GUID from the original hostname.
1141 if (!empty($item['author-link'])) {
1142 $parsed = parse_url($item['author-link']);
1143 if (!empty($parsed['host'])) {
1144 $prefix_host = $parsed['host'];
1148 if (empty($prefix_host) && !empty($item['plink'])) {
1149 $parsed = parse_url($item['plink']);
1150 if (!empty($parsed['host'])) {
1151 $prefix_host = $parsed['host'];
1155 if (empty($prefix_host) && !empty($item['uri'])) {
1156 $parsed = parse_url($item['uri']);
1157 if (!empty($parsed['host'])) {
1158 $prefix_host = $parsed['host'];
1162 // Is it in the format data@host.tld? - Used for mail contacts
1163 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1164 $mailparts = explode('@', $item['author-link']);
1165 $prefix_host = array_pop($mailparts);
1169 if (!empty($item['plink'])) {
1170 $guid = self::guidFromUri($item['plink'], $prefix_host);
1171 } elseif (!empty($item['uri'])) {
1172 $guid = self::guidFromUri($item['uri'], $prefix_host);
1174 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1180 private static function contactId($item)
1182 $contact_id = (int)$item["contact-id"];
1184 if (!empty($contact_id)) {
1187 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1189 * First we are looking for a suitable contact that matches with the author of the post
1190 * This is done only for comments
1192 if ($item['parent-uri'] != $item['uri']) {
1193 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1196 // If not present then maybe the owner was found
1197 if ($contact_id == 0) {
1198 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1201 // Still missing? Then use the "self" contact of the current user
1202 if ($contact_id == 0) {
1203 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1204 if (DBA::isResult($self)) {
1205 $contact_id = $self["id"];
1208 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1213 // This function will finally cover most of the preparation functionality in mod/item.php
1214 public static function prepare(&$item)
1216 $data = BBCode::getAttachmentData($item['body']);
1217 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1218 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1219 $posttype = Item::PT_PAGE;
1220 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1224 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1228 // If it is a posting where users should get notifications, then define it as wall posting
1231 $item['origin'] = 1;
1232 $item['network'] = NETWORK_DFRN;
1233 $item['protocol'] = PROTOCOL_DFRN;
1235 if (is_int($notify)) {
1236 $priority = $notify;
1238 $priority = PRIORITY_HIGH;
1241 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1244 $item['guid'] = self::guid($item, $notify);
1245 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1247 // Store conversation data
1248 $item = Conversation::insert($item);
1251 * If a Diaspora signature structure was passed in, pull it out of the
1252 * item array and set it aside for later storage.
1256 if (x($item, 'dsprsig')) {
1257 $encoded_signature = $item['dsprsig'];
1258 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1259 unset($item['dsprsig']);
1262 if (!empty($item['diaspora_signed_text'])) {
1263 $diaspora_signed_text = $item['diaspora_signed_text'];
1264 unset($item['diaspora_signed_text']);
1266 $diaspora_signed_text = '';
1269 // Converting the plink
1270 /// @TODO Check if this is really still needed
1271 if ($item['network'] == NETWORK_OSTATUS) {
1272 if (isset($item['plink'])) {
1273 $item['plink'] = OStatus::convertHref($item['plink']);
1274 } elseif (isset($item['uri'])) {
1275 $item['plink'] = OStatus::convertHref($item['uri']);
1279 if (!empty($item['thr-parent'])) {
1280 $item['parent-uri'] = $item['thr-parent'];
1283 if (isset($item['gravity'])) {
1284 $item['gravity'] = intval($item['gravity']);
1285 } elseif ($item['parent-uri'] === $item['uri']) {
1286 $item['gravity'] = GRAVITY_PARENT;
1287 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1288 $item['gravity'] = GRAVITY_COMMENT;
1290 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1291 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1294 $uid = intval($item['uid']);
1296 // check for create date and expire time
1297 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1299 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1300 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1301 $expire_interval = $user['expire'];
1304 if (($expire_interval > 0) && !empty($item['created'])) {
1305 $expire_date = time() - ($expire_interval * 86400);
1306 $created_date = strtotime($item['created']);
1307 if ($created_date < $expire_date) {
1308 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1314 * Do we already have this item?
1315 * We have to check several networks since Friendica posts could be repeated
1316 * via OStatus (maybe Diasporsa as well)
1318 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1319 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1320 trim($item['uri']), $item['uid'],
1321 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1322 $existing = self::selectFirst(['id', 'network'], $condition);
1323 if (DBA::isResult($existing)) {
1324 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1326 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1329 return $existing["id"];
1333 // Ensure to always have the same creation date.
1334 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1335 if (DBA::isResult($existing)) {
1336 $item['created'] = $existing['created'];
1337 $item['uri-hash'] = $existing['uri-hash'];
1340 $item['wall'] = intval(defaults($item, 'wall', 0));
1341 $item['extid'] = trim(defaults($item, 'extid', ''));
1342 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1343 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1344 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1345 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1346 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1347 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1348 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1349 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1350 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1351 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1352 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1353 $item['title'] = trim(defaults($item, 'title', ''));
1354 $item['location'] = trim(defaults($item, 'location', ''));
1355 $item['coord'] = trim(defaults($item, 'coord', ''));
1356 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1357 $item['deleted'] = 0;
1358 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1359 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1360 $item['verb'] = trim(defaults($item, 'verb', ''));
1361 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1362 $item['object'] = trim(defaults($item, 'object', ''));
1363 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1364 $item['target'] = trim(defaults($item, 'target', ''));
1365 $item['plink'] = trim(defaults($item, 'plink', ''));
1366 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1367 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1368 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1369 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1370 $item['private'] = intval(defaults($item, 'private', 0));
1371 $item['body'] = trim(defaults($item, 'body', ''));
1372 $item['tag'] = trim(defaults($item, 'tag', ''));
1373 $item['attach'] = trim(defaults($item, 'attach', ''));
1374 $item['app'] = trim(defaults($item, 'app', ''));
1375 $item['origin'] = intval(defaults($item, 'origin', 0));
1376 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1377 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1378 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1379 $item['inform'] = trim(defaults($item, 'inform', ''));
1380 $item['file'] = trim(defaults($item, 'file', ''));
1382 // Unique identifier to be linked against item-activities and item-content
1383 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1385 // When there is no content then we don't post it
1386 if ($item['body'].$item['title'] == '') {
1387 logger('No body, no title.');
1391 self::addLanguageToItemArray($item);
1393 // Items cannot be stored before they happen ...
1394 if ($item['created'] > DateTimeFormat::utcNow()) {
1395 $item['created'] = DateTimeFormat::utcNow();
1398 // We haven't invented time travel by now.
1399 if ($item['edited'] > DateTimeFormat::utcNow()) {
1400 $item['edited'] = DateTimeFormat::utcNow();
1403 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1405 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1406 $item["contact-id"] = self::contactId($item);
1408 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1409 'photo' => $item['author-avatar'], 'network' => $item['network']];
1411 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1413 if (Contact::isBlocked($item["author-id"])) {
1414 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1418 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1419 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1421 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1423 if (Contact::isBlocked($item["owner-id"])) {
1424 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1428 // These fields aren't stored anymore in the item table, they are fetched upon request
1429 unset($item['author-link']);
1430 unset($item['author-name']);
1431 unset($item['author-avatar']);
1433 unset($item['owner-link']);
1434 unset($item['owner-name']);
1435 unset($item['owner-avatar']);
1437 if ($item['network'] == NETWORK_PHANTOM) {
1438 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1440 $item['network'] = NETWORK_DFRN;
1441 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1444 // Checking if there is already an item with the same guid
1445 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1446 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1447 if (self::exists($condition)) {
1448 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1452 // Check for hashtags in the body and repair or add hashtag links
1453 self::setHashtags($item);
1455 $item['thr-parent'] = $item['parent-uri'];
1463 if ($item['parent-uri'] === $item['uri']) {
1465 $parent_deleted = 0;
1466 $allow_cid = $item['allow_cid'];
1467 $allow_gid = $item['allow_gid'];
1468 $deny_cid = $item['deny_cid'];
1469 $deny_gid = $item['deny_gid'];
1470 $notify_type = 'wall-new';
1472 // find the parent and snarf the item id and ACLs
1473 // and anything else we need to inherit
1475 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1476 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1477 'wall', 'private', 'forum_mode', 'origin'];
1478 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1479 $params = ['order' => ['id' => false]];
1480 $parent = self::selectFirst($fields, $condition, $params);
1482 if (DBA::isResult($parent)) {
1483 // is the new message multi-level threaded?
1484 // even though we don't support it now, preserve the info
1485 // and re-attach to the conversation parent.
1487 if ($parent['uri'] != $parent['parent-uri']) {
1488 $item['parent-uri'] = $parent['parent-uri'];
1490 $condition = ['uri' => $item['parent-uri'],
1491 'parent-uri' => $item['parent-uri'],
1492 'uid' => $item['uid']];
1493 $params = ['order' => ['id' => false]];
1494 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1496 if (DBA::isResult($toplevel_parent)) {
1497 $parent = $toplevel_parent;
1501 $parent_id = $parent['id'];
1502 $parent_deleted = $parent['deleted'];
1503 $allow_cid = $parent['allow_cid'];
1504 $allow_gid = $parent['allow_gid'];
1505 $deny_cid = $parent['deny_cid'];
1506 $deny_gid = $parent['deny_gid'];
1507 $item['wall'] = $parent['wall'];
1508 $notify_type = 'comment-new';
1511 * If the parent is private, force privacy for the entire conversation
1512 * This differs from the above settings as it subtly allows comments from
1513 * email correspondents to be private even if the overall thread is not.
1515 if ($parent['private']) {
1516 $item['private'] = $parent['private'];
1520 * Edge case. We host a public forum that was originally posted to privately.
1521 * The original author commented, but as this is a comment, the permissions
1522 * weren't fixed up so it will still show the comment as private unless we fix it here.
1524 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1525 $item['private'] = 0;
1528 // If its a post from myself then tag the thread as "mention"
1529 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1530 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1531 if (DBA::isResult($user)) {
1532 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1533 $self_id = Contact::getIdForURL($self, 0, true);
1534 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1535 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1536 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1537 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1542 * Allow one to see reply tweets from status.net even when
1543 * we don't have or can't see the original post.
1545 if ($force_parent) {
1546 logger('$force_parent=true, reply converted to top-level post.');
1548 $item['parent-uri'] = $item['uri'];
1549 $item['gravity'] = GRAVITY_PARENT;
1551 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1555 $parent_deleted = 0;
1559 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1560 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1561 if (self::exists($condition)) {
1562 logger('duplicated item with the same uri found. '.print_r($item,true));
1566 // On Friendica and Diaspora the GUID is unique
1567 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1568 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1569 if (self::exists($condition)) {
1570 logger('duplicated item with the same guid found. '.print_r($item,true));
1574 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1575 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1576 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1577 if (self::exists($condition)) {
1578 logger('duplicated item with the same body found. '.print_r($item,true));
1583 // Is this item available in the global items (with uid=0)?
1584 if ($item["uid"] == 0) {
1585 $item["global"] = true;
1587 // Set the global flag on all items if this was a global item entry
1588 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1590 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1594 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1597 $private = $item['private'];
1600 $item["allow_cid"] = $allow_cid;
1601 $item["allow_gid"] = $allow_gid;
1602 $item["deny_cid"] = $deny_cid;
1603 $item["deny_gid"] = $deny_gid;
1604 $item["private"] = $private;
1605 $item["deleted"] = $parent_deleted;
1607 // Fill the cache field
1608 put_item_in_cache($item);
1611 $item['edit'] = false;
1612 $item['parent'] = $parent_id;
1613 Addon::callHooks('post_local', $item);
1614 unset($item['edit']);
1615 unset($item['parent']);
1617 Addon::callHooks('post_remote', $item);
1620 // This array field is used to trigger some automatic reactions
1621 // It is mainly used in the "post_local" hook.
1622 unset($item['api_source']);
1624 if (x($item, 'cancel')) {
1625 logger('post cancelled by addon.');
1630 * Check for already added items.
1631 * There is a timing issue here that sometimes creates double postings.
1632 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1634 if ($item["uid"] == 0) {
1635 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1636 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1641 logger('' . print_r($item,true), LOGGER_DATA);
1643 if (array_key_exists('tag', $item)) {
1644 $tags = $item['tag'];
1645 unset($item['tag']);
1650 if (array_key_exists('file', $item)) {
1651 $files = $item['file'];
1652 unset($item['file']);
1657 // Creates or assigns the permission set
1658 $item['psid'] = PermissionSet::fetchIDForPost($item);
1660 // We are doing this outside of the transaction to avoid timing problems
1661 if (!self::insertActivity($item)) {
1662 self::insertContent($item);
1665 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1666 'inform' => defaults($item, 'inform', '')];
1668 unset($item['postopts']);
1669 unset($item['inform']);
1672 $ret = DBA::insert('item', $item);
1674 // When the item was successfully stored we fetch the ID of the item.
1675 if (DBA::isResult($ret)) {
1676 $current_post = DBA::lastInsertId();
1678 // This can happen - for example - if there are locking timeouts.
1681 // Store the data into a spool file so that we can try again later.
1683 // At first we restore the Diaspora signature that we removed above.
1684 if (isset($encoded_signature)) {
1685 $item['dsprsig'] = $encoded_signature;
1688 // Now we store the data in the spool directory
1689 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1690 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1692 $spoolpath = get_spoolpath();
1693 if ($spoolpath != "") {
1694 $spool = $spoolpath.'/'.$file;
1696 // Ensure to have the removed data from above again in the item array
1697 $item = array_merge($item, $delivery_data);
1699 file_put_contents($spool, json_encode($item));
1700 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1705 if ($current_post == 0) {
1706 // This is one of these error messages that never should occur.
1707 logger("couldn't find created item - we better quit now.");
1712 // How much entries have we created?
1713 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1714 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1717 // There are duplicates. We delete our just created entry.
1718 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1720 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1721 DBA::delete('item', ['id' => $current_post]);
1724 } elseif ($entries == 0) {
1725 // This really should never happen since we quit earlier if there were problems.
1726 logger("Something is terribly wrong. We haven't found our created entry.");
1731 logger('created item '.$current_post);
1732 self::updateContact($item);
1734 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1735 $parent_id = $current_post;
1739 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1741 $item['id'] = $current_post;
1742 $item['parent'] = $parent_id;
1744 // update the commented timestamp on the parent
1745 // Only update "commented" if it is really a comment
1746 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1747 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1749 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1754 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1755 * We can check for this condition when we decode and encode the stuff again.
1757 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1758 $dsprsig->signature = base64_decode($dsprsig->signature);
1759 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1762 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1763 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1766 if (!empty($diaspora_signed_text)) {
1767 // Formerly we stored the signed text, the signature and the author in different fields.
1768 // We now store the raw data so that we are more flexible.
1769 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1772 $deleted = self::tagDeliver($item['uid'], $current_post);
1775 * current post can be deleted if is for a community page and no mention are
1778 if (!$deleted && !$dontcache) {
1779 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1780 if (DBA::isResult($posted_item)) {
1782 Addon::callHooks('post_local_end', $posted_item);
1784 Addon::callHooks('post_remote_end', $posted_item);
1787 logger('new item not found in DB, id ' . $current_post);
1791 if ($item['parent-uri'] === $item['uri']) {
1792 self::addThread($current_post);
1794 self::updateThread($parent_id);
1797 $delivery_data['iid'] = $current_post;
1799 self::insertDeliveryData($delivery_data);
1804 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1805 * This is not perfect - but a workable solution until we found the reason for the problem.
1807 if (!empty($tags)) {
1808 Term::insertFromTagFieldByItemId($current_post, $tags);
1811 if (!empty($files)) {
1812 Term::insertFromFileFieldByItemId($current_post, $files);
1815 if ($item['parent-uri'] === $item['uri']) {
1816 self::addShadow($current_post);
1818 self::addShadowPost($current_post);
1821 check_user_notification($current_post);
1824 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1825 } elseif (!empty($parent) && $parent['origin']) {
1826 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1829 return $current_post;
1833 * @brief Insert a new item delivery data entry
1835 * @param array $item The item fields that are to be inserted
1837 private static function insertDeliveryData($delivery_data)
1839 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1843 DBA::insert('item-delivery-data', $delivery_data);
1847 * @brief Update an existing item delivery data entry
1849 * @param integer $id The item id that is to be updated
1850 * @param array $item The item fields that are to be inserted
1852 private static function updateDeliveryData($id, $delivery_data)
1854 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1858 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1862 * @brief Insert a new item content entry
1864 * @param array $item The item fields that are to be inserted
1866 private static function insertActivity(&$item)
1868 $activity_index = self::activityToIndex($item['verb']);
1870 if ($activity_index < 0) {
1874 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1875 'uri-hash' => $item['uri-hash']];
1877 // We just remove everything that is content
1878 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1879 unset($item[$field]);
1882 // To avoid timing problems, we are using locks.
1883 $locked = Lock::acquire('item_insert_activity');
1885 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1888 // Do we already have this content?
1889 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1890 if (DBA::isResult($item_activity)) {
1891 $item['iaid'] = $item_activity['id'];
1892 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1893 } elseif (DBA::insert('item-activity', $fields)) {
1894 $item['iaid'] = DBA::lastInsertId();
1895 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1897 // This shouldn't happen.
1898 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1902 Lock::release('item_insert_activity');
1908 * @brief Insert a new item content entry
1910 * @param array $item The item fields that are to be inserted
1912 private static function insertContent(&$item)
1914 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1916 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1917 if (isset($item[$field])) {
1918 $fields[$field] = $item[$field];
1919 unset($item[$field]);
1923 // To avoid timing problems, we are using locks.
1924 $locked = Lock::acquire('item_insert_content');
1926 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1929 // Do we already have this content?
1930 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1931 if (DBA::isResult($item_content)) {
1932 $item['icid'] = $item_content['id'];
1933 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1934 } elseif (DBA::insert('item-content', $fields)) {
1935 $item['icid'] = DBA::lastInsertId();
1936 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1938 // This shouldn't happen.
1939 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1942 Lock::release('item_insert_content');
1947 * @brief Update existing item content entries
1949 * @param array $item The item fields that are to be changed
1950 * @param array $condition The condition for finding the item content entries
1952 private static function updateActivity($item, $condition)
1954 if (empty($item['verb'])) {
1957 $activity_index = self::activityToIndex($item['verb']);
1959 if ($activity_index < 0) {
1963 $fields = ['activity' => $activity_index];
1965 logger('Update activity for ' . json_encode($condition));
1967 DBA::update('item-activity', $fields, $condition, true);
1973 * @brief Update existing item content entries
1975 * @param array $item The item fields that are to be changed
1976 * @param array $condition The condition for finding the item content entries
1978 private static function updateContent($item, $condition)
1980 // We have to select only the fields from the "item-content" table
1982 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1983 if (isset($item[$field])) {
1984 $fields[$field] = $item[$field];
1988 if (empty($fields)) {
1989 // when there are no fields at all, just use the condition
1990 // This is to ensure that we always store content.
1991 $fields = $condition;
1994 logger('Update content for ' . json_encode($condition));
1996 DBA::update('item-content', $fields, $condition, true);
2000 * @brief Distributes public items to the receivers
2002 * @param integer $itemid Item ID that should be added
2003 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2005 public static function distribute($itemid, $signed_text = '')
2007 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2008 $parent = self::selectFirst(['owner-id'], $condition);
2009 if (!DBA::isResult($parent)) {
2013 // Only distribute public items from native networks
2014 $condition = ['id' => $itemid, 'uid' => 0,
2015 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2016 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2017 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2018 if (!DBA::isResult($item)) {
2022 $origin = $item['origin'];
2025 unset($item['parent']);
2026 unset($item['mention']);
2027 unset($item['wall']);
2028 unset($item['origin']);
2029 unset($item['starred']);
2033 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2034 $parent['owner-id'], Contact::SHARING, Contact::FRIEND];
2036 $contacts = DBA::select('contact', ['uid'], $condition);
2038 while ($contact = DBA::fetch($contacts)) {
2039 $users[$contact['uid']] = $contact['uid'];
2044 if ($item['uri'] != $item['parent-uri']) {
2045 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2046 while ($parent = DBA::fetch($parents)) {
2047 $users[$parent['uid']] = $parent['uid'];
2048 if ($parent['origin'] && !$origin) {
2049 $origin_uid = $parent['uid'];
2054 foreach ($users as $uid) {
2055 if ($origin_uid == $uid) {
2056 $item['diaspora_signed_text'] = $signed_text;
2058 self::storeForUser($itemid, $item, $uid);
2063 * @brief Store public items for the receivers
2065 * @param integer $itemid Item ID that should be added
2066 * @param array $item The item entry that will be stored
2067 * @param integer $uid The user that will receive the item entry
2069 private static function storeForUser($itemid, $item, $uid)
2071 $item['uid'] = $uid;
2072 $item['origin'] = 0;
2074 if ($item['uri'] == $item['parent-uri']) {
2075 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2077 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2080 if (empty($item['contact-id'])) {
2081 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2082 if (!DBA::isResult($self)) {
2085 $item['contact-id'] = $self['id'];
2088 /// @todo Handling of "event-id"
2091 if ($item['uri'] == $item['parent-uri']) {
2092 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2093 if (DBA::isResult($contact)) {
2094 $notify = self::isRemoteSelf($contact, $item);
2098 $distributed = self::insert($item, false, $notify, true);
2100 if (!$distributed) {
2101 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2103 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2108 * @brief Add a shadow entry for a given item id that is a thread starter
2110 * We store every public item entry additionally with the user id "0".
2111 * This is used for the community page and for the search.
2112 * It is planned that in the future we will store public item entries only once.
2114 * @param integer $itemid Item ID that should be added
2116 public static function addShadow($itemid)
2118 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2119 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2120 $item = self::selectFirst($fields, $condition);
2122 if (!DBA::isResult($item)) {
2126 // is it already a copy?
2127 if (($itemid == 0) || ($item['uid'] == 0)) {
2131 // Is it a visible public post?
2132 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2136 // is it an entry from a connector? Only add an entry for natively connected networks
2137 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2141 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2145 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2147 if (DBA::isResult($item)) {
2148 // Preparing public shadow (removing user specific data)
2151 unset($item['parent']);
2152 unset($item['wall']);
2153 unset($item['mention']);
2154 unset($item['origin']);
2155 unset($item['starred']);
2156 unset($item['postopts']);
2157 unset($item['inform']);
2158 if ($item['uri'] == $item['parent-uri']) {
2159 $item['contact-id'] = $item['owner-id'];
2161 $item['contact-id'] = $item['author-id'];
2164 $public_shadow = self::insert($item, false, false, true);
2166 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2171 * @brief Add a shadow entry for a given item id that is a comment
2173 * This function does the same like the function above - but for comments
2175 * @param integer $itemid Item ID that should be added
2177 public static function addShadowPost($itemid)
2179 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2180 if (!DBA::isResult($item)) {
2184 // Is it a toplevel post?
2185 if ($item['id'] == $item['parent']) {
2186 self::addShadow($itemid);
2190 // Is this a shadow entry?
2191 if ($item['uid'] == 0) {
2195 // Is there a shadow parent?
2196 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2200 // Is there already a shadow entry?
2201 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2205 // Save "origin" and "parent" state
2206 $origin = $item['origin'];
2207 $parent = $item['parent'];
2209 // Preparing public shadow (removing user specific data)
2212 unset($item['parent']);
2213 unset($item['wall']);
2214 unset($item['mention']);
2215 unset($item['origin']);
2216 unset($item['starred']);
2217 unset($item['postopts']);
2218 unset($item['inform']);
2219 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2221 $public_shadow = self::insert($item, false, false, true);
2223 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2225 // If this was a comment to a Diaspora post we don't get our comment back.
2226 // This means that we have to distribute the comment by ourselves.
2227 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2228 self::distribute($public_shadow);
2233 * Adds a language specification in a "language" element of given $arr.
2234 * Expects "body" element to exist in $arr.
2236 private static function addLanguageToItemArray(&$item)
2238 $naked_body = BBCode::toPlaintext($item['body'], false);
2240 $ld = new Text_LanguageDetect();
2241 $ld->setNameMode(2);
2242 $languages = $ld->detect($naked_body, 3);
2244 if (is_array($languages)) {
2245 $item['language'] = json_encode($languages);
2250 * @brief Creates an unique guid out of a given uri
2252 * @param string $uri uri of an item entry
2253 * @param string $host hostname for the GUID prefix
2254 * @return string unique guid
2256 public static function guidFromUri($uri, $host)
2258 // Our regular guid routine is using this kind of prefix as well
2259 // We have to avoid that different routines could accidentally create the same value
2260 $parsed = parse_url($uri);
2262 // We use a hash of the hostname as prefix for the guid
2263 $guid_prefix = hash("crc32", $host);
2265 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2266 unset($parsed["scheme"]);
2268 // Glue it together to be able to make a hash from it
2269 $host_id = implode("/", $parsed);
2271 // We could use any hash algorithm since it isn't a security issue
2272 $host_hash = hash("ripemd128", $host_id);
2274 return $guid_prefix.$host_hash;
2278 * generate an unique URI
2280 * @param integer $uid User id
2281 * @param string $guid An existing GUID (Otherwise it will be generated)
2285 public static function newURI($uid, $guid = "")
2288 $guid = System::createGUID(32);
2291 $hostname = self::getApp()->get_hostname();
2293 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2295 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2301 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2303 * This can be used to filter for inactive contacts.
2304 * Only do this for public postings to avoid privacy problems, since poco data is public.
2305 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2307 * @param array $arr Contains the just posted item record
2309 private static function updateContact($arr)
2311 // Unarchive the author
2312 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2313 if (DBA::isResult($contact)) {
2314 Contact::unmarkForArchival($contact);
2317 // Unarchive the contact if it's not our own contact
2318 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2319 if (DBA::isResult($contact)) {
2320 Contact::unmarkForArchival($contact);
2323 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2325 // Is it a forum? Then we don't care about the rules from above
2326 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2327 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2333 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2334 ['id' => $arr['contact-id']]);
2336 // Now do the same for the system wide contacts with uid=0
2337 if (!$arr['private']) {
2338 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2339 ['id' => $arr['owner-id']]);
2341 if ($arr['owner-id'] != $arr['author-id']) {
2342 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2343 ['id' => $arr['author-id']]);
2348 public static function setHashtags(&$item)
2351 $tags = get_tags($item["body"]);
2354 if (!count($tags)) {
2358 // This sorting is important when there are hashtags that are part of other hashtags
2359 // Otherwise there could be problems with hashtags like #test and #test2
2362 $URLSearchString = "^\[\]";
2364 // All hashtags should point to the home server if "local_tags" is activated
2365 if (Config::get('system', 'local_tags')) {
2366 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2367 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2369 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2370 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2373 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2374 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2376 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2379 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2381 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2384 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2386 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2389 // Repair recursive urls
2390 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2391 "#$2", $item["body"]);
2393 foreach ($tags as $tag) {
2394 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2398 $basetag = str_replace('_',' ',substr($tag,1));
2400 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2402 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2404 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2405 if (strlen($item["tag"])) {
2406 $item["tag"] = ','.$item["tag"];
2408 $item["tag"] = $newtag.$item["tag"];
2412 // Convert back the masked hashtags
2413 $item["body"] = str_replace("#", "#", $item["body"]);
2416 public static function getGuidById($id)
2418 $item = self::selectFirst(['guid'], ['id' => $id]);
2419 if (DBA::isResult($item)) {
2420 return $item['guid'];
2426 public static function getIdAndNickByGuid($guid, $uid = 0)
2432 $uid == local_user();
2435 // Does the given user have this item?
2437 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2438 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2439 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2440 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2441 if (DBA::isResult($item)) {
2443 $nick = $item["nickname"];
2447 // Or is it anywhere on the server?
2449 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2450 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2451 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2452 AND NOT `item`.`private` AND `item`.`wall`
2453 AND `item`.`guid` = ?", $guid);
2454 if (DBA::isResult($item)) {
2456 $nick = $item["nickname"];
2459 return ["nick" => $nick, "id" => $id];
2463 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2465 * @param int $item_id
2466 * @return bool true if item was deleted, else false
2468 private static function tagDeliver($uid, $item_id)
2472 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2473 if (!DBA::isResult($user)) {
2477 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2478 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2480 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2481 if (!DBA::isResult($item)) {
2485 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2488 * Diaspora uses their own hardwired link URL in @-tags
2489 * instead of the one we supply with webfinger
2491 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2493 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2495 foreach ($matches as $mtch) {
2496 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2498 logger('mention found: ' . $mtch[2]);
2504 if (($community_page || $prvgroup) &&
2505 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2506 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2508 logger("no-mention top-level post to community or private group. delete.");
2509 DBA::delete('item', ['id' => $item_id]);
2515 $arr = ['item' => $item, 'user' => $user];
2517 Addon::callHooks('tagged', $arr);
2519 if (!$community_page && !$prvgroup) {
2524 * tgroup delivery - setup a second delivery chain
2525 * prevent delivery looping - only proceed
2526 * if the message originated elsewhere and is a top-level post
2528 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2532 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2533 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2534 if (!DBA::isResult($self)) {
2538 $owner_id = Contact::getIdForURL($self['url']);
2540 // also reset all the privacy bits to the forum default permissions
2542 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2544 $forum_mode = ($prvgroup ? 2 : 1);
2546 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2547 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2548 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2549 DBA::update('item', $fields, ['id' => $item_id]);
2551 self::updateThread($item_id);
2553 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2556 public static function isRemoteSelf($contact, &$datarray)
2560 if (!$contact['remote_self']) {
2564 // Prevent the forwarding of posts that are forwarded
2565 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2566 logger('Already forwarded', LOGGER_DEBUG);
2570 // Prevent to forward already forwarded posts
2571 if ($datarray["app"] == $a->get_hostname()) {
2572 logger('Already forwarded (second test)', LOGGER_DEBUG);
2576 // Only forward posts
2577 if ($datarray["verb"] != ACTIVITY_POST) {
2578 logger('No post', LOGGER_DEBUG);
2582 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2583 logger('Not public', LOGGER_DEBUG);
2587 $datarray2 = $datarray;
2588 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2589 if ($contact['remote_self'] == 2) {
2590 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2591 ['uid' => $contact['uid'], 'self' => true]);
2592 if (DBA::isResult($self)) {
2593 $datarray['contact-id'] = $self["id"];
2595 $datarray['owner-name'] = $self["name"];
2596 $datarray['owner-link'] = $self["url"];
2597 $datarray['owner-avatar'] = $self["thumb"];
2599 $datarray['author-name'] = $datarray['owner-name'];
2600 $datarray['author-link'] = $datarray['owner-link'];
2601 $datarray['author-avatar'] = $datarray['owner-avatar'];
2603 unset($datarray['created']);
2604 unset($datarray['edited']);
2606 unset($datarray['network']);
2607 unset($datarray['owner-id']);
2608 unset($datarray['author-id']);
2611 if ($contact['network'] != NETWORK_FEED) {
2612 $datarray["guid"] = System::createGUID(32);
2613 unset($datarray["plink"]);
2614 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2615 $datarray["parent-uri"] = $datarray["uri"];
2616 $datarray["thr-parent"] = $datarray["uri"];
2617 $datarray["extid"] = NETWORK_DFRN;
2618 $urlpart = parse_url($datarray2['author-link']);
2619 $datarray["app"] = $urlpart["host"];
2621 $datarray['private'] = 0;
2625 if ($contact['network'] != NETWORK_FEED) {
2626 // Store the original post
2627 $result = self::insert($datarray2, false, false);
2628 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2630 $datarray["app"] = "Feed";
2634 // Trigger automatic reactions for addons
2635 $datarray['api_source'] = true;
2637 // We have to tell the hooks who we are - this really should be improved
2638 $_SESSION["authenticated"] = true;
2639 $_SESSION["uid"] = $contact['uid'];
2648 * @param array $item
2652 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2654 if (Config::get('system', 'disable_embedded')) {
2658 logger('check for photos', LOGGER_DEBUG);
2659 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2664 $img_start = strpos($orig_body, '[img');
2665 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2666 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2668 while (($img_st_close !== false) && ($img_len !== false)) {
2669 $img_st_close++; // make it point to AFTER the closing bracket
2670 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2672 logger('found photo ' . $image, LOGGER_DEBUG);
2674 if (stristr($image, $site . '/photo/')) {
2675 // Only embed locally hosted photos
2677 $i = basename($image);
2678 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2679 $x = strpos($i, '-');
2682 $res = substr($i, $x + 1);
2683 $i = substr($i, 0, $x);
2684 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2685 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2686 if (DBA::isResult($photo)) {
2688 * Check to see if we should replace this photo link with an embedded image
2689 * 1. No need to do so if the photo is public
2690 * 2. If there's a contact-id provided, see if they're in the access list
2691 * for the photo. If so, embed it.
2692 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2693 * permissions, regardless of order but first check to see if they're an exact
2694 * match to save some processing overhead.
2696 if (self::hasPermissions($photo)) {
2698 $recips = self::enumeratePermissions($photo);
2699 if (in_array($cid, $recips)) {
2703 if (self::samePermissions($item, $photo)) {
2709 $data = $photo['data'];
2710 $type = $photo['type'];
2712 // If a custom width and height were specified, apply before embedding
2713 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2714 logger('scaling photo', LOGGER_DEBUG);
2716 $width = intval($match[1]);
2717 $height = intval($match[2]);
2719 $Image = new Image($data, $type);
2720 if ($Image->isValid()) {
2721 $Image->scaleDown(max($width, $height));
2722 $data = $Image->asString();
2723 $type = $Image->getType();
2727 logger('replacing photo', LOGGER_DEBUG);
2728 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2729 logger('replaced: ' . $image, LOGGER_DATA);
2735 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2736 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2737 if ($orig_body === false) {
2741 $img_start = strpos($orig_body, '[img');
2742 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2743 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2746 $new_body = $new_body . $orig_body;
2751 private static function hasPermissions($obj)
2753 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2754 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2757 private static function samePermissions($obj1, $obj2)
2759 // first part is easy. Check that these are exactly the same.
2760 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2761 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2762 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2763 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2767 // This is harder. Parse all the permissions and compare the resulting set.
2768 $recipients1 = self::enumeratePermissions($obj1);
2769 $recipients2 = self::enumeratePermissions($obj2);
2773 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2774 return ($recipients1 == $recipients2);
2777 // returns an array of contact-ids that are allowed to see this object
2778 private static function enumeratePermissions($obj)
2780 $allow_people = expand_acl($obj['allow_cid']);
2781 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2782 $deny_people = expand_acl($obj['deny_cid']);
2783 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2784 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2785 $deny = array_unique(array_merge($deny_people, $deny_groups));
2786 $recipients = array_diff($recipients, $deny);
2790 public static function getFeedTags($item)
2794 $cnt = preg_match_all('|\#\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2796 for ($x = 0; $x < $cnt; $x ++) {
2797 if ($matches[1][$x]) {
2798 $ret[$matches[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2803 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2805 for ($x = 0; $x < $cnt; $x ++) {
2806 if ($matches[1][$x]) {
2807 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2814 public static function expire($uid, $days, $network = "", $force = false)
2816 if (!$uid || ($days < 1)) {
2820 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2821 $uid, GRAVITY_PARENT];
2824 * $expire_network_only = save your own wall posts
2825 * and just expire conversations started by others
2827 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2829 if ($expire_network_only) {
2830 $condition[0] .= " AND NOT `wall`";
2833 if ($network != "") {
2834 $condition[0] .= " AND `network` = ?";
2835 $condition[] = $network;
2838 * There is an index "uid_network_received" but not "uid_network_created"
2839 * This avoids the creation of another index just for one purpose.
2840 * And it doesn't really matter wether to look at "received" or "created"
2842 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2843 $condition[] = $days;
2845 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2846 $condition[] = $days;
2849 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id'], $condition);
2851 if (!DBA::isResult($items)) {
2855 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2857 // Forcing expiring of items - but not notes and marked items
2859 $expire_items = true;
2862 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2863 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2864 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2868 while ($item = Item::fetch($items)) {
2869 // don't expire filed items
2871 if (strpos($item['file'], '[') !== false) {
2875 // Only expire posts, not photos and photo comments
2877 if (!$expire_photos && strlen($item['resource-id'])) {
2879 } elseif (!$expire_starred && intval($item['starred'])) {
2881 } elseif (!$expire_notes && $item['type'] == 'note') {
2883 } elseif (!$expire_items && $item['type'] != 'note') {
2887 self::deleteById($item['id'], PRIORITY_LOW);
2892 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2895 public static function firstPostDate($uid, $wall = false)
2897 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2898 $params = ['order' => ['created' => false]];
2899 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2900 if (DBA::isResult($thread)) {
2901 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2907 * @brief add/remove activity to an item
2909 * Toggle activities as like,dislike,attend of an item
2911 * @param string $item_id
2912 * @param string $verb
2913 * Activity verb. One of
2914 * like, unlike, dislike, undislike, attendyes, unattendyes,
2915 * attendno, unattendno, attendmaybe, unattendmaybe
2916 * @hook 'post_local_end'
2918 * 'post_id' => ID of posted item
2920 public static function performLike($item_id, $verb)
2922 if (!local_user() && !remote_user()) {
2929 $activity = ACTIVITY_LIKE;
2933 $activity = ACTIVITY_DISLIKE;
2937 $activity = ACTIVITY_ATTEND;
2941 $activity = ACTIVITY_ATTENDNO;
2944 case 'unattendmaybe':
2945 $activity = ACTIVITY_ATTENDMAYBE;
2948 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2952 // Enable activity toggling instead of on/off
2953 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2955 logger('like: verb ' . $verb . ' item ' . $item_id);
2957 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2958 if (!DBA::isResult($item)) {
2959 logger('like: unknown item ' . $item_id);
2963 $item_uri = $item['uri'];
2965 $uid = $item['uid'];
2966 if (($uid == 0) && local_user()) {
2967 $uid = local_user();
2970 if (!can_write_wall($uid)) {
2971 logger('like: unable to write on wall ' . $uid);
2975 // Retrieves the local post owner
2976 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2977 if (!DBA::isResult($owner_self_contact)) {
2978 logger('like: unknown owner ' . $uid);
2982 // Retrieve the current logged in user's public contact
2983 $author_id = public_contact();
2985 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
2986 if (!DBA::isResult($author_contact)) {
2987 logger('like: unknown author ' . $author_id);
2991 // Contact-id is the uid-dependant author contact
2992 if (local_user() == $uid) {
2993 $item_contact_id = $owner_self_contact['id'];
2994 $item_contact = $owner_self_contact;
2996 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
2997 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
2998 if (!DBA::isResult($item_contact)) {
2999 logger('like: unknown item contact ' . $item_contact_id);
3004 // Look for an existing verb row
3005 // event participation are essentially radio toggles. If you make a subsequent choice,
3006 // we need to eradicate your first choice.
3007 if ($event_verb_flag) {
3008 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3010 // Translate to the index based activity index
3012 foreach ($verbs as $verb) {
3013 $activities[] = self::activityToIndex($verb);
3016 $activities = self::activityToIndex($activity);
3019 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3020 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3022 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3024 // If it exists, mark it as deleted
3025 if (DBA::isResult($like_item)) {
3026 // Already voted, undo it
3027 $fields = ['deleted' => true, 'unseen' => true, 'changed' => DateTimeFormat::utcNow()];
3028 /// @todo Consider using self::update - but before doing so, check the side effects
3029 DBA::update('item', $fields, ['id' => $like_item['id']]);
3031 // Clean up the Diaspora signatures for this like
3032 DBA::delete('sign', ['iid' => $like_item['id']]);
3034 Worker::add(PRIORITY_HIGH, "Notifier", "like", $like_item['id']);
3036 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3041 // Verb is "un-something", just trying to delete existing entries
3042 if (strpos($verb, 'un') === 0) {
3046 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3049 'guid' => System::createGUID(32),
3050 'uri' => self::newURI($item['uid']),
3051 'uid' => $item['uid'],
3052 'contact-id' => $item_contact_id,
3053 'wall' => $item['wall'],
3055 'network' => NETWORK_DFRN,
3056 'gravity' => GRAVITY_ACTIVITY,
3057 'parent' => $item['id'],
3058 'parent-uri' => $item['uri'],
3059 'thr-parent' => $item['uri'],
3060 'owner-id' => $item['owner-id'],
3061 'author-id' => $author_id,
3062 'body' => $activity,
3063 'verb' => $activity,
3064 'object-type' => $objtype,
3065 'allow_cid' => $item['allow_cid'],
3066 'allow_gid' => $item['allow_gid'],
3067 'deny_cid' => $item['deny_cid'],
3068 'deny_gid' => $item['deny_gid'],
3073 $new_item_id = self::insert($new_item);
3075 // If the parent item isn't visible then set it to visible
3076 if (!$item['visible']) {
3077 self::update(['visible' => true], ['id' => $item['id']]);
3080 // Save the author information for the like in case we need to relay to Diaspora
3081 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3083 $new_item['id'] = $new_item_id;
3085 Addon::callHooks('post_local_end', $new_item);
3087 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3092 private static function addThread($itemid, $onlyshadow = false)
3094 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3095 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3096 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3097 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3098 $item = self::selectFirst($fields, $condition);
3100 if (!DBA::isResult($item)) {
3104 $item['iid'] = $itemid;
3107 $result = DBA::insert('thread', $item);
3109 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3113 private static function updateThread($itemid, $setmention = false)
3115 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3116 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3117 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3118 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3120 $item = self::selectFirst($fields, $condition);
3121 if (!DBA::isResult($item)) {
3126 $item["mention"] = 1;
3133 foreach ($item as $field => $data) {
3134 if (!in_array($field, ["guid"])) {
3135 $fields[$field] = $data;
3139 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3141 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3144 private static function deleteThread($itemid, $itemuri = "")
3146 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3147 if (!DBA::isResult($item)) {
3148 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3152 // Using dba::delete at this time could delete the associated item entries
3153 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3155 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3157 if ($itemuri != "") {
3158 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3159 if (!self::exists($condition)) {
3160 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3161 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);