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 'icid', 'iaid', 'psid'];
984 $item = self::selectFirst($fields, ['id' => $item_id]);
985 if (!DBA::isResult($item)) {
986 logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG);
990 if ($item['deleted']) {
991 logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG);
995 $parent = self::selectFirst(['origin'], ['id' => $item['parent']]);
996 if (!DBA::isResult($parent)) {
997 $parent = ['origin' => false];
1000 // clean up categories and tags so they don't end up as orphans
1003 $cnt = preg_match_all('/<(.*?)>/', $item['file'], $matches, PREG_SET_ORDER);
1005 foreach ($matches as $mtch) {
1006 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],true);
1012 $cnt = preg_match_all('/\[(.*?)\]/', $item['file'], $matches, PREG_SET_ORDER);
1014 foreach ($matches as $mtch) {
1015 file_tag_unsave_file($item['uid'], $item['id'], $mtch[1],false);
1020 * If item is a link to a photo resource, nuke all the associated photos
1021 * (visitors will not have photo resources)
1022 * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
1023 * generate a resource-id and therefore aren't intimately linked to the item.
1025 if (strlen($item['resource-id'])) {
1026 DBA::delete('photo', ['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
1029 // If item is a link to an event, delete the event.
1030 if (intval($item['event-id'])) {
1031 Event::delete($item['event-id']);
1034 // If item has attachments, drop them
1035 foreach (explode(", ", $item['attach']) as $attach) {
1036 preg_match("|attach/(\d+)|", $attach, $matches);
1037 if (is_array($matches) && count($matches) > 1) {
1038 DBA::delete('attach', ['id' => $matches[1], 'uid' => $item['uid']]);
1042 // Delete tags that had been attached to other items
1043 self::deleteTagsFromItem($item);
1045 // Set the item to "deleted"
1046 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1047 DBA::update('item', $item_fields, ['id' => $item['id']]);
1049 Term::insertFromTagFieldByItemId($item['id'], '');
1050 Term::insertFromFileFieldByItemId($item['id'], '');
1051 self::deleteThread($item['id'], $item['parent-uri']);
1053 if (!self::exists(["`uri` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri']])) {
1054 self::delete(['uri' => $item['uri'], 'uid' => 0, 'deleted' => false], $priority);
1057 DBA::delete('item-delivery-data', ['iid' => $item['id']]);
1059 if (!empty($item['iaid']) && !DBA::exists('item', ['iaid' => $item['iaid'], 'deleted' => false])) {
1060 DBA::delete('item-activity', ['id' => $item['iaid']], ['cascade' => false]);
1062 if (!empty($item['icid']) && !DBA::exists('item', ['icid' => $item['icid'], 'deleted' => false])) {
1063 DBA::delete('item-content', ['id' => $item['icid']], ['cascade' => false]);
1065 // When the permission set will be used in photo and events as well,
1066 // this query here needs to be extended.
1067 if (!empty($item['psid']) && !DBA::exists('item', ['psid' => $item['psid'], 'deleted' => false])) {
1068 DBA::delete('permissionset', ['id' => $item['psid']]);
1071 // If it's the parent of a comment thread, kill all the kids
1072 if ($item['id'] == $item['parent']) {
1073 self::delete(['parent' => $item['parent'], 'deleted' => false], $priority);
1076 // Is it our comment and/or our thread?
1077 if ($item['origin'] || $parent['origin']) {
1079 // When we delete the original post we will delete all existing copies on the server as well
1080 self::delete(['uri' => $item['uri'], 'deleted' => false], $priority);
1082 // send the notification upstream/downstream
1083 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", "drop", intval($item['id']));
1084 } elseif ($item['uid'] != 0) {
1086 // When we delete just our local user copy of an item, we have to set a marker to hide it
1087 $global_item = self::selectFirst(['id'], ['uri' => $item['uri'], 'uid' => 0, 'deleted' => false]);
1088 if (DBA::isResult($global_item)) {
1089 DBA::update('user-item', ['hidden' => true], ['iid' => $global_item['id'], 'uid' => $item['uid']], true);
1093 logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG);
1098 private static function deleteTagsFromItem($item)
1100 if (($item["verb"] != ACTIVITY_TAG) || ($item["object-type"] != ACTIVITY_OBJ_TAGTERM)) {
1104 $xo = XML::parseString($item["object"], false);
1105 $xt = XML::parseString($item["target"], false);
1107 if ($xt->type != ACTIVITY_OBJ_NOTE) {
1111 $i = self::selectFirst(['id', 'contact-id', 'tag'], ['uri' => $xt->id, 'uid' => $item['uid']]);
1112 if (!DBA::isResult($i)) {
1116 // For tags, the owner cannot remove the tag on the author's copy of the post.
1117 $owner_remove = ($item["contact-id"] == $i["contact-id"]);
1118 $author_copy = $item["origin"];
1120 if (($owner_remove && $author_copy) || !$owner_remove) {
1124 $tags = explode(',', $i["tag"]);
1127 foreach ($tags as $tag) {
1128 if (trim($tag) !== trim($xo->body)) {
1129 $newtags[] = trim($tag);
1133 self::update(['tag' => implode(',', $newtags)], ['id' => $i["id"]]);
1136 private static function guid($item, $notify)
1138 if (!empty($item['guid'])) {
1139 return notags(trim($item['guid']));
1143 // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
1144 // We add the hash of our own host because our host is the original creator of the post.
1145 $prefix_host = get_app()->get_hostname();
1149 // We are only storing the post so we create a GUID from the original hostname.
1150 if (!empty($item['author-link'])) {
1151 $parsed = parse_url($item['author-link']);
1152 if (!empty($parsed['host'])) {
1153 $prefix_host = $parsed['host'];
1157 if (empty($prefix_host) && !empty($item['plink'])) {
1158 $parsed = parse_url($item['plink']);
1159 if (!empty($parsed['host'])) {
1160 $prefix_host = $parsed['host'];
1164 if (empty($prefix_host) && !empty($item['uri'])) {
1165 $parsed = parse_url($item['uri']);
1166 if (!empty($parsed['host'])) {
1167 $prefix_host = $parsed['host'];
1171 // Is it in the format data@host.tld? - Used for mail contacts
1172 if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
1173 $mailparts = explode('@', $item['author-link']);
1174 $prefix_host = array_pop($mailparts);
1178 if (!empty($item['plink'])) {
1179 $guid = self::guidFromUri($item['plink'], $prefix_host);
1180 } elseif (!empty($item['uri'])) {
1181 $guid = self::guidFromUri($item['uri'], $prefix_host);
1183 $guid = System::createGUID(32, hash('crc32', $prefix_host));
1189 private static function contactId($item)
1191 $contact_id = (int)$item["contact-id"];
1193 if (!empty($contact_id)) {
1196 logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG);
1198 * First we are looking for a suitable contact that matches with the author of the post
1199 * This is done only for comments
1201 if ($item['parent-uri'] != $item['uri']) {
1202 $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
1205 // If not present then maybe the owner was found
1206 if ($contact_id == 0) {
1207 $contact_id = Contact::getIdForURL($item['owner-link'], $item['uid']);
1210 // Still missing? Then use the "self" contact of the current user
1211 if ($contact_id == 0) {
1212 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $item['uid']]);
1213 if (DBA::isResult($self)) {
1214 $contact_id = $self["id"];
1217 logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG);
1222 // This function will finally cover most of the preparation functionality in mod/item.php
1223 public static function prepare(&$item)
1225 $data = BBCode::getAttachmentData($item['body']);
1226 if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $item['body'], $match, PREG_SET_ORDER) || isset($data["type"]))
1227 && ($posttype != Item::PT_PERSONAL_NOTE)) {
1228 $posttype = Item::PT_PAGE;
1229 $objecttype = ACTIVITY_OBJ_BOOKMARK;
1233 public static function insert($item, $force_parent = false, $notify = false, $dontcache = false)
1237 // If it is a posting where users should get notifications, then define it as wall posting
1240 $item['origin'] = 1;
1241 $item['network'] = NETWORK_DFRN;
1242 $item['protocol'] = PROTOCOL_DFRN;
1244 if (is_int($notify)) {
1245 $priority = $notify;
1247 $priority = PRIORITY_HIGH;
1250 $item['network'] = trim(defaults($item, 'network', NETWORK_PHANTOM));
1253 $item['guid'] = self::guid($item, $notify);
1254 $item['uri'] = notags(trim(defaults($item, 'uri', self::newURI($item['uid'], $item['guid']))));
1256 // Store conversation data
1257 $item = Conversation::insert($item);
1260 * If a Diaspora signature structure was passed in, pull it out of the
1261 * item array and set it aside for later storage.
1265 if (x($item, 'dsprsig')) {
1266 $encoded_signature = $item['dsprsig'];
1267 $dsprsig = json_decode(base64_decode($item['dsprsig']));
1268 unset($item['dsprsig']);
1271 if (!empty($item['diaspora_signed_text'])) {
1272 $diaspora_signed_text = $item['diaspora_signed_text'];
1273 unset($item['diaspora_signed_text']);
1275 $diaspora_signed_text = '';
1278 // Converting the plink
1279 /// @TODO Check if this is really still needed
1280 if ($item['network'] == NETWORK_OSTATUS) {
1281 if (isset($item['plink'])) {
1282 $item['plink'] = OStatus::convertHref($item['plink']);
1283 } elseif (isset($item['uri'])) {
1284 $item['plink'] = OStatus::convertHref($item['uri']);
1288 if (!empty($item['thr-parent'])) {
1289 $item['parent-uri'] = $item['thr-parent'];
1292 if (isset($item['gravity'])) {
1293 $item['gravity'] = intval($item['gravity']);
1294 } elseif ($item['parent-uri'] === $item['uri']) {
1295 $item['gravity'] = GRAVITY_PARENT;
1296 } elseif (activity_match($item['verb'], ACTIVITY_POST)) {
1297 $item['gravity'] = GRAVITY_COMMENT;
1299 $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
1300 logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG);
1303 $uid = intval($item['uid']);
1305 // check for create date and expire time
1306 $expire_interval = Config::get('system', 'dbclean-expire-days', 0);
1308 $user = DBA::selectFirst('user', ['expire'], ['uid' => $uid]);
1309 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
1310 $expire_interval = $user['expire'];
1313 if (($expire_interval > 0) && !empty($item['created'])) {
1314 $expire_date = time() - ($expire_interval * 86400);
1315 $created_date = strtotime($item['created']);
1316 if ($created_date < $expire_date) {
1317 logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG);
1323 * Do we already have this item?
1324 * We have to check several networks since Friendica posts could be repeated
1325 * via OStatus (maybe Diasporsa as well)
1327 if (in_array($item['network'], [NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS, ""])) {
1328 $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
1329 trim($item['uri']), $item['uid'],
1330 NETWORK_DIASPORA, NETWORK_DFRN, NETWORK_OSTATUS];
1331 $existing = self::selectFirst(['id', 'network'], $condition);
1332 if (DBA::isResult($existing)) {
1333 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
1335 logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
1338 return $existing["id"];
1342 // Ensure to always have the same creation date.
1343 $existing = DBA::selectfirst('item', ['created', 'uri-hash'], ['uri' => $item['uri']]);
1344 if (DBA::isResult($existing)) {
1345 $item['created'] = $existing['created'];
1346 $item['uri-hash'] = $existing['uri-hash'];
1349 $item['wall'] = intval(defaults($item, 'wall', 0));
1350 $item['extid'] = trim(defaults($item, 'extid', ''));
1351 $item['author-name'] = trim(defaults($item, 'author-name', ''));
1352 $item['author-link'] = trim(defaults($item, 'author-link', ''));
1353 $item['author-avatar'] = trim(defaults($item, 'author-avatar', ''));
1354 $item['owner-name'] = trim(defaults($item, 'owner-name', ''));
1355 $item['owner-link'] = trim(defaults($item, 'owner-link', ''));
1356 $item['owner-avatar'] = trim(defaults($item, 'owner-avatar', ''));
1357 $item['received'] = ((x($item, 'received') !== false) ? DateTimeFormat::utc($item['received']) : DateTimeFormat::utcNow());
1358 $item['created'] = ((x($item, 'created') !== false) ? DateTimeFormat::utc($item['created']) : $item['received']);
1359 $item['edited'] = ((x($item, 'edited') !== false) ? DateTimeFormat::utc($item['edited']) : $item['created']);
1360 $item['changed'] = ((x($item, 'changed') !== false) ? DateTimeFormat::utc($item['changed']) : $item['created']);
1361 $item['commented'] = ((x($item, 'commented') !== false) ? DateTimeFormat::utc($item['commented']) : $item['created']);
1362 $item['title'] = trim(defaults($item, 'title', ''));
1363 $item['location'] = trim(defaults($item, 'location', ''));
1364 $item['coord'] = trim(defaults($item, 'coord', ''));
1365 $item['visible'] = ((x($item, 'visible') !== false) ? intval($item['visible']) : 1);
1366 $item['deleted'] = 0;
1367 $item['parent-uri'] = trim(defaults($item, 'parent-uri', $item['uri']));
1368 $item['post-type'] = defaults($item, 'post-type', self::PT_ARTICLE);
1369 $item['verb'] = trim(defaults($item, 'verb', ''));
1370 $item['object-type'] = trim(defaults($item, 'object-type', ''));
1371 $item['object'] = trim(defaults($item, 'object', ''));
1372 $item['target-type'] = trim(defaults($item, 'target-type', ''));
1373 $item['target'] = trim(defaults($item, 'target', ''));
1374 $item['plink'] = trim(defaults($item, 'plink', ''));
1375 $item['allow_cid'] = trim(defaults($item, 'allow_cid', ''));
1376 $item['allow_gid'] = trim(defaults($item, 'allow_gid', ''));
1377 $item['deny_cid'] = trim(defaults($item, 'deny_cid', ''));
1378 $item['deny_gid'] = trim(defaults($item, 'deny_gid', ''));
1379 $item['private'] = intval(defaults($item, 'private', 0));
1380 $item['body'] = trim(defaults($item, 'body', ''));
1381 $item['tag'] = trim(defaults($item, 'tag', ''));
1382 $item['attach'] = trim(defaults($item, 'attach', ''));
1383 $item['app'] = trim(defaults($item, 'app', ''));
1384 $item['origin'] = intval(defaults($item, 'origin', 0));
1385 $item['postopts'] = trim(defaults($item, 'postopts', ''));
1386 $item['resource-id'] = trim(defaults($item, 'resource-id', ''));
1387 $item['event-id'] = intval(defaults($item, 'event-id', 0));
1388 $item['inform'] = trim(defaults($item, 'inform', ''));
1389 $item['file'] = trim(defaults($item, 'file', ''));
1391 // Unique identifier to be linked against item-activities and item-content
1392 $item['uri-hash'] = defaults($item, 'uri-hash', self::itemHash($item['uri'], $item['created']));
1394 // When there is no content then we don't post it
1395 if ($item['body'].$item['title'] == '') {
1396 logger('No body, no title.');
1400 self::addLanguageToItemArray($item);
1402 // Items cannot be stored before they happen ...
1403 if ($item['created'] > DateTimeFormat::utcNow()) {
1404 $item['created'] = DateTimeFormat::utcNow();
1407 // We haven't invented time travel by now.
1408 if ($item['edited'] > DateTimeFormat::utcNow()) {
1409 $item['edited'] = DateTimeFormat::utcNow();
1412 $item['plink'] = defaults($item, 'plink', System::baseUrl() . '/display/' . urlencode($item['guid']));
1414 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
1415 $item["contact-id"] = self::contactId($item);
1417 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
1418 'photo' => $item['author-avatar'], 'network' => $item['network']];
1420 $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
1422 if (Contact::isBlocked($item["author-id"])) {
1423 logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
1427 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
1428 'photo' => $item['owner-avatar'], 'network' => $item['network']];
1430 $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
1432 if (Contact::isBlocked($item["owner-id"])) {
1433 logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
1437 // These fields aren't stored anymore in the item table, they are fetched upon request
1438 unset($item['author-link']);
1439 unset($item['author-name']);
1440 unset($item['author-avatar']);
1442 unset($item['owner-link']);
1443 unset($item['owner-name']);
1444 unset($item['owner-avatar']);
1446 if ($item['network'] == NETWORK_PHANTOM) {
1447 logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG);
1449 $item['network'] = NETWORK_DFRN;
1450 logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG);
1453 // Checking if there is already an item with the same guid
1454 logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG);
1455 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
1456 if (self::exists($condition)) {
1457 logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG);
1461 // Check for hashtags in the body and repair or add hashtag links
1462 self::setHashtags($item);
1464 $item['thr-parent'] = $item['parent-uri'];
1472 if ($item['parent-uri'] === $item['uri']) {
1474 $parent_deleted = 0;
1475 $allow_cid = $item['allow_cid'];
1476 $allow_gid = $item['allow_gid'];
1477 $deny_cid = $item['deny_cid'];
1478 $deny_gid = $item['deny_gid'];
1479 $notify_type = 'wall-new';
1481 // find the parent and snarf the item id and ACLs
1482 // and anything else we need to inherit
1484 $fields = ['uri', 'parent-uri', 'id', 'deleted',
1485 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
1486 'wall', 'private', 'forum_mode', 'origin'];
1487 $condition = ['uri' => $item['parent-uri'], 'uid' => $item['uid']];
1488 $params = ['order' => ['id' => false]];
1489 $parent = self::selectFirst($fields, $condition, $params);
1491 if (DBA::isResult($parent)) {
1492 // is the new message multi-level threaded?
1493 // even though we don't support it now, preserve the info
1494 // and re-attach to the conversation parent.
1496 if ($parent['uri'] != $parent['parent-uri']) {
1497 $item['parent-uri'] = $parent['parent-uri'];
1499 $condition = ['uri' => $item['parent-uri'],
1500 'parent-uri' => $item['parent-uri'],
1501 'uid' => $item['uid']];
1502 $params = ['order' => ['id' => false]];
1503 $toplevel_parent = self::selectFirst($fields, $condition, $params);
1505 if (DBA::isResult($toplevel_parent)) {
1506 $parent = $toplevel_parent;
1510 $parent_id = $parent['id'];
1511 $parent_deleted = $parent['deleted'];
1512 $allow_cid = $parent['allow_cid'];
1513 $allow_gid = $parent['allow_gid'];
1514 $deny_cid = $parent['deny_cid'];
1515 $deny_gid = $parent['deny_gid'];
1516 $item['wall'] = $parent['wall'];
1517 $notify_type = 'comment-new';
1520 * If the parent is private, force privacy for the entire conversation
1521 * This differs from the above settings as it subtly allows comments from
1522 * email correspondents to be private even if the overall thread is not.
1524 if ($parent['private']) {
1525 $item['private'] = $parent['private'];
1529 * Edge case. We host a public forum that was originally posted to privately.
1530 * The original author commented, but as this is a comment, the permissions
1531 * weren't fixed up so it will still show the comment as private unless we fix it here.
1533 if ((intval($parent['forum_mode']) == 1) && $parent['private']) {
1534 $item['private'] = 0;
1537 // If its a post from myself then tag the thread as "mention"
1538 logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG);
1539 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
1540 if (DBA::isResult($user)) {
1541 $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
1542 $self_id = Contact::getIdForURL($self, 0, true);
1543 logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG);
1544 if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
1545 DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
1546 logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG);
1551 * Allow one to see reply tweets from status.net even when
1552 * we don't have or can't see the original post.
1554 if ($force_parent) {
1555 logger('$force_parent=true, reply converted to top-level post.');
1557 $item['parent-uri'] = $item['uri'];
1558 $item['gravity'] = GRAVITY_PARENT;
1560 logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
1564 $parent_deleted = 0;
1568 $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
1569 $item['uri'], $item['network'], NETWORK_DFRN, $item['uid']];
1570 if (self::exists($condition)) {
1571 logger('duplicated item with the same uri found. '.print_r($item,true));
1575 // On Friendica and Diaspora the GUID is unique
1576 if (in_array($item['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
1577 $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
1578 if (self::exists($condition)) {
1579 logger('duplicated item with the same guid found. '.print_r($item,true));
1583 // Check for an existing post with the same content. There seems to be a problem with OStatus.
1584 $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
1585 $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
1586 if (self::exists($condition)) {
1587 logger('duplicated item with the same body found. '.print_r($item,true));
1592 // Is this item available in the global items (with uid=0)?
1593 if ($item["uid"] == 0) {
1594 $item["global"] = true;
1596 // Set the global flag on all items if this was a global item entry
1597 DBA::update('item', ['global' => true], ['uri' => $item["uri"]]);
1599 $item["global"] = self::exists(['uid' => 0, 'uri' => $item["uri"]]);
1603 if (strlen($allow_cid) || strlen($allow_gid) || strlen($deny_cid) || strlen($deny_gid)) {
1606 $private = $item['private'];
1609 $item["allow_cid"] = $allow_cid;
1610 $item["allow_gid"] = $allow_gid;
1611 $item["deny_cid"] = $deny_cid;
1612 $item["deny_gid"] = $deny_gid;
1613 $item["private"] = $private;
1614 $item["deleted"] = $parent_deleted;
1616 // Fill the cache field
1617 put_item_in_cache($item);
1620 $item['edit'] = false;
1621 $item['parent'] = $parent_id;
1622 Addon::callHooks('post_local', $item);
1623 unset($item['edit']);
1624 unset($item['parent']);
1626 Addon::callHooks('post_remote', $item);
1629 // This array field is used to trigger some automatic reactions
1630 // It is mainly used in the "post_local" hook.
1631 unset($item['api_source']);
1633 if (x($item, 'cancel')) {
1634 logger('post cancelled by addon.');
1639 * Check for already added items.
1640 * There is a timing issue here that sometimes creates double postings.
1641 * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
1643 if ($item["uid"] == 0) {
1644 if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
1645 logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG);
1650 logger('' . print_r($item,true), LOGGER_DATA);
1652 if (array_key_exists('tag', $item)) {
1653 $tags = $item['tag'];
1654 unset($item['tag']);
1659 if (array_key_exists('file', $item)) {
1660 $files = $item['file'];
1661 unset($item['file']);
1666 // Creates or assigns the permission set
1667 $item['psid'] = PermissionSet::fetchIDForPost($item);
1669 // We are doing this outside of the transaction to avoid timing problems
1670 if (!self::insertActivity($item)) {
1671 self::insertContent($item);
1674 $delivery_data = ['postopts' => defaults($item, 'postopts', ''),
1675 'inform' => defaults($item, 'inform', '')];
1677 unset($item['postopts']);
1678 unset($item['inform']);
1681 $ret = DBA::insert('item', $item);
1683 // When the item was successfully stored we fetch the ID of the item.
1684 if (DBA::isResult($ret)) {
1685 $current_post = DBA::lastInsertId();
1687 // This can happen - for example - if there are locking timeouts.
1690 // Store the data into a spool file so that we can try again later.
1692 // At first we restore the Diaspora signature that we removed above.
1693 if (isset($encoded_signature)) {
1694 $item['dsprsig'] = $encoded_signature;
1697 // Now we store the data in the spool directory
1698 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
1699 $file = 'item-'.round(microtime(true) * 10000).'-'.mt_rand().'.msg';
1701 $spoolpath = get_spoolpath();
1702 if ($spoolpath != "") {
1703 $spool = $spoolpath.'/'.$file;
1705 // Ensure to have the removed data from above again in the item array
1706 $item = array_merge($item, $delivery_data);
1708 file_put_contents($spool, json_encode($item));
1709 logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG);
1714 if ($current_post == 0) {
1715 // This is one of these error messages that never should occur.
1716 logger("couldn't find created item - we better quit now.");
1721 // How much entries have we created?
1722 // We wouldn't need this query when we could use an unique index - but MySQL has length problems with them.
1723 $entries = DBA::count('item', ['uri' => $item['uri'], 'uid' => $item['uid'], 'network' => $item['network']]);
1726 // There are duplicates. We delete our just created entry.
1727 logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
1729 // Yes, we could do a rollback here - but we are having many users with MyISAM.
1730 DBA::delete('item', ['id' => $current_post]);
1733 } elseif ($entries == 0) {
1734 // This really should never happen since we quit earlier if there were problems.
1735 logger("Something is terribly wrong. We haven't found our created entry.");
1740 logger('created item '.$current_post);
1741 self::updateContact($item);
1743 if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
1744 $parent_id = $current_post;
1748 DBA::update('item', ['parent' => $parent_id], ['id' => $current_post]);
1750 $item['id'] = $current_post;
1751 $item['parent'] = $parent_id;
1753 // update the commented timestamp on the parent
1754 // Only update "commented" if it is really a comment
1755 if (($item['gravity'] != GRAVITY_ACTIVITY) || !Config::get("system", "like_no_comment")) {
1756 DBA::update('item', ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1758 DBA::update('item', ['changed' => DateTimeFormat::utcNow()], ['id' => $parent_id]);
1763 * Friendica servers lower than 3.4.3-2 had double encoded the signature ...
1764 * We can check for this condition when we decode and encode the stuff again.
1766 if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
1767 $dsprsig->signature = base64_decode($dsprsig->signature);
1768 logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG);
1771 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $dsprsig->signed_text,
1772 'signature' => $dsprsig->signature, 'signer' => $dsprsig->signer]);
1775 if (!empty($diaspora_signed_text)) {
1776 // Formerly we stored the signed text, the signature and the author in different fields.
1777 // We now store the raw data so that we are more flexible.
1778 DBA::insert('sign', ['iid' => $current_post, 'signed_text' => $diaspora_signed_text]);
1781 $deleted = self::tagDeliver($item['uid'], $current_post);
1784 * current post can be deleted if is for a community page and no mention are
1787 if (!$deleted && !$dontcache) {
1788 $posted_item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $current_post]);
1789 if (DBA::isResult($posted_item)) {
1791 Addon::callHooks('post_local_end', $posted_item);
1793 Addon::callHooks('post_remote_end', $posted_item);
1796 logger('new item not found in DB, id ' . $current_post);
1800 if ($item['parent-uri'] === $item['uri']) {
1801 self::addThread($current_post);
1803 self::updateThread($parent_id);
1806 $delivery_data['iid'] = $current_post;
1808 self::insertDeliveryData($delivery_data);
1813 * Due to deadlock issues with the "term" table we are doing these steps after the commit.
1814 * This is not perfect - but a workable solution until we found the reason for the problem.
1816 if (!empty($tags)) {
1817 Term::insertFromTagFieldByItemId($current_post, $tags);
1820 if (!empty($files)) {
1821 Term::insertFromFileFieldByItemId($current_post, $files);
1824 if ($item['parent-uri'] === $item['uri']) {
1825 self::addShadow($current_post);
1827 self::addShadowPost($current_post);
1830 check_user_notification($current_post);
1833 Worker::add(['priority' => $priority, 'dont_fork' => true], "Notifier", $notify_type, $current_post);
1834 } elseif (!empty($parent) && $parent['origin']) {
1835 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "Notifier", "comment-import", $current_post);
1838 return $current_post;
1842 * @brief Insert a new item delivery data entry
1844 * @param array $item The item fields that are to be inserted
1846 private static function insertDeliveryData($delivery_data)
1848 if (empty($delivery_data['iid']) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1852 DBA::insert('item-delivery-data', $delivery_data);
1856 * @brief Update an existing item delivery data entry
1858 * @param integer $id The item id that is to be updated
1859 * @param array $item The item fields that are to be inserted
1861 private static function updateDeliveryData($id, $delivery_data)
1863 if (empty($id) || (empty($delivery_data['postopts']) && empty($delivery_data['inform']))) {
1867 DBA::update('item-delivery-data', $delivery_data, ['iid' => $id], true);
1871 * @brief Insert a new item content entry
1873 * @param array $item The item fields that are to be inserted
1875 private static function insertActivity(&$item)
1877 $activity_index = self::activityToIndex($item['verb']);
1879 if ($activity_index < 0) {
1883 $fields = ['uri' => $item['uri'], 'activity' => $activity_index,
1884 'uri-hash' => $item['uri-hash']];
1886 // We just remove everything that is content
1887 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1888 unset($item[$field]);
1891 // To avoid timing problems, we are using locks.
1892 $locked = Lock::acquire('item_insert_activity');
1894 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1897 // Do we already have this content?
1898 $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-hash' => $item['uri-hash']]);
1899 if (DBA::isResult($item_activity)) {
1900 $item['iaid'] = $item_activity['id'];
1901 logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1902 } elseif (DBA::insert('item-activity', $fields)) {
1903 $item['iaid'] = DBA::lastInsertId();
1904 logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
1906 // This shouldn't happen.
1907 logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
1911 Lock::release('item_insert_activity');
1917 * @brief Insert a new item content entry
1919 * @param array $item The item fields that are to be inserted
1921 private static function insertContent(&$item)
1923 $fields = ['uri' => $item['uri'], 'uri-plink-hash' => $item['uri-hash']];
1925 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1926 if (isset($item[$field])) {
1927 $fields[$field] = $item[$field];
1928 unset($item[$field]);
1932 // To avoid timing problems, we are using locks.
1933 $locked = Lock::acquire('item_insert_content');
1935 logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
1938 // Do we already have this content?
1939 $item_content = DBA::selectFirst('item-content', ['id'], ['uri-plink-hash' => $item['uri-hash']]);
1940 if (DBA::isResult($item_content)) {
1941 $item['icid'] = $item_content['id'];
1942 logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1943 } elseif (DBA::insert('item-content', $fields)) {
1944 $item['icid'] = DBA::lastInsertId();
1945 logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
1947 // This shouldn't happen.
1948 logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
1951 Lock::release('item_insert_content');
1956 * @brief Update existing item content entries
1958 * @param array $item The item fields that are to be changed
1959 * @param array $condition The condition for finding the item content entries
1961 private static function updateActivity($item, $condition)
1963 if (empty($item['verb'])) {
1966 $activity_index = self::activityToIndex($item['verb']);
1968 if ($activity_index < 0) {
1972 $fields = ['activity' => $activity_index];
1974 logger('Update activity for ' . json_encode($condition));
1976 DBA::update('item-activity', $fields, $condition, true);
1982 * @brief Update existing item content entries
1984 * @param array $item The item fields that are to be changed
1985 * @param array $condition The condition for finding the item content entries
1987 private static function updateContent($item, $condition)
1989 // We have to select only the fields from the "item-content" table
1991 foreach (array_merge(self::CONTENT_FIELDLIST, self::MIXED_CONTENT_FIELDLIST) as $field) {
1992 if (isset($item[$field])) {
1993 $fields[$field] = $item[$field];
1997 if (empty($fields)) {
1998 // when there are no fields at all, just use the condition
1999 // This is to ensure that we always store content.
2000 $fields = $condition;
2003 logger('Update content for ' . json_encode($condition));
2005 DBA::update('item-content', $fields, $condition, true);
2009 * @brief Distributes public items to the receivers
2011 * @param integer $itemid Item ID that should be added
2012 * @param string $signed_text Original text (for Diaspora signatures), JSON encoded.
2014 public static function distribute($itemid, $signed_text = '')
2016 $condition = ["`id` IN (SELECT `parent` FROM `item` WHERE `id` = ?)", $itemid];
2017 $parent = self::selectFirst(['owner-id'], $condition);
2018 if (!DBA::isResult($parent)) {
2022 // Only distribute public items from native networks
2023 $condition = ['id' => $itemid, 'uid' => 0,
2024 'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""],
2025 'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
2026 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2027 if (!DBA::isResult($item)) {
2031 $origin = $item['origin'];
2034 unset($item['parent']);
2035 unset($item['mention']);
2036 unset($item['wall']);
2037 unset($item['origin']);
2038 unset($item['starred']);
2042 $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
2043 $parent['owner-id'], Contact::SHARING, Contact::FRIEND];
2045 $contacts = DBA::select('contact', ['uid'], $condition);
2047 while ($contact = DBA::fetch($contacts)) {
2048 $users[$contact['uid']] = $contact['uid'];
2053 if ($item['uri'] != $item['parent-uri']) {
2054 $parents = self::select(['uid', 'origin'], ["`uri` = ? AND `uid` != 0", $item['parent-uri']]);
2055 while ($parent = DBA::fetch($parents)) {
2056 $users[$parent['uid']] = $parent['uid'];
2057 if ($parent['origin'] && !$origin) {
2058 $origin_uid = $parent['uid'];
2063 foreach ($users as $uid) {
2064 if ($origin_uid == $uid) {
2065 $item['diaspora_signed_text'] = $signed_text;
2067 self::storeForUser($itemid, $item, $uid);
2072 * @brief Store public items for the receivers
2074 * @param integer $itemid Item ID that should be added
2075 * @param array $item The item entry that will be stored
2076 * @param integer $uid The user that will receive the item entry
2078 private static function storeForUser($itemid, $item, $uid)
2080 $item['uid'] = $uid;
2081 $item['origin'] = 0;
2083 if ($item['uri'] == $item['parent-uri']) {
2084 $item['contact-id'] = Contact::getIdForURL($item['owner-link'], $uid);
2086 $item['contact-id'] = Contact::getIdForURL($item['author-link'], $uid);
2089 if (empty($item['contact-id'])) {
2090 $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
2091 if (!DBA::isResult($self)) {
2094 $item['contact-id'] = $self['id'];
2097 /// @todo Handling of "event-id"
2100 if ($item['uri'] == $item['parent-uri']) {
2101 $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
2102 if (DBA::isResult($contact)) {
2103 $notify = self::isRemoteSelf($contact, $item);
2107 $distributed = self::insert($item, false, $notify, true);
2109 if (!$distributed) {
2110 logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG);
2112 logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG);
2117 * @brief Add a shadow entry for a given item id that is a thread starter
2119 * We store every public item entry additionally with the user id "0".
2120 * This is used for the community page and for the search.
2121 * It is planned that in the future we will store public item entries only once.
2123 * @param integer $itemid Item ID that should be added
2125 public static function addShadow($itemid)
2127 $fields = ['uid', 'private', 'moderated', 'visible', 'deleted', 'network', 'uri'];
2128 $condition = ['id' => $itemid, 'parent' => [0, $itemid]];
2129 $item = self::selectFirst($fields, $condition);
2131 if (!DBA::isResult($item)) {
2135 // is it already a copy?
2136 if (($itemid == 0) || ($item['uid'] == 0)) {
2140 // Is it a visible public post?
2141 if (!$item["visible"] || $item["deleted"] || $item["moderated"] || $item["private"]) {
2145 // is it an entry from a connector? Only add an entry for natively connected networks
2146 if (!in_array($item["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
2150 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2154 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2156 if (DBA::isResult($item)) {
2157 // Preparing public shadow (removing user specific data)
2160 unset($item['parent']);
2161 unset($item['wall']);
2162 unset($item['mention']);
2163 unset($item['origin']);
2164 unset($item['starred']);
2165 unset($item['postopts']);
2166 unset($item['inform']);
2167 if ($item['uri'] == $item['parent-uri']) {
2168 $item['contact-id'] = $item['owner-id'];
2170 $item['contact-id'] = $item['author-id'];
2173 $public_shadow = self::insert($item, false, false, true);
2175 logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG);
2180 * @brief Add a shadow entry for a given item id that is a comment
2182 * This function does the same like the function above - but for comments
2184 * @param integer $itemid Item ID that should be added
2186 public static function addShadowPost($itemid)
2188 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
2189 if (!DBA::isResult($item)) {
2193 // Is it a toplevel post?
2194 if ($item['id'] == $item['parent']) {
2195 self::addShadow($itemid);
2199 // Is this a shadow entry?
2200 if ($item['uid'] == 0) {
2204 // Is there a shadow parent?
2205 if (!self::exists(['uri' => $item['parent-uri'], 'uid' => 0])) {
2209 // Is there already a shadow entry?
2210 if (self::exists(['uri' => $item['uri'], 'uid' => 0])) {
2214 // Save "origin" and "parent" state
2215 $origin = $item['origin'];
2216 $parent = $item['parent'];
2218 // Preparing public shadow (removing user specific data)
2221 unset($item['parent']);
2222 unset($item['wall']);
2223 unset($item['mention']);
2224 unset($item['origin']);
2225 unset($item['starred']);
2226 unset($item['postopts']);
2227 unset($item['inform']);
2228 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
2230 $public_shadow = self::insert($item, false, false, true);
2232 logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG);
2234 // If this was a comment to a Diaspora post we don't get our comment back.
2235 // This means that we have to distribute the comment by ourselves.
2236 if ($origin && self::exists(['id' => $parent, 'network' => NETWORK_DIASPORA])) {
2237 self::distribute($public_shadow);
2242 * Adds a language specification in a "language" element of given $arr.
2243 * Expects "body" element to exist in $arr.
2245 private static function addLanguageToItemArray(&$item)
2247 $naked_body = BBCode::toPlaintext($item['body'], false);
2249 $ld = new Text_LanguageDetect();
2250 $ld->setNameMode(2);
2251 $languages = $ld->detect($naked_body, 3);
2253 if (is_array($languages)) {
2254 $item['language'] = json_encode($languages);
2259 * @brief Creates an unique guid out of a given uri
2261 * @param string $uri uri of an item entry
2262 * @param string $host hostname for the GUID prefix
2263 * @return string unique guid
2265 public static function guidFromUri($uri, $host)
2267 // Our regular guid routine is using this kind of prefix as well
2268 // We have to avoid that different routines could accidentally create the same value
2269 $parsed = parse_url($uri);
2271 // We use a hash of the hostname as prefix for the guid
2272 $guid_prefix = hash("crc32", $host);
2274 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
2275 unset($parsed["scheme"]);
2277 // Glue it together to be able to make a hash from it
2278 $host_id = implode("/", $parsed);
2280 // We could use any hash algorithm since it isn't a security issue
2281 $host_hash = hash("ripemd128", $host_id);
2283 return $guid_prefix.$host_hash;
2287 * generate an unique URI
2289 * @param integer $uid User id
2290 * @param string $guid An existing GUID (Otherwise it will be generated)
2294 public static function newURI($uid, $guid = "")
2297 $guid = System::createGUID(32);
2300 $hostname = self::getApp()->get_hostname();
2302 $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
2304 $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
2310 * @brief Set "success_update" and "last-item" to the date of the last time we heard from this contact
2312 * This can be used to filter for inactive contacts.
2313 * Only do this for public postings to avoid privacy problems, since poco data is public.
2314 * Don't set this value if it isn't from the owner (could be an author that we don't know)
2316 * @param array $arr Contains the just posted item record
2318 private static function updateContact($arr)
2320 // Unarchive the author
2321 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
2322 if (DBA::isResult($contact)) {
2323 Contact::unmarkForArchival($contact);
2326 // Unarchive the contact if it's not our own contact
2327 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
2328 if (DBA::isResult($contact)) {
2329 Contact::unmarkForArchival($contact);
2332 $update = (!$arr['private'] && ((defaults($arr, 'author-link', '') === defaults($arr, 'owner-link', '')) || ($arr["parent-uri"] === $arr["uri"])));
2334 // Is it a forum? Then we don't care about the rules from above
2335 if (!$update && ($arr["network"] == NETWORK_DFRN) && ($arr["parent-uri"] === $arr["uri"])) {
2336 if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
2342 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2343 ['id' => $arr['contact-id']]);
2345 // Now do the same for the system wide contacts with uid=0
2346 if (!$arr['private']) {
2347 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2348 ['id' => $arr['owner-id']]);
2350 if ($arr['owner-id'] != $arr['author-id']) {
2351 DBA::update('contact', ['success_update' => $arr['received'], 'last-item' => $arr['received']],
2352 ['id' => $arr['author-id']]);
2357 public static function setHashtags(&$item)
2360 $tags = get_tags($item["body"]);
2363 if (!count($tags)) {
2367 // This sorting is important when there are hashtags that are part of other hashtags
2368 // Otherwise there could be problems with hashtags like #test and #test2
2371 $URLSearchString = "^\[\]";
2373 // All hashtags should point to the home server if "local_tags" is activated
2374 if (Config::get('system', 'local_tags')) {
2375 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2376 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["body"]);
2378 $item["tag"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2379 "#[url=".System::baseUrl()."/search?tag=$2]$2[/url]", $item["tag"]);
2382 // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
2383 $item["body"] = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2385 return ("[url=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/url]");
2388 $item["body"] = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
2390 return ("[bookmark=" . str_replace("#", "#", $match[1]) . "]" . str_replace("#", "#", $match[2]) . "[/bookmark]");
2393 $item["body"] = preg_replace_callback("/\[attachment (.*)\](.*?)\[\/attachment\]/ism",
2395 return ("[attachment " . str_replace("#", "#", $match[1]) . "]" . $match[2] . "[/attachment]");
2398 // Repair recursive urls
2399 $item["body"] = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2400 "#$2", $item["body"]);
2402 foreach ($tags as $tag) {
2403 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=')) {
2407 $basetag = str_replace('_',' ',substr($tag,1));
2409 $newtag = '#[url=' . System::baseUrl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
2411 $item["body"] = str_replace($tag, $newtag, $item["body"]);
2413 if (!stristr($item["tag"], "/search?tag=" . $basetag . "]" . $basetag . "[/url]")) {
2414 if (strlen($item["tag"])) {
2415 $item["tag"] = ','.$item["tag"];
2417 $item["tag"] = $newtag.$item["tag"];
2421 // Convert back the masked hashtags
2422 $item["body"] = str_replace("#", "#", $item["body"]);
2425 public static function getGuidById($id)
2427 $item = self::selectFirst(['guid'], ['id' => $id]);
2428 if (DBA::isResult($item)) {
2429 return $item['guid'];
2435 public static function getIdAndNickByGuid($guid, $uid = 0)
2441 $uid == local_user();
2444 // Does the given user have this item?
2446 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2447 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2448 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2449 AND `item`.`guid` = ? AND `item`.`uid` = ?", $guid, $uid);
2450 if (DBA::isResult($item)) {
2452 $nick = $item["nickname"];
2456 // Or is it anywhere on the server?
2458 $item = DBA::fetchFirst("SELECT `item`.`id`, `user`.`nickname` FROM `item`
2459 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
2460 WHERE `item`.`visible` AND NOT `item`.`deleted` AND NOT `item`.`moderated`
2461 AND NOT `item`.`private` AND `item`.`wall`
2462 AND `item`.`guid` = ?", $guid);
2463 if (DBA::isResult($item)) {
2465 $nick = $item["nickname"];
2468 return ["nick" => $nick, "id" => $id];
2472 * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2474 * @param int $item_id
2475 * @return bool true if item was deleted, else false
2477 private static function tagDeliver($uid, $item_id)
2481 $user = DBA::selectFirst('user', [], ['uid' => $uid]);
2482 if (!DBA::isResult($user)) {
2486 $community_page = (($user['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
2487 $prvgroup = (($user['page-flags'] == Contact::PAGE_PRVGROUP) ? true : false);
2489 $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2490 if (!DBA::isResult($item)) {
2494 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
2497 * Diaspora uses their own hardwired link URL in @-tags
2498 * instead of the one we supply with webfinger
2500 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
2502 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
2504 foreach ($matches as $mtch) {
2505 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
2507 logger('mention found: ' . $mtch[2]);
2513 if (($community_page || $prvgroup) &&
2514 !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
2515 // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
2517 logger("no-mention top-level post to community or private group. delete.");
2518 DBA::delete('item', ['id' => $item_id]);
2524 $arr = ['item' => $item, 'user' => $user];
2526 Addon::callHooks('tagged', $arr);
2528 if (!$community_page && !$prvgroup) {
2533 * tgroup delivery - setup a second delivery chain
2534 * prevent delivery looping - only proceed
2535 * if the message originated elsewhere and is a top-level post
2537 if ($item['wall'] || $item['origin'] || ($item['id'] != $item['parent'])) {
2541 // now change this copy of the post to a forum head message and deliver to all the tgroup members
2542 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], ['uid' => $uid, 'self' => true]);
2543 if (!DBA::isResult($self)) {
2547 $owner_id = Contact::getIdForURL($self['url']);
2549 // also reset all the privacy bits to the forum default permissions
2551 $private = ($user['allow_cid'] || $user['allow_gid'] || $user['deny_cid'] || $user['deny_gid']) ? 1 : 0;
2553 $forum_mode = ($prvgroup ? 2 : 1);
2555 $fields = ['wall' => true, 'origin' => true, 'forum_mode' => $forum_mode, 'contact-id' => $self['id'],
2556 'owner-id' => $owner_id, 'owner-link' => $self['url'], 'private' => $private, 'allow_cid' => $user['allow_cid'],
2557 'allow_gid' => $user['allow_gid'], 'deny_cid' => $user['deny_cid'], 'deny_gid' => $user['deny_gid']];
2558 DBA::update('item', $fields, ['id' => $item_id]);
2560 self::updateThread($item_id);
2562 Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], 'Notifier', 'tgroup', $item_id);
2565 public static function isRemoteSelf($contact, &$datarray)
2569 if (!$contact['remote_self']) {
2573 // Prevent the forwarding of posts that are forwarded
2574 if (!empty($datarray["extid"]) && ($datarray["extid"] == NETWORK_DFRN)) {
2575 logger('Already forwarded', LOGGER_DEBUG);
2579 // Prevent to forward already forwarded posts
2580 if ($datarray["app"] == $a->get_hostname()) {
2581 logger('Already forwarded (second test)', LOGGER_DEBUG);
2585 // Only forward posts
2586 if ($datarray["verb"] != ACTIVITY_POST) {
2587 logger('No post', LOGGER_DEBUG);
2591 if (($contact['network'] != NETWORK_FEED) && $datarray['private']) {
2592 logger('Not public', LOGGER_DEBUG);
2596 $datarray2 = $datarray;
2597 logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG);
2598 if ($contact['remote_self'] == 2) {
2599 $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2600 ['uid' => $contact['uid'], 'self' => true]);
2601 if (DBA::isResult($self)) {
2602 $datarray['contact-id'] = $self["id"];
2604 $datarray['owner-name'] = $self["name"];
2605 $datarray['owner-link'] = $self["url"];
2606 $datarray['owner-avatar'] = $self["thumb"];
2608 $datarray['author-name'] = $datarray['owner-name'];
2609 $datarray['author-link'] = $datarray['owner-link'];
2610 $datarray['author-avatar'] = $datarray['owner-avatar'];
2612 unset($datarray['created']);
2613 unset($datarray['edited']);
2615 unset($datarray['network']);
2616 unset($datarray['owner-id']);
2617 unset($datarray['author-id']);
2620 if ($contact['network'] != NETWORK_FEED) {
2621 $datarray["guid"] = System::createGUID(32);
2622 unset($datarray["plink"]);
2623 $datarray["uri"] = self::newURI($contact['uid'], $datarray["guid"]);
2624 $datarray["parent-uri"] = $datarray["uri"];
2625 $datarray["thr-parent"] = $datarray["uri"];
2626 $datarray["extid"] = NETWORK_DFRN;
2627 $urlpart = parse_url($datarray2['author-link']);
2628 $datarray["app"] = $urlpart["host"];
2630 $datarray['private'] = 0;
2634 if ($contact['network'] != NETWORK_FEED) {
2635 // Store the original post
2636 $result = self::insert($datarray2, false, false);
2637 logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG);
2639 $datarray["app"] = "Feed";
2643 // Trigger automatic reactions for addons
2644 $datarray['api_source'] = true;
2646 // We have to tell the hooks who we are - this really should be improved
2647 $_SESSION["authenticated"] = true;
2648 $_SESSION["uid"] = $contact['uid'];
2657 * @param array $item
2661 public static function fixPrivatePhotos($s, $uid, $item = null, $cid = 0)
2663 if (Config::get('system', 'disable_embedded')) {
2667 logger('check for photos', LOGGER_DEBUG);
2668 $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
2673 $img_start = strpos($orig_body, '[img');
2674 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2675 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2677 while (($img_st_close !== false) && ($img_len !== false)) {
2678 $img_st_close++; // make it point to AFTER the closing bracket
2679 $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2681 logger('found photo ' . $image, LOGGER_DEBUG);
2683 if (stristr($image, $site . '/photo/')) {
2684 // Only embed locally hosted photos
2686 $i = basename($image);
2687 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2688 $x = strpos($i, '-');
2691 $res = substr($i, $x + 1);
2692 $i = substr($i, 0, $x);
2693 $fields = ['data', 'type', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'];
2694 $photo = DBA::selectFirst('photo', $fields, ['resource-id' => $i, 'scale' => $res, 'uid' => $uid]);
2695 if (DBA::isResult($photo)) {
2697 * Check to see if we should replace this photo link with an embedded image
2698 * 1. No need to do so if the photo is public
2699 * 2. If there's a contact-id provided, see if they're in the access list
2700 * for the photo. If so, embed it.
2701 * 3. Otherwise, if we have an item, see if the item permissions match the photo
2702 * permissions, regardless of order but first check to see if they're an exact
2703 * match to save some processing overhead.
2705 if (self::hasPermissions($photo)) {
2707 $recips = self::enumeratePermissions($photo);
2708 if (in_array($cid, $recips)) {
2712 if (self::samePermissions($item, $photo)) {
2718 $data = $photo['data'];
2719 $type = $photo['type'];
2721 // If a custom width and height were specified, apply before embedding
2722 if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2723 logger('scaling photo', LOGGER_DEBUG);
2725 $width = intval($match[1]);
2726 $height = intval($match[2]);
2728 $Image = new Image($data, $type);
2729 if ($Image->isValid()) {
2730 $Image->scaleDown(max($width, $height));
2731 $data = $Image->asString();
2732 $type = $Image->getType();
2736 logger('replacing photo', LOGGER_DEBUG);
2737 $image = 'data:' . $type . ';base64,' . base64_encode($data);
2738 logger('replaced: ' . $image, LOGGER_DATA);
2744 $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2745 $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2746 if ($orig_body === false) {
2750 $img_start = strpos($orig_body, '[img');
2751 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2752 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2755 $new_body = $new_body . $orig_body;
2760 private static function hasPermissions($obj)
2762 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2763 !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2766 private static function samePermissions($obj1, $obj2)
2768 // first part is easy. Check that these are exactly the same.
2769 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2770 && ($obj1['allow_gid'] == $obj2['allow_gid'])
2771 && ($obj1['deny_cid'] == $obj2['deny_cid'])
2772 && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2776 // This is harder. Parse all the permissions and compare the resulting set.
2777 $recipients1 = self::enumeratePermissions($obj1);
2778 $recipients2 = self::enumeratePermissions($obj2);
2782 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2783 return ($recipients1 == $recipients2);
2786 // returns an array of contact-ids that are allowed to see this object
2787 private static function enumeratePermissions($obj)
2789 $allow_people = expand_acl($obj['allow_cid']);
2790 $allow_groups = Group::expand(expand_acl($obj['allow_gid']));
2791 $deny_people = expand_acl($obj['deny_cid']);
2792 $deny_groups = Group::expand(expand_acl($obj['deny_gid']));
2793 $recipients = array_unique(array_merge($allow_people, $allow_groups));
2794 $deny = array_unique(array_merge($deny_people, $deny_groups));
2795 $recipients = array_diff($recipients, $deny);
2799 public static function getFeedTags($item)
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[2][$x]] = ['#', $matches[1][$x], $matches[2][$x]];
2812 $cnt = preg_match_all('|\@\[url\=(.*?)\](.*?)\[\/url\]|', $item['tag'], $matches);
2814 for ($x = 0; $x < $cnt; $x ++) {
2815 if ($matches[1][$x]) {
2816 $ret[] = ['@', $matches[1][$x], $matches[2][$x]];
2823 public static function expire($uid, $days, $network = "", $force = false)
2825 if (!$uid || ($days < 1)) {
2829 $condition = ["`uid` = ? AND NOT `deleted` AND `id` = `parent` AND `gravity` = ?",
2830 $uid, GRAVITY_PARENT];
2833 * $expire_network_only = save your own wall posts
2834 * and just expire conversations started by others
2836 $expire_network_only = PConfig::get($uid, 'expire', 'network_only', false);
2838 if ($expire_network_only) {
2839 $condition[0] .= " AND NOT `wall`";
2842 if ($network != "") {
2843 $condition[0] .= " AND `network` = ?";
2844 $condition[] = $network;
2847 * There is an index "uid_network_received" but not "uid_network_created"
2848 * This avoids the creation of another index just for one purpose.
2849 * And it doesn't really matter wether to look at "received" or "created"
2851 $condition[0] .= " AND `received` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2852 $condition[] = $days;
2854 $condition[0] .= " AND `created` < UTC_TIMESTAMP() - INTERVAL ? DAY";
2855 $condition[] = $days;
2858 $items = self::select(['file', 'resource-id', 'starred', 'type', 'id', 'post-type'], $condition);
2860 if (!DBA::isResult($items)) {
2864 $expire_items = PConfig::get($uid, 'expire', 'items', true);
2866 // Forcing expiring of items - but not notes and marked items
2868 $expire_items = true;
2871 $expire_notes = PConfig::get($uid, 'expire', 'notes', true);
2872 $expire_starred = PConfig::get($uid, 'expire', 'starred', true);
2873 $expire_photos = PConfig::get($uid, 'expire', 'photos', false);
2877 while ($item = Item::fetch($items)) {
2878 // don't expire filed items
2880 if (strpos($item['file'], '[') !== false) {
2884 // Only expire posts, not photos and photo comments
2886 if (!$expire_photos && strlen($item['resource-id'])) {
2888 } elseif (!$expire_starred && intval($item['starred'])) {
2890 } elseif (!$expire_notes && (($item['type'] == 'note') || ($item['post-type'] == Item::PT_PERSONAL_NOTE))) {
2892 } elseif (!$expire_items && ($item['type'] != 'note') && ($item['post-type'] != Item::PT_PERSONAL_NOTE)) {
2896 self::deleteById($item['id'], PRIORITY_LOW);
2901 logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2904 public static function firstPostDate($uid, $wall = false)
2906 $condition = ['uid' => $uid, 'wall' => $wall, 'deleted' => false, 'visible' => true, 'moderated' => false];
2907 $params = ['order' => ['created' => false]];
2908 $thread = DBA::selectFirst('thread', ['created'], $condition, $params);
2909 if (DBA::isResult($thread)) {
2910 return substr(DateTimeFormat::local($thread['created']), 0, 10);
2916 * @brief add/remove activity to an item
2918 * Toggle activities as like,dislike,attend of an item
2920 * @param string $item_id
2921 * @param string $verb
2922 * Activity verb. One of
2923 * like, unlike, dislike, undislike, attendyes, unattendyes,
2924 * attendno, unattendno, attendmaybe, unattendmaybe
2925 * @hook 'post_local_end'
2927 * 'post_id' => ID of posted item
2929 public static function performLike($item_id, $verb)
2931 if (!local_user() && !remote_user()) {
2938 $activity = ACTIVITY_LIKE;
2942 $activity = ACTIVITY_DISLIKE;
2946 $activity = ACTIVITY_ATTEND;
2950 $activity = ACTIVITY_ATTENDNO;
2953 case 'unattendmaybe':
2954 $activity = ACTIVITY_ATTENDMAYBE;
2957 logger('like: unknown verb ' . $verb . ' for item ' . $item_id);
2961 // Enable activity toggling instead of on/off
2962 $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
2964 logger('like: verb ' . $verb . ' item ' . $item_id);
2966 $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
2967 if (!DBA::isResult($item)) {
2968 logger('like: unknown item ' . $item_id);
2972 $item_uri = $item['uri'];
2974 $uid = $item['uid'];
2975 if (($uid == 0) && local_user()) {
2976 $uid = local_user();
2979 if (!can_write_wall($uid)) {
2980 logger('like: unable to write on wall ' . $uid);
2984 // Retrieves the local post owner
2985 $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
2986 if (!DBA::isResult($owner_self_contact)) {
2987 logger('like: unknown owner ' . $uid);
2991 // Retrieve the current logged in user's public contact
2992 $author_id = public_contact();
2994 $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
2995 if (!DBA::isResult($author_contact)) {
2996 logger('like: unknown author ' . $author_id);
3000 // Contact-id is the uid-dependant author contact
3001 if (local_user() == $uid) {
3002 $item_contact_id = $owner_self_contact['id'];
3003 $item_contact = $owner_self_contact;
3005 $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
3006 $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
3007 if (!DBA::isResult($item_contact)) {
3008 logger('like: unknown item contact ' . $item_contact_id);
3013 // Look for an existing verb row
3014 // event participation are essentially radio toggles. If you make a subsequent choice,
3015 // we need to eradicate your first choice.
3016 if ($event_verb_flag) {
3017 $verbs = [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE];
3019 // Translate to the index based activity index
3021 foreach ($verbs as $verb) {
3022 $activities[] = self::activityToIndex($verb);
3025 $activities = self::activityToIndex($activity);
3028 $condition = ['activity' => $activities, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
3029 'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent' => $item_uri];
3031 $like_item = self::selectFirst(['id', 'guid', 'verb'], $condition);
3033 // If it exists, mark it as deleted
3034 if (DBA::isResult($like_item)) {
3035 self::deleteById($like_item['id']);
3037 if (!$event_verb_flag || $like_item['verb'] == $activity) {
3042 // Verb is "un-something", just trying to delete existing entries
3043 if (strpos($verb, 'un') === 0) {
3047 $objtype = $item['resource-id'] ? ACTIVITY_OBJ_IMAGE : ACTIVITY_OBJ_NOTE ;
3050 'guid' => System::createGUID(32),
3051 'uri' => self::newURI($item['uid']),
3052 'uid' => $item['uid'],
3053 'contact-id' => $item_contact_id,
3054 'wall' => $item['wall'],
3056 'network' => NETWORK_DFRN,
3057 'gravity' => GRAVITY_ACTIVITY,
3058 'parent' => $item['id'],
3059 'parent-uri' => $item['uri'],
3060 'thr-parent' => $item['uri'],
3061 'owner-id' => $item['owner-id'],
3062 'author-id' => $author_id,
3063 'body' => $activity,
3064 'verb' => $activity,
3065 'object-type' => $objtype,
3066 'allow_cid' => $item['allow_cid'],
3067 'allow_gid' => $item['allow_gid'],
3068 'deny_cid' => $item['deny_cid'],
3069 'deny_gid' => $item['deny_gid'],
3074 $new_item_id = self::insert($new_item);
3076 // If the parent item isn't visible then set it to visible
3077 if (!$item['visible']) {
3078 self::update(['visible' => true], ['id' => $item['id']]);
3081 // Save the author information for the like in case we need to relay to Diaspora
3082 Diaspora::storeLikeSignature($item_contact, $new_item_id);
3084 $new_item['id'] = $new_item_id;
3086 Addon::callHooks('post_local_end', $new_item);
3088 Worker::add(PRIORITY_HIGH, "Notifier", "like", $new_item_id);
3093 private static function addThread($itemid, $onlyshadow = false)
3095 $fields = ['uid', 'created', 'edited', 'commented', 'received', 'changed', 'wall', 'private', 'pubmail',
3096 'moderated', 'visible', 'starred', 'contact-id', 'post-type',
3097 'deleted', 'origin', 'forum_mode', 'mention', 'network', 'author-id', 'owner-id'];
3098 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3099 $item = self::selectFirst($fields, $condition);
3101 if (!DBA::isResult($item)) {
3105 $item['iid'] = $itemid;
3108 $result = DBA::insert('thread', $item);
3110 logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3114 private static function updateThread($itemid, $setmention = false)
3116 $fields = ['uid', 'guid', 'created', 'edited', 'commented', 'received', 'changed', 'post-type',
3117 'wall', 'private', 'pubmail', 'moderated', 'visible', 'starred', 'contact-id',
3118 'deleted', 'origin', 'forum_mode', 'network', 'author-id', 'owner-id'];
3119 $condition = ["`id` = ? AND (`parent` = ? OR `parent` = 0)", $itemid, $itemid];
3121 $item = self::selectFirst($fields, $condition);
3122 if (!DBA::isResult($item)) {
3127 $item["mention"] = 1;
3134 foreach ($item as $field => $data) {
3135 if (!in_array($field, ["guid"])) {
3136 $fields[$field] = $data;
3140 $result = DBA::update('thread', $fields, ['iid' => $itemid]);
3142 logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG);
3145 private static function deleteThread($itemid, $itemuri = "")
3147 $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
3148 if (!DBA::isResult($item)) {
3149 logger('No thread found for id '.$itemid, LOGGER_DEBUG);
3153 // Using dba::delete at this time could delete the associated item entries
3154 $result = DBA::e("DELETE FROM `thread` WHERE `iid` = ?", $itemid);
3156 logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG);
3158 if ($itemuri != "") {
3159 $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
3160 if (!self::exists($condition)) {
3161 DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
3162 logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG);